desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Get the actual object of the source key'
| def get_source_object(self, sourcekey):
| return self.boosting_sources.get(sourcekey, None)
|
'Dynamically enable/disable mining source.'
| def set_enable_mining(self, source, mining_bool=True, force_restart=False):
| for ihash in list(self.torrents):
tor = self.torrents.get(ihash)
if (tor['source'] == source_to_string(source)):
self.torrents[ihash]['enabled'] = mining_bool
if (not mining_bool):
self.stop_download(tor)
self.boosting_sources[string_to_source(source)].ena... |
'add new source into the boosting manager'
| def add_source(self, source):
| if (source not in self.boosting_sources):
args = (self.session, source, self.settings, self.on_torrent_insert)
try:
isdir = os.path.isdir(source)
except TypeError:
isdir = False
if isdir:
self.boosting_sources[source] = DirectorySource(*args)
... |
'remove source by stop the downloading and remove its metainfo for all its swarms'
| def remove_source(self, source_key):
| if (source_key in self.boosting_sources):
source = self.boosting_sources.pop(source_key)
source.kill_tasks()
self._logger.info('Removed source %s', source_key)
rm_torrents = [torrent for (_, torrent) in self.torrents.items() if (torrent['source'] == source_to_string(source_key)... |
'This function called when a source is finally determined. Fetch some torrents from it,
then insert it into our data'
| def on_torrent_insert(self, source, infohash, torrent):
| self._logger.debug('remember torrent %s from %s', torrent, source_to_string(source))
torrent['source'] = source_to_string(source)
boost_source = self.boosting_sources.get(source, None)
if (not boost_source):
self._logger.info('Dropping torrent insert from removed sourc... |
'Notify us when we have new seeder/leecher value in torrent from tracker'
| def on_torrent_notify(self, subject, change_type, infohash):
| if (infohash not in self.torrents):
return
self._logger.debug('infohash %s %s %s updated', subject, change_type, hexlify(infohash))
tdict = self.torrent_db.getTorrent(infohash, keys=['C.torrent_id', 'infohash', 'name', 'length', 'category', 'status', 'num_seeders', 'num_leechers'])
i... |
'Manually scrape tracker by requesting to tracker manager'
| def scrape_trackers(self):
| for infohash in list(self.torrents):
lt_torrent = self.session.lm.ltmgr.get_session().find_torrent(lt.big_number(infohash))
peer_list = []
for i in lt_torrent.get_peer_info():
peer = LibtorrentDownloadImpl.create_peerlist_data(i)
peer_list.append(peer)
(num_se... |
'setting archive of a particular source. This affects all the torrents in this source'
| def set_archive(self, source, enable):
| if (source in self.boosting_sources):
self.boosting_sources[source].archive = enable
self._logger.info('Set archive mode for %s to %s', source, enable)
else:
self._logger.error('Could not set archive mode for unknown source %s', source)
|
'Start downloading a particular torrent and add it to download list in Tribler'
| def start_download(self, torrent):
| dscfg = DownloadStartupConfig()
dscfg.set_dest_dir(self.settings.credit_mining_path)
dscfg.set_safe_seeding(False)
preload = torrent.get('preload', False)
if self.session.lm.download_exists(torrent['metainfo'].get_infohash()):
self._logger.error('Already downloading %s. Cancel st... |
'Stopping torrent that currently downloading'
| def stop_download(self, torrent):
| ihash = lt.big_number(torrent['metainfo'].get_infohash())
self._logger.info('Stopping %s', str(ihash))
download = torrent.pop('download', False)
lt_torrent = self.session.lm.ltmgr.get_session().find_torrent(ihash)
if (download and lt_torrent.is_valid()):
self._logger.info('Writing resu... |
'Function to select which torrent in the torrent list will be downloaded in the
next iteration. It depends on the source and applied policy'
| def _select_torrent(self):
| torrents = {}
for infohash in list(self.torrents):
torrent = self.torrents.get(infohash)
if torrent.get('preload', False):
if ('download' not in torrent):
self.start_download(torrent)
elif (torrent['download'].get_status() == DLSTATUS_SEEDING):
... |
'load config in file configuration and apply it to manager'
| def load_config(self):
| self._logger.info('Loading config file from session configuration')
def _add_sources(values):
'\n adding sources in configuration file\n '
for boosting_source in values:
... |
'save the environment parameters in config file'
| def save_config(self):
| for k in SAVED_ATTR:
try:
setattr(self.session, ('set_cm_%s' % k), getattr(self.settings, k))
except OperationNotPossibleAtRuntimeException:
self._logger.debug('Cannot set attribute %s. Not permitted in runtime', k)
archive_sources = []
lboosting_... |
'Log transfer statistics'
| def log_statistics(self):
| lt_torrents = self.session.lm.ltmgr.get_session().get_torrents()
for lt_torrent in lt_torrents:
status = lt_torrent.status()
if (unhexlify(str(status.info_hash)) in self.torrents):
self._logger.debug('Status for %s : %s %s | ul_lim : %d, max_ul %d, ... |
'function to update swarm statistics.
This function called when we get new Downloadstate for active torrents.
Updated downloadstate (seeding_stats) for a particular torrent is stored here.'
| def update_torrent_stats(self, torrent_infohash_str, seeding_stats):
| if ('time_seeding' in self.torrents[torrent_infohash_str]['last_seeding_stats']):
if (seeding_stats['time_seeding'] >= self.torrents[torrent_infohash_str]['last_seeding_stats']['time_seeding']):
self.torrents[torrent_infohash_str]['last_seeding_stats'] = seeding_stats
else:
self.torr... |
'Start operating mining for this source'
| def start(self):
| d = self._load_if_ready(self.source)
self.register_task((str(self.source) + '_load'), d, value=self.source)
self._logger.debug('Start mining on %s', self.source)
|
'kill tasks on this source'
| def kill_tasks(self):
| self.ready = False
self.cancel_all_pending_tasks()
|
'load source if and only if the overall system is ready.
This is useful so we don\'t burden the application during the startup'
| def _load_if_ready(self, source):
| def check_system(defer_param=None):
"\n function that check the system whether it's ready or not\n\n it depends on #connection and #channel\n ... |
'returning \'raw\' source. May be overriden'
| def get_source_text(self):
| return self.source
|
'periodically check torrents in channel. Will return the torrent data if finished.'
| def _check_tor(self):
| def showtorrent(torrent):
'\n assembly torrent data, call the callback\n '
infohash = torrent.infohash
if (torrent.get_files() and (infohash in self.unavail_torrent)):
if ... |
'function to download a torrent by infohash and call a callback afterwards
with TorrentDef object as parameter.'
| def _load_torrent(self, infohash):
| def add_to_loaded(infohash_str):
'\n function to add loaded infohash to memory\n '
self.loaded_torrent[unhexlify(infohash_str)].callback(TorrentDef.load_from_memory(self.session.get_collec... |
'function called when RSS successfully read'
| def _on_success_rss(self, body_rss, rss_feed):
| self.register_task((str(self.source) + '_update'), LoopingCall(self._update), 10, interval=self.interval)
self.parsed_rss = feedparser.parse(body_rss)
self._logger.info('Got RSS feed %s', rss_feed)
self.ready = True
|
'function called when RSS failed except from 503
aborting load the source'
| def _on_error_rss(self, failure, rss_feed):
| failure.trap(CancelledError, Error)
self._logger.error('Aborting load on : %s. Reason : %s.', rss_feed, failure.getErrorMessage())
if ('503' in failure.getErrorMessage()):
self.register_task((str(self.source) + '_load_delay'), reactor.callLater(10, self._load, rss_feed))
... |
'apply the policy to the torrents stored'
| def apply(self, torrents, max_active, force=False):
| sorted_torrents = sorted([torrent for torrent in torrents.itervalues() if self.key_check(torrent)], key=self.key, reverse=self.reverse)
torrents_start = []
for torrent in sorted_torrents[:max_active]:
if (not self.session.get_download(torrent['metainfo'].get_infohash())):
torrents_start.... |
'function to find a key of an object'
| def key(self, key):
| return None
|
'function to check whether a swarm is included to download'
| def key_check(self, key):
| return False
|
'Initializes this DBHandler.'
| def initialize(self, *args, **kwargs):
| pass
|
'Search in the local database for torrents matching a specific query. This method also assigns a relevance
score to each torrent, based on the name, files and file extensions.
The algorithm is based on BM25. The document length factor is regarded since our "documents" are very small
(often a few keywords).
See https://... | def search_in_local_torrents_db(self, query, keys=None):
| search_results = []
keys_str = ', '.join(keys)
keywords = split_into_keywords(query, to_filter_stopwords=True)
infohash_index = keys.index('infohash')
results = self._db.fetchall(("SELECT DISTINCT %s, Matchinfo(FullTextIndex, 'pcnalx') FROM Torrent T, FullTextIndex LEFT... |
'return the vote status if such record exists, otherwise None'
| def getVoteOnChannel(self, channel_id, voter_id):
| if voter_id:
sql = 'select vote from ChannelVotes where channel_id = ? and voter_id = ?'
return self._db.fetchone(sql, (channel_id, voter_id))
sql = 'select vote from ChannelVotes where channel_id = ? and voter_id ISNULL'
return ... |
'return the dispersy_id for this vote'
| def getDispersyId(self, channel_id, voter_id):
| if voter_id:
sql = 'select dispersy_id from ChannelVotes where channel_id = ? and voter_id = ?'
return self._db.fetchone(sql, (channel_id, voter_id))
sql = 'select dispersy_id from ChannelVotes where channel_id = ? and voter_id ISNUL... |
'return the timestamp for this vote'
| def getTimestamp(self, channel_id, voter_id):
| if voter_id:
sql = 'select time_stamp from ChannelVotes where channel_id = ? and voter_id = ?'
return self._db.fetchone(sql, (channel_id, voter_id))
sql = 'select time_stamp from ChannelVotes where channel_id = ? and voter_id ISNULL'... |
'Return some random (channel) torrents from the database.'
| def get_random_channel_torrents(self, keys, limit=10):
| sql = ('SELECT %s FROM ChannelTorrents, Torrent WHERE ChannelTorrents.torrent_id = Torrent.torrent_id AND Torrent.name IS NOT NULL ORDER BY RANDOM() LIMIT ?' % ', '.join(keys))
results = self._db.fetchall(sql, (limit,))
return self.__fixTorrents(keys,... |
'Calculate the relevance score of a channel from the database.
The algorithm used is a very stripped-down version of BM25 where only the matching terms are counted.'
| @staticmethod
def calculate_score_channel(keywords, channel_name, channel_description):
| values = [channel_name, channel_description]
scores = []
for col_ind in xrange(2):
score = 0
for keyword in keywords:
term_freq = values[col_ind].lower().count(keyword)
right_side = ((term_freq * (1.2 + 1)) / (term_freq + 1.2))
score += right_side
... |
'Searches for matching channels against a given query in the database.'
| def search_in_local_channels_db(self, query):
| search_results = []
keywords = split_into_keywords(query, to_filter_stopwords=True)
sql = 'SELECT id, dispersy_cid, name, description, nr_torrents, nr_favorite, nr_spam, modified FROM Channels WHERE '
for _ in xrange(len(keywords)):
sql += ' name LIKE ... |
'Returns all the channels'
| def getAllChannels(self):
| sql = 'Select id, name, description, dispersy_cid, modified, nr_torrents, nr_favorite, nr_spam FROM Channels'
return self._getChannels(sql)
|
'Returns all newest unsubscribed channels, ie the ones with no votes (positive or negative)'
| def getNewChannels(self, updated_since=0):
| sql = ('Select id, name, description, dispersy_cid, modified, nr_torrents, nr_favorite, nr_spam ' + 'FROM Channels WHERE nr_favorite = 0 AND nr_spam = 0 AND modified > ?')
return self._getChannels(sql, (updated_since,))
|
'Returns the channels based on the input sql, if the number of positive votes
is less than maxvotes and the number of torrent > 0'
| def _getChannels(self, sql, args=None, cmpF=None, includeSpam=True):
| if (self.votecast_db is None):
return []
channels = []
results = self._db.fetchall(sql, args)
my_votes = self.votecast_db.getMyVotes()
for (id, name, description, dispersy_cid, modified, nr_torrents, nr_favorites, nr_spam) in results:
my_vote = my_votes.get(id, 0)
if ((not in... |
'Returns channel id, name, nrfavorites of most popular channel if any'
| def getMostPopularChannelFromTorrent(self, infohash):
| sql = 'SELECT Channels.id, Channels.dispersy_cid, Channels.name, Channels.description,\n Channels.nr_torrents, Channels.nr_favorite, Channels.nr_spam, Channels.modified,\n ChannelTorren... |
'Returns the torrent dispersy IDs from a specified playlist.'
| def get_torrent_ids_from_playlist(self, playlist_id):
| sql = 'SELECT dispersy_id FROM PlaylistTorrents WHERE playlist_id = ?'
return self._db.fetchall(sql, (playlist_id,))
|
'The version of this database.'
| @property
def version(self):
| return self._version
|
'Returns the connection of the database, which may be None if not initialized or closed.
:return: The connection object of the database'
| @property
def connection(self):
| return self._connection
|
'Initializes the database. If the database doesn\'t exist, we create a new one. Otherwise, we check the
version and upgrade to the latest version.'
| @blocking_call_on_reactor_thread
def initialize(self):
| self._open_connection()
|
'Cancels all pending tasks and closes all cursors. Then, it closes the connection.'
| @blocking_call_on_reactor_thread
def close(self):
| self.cancel_all_pending_tasks()
with self._cursor_lock:
for cursor in self._cursor_table.itervalues():
cursor.close()
self._cursor_table = {}
self._connection.close()
self._connection = None
|
'Opens a connection to the database. If the database doesn\'t exist, we create a new one and run the
initialization SQL scripts. If the database doesn\'t exist, we simply connect to it.
And finally, we read the database version.'
| def _open_connection(self):
| is_in_memory = (self.sqlite_db_path == u':memory:')
is_new_db = is_in_memory
if (not is_in_memory):
if (not os.path.exists(self.sqlite_db_path)):
is_new_db = True
elif (not os.path.isfile(self.sqlite_db_path)):
msg = (u'Not a file: %s' % self.sqlite_db_path)
... |
'values must be a list of tuples'
| def insertMany(self, table_name, values, keys=None):
| questions = (u'?,' * len(values[0]))
if (keys is None):
sql = (u'INSERT INTO %s VALUES (%s);' % (table_name, questions[:(-1)]))
else:
sql = (u'INSERT INTO %s %s VALUES (%s);' % (table_name, tuple(keys), questions[:(-1)]))
self.executemany(sql, values)
|
'value_name could be a string, a tuple of strings, or \'*\''
| def getOne(self, table_name, value_name, where=None, conj=u'AND', **kw):
| if isinstance(value_name, tuple):
value_names = u','.join(value_name)
elif isinstance(value_name, list):
value_names = u','.join(value_name)
else:
value_names = value_name
if isinstance(table_name, tuple):
table_names = u','.join(table_name)
elif isinstance(table_name... |
'value_name could be a string, or a tuple of strings
order by is represented as order_by
group by is represented as group_by'
| def getAll(self, table_name, value_name, where=None, group_by=None, having=None, order_by=None, limit=None, offset=None, conj=u'AND', **kw):
| if isinstance(value_name, tuple):
value_names = u','.join(value_name)
elif isinstance(value_name, list):
value_names = u','.join(value_name)
else:
value_names = value_name
if isinstance(table_name, tuple):
table_names = u','.join(table_name)
elif isinstance(table_name... |
'Add observer function which will be called upon certain event
Example:
addObserver(NTFY_TORRENTS, [NTFY_INSERT,NTFY_DELETE]) -> get callbacks
when peers are added or deleted
addObserver(NTFY_TORRENTS, [NTFY_SEARCH_RESULT], \'a_search_id\') -> get
callbacks when peer-searchresults of of search
with id==\'a_search_id\' ... | def add_observer(self, func, subject, changeTypes=[NTFY_UPDATE, NTFY_INSERT, NTFY_DELETE], id=None, cache=0):
| assert isinstance(changeTypes, list)
assert (subject in self.SUBJECTS), ('Subject %s not in SUBJECTS' % subject)
obs = (func, subject, changeTypes, id, cache)
self.observerLock.acquire()
self.observers.append(obs)
self.observerLock.release()
|
'Remove all observers with function func'
| def remove_observer(self, func):
| with self.observerLock:
i = 0
while (i < len(self.observers)):
ofunc = self.observers[i][0]
if (ofunc == func):
del self.observers[i]
else:
i += 1
|
'Notify all interested observers about an event with threads from the pool'
| def notify(self, subject, changeType, obj_id, *args):
| tasks = []
assert (subject in self.SUBJECTS), ('Subject %s not in SUBJECTS' % subject)
args = ([subject, changeType, obj_id] + list(args))
self.observerLock.acquire()
for (ofunc, osubject, ochangeTypes, oid, cache) in self.observers:
try:
if ((subject == osubject) and... |
'Return the current Video-On-Demand download that is being requested.'
| def get_vod_download(self):
| return self.vod_download
|
'Set a new Video-On-Demand download. Set the mode of old download to normal and close the file stream of
the old download.'
| def set_vod_download(self, new_download):
| if self.vod_download:
self.vod_download.set_mode(DLMODE_NORMAL)
vi_dict = self.vod_info.pop(self.vod_download.get_def().get_infohash(), None)
if (vi_dict and ('stream' in vi_dict)):
vi_dict['stream'][0].close()
self.vod_download = new_download
|
'Get the destination directory of the VOD download.'
| @staticmethod
def get_vod_destination(download):
| if download.get_def().is_multifile_torrent():
return os.path.join(download.get_content_dest(), download.get_selected_files()[0])
else:
return download.get_content_dest()
|
'Shutdown the video HTTP server.'
| def shutdown_server(self):
| self.shutdown()
self.server_close()
self.set_vod_download(None)
|
'Called only once (unless we have multiple Sessions) by MainThread'
| def __init__(self):
| super(TriblerLaunchMany, self).__init__()
self.initComplete = False
self.registered = False
self.dispersy = None
self.state_cb_count = 0
self.previous_active_downloads = []
self.download_states_lc = None
self.get_peer_list = []
self._logger = logging.getLogger(self.__class__.__name__... |
'Called by any thread'
| def add(self, tdef, dscfg, pstate=None, setupDelay=0, hidden=False, share_mode=False, checkpoint_disabled=False):
| d = None
with self.session_lock:
if ((not isinstance(tdef, TorrentDefNoMetainfo)) and (not tdef.is_finalized())):
raise ValueError('TorrentDef not finalized')
infohash = tdef.get_infohash()
try:
if (not os.path.isdir(dscfg.get_dest_dir())):
o... |
'This method is called when the download handle has been created.
Immediately checkpoint the download and write the resume data.'
| def on_download_handle_created(self, download):
| return download.checkpoint()
|
'Called by any thread'
| def remove(self, d, removecontent=False, removestate=True, hidden=False):
| with self.session_lock:
d.stop_remove(removestate=removestate, removecontent=removecontent)
infohash = d.get_def().get_infohash()
if (infohash in self.downloads):
del self.downloads[infohash]
if (not hidden):
self.remove_id(infohash)
if self.tunnel_community:
... |
'Called by any thread'
| def get_downloads(self):
| with self.session_lock:
return self.downloads.values()
|
'Called by any thread'
| def get_download(self, infohash):
| with self.session_lock:
return self.downloads.get(infohash, None)
|
'Update the amount of hops for a specified download. This can be done on runtime.'
| def update_download_hops(self, download, new_hops):
| infohash = binascii.hexlify(download.tdef.get_infohash())
self._logger.info('Updating the amount of hops of download %s', infohash)
self.session.remove_download(download)
dscfg = download.copy()
dscfg.set_hops(new_hops)
self.register_task(('reschedule_download_%s' % infohash... |
'Update the trackers for a download.
:param infohash: infohash of the torrent that needs to be updated
:param trackers: A list of tracker urls.'
| def update_trackers(self, infohash, trackers):
| dl = self.get_download(infohash)
old_def = (dl.get_def() if dl else None)
if old_def:
old_trackers = old_def.get_trackers_as_single_tuple()
new_trackers = list((set(trackers) - set(old_trackers)))
all_trackers = (list(old_trackers) + new_trackers)
if new_trackers:
... |
'Stop any download states callback if present.'
| def stop_download_states_callback(self):
| if self.is_pending_task_active('download_states_lc'):
self.cancel_pending_task('download_states_lc')
|
'Set the download state callback. Remove any old callback if it\'s present.'
| def set_download_states_callback(self, user_callback, interval=1.0):
| self.stop_download_states_callback()
self._logger.debug('Starting the download state callback with interval %f', interval)
self.download_states_lc = self.register_task('download_states_lc', LoopingCall(self._invoke_states_cb, user_callback))
self.download_states_lc.start(interval)
|
'Invoke the download states callback with a list of the download states.'
| def _invoke_states_cb(self, callback):
| dslist = []
for d in self.downloads.values():
d.set_moreinfo_stats(((True in self.get_peer_list) or (d.get_def().get_infohash() in self.get_peer_list)))
ds = d.network_get_state(None, False)
dslist.append(ds)
def on_cb_done(new_get_peer_list):
self.get_peer_list = new_get_pee... |
'This method is periodically (every second) called with a list of the download states of the active downloads.'
| def sesscb_states_callback(self, states_list):
| self.state_cb_count += 1
new_active_downloads = []
do_checkpoint = False
seeding_download_list = []
for ds in states_list:
state = ds.get_status()
download = ds.get_download()
tdef = download.get_def()
safename = tdef.get_name_as_unicode()
if (state == DLSTATU... |
'Called by any thread'
| def load_checkpoint(self):
| def do_load_checkpoint():
with self.session_lock:
for (i, filename) in enumerate(iglob(os.path.join(self.session.get_downloads_pstate_dir(), '*.state'))):
self.resume_download(filename, setupDelay=(i * 0.1))
if self.initComplete:
do_load_checkpoint()
else:
... |
'Called by any thread, assume session_lock already held'
| def load_download_pstate_noexc(self, infohash):
| try:
basename = (binascii.hexlify(infohash) + '.state')
filename = os.path.join(self.session.get_downloads_pstate_dir(), basename)
if os.path.exists(filename):
return self.load_download_pstate(filename)
else:
self._logger.info('%s not found', basename)
... |
'Checkpoints all running downloads in Tribler.
Even if the list of Downloads changes in the mean time this is no problem.
For removals, dllist will still hold a pointer to the download, and additions are no problem
(just won\'t be included in list of states returned via callback).'
| def checkpoint_downloads(self):
| downloads = self.downloads.values()
deferred_list = []
self._logger.debug('tlm: checkpointing %s downloads', len(downloads))
for download in downloads:
deferred_list.append(download.checkpoint())
return DeferredList(deferred_list)
|
'Shutdown all downloads in Tribler.'
| def shutdown_downloads(self):
| for download in self.downloads.values():
download.stop()
|
'Called as soon as Session shutdown is initiated. Used to start
shutdown tasks that takes some time and that can run in parallel
to checkpointing, etc.
:returns a Deferred that will fire once all dependencies acknowledge they have shutdown.'
| @inlineCallbacks
def early_shutdown(self):
| self._logger.info('tlm: early_shutdown')
self.cancel_all_pending_tasks()
self.shutdownstarttime = timemod.time()
if self.boosting_manager:
(yield self.boosting_manager.shutdown())
self.boosting_manager = None
if self.torrent_checker:
(yield self.torrent_checker.shutdown())
... |
'Called by network thread'
| def save_download_pstate(self, infohash, pstate):
| self.downloads[infohash].pstate_for_restart = pstate
self.register_task(('save_pstate %f' % timemod.clock()), self.downloads[infohash].save_resume_data())
|
'Called by any thread'
| def load_download_pstate(self, filename):
| pstate = CallbackConfigParser()
pstate.read_file(filename)
return pstate
|
'Adds a new tracker into the tracker info dict and the database.
:param tracker_url: The new tracker URL to be added.'
| @call_on_reactor_thread
def add_tracker(self, tracker_url):
| sanitized_tracker_url = get_uniformed_tracker_url(tracker_url)
if (sanitized_tracker_url is None):
self._logger.warn(u'skip invalid tracker: %s', repr(tracker_url))
return
if (sanitized_tracker_url in self._tracker_dict):
self._logger.debug(u'skip existing tracker: ... |
'Gets the tracker information with the given tracker URL.
:param tracker_url: The given tracker URL.
:return: The tracker info dict if exists, None otherwise.'
| @call_on_reactor_thread
def get_tracker_info(self, tracker_url):
| sanitized_tracker_url = get_uniformed_tracker_url(tracker_url)
return self._tracker_dict.get(sanitized_tracker_url)
|
'Updates a tracker information.
:param tracker_url: The given tracker_url.
:param is_successful: If the check was successful.'
| def update_tracker_info(self, tracker_url, is_successful):
| if (tracker_url not in self._tracker_dict):
self._logger.error('Trying to update the tracker info of an unknown tracker URL')
return
tracker_info = self._tracker_dict[tracker_url]
current_time = int(time.time())
failures = (0 if is_successful else (tracker_i... |
'Checks if the given tracker URL should be checked right now or not.
:param tracker_url: The given tracker URL.
:return: True or False.'
| @call_on_reactor_thread
def should_check_tracker(self, tracker_url):
| current_time = int(time.time())
tracker_info = self._tracker_dict.get(tracker_url, {u'is_alive': True, u'last_check': 0, u'failures': 0})
next_check_time = (tracker_info[u'last_check'] + (self._tracker_retry_interval * (2 ** tracker_info[u'failures'])))
return (next_check_time <= current_time)
|
'Gets the next tracker for automatic tracker-checking.
:return: The next tracker for automatic tracker-checking.'
| @call_on_reactor_thread
def get_next_tracker_for_auto_check(self):
| if (len(self._tracker_dict) == 0):
return
next_tracker_url = None
next_tracker_info = None
sorted_tracker_list = sorted(self._tracker_dict.items(), key=(lambda d: d[1][u'last_check']))
for (tracker_url, tracker_info) in sorted_tracker_list:
if (tracker_url == u'DHT'):
nex... |
'Check whether a lock file exists in the Tribler directory. If not, create the file. If it exists,
check the PID that is written inside the lock file.'
| def __init__(self, state_directory=None):
| self.already_running = False
self.state_directory = (state_directory or TriblerConfig().get_state_dir())
self.lock_file_path = os.path.join(self.state_directory, LOCK_FILE_NAME)
if os.path.exists(self.lock_file_path):
try:
file_pid = int(self.get_pid_from_lock_file())
except ... |
'Check whether a given process ID is currently running. We do this by sending signal 0 to the process
which does not has any effect on the running process.
Source: http://stackoverflow.com/questions/7647167/check-if-a-process-is-running-in-python-in-linux-unix'
| @staticmethod
def is_pid_running(pid):
| try:
os.kill(pid, 0)
except OSError:
return False
else:
return True
|
'Create the lock file and write the PID in it. We also create the directory structure since the ProcessChecker
might be called before the .Tribler directory has been created.'
| def create_lock_file(self):
| if (not os.path.exists(self.state_directory)):
os.makedirs(self.state_directory)
with open(self.lock_file_path, 'wb') as lock_file:
lock_file.write(str(os.getpid()))
|
'Remove the lock file.'
| def remove_lock_file(self):
| os.unlink(self.lock_file_path)
|
'Returns the PID from the lock file.'
| def get_pid_from_lock_file(self):
| with open(self.lock_file_path, 'rb') as lock_file:
return lock_file.read()
|
'Parses an HTML content and find links.'
| def _parse_html(self, content):
| if (content is None):
return None
url_set = set()
a_list = re.findall('<a.+href=[\\\'"]?([^\\\'" >]+)', content)
for a_href in a_list:
url_set.add(a_href)
img_list = re.findall('<img.+src=[\\\'"]?([^\\\'" >]+)', content)
for img_src in img_list:
url_set.add(img_src)... |
'Converts an HTML document to plain text.'
| def _html2plaintext(self, html_content):
| content = html_content.replace('\r\n', '\n')
content = re.sub('<br[ DCTB \r\n\x0b\x0c]*.*/>', '\n', content)
content = re.sub('<p[ DCTB \r\n\x0b\x0c]*.*/>', '\n', content)
content = re.sub('<p>', '', content)
content = re.sub('</p>', '\n', content)
content = re.sub('<.+/>', '', content)
... |
'Parses a RSS feed. This methods supports RSS 2.0 and Media RSS.'
| def parse(self, url, cache):
| feed = feedparser.parse(url)
for item in feed.entries:
link = item.get(u'link', None)
if ((link is None) or cache.has(link)):
continue
title = self._html2plaintext(item[u'title']).strip()
description = self._html2plaintext(item.get(u'media_description', u'')).strip()
... |
'Creates a new Channel.
:param name: Name of the Channel.
:param description: Description of the Channel.
:param mode: Mode of the Channel (\'open\', \'semi-open\', or \'closed\').
:param rss_url: RSS URL for the Channel.
:return: Channel ID
:raises DuplicateChannelNameError if name already exists'
| @call_on_reactor_thread
def create_channel(self, name, description, mode, rss_url=None):
| assert isinstance(name, basestring), (u'name is not a basestring: %s' % type(name))
assert isinstance(description, basestring), (u'description is not a basestring: %s' % type(description))
assert (mode in self._channel_mode_map), (u'invalid mode: %s' % mode)
assert (i... |
'Gets the ChannelObject with the given channel id.
:return: The ChannelObject if exists, otherwise None.'
| def get_my_channel(self, channel_id):
| channel_object = None
for obj in self._channel_list:
if (obj.channel_id == channel_id):
channel_object = obj
break
return channel_object
|
'Gets a Channel by name.
:param name: Channel name.
:return: The channel object if exists, otherwise None.'
| def get_channel(self, name):
| channel_object = None
for obj in self._channel_list:
if (obj.name == name):
channel_object = obj
break
return channel_object
|
'Gets a list of all channel objects.
:return: The list of all channel objects.'
| def get_channel_list(self):
| return self._channel_list
|
'Searches for torrents using SearchCommunity with the given keywords.
:param keywords: The given keywords.'
| @call_on_reactor_thread
def search_for_torrents(self, keywords):
| nr_requests_made = 0
if (self.dispersy is None):
return nr_requests_made
for community in self.dispersy.get_communities():
if isinstance(community, SearchCommunity):
self._current_keywords = keywords
nr_requests_made = community.create_search(keywords)
if ... |
'The callback function handles the search results from SearchCommunity.
:param subject: Must be SIGNAL_SEARCH_COMMUNITY.
:param change_type: Must be SIGNAL_ON_SEARCH_RESULTS.
:param object_id: Must be None.
:param search_results: The result dictionary which has \'keywords\', \'results\', and \'candidate\'.'
| @call_on_reactor_thread
def _on_torrent_search_results(self, subject, change_type, object_id, search_results):
| if (self.session is None):
return 0
keywords = search_results['keywords']
results = search_results['results']
candidate = search_results['candidate']
self._logger.debug('Got torrent search results %s, keywords %s, candidate %s', len(results), keywords, candidate)
... |
'Searches for channels using AllChannelCommunity with the given keywords.
:param keywords: The given keywords.'
| @call_on_reactor_thread
def search_for_channels(self, keywords):
| if (self.dispersy is None):
return
for community in self.dispersy.get_communities():
if isinstance(community, AllChannelCommunity):
self._current_keywords = keywords
community.create_channelsearch(keywords)
break
|
'The callback function handles the search results from AllChannelCommunity.
:param subject: Must be SIGNAL_ALLCHANNEL_COMMUNITY.
:param change_type: Must be SIGNAL_ON_SEARCH_RESULTS.
:param object_id: Must be None.
:param search_results: The result dictionary which has \'keywords\', \'results\', and \'candidate\'.'
| @call_on_reactor_thread
def _on_channel_search_results(self, subject, change_type, object_id, search_results):
| if (self.session is None):
return
keywords = search_results['keywords']
results = search_results['torrents']
self._logger.debug('Got channel search results %s. keywords %s', len(results), keywords)
if (keywords != self._current_keywords):
return
channel_cids = r... |
'.. http:put:: /shutdown
A PUT request to this endpoint will shutdown Tribler.
**Example request**:
.. sourcecode:: none
curl -X PUT http://localhost:8085/shutdown
**Example response**:
.. sourcecode:: javascript
"shutdown": True'
| def render_PUT(self, request):
| def shutdown_process(_, code=1):
reactor.addSystemEventTrigger('after', 'shutdown', os._exit, code)
reactor.stop()
self.process_checker.remove_lock_file()
def log_and_shutdown(failure):
self._logger.error(failure.value)
shutdown_process(failure, 0)
task.deferLater(rea... |
'.. http:get:: /wallets
A GET request to this endpoint will return information about all available wallets in Tribler.
This includes information about the address, a human-readable wallet name and the balance.
**Example request**:
.. sourcecode:: none
curl -X GET http://localhost:8085/wallets
**Example response**:
.. s... | def render_GET(self, request):
| wallets = {}
balance_deferreds = []
for wallet_id in self.session.lm.market_community.get_wallet_ids():
wallet = self.session.lm.market_community.wallets[wallet_id]
wallets[wallet_id] = {'created': wallet.created, 'address': wallet.get_address(), 'name': wallet.get_name()}
balance_de... |
'.. http:put:: /wallets/(string:wallet identifier)
A request to this endpoint will create a new wallet.
**Example request**:
.. sourcecode:: none
curl -X PUT http://localhost:8085/wallets/BTC --data "password=secret"
**Example response**:
.. sourcecode:: javascript
"created": True'
| def render_PUT(self, request):
| if self.session.lm.market_community.wallets[self.identifier].created:
request.setResponseCode(http.BAD_REQUEST)
return json.dumps({'error': 'this wallet already exists'})
def on_wallet_created(_):
request.write(json.dumps({'created': True}))
request.finish()
paramete... |
'.. http:get:: /wallets/(string:wallet identifier)/balance
A GET request to this endpoint will return balance information of a specific wallet.
**Example request**:
.. sourcecode:: none
curl -X GET http://localhost:8085/wallets/BTC/balance
**Example response**:
.. sourcecode:: javascript
"balance": {
"available": 0.000... | def render_GET(self, request):
| def on_balance(balance):
request.write(json.dumps({'balance': balance}))
request.finish()
self.session.lm.market_community.wallets[self.identifier].get_balance().addCallback(on_balance)
return NOT_DONE_YET
|
'.. http:get:: /wallets/(string:wallet identifier)/transactions
A GET request to this endpoint will return past transactions of a specific wallet.
**Example request**:
.. sourcecode:: none
curl -X GET http://localhost:8085/wallets/BTC/transactions
**Example response**:
.. sourcecode:: javascript
"transactions": [{
"cur... | def render_GET(self, request):
| def on_transactions(transactions):
request.write(json.dumps({'transactions': transactions}))
request.finish()
self.session.lm.market_community.wallets[self.identifier].get_transactions().addCallback(on_transactions)
return NOT_DONE_YET
|
'.. http:get:: /wallets/(string:wallet identifier)/transfer
A GET request to this endpoint will return past transactions of a specific wallet.
**Example request**:
.. sourcecode:: none
curl -X GET http://localhost:8085/wallets/BTC/transfer
--data "amount=0.3&destination=mpC1DDgSP4PKc5HxJzQ5w9q6CGLBEQuLsN"
**Example res... | def render_POST(self, request):
| parameters = http.parse_qs(request.content.read(), 1)
if (self.identifier != 'BTC'):
request.setResponseCode(http.BAD_REQUEST)
return json.dumps({'error': 'currently, currency transfers using the API is only supported for Bitcoin'})
wallet = self.session.lm.mark... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.