def __load_session_state(self): """Loads the libtorrent session state""" try: self.session.load_state(lt.bdecode( open(deluge.configmanager.get_config_dir("session.state"), "rb").read())) except Exception, e: log.warning("Failed to load lt state: %s", e)
def stream_torrent(self, infohash=None, url=None, filedump=None, filepath_or_index=None): tor = component.get("TorrentManager").torrents.get(infohash, None) if tor is None: logger.info('Did not find torrent, must add it') if not filedump and url: filedump = yield client.getPage(url) if not filedump: defer.returnValue({'status': 'error', 'message': 'unable to find torrent, provide infohash, url or filedump'}) torrent_info = lt.torrent_info(lt.bdecode(filedump)) infohash = str(torrent_info.info_hash()) core = component.get("Core") try: yield core.add_torrent_file('file.torrent', filedump.encode('base64'), {'add_paused': True}) except: defer.returnValue({'status': 'error', 'message': 'failed to add torrent'}) try: tf = self.torrent_handler.get_stream(infohash, filepath_or_index) except UnknownTorrentException: defer.returnValue({'status': 'error', 'message': 'unable to find torrent, probably failed to add it'}) defer.returnValue({ 'status': 'success', 'use_stream_urls': self.config['use_stream_urls'], 'auto_open_stream_urls': self.config['auto_open_stream_urls'], 'url': 'http://%s:%s/file/%s/%s' % (self.config.config['ip'], self.config.config['port'], self.fsr.add_file(tf), urllib.quote_plus(os.path.basename(tf.path))) })
def add(self, torrent_info=None, state=None, options=None, save_state=True, filedump=None, filename=None, magnet=None, resume_data=None, owner=None): """Add a torrent to the manager and returns it's torrent_id""" if owner is None: owner = component.get("RPCServer").get_session_user() if not owner: owner = "localclient" if torrent_info is None and state is None and filedump is None and magnet is None: log.debug( "You must specify a valid torrent_info, torrent state or magnet." ) return add_torrent_params = {} if filedump is not None: try: torrent_info = lt.torrent_info(lt.bdecode(filedump)) except Exception, e: log.error("Unable to decode torrent file!: %s", e) # XXX: Probably should raise an exception here.. return
class TorrentHandler(object): def __init__(self, logger): self.log = logger def download_torrent_file(self, torrent_url, cookie_header): filedump = None opener = urllib2.build_opener() if cookie_header.has_key("Cookie"): opener.addheaders.append(("Cookie", cookie_header["Cookie"])) try: webFile = opener.open(torrent_url) filedump = webFile.read() except Exception, e: self.log.error( "Failed to download torrent url: '%s'. Exception: %s" % (torrent_url, str(e))) return None # Get the info to see if any exceptions are raised try: torrent_info = lt.torrent_info(lt.bdecode(filedump)) except Exception, e: self.log.error("Unable to decode torrent file! (%s) URL: '%s'" % (str(e), torrent_url)) return None
class TorrentHandler(object): def __init__(self, logger): self.log = logger def listen_on_torrent_finished(self, enable=True): component.get("EventManager").register_event_handler( "TorrentFinishedEvent", self.on_torrent_finished_event) def download_torrent_file(self, torrent_url, cookies=None, headers=None): download = TorrentDownload() download.url = torrent_url download.cookies = cookies args = {"verify": False} if cookies is not None: args["cookies"] = cookies if headers is not None: args["headers"] = headers download.headers = headers try: r = requests.get(torrent_url, **args) download.filedump = r.content except Exception, e: error_msg = "Failed to download torrent url: '%s'. Exception: %s" % ( torrent_url, str(e)) self.log.error(error_msg) download.set_error(error_msg) return download try: # Get the info to see if any exceptions are raised lt.torrent_info(lt.bdecode(download.filedump)) except Exception, e: error_msg = "Unable to decode torrent file! (%s) URL: '%s'" % ( str(e), torrent_url) download.set_error(error_msg) self.log.error(error_msg)
def download_torrent_file(self, torrent_url, cookies=None, headers=None): download = TorrentDownload() download.url = torrent_url download.cookies = cookies args = {"verify": False} if cookies is not None: args["cookies"] = cookies if headers is not None: args["headers"] = headers download.headers = headers try: r = requests.get(torrent_url, **args) download.filedump = r.content except Exception as e: error_msg = "Failed to download torrent url: '%s'. Exception: %s" % ( torrent_url, str(e)) self.log.error(error_msg) download.set_error(error_msg) return download if download.filedump is None: error_msg = "Filedump is None" download.set_error(error_msg) self.log.warning(error_msg) return download try: # Get the info to see if any exceptions are raised lt.torrent_info(lt.bdecode(download.filedump)) except Exception as e: error_msg = "Unable to decode torrent file! (%s) URL: '%s'" % ( str(e), torrent_url) download.set_error(error_msg) self.log.error(error_msg) return download
def add( self, torrent_info=None, state=None, options=None, save_state=True, filedump=None, filename=None, magnet=None, resume_data=None, ): """Add a torrent to the manager and returns it's torrent_id""" if torrent_info is None and state is None and filedump is None and magnet is None: log.debug("You must specify a valid torrent_info, torrent state or magnet.") return log.debug("torrentmanager.add") add_torrent_params = {} if filedump is not None: try: torrent_info = lt.torrent_info(lt.bdecode(filedump)) except Exception, e: log.error("Unable to decode torrent file!: %s", e) # XXX: Probably should raise an exception here.. return
def add(self, torrent_info=None, state=None, options=None, save_state=True, filedump=None, filename=None, magnet=None, resume_data=None): """Add a torrent to the manager and returns it's torrent_id""" if torrent_info is None and state is None and filedump is None and magnet is None: log.debug( "You must specify a valid torrent_info, torrent state or magnet." ) return log.debug("torrentmanager.add") add_torrent_params = {} if filedump is not None: try: torrent_info = lt.torrent_info(lt.bdecode(filedump)) except Exception, e: log.error("Unable to decode torrent file!: %s", e) # XXX: Probably should raise an exception here.. return
def stream_torrent(self, infohash=None, url=None, filedump=None, filepath_or_index=None): tor = component.get("TorrentManager").torrents.get(infohash, None) if tor is None: logger.info('Did not find torrent, must add it') if not filedump and url: filedump = yield client.getPage(url) if not filedump: defer.returnValue({ 'status': 'error', 'message': 'unable to find torrent, provide infohash, url or filedump' }) torrent_info = lt.torrent_info(lt.bdecode(filedump)) infohash = str(torrent_info.info_hash()) core = component.get("Core") try: yield core.add_torrent_file('file.torrent', filedump.encode('base64'), {'add_paused': True}) except: defer.returnValue({ 'status': 'error', 'message': 'failed to add torrent' }) try: tf = self.torrent_handler.get_stream(infohash, filepath_or_index) except UnknownTorrentException: defer.returnValue({ 'status': 'error', 'message': 'unable to find torrent, probably failed to add it' }) defer.returnValue({ 'status': 'success', 'use_stream_urls': self.config['use_stream_urls'], 'auto_open_stream_urls': self.config['auto_open_stream_urls'], 'url': 'http://%s:%s/file/%s/%s' % (self.config.config['ip'], self.config.config['port'], self.fsr.add_file(tf), urllib.quote_plus(os.path.basename( tf.path))) })
def _update(self, state_file, resume_file): state_data = cPickle.load(state_file) resume_data = lt.bdecode(resume_file.read()) state_file.close() resume_file.close() for torrent_state in state_data.torrents: torrent_id = torrent_state.torrent_id self.torrents.setdefault(torrent_id, {})["state"] = torrent_state self.torrents[torrent_id]["resume"] = resume_data.get(torrent_id)
def load_resume_data_file(self): resume_data = {} try: log.debug("Opening torrents fastresume file for load.") fastresume_file = open(os.path.join(get_config_dir(), "state", "torrents.fastresume"), "rb") resume_data = lt.bdecode(fastresume_file.read()) fastresume_file.close() except (EOFError, IOError, Exception), e: log.warning("Unable to load fastresume file: %s", e)
def stream_torrent(self, infohash=None, url=None, filedump=None, filepath_or_index=None, includes_name=False, wait_for_end_pieces=False, label=None, as_inline=False): logger.debug('Trying to stream infohash:%s, url:%s, filepath_or_index:%s' % (infohash, url, filepath_or_index)) torrent = get_torrent(infohash) if torrent is None: logger.info('Did not find torrent, must add it') if not filedump and url: filedump = yield client.getPage(url) if not filedump: defer.returnValue({'status': 'error', 'message': 'unable to find torrent, provide infohash, url or filedump'}) torrent_info = lt.torrent_info(lt.bdecode(filedump)) infohash = str(torrent_info.info_hash()) core = component.get("Core") try: yield core.add_torrent_file('file.torrent', base64.b64encode(filedump), {'add_paused': True}) if label and 'Label' in component.get('CorePluginManager').get_enabled_plugins(): label_plugin = component.get('CorePlugin.Label') if label not in label_plugin.get_labels(): label_plugin.add(label) try: label_plugin.set_torrent(infohash, label) except: logger.exception('Failed to set label') except: logger.exception('Failed to add torrent') defer.returnValue({'status': 'error', 'message': 'failed to add torrent'}) if filepath_or_index is None: fn = '' elif isinstance(filepath_or_index, int): status = torrent.get_status(['files']) fn = status['files'][filepath_or_index]['path'] else: fn = filepath_or_index try: stream_or_item = yield defer.maybeDeferred(self.torrent_handler.stream, infohash, fn, wait_for_end_pieces=wait_for_end_pieces) stream_url = self.thomas_http_output.serve_item(stream_or_item, as_inline=as_inline) except: logger.exception('Failed to stream torrent') defer.returnValue({'status': 'error', 'message': 'failed to stream torrent'}) defer.returnValue({ 'status': 'success', 'filename': stream_or_item.id, 'use_stream_urls': self.config['use_stream_urls'], 'auto_open_stream_urls': self.config['auto_open_stream_urls'], 'url': '%s/streaming/%s' % (self.base_url, stream_url.lstrip('/')) })
def get_torrent_atp(self, filename): filename = os.path.join(os.path.dirname(__file__), filename) e = lt.bdecode(open(filename, 'rb').read()) info = lt.torrent_info(e) atp = {"ti": info} atp["save_path"] = os.getcwd() atp["storage_mode"] = lt.storage_mode_t.storage_mode_sparse atp["add_paused"] = False atp["auto_managed"] = True atp["duplicate_is_error"] = True return atp
def get_torrent_atp(self, filename): filename = common.get_test_data_file(filename) with open(filename, 'rb') as _file: info = lt.torrent_info(lt.bdecode(_file.read())) atp = {'ti': info} atp['save_path'] = os.getcwd() atp['storage_mode'] = lt.storage_mode_t.storage_mode_sparse atp['add_paused'] = False atp['auto_managed'] = True atp['duplicate_is_error'] = True return atp
def get_torrent_info_from_file(self, filepath): """Returns a torrent_info for the file specified or None""" torrent_info = None # Get the torrent data from the torrent file try: log.debug("Attempting to create torrent_info from %s", filepath) _file = open(filepath, "rb") torrent_info = lt.torrent_info(lt.bdecode(_file.read())) _file.close() except (IOError, RuntimeError), e: log.warning("Unable to open %s: %s", filepath, e)
def load_resume_data_file(self): resume_data = {} try: log.debug("Opening torrents fastresume file for load.") fastresume_file = open( os.path.join(get_config_dir(), "state", "torrents.fastresume"), "rb") resume_data = lt.bdecode(fastresume_file.read()) fastresume_file.close() except (EOFError, IOError, Exception), e: log.warning("Unable to load fastresume file: %s", e)
def load_torrent(self, torrent_id): """Load a torrent file from state and return it's torrent info""" filedump = None # Get the torrent data from the torrent file try: log.debug("Attempting to open %s for add.", torrent_id) _file = open(os.path.join(get_config_dir(), "state", torrent_id + ".torrent"), "rb") filedump = lt.bdecode(_file.read()) _file.close() except (IOError, RuntimeError), e: log.warning("Unable to open %s: %s", torrent_id, e) return False
def read_torrent_info(file_contents): """Returns a dictionary with basic information from torrent contents (see `read_torrent_file()`). Dict keys: hash - Torrent hash. files - A list of files within the torrent. """ info_contents = lt.torrent_info(lt.bdecode(file_contents)) files_from_torrent = [a_file.path.decode('utf-8') for a_file in info_contents.files()] info = {'hash': str(info_contents.info_hash()), 'files': files_from_torrent} return info
def load_torrent(self, torrent_id): """Load a torrent file from state and return it's torrent info""" filedump = None # Get the torrent data from the torrent file try: log.debug("Attempting to open %s for add.", torrent_id) _file = open( os.path.join(get_config_dir(), "state", torrent_id + ".torrent"), "rb") filedump = lt.bdecode(_file.read()) _file.close() except (IOError, RuntimeError), e: log.warning("Unable to open %s: %s", torrent_id, e) return False
def write_torrentfile(self): """Writes the torrent file""" path = "%s/%s.torrent" % (os.path.join(get_config_dir(), "state"), self.torrent_id) log.debug("Writing torrent file: %s", path) try: self.torrent_info = self.handle.get_torrent_info() # Regenerate the file priorities self.set_file_priorities([]) md = lt.bdecode(self.torrent_info.metadata()) torrent_file = {} torrent_file["info"] = md open(path, "wb").write(lt.bencode(torrent_file)) except Exception, e: log.warning("Unable to save torrent file: %s", e)
def load_resume_data_file(self): filepath = os.path.join(get_config_dir(), "state", "torrents.fastresume") log.debug("Opening torrents fastresume file for load.") for _filepath in (filepath, filepath + ".bak"): try: fastresume_file = open(_filepath, "rb") resume_data = lt.bdecode(fastresume_file.read()) fastresume_file.close() except (EOFError, IOError, Exception), e: log.warning("Unable to load fastresume file: %s", e) resume_data = None else: log.info("Successfully loaded fastresume file: %s", _filepath) break
def write_torrentfile(self): """Writes the torrent file""" path = "%s/%s.torrent" % (os.path.join(get_config_dir(), "state"), self.torrent_id) log.debug("Writing torrent file: %s", path) try: # Regenerate the file priorities self.set_file_priorities([]) md = lt.bdecode(self.torrent_info.metadata()) torrent_file = {} torrent_file["info"] = md open(path, "wb").write(lt.bencode(torrent_file)) except Exception, e: log.warning("Unable to save torrent file: %s", e)
def test_prefetch_metadata(self): from deluge._libtorrent import lt with open(common.get_test_data_file('test.torrent'), 'rb') as _file: t_info = lt.torrent_info(lt.bdecode(_file.read())) mock_alert = mock.MagicMock() mock_alert.handle.info_hash = mock.MagicMock( return_value='ab570cdd5a17ea1b61e970bb72047de141bce173' ) mock_alert.handle.get_torrent_info = mock.MagicMock(return_value=t_info) magnet = 'magnet:?xt=urn:btih:ab570cdd5a17ea1b61e970bb72047de141bce173' d = self.tm.prefetch_metadata(magnet, 30) self.tm.on_alert_metadata_received(mock_alert) expected = ( 'ab570cdd5a17ea1b61e970bb72047de141bce173', bencode( { 'piece length': 32768, 'sha1': ( b'2\xce\xb6\xa8"\xd7\xf0\xd4\xbf\xdc^K\xba\x1bh' b'\x9d\xc5\xb7\xac\xdd' ), 'name': 'azcvsupdater_2.6.2.jar', 'private': 0, 'pieces': ( b'\xdb\x04B\x05\xc3\'\xdab\xb8su97\xa9u' b'\xca<w\\\x1ef\xd4\x9b\x16\xa9}\xc0\x9f:\xfd' b'\x97qv\x83\xa2"\xef\x9d7\x0by!\rl\xe5v\xb7' b'\x18{\xf7/"P\xe9\x8d\x01D\x9e8\xbd\x16\xe3' b'\xfb-\x9d\xaa\xbcM\x11\xba\x92\xfc\x13F\xf0' b'\x1c\x86x+\xc8\xd0S\xa9\x90`\xa1\xe4\x82\xe8' b'\xfc\x08\xf7\xe3\xe5\xf6\x85\x1c%\xe7%\n\xed' b'\xc0\x1f\xa1;\x9a\xea\xcf\x90\x0c/F>\xdf\xdagA' b'\xc42|\xda\x82\xf5\xa6b\xa1\xb8#\x80wI\xd8f' b'\xf8\xbd\xacW\xab\xc3s\xe0\xbbw\xf2K\xbe\xee' b'\xa8rG\xe1W\xe8\xb7\xc2i\xf3\xd8\xaf\x9d\xdc' b'\xd0#\xf4\xc1\x12u\xcd\x0bE?:\xe8\x9c\x1cu' b'\xabb(oj\r^\xd5\xd5A\x83\x88\x9a\xa1J\x1c?' b'\xa1\xd6\x8c\x83\x9e&' ), 'length': 307949, 'name.utf-8': b'azcvsupdater_2.6.2.jar', 'ed2k': b'>p\xefl\xfa]\x95K\x1b^\xc2\\;;e\xb7', } ), ) self.assertEqual(expected, self.successResultOf(d))
def get_torrent_atp(self, filename): filename = common.get_test_data_file(filename) with open(filename, 'rb') as _file: info = lt.torrent_info(lt.bdecode(_file.read())) atp = { 'ti': info, 'save_path': os.getcwd(), 'storage_mode': lt.storage_mode_t.storage_mode_sparse, 'flags': (lt.add_torrent_params_flags_t.flag_auto_managed | lt.add_torrent_params_flags_t.flag_duplicate_is_error & ~lt.add_torrent_params_flags_t.flag_paused), } return atp
def load_torrent(self, filename, magnet): log.debug('Attempting to open %s for add.', filename) file_mode = 'r' if magnet else 'rb' try: with open(filename, file_mode) as _file: filedump = _file.read() except IOError as ex: log.warning('Unable to open %s: %s', filename, ex) raise ex if not filedump: raise EOFError('Torrent is 0 bytes!') # Get the info to see if any exceptions are raised if not magnet: lt.torrent_info(lt.bdecode(filedump)) return filedump
def read_torrent_info(file_contents): """Returns a dictionary with basic information from torrent contents (see `read_torrent_file()`). Dict keys: hash - Torrent hash. files - A list of files within the torrent. """ info_contents = lt.torrent_info(lt.bdecode(file_contents)) files_from_torrent = [ a_file.path.decode('utf-8') for a_file in info_contents.files() ] info = { 'hash': str(info_contents.info_hash()), 'files': files_from_torrent } return info
class Core(CorePluginBase): def enable(self): self.config = deluge.configmanager.ConfigManager("yarss.conf", DEFAULT_PREFS) self.update_status_timer = LoopingCall(self.update_handler) #self.update_handler() self.update_status_timer.start(self.config['updatetime']) def disable(self): self.update_status_timer.stop() self.config.save(); def update(self): pass @export def set_config(self, config): "sets the config dictionary" for key in config.keys(): self.config[key] = config[key] self.config.save() @export def get_config(self): "returns the config dictionary" return self.config.config def load_torrent(self, filename): try: log.debug("Attempting to open %s for add.", filename) _file = open(filename, "rb") filedump = _file.read() if not filedump: raise RuntimeError, "Torrent is 0 bytes!" _file.close() except IOError, e: log.warning("Unable to open %s: %s", filename, e) raise e # Get the info to see if any exceptions are raised info = lt.torrent_info(lt.bdecode(filedump)) return filedump
def render_POST(self, request): log.debug("StreamXBMC: post: %r" % request.path) r = self.re_post.search(request.path) if not r: return self.bad_request(request) log.debug("StreamXBMC: request: %r" % request) headers = request.getAllHeaders() try: files = cgi.FieldStorage( fp=request.content, headers=headers, environ={"REQUEST_METHOD": "POST", "CONTENT_TYPE": headers["content-type"]}, ) filename, torrent = files["torrent_file"].filename, files["torrent_file"].value torrent_info = libtorrent.torrent_info(libtorrent.bdecode(torrent)) except Exception, e: log.error("StreamXBMC: unable to parse torrent file: %s", e) return self.bad_request(request)
def add(self, torrent_info=None, state=None, options=None, save_state=True, filedump=None, filename=None, magnet=None, resume_data=None, owner=None): """Add a torrent to the manager and returns it's torrent_id""" if owner is None: owner = component.get("RPCServer").get_session_user() if not owner: owner = "localclient" if torrent_info is None and state is None and filedump is None and magnet is None: log.debug("You must specify a valid torrent_info, torrent state or magnet.") return add_torrent_params = {} if filedump is not None: try: torrent_info = lt.torrent_info(lt.bdecode(filedump)) except Exception, e: log.error("Unable to decode torrent file!: %s", e) # XXX: Probably should raise an exception here.. return
def _load_session_state(self): """Loads the libtorrent session state Returns: dict: A libtorrent sesion state, empty dict if unable to load it. """ filename = 'session.state' filepath = get_config_dir(filename) filepath_bak = filepath + '.bak' for _filepath in (filepath, filepath_bak): log.debug('Opening %s for load: %s', filename, _filepath) try: with open(_filepath, 'rb') as _file: state = lt.bdecode(_file.read()) except (IOError, EOFError, RuntimeError) as ex: log.warning('Unable to load %s: %s', _filepath, ex) else: log.info('Successfully loaded %s: %s', filename, _filepath) self.session.load_state(state)
def stream_torrent(self, infohash=None, url=None, filedump=None, filepath_or_index=None, includes_name=False, wait_for_end_pieces=False): tor = component.get("TorrentManager").torrents.get(infohash, None) if tor is None: logger.info('Did not find torrent, must add it') if not filedump and url: filedump = yield client.getPage(url) if not filedump: defer.returnValue({'status': 'error', 'message': 'unable to find torrent, provide infohash, url or filedump'}) torrent_info = lt.torrent_info(lt.bdecode(filedump)) infohash = str(torrent_info.info_hash()) core = component.get("Core") try: yield core.add_torrent_file('file.torrent', filedump.encode('base64'), {'add_paused': True}) except: defer.returnValue({'status': 'error', 'message': 'failed to add torrent'}) try: tf = self.torrent_handler.get_stream(infohash, filepath_or_index, includes_name) except UnknownTorrentException: defer.returnValue({'status': 'error', 'message': 'unable to find torrent, probably failed to add it'}) if wait_for_end_pieces: logger.debug('Waiting for end pieces') yield tf.wait_for_end_pieces() filename = os.path.basename(tf.path).encode('utf-8') defer.returnValue({ 'status': 'success', 'filename': filename, 'use_stream_urls': self.config['use_stream_urls'], 'auto_open_stream_urls': self.config['auto_open_stream_urls'], 'url': '%s/streaming/file/%s/%s' % (self.base_url, self.fsr.add_file(tf), urllib.quote_plus(filename)) })
def render_POST(self, request): log.debug('StreamXBMC: post: %r' % request.path) r = self.re_post.search(request.path) if not r: return self.bad_request(request) log.debug('StreamXBMC: request: %r' % request) headers = request.getAllHeaders() try: files = cgi.FieldStorage(fp=request.content, headers=headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': headers['content-type'] }) filename, torrent = files['torrent_file'].filename, files[ 'torrent_file'].value torrent_info = libtorrent.torrent_info(libtorrent.bdecode(torrent)) except Exception, e: log.error('StreamXBMC: unable to parse torrent file: %s', e) return self.bad_request(request)
def assert_resume_data(): self.assert_state(torrent, 'Error') tm_resume_data = lt.bdecode( self.core.torrentmanager.resume_data[torrent.torrent_id]) self.assertEqual(tm_resume_data, resume_data)
os.remove(filepath) def load_torrent(self, filename): try: log.debug("Attempting to open %s for add.", filename) _file = open(filename, "rb") filedump = _file.read() if not filedump: raise RuntimeError, "Torrent is 0 bytes!" _file.close() except IOError, e: log.warning("Unable to open %s: %s", filename, e) raise e # Get the info to see if any exceptions are raised info = lt.torrent_info(lt.bdecode(filedump)) return filedump def _on_autoadd_enable(self, key, value): log.debug("_on_autoadd_enable") if value: component.resume("AutoAdd") else: component.pause("AutoAdd") def _on_autoadd_location(self, key, value): log.debug("_on_autoadd_location") # We need to resume the component just incase it was paused due to # an invalid autoadd location. if self.config["autoadd_enable"]:
#cleanup of args if contentPath.endswith(os.sep): contentPath = contentPath[:-1]; if configPath.endswith(os.sep): configPath = contentPath[:-1]; #cd of configPath to ./state configPath = configPath+os.sep+"state"+os.sep #get file pointers statefile = None; resume_file = None; #open and parse resume_file with open(configPath+"torrents.fastresume", 'rb') as resume_file_handler: resume_file = lt.bdecode(resume_file_handler.read()); #open statefile with open(configPath+"torrents.state", 'rb') as statefile_handler: statefile = cPickle.load(statefile_handler); #get list of all subdirfiles allfiles=get_filepaths(contentPath) #begin processing i = 0 target_path = None change = False for t in statefile.torrents: print i, t.filename; i+=1
def assert_resume_data(): self.assert_state(torrent, 'Error') tm_resume_data = lt.bdecode(self.core.torrentmanager.resume_data[torrent.torrent_id]) self.assertEqual(tm_resume_data, resume_data)
class OldStateUpgrader: def __init__(self): self.config = ConfigManager("core.conf") self.state05_location = os.path.join(get_config_dir(), "persistent.state") self.state10_location = os.path.join(get_config_dir(), "state", "torrents.state") if os.path.exists(self.state05_location) and not os.path.exists( self.state10_location): # If the 0.5 state file exists and the 1.0 doesn't, then let's upgrade it self.upgrade05() def upgrade05(self): try: state = PickleUpgrader(open(self.state05_location, "rb")).load() except Exception, e: log.debug("Unable to open 0.5 state file: %s", e) return # Check to see if we can upgrade this file if type(state).__name__ == 'list': log.warning("0.5 state file is too old to upgrade") return new_state = deluge.core.torrentmanager.TorrentManagerState() for ti, uid in state.torrents.items(): torrent_path = os.path.join(get_config_dir(), "torrentfiles", ti.filename) try: torrent_info = None log.debug("Attempting to create torrent_info from %s", torrent_path) _file = open(torrent_path, "rb") torrent_info = lt.torrent_info(lt.bdecode(_file.read())) _file.close() except (IOError, RuntimeError), e: log.warning("Unable to open %s: %s", torrent_path, e) # Copy the torrent file to the new location import shutil shutil.copyfile( torrent_path, os.path.join(get_config_dir(), "state", str(torrent_info.info_hash()) + ".torrent")) # Set the file prioritiy property if not already there if not hasattr(ti, "priorities"): ti.priorities = [1] * torrent_info.num_files() # Create the new TorrentState object new_torrent = deluge.core.torrentmanager.TorrentState( torrent_id=str(torrent_info.info_hash()), filename=ti.filename, save_path=ti.save_dir, compact=ti.compact, paused=ti.user_paused, total_uploaded=ti.uploaded_memory, max_upload_speed=ti.upload_rate_limit, max_download_speed=ti.download_rate_limit, file_priorities=ti.priorities, queue=state.queue.index(ti)) # Append the object to the state list new_state.torrents.append(new_torrent)