Esempio n. 1
0
async def list_torrent_contents(request):

    torr = request.match_info["hash_id"]
    gets = request.query

    if "pin_code" not in gets.keys():
        rend_page = code_page.replace("{form_url}", f"/app/files/{torr}")
        return web.Response(text=rend_page, content_type='text/html')

    client = qba.Client(host="localhost", port="8090")
    try:
        res = client.torrents_files(torrent_hash=torr)
    except qba.NotFound404Error:
        raise web.HTTPNotFound()
    passw = ""
    for n in str(torr):
        if n.isdigit():
            passw += str(n)
        if len(passw) == 4:
            break
    if isinstance(passw, bool):
        raise web.HTTPNotFound()
    pincode = passw
    if gets["pin_code"] != pincode:
        return web.Response(text="Incorrect pin code")

    par = nodes.make_tree(res)

    cont = ["", 0]
    nodes.create_list(par, cont)
    rend_page = page.replace("{My_content}", cont[0])
    rend_page = rend_page.replace("{form_url}", f"/app/files/{torr}?pin_code={pincode}")
    client.auth_log_out()
    return web.Response(text=rend_page, content_type='text/html')
async def get_client(host=None,port=None,uname=None,passw=None,retry=2) -> qba.TorrentsAPIMixIn:
    """Creats and returns a client to communicate with qBittorrent server. Max Retries 2
    """
    #getting the conn 
    host = host if host is not None else "localhost"
    port = port if port is not None else "8090"
    uname = uname if uname is not None else "admin"
    passw = passw if passw is not None else "adminadmin"
    torlog.info(f"Trying to login in qBittorrent using creds {host} {port} {uname} {passw}")

    client = qba.Client(host=host,port=port,username=uname,password=passw)
    
    #try to connect to the server :)
    try:
        client.auth_log_in()
        torlog.info("Client connected successfully to the torrent server. :)")
        client.application.set_preferences({"disk_cache":20,"incomplete_files_ext":True,"max_connec":3000,"max_connec_per_torrent":300,"async_io_threads":6})
        torlog.debug("Setting the cache size to 20 incomplete_files_ext:True,max_connec:3000,max_connec_per_torrent:300,async_io_threads:6")
        return client
    except qba.LoginFailed as e:
        torlog.error("An errot occured invalid creds detected\n{}\n{}".format(e,traceback.format_exc()))
        return None
    except qba.APIConnectionError:
        if retry == 0:
            torlog.error("Tried to get the client 3 times no luck")
            return None
        
        torlog.info("Oddly enough the qbittorrent server is not running.... Attempting to start at port {}".format(port))
        cmd = f"qbittorrent-nox -d --webui-port={port}"
        cmd = cmd.split(" ")

        subpr = await aio.create_subprocess_exec(*cmd,stderr=aio.subprocess.PIPE,stdout=aio.subprocess.PIPE)
        _, _ = await subpr.communicate()
        return await get_client(host,port,uname,passw,retry=retry-1)
Esempio n. 3
0
 async def qbittorrent(self, path, torrent, local_path, remote_path, client, is_disc, filelist):
     # infohash = torrent.infohash
     #Remote path mount
     isdir = os.path.isdir(path)
     if not isdir and len(filelist) == 1:
         path = os.path.dirname(path)
     if len(filelist) != 1:
         path = os.path.dirname(path)
     if local_path in path and local_path != remote_path:
         path = path.replace(local_path, remote_path)
         path = path.replace(os.sep, '/')
     
     qbt_client = qbittorrentapi.Client(host=client['qbit_url'], port=client['qbit_port'], username=client['qbit_user'], password=client['qbit_pass'])
     cprint("Adding and rechecking torrent", 'grey', 'on_yellow')
     try:
         qbt_client.auth_log_in()
     except qbittorrentapi.LoginFailed:
         cprint("INCORRECT QBIT LOGIN CREDENTIALS", 'grey', 'on_red')
         exit()
     qbt_client.torrents_add(torrent_files=torrent.dump(), save_path=path, use_auto_torrent_management=False, is_skip_checking=True)
     qbt_client.torrents_resume(torrent.infohash)
     if client.get('qbit_tag', None) != None:
         qbt_client.torrents_add_tags(tags=client.get('qbit_tag'), torrent_hashes=torrent.infohash)
     
     print(f"Added to: {path}")
