desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Get a string marquee option value. @param option: marq option to get See libvlc_video_marquee_string_option_t.'
def video_get_marquee_string(self, option):
return libvlc_video_get_marquee_string(self, option)
'Enable, disable or set an integer marquee option Setting libvlc_marquee_Enable has the side effect of enabling (arg !0) or disabling (arg 0) the marq filter. @param option: marq option to set See libvlc_video_marquee_int_option_t. @param i_val: marq option value.'
def video_set_marquee_int(self, option, i_val):
return libvlc_video_set_marquee_int(self, option, i_val)
'Set a marquee string option. @param option: marq option to set See libvlc_video_marquee_string_option_t. @param psz_text: marq option value.'
def video_set_marquee_string(self, option, psz_text):
return libvlc_video_set_marquee_string(self, option, str_to_bytes(psz_text))
'Get integer logo option. @param option: logo option to get, values of libvlc_video_logo_option_t.'
def video_get_logo_int(self, option):
return libvlc_video_get_logo_int(self, option)
'Set logo option as integer. Options that take a different type value are ignored. Passing libvlc_logo_enable as option value has the side effect of starting (arg !0) or stopping (arg 0) the logo filter. @param option: logo option to set, values of libvlc_video_logo_option_t. @param value: logo option value.'
def video_set_logo_int(self, option, value):
return libvlc_video_set_logo_int(self, option, value)
'Set logo option as string. Options that take a different type value are ignored. @param option: logo option to set, values of libvlc_video_logo_option_t. @param psz_value: logo option value.'
def video_set_logo_string(self, option, psz_value):
return libvlc_video_set_logo_string(self, option, str_to_bytes(psz_value))
'Get integer adjust option. @param option: adjust option to get, values of libvlc_video_adjust_option_t. @version: LibVLC 1.1.1 and later.'
def video_get_adjust_int(self, option):
return libvlc_video_get_adjust_int(self, option)
'Set adjust option as integer. Options that take a different type value are ignored. Passing libvlc_adjust_enable as option value has the side effect of starting (arg !0) or stopping (arg 0) the adjust filter. @param option: adust option to set, values of libvlc_video_adjust_option_t. @param value: adjust option value....
def video_set_adjust_int(self, option, value):
return libvlc_video_set_adjust_int(self, option, value)
'Get float adjust option. @param option: adjust option to get, values of libvlc_video_adjust_option_t. @version: LibVLC 1.1.1 and later.'
def video_get_adjust_float(self, option):
return libvlc_video_get_adjust_float(self, option)
'Set adjust option as float. Options that take a different type value are ignored. @param option: adust option to set, values of libvlc_video_adjust_option_t. @param value: adjust option value. @version: LibVLC 1.1.1 and later.'
def video_set_adjust_float(self, option, value):
return libvlc_video_set_adjust_float(self, option, value)
'Selects an audio output module. @note: Any change will take be effect only after playback is stopped and restarted. Audio output cannot be changed while playing. @param psz_name: name of audio output, use psz_name of See L{AudioOutput}. @return: 0 if function succeded, -1 on error.'
def audio_output_set(self, psz_name):
return libvlc_audio_output_set(self, str_to_bytes(psz_name))
'Gets a list of potential audio output devices, See L{audio_output_device_set}(). @note: Not all audio outputs support enumerating devices. The audio output may be functional even if the list is empty (None). @note: The list may not be exhaustive. @warning: Some audio output devices in the list might not actually work ...
def audio_output_device_enum(self):
return libvlc_audio_output_device_enum(self)
'Configures an explicit audio output device. If the module paramater is None, audio output will be moved to the device specified by the device identifier string immediately. This is the recommended usage. A list of adequate potential device strings can be obtained with L{audio_output_device_enum}(). However passing Non...
def audio_output_device_set(self, module, device_id):
return libvlc_audio_output_device_set(self, str_to_bytes(module), str_to_bytes(device_id))
'Get the current audio output device identifier. This complements L{audio_output_device_set}(). @warning: The initial value for the current audio output device identifier may not be set or may be some unknown value. A LibVLC application should compare this value against the known device identifiers (e.g. those that wer...
def audio_output_device_get(self):
return libvlc_audio_output_device_get(self)
'Toggle mute status.'
def audio_toggle_mute(self):
return libvlc_audio_toggle_mute(self)
'Get current mute status. @return: the mute status (boolean) if defined, -1 if undefined/unapplicable.'
def audio_get_mute(self):
return libvlc_audio_get_mute(self)
'Set mute status. @param status: If status is true then mute, otherwise unmute @warning This function does not always work. If there are no active audio playback stream, the mute status might not be available. If digital pass-through (S/PDIF, HDMI...) is in use, muting may be unapplicable. Also some audio output plugin...
def audio_set_mute(self, status):
return libvlc_audio_set_mute(self, status)
'Get current software audio volume. @return: the software volume in percents (0 = mute, 100 = nominal / 0dB).'
def audio_get_volume(self):
return libvlc_audio_get_volume(self)
'Set current software audio volume. @param i_volume: the volume in percents (0 = mute, 100 = 0dB). @return: 0 if the volume was set, -1 if it was out of range.'
def audio_set_volume(self, i_volume):
return libvlc_audio_set_volume(self, i_volume)
'Get number of available audio tracks. @return: the number of available audio tracks (int), or -1 if unavailable.'
def audio_get_track_count(self):
return libvlc_audio_get_track_count(self)
'Get current audio track. @return: the audio track ID or -1 if no active input.'
def audio_get_track(self):
return libvlc_audio_get_track(self)
'Set current audio track. @param i_track: the track ID (i_id field from track description). @return: 0 on success, -1 on error.'
def audio_set_track(self, i_track):
return libvlc_audio_set_track(self, i_track)
'Get current audio channel. @return: the audio channel See libvlc_audio_output_channel_t.'
def audio_get_channel(self):
return libvlc_audio_get_channel(self)
'Set current audio channel. @param channel: the audio channel, See libvlc_audio_output_channel_t. @return: 0 on success, -1 on error.'
def audio_set_channel(self, channel):
return libvlc_audio_set_channel(self, channel)
'Get current audio delay. @return: the audio delay (microseconds). @version: LibVLC 1.1.1 or later.'
def audio_get_delay(self):
return libvlc_audio_get_delay(self)
'Set current audio delay. The audio delay will be reset to zero each time the media changes. @param i_delay: the audio delay (microseconds). @return: 0 on success, -1 on error. @version: LibVLC 1.1.1 or later.'
def audio_set_delay(self, i_delay):
return libvlc_audio_set_delay(self, i_delay)
'Apply new equalizer settings to a media player. The equalizer is first created by invoking L{audio_equalizer_new}() or L{audio_equalizer_new_from_preset}(). It is possible to apply new equalizer settings to a media player whether the media player is currently playing media or not. Invoking this method will immediately...
def set_equalizer(self, p_equalizer):
return libvlc_media_player_set_equalizer(self, p_equalizer)
'First test whether we already have a Tribler process listening on port 8085. If so, use that one and don\'t start a new, fresh session.'
def start(self):
def on_request_error(_): self.use_existing_core = False self.start_tribler_core() self.events_manager.connect(reschedule_on_err=False) self.events_manager.reply.error.connect(on_request_error)
'This method is executed in a separate thread and is only here since there are some calls that are crashing on macOS in a subprocess (due to libdispatch.dylib).'
def pipe_wait(self, child_conn):
while True: (cmd, arg) = child_conn.recv() if (cmd == 'get_keyring_password'): child_conn.send(keyring.get_password('tribler', arg['username'])) elif (cmd == 'set_keyring_password'): keyring.set_password('tribler', arg['username'], arg['password']) child_c...
'Plot two lines of the absolute amounts of contributed and consumed bytes.'
def plot_absolute_values(self):
plot_data = [[[], []], []] for block in self.blocks: plot_data[1].append(datetime.datetime.strptime(block['insert_time'], '%Y-%m-%d %H:%M:%S')) plot_data[0][0].append((block['total_up'] / self.byte_scale)) plot_data[0][1].append((block['total_down'] / self.byte_scale)) if (len(sel...
'Perform a request to check the health of the torrent that is represented by this widget. Don\'t do this if we are already checking the health or if we have the health info.'
def check_health(self):
if (self.is_health_checking or self.has_health): return self.health_text.setText('checking health...') self.set_health_indicator(STATUS_UNKNOWN) self.is_health_checking = True self.health_request_mgr = TriblerRequestManager() self.health_request_mgr.perform_request(('torrents/%s/healt...
'When we receive a health response, update the health status.'
def on_health_response(self, response):
if (not self): return self.has_health = True total_seeders = 0 total_leechers = 0 if ((not response) or ('error' in response)): self.update_health(0, 0) return for (_, status) in response['health'].iteritems(): if ('error' in status): continue ...
'Return the first num widget items with type cls. This can be useful when for instance you need the first five search results.'
def get_first_items(self, num, cls=None):
result = [] for i in xrange(self.count()): widget_item = self.itemWidget(self.item(i)) if ((not cls) or (cls and isinstance(widget_item, cls))): result.append(widget_item) if (len(result) >= num): break return result
'Reset the video player, i.e. when a download is removed that was being played.'
def reset_player(self):
self.active_infohash = '' self.active_index = (-1) self.window().left_menu_playlist.clear() self.window().video_player_header_label.setText('') self.mediaplayer.stop() self.mediaplayer.set_media(None) self.media = None self.window().video_player_play_pause_button.setIcon(self.play_icon) ...
'Process a URI request if we have one in the queue.'
def process_uri_request(self):
if (len(self.pending_uri_requests) == 0): return uri = self.pending_uri_requests.pop() if (uri.startswith('file') or uri.startswith('magnet')): self.start_download_from_uri(uri)
'Perform a HTTP request. :param endpoint: the endpoint to call (i.e. "statistics") :param read_callback: the callback to be called with result info when we have the data :param data: optional POST data to be sent with the request :param method: the HTTP verb (GET/POST/PUT/PATCH) :param capture_errors: whether errors sh...
def perform_request(self, endpoint, read_callback, data='', method='GET', capture_errors=True):
performed_requests[self.request_id] = [endpoint, method, data, time(), (-1)] performed_requests_ids.append(self.request_id) if (len(performed_requests_ids) > 200): del performed_requests[performed_requests_ids.pop(0)] url = (self.base_url + endpoint) if (method == 'GET'): buf = QBuff...
'Somehow, the events connection dropped. Try to reconnect.'
def on_finished(self):
if self.shutting_down: return self._logger.warning('Events connection dropped, attempting to reconnect') self.failed_attempts = 0 self.connect_timer = QTimer() self.connect_timer.setSingleShot(True) self.connect_timer.timeout.connect(self.connect) self.connect_timer.st...
'Uses RemoteTorrentHandler to schedule a task.'
@pass_when_stopped def schedule_task(self, task, delay_time=0.0, *args, **kwargs):
self._remote_torrent_handler.schedule_task(self._name, task, delay_time=delay_time, *args, **kwargs)
'Starts pending requests.'
@pass_when_stopped def _start_pending_requests(self):
if self._remote_torrent_handler.is_pending_task_active(self._name): return if self._pending_request_queue: self.schedule_task(self._do_request, delay_time=(Requester.REQUEST_INTERVAL * (MAX_PRIORITY - self._priority)))
'Adds a new request.'
@abstractmethod def add_request(self, key, candidate, timeout=None):
pass
'Starts processing pending requests.'
@abstractmethod def _do_request(self):
pass
'The callback that will be called by LibtorrentMgr when a download was successful.'
@call_on_reactor_thread def _success_callback(self, meta_info):
tdef = TorrentDef.load_from_dict(meta_info) assert (tdef.get_infohash() in self._running_requests) infohash = tdef.get_infohash() self._logger.debug(u'received torrent %s through magnet', hexlify(infohash)) self._remote_torrent_handler.save_torrent(tdef) self._running_requests.remove...
'The callback that will be called by LibtorrentMgr when a download failed.'
@call_on_reactor_thread def _failure_callback(self, infohash):
if (infohash not in self._running_requests): self._logger.debug(u'++ failed INFOHASH: %s', hexlify(infohash)) for ih in self._running_requests: self._logger.debug(u'++ INFOHASH in running_requests: %s', hexlify(ih)) self._logger.debug(u'failed to retrieve ...
'This method returns the version of the used libtorrent library and is required for compatibility purposes'
def get_libtorrent_version(self):
if hasattr(lt, '__version__'): return lt.__version__ else: return lt.version
'Set the maximum download and maximum upload rate limits with the value in the config. This is the extra step necessary to apply a new maximum download/upload rate setting. :return:'
def update_max_rates_from_config(self):
for lt_session in self.ltsessions.itervalues(): ltsession_settings = lt_session.get_settings() ltsession_settings['download_rate_limit'] = self.tribler_session.config.get_libtorrent_max_download_rate() ltsession_settings['upload_rate_limit'] = self.tribler_session.config.get_libtorrent_max_u...
'Check whether the handle exists and is valid. If so, stop the looping call and fire the deferreds waiting for the handle.'
def check_handle(self):
if (self.handle and self.handle.is_valid()): self.handle_check_lc.stop() for deferred in self.deferreds_handle: deferred.callback(self.handle)
'Returns a deferred that fires with a valid libtorrent download handle.'
def get_handle(self):
if (self.handle and self.handle.is_valid()): return succeed(self.handle) deferred = Deferred() self.deferreds_handle.append(deferred) return deferred
'Create a Download object. Used internally by Session. @param dcfg DownloadStartupConfig or None (in which case a new DownloadConfig() is created and the result becomes the runtime config of this Download. :returns a Deferred to which a callback can be added which returns the result of network_create_engine_wrapper.'
def setup(self, dcfg=None, pstate=None, wrapperDelay=0, share_mode=False, checkpoint_disabled=False):
self.handle_check_lc.start(1, now=False) self.set_checkpoint_disabled(checkpoint_disabled) try: deferred = Deferred() with self.dllock: if (dcfg is None): cdcfg = DownloadStartupConfig() else: cdcfg = dcfg self.dlconfig = cd...
'Periodically checks whether the engine wrapper can be created. Notifies when it\'s ready by calling the callback of the deferred being returned. :return: A deferred that will be called when you can create the engine wrapper.'
def can_create_engine_wrapper(self):
can_create_deferred = Deferred() def do_check(): with self.dllock: if (not self.cew_scheduled): self.ltmgr = self.session.lm.ltmgr dht_ok = ((not isinstance(self.tdef, TorrentDefNoMetainfo)) or self.ltmgr.is_dht_ready()) tunnel_community = self...
'Returns a base64 encoded bitmask of the pieces that we have.'
@checkHandleAndSynchronize('') def get_pieces_base64(self):
bitstr = '' for bit in self.handle.status().pieces: bitstr += ('1' if bit else '0') encoded_str = '' for i in range(0, len(bitstr), 8): encoded_str += chr(int(bitstr[i:(i + 8)].ljust(8, '0'), 2)) return base64.b64encode(encoded_str)
'Return the total number of pieces'
@checkHandleAndSynchronize(0) def get_num_pieces(self):
if get_info_from_handle(self.handle): return get_info_from_handle(self.handle).num_pieces()
'Callback for the alert that contains the resume data of a specific download. This resume data will be written to a file on disk.'
def on_save_resume_data_alert(self, alert):
resume_data = alert.resume_data self.pstate_for_restart = self.get_persistent_download_config() self.pstate_for_restart.set('state', 'engineresumedata', resume_data) self._logger.debug('%s get resume data %s', hexlify(resume_data['info-hash']), resume_data) basename = (hexlify(resume_dat...
'Update libtorrent stats and check if the download should be stopped.'
def update_lt_stats(self):
status = self.handle.status() self.dlstate = (self.dlstates[status.state] if (not status.paused) else DLSTATUS_STOPPED) self.dlstate = (DLSTATUS_STOPPED_ON_ERROR if ((self.dlstate == DLSTATUS_STOPPED) and status.error) else self.dlstate) if (self.get_mode() == DLMODE_VOD): self.progress = self.g...
'Returns the status of the download. @return DLSTATUS_*'
def get_status(self):
with self.dllock: return self.dlstate
'Returns the size of the torrent content. @return float'
def get_length(self):
with self.dllock: return self.length
'Return fraction of content downloaded. @return float 0..1'
def get_progress(self):
with self.dllock: return self.progress
'Return last reported speed in bytes/s @return float'
def get_current_speed(self, dir):
with self.dllock: return self.curspeeds[dir]
'Save the resume data of a download. This method returns a deferred that fires when the resume data is available. Note that this method only calls save_resume_data once on subsequent calls.'
def save_resume_data(self):
if (not self.deferreds_resume): self.get_handle().addCallback((lambda handle: handle.save_resume_data())) defer_resume = Deferred() defer_resume.addErrback(self._on_resume_err) self.deferreds_resume.append(defer_resume) return defer_resume
'Called by any thread'
def set_moreinfo_stats(self, enable):
self.askmoreinfo = enable
'@return (status, stats, seeding_stats, logmsgs, coopdl_helpers, coopdl_coordinator)'
def network_get_stats(self, getpeerlist):
stats = {} stats['down'] = self.curspeeds[DOWNLOAD] stats['up'] = self.curspeeds[UPLOAD] stats['frac'] = self.progress stats['wanted'] = self.length stats['stats'] = self.network_create_statistics_reponse() stats['time'] = self.network_calc_eta() stats['vod_prebuf_frac'] = self.network_c...
'A function to convert peer_info libtorrent object into dictionary This data is used to identify peers with combination of several flags'
@staticmethod def create_peerlist_data(peer_info):
peer_dict = {'id': peer_info.pid.to_bytes().encode('hex'), 'extended_version': peer_info.client, 'ip': peer_info.ip[0], 'port': peer_info.ip[1], 'optimistic': bool((peer_info.flags & 2048)), 'direction': ('L' if bool((peer_info.flags & peer_info.local_connection)) else 'R'), 'uprate': peer_info.payload_up_speed, 'u...
'Called by any thread'
def set_state_callback(self, usercallback, getpeerlist=False):
with self.dllock: reactor.callFromThread((lambda : self.network_get_state(usercallback, getpeerlist)))
'Called by network thread'
def network_get_state(self, usercallback, getpeerlist):
with self.dllock: if (self.handle is None): self._logger.debug('LibtorrentDownloadImpl: network_get_state: Download not running') if (self.dlstate != DLSTATUS_CIRCUITS): progress = self.progressbeforestop else: tunnel_community ...
'Called by any thread. Called on Session.remove_download()'
def stop_remove(self, removestate=False, removecontent=False):
self.done = removestate self.network_stop(removestate=removestate, removecontent=removecontent)
'Called by network thread, but safe for any'
def network_stop(self, removestate, removecontent):
with self.dllock: self._logger.debug('LibtorrentDownloadImpl: network_stop %s', self.tdef.get_name()) self.cancel_all_pending_tasks() pstate = self.get_persistent_download_config() if (self.handle is not None): self._logger.debug('LibtorrentDownloadImpl: network_...
'Returns the file to which the downloaded content is saved.'
def get_content_dest(self):
return os.path.join(self.get_dest_dir(), self.correctedinfoname)
'Determine which file maps to which piece ranges for progress info'
def set_filepieceranges(self):
self._logger.debug('LibtorrentDownloadImpl: set_filepieceranges: %s', self.get_selected_files()) metainfo = self.tdef.get_metainfo() self.filepieceranges = maketorrent.get_length_filepieceranges_from_metainfo(metainfo, [])[1]
'Restart the Download'
def restart(self):
self.set_user_stopped(False) self._logger.debug('LibtorrentDownloadImpl: restart: %s', self.tdef.get_name()) self.cancel_pending_task('check_create_wrapper') with self.dllock: if (self.handle is None): self.error = None def schedule_create_engine(_): ...
'You can give a list of extensions to return. If None: return all dest_files @return list of (torrent,disk) filename tuples.'
@checkHandleAndSynchronize([]) def get_dest_files(self, exts=None):
dest_files = [] for (index, file_entry) in enumerate(get_info_from_handle(self.handle).files()): if (self.handle.file_priority(index) > 0): filename = file_entry.path ext = os.path.splitext(filename)[1].lstrip('.') if ((exts is None) or (ext in exts)): ...
'Checkpoint this download. Returns a deferred that fires when the checkpointing is completed.'
def checkpoint(self):
if (self._checkpoint_disabled or (not self.handle) or (not self.handle.is_valid())): self._logger.warning('Ignoring checkpoint() call as checkpointing is disabled for this download or the handle is not ready.') return succeed(None) return self.save_re...
'Add a peer address from 3rd source (not tracker, not DHT) to this download. @param (hostname_ip,port) tuple'
def add_peer(self, addr):
self.get_handle().addCallback((lambda handle: handle.connect_peer(addr, 0)))
'Constructor. :param session: The Tribler session.'
def __init__(self, session):
self.session = session
'Return a dictionary with some general Tribler statistics.'
def get_tribler_statistics(self):
torrent_db_handler = self.session.open_dbhandler(NTFY_TORRENTS) channel_db_handler = self.session.open_dbhandler(NTFY_CHANNELCAST) torrent_stats = torrent_db_handler.getTorrentsStats() torrent_total_size = (0 if (torrent_stats[1] is None) else torrent_stats[1]) stats_dict = {'torrents': {'num_collec...
'Return a dictionary with some general Dispersy statistics.'
def get_dispersy_statistics(self):
dispersy = self.session.get_dispersy_instance() dispersy.statistics.update() stats = dispersy.statistics return {'wan_address': ('%s:%d' % stats.wan_address), 'lan_address': ('%s:%d' % stats.lan_address), 'connection': unicode(stats.connection_type), 'runtime': (stats.timestamp - stats.start), 'total_do...
'Return a dictionary with general statistics of the active Dispersy communities.'
def get_community_statistics(self):
communities_stats = [] dispersy = self.session.get_dispersy_instance() dispersy.statistics.update() for community in dispersy.statistics.communities: if (community.dispersy_enable_candidate_walker or community.dispersy_enable_candidate_walker_responses or community.candidates): candi...
'Migrates the torrent collecting directory.'
def _migrate_torrent_collecting_dir(self):
if ((self.torrent_collecting_dir is None) or (not os.path.isdir(self.torrent_collecting_dir))): self._logger.info(u'torrent collecting directory not found, skip: %s', self.torrent_collecting_dir) return self._delete_swift_reseeds() self._get_total_file_count() self._del...
'Renames all the torrent files to INFOHASH.torrent and delete unparseable ones.'
def _ingest_torrent_files(self):
def update_status(): progress = 1.0 if (self.total_torrent_file_count > 0): progress = (float(self.total_torrent_files_processed) / self.total_torrent_file_count) progress *= 100 self.status_update_func((u'Ingesting torrent files %.1f%% (%d/%d)...' % (progress...
'Calling this method will convert all configuration files to the ConfigObj.state format.'
def convert(self):
self.convert_session_config() self.convert_main_config() self.convert_download_checkpoints()
'Convert the sessionconfig.pickle file to triblerd.conf. Do nothing if we do not have a pickle file. Remove the pickle file after we are done.'
def convert_session_config(self):
old_filename = os.path.join(self.session.config.get_state_dir(), 'sessconfig.pickle') if (not os.path.exists(old_filename)): return with open(old_filename, 'rb') as old_file: sessconfig = pickle.load(old_file) new_config = self.session.config for (key, value) in sessconfig.iteritems(...
'Convert the abc.conf, user_download_choice.pickle, gui_settings and recent download history files to triblerd.conf.'
def convert_main_config(self):
new_config = self.session.config udcfilename = os.path.join(self.session.config.get_state_dir(), 'user_download_choice.pickle') if os.path.exists(udcfilename): with open(udcfilename, 'r') as udc_file: choices = cPickle.Unpickler(udc_file).load() choices = dict([(k.encode('hex...
'Convert all pickle download checkpoints to .state files.'
def convert_download_checkpoints(self):
checkpoint_dir = self.session.get_downloads_pstate_dir() filelist = os.listdir(checkpoint_dir) if (not any([filename.endswith('.pickle') for filename in filelist])): return if os.path.exists(checkpoint_dir): for old_filename in glob.glob(os.path.join(checkpoint_dir, '*.pickle')): ...
'Run the upgrader if it is enabled in the config. Note that by default, upgrading is enabled in the config. It is then disabled after upgrading to Tribler 7.'
def run(self):
self.current_status = u'Checking Tribler version...' if self.session.config.get_upgrader_enabled(): (failed, has_to_upgrade) = self.check_should_upgrade_database() if (has_to_upgrade and (not failed)): self.notify_starting() self.upgrade_database_to_current_version(...
'This method performs actions necessary to upgrade to Tribler 7.'
def upgrade_to_tribler7(self):
self.session.config = convert_config_to_tribler71() self.session.config.set_trustchain_enabled(True) self.session.config.set_upgrader_enabled(False) self.session.config.write()
'Broadcast a notification (event) that the upgrader is starting doing work after a check has established work on the db is required. Will only fire once.'
def notify_starting(self):
if (not self.notified): self.notified = True self.session.notifier.notify(NTFY_UPGRADER, NTFY_STARTED, None)
'Broadcast a notification (event) that the upgrader is done.'
def notify_done(self):
self.session.notifier.notify(NTFY_UPGRADER, NTFY_FINISHED, None)
'Checks the database version and upgrade if it is not the latest version.'
@blocking_call_on_reactor_thread @inlineCallbacks def upgrade_database_to_current_version(self):
try: from Tribler.Core.leveldbstore import LevelDbStore torrent_store = LevelDbStore(self.session.config.get_torrent_store_dir()) torrent_migrator = TorrentMigrator65(self.session.config.get_torrent_collecting_dir(), self.session.config.get_state_dir(), torrent_store=torrent_store, status_up...
'Starts migrating from Tribler 6.3 to 6.4.'
def start_migrate(self):
useless_files = [u'upgradingdb.txt', u'upgradingdb2.txt', u'upgradingdb3.txt', u'upgradingdb4.txt'] for i in xrange(len(useless_files)): useless_tmp_file = os.path.join(self.state_dir, useless_files[i]) if os.path.exists(useless_tmp_file): os.unlink(useless_tmp_file) self._migrat...
'Migrates the torrent collecting directory.'
def _migrate_torrent_collecting_dir(self):
if os.path.exists(self.tmp_migration_tcd_file): return if (not os.path.exists(self.tmp_migration_dir)): try: os.mkdir(self.tmp_migration_dir) except OSError as e: msg = (u'Failed to create temporary torrent collecting migration directory %s...
'Walks through the torrent collecting directory and gets the total number of file.'
def _get_total_file_count(self):
self.status_update_func(u'Scanning torrent directory. This may take a while if you have a big torrent collection...') for (root, _, files) in os.walk(self.torrent_collecting_dir): for name in files: if (name.endswith(u'.mbinmap') or name.endswith(u'....
'Deletes the reseeds dir, not used anymore.'
def _delete_swift_reseeds(self):
reseeds_path = os.path.join(self.torrent_collecting_dir, u'swift_reseeds') if os.path.exists(reseeds_path): if (not os.path.isdir(reseeds_path)): raise RuntimeError(u'The swift_reseeds path is not a directory: %s', reseeds_path) rmtree(reseeds_path) self....
'Deletes all partial swift downloads, also clean up obsolete .mhash and .mbinmap files.'
def _delete_swift_files(self):
def update_status(): progress = 1.0 if (self.total_swift_file_count > 0): progress = (float(self.swift_files_deleted) / self.total_swift_file_count) progress *= 100 self.status_update_func((u'Deleting swift files %.1f%%...' % progress)) for (root, _, files) i...
'Renames all the torrent files to INFOHASH.torrent and delete unparseable ones.'
def _rename_torrent_files(self):
def update_status(): progress = 1.0 if (self.total_torrent_file_count > 0): progress = (float(self.total_torrent_files_processed) / self.total_torrent_file_count) progress *= 100 self.status_update_func((u'Migrating torrent files %.2f%%...' % progress)) for (...
'Deletes all directories in the torrent collecting directory.'
def _delete_all_directories(self):
self.status_update_func(u'Checking all directories in torrent collecting directory...') for (root, dirs, files) in os.walk(self.torrent_collecting_dir): for d in dirs: dir_path = os.path.join(root, d) rmtree(dir_path, ignore_errors=True)
'Cleans up all SearchCommunity and MetadataCommunity stuff in dispersy database.'
def _update_dispersy(self):
db_path = os.path.join(self.state_dir, u'sqlite', u'dispersy.db') if (not os.path.isfile(db_path)): return communities_to_delete = (u'SearchCommunity', u'MetadataCommunity') connection = Connection(db_path) cursor = connection.cursor() data_updated = False for community in communitie...
'Starts migrating from Tribler 6.3 to 6.4.'
def start_migrate(self):
if (self.db.version == 17): self._upgrade_17_to_18() if (self.db.version == 18): self._upgrade_18_to_22() if (self.db.version == 22): self._upgrade_22_to_23() if (self.db.version == 23): self._upgrade_23_to_24() if (self.db.version == 24): self._upgrade_24_to_...
'Cleans up all SearchCommunity and MetadataCommunity stuff in dispersy database.'
def _purge_old_search_metadata_communities(self):
db_path = os.path.join(self.session.config.get_state_dir(), u'sqlite', u'dispersy.db') if (not os.path.isfile(db_path)): return communities_to_delete = (u'SearchCommunity', u'MetadataCommunity', u'TunnelCommunity') connection = Connection(db_path) cursor = connection.cursor() for communi...
'Migrates the database to the new version.'
def _upgrade_22_to_23(self):
self.status_update_func((u'Upgrading database from v%s to v%s...' % (22, 23))) self.db.execute(u'\nDROP TABLE IF EXISTS BarterCast;\nDROP INDEX IF EXISTS bartercast_idx;\n\nDROP INDEX IF EXISTS Torrent_swift_torrent_hash_idx;\n') try: next(self.db.e...
'Import all torrent files in the collected torrent dir, all the files already in the database will be ignored.'
def reimport_torrents(self):
self.status_update_func('Opening TorrentDBHandler...') torrent_db_handler = TorrentDBHandler(self.session) torrent_db_handler.category = Category() self.status_update_func('Registering recovered torrents...') try: for (infoshash_str, torrent_data) in self.torrent_store.iteritems(): ...
'Reindex all torrents in the database. Required when upgrading to a newer FTS engine.'
def reindex_torrents(self):
results = self.db.fetchall('SELECT torrent_id, name FROM Torrent') for torrent_result in results: if (torrent_result[1] is None): continue swarmname = split_into_keywords(torrent_result[1]) files_results = self.db.fetchall('SELECT path FROM TorrentFiles ...
'Shutting down boosting manager. It also stops and remove all the sources.'
def shutdown(self):
self.save_config() self._logger.info('Shutting down boostingmanager') for sourcekey in self.boosting_sources.keys(): self.remove_source(sourcekey) self.cancel_all_pending_tasks() shutil.rmtree(self.settings.credit_mining_path, ignore_errors=True)