desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Returns the max amount of retries allowed for this session.
:return: The maximum amount of retries.'
| def max_retries(self):
| return UDP_TRACKER_MAX_RETRIES
|
'Returns the time one has to wait until retrying the connection again.
Increases exponentially with the number of retries.
:return: The interval one has to wait before retrying the connection.'
| def retry_interval(self):
| return (UDP_TRACKER_RECHECK_INTERVAL * (2 ** self._retries))
|
'Connects to the tracker and starts querying for seed and leech data.
:return: A deferred that will fire with a dictionary containing seed/leech information per infohash'
| def connect_to_tracker(self):
| self._is_initiated = True
self.cancel_pending_task('result')
self.cancel_pending_task('resolve')
self.ip_resolve_deferred = self.register_task('resolve', reactor.resolve(self._tracker_address[0]))
self.ip_resolve_deferred.addCallbacks(self.on_ip_address_resolved, self.on_error)
self._last_contac... |
'Called by the UDPScraper when it is connected to the tracker.
Creates a connection message and calls the scraper to send it.'
| def on_start(self):
| message = struct.pack('!qii', self._connection_id, self._action, self._transaction_id)
self.scraper.write_data(message)
|
'Handles the connection response from the UDP scraper and queries
it immediately for seed/leech data per infohash
:param response: The connection response from the UDP scraper'
| def handle_connection_response(self, response):
| if self.is_failed:
return
if (len(response) < 16):
self._logger.error(u'%s Invalid response for UDP CONNECT: %s', self, repr(response))
self.failed(msg='invalid response size')
return
(action, transaction_id) = struct.unpack_from('!ii', response, 0)
... |
'Handles the response from the UDP scraper.
:param response: The response from the UDP scraper'
| def handle_response(self, response):
| if self._is_failed:
return
if (len(response) < 8):
self._logger.info(u'%s Invalid response for UDP SCRAPE: %s', self, repr(response))
self.failed('invalid message size')
return
(action, transaction_id) = struct.unpack_from('!ii', response, 0)
if ((... |
'Cleans the session by cancelling all deferreds and closing sockets.
:return: A deferred that fires once the cleanup is done.'
| def cleanup(self):
| self._infohash_list = None
self._session = None
return defer.succeed(None)
|
'Returns whether or not this session can accept additional infohashes.
:return:'
| def can_add_request(self):
| return True
|
'This function adds a infohash to the request list.
:param infohash: The infohash to be added.'
| def add_infohash(self, infohash):
| self.infohash = infohash
|
'Fakely connects to a tracker.
:return: A deferred with a callback containing an empty dictionary.'
| def connect_to_tracker(self):
| @call_on_reactor_thread
def on_metainfo_received(metainfo):
self.result_deferred.callback({'DHT': [{'infohash': self.infohash.encode('hex'), 'seeders': metainfo['seeders'], 'leechers': metainfo['leechers']}]})
@call_on_reactor_thread
def on_metainfo_timeout(_):
self.result_deferred.errba... |
'Returns the max amount of retries allowed for this session.
:return: The maximum amount of retries.'
| @property
def max_retries(self):
| return DHT_TRACKER_MAX_RETRIES
|
'Returns the interval one has to wait before retrying to connect.
:return: The interval before retrying.'
| @property
def retry_interval(self):
| return DHT_TRACKER_RECHECK_INTERVAL
|
'Shutdown the torrent health checker.
Once shut down it can\'t be started again.
:returns A deferred that will fire once the shutdown has completed.'
| def shutdown(self):
| self._should_stop = True
self.cancel_all_pending_tasks()
for tracker_url in self._session_list.keys():
for session in self._session_list[tracker_url]:
self.session_stop_defer_list.append(session.cleanup())
defer_stop_list = DeferredList(self.session_stop_defer_list)
self._session... |
'Changes the tracker selection interval dynamically and schedules the task.'
| def _reschedule_tracker_select(self):
| num_torrents = self._torrent_db.getNumberCollectedTorrents()
tracker_select_interval = (min(max((7200 / num_torrents), 10), 100) if num_torrents else DEFAULT_TORRENT_SELECTION_INTERVAL)
self._logger.debug(u'tracker selection interval changed to %s', tracker_select_interval)
self.register_... |
'The regularly scheduled task that selects torrents associated with a specific tracker to check.'
| def _task_select_tracker(self):
| self._reschedule_tracker_select()
result = self.tribler_session.lm.tracker_manager.get_next_tracker_for_auto_check()
if (result is None):
self._logger.warn(u'No tracker to select from, skip')
return succeed(None)
(tracker_url, _) = result
self._logger.debug(u'Start ... |
'Public API for adding a GUI request.
:param infohash: Torrent infohash.
:param timeout: The timeout to use in the performed requests
:param scrape_now: Flag whether we want to force scraping immediately'
| @call_on_reactor_thread
def add_gui_request(self, infohash, timeout=20, scrape_now=False):
| result = self._torrent_db.getTorrent(infohash, (u'torrent_id', u'last_tracker_check', u'num_seeders', u'num_leechers'), False)
if (result is None):
self._logger.warn(u'torrent info not found, skip. infohash: %s', hexlify(infohash))
return fail(Failure(RuntimeError('Torrent n... |
'Handles the scenario of when a tracker session has failed by calling the
tracker_manager\'s update_tracker_info function.
Trap value errors that are thrown by e.g. the HTTPTrackerSession when a connection fails.
And trap CancelledErrors that can be thrown when shutting down.
:param failure: The failure object raised b... | def on_session_error(self, session, failure):
| failure.trap(ValueError, CancelledError, ConnectingCancelledError, RuntimeError)
self._logger.warning(u'Got session error for URL %s: %s', session.tracker_url, failure)
if (failure.check(CancelledError, ConnectingCancelledError) is None):
self.tribler_session.lm.tracker_manager.upd... |
'A Session object is created which is configured with the Tribler configuration object.
Only a single session instance can exist at a time in a process.
:param config: a TriblerConfig object or None, in which case we
look for a saved session in the default location (state dir). If
we can\'t find it, we create a new Tri... | def __init__(self, config=None, ignore_singleton=False, autoload_discovery=True):
| addObserver(self.unhandled_error_observer)
patch_crypto_be_discovery()
if (not ignore_singleton):
if Session.__single:
raise RuntimeError('Session is singleton')
Session.__single = self
self._logger = logging.getLogger(self.__class__.__name__)
self.ignore_singleton ... |
'Create directory structure of the state directory.'
| def create_state_directory_structure(self):
| def create_dir(path):
if (not os.path.isdir(path)):
os.makedirs(path)
def create_in_state_dir(path):
create_dir(os.path.join(self.config.get_state_dir(), path))
create_dir(self.config.get_state_dir())
create_dir(self.config.get_torrent_store_dir())
create_dir(self.config.... |
'Claim all required random ports.'
| def get_ports_in_config(self):
| self.config.get_libtorrent_port()
self.config.get_dispersy_port()
self.config.get_mainline_dht_port()
self.config.get_video_server_port()
self.config.get_anon_listen_port()
self.config.get_tunnel_community_socks5_listen_ports()
|
'Set parameters that depend on state_dir.'
| def init_keypair(self):
| permid_module.init()
pair_filename = self.config.get_permid_keypair_filename()
if os.path.exists(pair_filename):
self.keypair = permid_module.read_keypair(pair_filename)
else:
self.keypair = permid_module.generate_keypair()
public_key_filename = os.path.join(self.config.get_state... |
'Returns the Session singleton if it exists or otherwise creates it first, in which
case you need to pass the constructor params.
:return: the Session singleton'
| @staticmethod
def get_instance(*args, **kw):
| if (Session.__single is None):
Session(*args, **kw)
return Session.__single
|
'Check if there exists a Session singleton.
:return: either True or False.'
| @staticmethod
def has_instance():
| return (Session.__single is not None)
|
'Remove the Session singleton.'
| @staticmethod
def del_instance():
| Session.__single = None
|
'This method is called when an unhandled error in Tribler is observed.
It broadcasts the tribler_exception event.'
| def unhandled_error_observer(self, event):
| if event['isError']:
text = ''
if (('log_legacy' in event) and ('log_text' in event)):
text = event['log_text']
elif ('log_failure' in event):
text = str(event['log_failure'])
if ('socket.error: [Errno 113]' in text):
self._logger.error('Obse... |
'Start a download from an argument. This argument can be of the following type:
-http: Start a download from a torrent file at the given url.
-magnet: Start a download from a torrent file by using a magnet link.
-file: Start a download from a torrent file at given location.
:param uri: specifies the location of the tor... | def start_download_from_uri(self, uri, download_config=None):
| if self.config.get_libtorrent_enabled():
return self.lm.ltmgr.start_download_from_uri(uri, dconfig=download_config)
raise OperationNotEnabledByConfigurationException()
|
'Creates a Download object and adds it to the session. The passed
ContentDef and DownloadStartupConfig are copied into the new Download
object. The Download is then started and checkpointed.
If a checkpointed version of the Download is found, that is restarted
overriding the saved DownloadStartupConfig if "download_sta... | def start_download_from_tdef(self, torrent_definition, download_startup_config=None, hidden=False):
| if self.config.get_libtorrent_enabled():
return self.lm.add(torrent_definition, download_startup_config, hidden=hidden)
raise OperationNotEnabledByConfigurationException()
|
'Recreates Download from resume file.
Note: this cannot be made into a method of Download, as the Download
needs to be bound to a session, it cannot exist independently.
:return: a Download object
:raises: a NotYetImplementedException'
| def resume_download_from_file(self, filename):
| raise NotYetImplementedException()
|
'Returns a copy of the list of Downloads.
Locking is done by LaunchManyCore.
:return: a list of Download objects'
| def get_downloads(self):
| return self.lm.get_downloads()
|
'Returns the Download object for this hash.
Locking is done by LaunchManyCore.
:return: a Download object'
| def get_download(self, infohash):
| return self.lm.get_download(infohash)
|
'Checks if the torrent download already exists.
:param infohash: The torrent infohash
:return: True or False indicating if the torrent download already exists'
| def has_download(self, infohash):
| return self.lm.download_exists(infohash)
|
'Stops the download and removes it from the session.
Note that LaunchManyCore locks.
:param download: the Download to remove
:param remove_content: whether to delete the already downloaded content from disk
:param remove_state: whether to delete the metadata files of the downloaded content from disk
:param hidden: whet... | def remove_download(self, download, remove_content=False, remove_state=True, hidden=False):
| self.lm.remove(download, removecontent=remove_content, removestate=remove_state, hidden=hidden)
|
'Remove a download by it\'s infohash.
We can only remove content when the download object is found, otherwise only
the state is removed.
:param infohash: the download to remove
:param remove_content: whether to delete the already downloaded content from disk
:param remove_state: whether to remove the metadata files fro... | def remove_download_by_id(self, infohash, remove_content=False, remove_state=True):
| download_list = self.get_downloads()
for download in download_list:
if (download.get_def().get_infohash() == infohash):
self.remove_download(download, remove_content, remove_state)
return
self.lm.remove_id(infohash)
|
'See Download.set_state_callback. Calls user_callback with a list of
DownloadStates, one for each Download in the Session as first argument.
The user_callback must return a tuple (when, getpeerlist) that indicates
when to invoke the callback again (as a number of seconds from now,
or < 0.0 if not at all) and whether to... | def set_download_states_callback(self, user_callback, interval=1.0):
| self.lm.set_download_states_callback(user_callback, interval)
|
'Returns the PermID of the Session, as determined by the
TriblerConfig.set_permid() parameter. A PermID is a public key.
:return: the PermID encoded in a string in DER format'
| def get_permid(self):
| return str(self.keypair.pub().get_der())
|
'Add an observer function function to the Session. The observer
function will be called when one of the specified events (changeTypes)
occurs on the specified subject.
The function will be called by a popup thread which can be used indefinitely (within reason)
by the higher level code. Note that this function is called... | def add_observer(self, observer_function, subject, change_types=None, object_id=None, cache=0):
| change_types = (change_types or [NTFY_UPDATE, NTFY_INSERT, NTFY_DELETE])
self.notifier.add_observer(observer_function, subject, change_types, object_id, cache=cache)
|
'Remove observer function. No more callbacks will be made.
This function is called by any thread and is thread safe.
:param function: the observer function to remove.'
| def remove_observer(self, function):
| self.notifier.remove_observer(function)
|
'Opens a connection to the specified database. Only the thread calling this method may
use this connection. The connection must be closed with close_dbhandler() when this
thread exits. This function is called by any thread.
;param subject: the database to open. Must be one of the subjects specified here.
:return: a ref... | def open_dbhandler(self, subject):
| if (not self.config.get_megacache_enabled()):
raise OperationNotEnabledByConfigurationException()
if (subject == NTFY_PEERS):
return self.lm.peer_db
elif (subject == NTFY_TORRENTS):
return self.lm.torrent_db
elif (subject == NTFY_MYPREFERENCES):
return self.lm.mypref_db
... |
'Closes the given database connection.'
| @staticmethod
def close_dbhandler(database_handler):
| database_handler.close()
|
'Return a dictionary with general Tribler statistics.'
| def get_tribler_statistics(self):
| return TriblerStatistics(self).get_tribler_statistics()
|
'Return a dictionary with general Dispersy statistics.'
| def get_dispersy_statistics(self):
| return TriblerStatistics(self).get_dispersy_statistics()
|
'Return a dictionary with general communities statistics.'
| def get_community_statistics(self):
| return TriblerStatistics(self).get_community_statistics()
|
'Restart Downloads from a saved checkpoint, if any. Note that we fetch information from the user download
choices since it might be that a user has stopped a download. In that case, the download should not be
resumed immediately when being loaded by libtorrent.'
| def load_checkpoint(self):
| self.lm.load_checkpoint()
|
'Saves the internal session state to the Session\'s state dir.
Checkpoints the downloads via the LaunchManyCore instance. This function is called by any thread.'
| def checkpoint(self):
| self.lm.checkpoint_downloads()
|
'Start the SQLite database.'
| @blocking_call_on_reactor_thread
def start_database(self):
| db_path = os.path.join(self.config.get_state_dir(), DB_FILE_RELATIVE_PATH)
self.sqlite_db = SQLiteCacheDB(db_path)
self.sqlite_db.initialize()
self.sqlite_db.initial_begin()
|
'Start a Tribler session by initializing the LaunchManyCore class, opening the database and running the upgrader.
Returns a deferred that fires when the Tribler session is ready for use.'
| @blocking_call_on_reactor_thread
def start(self):
| if self.config.get_http_api_enabled():
self.lm.api_manager = RESTManager(self)
self.lm.api_manager.start()
self.start_database()
if self.config.get_upgrader_enabled():
self.upgrader = TriblerUpgrader(self, self.sqlite_db)
self.upgrader.run()
startup_deferred = self.lm.reg... |
'Checkpoints the session and closes it, stopping the download engine.
This method has to be called from the reactor thread.'
| @blocking_call_on_reactor_thread
def shutdown(self):
| assert isInIOThread()
@inlineCallbacks
def on_early_shutdown_complete(_):
'\n Callback that gets called when the early shutdown has been completed.\n Continues the shutdo... |
'Whether the Session has completely shutdown, i.e., its internal
threads are finished and it is safe to quit the process the Session
is running in.
:return: a boolean.'
| def has_shutdown(self):
| return self.lm.sessdoneflag.isSet()
|
'Returns the directory in which to checkpoint the Downloads in this
Session. This function is called by the network thread.'
| def get_downloads_pstate_dir(self):
| return os.path.join(self.config.get_state_dir(), STATEDIR_DLPSTATE_DIR)
|
'Try to download the torrent file without a known source. A possible source could be the DHT.
If the torrent is received successfully, the user_callback method is called with the infohash as first
and the contents of the torrent file (bencoded dict) as second parameter. If the torrent could not
be obtained, the callbac... | def download_torrentfile(self, infohash=None, user_callback=None, priority=0):
| if (not self.lm.rtorrent_handler):
raise OperationNotEnabledByConfigurationException()
self.lm.rtorrent_handler.download_torrent(None, infohash, user_callback=user_callback, priority=priority)
|
'Ask the designated peer to send us the torrent file for the torrent
identified by the passed infohash. If the torrent is successfully
received, the user_callback method is called with the infohash as first
and the contents of the torrent file (bencoded dict) as second parameter.
If the torrent could not be obtained, t... | def download_torrentfile_from_peer(self, candidate, infohash=None, user_callback=None, priority=0):
| if (not self.lm.rtorrent_handler):
raise OperationNotEnabledByConfigurationException()
self.lm.rtorrent_handler.download_torrent(candidate, infohash, user_callback=user_callback, priority=priority)
|
'Ask the designated peer to send us the torrent message for the torrent
identified by the passed infohash. If the torrent message is successfully
received, the user_callback method is called with the infohash as first
and the contents of the torrent file (bencoded dict) as second parameter.
If the torrent could not be ... | def download_torrentmessage_from_peer(self, candidate, infohash, user_callback, priority=0):
| if (not self.lm.rtorrent_handler):
raise OperationNotEnabledByConfigurationException()
self.lm.rtorrent_handler.download_torrentmessage(candidate, infohash, user_callback, priority)
|
'Checkpoints the downloads.'
| def checkpoint_downloads(self):
| return self.lm.checkpoint_downloads()
|
'Updates the trackers of a torrent.
:param infohash: infohash of the torrent that needs to be updated
:param trackers: A list of tracker urls'
| def update_trackers(self, infohash, trackers):
| return self.lm.update_trackers(infohash, trackers)
|
'Checks if the given torrent infohash exists in the torrent_store database.
:param infohash: The given infohash binary
:return: True or False indicating if we have the torrent'
| def has_collected_torrent(self, infohash):
| if (not self.config.get_torrent_store_enabled()):
raise OperationNotEnabledByConfigurationException('torrent_store is not enabled')
return (hexlify(infohash) in self.lm.torrent_store)
|
'Gets the given torrent from the torrent_store database.
:param infohash: the given infohash binary
:return: the torrent data if exists, None otherwise'
| def get_collected_torrent(self, infohash):
| if (not self.config.get_torrent_store_enabled()):
raise OperationNotEnabledByConfigurationException('torrent_store is not enabled')
return self.lm.torrent_store.get(hexlify(infohash))
|
'Saves the given torrent into the torrent_store database.
:param infohash: the given infohash binary
:param data: the torrent file data'
| def save_collected_torrent(self, infohash, data):
| if (not self.config.get_torrent_store_enabled()):
raise OperationNotEnabledByConfigurationException('torrent_store is not enabled')
self.lm.torrent_store.put(hexlify(infohash), data)
|
'Deletes the given torrent from the torrent_store database.
:param infohash: the given infohash binary'
| def delete_collected_torrent(self, infohash):
| if (not self.config.get_torrent_store_enabled()):
raise OperationNotEnabledByConfigurationException('torrent_store is not enabled')
del self.lm.torrent_store[hexlify(infohash)]
|
'Searches for remote torrents through SearchCommunity with the given keywords.
:param keywords: the given keywords
:return: the number of requests made'
| def search_remote_torrents(self, keywords):
| if (not self.config.get_torrent_search_enabled()):
raise OperationNotEnabledByConfigurationException('torrent_search is not enabled')
return self.lm.search_manager.search_for_torrents(keywords)
|
'Searches for remote channels through AllChannelCommunity with the given keywords.
:param keywords: the given keywords'
| def search_remote_channels(self, keywords):
| if (not self.config.get_channel_search_enabled()):
raise OperationNotEnabledByConfigurationException('channel_search is not enabled')
self.lm.search_manager.search_for_channels(keywords)
|
'Creates a torrent file.
:param file_path_list: files to add in torrent file
:param params: optional parameters for torrent file
:return: a Deferred that fires when the torrent file has been created'
| @staticmethod
def create_torrent_file(file_path_list, params=None):
| params = (params or {})
return threads.deferToThread(torrent_utils.create_torrent_file, file_path_list, params)
|
'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\')
:return: a channel ID
:raises a DuplicateChannelNameError if name already exists'
| def create_channel(self, name, description, mode=u'closed'):
| return self.lm.channel_manager.create_channel(name, description, mode)
|
'Adds a TorrentDef to a Channel.
:param channel_id: id of the Channel to add the Torrent to
:param torrent_def: definition of the Torrent to add
:param extra_info: description of the Torrent to add
:param forward: when True the messages are forwarded (as defined by their message
destination policy) to other nodes in th... | def add_torrent_def_to_channel(self, channel_id, torrent_def, extra_info={}, forward=True):
| self.lm.rtorrent_handler.save_torrent(torrent_def)
channelcast_db = self.open_dbhandler(NTFY_CHANNELCAST)
if channelcast_db.hasTorrent(channel_id, torrent_def.infohash):
raise DuplicateTorrentFileError('This torrent file already exists in your channel.')
dispersy_cid = str(c... |
'Checks the given torrent\'s health on its trackers.
:param infohash: the given torrent infohash
:param timeout: time to wait while performing the request
:param scrape_now: flag to scrape immediately'
| def check_torrent_health(self, infohash, timeout=20, scrape_now=False):
| if self.lm.torrent_checker:
return self.lm.torrent_checker.add_gui_request(infohash, timeout=timeout, scrape_now=scrape_now)
return fail(Failure(RuntimeError('Torrent checker not available')))
|
'Gets the thumbnail data.
:param thumb_hash: the thumbnail SHA1 hash
:return: the thumbnail data'
| def get_thumbnail_data(self, thumb_hash):
| if (not self.lm.metadata_store):
raise OperationNotEnabledByConfigurationException('libtorrent is not enabled')
return self.lm.rtorrent_handler.get_metadata(thumb_hash)
|
'Normal constructor for TorrentDef (The input, metainfo and infohash
parameters are used internally to make this a copy constructor)'
| def __init__(self, input=None, metainfo=None, infohash=None):
| assert ((infohash is None) or isinstance(infohash, str)), ('INFOHASH has invalid type: %s' % type(infohash))
assert ((infohash is None) or (len(infohash) == INFOHASH_LENGTH)), ('INFOHASH has invalid length: %d' % len(infohash))
self._logger = logging.getLogger(self.__class__.__name__... |
'Load a BT .torrent or Tribler .tribe file from disk and convert
it into a finalized TorrentDef.
@param filename An absolute Unicode filename
@return TorrentDef'
| @staticmethod
def load(filename):
| f = open(filename, 'rb')
return TorrentDef._read(f)
|
'Loads a torrent file that is already in memory.
:param data: The torrent file data.
:return: A TorrentDef object.'
| @staticmethod
def load_from_memory(data):
| data = bdecode(data)
return TorrentDef._create(data)
|
'Internal class method that reads a torrent file from stream,
checks it for correctness and sets self.input and self.metainfo
accordingly.'
| def _read(stream):
| bdata = stream.read()
stream.close()
data = bdecode(bdata)
return TorrentDef._create(data)
|
'Load a BT .torrent or Tribler .tstream file from the URL and
convert it into a TorrentDef.
@param url URL
@return Deferred'
| @staticmethod
@blocking_call_on_reactor_thread
def load_from_url(url):
| def _on_response(data):
return TorrentDef.load_from_memory(data)
deferred = http_get(url)
deferred.addCallback(_on_response)
return deferred
|
'Load a BT .torrent or Tribler .tribe file from the metainfo dictionary
it into a TorrentDef
@param metainfo A dictionary following the BT torrent file spec.
@return TorrentDef.'
| @staticmethod
def load_from_dict(metainfo):
| return TorrentDef._create(metainfo)
|
'Add a file or directory to this torrent definition. When adding a
directory, all files in that directory will be added to the torrent.
One can add multiple files and directories to a torrent definition.
In that case the "outpath" parameter must be used to indicate how
the files/dirs should be named in the torrent. The... | def add_content(self, inpath, outpath=None, playtime=None):
| s = os.stat(inpath)
d = {'inpath': inpath, 'outpath': outpath, 'playtime': playtime, 'length': s.st_size}
self.input['files'].append(d)
self.metainfo_valid = False
|
'Remove a file or directory from this torrent definition
@param inpath Absolute name of file or directory on local filesystem,
as Unicode string.'
| def remove_content(self, inpath):
| for d in self.input['files']:
if (d['inpath'] == inpath):
self.input['files'].remove(d)
break
|
'Set the character encoding for e.g. the \'name\' field'
| def set_encoding(self, enc):
| self.input['encoding'] = enc
self.metainfo_valid = False
|
'Sets the tracker (i.e. the torrent file\'s \'announce\' field).
@param url The announce URL.'
| def set_tracker(self, url):
| if (not is_valid_url(url)):
raise ValueError('Invalid URL')
if url.endswith('/'):
url = url[:(-1)]
self.input['announce'] = url
self.metainfo_valid = False
|
'Returns the announce URL.
@return URL'
| def get_tracker(self):
| return self.input['announce']
|
'Set hierarchy of trackers (announce-list) following the spec
at http://www.bittorrent.org/beps/bep_0012.html
@param hier A hierarchy of trackers as a list of lists.'
| def set_tracker_hierarchy(self, hier):
| newhier = []
if (not isinstance(hier, ListType)):
raise ValueError('hierarchy is not a list')
for tier in hier:
if (not isinstance(tier, ListType)):
raise ValueError('tier is not a list')
newtier = []
for url in tier:
if (not is... |
'Returns the hierarchy of trackers.
@return A list of lists.'
| def get_tracker_hierarchy(self):
| return self.input['announce-list']
|
'Returns a flat tuple of all known trackers
@return A tuple containing trackers'
| def get_trackers_as_single_tuple(self):
| if self.get_tracker_hierarchy():
trackers = []
for level in self.get_tracker_hierarchy():
for tracker in level:
if (tracker and (tracker not in trackers)):
trackers.append(tracker)
return tuple(trackers)
tracker = self.get_tracker()
if ... |
'Sets the DHT nodes required by the mainline DHT support,
See http://www.bittorrent.org/beps/bep_0005.html
@param nodes A list of [hostname,port] lists.'
| def set_dht_nodes(self, nodes):
| if (not isinstance(nodes, ListType)):
raise ValueError('nodes not a list')
else:
for node in nodes:
if ((not isinstance(node, ListType)) or (len(node) != 2)):
raise ValueError(('node in nodes not a 2-item list: ' + repr(node)))
... |
'Returns the DHT nodes set.
@return A list of [hostname,port] lists.'
| def get_dht_nodes(self):
| return self.input['nodes']
|
'Set comment field.
@param value A Unicode string.'
| def set_comment(self, value):
| self.input['comment'] = value
self.metainfo_valid = False
|
'Returns the comment field of the def.
@return A Unicode string.'
| def get_comment(self):
| return self.input['comment']
|
'Returns the comment field of the def as a unicode string.
@return A Unicode string.'
| def get_comment_as_unicode(self):
| return dunno2unicode(self.input['comment'])
|
'Set \'created by\' field.
@param value A Unicode string.'
| def set_created_by(self, value):
| self.input['created by'] = value
self.metainfo_valid = False
|
'Returns the \'created by\' field.
@return Unicode string.'
| def get_created_by(self):
| return self.input['created by']
|
'Set list of HTTP seeds following the BEP 19 spec (GetRight style):
http://www.bittorrent.org/beps/bep_0019.html
@param value A list of URLs.'
| def set_urllist(self, value):
| for url in value:
if (not is_valid_url(url)):
raise ValueError(('Invalid URL: ' + repr(url)))
self.input['url-list'] = value
self.metainfo_valid = False
|
'Returns the list of HTTP seeds.
@return A list of URLs.'
| def get_urllist(self):
| return self.input['url-list']
|
'Set list of HTTP seeds following the BEP 17 spec (John Hoffman style):
http://www.bittorrent.org/beps/bep_0017.html
@param value A list of URLs.'
| def set_httpseeds(self, value):
| for url in value:
if (not is_valid_url(url)):
raise ValueError(('Invalid URL: ' + repr(url)))
self.input['httpseeds'] = value
self.metainfo_valid = False
|
'Returns the list of HTTP seeds.
@return A list of URLs.'
| def get_httpseeds(self):
| return self.input['httpseeds']
|
'Set the size of the pieces in which the content is traded.
The piece size must be a multiple of the chunk size, the unit in which
it is transmitted, which is 16K by default (see
DownloadConfig.set_download_slice_size()). The default is automatic
(value 0).
@param value A number of bytes as per the text.'
| def set_piece_length(self, value):
| if (not (isinstance(value, IntType) or isinstance(value, LongType))):
raise ValueError('Piece length not an int/long')
self.input['piece length'] = value
self.metainfo_valid = False
|
'Returns the piece size.
@return A number of bytes.'
| def get_piece_length(self):
| return self.input['piece length']
|
'Returns the number of pieces.
@return A number of pieces.'
| def get_nr_pieces(self):
| return (len(self.metainfo['info']['pieces']) / 20)
|
'Returns the pieces'
| def get_pieces(self):
| return self.metainfo['info']['pieces'][:]
|
'Set the initial peers to connect to.
@param value List of (IP,port) tuples'
| def set_initial_peers(self, value):
| self.input['initial peers'] = value
|
'Returns the list of initial peers.
@return List of (IP,port) tuples.'
| def get_initial_peers(self):
| if ('initial peers' in self.input):
return self.input['initial peers']
else:
return []
|
'Create BT torrent file by reading the files added with
add_content() and calculate the torrent file\'s infohash.
Creating the torrent file can take a long time and will be carried out
by the calling thread. The process can be made interruptable by passing
a threading.Event() object via the userabortflag and setting it... | def finalize(self, userabortflag=None, userprogresscallback=None):
| if self.metainfo_valid:
return
(infohash, metainfo) = maketorrent.make_torrent_file(self.input, userabortflag=userabortflag, userprogresscallback=userprogresscallback)
if (infohash is not None):
self.infohash = infohash
self.metainfo = metainfo
self.input['name'] = metainfo['... |
'Returns whether the TorrentDef is finalized or not.
@return Boolean.'
| def is_finalized(self):
| return self.metainfo_valid
|
'Returns the infohash of the torrent, for non-URL compatible
torrents. Otherwise it returns the swarm identifier (either the root hash
(Merkle torrents) or hash of the live-source authentication key.
@return A string of length 20.'
| def get_infohash(self):
| if self.metainfo_valid:
return self.infohash
else:
raise TorrentDefNotFinalizedException()
|
'Returns the torrent definition as a dictionary that follows the BT
spec for torrent files.
@return dict'
| def get_metainfo(self):
| if self.metainfo_valid:
return self.metainfo
else:
raise TorrentDefNotFinalizedException()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.