class QBittorrentClient(TorrentClient): def __init__(self, endpoint, username, password): self._api_client = Client(endpoint) self._api_client.login(username, password) if not self._api_client: message = "Unable to connect to qBittorrent API. Please check your -e, -u and -p arguments." logger.error(message) raise Exception(message) def get_torrent_info(self, torrent_hash): torrents = self._api_client.torrents() for torrent in torrents: if torrent['hash'] == torrent_hash: return Torrent(torrent_hash, torrent['progress'] == 1, torrent['category'], torrent['save_path']) return None def remove_torrent(self, torrent_hash): self._api_client.delete_permanently(torrent_hash) def stop_torrent(self, torrent_hash): self._api_client.pause(torrent_hash) def get_torrent_files(self, torrent_hash): files = self._api_client.get_torrent_files(torrent_hash) parsed_files = [] for file in files: if ".unwanted" not in file['name']: parsed_files.append(TorrentFile(file['name'])) return parsed_files
txt = "torrentName.torrent" #à modifier torrent_file = open(txt, "rb") qb.download_from_file(torrent_file) x = txt.split(".torrent") torrents = qb.torrents() for torrent in torrents: if (torrent["name"] == x[0]): torrent_hash = torrent["hash"] x.clear() r = qb.get_torrent_files(torrent_hash) nb_file = 0 print(type(r)) for i in r: x.append(i["name"]) nb_file += 1 x.sort() r.clear() qb.resume(torrent_hash) j = 0 while (j < nb_file): r = qb.get_torrent_files(torrent_hash)
def main_proc(): print('\n#################### [ Begin - Running at ' + time.ctime() + ' ] ##########') # load config with codecs.open('config.json', 'r', encoding='utf8') as f: cfg = json.loads(f.read()) torrentcfg = cfg['torrent'] policycfg = cfg['downloadpolicy'] dbcfg = cfg['db'] crawlcfg = cfg['crawl'] # init db db = DownloadDb(dbcfg) # get qbittorrent connection q = Client(torrentcfg['addr']) errmsg = q.login(torrentcfg['user'], torrentcfg['pwd']) if errmsg: print('Torrent server ' + errmsg, file=sys.stderr) # crawl t = TorrentKim3Net( crawlinfo = crawlcfg['torrentkim3.net'], downloadpolicy = policycfg ) l = [] for i in range(1, 3+1): l += t.getlist_tvdrama(page=i) l += t.getlist_variety(page=i) l += t.getlist_docu(page=i) print('\n########## Crawl torrentkim3.net') for each in l: subj = each['subject'] matched = t.filtersubject(subj) if not matched: try: print('not matched : {}'.format(subj)) except UnicodeEncodeError: print('not matched : {}'.format(subj.encode('cp949', 'replace'))) continue magnet = t.getmagnetfrom(each['href']) if not magnet: print('failed to get magnet : ' + subj) continue if db.isadded(magnet): print('already added : ' + subj) else: q.download_from_link(magnet) print('added : '+ subj) db.added(magnet) db.sync() time.sleep(1) # check qbittorrent status print('\n########## QBittorrent Status') for each in q.torrents(): progress = each['progress'] percent = str(100 * progress) + ' %' name = each['name'] magnet = 'magnet:?xt=urn:btih:' + each['hash'].lower() tr_files = map(lambda x: x['name'], q.get_torrent_files(each['hash'])) print('+ ', percent + ' | ' + name + ' | ' + magnet) for each_file in tr_files: try: print('+-- ' + each_file) except UnicodeEncodeError: print('+-- {}'.format(each_file.encode('cp949', 'replace'))) if progress == 1 and not db.isdownloaded(magnet): db.downloaded(magnet) db.sync() print('\n#################### [ End - Running at ' + time.ctime() + ' ] ##########') time.sleep (300)
class TorrentClient(object): def __init__(self): self.conn = None def connect(self, host, username, password, test=False): if self.conn is not None: return self.connect if not host: return {'status': False, 'error': 'host not specified'} try: self.client = Client(host) except Exception as e: logger.error('Could not create qBittorrent Object %s' % e) return {'status': False, 'error': e} else: try: self.client.login(username, password) except Exception as e: logger.error('Could not connect to qBittorrent: %s' % host) return {'status': False, 'error': e} else: if test is True: version = self.client.qbittorrent_version return {'status': True, 'version': version} else: return self.client def find_torrent(self, hash): logger.debug('Finding Torrent hash: %s' % hash) torrent_info = self.get_torrent(hash) if torrent_info: return True else: return False def get_torrent(self, hash): logger.debug('Getting Torrent info hash: %s' % hash) try: torrent_info = self.client.get_torrent(hash) except Exception as e: logger.error('Could not get torrent info for %s' % hash) return False else: logger.info('Successfully located information for torrent') return torrent_info def load_torrent(self, filepath): if not filepath.startswith('magnet'): logger.info('filepath to torrent file set to : %s' % filepath) if self.client._is_authenticated is True: logger.info('Checking if Torrent Exists!') if filepath.startswith('magnet'): torrent_hash = re.findall("urn:btih:([\w]{32,40})", filepath)[0] if len(torrent_hash) == 32: torrent_hash = b16encode(b32decode(torrent_hash)).lower() hash = torrent_hash.upper() logger.debug('Magnet (load_torrent) initiating') else: hash = self.get_the_hash(filepath) logger.debug('FileName (load_torrent): %s' % os.path.basename(filepath)) logger.debug('Torrent Hash (load_torrent): "%s"' % hash) #Check if torrent already added if self.find_torrent(hash): logger.info('load_torrent: Torrent already exists!') return {'status': False, 'error': 'Torrent already exists'} #should set something here to denote that it's already loaded, and then the failed download checker not run so it doesn't download #multiple copies of the same issues that's already downloaded else: logger.info('Torrent not added yet, trying to add it now!') # Build an arg dict based on user prefs. addargs = {} if not any([mylar.CONFIG.QBITTORRENT_LABEL is None, mylar.CONFIG.QBITTORRENT_LABEL == '', mylar.CONFIG.QBITTORRENT_LABEL == 'None']): addargs.update( { 'category': str(mylar.CONFIG.QBITTORRENT_LABEL) } ) logger.info('Setting download label to: %s' % mylar.CONFIG.QBITTORRENT_LABEL) if not any([mylar.CONFIG.QBITTORRENT_FOLDER is None, mylar.CONFIG.QBITTORRENT_FOLDER == '', mylar.CONFIG.QBITTORRENT_FOLDER == 'None']): addargs.update( { 'savepath': str(mylar.CONFIG.QBITTORRENT_FOLDER) } ) logger.info('Forcing download location to: %s' % mylar.CONFIG.QBITTORRENT_FOLDER) if mylar.CONFIG.QBITTORRENT_LOADACTION == 'pause': addargs.update( { 'paused': 'true' } ) logger.info('Attempting to add torrent in paused state') if filepath.startswith('magnet'): try: tid = self.client.download_from_link(filepath, **addargs) except Exception as e: logger.error('Torrent not added') return {'status': False, 'error': e} else: logger.debug('Successfully submitted for add as a magnet. Verifying item is now on client.') else: try: torrent_content = open(filepath, 'rb') tid = self.client.download_from_file(torrent_content, **addargs) except Exception as e: logger.error('Torrent not added') return {'status': False, 'error': e} else: logger.debug('Successfully submitted for add via file. Verifying item is now on client.') if mylar.CONFIG.QBITTORRENT_LOADACTION == 'force_start': logger.info('Attempting to force start torrent') try: startit = self.client.force_start(hash) logger.info('startit returned: %s' % startit) except: logger.warn('Unable to force start torrent - please check your client.') else: logger.info('Client default add action selected. Doing nothing.') try: time.sleep(5) # wait 5 in case it's not populated yet. tinfo = self.get_torrent(hash) except Exception as e: logger.warn('Torrent was not added! Please check logs') return {'status': False, 'error': e} else: logger.info('Torrent successfully added!') filelist = self.client.get_torrent_files(hash) #logger.info(filelist) if len(filelist) == 1: to_name = filelist[0]['name'] else: to_name = tinfo['save_path'] torrent_info = {'hash': hash, 'files': filelist, 'name': to_name, 'total_filesize': tinfo['total_size'], 'folder': tinfo['save_path'], 'time_started': tinfo['addition_date'], 'label': mylar.CONFIG.QBITTORRENT_LABEL, 'status': True} #logger.info(torrent_info) return torrent_info def get_the_hash(self, filepath): import hashlib import bencode # Open torrent file torrent_file = open(filepath, "rb") metainfo = bencode.decode(torrent_file.read()) info = metainfo['info'] thehash = hashlib.sha1(bencode.encode(info)).hexdigest().upper() return thehash
qb = Client('http://127.0.0.1:8080/') qb.login('admin', 'kankerlelijk') torrents = qb.torrents() # print(json.dumps(torrents[0], sort_keys=True, indent=4 * ' ')) torfiles = dict() regex = str(sys.argv[1]) for torrent in torrents: name = torrent['name'] files = qb.get_torrent_files(torrent['hash']) filenames = list() for file in files: n = file['name'] if n.endswith('.mp4') or n.endswith('.mkv'): filenames.append(file['name']) torfiles[name] = filenames # print(torfiles) # print(torrent['hash']) # print(json.dumps(torfiles, sort_keys=True, indent=4 * ' ')) for key in torfiles.keys(): flist = torfiles[key]
except ImportError: log.exception( "Python module PYTHON-QBITTORRENT is required. Install with 'pip install python-qbittorrent' then try again." ) sys.exit() qb = Client(settings.qBittorrent['host']) qb.login(settings.qBittorrent['username'], settings.qBittorrent['password']) log.info("Pausing all torrents") qb.pause_all() torrent_name = qb._get('query/torrents', params={'hashes': torrent_hash})[0]['name'] torrent_save_path = qb.get_torrent(torrent_hash)['save_path'] torrent_files = [f['name'] for f in qb.get_torrent_files(torrent_hash)] if not torrent_name: raise Exception("Torrent name could not be fetched") copy_to = "/downloads/{}".format(torrent_name) if os.path.exists(copy_to): log.info("Removing existing copy_to of {}".format(copy_to)) rmtree(copy_to, ignore_errors=True) log.info("Creating copy_to of {}".format(copy_to)) os.makedirs(copy_to) for torrent_file in torrent_files: source_path = "{}/{}".format(torrent_save_path, torrent_file) target_path = "{}/{}".format(copy_to, basename(torrent_file))