def qbitCategorizer(torrent_name, torrent_tracker, torrent_hash):

    # login
    qbt_client = qbittorrentapi.Client(host=WEBSERVER_IP + ":" +
                                       WEBSERVER_PORT,
                                       username=WEBSERVER_USERNAME,
                                       password=WEBSERVER_PASSWORD,
                                       VERIFY_WEBUI_CERTIFICATE=False)
    try:
        qbt_client.auth_log_in()
        # TelegramInterface.logToTelegram("[QbitTorrentInterface] - Qbit login SUCCESS \n")
    except qbittorrentapi.LoginFailed as e:
        TelegramInterface.logToTelegram(
            "[QbitTorrentInterface] - Qbit login FAILED \n")
        print(e)

    # get torrent via hash
    torrent_list = qbt_client.torrents_info(hashes=torrent_hash)

    for torrent in torrent_list:
        print(torrent.name)

    torrent = torrent_list[0]

    # enumerate category and set it
    if torrent_tracker.__contains__(
            IPT_TRACKER_ASYNC) or torrent_tracker.__contains__(
                IPT_TRACKER_STACK) or torrent_tracker.__contains__(
                    IPT_TRACKER_BGP) or torrent_tracker.__contains__(
                        IPT_TRACKER_IPT):
        torrent.set_category(category='IPTorrents')
        TelegramInterface.logToTelegram(
            "[QbitTorrentInterface] - categorized to: IPTorrents \n")
    elif torrent_tracker.__contains__(MYANON_TRACKER):
        torrent.set_category(category='MyAnonaMouse')
        TelegramInterface.logToTelegram(
            "[QbitTorrentInterface] - categorized to: MyAnonaMouse \n")
    elif torrent_tracker.__contains__(ORPHEUS_TRACKER):
        torrent.set_category(category='Orpheus')
        TelegramInterface.logToTelegram(
            "[QbitTorrentInterface] - categorized to: Orpheus \n")
    elif torrent_tracker.__contains__(REDACTED_TRACKER):
        torrent.set_category(category='REDacted')
        TelegramInterface.logToTelegram(
            "[QbitTorrentInterface] - categorized to: REDacted \n")
    elif torrent_tracker.__contains__(TORRENTECH_TRACKER):
        torrent.set_category(category='TorrenTech')
        TelegramInterface.logToTelegram(
            "[QbitTorrentInterface] - categorized to: TorrenTech \n")
    elif torrent_tracker.__contains__(THEPOLISH_TRACKER):
        torrent.set_category(category='ThePolishTracker')
        TelegramInterface.logToTelegram(
            "[QbitTorrentInterface] - categorized to: ThePolishTracker \n")
    elif torrent_tracker.__contains__(AWESOME_HD_TRACKER):
        torrent.set_category(category='Awesome-HD')
        TelegramInterface.logToTelegram(
            "[QbitTorrentInterface] - categorized to: Awesome-HD \n")
    else:
        TelegramInterface.logToTelegram(
            "[QbitTorrentInterface] - could not determine categry! \n")
Esempio n. 5
0
def detect_client(address):
    client = False
    tr = _parse_address(address)
    # Check for qBittorrent v4.3.8+
    try:
        qbt_client = qbt.Client(host=f"{tr['scheme']}://{tr['hostname']}",
                                port=tr['port'],
                                username=tr['username'],
                                password=tr['password'])
        try:
            qbt_client.auth_log_in()
        except qbt.LoginFailed as e:
            pass
        client = "qBittorrent"
    except Exception as e:
        log.debug("detect_client.qBittorrent: %s", e)
        pass
    # Check for Transmission
    try:
        c = transm.Client(host=tr['hostname'],
                          port=tr['port'],
                          username=tr['username'],
                          password=tr['password'],
                          protocol=tr['scheme'],
                          path=tr['path'])
        c.rpc_version
        client = "Transmission"
    except Exception as e:
        log.debug("detect_client.Transmission: %s", e)
        pass
    log.info(f"Detected {client}")
    return client
