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 user_login(self): try: ip = self.var_ip.get() port = self.var_port.get() name = self.var_name.get() pwd = self.var_pwd.get() qb = Client('http://{ip}:{port}/'.format(ip=ip, port=port)) qb.login(name, pwd) # 测试是否通过 qb.torrents() self.controller.qb = qb self.controller.login_statu = True with open(USER_INFO_PATH, "wb") as usr_file: # with open with语句可以自动关闭资源 usrs_info = { "ip": ip, 'port': port, 'name': name, 'pwd': pwd } # 以字典的形式保存账户和密码 pickle.dump(usrs_info, usr_file) except Exception as exc: tk.messagebox.showerror('Error', '登录失败:%s' % exc)
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 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
async def get_qb_client(): try: qb = Client(config.qb_web_url) qb.login() except Exception as e: bot = nonebot.get_bot() msg = ( "❌ 无法连接到 qbittorrent ,请检查:\n" "1.是否启动程序\n" "2.是否勾选了“Web用户界面(远程控制)”\n" f"3.连接地址、端口是否正确\nE: {e}" ) logger.error(msg) await bot.send_msg( message_type="private", user_id=str(list(config.superusers)[0]), message=msg ) return None try: qb.get_default_save_path() except Exception as e: bot = nonebot.get_bot() msg = f"❌ 无法连登录到 qbittorrent ,请检查是否勾选 “对本地主机上的客户端跳过身份验证”。\nE: {e}" logger.error(msg) await bot.send_msg( message_type="private", user_id=str(list(config.superusers)[0]), message=msg ) return None 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 __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 main(): qb = Client('http://127.0.0.1:8080') qb.login() pool = eventlet.GreenPool(1) # Get Data rid = 0 while True: log.warning(time.asctime(time.localtime())) try: data = qb.sync(rid) rid = data['rid'] #pp.pprint(data.get('torrents')) check_if_torrent_finish(data.get('torrents'), pool, qb) except KeyboardInterrupt: break except: qb.login() rid = 0 continue time.sleep(5 * 60) pass
def descargar(link): #aqui poner puerto 8080 o el puerto definido en qbit torrent cliente = Client("http://127.0.0.1:4000/") cliente.login("admin", "adminadmin") #en savepath poner donde quiere guardar las peliculas cliente.download_from_link( link, savepath="/home/jaime/compartida/codigo/downloader/descargas/")
def thread_torr(name): log.append("Поток запущен, бот работает") while True: if threadStop: # bot.stop_polling() log.append("Бот остановлен: поток") break try: cont = False qb = Client('http://localhost:8080/') qb.login('admin', '1karina1') torrents = qb.torrents(filter='downloading') for dtor in downloadTorrents: for tor in torrents: if tor['name'] == dtor['name']: cont = True break if cont: cont = False continue bot.send_message(dtor['userid'], "Файл " + dtor['name'] + "загружен") qb.logout() time.sleep(20) except Exception as e: print(e) log.append("Ошбика") time.sleep(3)
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)
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 status(update: Update, context: CallbackContext) -> None: """ Muestra el estado de la cola de descargas """ if int(update.effective_chat.id) not in config.ALLOWED_IDS: not_allowed(update) else: logger.info(' El usuario ha ejecutado /status') qb = Client(config.TORRENT['server']) qb.login(config.TORRENT['user'], config.TORRENT['pass']) torrents = qb.torrents() qb.logout() if len(torrents) == 0: update.message.reply_text('Parece que en este momento no hay nada en cola') else: update.message.reply_text('Hay {} torrents en cola\n'.format(len(torrents))) for torrent in torrents: update.message.reply_text( 'Torrent: {}\nEstado: {}\nTamaño: {}\nProgreso: {}%\nTasa de descarga: {}/s\n'.format( torrent['name'], torrent['state'], get_size_format(torrent['total_size']), str(float(torrent['progress'])*100), get_size_format(torrent['dlspeed']), ) )
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 download_torrent(order): qb = Client(URL) qb.login(user, password) app_data = ad.get_library_path() qb.download_from_link(order['magnet'], savepath=app_data['path']) db.insert_order(order) return 'downloading torrent'
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 watch_movie(torrent_link): try: qb = Client('http://' + qbittorrent_conf['ip'] + ':' + qbittorrent_conf['port'] + '/') qb.login(qbittorrent_conf['username'], qbittorrent_conf['password']) qb.download_from_link(torrent_link) except: print(error_message("You must enable qBittorrent Web UI for this to work."))
def tor_info_message(message): startqtrnt() qb = Client('http://localhost:8080/') qb.login('admin', '1karina1') torrents = qb.torrents() for torrent in torrents: bot.send_message(message.chat.id, torrent['name']) qb.logout()
def __init__(self, client): self.client = client qb = Client(os.getenv('QBT_URL')) qb.login('admin', os.getenv('QBT_KEY')) self.qb = qb
def set_torrent_client(): ip = socket.gethostbyname(socket.gethostname()) qb = Client('http://'+ip+':8080/') qb.login() return qb
def dw_torrent(torrents, magnet_urls, host, login, password): qb = Client(f'http://{host}/') qb.login(login, password) if qb._is_authenticated: qb.download_from_file(torrents) qb.download_from_link(magnet_urls) else: raise NotTorrentClient
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 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 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 download(logger): # logger 설정 # filename = re.sub('.py', '.log', os.path.basename(__file__)) # log_dir = os.path.dirname(os.path.realpath(__file__)) # logger = custom_logger_v2.set_logger(log_dir, filename) con = sqlite3.connect('db/avlist.db') cur = con.cursor() table_name = 'av_list' # 변수선언 with open('conf/data.yml', 'rt', encoding='UTF8') as f: conf = yaml.load(f, Loader=yaml.FullLoader) qburl = conf['qburl'] qbid = conf['qbid'] qbpwd = conf['qbpwd'] # qBittorrent 연결 qb = Client(qburl) qb.login(qbid, qbpwd) # 미 다운로드 목록을 조회 urls = [] try: sql = "select title, url from av_list where qbittorrent_add = 'n' and url <> ''" cur.execute(sql) rows = cur.fetchall() # print(len(rows)) for row in rows: urls.append((row[0], row[1])) except: logger.info("쿼리 실패") total_count = len(urls) count = 0 for u in urls: logger.info("TITLE : " + u[0] + "\t\t" + "URL : " + u[1]) try: qb.download_from_link(u[1]) logger.info(u[0] + "\t" + "다운로드 요청 전송 성공") sql = "update av_list set qbittorrent_add = 'y' where title = '" + u[ 0] + "'" con.execute(sql) count += 1 # print(sql) except Exception as ex: logger.info(u[0] + "\t" + "다운로드 요청 전송 실패") logger.error(ex) logger.info("총 " + total_count.__str__() + "건 중 " + count.__str__() + "건을 신규로 다운로드 요청하였습니다.") con.commit() con.close() return
def download(): # logger 설정 filename = re.sub('.py', '.log', os.path.basename(__file__)) log_dir = os.path.dirname(os.path.realpath(__file__)) logger = custom_logger_v2.set_logger(log_dir, filename) # sqlite3 db 연결 # 로그 저장할 폴더 생성 # current_dir = os.path.dirname(os.path.realpath(__file__)) # db_dir = '{}/db'.format(current_dir) # if not os.path.exists(db_dir): # os.makedirs(db_dir) con = sqlite3.connect('../db/avlist.db') cur = con.cursor() table_name = 'av_list' # 변수선언 with open('../conf/data.yml', 'rt', encoding='UTF8') as f: conf = yaml.load(f, Loader=yaml.FullLoader) qburl = conf['qburl'] qbid = conf['qbid'] qbpwd = conf['qbpwd'] # qBittorrent 연결 qb = Client(qburl) qb.login(qbid, qbpwd) # 미 다운로드 목록을 조회 urls = [] try: sql = "select title, url from av_list where qbittorrent_add = 'n' and url <> ''" cur.execute(sql) rows = cur.fetchall() print(len(rows)) for row in rows: urls.append((row[0], row[1])) except: logger.info("쿼리 실패") for u in urls: logger.info("TITLE : " + u[0] + "\t\t" + "URL : " + u[1]) try: qb.download_from_link(u[1]) logger.info(u[0] + "\t" + "다운로드 요청 전송 성공") sql = "update av_list set qbittorrent_add = 'y' where title = '" + u[ 0] + "'" con.execute(sql) # print(sql) except: logger.info(u[0] + "\t" + "다운로드 요청 전송 실패") con.commit() con.close() return
def search_database(request): found = False for root, dirs, files in os.walk("/media/HDD1/PlexContent/Movies"): for file in files: if temp[0] in file: found = True if found: return render( request, "movies/dbsearch.html", {"temp": temp[0] + " Found on Plex Server, no need to download!!"}) else: options = Options() options.add_argument("--headless") # Runs Chrome in headless mode. options.add_argument('--no-sandbox') # # Bypass OS security model options.add_argument('start-maximized') options.add_argument('disable-infobars') options.add_argument("--disable-extensions") driver = webdriver.Chrome( chrome_options=options, executable_path= r'/home/littlejiver/Downloads/chromedriver_linux64/chromedriver') # driver = webdriver.Chrome(executable_path=r'/home/littlejiver/Downloads/chromedriver_linux64/chromedriver') wait = WebDriverWait(driver, 10) driver.get("https://www.zooqle.com/") wait.until( ec.element_to_be_clickable( (By.XPATH, '//div[@id="anp2-wrapper"]//div[text()="NO THANKS"]' ))).click() wait.until(ec.element_to_be_clickable( (By.XPATH, '//input[@name="q"]'))).send_keys(temp[0]) searchBar = wait.until( ec.element_to_be_clickable( (By.XPATH, '//div[@class="tt-dataset tt-datas' + 'et-qs"]//p[@class="tt-wrap tt-suggestion ' + 'tt-selectable"]//span[text()="' + temp[0] + '"]'))) searchBar.click() wait.until( ec.element_to_be_clickable(( By.XPATH, '//*[@id="body_container"]/div/div[1]/div[2]/div/table/tbody/tr[2]/td[2]/a' ))).click() magnetLink = wait.until( ec.element_to_be_clickable( (By.XPATH, '//*[@id="dlPanel"]/div[2]/ul/li[2]/a'))) torrentLink = magnetLink.get_attribute("href") qb = Client("http://www.on-demandlogistics.com:8080/") qb.login("admin", "adminadmin") qb.download_from_link(torrentLink) task = torrent_downloading_progress.delay(1) return render( request, "movies/dbsearch.html", { "temp": "Downloading " + temp[0].title() + " now!", 'task_id': task.task_id })
def start_download(magnet, name, path): open_qb() try: qb = Client('http://127.0.0.1:8080/') qb.login() qb.download_from_link(magnet, savepath=path) print(name + " started downloading. The files will be saved to " + path + "\n") except Exception as e: print(e)
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