def test_to_file(): t0 = Torrent({}) with pytest.raises(TorrentError): t0.to_file() t1 = Torrent.from_file(FPATH_TORRENT_SIMPLE) fpath = join(mkdtemp(), str(uuid4())) t1.to_file(fpath) t2 = Torrent.from_file(fpath) assert t1._struct == t2._struct
def monitor_update(TorrentPath, value, remove=False): elementum_setting, elementum_host, TorrentPath = setting() json = jsontools.load(open(monitor, "r").read()) Monitor = json['monitor'] info = Torrent.from_file(filetools.join(TorrentPath, value + '.torrent')) path = xbmc.translatePath(config.get_setting('downloadlistpath')) if not value in Monitor: Monitor[value]={} Monitor[value]['name'] = info.name Monitor[value]['size'] = info.total_size File = find_file(value) Monitor[value]['file'] = File json = jsontools.dump(json) filetools.write(monitor, json, silent=True) backupFilename = jsontools.load(open(filetools.join(path, File), "r").read())['downloadFilename'] jsontools.update_node(value, File, 'TorrentName', path, silent=True) jsontools.update_node(info.total_size, File, 'downloadSize', path, silent=True) jsontools.update_node(backupFilename, File, 'backupFilename', path, silent=True) jsontools.update_node(info.name, File, 'downloadFilename', path, silent=True) elif remove: Monitor.pop(value) jsontools.dump(json) filetools.write(monitor, jsontools.dump(json), silent=True) if len(Monitor) == 0: set_elementum()
def get_torrent_file(sha256): #### 1. Locate the sample for downloading f_src = DIR_DATA + sha256[0] + "/" + sha256[1] + "/" + sha256[2] + "/" + sha256[3] + "/" + sha256 f_src = os.path.abspath(f_src) print("[p2p] Download sample: {}".format(f_src)) #### 2. Create a folder to store sample dir_download = DIR_DOWNLOAD_TORRENT + sha256 + "/" dir_download = os.path.abspath(dir_download) + "/" os.makedirs(dir_download, exist_ok=True) print("[p2p] Download folder: {}".format(dir_download)) #### 3. Copy the sample into download folder f_dst = dir_download + sha256 f_dst = os.path.abspath(f_dst) shutil.copyfile(f_src, f_dst) print("[p2p] Copy sample to {}".format(f_dst)) #### 4. Generate torrent file new_torrent = Torrent.create_from(dir_download) f_torrent = DIR_DOWNLOAD_TORRENT + sha256 + ".torrent" f_torrent = os.path.abspath(f_torrent) new_torrent.to_file(f_torrent) print("[p2p] Create torrent file {}".format(f_torrent)) #### 5. Return torrent file return f_torrent
def get_torrent_files(list_sha256): if not list_sha256: return "" #### 1. Clean TEMP folder del_dir_files() #### 2. Mov files into TEMP folder for sha256 in list_sha256: # 1.1 locate source file f_src = DIR_DATA + sha256[0] + "/" + sha256[1] + "/" + sha256[2] + "/" + sha256[3] + "/" + sha256 f_src = os.path.abspath(f_src) if not os.path.exists(f_src): continue # 1.2 locate destination file f_dst = DIR_TEMP + sha256 f_dst = os.path.abspath(f_dst) # 1.3 copy samples into TEMP folder shutil.copy(f_src, f_dst) #### 3. Generate torrent file new_torrent = Torrent.create_from(DIR_TEMP) f_torrent = DIR_DOWNLOAD + "list.torrent" f_torrent = os.path.abspath(f_torrent) new_torrent.to_file(f_torrent) print("[p2p] Create torrent file {}".format(f_torrent)) #### 4. Return torrent file return f_torrent
def test_str(torr_test_file): """ Tests Torrent.__str__ method """ t = Torrent.from_file(torr_test_file) assert str(t) == 'Torrent: root.txt' t.name = 'Мой торрент' assert str(t) == 'Torrent: Мой торрент'
def transfer_files(filename, base_folder): if filename.find(".") != -1: ext = get_extension(filename) # torrent file check # watch torrent which will be checked when processing directories if (ext == ".torrent"): torrent_folder = Torrent.from_file(base_folder + "/" + filename).name.encode('ascii') # convert name property of torrent file to a normal string global folder_torrent folder_torrent.append(torrent_folder) folder = get_folder(ext) # print "folder = " + folder if folder != "NA": folder_path = base_folder + "/" + folder # check if a sorting folder directory exists if os.path.exists(folder_path) == False: os.mkdir(folder_path) #move file to sorting folder try: shutil.move(base_folder + "/" + filename, folder_path) global move_count move_count += 1 # print "moved " + filename + " to " + folder except: print("\nERROR: File transfer error: " + filename + "\n")
def parse_torrent(torrent: bytes) -> Torrent: """Returns Torrent object from torrent contents. :param torrent: Torrent file contents. """ return Torrent.from_string(torrent)
def test_getters_dir(): t = Torrent.from_file(FPATH_TORRENT_WITH_DIR) assert t._filepath == FPATH_TORRENT_WITH_DIR assert t.created_by == 'Transmission/2.84 (14307)' assert t.files == [(normpath('torrtest/root.txt'), 4), (normpath('torrtest/sub1/sub11.txt'), 4), (normpath(u'torrtest/sub1/sub2/кириллица.txt'), 11), (normpath('torrtest/sub1/sub2/sub22.txt'), 4)] assert t.total_size == 23 assert t.announce_urls == [[ 'http://track1.org/1/', 'http://track2.org/2/' ]] assert t.creation_date.isoformat() == '2015-10-25T09:42:04' assert t.comment == u'примечание' hash_expected = 'c815be93f20bf8b12fed14bee35c14b19b1d1984' assert t.info_hash == hash_expected magnet = t.magnet_link assert hash_expected in magnet assert 'btih' in magnet assert 'magnet:' in magnet magnet = t.get_magnet(detailed=True) assert ( magnet == 'magnet:?xt=urn:btih:c815be93f20bf8b12fed14bee35c14b19b1d1984' '&tr=http%3A%2F%2Ftrack1.org%2F1%2F&tr=http%3A%2F%2Ftrack2.org%2F2%2F')
def test_str(): """ Tests Torrent.__str__ method """ t = Torrent.from_file(FPATH_TORRENT_SIMPLE) assert str(t) == 'Torrent: root.txt' t.name = 'Мой торрент' assert str(t) == 'Torrent: Мой торрент'
def test_getters_simple(): t = Torrent.from_file(FPATH_TORRENT_SIMPLE) assert t._filepath == FPATH_TORRENT_SIMPLE assert t.created_by == 'Transmission/2.84 (14307)' files = t.files assert len(files) == 1 assert files[0].name == files[0][0] == 'root.txt' assert files[0].length == 4 assert t.total_size == 4 assert t.name == u'root.txt' assert t.announce_urls == [['udp://123.123.123.123']] assert t.creation_date.isoformat() == '2015-10-21T17:40:05' assert t.comment is None hash_expected = '238967c8417cc6ccc378df16687d1958277f270b' assert t.info_hash == hash_expected magnet = t.magnet_link assert hash_expected in magnet assert 'btih' in magnet assert 'magnet:' in magnet
def getHashinfor(): dir = "/home/pyHome/download/" file_path = dir+"down.torrent" file_name = "" #print file_path my_torrent = None my_torrent = Torrent.from_file(file_path) #print type(my_torrent) print my_torrent.magnet_link files = my_torrent.files con = getConnect() print files print "------------------------------------------" try: uuid1 = str(uuid.uuid1()) for file in files: sqlStr = "insert into torrent_info (name, size, mangent, fkey) VALUES('v1', v2, 'v3', 'v4')" name = file[0].replace("'", "\'"); sqlStr = sqlStr.replace("v1", name) sqlStr = sqlStr.replace("v2", str(file[1])) sqlStr = sqlStr.replace("v3", "#") sqlStr = sqlStr.replace("v4", uuid1) print sqlStr cur = con.cursor() cur.execute(sqlStr) con.commit() finally: cur.close()
def test_create(): fp = join(CURRENT_DIR, 'torrtest', 'root.txt') t = Torrent.create_from(fp) t.private = True assert t._struct['info'] == STRUCT_TORRENT_SIMPLE['info'] # Note that STRUCT_TORRENT_WITH_DIR will probably # differ from struct created during this test (due to different file ordering - Transmission-torrentool), # so all we do is checking all files are present. t = Torrent.create_from(join(CURRENT_DIR, 'torrtest')) info = t._struct['info'] expected_info = STRUCT_TORRENT_WITH_DIR['info'] def get_fpaths(info): return {'|'.join(f['path']) for f in info['files']} assert get_fpaths(info) == get_fpaths(expected_info)
def test_create(datafix_dir, struct_torr_dir, struct_torr_file): fp = datafix_dir / 'torrtest' / 'root.txt' t = Torrent.create_from(str(fp)) t.private = True assert t._struct['info'] == struct_torr_file['info'] # Note that STRUCT_TORRENT_WITH_DIR will probably # differ from struct created during this test (due to different file ordering - Transmission-torrentool), # so all we do is checking all files are present. t = Torrent.create_from(str(datafix_dir / 'torrtest')) info = t._struct['info'] expected_info = struct_torr_dir['info'] def get_fpaths(info): return {'|'.join(f['path']) for f in info['files']} assert get_fpaths(info) == get_fpaths(expected_info)
def to_torrent(self, save_path=None): if save_path is None: save_path = os.path.join(os.getcwd(), (self.name + '.torrent')) # Fix me! new_torrent = Torrent.create_from(self.fp) # #new_torrent.announce_urls = 'udp://tracker.openbittorrent.com:80' new_torrent.to_file(save_path) # fix me self.torrent_name = os.path.basename(save_path) return new_torrent, save_path """0-250MB: 256KB (262144 bytes)
def parse_torrent(torrent: bytes) -> Optional[Torrent]: """Returns Torrent object from torrent contents. :param torrent: Torrent file contents. """ try: return Torrent.from_string(torrent) except BencodeDecodingError as e: LOGGER.error(f'Unable to parse torrent: {e}') return None
def parse_torrent(torrent): """Returns a dictionary with basic information from torrent contents. :param torrent: :return: torrent info dict - keys: hash; name; files; torrent (torrent file contents just from input). :rtype: dict """ torrent_info = Torrent.from_string(torrent) files_from_torrent = [a_file[0] for a_file in torrent_info.files] info = { 'hash': str(torrent_info.info_hash), 'name': torrent_info.name, 'files': files_from_torrent, 'torrent': torrent } return info
def test_setters_webseed(): t = Torrent() t.name = 'mytorrent' t.webseeds = None assert t.webseeds == [] t.webseeds = 'http://host.some/file' assert t.webseeds == ['http://host.some/file'] assert (t.get_magnet() == 'magnet:?xt=urn:btih:0f967b3f021421750069f93d256e319f13c404b1' '&ws=http%3A%2F%2Fhost.some%2Ffile') seeds = ['seed1', 'seed2'] t.webseeds = seeds assert t.webseeds == seeds assert t.get_magnet( ) == 'magnet:?xt=urn:btih:0f967b3f021421750069f93d256e319f13c404b1&ws=seed1&ws=seed2' t.webseeds = None assert t.webseeds == [] assert 'url-list' not in t._struct
def test_to_file(torr_test_file): t0 = Torrent({}) with pytest.raises(TorrentError): t0.to_file() t1 = Torrent.from_file(torr_test_file) fpath = join(mkdtemp(), str(uuid4())) t1.to_file(fpath) t2 = Torrent.from_file(fpath) assert t1._struct == t2._struct
def create(source, dest, tracker, open_trackers, comment, cache): """Create torrent file from a single file or a directory.""" def check_path(fpath): fpath = path.abspath(fpath) if not path.exists(fpath): click.secho('Path is not found: %s' % fpath, fg='red', err=True) exit(1) return fpath if not dest: dest = getcwd() source = check_path(source) source_title = path.basename(source).replace('.', '_').replace(' ', '_') dest = check_path(dest) dest = '%s.torrent' % path.join(dest, source_title) click.secho('Creating torrent from %s ...' % source) my_torrent = Torrent.create_from(source) if comment: my_torrent.comment = comment urls = [] if tracker: urls = tracker.split(',') if open_trackers: urls.extend(get_open_trackers()) if urls: my_torrent.announce_urls = urls my_torrent.to_file(dest) click.secho('Torrent file created: %s' % dest, fg='green') click.secho('Torrent info hash: %s' % my_torrent.info_hash, fg='blue') if cache: upload_cache(dest)
def test_setters_httpseed(): t = Torrent() t.name = 'mytorrent' t.httpseeds = None assert t.httpseeds == [] t.httpseeds = 'http://host.some/file' assert t.httpseeds == ['http://host.some/file'] seeds = ['seed1', 'seed2'] t.httpseeds = seeds assert t.httpseeds == seeds t.httpseeds = None assert t.httpseeds == [] assert 'httpseeds' not in t._struct
def test_getters_simple(): t = Torrent.from_file(FPATH_TORRENT_SIMPLE) assert t._filepath == FPATH_TORRENT_SIMPLE assert t.created_by == 'Transmission/2.84 (14307)' assert t.files == [('root.txt', 4)] assert t.total_size == 4 assert t.name == u'root.txt' assert t.announce_urls == [['udp://123.123.123.123']] assert t.creation_date.isoformat() == '2015-10-21T17:40:05' assert t.comment is None hash_expected = '238967c8417cc6ccc378df16687d1958277f270b' assert t.info_hash == hash_expected magnet = t.magnet_link assert hash_expected in magnet assert 'btih' in magnet assert 'magnet:' in magnet
def get_torrent(infohash): downloadUrl = "http://torcache.net/torrent/value1.torrent" downloadUrl = downloadUrl.replace('value1', infohash) dirHome = "/home/pyHome/download/" downloadFile = dirHome+infohash+".torrent" #print downloadFile #os.chdir(dirHome) try: send_headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36', 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' } req = urllib2.Request(downloadUrl,headers=send_headers) file = urllib2.urlopen(req).read() open(downloadFile, "w").write(file) my_torrent = Torrent.from_file(downloadFile) print my_torrent.files except NameError, msg: print msg
def generatingTorrent(): remoteTempTorrent() if not os.path.exists(f'torrents/{request.args.get("id")}.torrent'): return "torrent unavailable" my_torrent = Torrent.from_file( f'torrents/{request.args.get("id")}.torrent') # changing passkey for one transmitted as parameter by user newUrlTracker = re.sub("[a-zA-Z0-9]{32}", request.args.get("passkey"), ((my_torrent.announce_urls[0])[0])) my_torrent.announce_urls = newUrlTracker # write it in temp dir for more clarity my_torrent.to_file( f'torrents/tmp/{request.args.get("id")}.{request.args.get("passkey")}.torrent' ) # send torrent file return send_file( f'torrents/tmp/{request.args.get("id")}.{request.args.get("passkey")}.torrent', as_attachment=True, attachment_filename=(my_torrent.name + ".torrent"), mimetype='application/x-bittorrent')
def create_seek_data(seed_file, torDir): if not os.path.exists(seed_file): print('invalid torrent file') return from torrentool.api import Torrent torrent_info = Torrent.from_file(seed_file) print('seek for %s' % torrent_info.name) for it in torrent_info.files: fit = os.path.join('/tmp', it[0]) pname, fname = os.path.split(fit) if not os.path.exists(pname): os.makedirs(pname) with open(fit, 'wb') as f: f.seek(max(0, it[1] - 1)) f.write(b'\x00') entry = os.path.join('/tmp', torrent_info.name) os.system('rsync -avhP --size-only --bwlimit=32000 "%s" "%s"' % (entry, torDir))
def vuze_done_move(): res = os.popen("ps aux | grep '[%s]%s'" % (vuzescpt[0], vuzescpt[1:])).readlines() if len(res) != 0: return L = [] for it in os.listdir(vuzetodo): if not it.endswith('.torrent') or it.startswith('.'): continue seed_file = os.path.join(vuzetodo, it) torrent_info = Torrent.from_file(seed_file) tpath = os.path.join('/Volumes/Store/Downloads/complete', torrent_info.name) if torrent_info.announce_urls[0][0].find('totheglory.im') < 0: continue all_exists = True # 避免重复下载了已有的种子,再次传输到主磁盘 for fit in torrent_info.files: if not os.path.exists( os.path.join('/Volumes/Googol/Torrent', fit[0])): all_exists = False break if not all_exists and os.path.exists(tpath): print('add', torrent_info.name) L.append( (tpath, seed_file, torrent_info.total_size, torrent_info.name)) torrent_info.announce_urls = [] torrent_info.to_file( os.path.join('/Volumes/Store/Downloads/cheat', torrent_info.name + '.torrent')) if len(L) > 0: f = open('/tmp/vuzetext', 'w', encoding='utf-8') for it in L: str = '%s###%s###%d###%s\n' % (it[0], it[1], it[2], it[3]) f.write(str) f.close() os.system('open -ga iTerm %s' % vuzescpt)
def parse_torrent(torrent: bytes) -> dict: """Returns a dictionary with basic information from torrent contents. keys: * hash; * name; * files; * torrent (torrent file contents just from input). :param torrent: """ torrent_info = Torrent.from_string(torrent) files_from_torrent = [a_file[0] for a_file in torrent_info.files] info = { 'hash': str(torrent_info.info_hash), 'name': torrent_info.name, 'files': files_from_torrent, 'torrent': torrent } return info
def to_torrent(self, save_path=None, announce_urls=None): """Create a torrent Args: save_path (str, None): save torrent to this location if omitted its saved to the userdata/torrents foler announce_urls (str, list): list of trackers """ if save_path is None: save_path = os.path.join(self.save_torrent_path, os.path.basename(self.name) + '.torrent') self.torrent_name = os.path.basename(save_path) new_torrent = Torrent.create_from(self.fp) if announce_urls: new_torrent.announce_urls = announce_urls new_torrent.to_file(save_path) return new_torrent, save_path """0-250MB: 256KB (262144 bytes)
def generatingTorrent(): remoteTempTorrent() if not (os.path.isfile(os.getcwd() + "/blackhole/torrents/" + request.args.get("id") + ".torrent")): return "torrent unavailable" # grab torrent file matching id provided my_torrent = Torrent.from_file(os.getcwd() + "/blackhole/torrents/" + request.args.get("id") + ".torrent") # changing passkey for one transmitted as parameter by user newUrlTracker = re.sub("[a-zA-Z0-9]{32}", request.args.get("passkey"), ((my_torrent.announce_urls[0])[0])) my_torrent.announce_urls = newUrlTracker # write it in temp dir for more clarity my_torrent.to_file(os.getcwd() + "/blackhole/torrents/tmp/" + request.args.get("id") + request.args.get("passkey") + ".torrent") # send torrent file return send_file(os.getcwd() + "/blackhole/torrents/tmp/" + request.args.get("id") + request.args.get("passkey") + ".torrent", as_attachment=True, attachment_filename=(my_torrent.name + ".torrent"), mimetype='application/x-bittorrent')
def test_getters_dir(): t = Torrent.from_file(FPATH_TORRENT_WITH_DIR) assert t._filepath == FPATH_TORRENT_WITH_DIR assert t.created_by == 'Transmission/2.84 (14307)' assert t.files == [ (normpath('torrtest/root.txt'), 4), (normpath('torrtest/sub1/sub11.txt'), 4), (normpath(u'torrtest/sub1/sub2/кириллица.txt'), 11), (normpath('torrtest/sub1/sub2/sub22.txt'), 4) ] assert t.total_size == 23 assert t.announce_urls == [['http://track1.org/1/', 'http://track2.org/2/']] assert t.creation_date.isoformat() == '2015-10-25T09:42:04' assert t.comment == u'примечание' hash_expected = 'c815be93f20bf8b12fed14bee35c14b19b1d1984' assert t.info_hash == hash_expected magnet = t.magnet_link assert hash_expected in magnet assert 'btih' in magnet assert 'magnet:' in magnet
def test_from_string(): torrstr = '4:spam' t = Torrent.from_string(torrstr) assert t._struct == 'spam'
def test_setters(): t = Torrent() assert t.info_hash is None assert t.comment is None assert t.created_by is None assert t.creation_date is None assert t.total_size == 0 assert t.announce_urls == [] assert t.files == [] t.name = 'mytorrent' assert t.name == 'mytorrent' t.comment = 'mycomment' assert t.comment == 'mycomment' t.created_by = 'some/1.0' assert t.created_by == 'some/1.0' now = datetime.now() t.creation_date = now assert t.creation_date == now.replace(microsecond=0) t.announce_urls = 'some1' assert t.announce_urls == [['some1']] assert t._struct['announce'] == 'some1' assert 'announce-list' not in t._struct t.announce_urls = ['some3', 'some4'] assert t.announce_urls == [['some3'], ['some4']] assert t._struct['announce'] == 'some3' t.announce_urls = ['some5'] assert t.announce_urls == [['some5']] assert t._struct['announce'] == 'some5' assert 'announce-list' not in t._struct assert not t.private t.private = False assert not t.private t.private = True assert t.private t.private = False assert not t.private
def get_hash_file(path): tr = Torrent.from_file(path) mgt = tr.magnet_link return get_hash_magnet(mgt)
def get_torrents_in_dir(path): torrent_files = (fn for fn in os.listdir(path) if fn.endswith('.torrent')) return (Torrent.from_file(name) for name in torrent_files)
activePath = activeDownload.replace(dataSource, dataReturn) try: ##Debug #print(activePath) #input() ## os.makedirs(activePath) except: print("Folder Exists, Skipping...") activeFile = os.path.normpath(activeFile) activeTorrent = os.path.normpath(activeTorrent) ##Debug #print(activeFile) #input() ## GlassTorrent = Torrent.create_from(activeFile) GlassTorrent.announce_urls = urls GlassTorrent.comment = "Torrent created by the GlassLibrary" ##Debug #print(activeTorrent) #input() ## GlassTorrent.to_file(activeTorrent) print(f"Made {activeTorrent}") newTorrents += 1 try: launchSeed(activeTorrent) except: try: launchSeed(activeTorrent) except:
def getMagnetLink(filePath): try: torrent = Torrent.from_file(filePath) return torrent.magnet_link except FileNotFoundError: return None
except request.HTTPError as e: print("Error "+str(e.code)) print("Resource not available. Quitting...") quit() #latest Desktop Live iso URL webseed_desktop_live = "https://cdn.download.clearlinux.org/releases/"+latest_version+"/clear/clear-"+latest_version+"-live-desktop.iso" iso_desktop_live = "/tmp/clear-linux_"+latest_version+"_live-desktop.iso" #Check if iso is available try: print("Downloading latest iso (Version : " + latest_version + ") from mirror (" + humanize.naturalsize(request.urlopen(webseed_desktop_live).getheader("Content-Length")) + "). Please wait...") #TODO : Check if file exists and overwrite #retrieve iso from clear linux website request.urlretrieve(webseed_desktop_live,iso_desktop_live) except request.HTTPError as e: print("Error "+str(e.code)) print("Resource not available. Quitting...") quit() live_desktop_torrent = Torrent.create_from(iso_desktop_live) live_desktop_torrent.announce_urls = 'udp://tracker.openbittorrent.com:80' live_desktop_torrent.webseeds = webseed_desktop_live live_desktop_torrent.comment = "Torrent automatically created on " + datetime.now().strftime("%m/%d/%Y, %H:%M:%S") live_desktop_torrent.to_file('clear-linux-live-desktop-'+latest_version+'.torrent')
def generate_torrent_file(dir_sample, file_torrent): # d_samples is the directory containing samples # f_name is the specified name for the new torrent file print("\n[i] Generating torrent file.") new_torrent = Torrent.create_from(dir_sample) new_torrent.to_file(file_torrent)