Esempio n. 6
0
async def re_verfiy(paused, resumed, client, torr):

    paused = paused.strip()
    resumed = resumed.strip()
    if paused:
        paused = paused.split("|")
    if resumed:
        resumed = resumed.split("|")
    k = 0
    while True:

        res = client.torrents_files(torrent_hash=torr)
        verify = True

        for i in res:
            if str(i.id) in paused:
                if i.priority == 0:
                    continue
                else:
                    verify = False
                    break

            if str(i.id) in resumed:
                if i.priority != 0:
                    continue
                else:
                    verify = False
                    break

        if not verify:
            LOGGER.info("Reverification Failed :- correcting stuff")
            # reconnect and issue the request again
            client.auth_log_out()
            client = qba.Client(host="localhost",
                                port="8090",
                                username="******",
                                password="******")
            client.auth_log_in()
            try:
                client.torrents_file_priority(torrent_hash=torr,
                                              file_ids=paused,
                                              priority=0)
            except:
                LOGGER.error("Errored in reverification paused")
            try:
                client.torrents_file_priority(torrent_hash=torr,
                                              file_ids=resumed,
                                              priority=1)
            except:
                LOGGER.error("Errored in reverification resumed")
            client.auth_log_out()
        else:
            break
        k += 1
        if k >= 2:
            # avoid an infite loop here
            return False
    return True
Esempio n. 7
0
def get_client() -> qba.TorrentsAPIMixIn:
    qb_client = qba.Client(host="localhost",
                           port=8090,
                           username="******",
                           password="******")
    try:
        qb_client.auth_log_in()
        qb_client.application.set_preferences({
            "disk_cache":
            64,
            "incomplete_files_ext":
            True,
            "max_connec":
            3000,
            "max_connec_per_torrent":
            300,
            "async_io_threads":
            8,
            "preallocate_all":
            True,
            "upnp":
            True,
            "dl_limit":
            -1,
            "up_limit":
            -1,
            "dht":
            True,
            "pex":
            True,
            "lsd":
            True,
            "encryption":
            0,
            "queueing_enabled":
            True,
            "max_active_downloads":
            15,
            "max_active_torrents":
            50,
            "dont_count_slow_torrents":
            True,
            "bittorrent_protocol":
            0,
            "recheck_completed_torrents":
            True,
            "enable_multi_connections_from_same_ip":
            True,
            "slow_torrent_dl_rate_threshold":
            100,
            "slow_torrent_inactive_timer":
            600
        })
        return qb_client
    except qba.LoginFailed as e:
        LOGGER.error(str(e))
        return None
Esempio n. 8
0
 def __init__(self, host=None, username=None, password=None):
     super().__init__('qBittorrent', host, username, password)
     self.host, self.port = splitport(self.host or settings.TORRENT_HOST)
     self.api = qbittorrentapi.Client(host=self.host,
                                      port=self.port or 8080,
                                      username=self.username
                                      or settings.TORRENT_USERNAME,
                                      password=self.password
                                      or settings.TORRENT_PASSWORD)
Esempio n. 9
0
 def __init__(self):
     self.qbt_client = qbt_api.Client(host=config.qbittorrent_host,
                                      port=config.qbittorrent_port,
                                      username=config.qbittorrent_username,
                                      password=config.qbittorrent_password,
                                      VERIFY_WEBUI_CERTIFICATE=False,
                                      DISABLE_LOGGING_DEBUG_OUTPUT=True)
     self._torrent_cache = None
     self._torrent_cache_time = time.time()
     self._torrent_cache_max_age = 3
Esempio n. 10
0
 def __init__(self, config, secret):
     super().__init__(config, secret)
     self.logger = logging.getLogger("animaid.qbittorrent")
     self.logger.debug("Logging into qbittorrent")
     self.client = qbt.Client(
         host=self.secret["qbittorrent"]["addr"],
         port=int(self.secret["qbittorrent"]["port"]),
         username=self.secret["qbittorrent"]["username"],
         password=self.secret["qbittorrent"]["password"],
     )
     self.path = self.secret["qbittorrent"]["download_path"]
Esempio n. 11
0
 def get_qbt_instance(self) -> qbittorrentapi.Client:
     if not isinstance(self.qbt, qbittorrentapi.Client):
         logger.info('开始连接qBittorrent.......')
         qbt = qbittorrentapi.Client(host=qbt_address,
                                     port=qbt_port,
                                     username=qbt_user,
                                     password=qbt_password)
         qbt.auth_log_in()
         logger.info('qBittorrent 连接成功……')
         self.qbt = qbt
     return self.qbt
