def load_torrent(proxy, ID, path): """Send a torrent to rtorrent and kick off the hash recheck""" logger = logging.getLogger(__name__) torrent = ptpapi.Torrent(ID=ID) torrent_data = torrent.download() data = bencode.bdecode(torrent_data) thash = metafile.info_hash(data) try: logger.debug(u"Testing for hash {0}".format( proxy.d.hash(thash, fail_silently=True))) logger.error( u"Hash {0} already exists in rtorrent as {1}, cannot load.".format( thash, proxy.d.name(thash))) return except (xmlrpc_client.Fault, xmlrpc.HashNotFound): pass proxy.load.raw('', xmlrpc_client.Binary(torrent_data)) # Wait until the torrent is loaded and available while True: sleep(1) try: proxy.d.hash(thash, fail_silently=True) break except (xmlrpc_client.Fault, xmlrpc.HashNotFound): pass logger.info(u"Torrent loaded at {0}".format(path)) proxy.d.custom.set(thash, 'tm_completed', str(int(time()))) proxy.d.directory.set(thash, path) proxy.d.check_hash(thash)
def download_to_file(self, ID, dest=None): logger = logging.getLogger(__name__) r = self.session.get(self.baseURL + '/download.php', params={'id': ID}) r.raise_for_status() if not dest: name = bencode.bdecode(r.content)['info']['name'].replace('/', '_') + '.torrent' dest = os.path.join(config.get('Main', 'downloadDirectory'), name) logger.debug('Downloading ID {} to {}'.format(ID, dest.encode('utf-8'))) with open(dest, 'wb') as fh: fh.write(r.content)
def main(args): if len(args) != 3 or '-h' in args or '--help' in args: print('Usage: {} <uTorrent-directory> <transmission-directory>'.format(args[0])) return input_dir = args[1] input_file_name = os.path.join(input_dir, 'resume.dat') output_dir = args[2] dec = None try: with open(input_file_name) as ut: dec = bdecode(ut.read()) except Exception, e: print('Error: {}'.format(e)) return
def checked_open(filename, log=None, quiet=False): """ Open and validate the given metafile. Optionally provide diagnostics on the passed logger, for invalid metafiles, which then just cause a warning but no exception. "quiet" can supress that warning. """ with closing(open(filename, "rb")) as handle: raw_data = handle.read() data = bencode.bdecode(raw_data) try: check_meta(data) if raw_data != bencode.bencode(data): raise ValueError("Bad bencoded data - dict keys out of order?") except ValueError, exc: if log: # Warn about it, unless it's a quiet value query if not quiet: log.warn("%s: %s" % (filename, exc)) else: raise
def do_session(self): """Restore state from session files.""" def filenames(): 'Helper' for arg in self.args: if os.path.isdir(arg): for name in glob.glob(os.path.join(arg, '*.torrent.rtorrent')): yield name elif arg == '@-': for line in sys.stdin.read().splitlines(): if line.strip(): yield line.strip() elif arg.startswith('@'): if not os.path.isfile(arg[1:]): self.parser.error("File not found (or not a file): {}".format(arg[1:])) with io.open(arg[1:], encoding='utf-8') as handle: for line in handle: if line.strip(): yield line.strip() else: yield arg proxy = self.open() for filename in filenames(): # Check filename and extract infohash self.LOG.debug("Reading '%s'...", filename) match = re.match(r'(?:.+?[-._])?([a-fA-F0-9]{40})(?:[-._].+?)?\.torrent\.rtorrent', os.path.basename(filename)) if not match: self.LOG.warn("Skipping badly named session file '%s'...", filename) continue infohash = match.group(1) # Read bencoded data try: with open(filename, 'rb') as handle: raw_data = handle.read() data = Bunch(bencode.bdecode(raw_data)) except EnvironmentError as exc: self.LOG.warn("Can't read '%s' (%s)" % ( filename, str(exc).replace(": '%s'" % filename, ""), )) continue ##print(infohash, '=', repr(data)) if 'state_changed' not in data: self.LOG.warn("Skipping invalid session file '%s'...", filename) continue # Restore metadata was_active = proxy.d.is_active(infohash) proxy.d.ignore_commands.set(infohash, data.ignore_commands) proxy.d.priority.set(infohash, data.priority) if proxy.d.throttle_name(infohash) != data.throttle_name: proxy.d.pause(infohash) proxy.d.throttle_name.set(infohash, data.throttle_name) if proxy.d.directory(infohash) != data.directory: proxy.d.stop(infohash) proxy.d.directory_base.set(infohash, data.directory) for i in range(5): key = 'custom%d' % (i + 1) getattr(proxy.d, key).set(infohash, data[key]) for key, val in data.custom.items(): proxy.d.custom.set(infohash, key, val) for name in data.views: try: proxy.view.set_visible(infohash, name) except xmlrpclib.Fault as exc: if 'Could not find view' not in str(exc): raise if was_active and not proxy.d.is_active(infohash): (proxy.d.resume if proxy.d.is_open(infohash) else proxy.d.start)(infohash) proxy.d.save_full_session(infohash) """ TODO: