def clear(update: Update, context: CallbackContext) -> None: """ Limpia los torrents finalizados de la cola de descarga """ FINISHED_STATES = [ 'uploading', 'pausedUP', 'stalledUP', 'queuedUP', ] if int(update.effective_chat.id) not in config.ALLOWED_IDS: not_allowed(update) else: logger.info(' Un usuario CON permiso ha ejecutado /clear') qb = Client(config.TORRENT['server']) qb.login(config.TORRENT['user'], config.TORRENT['pass']) torrents = qb.torrents() del_torrents = len(torrents) for torrent in torrents: if torrent['state'] in FINISHED_STATES: qb.delete(torrent['hash']) torrents = qb.torrents() del_torrents = del_torrents - len(torrents) qb.logout() logger.info('{} torrents han sido eliminados de la cola'.format(del_torrents)) if del_torrents != 0: update.message.reply_text('Borrados todos los torrents finalizados') else: update.message.reply_text('No se ha eliminado ningún torrent de la cola')
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(): qb = Client(URL) qb.login(user, password) torrents = qb.torrents() active_torrents = db.get_active_torrents() torr = [] for i in range(len(torrents)): for a in active_torrents: if a[1] == torrents[i]['name']: info = { 'name': torrents[i]["name"], 'hash': torrents[i]["hash"], 'seeds': torrents[i]["num_seeds"], 'progress': torrents[i]['progress'], 'size': get_size_format(torrents[i]["total_size"]), 'speed': get_size_format(torrents[i]["dlspeed"]) + '/s' } torr.append(info) if torrents[i]['progress'] == 1: db.finished_downloading_title(torrents[i]['name']) ad.fix_files(torrents[i]['name']) # if no active torrents / stop seeding if len(torr) == 0: pause_all() return 'no torrents' return torr
def pQbClient(): from qbittorrent import Client info = getQbConf() url = 'http://' + info['QB_HOST'] + ':' + info['QB_PORT'] + '/' qb = Client(url) qb.login(info['QB_USER'], info['QB_PWD']) return qb
def __init__(self, ip, username, password): self.ip = ip self.username = username self.password = password self.qb = Client(ip) self.qb.login(self.username, self.password)
def add_client(clientIP, username, password): try: qb = Client(clientIP + "/") qb.login(username, password) return qb except: pass
def ip(self, bot, update): self.ip_port_text = update.message.text user = update.message.from_user if re.match('^(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}|localhost):\d{1,5}$', self.ip_port_text): self.logger.info("User %s entered a right IP and PORT" % user.id) self.logger.info("Trying to connect to client") try: self.qb = Client("http://%s/" % self.ip_port_text) try: self.qb.torrents() self.logger.info("Logging in was successful.") update.message.reply_text("Logged in! Now you can use me.\n" "To get info about commands type /help") self.logged_in = True except client.LoginRequired: self.logger.info("Login required.") update.message.reply_text("Username and password is required to connect client.\n" "Please enter an username and password by seperating them with space.\n" "If you don't know username and password you can" " '/cancel'. and try again later") return self.LOGIN_PROMPT except exceptions.ConnectionError: self.logger.info("Connection refused.") update.message.reply_text("Connection to given IP address is refused." "\nPlease try again by typing /start") self.ip_port_text = None else: self.logger.info("User %s entered a wrong IP and PORT" % user.id) update.message.reply_text("Please enter a proper ip and port. You can restart by typing /start") return ConversationHandler.END
def __init__(self, login, config): self.config = config self.login = login self.localhost = self.config["host"] self.download_path = os.path.expanduser("~") + config["download_path"] self.qb = Client(self.localhost) self.qb.login(self.config["username"], self.config["passwd"])
def gettorrents(): torrentlist = [] qb = Client('http://127.0.0.1:8081/') temp = qb.torrents() for dictn in temp: torrentlist.append({ 'name' : "Torrent Name: " + dictn['name'], 'progress' : "Progress: " + "{:.1%}".format(dictn['progress']), 'state' : "State: " + dictn['state'], 'hash' : dictn['hash'], 'eta' : "ETC: " + str(dictn['eta']//60) + " minutes"}) return torrentlist
def set_torrent_client(): ip = socket.gethostbyname(socket.gethostname()) qb = Client('http://'+ip+':8080/') qb.login() return qb
class Bittorrent: def __init__(self): self.bittorrent = Client('http://localhost:8080/') self.bittorrent.login('pavo', 'buffalo12') def download(self, movie): filename = str(movie.metadata.title) + ' (' + str(movie.metadata.year) + ')' self.bittorrent.download_from_link(movie.metadata.magnet_link, savepath=filename)
def __init__(self, client): self.client = client qb = Client(os.getenv('QBT_URL')) qb.login('admin', os.getenv('QBT_KEY')) self.qb = qb
def connectToClient(qb_client, qb_login, qb_password): # connect to the qbittorent Web UI qb = Client(qb_client) # put the credentials (as you configured) qb.login(qb_login, qb_password) return qb
def login(self): self.myPlex = myplex.MyPlexAccount( username=self.config.get("Plex", "username"), password=self.config.get("Plex", "password")) self.client = Client(self.config.get("qBittorrent", "host")) self.client.login(self.config.get("qBittorrent", "username"), self.config.get("qBittorrent", "password"))
def check_qb(): if process_check("qbittorrent.exe"): qb = Client('http://127.0.0.1:8080/') while len(qb.torrents()) > 0: print("Downloading...") time.sleep(5) else: return True else: return False
def __init__(self): super().__init__() self.host = input("输入客户端地址(http://IP:端口):") self.user = input("输入客户端用户名:") self.password = input("输入客户端密码:") qb = QbittorrentClient(self.host) print("开始连接 Qbittorrent 客户端...") qb.login(self.user, self.password) self.qb = qb
def __enter__(self): try: self.connection = Client(config.qbt_host) self.connection.login(config.qbt_user, config.qbt_pass) return self.connection except ConnectionError: log("Error connecting to qBittorrent Web UI", important=True, context="QB") raise ConnectionError
def __init__(self,config): self.config = config username = self.config.get('global','webui_username') password = self.config.get('global','webui_password') webui_url = self.config.get('global','webui_url') self.torrentHash = [] self.torrentData = [] self.client = Client(webui_url) self.client.login(username, password) self.getTorrentInfo() self.getTorrentSeedTime()
def __init__(self, url='http://127.0.0.1:8080/', user='', passwd=''): self.name = self.__class__.__name__ # Default Parameters for QClient Session self.defautl_url = url self.user = user self.passwd = passwd # Launching Session in QClient self.session = Client(self.defautl_url) if self.user != '' and self.passwd != '': self.session.login(self.user, self.passwd)
def __init__(self, url: str, username: str, password: str, download_dir: str): """ :param url: :param username: :param password: :param download_dir: """ self.client = Client(url) self.client.login(username, password) self.download_dir = download_dir
def torrent_message(message): log.append("Получен торрент файл") if message.document.file_name.find(".torrent") < 0: mes = "Прислан не тот документ" bot.send_message(message.chat.id, mes) return mes = 'Привет, ты прислал мне документ:' + message.document.file_name bot.send_message(message.chat.id, mes) file_id = message.document.file_id newFile = bot.get_file(file_id) filepath = os.path.exists(config.DOWNLOADPATH) if not filepath: os.mkdir(config.DOWNLOADPATH) downloaded_file = bot.download_file(newFile.file_path) # src = message.document.file_name # with open(config.DOWNLOADPATH + "/" + src, 'wb') as new_file: # new_file.write(downloaded_file) # mes = "Файл сохранен в " + config.DOWNLOADPATH # bot.send_message(message.chat.id, mes) # проверим запущен ли bittorrent startqtrnt() qb = Client('http://localhost:8080/') qb.login('admin', '1karina1') downTorrents = qb.torrents(filter='downloading') qb.download_from_file(downloaded_file) time.sleep(2) downAddedTorrents = qb.torrents(filter='downloading') findtorr = {} cont = False # поиск добавленного файла for addtorr in downAddedTorrents: for notaddtorr in downTorrents: if addtorr['name'] == notaddtorr['name']: #downAddedTorrents.remove(addtorr) #downTorrents.remove(notaddtorr) cont = True break if cont: cont = False continue findtorr = addtorr break if findtorr: downloadTorrents.append({ 'userid': message.chat.id, 'name': findtorr['name'] }) qb.logout()
def main() -> None: load_config() if CONFIG["torrent"]["enabled"]: global QBCLIENT QBCLIENT = QBClient(CONFIG["torrent"]["webUrl"]) QBCLIENT.login(CONFIG["torrent"]["login"], CONFIG["torrent"]["password"]) print("Running...") CLIENT.run(CONFIG["discord"]["token"])
def relogin(): try: with open(USER_INFO_PATH, "rb") as usr_file: usrs_info = pickle.load(usr_file) ip = usrs_info['ip'] port = usrs_info['port'] name = usrs_info['name'] pwd = usrs_info['pwd'] qb = Client('http://{ip}:{port}/'.format(ip=ip, port=port)) qb.login(name, pwd) return qb except Exception as exc: print('重新认证出错: %s' % exc)
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
def torrent_view(request): qb = Client('http://127.0.0.1:8080/') qb.login('admin', 'adminadmin') BASE_DIR = Path(__file__).resolve().parent.parent d_path = os.path.join(BASE_DIR, 'static/folder/') print("Location : ", qb.get_default_save_path()) if request.method == 'POST': ezflix = Ezflix(query=request.POST['title1'], media_type='movie', quality='720p', limit=1) shows = ezflix.search() # magnet = 'https://webtorrent.io/torrents/big-buck-bunny.torrent' magnet = 'https://webtorrent.io/torrents/cosmos-laundromat.torrent' if shows is not None: for s in shows: if s['imdb'] == request.POST['imdb1']: print(s['link']) # torrent_location=Torrent.objects.filter(Info_code=s['title'])[0] # print ("Finally",torrent_location.title) # print(torrent_location) qb.download_from_link(magnet, savepath=d_path) time.sleep(90) torrents = qb.torrents(filter='downloading') # for k in info_hash # k.Info code # print("This is the info") path_torrent = Torrent_details(torrents, qb, s['title']) print( '--------------------------------------------------------------------------------------' ) else: print("Not found") return HttpResponse(path_torrent)
class QBitTorrentWrapper(object): def __init__(self, ip, username, password): self.ip = ip self.username = username self.password = password self.qb = Client(ip) self.qb.login(self.username, self.password) def addTorrentsFromFolder(self, dl_location_path): self.dl_location_path = dl_location_path for filename in filter(os.path.isfile, os.listdir(os.curdir)): if filename.endswith(".torrent"): torrent_file = open('%s' % filename, 'rb') self.qb.download_from_file(torrent_file, savepath=dl_location_path) def startDownloading(self): self.qb.resume_all() def stopDownloading(self): self.qb.pause_all() def timeInterval(self): schedule.every().day.at("00:00").do(self.startDownloading) schedule.every().day.at("06:00").do(self.stopDownloading) while True: schedule.run_pending()
def add_torrent(file_path: str) -> None: """ Function to add torrent file to qbittorrent app. :param file_path: Path to the downloaded torrent file. :return: None """ # connect to the qbittorent Web UI try: qb = Client('https://127.0.0.1:8080/') torrent_file = open(file_path, 'rb') qb.download_from_file(torrent_file) print("Torrent added. Starting download.") except requests.exceptions.ConnectionError: print("qBittorrent app is not open.")
def establishRPC(self, client, magnet_link=None, type="magnet"): print "• Establishing connection to", client try: if client == "transmission": tc = transmissionrpc.Client(self.transmission_url.split(":")[0], port=self.transmission_url.split(":")[1], user=self.transmission_user, password=self.transmission_password) if type == "magnet": print "• Adding magnet to", client tc.add_torrent(magnet_link) else: print "• Adding torrent to", client tc.add_torrent('file://' + os.path.abspath('torrent.torrent')) elif client == "qbittorrent": qb = Client(self.qbittorrent_url) qb.login(self.qbittorrent_user, self.qbittorrent_password) if qb._is_authenticated is True: if type == "magnet": print "• Adding magnet to", client qb.download_from_link(magnet_link) else: print "• Adding torrent to", client qb.download_from_file(file('torrent.torrent')) except: traceback.print_exc() raise IOError
def connect_test(url, id, pw): try: ret = {} qb = Client(url) qb.login(id, pw) torrents = qb.torrents() ret['ret'] = 'success' ret['current'] = len(torrents) except Exception as e: logger.error('Exception:%s', e) logger.error(traceback.format_exc()) ret['ret'] = 'fail' ret['log'] = str(e) finally: return ret
def get_qbittorrent_client() -> Client: _url: str = _get_qbittorrent_url() try: client = Client(_url, verify=False) except requests.exceptions.ConnectionError: raise Exception("Qbittorrent is not running.") _login: Optional[str] = client.login( get_setting_or_environment("QBITTORRENT_USERNAME"), get_setting_or_environment("QBITTORRENT_PASSWORD"), ) if _login is None: return client raise Exception("Could not login to qbittorrent.")
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)
from qbittorrent import Client qb = Client('http://127.0.0.1:8080/') qb.login() torrents = qb.torrents() for torrent in torrents: print torrent['name']