Esempio n. 12
0
def auth():
    qbt_client = qbittorrentapi.Client(host='localhost:8081', username='******', password='******')

    try:
        qbt_client.auth_log_in()
        print(f'qBittorrent: {qbt_client.app.version}')
        print(f'qBittorrent Web API: {qbt_client.app.web_api_version}')
    except qbittorrentapi.LoginFailed as e:
        print(e)

    return qbt_client
Esempio n. 13
0
async def re_verfiy(paused, resumed, client, torr):

    paused = paused.strip()
    resumed = resumed.strip()
    if paused:
        paused = paused.split("|")
    if resumed:
        resumed = resumed.split("|")
    k = 0
    while True:

        res = client.torrents_files(torrent_hash=torr)
        verify = True

        for i in res:
            if str(i.id) in paused:
                if i.priority == 0:
                    continue
                verify = False
                break

            if str(i.id) in resumed and i.priority == 0:
                verify = False
                break

        if verify:
            break
        LOGGER.info("Reverification Failed: correcting stuff...")
        client.auth_log_out()
        client = qba.Client(host="localhost",
                            port="8090",
                            username="******",
                            password="******")
        client.auth_log_in()
        try:
            client.torrents_file_priority(torrent_hash=torr,
                                          file_ids=paused,
                                          priority=0)
        except:
            LOGGER.error("Errored in reverification paused")
        try:
            client.torrents_file_priority(torrent_hash=torr,
                                          file_ids=resumed,
                                          priority=1)
        except:
            LOGGER.error("Errored in reverification resumed")
        client.auth_log_out()
        k += 1
        if k > 4:
            return False
    LOGGER.info("Verified")
    return True
Esempio n. 14
0
 def __init__(self,
              host: str = None,
              username: str = None,
              password: str = None):
     super().__init__("qBittorrent", host, username, password)
     self.host, self.port = splitport(self.host or settings.TORRENT_HOST)
     self.api = qbittorrentapi.Client(
         host=self.host,
         port=self.port or None,
         username=self.username or settings.TORRENT_USERNAME,
         password=self.password or settings.TORRENT_PASSWORD,
         VERIFY_WEBUI_CERTIFICATE=settings.TORRENT_VERIFY_CERT,
     )
Esempio n. 15
0
def qBit_Connection(logger, cfgGen):

    qbt = qbittorrentapi.Client(
        host=cfgGen["qBittorrent"]["host"], username=cfgGen["qBittorrent"]["user"], password=cfgGen["qBittorrent"]["password"], VERIFY_WEBUI_CERTIFICATE=False)
    try:
        qbt.auth_log_in()
        logger.info(
            f'{Fore.CYAN}Conection with qBittorrent tested OK : Qbittorrent {qbt.app.version}, API {qbt.app.web_api_version}{Style.RESET_ALL}')
    except:
        logger.warning(
            f'{Fore.RED}{Style.BRIGHT}Conection with qBittorrent and Web Api Logging failed{Style.RESET_ALL}')
        raise
    return qbt
Esempio n. 16
0
def RestartQB():

    #连接到QB,暂停种子,并关闭QB
    try:
        qb_client = qbittorrentapi.Client(host=QB_IPPORT,
                                          username=QB_USER,
                                          password=QB_PWD)
        qb_client.auth_log_in()
        qb_client.torrents.pause.all()
        qb_client.app_shutdown()
    except:
        print("failed to stop QB")
        return False
    else:
        print("success to stop QB")

    #休眠10分钟,给qb后台完成缓存的写入时间,避免重启后重新校验
    time.sleep(600)

    #重启QB,执行命令行"/usr/bin/qbittorrent &",适用于我的ubuntu环境,其他linux环境,请更换对应的命令行
    #   注意:我的ubuntu桌面版,qbittorrent需要启动客户端,远程环境需要设置DISPLAY才能成功。不知道怎么操作的就在ubuntu本机桌面的"终端"中运行该脚本。
    if os.system("/usr/bin/qbittorrent &") == 0: print("success to start qb")
    else:
        print("failed to start qb")
        return False

    time.sleep(10)
    try:
        qb_client = qbittorrentapi.Client(host=QB_IPPORT,
                                          username=QB_USER,
                                          password=QB_PWD)
        qb_client.auth_log_in()
        qb_client.torrents.resume.all()
    except:
        print("failed to resume torrents")
        return False
    else:
        print("success to resume torrents")
    return True
