def change_tracker(torrent_path): back_path = torrent_path + '.torrent' os.rename(torrent_path, back_path) data = bencode.bread(back_path) data["announce"] = data["announce"].replace('http', 'https') bencode.bwrite(data, torrent_path) os.remove(back_path)
def test_write_path(): """Test the writing of bencode files.""" bwrite( {'foo': 42, 'bar': {'sketch': 'parrot', 'foobar': 23}}, os.path.join(TEMP_DIR, 'beta') ) with open(os.path.join(TEMP_DIR, 'beta'), 'r') as fp: assert fp.read() == 'd3:bard6:foobari23e6:sketch6:parrote3:fooi42ee'
def test_write_pathlib(): """Test the reading of bencode paths.""" from pathlib import Path bwrite( {'foo': 42, 'bar': {'sketch': 'parrot', 'foobar': 23}}, Path(TEMP_DIR, 'beta') ) with open(os.path.join(TEMP_DIR, 'beta'), 'r') as fp: assert fp.read() == 'd3:bard6:foobari23e6:sketch6:parrote3:fooi42ee'
def bencode_ops(tor_dir, base_paths_to_be_replaced1, substituted_base_paths1, dry_run): bencode_ops.unmodified = [] displayed_lines = 0 for file in listdir(tor_dir): if file.endswith(".fastresume"): modified = False # Set variable for each file name file_path_name = path.join(tor_dir, file) # Set variable for the contents of each fastresume file torrent = bread(file_path_name) # Set the variable for the original "save_path" value save_path_orig = (torrent['save_path']) for s, d in zip(base_paths_to_be_replaced1, substituted_base_paths1): if modified is False: if s in save_path_orig: modified = True # Replace the specified portion of the original path "s" with the desired replacement "d". save_path1 = save_path_orig.replace(s, d) # Replace rest of the backslashes with forward slashes save_path2 = sub("\\\\", "/", save_path1) # Replace value of dictionary item "save_path" with the linux equivalent if dry_run is False: torrent['save_path'] = save_path2 # Replace value of dictionary item "qBt-savePath" with the linux equivalent if dry_run is False: torrent['qBt-savePath'] = save_path2 # Print the new torrent path print(save_path_orig+" ----converts to---- "+save_path2) displayed_lines = displayed_lines + 1 if displayed_lines >= line_height: input("Press Enter to Continue...") displayed_lines = 0 if 'mapped_files' in torrent: mf_orig1 = (torrent['mapped_files']) mf_orig2 = str(mf_orig1) mf_fixed = sub("\\\\\\\\", "/", mf_orig2) if dry_run is False: torrent['mapped_files'] = mf_fixed print(file+" contains \'mapped_files\'") displayed_lines = displayed_lines + 1 if displayed_lines >= line_height: input("Press Enter to Continue...") displayed_lines = 0 print(mf_orig2+"\r\n----converts to----\r\n"+mf_fixed) displayed_lines = displayed_lines + 3 if displayed_lines >= line_height: input("Press Enter to Continue...") displayed_lines = 0 # Write the modified dictionary back to the fastresume file if dry_run is False: bwrite(torrent, file_path_name) if modified is False: bencode_ops.unmodified.append("NO CHANGE:"+file+" did not match any specified path. " + save_path_orig)
def mailcheck(self): #Gets searches for valid emails, there are two, the json and binary file key = autodownload.getkey() queryT = '''filename:txt subject:DON'T newer_than:2d "This message is used for autodownload" +%s''' % (key) queryJ = '''filename:json subject:DON'T newer_than:2d "This message is used for autodownload" +%s''' % (key) msg_idT = self.searchmail(queryT) msg_idJ = self.searchmail(queryJ) if(msg_idT==[] or msg_idJ==[]): return 1 #Saves the attachments to the computer locT = self.downloadtorrent(msg_idT[0]['id'], binary=True) locJ = self.downloadtorrent(msg_idJ[0]['id']) #Opens the json as an ordered dict and inserts the safely encoded binary data into the correct # pair so that it can then be saved as a torrent js = json.load(open(locJ, 'r'), object_pairs_hook=OrderedDict) with open(locT, 'rb') as f: bb = f.read() bb = base64.urlsafe_b64decode(bb) #Needs to be decoded twice so because the binary data is encoded for safe transmission and # then the entire message is encoded again bb = base64.urlsafe_b64decode(bb) js['info']['pieces'] = bb name = locT.split('/') name = name[-1] name = name.split('.') name = name[0] path = '/Users/%s/Downloads/%s.torrent' % (getpass.getuser(), name) #Writes the new torrent file bencode.bwrite(js, path) #Opens the torrent file with a client to begin download process = subprocess.Popen(['open', path]) #Deletes gmail messages that the json and binary data are from self.deletemsg(msg_idT[0]['id']) self.deletemsg(msg_idJ[0]['id']) #Removes files from computer that were used for rebuilding torrent os.remove(locT) os.remove(locJ) #Sends a confimation email message = self.msgnormal(self.email, 'Download Confirmation: autodownload', self.normaltext()) self.sendmsg(message) return 'Download Started'
def download_torrent(args, BHD_link, path): print("Downloading Torrent to client") wget = args.wget client = args.client if client not in ["rtorrent", "qbit", "deluge", "transmission"]: name = "".join([args.title, ".torrent"]) torrentpath = os.path.join(client, name) bhdlogger.info(torrentpath) try: t = subprocess.run([wget, BHD_link, '-O', torrentpath], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) bhdlogger.debug( f"Downloading Final Torrent -No Fast Resume Data added :{t.stdout}" ) except: bhdlogger.warn( "error downloading torrent please get directly from BHD") if client == "rtorrent": temptor = os.path.join(tempfile.gettempdir(), os.urandom(24).hex() + ".torrent") t = subprocess.run([wget, BHD_link, '-O', temptor], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) #important line remove private infromation from download link t = f"Downloading Temp Torrent:{t.stdout.decode('utf8', 'strict')}" bhdlogger.debug(t) metainfo = bencode.bread(temptor) resumedata = add_fast_resume(metainfo, path) bhdlogger.info( f"resume date added?: {bencode.encode(resumedata)!=metainfo}") if bencode.encode(resumedata) != metainfo: bencode.bwrite(resumedata, temptor) clienturl = re.sub("unix", "scgi", args.clienturl) server = SCGIServerProxy(clienturl) if args.clientcat != None: server.load.start_verbose("", temptor, f"d.directory_base.set={args.media}", f"d.custom1.set={args.clientcat}") else: server.load.start_verbose("", temptor, f"d.directory_base.set={args.media}")
def rtorrent(self, path, torrent_path, torrent, meta, local_path, remote_path, client): rtorrent = xmlrpc.client.Server(client['rtorrent_url'], context=ssl._create_stdlib_context()) metainfo = bencode.bread(torrent_path) try: fast_resume = self.add_fast_resume(metainfo, path, torrent) except EnvironmentError as exc: cprint("Error making fast-resume data (%s)" % (exc,), 'grey', 'on_red') raise new_meta = bencode.bencode(fast_resume) if new_meta != metainfo: fr_file = torrent_path.replace('.torrent', '-resume.torrent') print("Creating fast resume") bencode.bwrite(fast_resume, fr_file) isdir = os.path.isdir(path) # if meta['type'] == "DISC": # path = os.path.dirname(path) #Remote path mount modified_fr = False if local_path in path and local_path != remote_path: path_dir = os.path.dirname(path) path = path.replace(local_path, remote_path) path = path.replace(os.sep, '/') shutil.copy(fr_file, f"{path_dir}/fr.torrent") fr_file = f"{os.path.dirname(path)}/fr.torrent" modified_fr = True if isdir == False: path = os.path.dirname(path) cprint("Adding and starting torrent", 'grey', 'on_yellow') rtorrent.load.start_verbose('', fr_file, f"d.directory_base.set={path}") # Delete modified fr_file location if modified_fr: os.remove(f"{path_dir}/fr.torrent") if meta['debug']: cprint(f"Path: {path}", 'cyan') return
def write_torrent(data, path): # type: (dict, PathType) -> None bencode.bwrite(data, path)
# For each file in the directory that has the extension ".fastresume" for file in os.listdir(tor_dir): if file.endswith(".fastresume"): # Set variable for each file name file_path_name = os.path.join(tor_dir, file) # Set variable for the contents of each fastresume file torrent = bencode.bread(file_path_name) # Set the variable for the original "save_path" value save_path_orig = (torrent['save_path']) # Replace {x}:\ with linux_dir_start (ie "c:\" converts to "/data/"). # RegEx notes -- Triple escape backslash. Period = any drive letter. Carrot "^" indicates beginning of string. save_path1 = sub("^.:\\\\", linux_dir_start, save_path_orig) # Replace rest of the backslashes with forward slashes. save_path2 = sub("\\\\", "/", save_path1) # Replace value of dictionary item "save_path" with the linux equivalent. torrent['save_path'] = save_path2 # Replace value of dictionary item "qBt-savePath" with the linux equivalent. torrent['qBt-savePath'] = save_path2 # Print the new torrent path print(save_path_orig + " ----converts to---- " + save_path2) # This section check if the fastresume file has a section called "mapped_files" and replaces the backslashes with forward slashes. if 'mapped_files' in torrent: mf_orig1 = (torrent['mapped_files']) mf_orig2 = str(mf_orig1) mf_fixed = sub("\\\\\\\\", "/", mf_orig2) torrent['mapped_files'] = mf_fixed print(file + " contains \'mapped_files\'") print(mf_orig2 + "\r\n----converts to----\r\n" + mf_fixed) # Write the modified dictionary back to the fastresume file. Comment the following line out for a dry run. bencode.bwrite(torrent, file_path_name)
def save(self, file_name: Optional[str] = None): if file_name is None: file_name = self.file_path self.logger.info(f'Saving File {file_name}...') bencode.bwrite(self._data, file_name)
def save(self, filename): with open(filename, 'wb') as f: bencode.bwrite(self.encode(), f)
def save(self, file_name=None): if file_name is None: file_name = self.file_path self.logger.info('Saving File %s...' % file_name) bencode.bwrite(self._data, file_name)