desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Returns the info[\'name\'] field as raw string of bytes.
@return String'
| def get_name(self):
| if self.metainfo_valid:
return self.input['name']
else:
raise TorrentDefNotFinalizedException()
|
'Set the name of this torrent
@param name name of torrent as String'
| def set_name(self, name):
| self.input['name'] = name
self.metainfo_valid = False
|
'Returns the info[\'name\'] field as Unicode string.
@return Unicode string.'
| def get_name_as_unicode(self):
| if (not self.metainfo_valid):
raise TorrentDefNotFinalizedException()
if ('name.utf-8' in self.metainfo['info']):
try:
return unicode(self.metainfo['info']['name.utf-8'], 'UTF-8')
except UnicodeError:
pass
if ('name' in self.metainfo['info']):
if ('enc... |
'Finalizes the torrent def and writes a torrent file i.e., bencoded dict
following BT spec) to the specified filename. Note this may take a
long time when the torrent def is not yet finalized.
@param filename An absolute Unicode path name.'
| def save(self, filename):
| with open(filename, 'wb') as f:
f.write(self.encode())
|
'Finalizes the torrent def and converts the metainfo to string, returns the
number of bytes the string would take on disk.'
| def get_torrent_size(self):
| return len(self.encode())
|
'Get a generator for files in the torrent def. No filtering
is possible and all tricks are allowed to obtain a unicode
list of filenames.
@return A unicode filename generator.'
| def _get_all_files_as_unicode_with_length(self):
| assert self.metainfo_valid, 'TorrentDef is not finalized'
if ('files' in self.metainfo['info']):
join = os.path.join
files = self.metainfo['info']['files']
for file_dict in files:
if ('path.utf-8' in file_dict):
try:
(yield (join(*... |
'The list of files in the finalized torrent def.
@param exts (Optional) list of filename extensions (without leading .)
to search for.
@return A list of filenames.'
| def get_files_with_length(self, exts=None):
| if (not self.metainfo_valid):
raise NotYetImplementedException()
videofiles = []
for (filename, length) in self._get_all_files_as_unicode_with_length():
(prefix, ext) = os.path.splitext(filename)
if ((ext != '') and (ext[0] == '.')):
ext = ext[1:]
if ((exts is Non... |
'Returns the total size of the content in the torrent. If the
optional selectedfiles argument is specified, the method returns
the total size of only those files.
@return A length (long)'
| def get_length(self, selectedfiles=None):
| if (not self.metainfo_valid):
raise NotYetImplementedException()
return maketorrent.get_length_from_metainfo(self.metainfo, selectedfiles)
|
'Returns whether this TorrentDef is a multi-file torrent.
@return Boolean'
| def is_multifile_torrent(self):
| if (not self.metainfo_valid):
raise NotYetImplementedException()
return ('files' in self.metainfo['info'])
|
'Returns whether this TorrentDef is a private torrent.
@return Boolean'
| def is_private(self):
| if (not self.metainfo_valid):
raise NotYetImplementedException()
return (int(self.metainfo['info'].get('private', 0)) == 1)
|
'The constructor.
:param session: The tribler session.
:param endpoint: The endpoint to use.
:param prefix: The prefix to use.
:param block_size: Transmission block size.
:param timeout: Transmission timeout.
:param max_retries: Transmission maximum retries.'
| def __init__(self, session, endpoint, prefix, block_size=DEFAULT_BLOCK_SIZE, timeout=DEFAULT_TIMEOUT, max_retries=DEFAULT_RETIES):
| super(TftpHandler, self).__init__()
self._logger = logging.getLogger(self.__class__.__name__)
self.session = session
self._endpoint = endpoint
self._prefix = prefix
self._block_size = block_size
self._timeout = timeout
self._max_retries = max_retries
self._timeout_check_interval = 0.... |
'Initializes the TFTP service. We create a UDP socket and a server session.'
| def initialize(self):
| self._endpoint.listen_to(self._prefix, self.data_came_in)
self.register_task(u'tftp timeout check', LoopingCall(self._task_check_timeout)).start(self._timeout_check_interval, now=True)
self._is_running = True
|
'Shuts down the TFTP service.'
| @blocking_call_on_reactor_thread
def shutdown(self):
| self.cancel_all_pending_tasks()
if self._endpoint:
self._endpoint.stop_listen_to(self._prefix)
self._endpoint = None
self._session_id_dict = None
self._session_dict = None
self._is_running = False
|
'Downloads a file from a remote host.
:param file_name: The file name of the file to be downloaded.
:param ip: The IP of the remote host.
:param port: The port of the remote host.
:param success_callback: The success callback.
:param failure_callback: The failure callback.'
| @call_on_reactor_thread
def download_file(self, file_name, ip, port, extra_info=None, success_callback=None, failure_callback=None):
| if (not self._is_running):
return
target_ip = unpack('!L', inet_aton(ip))[0]
target_port = port
(self_ip, self_port) = self.session.lm.dispersy.wan_address
self_ip = unpack('!L', inet_aton(self_ip))[0]
if (target_ip > self_ip):
generate_session = (lambda : (randint(0, MAX_INT16) ... |
'A scheduled task that checks for timeout.'
| @attach_runtime_statistics(u'{0.__class__.__name__}.{function_name}')
def _task_check_timeout(self):
| if (not self._is_running):
return
need_session_cleanup = False
for (key, session) in self._session_dict.items():
if self._check_session_timeout(session):
need_session_cleanup = True
self._logger.info(u'%s timed out', session)
if session.failure_callb... |
'Checks if a session has timed out and tries to retransmit packet if allowed.
:param session: The given session.
:return: True or False indicating if the session has failed.'
| def _check_session_timeout(self, session):
| has_failed = False
timeout = (session.timeout * (2 ** session.retries))
if ((session.last_contact_time + timeout) < time()):
if ((session.retries < self._max_retries) and (session.last_sent_packet['opcode'] in (OPCODE_ACK, OPCODE_DATA))):
self._send_packet(session, session.last_sent_pack... |
'Schedules a task to process callbacks.'
| def _schedule_callback_processing(self):
| if (not self._callback_scheduled):
self.register_task(u'tftp_process_callback', reactor.callLater(0, self._process_callbacks))
self._callback_scheduled = True
|
'Process the callbacks'
| @attach_runtime_statistics(u'{0.__class__.__name__}.{function_name}')
def _process_callbacks(self):
| for callback in self._callbacks:
callback()
self._callbacks = []
self._callback_scheduled = False
|
'The callback function that the thread pool will call when there is incoming data.
:param addr: The (IP, port) address tuple of the sender.
:param data: The data received.'
| @attach_runtime_statistics(u'{0.__class__.__name__}.{function_name}')
@call_on_reactor_thread
def data_came_in(self, addr, data):
| if (not self._is_running):
return
(ip, port) = addr
try:
packet = decode_packet(data)
except InvalidPacketException as e:
self._logger.error(u'Invalid packet from [%s:%s], packet=[%s], error=%s', ip, port, hexlify(data), e)
return
if (packet['opcode'] =... |
'Handles a new request.
:param ip: The IP of the client.
:param port: The port of the client.
:param packet: The packet.'
| def _handle_new_request(self, ip, port, packet):
| if (packet['opcode'] != OPCODE_RRQ):
self._logger.error(u'Unexpected request from %s:%s, opcode=%s: packet=%s', ip, port, packet['opcode'], repr(packet))
return
if ('options' not in packet):
self._logger.error(u"No 'options' in request from %s:%s, opcode=... |
'Loads a thumbnail into memory.
:param thumb_hash: The thumbnail hash.'
| def _load_metadata(self, thumb_hash):
| file_data = self.session.lm.metadata_store.get(thumb_hash.encode('utf8'))
if (not file_data):
msg = (u'Metadata not in store: %s' % thumb_hash)
raise FileNotFound(msg)
return (file_data, len(file_data))
|
'Loads a file into memory.
:param file_name: The file name.'
| def _load_torrent(self, file_name):
| infohash = file_name[:(-8)].encode('utf8')
file_data = self.session.lm.torrent_store.get(infohash)
if (not file_data):
msg = (u'Torrent not in store: %s' % infohash)
raise FileNotFound(msg)
return (file_data, len(file_data))
|
'Gets the next block of data to be uploaded. This method is only used for data uploading.
:return The data to transfer.'
| def _get_next_data(self, session):
| start_idx = (session.block_number * session.block_size)
end_idx = (start_idx + session.block_size)
data = session.file_data[start_idx:end_idx]
session.block_number += 1
if (len(data) < session.block_size):
session.is_waiting_for_last_ack = True
return data
|
'processes an incoming packet.
:param packet: The incoming packet dictionary.'
| def _process_packet(self, session, packet):
| session.last_contact_time = time()
if (packet['opcode'] == OPCODE_ERROR):
self._logger.warning(u'%s got ERROR message: code = %s, msg = %s', session, packet['error_code'], packet['error_msg'])
session.is_failed = True
return
if session.is_client:
se... |
'Processes an incoming packet as a receiver.
:param packet: The incoming packet dictionary.'
| def _handle_packet_as_receiver(self, session, packet):
| if (packet['opcode'] == OPCODE_OACK):
if (session.last_received_packet is None):
if (session.block_size != packet['options']['blksize']):
msg = ('%s OACK blksize mismatch: %s != %s (expected)' % (session, session.block_size, packet['options']['blksize']))
... |
'Processes an incoming packet as a sender.
:param packet: The incoming packet dictionary.'
| def _handle_packet_as_sender(self, session, packet):
| if (packet['opcode'] != OPCODE_ACK):
self._logger.error(u'%s got OPCODE(%s) while expecting %s', session, packet['opcode'], OPCODE_ACK)
self._handle_error(session, 4)
return
if (packet['block_number'] < session.block_number):
self._logger.warn(u'%s ignore old... |
'Handles an error during packet processing.
:param error_code: The error code.'
| def _handle_error(self, session, error_code, error_msg=''):
| session.is_failed = True
msg = (error_msg if error_msg else ERROR_DICT.get(error_code, error_msg))
self._send_error_packet(session, error_code, msg)
|
'Sets the directory where to save this Download.
@param path A path of a directory.'
| def set_dest_dir(self, path):
| assert isinstance(path, basestring), path
self.dlconfig.set('download_defaults', 'saveas', path)
|
'Gets the directory where to save this Download.'
| def get_dest_dir(self):
| dest_dir = self.dlconfig.get('download_defaults', 'saveas')
if (not dest_dir):
dest_dir = get_default_dest_dir()
self.set_dest_dir(dest_dir)
return dest_dir
|
'Gets the directory name where to save this torrent'
| def get_corrected_filename(self):
| return self.dlconfig.get('download_defaults', 'correctedfilename')
|
'Sets the directory name where to save this torrent
@param correctedfilename name for multifile directory'
| def set_corrected_filename(self, correctedfilename):
| self.dlconfig.set('download_defaults', 'correctedfilename', correctedfilename)
|
'Sets the mode of this download.
@param mode DLMODE_NORMAL/DLMODE_VOD'
| def set_mode(self, mode):
| self.dlconfig.set('download_defaults', 'mode', mode)
|
'Returns the mode of this download.
@return DLMODE_NORMAL/DLMODE_VOD'
| def get_mode(self):
| return self.dlconfig.get('download_defaults', 'mode')
|
'Select which files in the torrent to download. The filenames must
be the names as they appear in the content def, including encoding.
Trivially, when the torrent contains a file \'sjaak.avi\' the files
parameter must be \'sjaak.avi\'. When the content def is a torrent def
and contains multiple files and is named \'fil... | def set_selected_files(self, files):
| if isinstance(files, StringType):
files = [files]
if ((self.get_mode() == DLMODE_VOD) and (len(files) > 1)):
raise ValueError('In Video-On-Demand mode only 1 file can be selected for download')
self.dlconfig.set('download_defaults', 'selected_files', files)
|
'Returns the list of files selected for download.
@return A list of strings.'
| def get_selected_files(self):
| return self.dlconfig.get('download_defaults', 'selected_files')
|
'Normal constructor for DownloadStartupConfig (copy constructor
used internally)'
| def __init__(self, dlconfig=None):
| DownloadConfigInterface.__init__(self, dlconfig)
|
'Load a saved DownloadStartupConfig from disk.
@param filename An absolute Unicode filename
@return DownloadStartupConfig object'
| def load(filename):
| dlconfig = CallbackConfigParser()
try:
dlconfig.read_file(filename)
except (ParsingError, IOError, MissingSectionHeaderError):
logger.error('Failed to open download config file: %s', filename)
raise
return DownloadStartupConfig(dlconfig)
|
'Save the DownloadStartupConfig to disk.
@param filename An absolute Unicode filename'
| def save(self, filename):
| self.dlconfig.write_file(filename)
|
'Create a new TriblerConfig instance.
:param config: a ConfigObj instance
:raises an InvalidConfigException if ConfigObj is invalid'
| def __init__(self, config=None):
| self._logger = logging.getLogger(self.__class__.__name__)
if (config is None):
file_name = os.path.join(self.get_default_state_dir(), FILENAME)
if os.path.exists(file_name):
config = ConfigObj(file_name, configspec=CONFIG_SPEC_PATH)
else:
config = ConfigObj(config... |
'Load a TriblerConfig from disk.'
| @staticmethod
def load(config_path=None):
| return TriblerConfig(ConfigObj(config_path, configspec=CONFIG_SPEC_PATH))
|
'Return a TriblerConfig object that has the same values.'
| def copy(self):
| new_configobj = ConfigObj(self.config.copy(), configspec=self.config.configspec)
for section in self.config:
new_configobj[section] = self.config[section].copy()
return TriblerConfig(new_configobj)
|
'Validate the ConfigObj using Validator.
Note that `validate()` returns `True` if the ConfigObj is correct and a dictionary with `True` and `False`
values for keys who\'s validation failed if at least one key was found to be incorrect.'
| def validate(self):
| validator = Validator()
validation_result = self.config.validate(validator, copy=True)
if (validation_result is not True):
raise InvalidConfigException(msg=('TriblerConfig is invalid: %s' % str(validation_result)))
|
'Write the configuration to the config file in the state dir as specified in the config.'
| def write(self):
| if (not os.path.exists(self.get_state_dir())):
os.makedirs(self.get_state_dir())
with open(os.path.join(self.get_state_dir(), FILENAME), 'w') as outfile:
self.config.write(outfile=outfile)
|
'Get the default application state directory.'
| @staticmethod
def get_default_state_dir(home_dir_postfix=u'.Tribler'):
| state_directory_variable = u'${TSTATEDIR}'
state_directory = os.path.expandvars(state_directory_variable)
if (state_directory and (state_directory != state_directory_variable)):
return state_directory
if os.path.isdir(home_dir_postfix):
return os.path.abspath(home_dir_postfix)
applic... |
'Fetch a port setting from the config file and in case it\'s set to -1 (random), look for a free port
and assign it to this particular setting.'
| def _obtain_port(self, section, option):
| settings_port = self.config[section][option]
path = ((section + '~') + option)
in_selected_ports = (path in self.selected_ports)
if (in_selected_ports or (settings_port == (-1))):
return self._get_random_port(path)
return settings_port
|
'Get a random port which is not already selected.'
| def _get_random_port(self, path):
| if (path not in self.selected_ports):
self.selected_ports[path] = get_random_port()
self._logger.debug(u'Get random port %d for [%s]', self.selected_ports[path], path)
return self.selected_ports[path]
|
'Set the path of the video analyser.
The path set depends on the current platform.
:return:'
| def _set_video_analyser_path(self):
| if (sys.platform == 'win32'):
from Tribler.Main.hacks import get_environment_variable
path_env = get_environment_variable(u'PATH')
elif is_android():
path_env = unicode(os.environ['PYTHONPATH'])
else:
path_env = os.environ['PATH']
if (sys.platform == 'win32'):
ffm... |
'Set which proxy LibTorrent should use (default = 0).
:param proxy_type: int (0 = no proxy server,
1 = SOCKS4,
2 = SOCKS5,
3 = SOCKS5 + auth,
4 = HTTP,
5 = HTTP + auth)
:param server: (host, port) tuple or None
:param auth: (username, password) tuple or None'
| def set_libtorrent_proxy_settings(self, proxy_type, server=None, auth=None):
| self.config['libtorrent']['proxy_type'] = proxy_type
self.config['libtorrent']['proxy_server'] = (server if proxy_type else None)
self.config['libtorrent']['proxy_auth'] = (auth if (proxy_type in [3, 5]) else None)
|
':param proxy_type: int (0 = no proxy server,
1 = SOCKS4,
2 = SOCKS5,
3 = SOCKS5 + auth,
4 = HTTP,
5 = HTTP + auth)
:param server: (host, [ports]) tuple or None
:param auth: (username, password) tuple or None'
| def set_anon_proxy_settings(self, proxy_type, server=None, auth=None):
| self.config['libtorrent']['anon_proxy_type'] = proxy_type
if (server and proxy_type):
self.config['libtorrent']['anon_proxy_server_ip'] = server[0]
self.config['libtorrent']['anon_proxy_server_ports'] = [str(i) for i in server[1]]
else:
self.config['libtorrent']['anon_proxy_server_ip... |
'Get the anon proxy settings.
:return: a 4-tuple with the proxytype in int, (ip as string, list of ports in int), auth'
| def get_anon_proxy_settings(self):
| server_ports = self.config['libtorrent']['anon_proxy_server_ports']
return (self.config['libtorrent']['anon_proxy_type'], (self.config['libtorrent']['anon_proxy_server_ip'], ([int(s) for s in server_ports] if server_ports else None)), self.config['libtorrent']['anon_proxy_auth'])
|
'Set the maximum amount of connections for each download.
By default, this is -1, unlimited.
:param value: int.'
| def set_libtorrent_max_conn_download(self, value):
| self.config['libtorrent']['max_connections_download'] = value
|
'Returns the maximum amount of connections per download
:return: int.'
| def get_libtorrent_max_conn_download(self):
| return self.config['libtorrent']['max_connections_download']
|
'Sets the maximum upload rate (kB / s).
:param value: the new maximum upload rate in kB / s
:return:'
| def set_libtorrent_max_upload_rate(self, value):
| self.config['libtorrent']['max_upload_rate'] = value
|
'Gets the maximum upload rate (kB / s).
:return: the maximum upload rate in kB / s'
| def get_libtorrent_max_upload_rate(self):
| return self.config['libtorrent'].as_int('max_upload_rate')
|
'Sets the maximum download rate (kB / s).
:param value: the new maximum download rate in kB / s
:return:'
| def set_libtorrent_max_download_rate(self, value):
| self.config['libtorrent']['max_download_rate'] = value
|
'Gets the maximum download rate (kB / s).
:return: the maximum download rate in kB / s'
| def get_libtorrent_max_download_rate(self):
| return self.config['libtorrent'].as_int('max_download_rate')
|
'Set source list for a chosen key: boosting_sources, boosting_enabled, boosting_disabled, or archive_sources.
:param source_list: One of boosting_sources,
boosting_enabled,
boosting_disabled,
archive_sources
:param key: the ConfigObj key'
| def set_credit_mining_sources(self, source_list, key):
| self.config['credit_mining'][('%s' % key)] = source_list
|
'The policy should be one of
- "random"
- "creation"
- "seederratio"
:param policy: a string
:return:'
| def set_credit_mining_policy(self, policy):
| self.config['credit_mining']['policy'] = policy
|
'Get the credit mining policy.
:param as_class: whether to return a string or the python class
:return: the policy in string form or the policy class.'
| def get_credit_mining_policy(self, as_class=False):
| policy_str = self.config['credit_mining']['policy']
if as_class:
switch_policy = {'random': RandomPolicy, 'creation': CreationDatePolicy, 'seederratio': SeederRatioPolicy}
return switch_policy[policy_str]
return policy_str
|
'Internal constructor.
@param download The Download this state belongs too.
@param status The status of the Download (DLSTATUS_*)
@param progress The general progress of the Download.
@param stats The BT engine statistics for the Download.
@param filepieceranges The range of pieces that we are interested in.
The get_pi... | def __init__(self, download, status, error, progress, stats=None, seeding_stats=None, filepieceranges=None, logmsgs=None, peerid=None, videoinfo=None):
| self._logger = logging.getLogger(self.__class__.__name__)
self.download = download
self.filepieceranges = filepieceranges
self.logmsgs = logmsgs
self.vod_status_msg = None
self.seeding_stats = seeding_stats
self.haveslice = None
self.stats = None
self.length = None
name = self.do... |
'Returns the Download object of which this is the state'
| def get_download(self):
| return self.download
|
'The general progress of the Download as a percentage. When status is
* DLSTATUS_HASHCHECKING it is the percentage of already downloaded
content checked for integrity.
* DLSTATUS_DOWNLOADING/SEEDING it is the percentage downloaded.
@return Progress as a float (0..1).'
| def get_progress(self):
| return self.progress
|
'Returns the status of the torrent.
@return DLSTATUS_*'
| def get_status(self):
| return self.status
|
'Returns the Exception that caused the download to be moved to
DLSTATUS_STOPPED_ON_ERROR status.
@return Exception'
| def get_error(self):
| return self.error
|
'Returns the current up or download speed.
@return The speed in bytes/s.'
| def get_current_speed(self, direct):
| if (self.stats is None):
return 0
if (direct == UPLOAD):
return self.stats['up']
else:
return self.stats['down']
|
'Returns the total amount of up or downloaded bytes.
@return The amount in bytes.'
| def get_total_transferred(self, direct):
| if (self.stats is None):
return 0
if (direct == UPLOAD):
return self.stats['stats'].upTotal
else:
return self.stats['stats'].downTotal
|
'Returns the seedings stats for this download. Will only be availible after
SeedingManager update_download_state is called.
Contains if not null, version, total_up, total_down, time_seeding
All values are stored by the seedingmanager, thus will not only contain current download session values'
| def get_seeding_statistics(self):
| return self.seeding_stats
|
'Returns the estimated time to finish of download.
@return The time in ?, as ?.'
| def get_eta(self):
| return (self.stats['time'] if self.stats else 0.0)
|
'Returns the download\'s number of initiated connections. This is used
to see if there is any progress when non-fatal errors have occured
(e.g. tracker timeout).
@return An integer.'
| def get_num_con_initiated(self):
| return (self.stats['stats'].numConInitiated if self.stats else 0)
|
'Returns the download\'s number of active connections. This is used
to see if there is any progress when non-fatal errors have occured
(e.g. tracker timeout).
@return An integer.'
| def get_num_peers(self):
| if (self.stats is None):
return 0
statsobj = self.stats['stats']
return (statsobj.numSeeds + statsobj.numPeers)
|
'Returns the download\'s number of non-seeders.
@return An integer.'
| def get_num_nonseeds(self):
| if (self.stats is None):
return 0
statsobj = self.stats['stats']
return statsobj.numPeers
|
'Returns the sum of the number of seeds and peers. This function
works only if the Download.set_state_callback() /
Session.set_download_states_callback() was called with the getpeerlist
parameter set to True, otherwise returns (None,None)
@return A tuple (num seeds, num peers)'
| def get_num_seeds_peers(self):
| if ((self.stats is None) or (self.stats.get('spew', None) is None)):
total = self.get_num_peers()
non_seeds = self.get_num_nonseeds()
return ((total - non_seeds), non_seeds)
total = len(self.stats['spew'])
seeds = len([i for i in self.stats['spew'] if (i.get('completed', 0) == 1.0)])... |
'Returns a list of booleans indicating whether we have completely
received that piece of the content. The list of pieces for which
we provide this info depends on which files were selected for download
using DownloadStartupConfig.set_selected_files().
@return A list of booleans'
| def get_pieces_complete(self):
| if (self.haveslice is None):
return []
else:
return self.haveslice
|
'Returns the number of total and completed pieces
@return A tuple containing two integers, total and completed nr of pieces'
| def get_pieces_total_complete(self):
| if (self.haveslice is None):
return (0, 0)
else:
return (len(self.haveslice), sum(self.haveslice))
|
'Returns a list of filename, progress tuples indicating the progress
for every file selected using set_selected_files. Progress is a float
between 0 and 1'
| def get_files_completion(self):
| if (len(self.download.get_selected_files()) > 0):
files = self.download.get_selected_files()
else:
files = self.download.get_def().get_files()
completion = []
if self.filepieceranges:
for (t, tl, o, f) in self.filepieceranges:
if ((f in files) and (self.progress == 1.... |
'Return overall the availability of all pieces, using connected peers
Availability is defined as the number of complete copies of a piece, thus seeders
increment the availability by 1. Leechers provide a subset of piece thus we count the
overall availability of all pieces provided by the connected peers and use the min... | def get_availability(self):
| nr_seeders_complete = 0
merged_bitfields = None
peers = self.get_peerlist()
for peer in peers:
completed = peer.get('completed', 0)
have = peer.get('have', [])
if ((completed == 1) or (have and all(have))):
nr_seeders_complete += 1
else:
if (merged... |
'Returns the percentage of prebuffering for Video-On-Demand already
completed.
@return A float (0..1)'
| def get_vod_prebuffering_progress(self):
| if (self.stats is None):
if ((self.status == DLSTATUS_STOPPED) and (self.progress == 1.0)):
return 1.0
else:
return 0.0
else:
return self.stats['vod_prebuf_frac']
|
'Returns the percentage of consecutive prebuffering for Video-On-Demand already
completed.
@return A float (0..1)'
| def get_vod_prebuffering_progress_consec(self):
| if (self.stats is None):
if ((self.status == DLSTATUS_STOPPED) and (self.progress == 1.0)):
return 1.0
else:
return 0.0
else:
return self.stats.get('vod_prebuf_frac_consec', (-1))
|
'Returns if this download is currently in vod mode
@return A Boolean'
| def is_vod(self):
| if (self.stats is None):
return False
else:
return self.stats['vod']
|
'Returns a list of dictionaries, one for each connected peer
containing the statistics for that peer. In particular, the
dictionary contains the keys:
<pre>
\'id\' = PeerID or \'http seed\'
\'extended_version\' = Peer client version, as received during the extend handshake message
\'ip\' = IP address as string or URL o... | def get_peerlist(self):
| if ((self.stats is None) or ('spew' not in self.stats) or (self.stats['spew'] is None)):
return []
else:
return self.stats['spew']
|
'Return is xxx filtering is enabled in this client'
| def family_filter_enabled(self):
| return self.ffEnabled
|
'Encode a half block message.
:param message: Message.impl of HalfBlockPayload.impl
:return encoding ready to be sent to the network of the message'
| @staticmethod
def _encode_half_block(message):
| return (message.payload.block.pack(),)
|
'Decode an incoming half block message.
:param placeholder:
:param offset: Start of the HalfBlock message in the data.
:param data: ByteStream containing the message.
:return: (offset, HalfBlockPayload.impl)'
| @staticmethod
def _decode_half_block(placeholder, offset, data):
| if (len(data) < (offset + block_pack_size)):
raise DropPacket('Unable to decode the payload')
try:
block = TrustChainBlock.unpack(data, offset)
except IndexError:
raise DropPacket('Invalid block contents')
return (len(data), placeholder.meta.payload.implement(bl... |
'Encode a crawl request message.
:param message: Message.impl of CrawlRequestPayload.impl
:return encoding ready to be sent of the network of the message'
| @staticmethod
def _encode_crawl_request(message):
| return (pack(crawl_request_format, EMPTY_PK, message.payload.requested_sequence_number, 10),)
|
'Decode an incoming crawl request message.
:param placeholder:
:param offset: Start of the CrawlRequest message in the data.
:param data: ByteStream containing the message.
:return: (offset, CrawlRequest.impl)'
| @staticmethod
def _decode_crawl_request(placeholder, offset, data):
| if (len(data) < (offset + crawl_request_size)):
raise DropPacket('Unable to decode the payload')
(who, seq, limit) = unpack_from(crawl_request_format, data, offset)
return ((offset + crawl_request_size), placeholder.meta.payload.implement(seq))
|
'Sets up the persistence layer ready for use.
:param working_directory: Path to the working directory
that will contain the the db at working directory/DATABASE_PATH
:param db_name: The name of the database'
| def __init__(self, working_directory, db_name):
| db_path = os.path.join(working_directory, os.path.join(DATABASE_DIRECTORY, (u'%s.db' % db_name)))
super(TrustChainDB, self).__init__(db_path)
self._logger.debug('TrustChain database path: %s', db_path)
self.db_name = db_name
self.open()
|
'Persist a block
:param block: The data that will be saved.'
| def add_block(self, block):
| self.execute((u'INSERT INTO %s (tx, public_key, sequence_number, link_public_key,link_sequence_number, previous_hash, signature, block_hash) VALUES(?,?,?,?,?,?,?,?)' % self.db_name), block.pack_db_insert())
self.commit()
|
'Get a specific block for a given public key
:param public_key: The public_key for which the block has to be found.
:param sequence_number: The specific block to get
:return: the block or None if it is not known'
| def get(self, public_key, sequence_number):
| return self._get(u'WHERE public_key = ? AND sequence_number = ?', (buffer(public_key), sequence_number))
|
'Check if a block is existent in the persistence layer.
:param block: the block to check
:return: True if the block exists, else false.'
| def contains(self, block):
| return (self.get(block.public_key, block.sequence_number) is not None)
|
'Get the latest block for a given public key
:param public_key: The public_key for which the latest block has to be found.
:return: the latest block or None if it is not known'
| def get_latest(self, public_key):
| return self._get((u'WHERE public_key = ? AND sequence_number = (SELECT MAX(sequence_number) FROM %s WHERE public_key = ?)' % self.db_name), (buffer(public_key), buffer(public_key)))
|
'Returns database block with the lowest sequence number higher than the block\'s sequence_number
:param block: The block who\'s successor we want to find
:return A block'
| def get_block_after(self, block):
| return self._get(u'WHERE sequence_number > ? AND public_key = ? ORDER BY sequence_number ASC', (block.sequence_number, buffer(block.public_key)))
|
'Returns database block with the highest sequence number lower than the block\'s sequence_number
:param block: The block who\'s predecessor we want to find
:return A block'
| def get_block_before(self, block):
| return self._get(u'WHERE sequence_number < ? AND public_key = ? ORDER BY sequence_number DESC', (block.sequence_number, buffer(block.public_key)))
|
'Get the block that is linked to the given block
:param block: The block for which to get the linked block
:return: the latest block or None if it is not known'
| def get_linked(self, block):
| return self._get(u'WHERE public_key = ? AND sequence_number = ? OR link_public_key = ? AND link_sequence_number = ?', (buffer(block.link_public_key), block.link_sequence_number, buffer(block.public_key), block.sequence_number))
|
'Return the first part of a generic sql select query.'
| def get_sql_header(self):
| _columns = u'tx, public_key, sequence_number, link_public_key, link_sequence_number, previous_hash, signature, insert_time'
return ((u'SELECT ' + _columns) + (u' FROM %s ' % self.db_name))
|
'Return the schema for the database.'
| def get_schema(self):
| return (u"\n CREATE TABLE IF NOT EXISTS %s(\n tx TEXT NOT NULL,\n public_key ... |
'Return the upgrade script for a specific version.
:param current_version: the version of the script to return.'
| def get_upgrade_script(self, current_version):
| return None
|
'Ensure the proper schema is used by the database.
:param database_version: Current version of the database.
:return:'
| def check_database(self, database_version):
| assert isinstance(database_version, unicode)
assert database_version.isdigit()
assert (int(database_version) >= 0)
database_version = int(database_version)
if (database_version < self.LATEST_DB_VERSION):
while (database_version < self.LATEST_DB_VERSION):
upgrade_script = self.get... |
'Validates the transaction of this block
:param database: the database to check against
:return: A tuple consisting of a ValidationResult and a list of user string errors'
| def validate_transaction(self, database):
| return (ValidationResult.valid, [])
|
'Validates this block against what is known in the database
:param database: the database to check against
:return: A tuple consisting of a ValidationResult and a list of user string errors'
| def validate(self, database):
| result = [ValidationResult.valid]
errors = []
crypto = ECCrypto()
def err(reason):
result[0] = ValidationResult.invalid
errors.append(reason)
blk = database.get(self.public_key, self.sequence_number)
link = database.get_linked(self)
prev_blk = database.get_block_before(self)
... |
'Signs this block with the given key
:param key: the key to sign this block with'
| def sign(self, key):
| crypto = ECCrypto()
self.signature = crypto.create_signature(key, self.pack(signature=False))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.