def make_meta_file(loc, url, params=None, flag=None, progress=lambda x: None, progress_percent=True): """Make a single .torrent file for a given location""" if params is None: params = {} if flag is None: flag = threading.Event() tree = BTTree(loc, []) # Extract target from parameters if 'target' not in params or params['target'] == '': fname, ext = os.path.split(loc) if ext == '': target = fname + '.torrent' else: target = os.path.join(fname, ext + '.torrent') params['target'] = target info = tree.makeInfo(flag=flag, progress=progress, progress_percent=progress_percent, **params) if flag is not None and flag.is_set(): return metainfo = MetaInfo(announce=url, info=info, **params) metainfo.write(params['target'])
def get_metainfo(fname, url, errorfunc): with WarningLock(lambda *args: errorfunc("warning: bad data in metafile")): if fname: try: metainfo = MetaInfo.read(fname) except (OSError, TypeError, KeyError, ValueError): errorfunc(fname + ' is not a valid metafile') return None else: try: metainfo = MetaInfo(bdecode(geturl(url))) except IOError as e: errorfunc('problem getting response info - ' + str(e)) return None except (TypeError, KeyError, ValueError): errorfunc(fname + ' is not a valid metafile') return None try: check_info(metainfo.get('info')) except ValueError as e: errorfunc("got bad file info - " + str(e)) return None return metainfo
def get_metainfo(fname, url, errorfunc): with WarningLock(lambda *args: errorfunc("warning: bad data in metafile")): if fname: try: metainfo = MetaInfo.read(fname) except (OSError, TypeError, KeyError, ValueError): errorfunc(fname + ' is not a valid metafile') return None else: try: with urlopen(url) as handle: metainfo = MetaInfo(bdecode(handle.read())) except IOError as e: errorfunc('problem getting response info - ' + str(e)) return None except (TypeError, KeyError, ValueError): errorfunc(fname + ' is not a valid metafile') return None try: check_info(metainfo.get('info')) except ValueError as e: errorfunc("got bad file info - " + str(e)) return None return metainfo
def _announcecopy(self, f): try: metainfo = MetaInfo.read(f) self.announce = metainfo['announce'] self.announce_list = metainfo.get('announce-list') except (IOError, ValueError): return
def reannounce(fname, announce, announce_list=None, verbose=False): """Replace announce and announce-list in info file""" metainfo = MetaInfo.read(fname) if verbose: # Accept torrents with no announce if 'announce' in metainfo: print('old announce for {}: {}'.format(fname, metainfo['announce'])) else: print('No announce found.') metainfo['announce'] = announce if 'announce-list' in metainfo: if verbose: print('old announce-list for {}: {}'.format( fname, '|'.join(','.join(tier) for tier in metainfo['announce-list']))) if announce_list is not None: metainfo['announce-list'] = announce_list else: metainfo.pop('announce-list', None) metainfo.write(fname)
def rename(fname, newname, verbose=False): metainfo = MetaInfo.read(fname) if verbose: print("{}: {} -> {}".format(fname, metainfo['info']['name'], newname)) metainfo['info']['name'] = newname metainfo.write(fname)
def rename(fname, newname, verbose=False): metainfo = MetaInfo.read(fname) if verbose: print "%s: %s -> %s" % (fname, metainfo['info']['name'], newname) metainfo['info']['name'] = newname metainfo.write(fname)
def _announcecopy(self, f, external=False): try: metainfo = MetaInfo.read(f) self.annCtl.SetValue(metainfo['announce']) if 'announce-list' in metainfo: self.annListCtl.SetValue('\n'.join( ', '.join(tier) for tier in metainfo['announce-list'])) else: self.annListCtl.SetValue('') if external: self.choices.SetSelection(0) self.choices1.SetSelection(0) except (IOError, ValueError): return
def main(argv): program, _ = os.path.splitext(os.path.basename(argv[0])) usage = ( """Usage: %s <http-seeds> file1.torrent [file2.torrent...] Where: http-seeds = list of seed URLs, in the format: url[|url...] or 0 if the list is a zero, any http seeds will be stripped. """ % program ) try: opts, args = getopt.getopt(argv[1:], "hv", ("help", "verbose")) except getopt.error as msg: print(msg) return 1 if len(args) < 2: print(usage) return 2 http_seeds = None if args[0] != "0": http_seeds = args[0].split("|") verbose = False for opt, _ in opts: if opt in ("-h", "--help"): print(usage) return 0 elif opt in ("-v", "--verbose"): verbose = True for fname in args[1:]: metainfo = MetaInfo.read(fname) if "httpseeds" in metainfo: if verbose: print("old http-seed list for {}: {}".format(fname, "|".join(metainfo["httpseeds"]))) if http_seeds is None: del metainfo["httpseeds"] if http_seeds is not None: metainfo["httpseeds"] = http_seeds metainfo.write(fname)
def _announcecopy(self, f, external=False): try: metainfo = MetaInfo.read(f) self.annCtl.SetValue(metainfo['announce']) if 'announce-list' in metainfo: self.annListCtl.SetValue('\n'.join(', '.join(tier) for tier in metainfo['announce-list']) ) else: self.annListCtl.SetValue('') if external: self.choices.SetSelection(0) self.choices1.SetSelection(0) except (IOError, ValueError): return
def announcecopy(self, event): dialog = wx.FileDialog(self.frame, 'Choose .torrent file to use', wildcard='*.torrent', style=wx.OPEN) if dialog.ShowModal() == wx.ID_OK: try: metainfo = MetaInfo.read(dialog.GetPath()) self.annCtl.SetValue(metainfo['announce']) if 'announce-list' in metainfo: self.annListCtl.SetValue( '\n'.join(', '.join(tier) for tier in metainfo['announce-list'])) else: self.annListCtl.SetValue('') except (IOError, ValueError): return
def main(argv): program, _ = os.path.splitext(os.path.basename(argv[0])) usage = """Usage: %s <http-seeds> file1.torrent [file2.torrent...] Where: http-seeds = list of seed URLs, in the format: url[|url...] or 0 if the list is a zero, any http seeds will be stripped. """ % program try: opts, args = getopt.getopt(argv[1:], "hv", ("help", "verbose")) except getopt.error as msg: print msg return 1 if len(args) < 2: print usage return 2 http_seeds = None if args[0] != '0': http_seeds = args[0].split('|') verbose = False for opt, _ in opts: if opt in ('-h', '--help'): print usage return 0 elif opt in ('-v', '--verbose'): verbose = True for fname in args[1:]: metainfo = MetaInfo.read(fname) if 'httpseeds' in metainfo: if verbose: print 'old http-seed list for {}: {}'.format( fname, '|'.join(metainfo['httpseeds'])) if http_seeds is None: del metainfo['httpseeds'] if http_seeds is not None: metainfo['httpseeds'] = http_seeds metainfo.write(fname)
def parse_torrent(path, return_metainfo=False): """Load and derive metadata from torrent file Parameters str - path of file to parse bool - parsed metadata to include full torrent data Returns {str: *} - torrent file metadata str - sha hash of encoded info dict """ fname = os.path.basename(path) data = MetaInfo.read(path) # Validate and hash info dict info = data['info'] check_info(info) infohash = hashlib.sha1(bencode(info)).digest() single = 'length' in info torrentinfo = { 'path': path, 'file': fname, 'name': info.get('name', fname), 'numfiles': 1 if single else len(info['files']), 'length': info['length'] if single else sum(li['length'] for li in info['files'] if 'length' in li) } for key in ('failure reason', 'warning message', 'announce-list'): if key in data: torrentinfo[key] = data[key] if return_metainfo: torrentinfo['metainfo'] = data return torrentinfo, infohash
def main(argv): """Copy announce information from source to all specified torrents""" program, _ = os.path.splitext(os.path.basename(argv[0])) usage = "Usage: %s <source.torrent> <file1.torrent> " \ "[file2.torrent...]" % program try: opts, args = getopt.getopt(argv[1:], "hv", ("help", "verbose")) except getopt.error as msg: print msg return 1 if len(args) < 2: print "%s\n%s\n" % (usage, main.__doc__) return 2 source_metainfo = MetaInfo.read(args[0]) verbose = False for opt, _ in opts: if opt in ('-h', '--help'): print "%s\n%s\n" % (usage, main.__doc__) return 0 elif opt in ('-v', '--verbose'): verbose = True announce = source_metainfo['announce'] announce_list = source_metainfo.get('announce-list') if verbose: print 'new announce: ' + announce if announce_list: print 'new announce-list: ' + \ '|'.join(','.join(tier) for tier in announce_list) for fname in args[1:]: reannounce(fname, announce, announce_list, verbose) return 0
def parse_torrent(path, return_metainfo=False): """Load and derive metadata from torrent file Parameters str - path of file to parse bool - parsed metadata to include full torrent data Returns {str: *} - torrent file metadata str - sha hash of encoded info dict """ fname = os.path.basename(path) data = MetaInfo.read(path) # Validate and hash info dict info = data['info'] check_info(info) infohash = hashlib.sha1(bencode(info)).digest() single = 'length' in info torrentinfo = { 'path': path, 'file': fname, 'name': info.get('name', fname), 'numfiles': 1 if single else len(info['files']), 'length': info['length'] if single else sum( li['length'] for li in info['files'] if 'length' in li) } for key in ('failure reason', 'warning message', 'announce-list'): if key in data: torrentinfo[key] = data[key] if return_metainfo: torrentinfo['metainfo'] = data return torrentinfo, infohash
def reannounce(fname, announce, announce_list=None, verbose=False): """Replace announce and announce-list in info file""" metainfo = MetaInfo.read(fname) if verbose: # Accept torrents with no announce if "announce" in metainfo: print("old announce for {}: {}".format(fname, metainfo["announce"])) else: print("No announce found.") metainfo["announce"] = announce if "announce-list" in metainfo and verbose: print( "old announce-list for {}: {}".format(fname, "|".join(",".join(tier) for tier in metainfo["announce-list"])) ) if announce_list is not None: metainfo["announce-list"] = announce_list else: metainfo.pop("announce-list", None) metainfo.write(fname)
from BitTornado.Meta.bencode import bencode NAME, EXT = os.path.splitext(os.path.basename(sys.argv[0])) VERSION = '20130326' print('{} {} - decode BitTorrent metainfo files'.format(NAME, VERSION)) print() if len(sys.argv) == 1: print('{} file1.torrent file2.torrent file3.torrent ...'.format( sys.argv[0])) print() sys.exit(2) # common exit code for syntax error for metainfo_name in sys.argv[1:]: metainfo = MetaInfo.read(metainfo_name) info = metainfo['info'] info_hash = hashlib.sha1(bencode(info)) print('metainfo file.:', os.path.basename(metainfo_name)) print('info hash.....:', info_hash.hexdigest()) piece_length = info['piece length'] if 'length' in info: # let's assume we just have a file print('file name.....:', info['name']) file_length = info['length'] name = 'file size.....:' else: # let's assume we have a directory structure print('directory name:', info['name']) print('files.........:')