Esempio n. 17
0
def MovieFinder(moviename):

    response = ''
    link = MovieSearch(moviename)

    if link == 'No results found':
        response = 'No results found for' + moviename
    elif "1080p" in link:
        try:
            client = putiopy.Client(pkey.OAUTH_KEY)
            client.Transfer.add_url(link)
            response = "You'll be able to watch " + moviename + " on Put IO soon..."
        except Exception:
            return 'Something went wrong adding file to Put IO.'
    else:
        # instantiate a Client using the appropriate WebUI configuration
        qbt_client = qbit.Client(host=qbt_auth['host'],
                                 username=qbt_auth['username'],
                                 password=qbt_auth['password'])

        # the Client will automatically acquire/maintain a logged in state in line with any request.
        # therefore, this is not necessary; however, you many want to test the provided login credentials.
        try:
            qbt_client.auth_log_in()
        except qbit.LoginFailed:
            return 'Could not authenticate. Qbt is probably down.'

        # add download link to qbt client
        # help(qbt_client.torrents_add)
        try:
            qbt_client.torrents_add(urls=link,
                                    save_path=path_to_save,
                                    is_paused=False)
            response = "You'll be able to watch " + moviename + " in 4K soon..."
        except Exception:
            return 'Something went wrong adding file to Qbt.'

    try:
        with open("/var/www/piAppSwitcher/MovieFinder/MFResponses.txt",
                  mode='a+') as txtfile:
            txtfile.write('On ' +
                          datetime.now().strftime("%Y-%m-%d %H:%M:%S") +
                          ' MovieFinder sent response "' + response + '".\n')
    except IOError:
        print("Couldn't write to file!")

    # Send response to Telegram Chat
    payload = dict(chat_id=tkeys.chat_id, text=response)
    requests.post(tkeys.url, data=payload)

    return response
Esempio n. 18
0
async def set_priority(request):

    torr = request.match_info["hash_id"]
    client = qba.Client(host="localhost",
                        port="8090",
                        username="******",
                        password="******")
    client.auth_log_in()

    data = await request.post()
    resume = ""
    pause = ""
    data = dict(data)

    for i in data.keys():
        if i.find("filenode") != -1:
            node_no = i.split("_")[-1]

            if data[i] == "on":
                resume += f"{node_no}|"
            else:
                pause += f"{node_no}|"

    pause = pause.strip("|")
    resume = resume.strip("|")
    LOGGER.info(f"Paused {pause} of {torr}")
    LOGGER.info(f"Resumed {resume} of {torr}")

    try:
        client.torrents_file_priority(torrent_hash=torr,
                                      file_ids=pause,
                                      priority=0)
    except qba.NotFound404Error:
        raise web.HTTPNotFound()
    except:
        LOGGER.info("Errored in paused")

    try:
        client.torrents_file_priority(torrent_hash=torr,
                                      file_ids=resume,
                                      priority=1)
    except qba.NotFound404Error:
        raise web.HTTPNotFound()
    except:
        LOGGER.info("Errored in resumed")

    await asyncio.sleep(2)
    if not await re_verfiy(pause, resume, client, torr):
        LOGGER.error("The torrent choose errored reverification failed")
    client.auth_log_out()
    return await list_torrent_contents(request)
Esempio n. 19
0
def client(config):
    qbt = config["qbittorrent"]

    qbt_client = qbittorrentapi.Client(host=qbt["host"],
                                       port=qbt["port"],
                                       username=qbt["username"],
                                       password=qbt["password"])

    try:
        qbt_client.auth_log_in()
    except qbittorrentapi.LoginFailed as e:
        print(e)

    return qbt_client
Esempio n. 20
0
def send_to_client_rpc(scheme, hostname, port, username, password, path,
                       tor_hash):
    try:
        host = f"{scheme}://{hostname}{path if path != None else ''}"
        c = qbt.Client(host=host,
                       port=port,
                       username=username,
                       password=password)
        m = f'magnet:?xt=urn:btih:{tor_hash}'
        c.torrents_add(urls=m)
        return True
    except Excepion as exc:
        log.warn("Failed to send to qBittorrent: %s", host)
        return False
Esempio n. 21
0
def search(update, context):
    
    context.chat_data.clear()

    chat_id = update.effective_chat.id
    message_info = context.bot.send_message(chat_id=chat_id, text="Fetching results...")
    context.chat_data['msg_id'] = message_info.message_id

    search = ' '.join(context.args)
    print(f"New search: {search}")
    
    #perform search 
    qbt_client = qbittorrentapi.Client(host='', username='', password='')

    try:
        qbt_client.auth_log_in()
    except qbittorrentapi.LoginFailed as err:
        print(err)
    
    search_job = qbt_client.search_start(pattern=search, category='all', plugins='all')
    
    while search_job.status()[0].status != 'Stopped':
        time.sleep(.1)

    search_result = search_job.results(limit=5, offset=1)

    context.chat_data['magnet_list'] = [result.fileUrl for result in search_result.results]

    #construct message
    title = ''
    for result in search_result.results:
        title = title + f"*Name:* _{result.fileName}_\n*Seeders:* _{result.nbSeeders}_\n*Size:* _{round(result.fileSize/(1024**3),2)} GB_\n\n"

    #Construct inline keybpoard
    kb_markup = InlineKeyboardMarkup([
                    [InlineKeyboardButton(text='Magnet 1', callback_data=f'0'), InlineKeyboardButton(text='Magnet 2', callback_data=f'1')],
                    [InlineKeyboardButton(text='Magnet 3', callback_data=f'2'), InlineKeyboardButton(text='Magnet 4', callback_data=f'3')],
                    [InlineKeyboardButton(text='Magnet 5', callback_data=f'4')]
                ])

    search_job.delete()

    try:
        context.bot.edit_message_text(message_id = context.chat_data['msg_id'], chat_id=chat_id, text=title, reply_markup=kb_markup, parse_mode = 'markdown')
    except Exception as err: 
        context.bot.edit_message_text(message_id = context.chat_data['msg_id'], chat_id=chat_id, text="No results found")
        print(err)
    else:
        print("Search result found")
Esempio n. 22
0
def download():
    magnet = request.args.get("magnet")
    print("magnet")
    print(magnet)
    qbt = qbittorrentapi.Client(host='http://192.168.15.2',
                                port=8080,
                                username=config('QBIT_USER'),
                                password=config('QBIT_PASS'))
    try:
        qbt.auth_log_in()
    except qbittorrentapi.LoginFailed as e:
        print(e)

    qbt.torrents.add(magnet)
    return redirect(url_for('search'))
Esempio n. 23
0
def change():
    qbt_client = qbittorrentapi.Client(host=f'localhost:{QB_port}',
                                       username='******',
                                       password='******')
    # this are all the same attributes that are available as named in the
    #  endpoints or the more pythonic names in Client (with or without 'app_' prepended)

    prefs = qbt_client.app.preferences
    prefs['web_ui_password'] = Password
    qbt_client.app.preferences = prefs
    prefs = qbt_client.app.preferences
    prefs['web_ui_username'] = Username
    qbt_client.app.preferences = prefs
    print(f"修改账号:{Username}\n修改密码为:{Password}\n")
    sys.stdout.flush()
    def wrapper(*args, **kwargs):

        qbt_client = qbittorrentapi.Client(host=f'http://{QBITTORRENT_IP}:'
                                           f'{QBITTORRENT_PORT}',
                                           username=QBITTORRENT_USER,
                                           password=QBITTORRENT_PSW)

        try:
            qbt_client.auth_log_in()
        except qbittorrentapi.LoginFailed as e:
            print(e)

        resp = func(qbt_client, *args, **kwargs)

        qbt_client.auth_log_out()

        return resp
Esempio n. 25
0
 def __init__(self, api_token, group_id, server_name: str = "Empty"):
     print("Инициализация вк")
     self.server_name = server_name
     self.vk = vk_api.VkApi(token=api_token)
     self.upload = vk_api.VkUpload(self.vk)
     self.long_poll = VkBotLongPoll(self.vk, group_id)
     self.vk_api = self.vk.get_api()
     print("Готово")
     print("Инициализация торрента")
     self.qbt_client = qbittorrentapi.Client(host=url_web_api_torrent,
                                             username=torrent_login_api,
                                             password=torrent_password_api)
     try:
         self.qbt_client.auth_log_in()
     except qbittorrentapi.LoginFailed as e:
         print(e)
     print("Готово")
Esempio n. 26
0
 def __init__(self):
     try:
         self.status = Status.IDLE
         self.status_string = ""
         self.error = None
         alpha = "qweryuiopasdfhghzxcvbnm1234567890"
         self.token = "".join(
             [alpha[randint(0,
                            len(alpha) - 1)] for _ in range(16)])
         self.qbt = qbittorrentapi.Client(host='localhost:8080',
                                          username='******',
                                          password='******')
         self.qbt.auth_log_in()
     except (qbittorrentapi.LoginFailed,
             qbittorrentapi.exceptions.APIConnectionError) as e:
         self.set_error(str(e))
         print("Bootstrapper initialization failed")
    def wrapper(*args, **kwargs):

        qbt_client = qbittorrentapi.Client(
            host=f'http://{get_configs().qbittorrent.ip}:'
            f'{get_configs().qbittorrent.port}',
            username=get_configs().qbittorrent.user,
            password=get_configs().qbittorrent.password)

        try:
            qbt_client.auth_log_in()
        except qbittorrentapi.LoginFailed as e:
            print(e)

        resp = func(qbt_client, *args, **kwargs)

        qbt_client.auth_log_out()

        return resp
Esempio n. 28
0
def get_client() -> qba.TorrentsAPIMixIn:
    qb_client = qba.Client(host="localhost",
                           port=8090,
                           username="******",
                           password="******")
    try:
        qb_client.auth_log_in()
        qb_client.application.set_preferences({
            "disk_cache": 64,
            "incomplete_files_ext": True,
            "max_connec": 3000,
            "max_connec_per_torrent": 300,
            "async_io_thread": 32
        })
        return qb_client
    except qba.LoginFailed as e:
        LOGGER.error(str(e))
        return None
Esempio n. 29
0
def checkUpdate():
    try:
        seq = jpopsuki.get(tv_url).text
        jpopsukiDoc = pq(seq)
        data = jpopsukiDoc("#torrent_table .torrent_redline").items()
        for i in data:
            pt_url = i("td:nth-child(4) > a:nth-child(3)")
            now_pool.append(pt_url.attr("href"))

        else_data = jpopsukiDoc(
            "#torrent_table .group_torrent_redline").items()
        for i in else_data:
            pt_url = i("td:nth-child(1) > a")
            now_pool.append(pt_url.attr("href"))

        authdata = jpopsukiDoc(
            "#torrent_table .torrent_redline td:nth-child(4) > span > a:nth-child(1)"
        )
        url = authdata.attr("href")
        authkey = url[38:]

        for i in now_pool:
            if i not in seed_pool:
                print(i + "  NOT IN SEED POOL!!")
                seed_pool.append(i)
                qbt_client = qbittorrentapi.Client(host='127.0.0.1:8080',
                                                   username='',
                                                   password='')
                res = qbt_client.torrents_add(
                    urls="https://jpopsuki.eu/torrents.php?action=download&id={}"
                    .format(i[-6:]) + authkey,
                    save_path="E:/PT/",
                    cookie=jpopsuki.cookies.get_dict(),
                    is_skip_checking=False,
                    is_root_folder=True,
                )
    except Exception as e:
        print("遇到错误", e)
        time.sleep(300)
        getCookie()
Esempio n. 30
0
async def set_priority(request):

    torr = request.match_info["hash_id"]
    client = qba.Client(host="localhost", port="8090")

    data = await request.post()
    resume = ""
    pause = ""
    data = dict(data)

    for i, value in data.items():
        if i.find("filenode") != -1:
            node_no = i.split("_")[-1]

            if value == "on":
                resume += f"{node_no}|"
            else:
                pause += f"{node_no}|"

    pause = pause.strip("|")
    resume = resume.strip("|")

    try:
        client.torrents_file_priority(torrent_hash=torr, file_ids=pause, priority=0)
    except qba.NotFound404Error:
        raise web.HTTPNotFound()
    except:
        LOGGER.error("Errored in paused")

    try:
        client.torrents_file_priority(torrent_hash=torr, file_ids=resume, priority=1)
    except qba.NotFound404Error:
        raise web.HTTPNotFound()
    except:
        LOGGER.error("Errored in resumed")

    await asyncio.sleep(2)
    if not await re_verfiy(pause, resume, client, torr):
        LOGGER.error("Verification Failed")
    return await list_torrent_contents(request)