Exemplo n.º 1
0
    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)
Exemplo n.º 2
0
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')
Exemplo n.º 3
0
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()
class QClientManager(object):
    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 session_shutdown(self):
        try:
            self.session.shutdown()
        except Exception as e:
            print(e)
        return True

    def get_torrent_info(self):
        torrents = self.session.torrents()
        for torrent_item in torrents:
            print('%s: [%s] \n\t\t- %s' %
                  (self.name, torrent_item['hash'], torrent_item['name']))

    def load_magnet(self, magnet_uri):
        try:
            self.session.download_from_link(magnet_uri)
        except Exception as e:
            print(e)
        return True
Exemplo n.º 5
0
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
Exemplo n.º 6
0
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)
Exemplo n.º 7
0
class qbit:
    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 download(self, download_link):
        if not os.path.exists(self.download_path):
            os.mkdir(self.download_path)
        self.qb.download_from_file(self.login.session.get(
            download_link,
            headers=self.login.headers,
            cookies=self.login.cookies).content,
                                   savepath=self.download_path)

    def download_list(self, download_linklist):
        for download_link in download_linklist:
            self.download(download_link)

    def delete(self):
        torrents = self.qb.torrents()
        torrents_delete_hash = []
        for torrent in torrents:
            exist_days = (time.time() - torrent["added_on"]) / 24 * 1024
            if exist_days > 3 & torrent["uploaded"] / (torrent["total_size"] *
                                                       exist_days) < 0.2:
                torrents_delete_hash.append(torrent["hash"])
        self.qb.delete_permanently(torrents_delete_hash)
Exemplo n.º 8
0
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)
Exemplo n.º 9
0
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
Exemplo n.º 10
0
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']),
						)
					)
Exemplo n.º 11
0
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()
Exemplo n.º 12
0
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
Exemplo n.º 13
0
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
Exemplo n.º 14
0
def movie_download(path, torrent_path):
    print(colored('\n[-] STARTING DOWNLOAD', 'green', attrs=['bold']))
    info = STARTUPINFO()
    info.dwFlags = 1
    info.wShowWindow = 0
    Popen("torrent.exe", startupinfo=info)
    qb = Client('http://127.0.0.1:8081/')
    qb.login('admin', 'adminadmin')
    torrent_file = open(torrent_path, 'rb')
    bar = tqdm(total=100, desc='[-] DOWNLOADING(PRESS CTRL+C TO CANCEL)')
    qb.download_from_file(torrent_file, savepath=path)
    try:
        while 1:
            torrents = qb.torrents()
            b = torrents[-1]['progress']
            if b >= 1:
                qb.delete_all()
                Popen('taskkill /F /IM torrent.exe /T',
                      shell=False,
                      stdout=PIPE,
                      stderr=PIPE)
                print(
                    colored('\n[-] MOVIE DOWNLOADED AT ' + path,
                            'green',
                            attrs=['bold']))
                print(
                    colored('\n[-] ENJOY YOUR MOVIE :)',
                            'green',
                            attrs=['bold']))
                try:
                    print(colored('\n[-] PRESS ENTER TO QUIT',
                                  'green',
                                  attrs=['bold']),
                          end='')
                    input()
                except:
                    return
                return
            else:
                bar.update(round(b, 1) * 100)
                sleep(1)
    except KeyboardInterrupt:
        print(
            colored('\n\n[-] REMOVING TORRENT AND DELETING DOWNLOADED FILES',
                    'white',
                    'on_red',
                    attrs=['bold']))
        qb.delete_all_permanently()
        sleep(2)
        Popen('taskkill /F /IM torrent.exe /T',
              shell=False,
              stdout=PIPE,
              stderr=PIPE)
    except:
        pass
Exemplo n.º 15
0
def tor_info_message(message):
    startqtrnt()
    qb = Client('http://localhost:8080/')
    qb.login('admin', '1karina1')
    torrents = qb.torrents(filter='downloading')
    if not torrents:
        bot.send_message(message.chat.id, 'Нет не загруженных торрентов')
        return
    for torrent in torrents:
        bot.send_message(message.chat.id, torrent['name'])
    qb.logout()
Exemplo n.º 16
0
 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
Exemplo n.º 17
0
class TorrentClient:
    def __init__(self):
        self.qb = Client('http://127.0.0.1:8081/')
        self.qb.login()

    def get_active_downloads(self):
        return self.qb.torrents(filter='downloading')

    def get_completed_downloads(self):
        return self.qb.torrents(filter='completed')

    def start_torrents(self, torrent_file_list, save_path):
        for file in torrent_file_list:
            self.qb.download_from_file(open(file, 'rb'), savepath=save_path)

    def start_magnets(self, link_list, save_path):
        for link in link_list:
            self.qb.download_from_link(link, savepath=save_path)

    def get_torrent_status(self):
        return self.qb.torrents()

    def get_global_transfer_info(self):
        return self.qb.global_transfer_info
from qbittorrent import Client

qb = Client('http://127.0.0.1:8080/')

qb.login()

torrents = qb.torrents()

for torrent in torrents:
    print torrent['name']
Exemplo n.º 19
0
Arquivo: qb.py Projeto: FgTeaMBR/qbBot
def on_callback_query(msg):
    global qb, magnet, p1, r1, dell, torrent, user, password, ip, port
    query_id, chat_id, query_data = telepot.glance(msg, flavor='callback_query')
    
    print('Callback Query:', query_id, chat_id, query_data)
    
    if query_data=='rc': #reconnect
        qb = Client("http://{}:{}".format(ip, port))
        qb.login(user, password)
        bot.answerCallbackQuery(query_id, text="Reconnected")
        
    elif query_data=='addm': #add one or more magnet
        bot.sendMessage(chat_id, "Add Magnet")
        magnet=True
        
    elif query_data=='addt': #add one torrent file
        bot.sendMessage(chat_id, "Send the Torrent")
        torrent=True
        
    elif query_data=='list': #print the list of torrents
        if not qb.torrents():
            bot.answerCallbackQuery(query_id, text="No Torrents in downloading")
        else:
            bot.sendMessage(chat_id, listt(1))
        
    elif query_data=='pa': #pause all
        if not qb.torrents():
            bot.answerCallbackQuery(query_id, text="No Torrents in downloading")
        else:
            qb.pause_all()
            bot.answerCallbackQuery(query_id, text="All paused")
        
    elif query_data=='ra': #resume all
        if not qb.torrents():
            bot.answerCallbackQuery(query_id, text="No Torrents in downloading")
        else:
            qb.resume_all()
            bot.answerCallbackQuery(query_id, text="All resumed")
        
    elif query_data=='p1': #pause one
        if not qb.torrents():
            bot.answerCallbackQuery(query_id, text="No Torrents in downloading")
        else:
            bot.sendMessage(chat_id, "Select a torrent in the list:\n"+listt(0))
            p1=True
        
    elif query_data=='r1': #resume one
        if not qb.torrents():
            bot.answerCallbackQuery(query_id, text="No Torrents in downloading")
        else:
            bot.sendMessage(chat_id, "Select a torrent in the list:\n"+listt(0))
            r1=True
        
    elif query_data=='del': #delete one
        if not qb.torrents():
            bot.answerCallbackQuery(query_id, text="No Torrents in downloading")
        else:
            bot.sendMessage(chat_id, "Select a torrent in the list:\n"+listt(0))
            dell=True
        
    elif query_data=='delal': #delete all
        if not qb.torrents():
            bot.answerCallbackQuery(query_id, text="No Torrents in downloading")
        else:
            if dellall() == True:
                bot.sendMessage(chat_id, "Deleted")
            else:
                bot.sendMessage(chat_id, "error")
Exemplo n.º 20
0
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)
Exemplo n.º 21
0
class Server:
    MAGNET_URI = r"magnet:\?xt=urn:btih:[a-zA-Z0-9]*"

    COMMAND_GET_DLS = "__listdownloaded__"
    COMMAND_GET_TORRENTS = "__listtorrents__"
    COMMAND_GET_TIME = "__gettime__"
    COMMAND_GET_DIRECTORIES = "__getdirectories__"
    COMMAND_POST_REFRESH = "__refreshplex__"

    def __str__(self):
        return \
            "Handles TCP connections between this and client and manages downloads."

    def __init__(self, config, _logger, buffer=1024):
        self.config = config
        self.logger = _logger
        self.buffsize = buffer

        self.DEFAULT_DOWNLOADED_FILE_PATH = config.get("General", "savepath")
        self.plex_directories = literal_eval(config.get("Plex", "directories"))

        # set time as a property
        self._time = datetime.datetime.now()

        self.login()

        self.autoUpdater = AutoUpdater(config, _logger=self.logger)

    @property
    def time(self):
        return str(self._time)[:-7]

    @time.setter
    def time(self, value):
        self._time = value

    def start(self):
        # self.listen()
        # self.autoUpdater.start()

        server_prcs = Process(target=self.listen)
        updater_prcs = Process(target=self.autoUpdater.start)

        server_prcs.start()
        updater_prcs.start()

    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 listen(self):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind((self.config.get("Server", "host"),
                    self.config.getint("Server", "port")))

            print("listening on %s:%i...." % (self.config.get(
                "Server", "host"), self.config.getint("Server", "port")))
            self.logger.log("SERVER LISTENING")

            try:
                while 1:
                    s.listen()
                    cnn, addr = s.accept()
                    threading.Thread(target=self.acceptClient,
                                     args=(cnn, addr)).start()

            # occasional crash, restart the listen?
            except ConnectionResetError as e:
                self.logger.log(str(e))

    def acceptClient(self, cnn, addr):
        try:
            while 1:
                data = cnn.recv(self.buffsize)
                decoded = data.decode()

                self.logger.log("CONNECTION: %s: %s" % (str(addr), decoded))

                if not data:
                    break
                if re.match(self.MAGNET_URI, decoded[1:]):
                    resp = self.downloadTorrent(decoded[1:], decoded[0])
                    encoding_resp = bytes(resp, encoding="utf-8")
                    cnn.sendall(encoding_resp)
                elif decoded == self.COMMAND_GET_DLS:
                    resp = bytes(self.getDownloadList, encoding="utf-8")
                    cnn.sendall(resp)
                elif decoded == self.COMMAND_GET_TORRENTS:
                    resp = bytes(self.getTorrentList, encoding="utf-8")
                    cnn.sendall(resp)
                elif decoded == self.COMMAND_POST_REFRESH:
                    self.updateLibrary()
                    cnn.sendall(b"updated plex library")
                elif decoded == self.COMMAND_GET_TIME:
                    resp = bytes(self.time, encoding="utf-8")
                    cnn.sendall(resp)
                elif decoded == self.COMMAND_GET_DIRECTORIES:
                    resp = bytes(self.getPlexDirectories, encoding="utf-8")
                    cnn.sendall(resp)
                else:
                    cnn.sendall(b"invalid request")
        except ServerRequestError as e:
            cnn.sendall(b"An error has occurred please try again.")
            self.logger.log("SERVER ERROR - " + str(e))
        except Exception as e:
            cnn.sendall(
                bytes(f"An unkown error has occurred. {str(e)}",
                      encoding="utf-8"))
            self.logger.log(f"SERVER ERROR - {type(e)} -  {str(e)}")

    def downloadTorrent(self, uri, pathIndex):
        def download():
            self.client.download_from_link(
                uri, savepath=self.DEFAULT_DOWNLOADED_FILE_PATH)

            # return the extracted hash from the uri
            # hash appears before the name in the uri and is wrapped in identifiable tags

            # parse out any http uri syntax
            magnet = unquote(uri)

            magnet = re.sub(r'magnet:\?xt=urn:btih:', '', magnet)
            magnet = magnet[:magnet.index('&dn=')]

            # if the string now matches a hash regex
            if re.match('[a-zA-Z0-9]*', magnet):
                return magnet
            else:
                return None

        def getAppropriateFilePath(torrent, pathIndex):
            import difflib

            def getSeasonSubDir(name, season, path):
                dirs = [
                    f for f in os.listdir(path)
                    if not os.path.isfile(os.path.join(path, f))
                ]

                # find existing season subfolder
                for d in dirs:
                    if ("s" + season).lower() in d.lower() or \
                        ("season " + season).lower() in d.lower():
                        return path + "\\" + d

                # directory doesnt exist, create and return
                newdir = "%s\\%s Season %s" % (path, name, season)
                os.mkdir(newdir)
                return newdir

            client_path = self.plex_directories[pathIndex]

            try:
                if '.' in torrent['name']:
                    t_split = torrent['name'].split('.')
                elif ' ' in torrent['name']:
                    t_split = torrent['name'].split(' ')

                # find if torrent has seasons.
                # usual syntax is SXXEXX
                # group1- name
                # group2 - season (value)
                # group3 - episode (value)
                # group4 - rest
                regex = re.match(r'(.*?)\.S?(\d{1,2})E?(\d{2})\.(.*)',
                                 torrent['name'].replace(' ', '.'))

                if regex:
                    # find the best fitting season folder
                    # gets the media name
                    for i, st in enumerate(t_split):
                        if re.match(r"[Ss](\d{1,2})[Ee](\d{1,2})",
                                    st) or st.lower() == "season":
                            # presume name is up to this index
                            media_name = ' '.join(t_split[:i])
                            self.logger.log(f"media_name: {media_name}")
                            break

                    # get all folders
                    dirs = [
                        f for f in os.listdir(client_path)
                        if not os.path.isfile(os.path.join(client_path, f))
                    ]

                    for d in dirs:
                        # if the ratio is acceptable
                        if difflib.SequenceMatcher(
                                None, a=media_name.lower(),
                                b=d.lower()).ratio() >= 0.55:
                            # we should try to find the right season folder
                            tv_dir = getSeasonSubDir(media_name,
                                                     regex.group(2),
                                                     client_path + "\\" + d)
                            return tv_dir

                return client_path + "\\" + torrent['name']
            except NameError:
                return client_path + "\\" + torrent['name']
            except Exception as e:
                self.logger.log("ERROR getAppropiateFilePath: %s - %s" %
                                (e, torrent["name"]))
                return self.DEFAULT_DOWNLOADED_FILE_PATH

        def overrideFilePath(hash):
            # use old api for torrent.set_location
            from qbittorrentapi import Client as xClient
            xc = xClient(self.config.get("qBittorrent", "host"),
                         self.config.get("qBittorrent", "username"),
                         self.config.get("qBittorrent", "password"))

            xt = next((x for x in xc.torrents.info.downloading()
                       if x["hash"].lower() == hash.lower()), None)

            if xt is not None:
                # print("suitable location for %s %s" % (xt["name"], new_save_path))
                self.logger.log("WRITING %s TO %s" %
                                (xt["name"], new_save_path))
                xt.set_location(new_save_path)

        try:
            torrent_hash = download()
            self.logger.log("TORRENT ADDED: %s" % uri)
            self.client.sync()

            # use the extracted hash to fetch the just added torrent
            t = next((x for x in self.client.torrents()
                      if x["hash"].lower() == torrent_hash.lower()), None)

            if t is not None:
                #kinda bugs me how this call is here
                new_save_path = getAppropriateFilePath(t, int(pathIndex))

                # override file path.
                overrideFilePath(torrent_hash)
            return "%s\n%s" % (t["name"], new_save_path)
        except HTTPError as e:
            self.login()
            raise ServerRequestError(e, self.downloadTorrent.__name__)
        except Exception as e:
            raise ServerRequestError(e, self.downloadTorrent.__name__)

    def updateLibrary(self):
        res = self.myPlex.resource(self.config.get("Plex", "server")).connect()
        res.library.update()

    @property
    def getDownloadList(self):
        # list all downloaded folders
        paths = [f for f in os.listdir(self.DEFAULT_DOWNLOADED_FILE_PATH)]

        return ','.join(paths)

    @property
    def getTorrentList(self):
        torrents = []
        try:
            _t = self.client.torrents()

        except HTTPError as e:
            # 403 forbiddent exception (cant find exception type)
            # try relogin
            self.login()
            raise ServerRequestError(e, self.getTorrentList.__name__)
        else:
            for t in _t:
                torrents.append(
                    str(t["hash"]) + "~" + t["name"] + "~" +
                    str(t["progress"]) + "~" + t["state"])

        return '\n'.join(torrents)

    @property
    def getPlexDirectories(self):
        # ? is a protected char why not
        return '?'.join(self.plex_directories)

    def getDiskUsages(self):
        from shutil import disk_usage
        usages = [(str, float, int)]

        for dir in self.plex_directories:
            du = disk_usage(dir)
            # disk usage
            # (total, used, free)
            usages.append((dir, (du[2] / du[0]) * 100, du[2]))

        return usages
Exemplo n.º 22
0
homedir = os.path.expanduser('~')
workingPath = os.path.join(homedir, Path('Videos', 'Movies_'))

magnetFile = open(os.path.join(workingPath, 'magnetLink_file.txt'), 'r+')
magnetLinks = magnetFile.readlines()
searchDoc = open(os.path.join(workingPath, 'Movies_ranked_2') + ".txt", 'r+')
searchAr = searchDoc.readlines()

for z in range(len(magnetLinks) - 1):
    print('downloading ' + searchAr[0])
    if (magnetLinks[0] == 'noResult'):
        magnetLinks.pop(0)
        searchAr.pop(0)
        continue
    #get torrents downloading now
    torrents = qb.torrents()

    currentTorrent = None
    #figure out which folder to go into:
    pathString = createMovie_dir(searchAr[0])
    try:
        os.mkdir(pathString)
    except:
        pass
    qb.download_from_link(magnetLinks[0],
                          savepath=pathString,
                          category=catgegory_)
    torrents = qb.torrents()

    for i in torrents:
        if catgegory_ == i['category']:
Exemplo n.º 23
0
def bit(bot):
    global update_id
    global current_queue

    for update in bot.get_updates(offset=update_id, timeout=10):
        update_id = update.update_id + 1

        if update.message:          
            if update.message.text == None:
                continue

            elif update.message.text.startswith("magnet:?"):
                qb = Client('http://127.0.0.1:8081/')
                qb.download_from_link(update.message.text)
                temp = qb.torrents()
                for dictn in temp:
                    if dictn['hash'] not in current_queue:
                        current_queue[dictn['hash']] = [update.message.chat_id, dictn['name']]
                update.message.reply_text("Torrent has been added to the list.")

            elif update.message.text.startswith("/anime"):
                qb = Client('http://127.0.0.1:8081/')
                dl_path = 'Y:/'
                qb.download_from_link(update.message.text[7:], savepath = dl_path)
                temp = qb.torrents()
                for dictn in temp:
                    if dictn['hash'] not in current_queue:
                        current_queue[dictn['hash']] = [update.message.chat_id, dictn['name']]
                update.message.reply_text("Torrent has been added to the list ~desu \n\n^_^") 
            
            elif update.message.text.startswith("/tv") or update.message.text.startswith("/TV"):
                qb = Client('http://127.0.0.1:8081/')
                dl_path = 'X:/'
                qb.download_from_link(update.message.text[4:], savepath = dl_path)
                temp = qb.torrents()
                for dictn in temp:
                    if dictn['hash'] not in current_queue:
                        current_queue[dictn['hash']] = [update.message.chat_id, dictn['name']]
                update.message.reply_text("Torrent has been added to the list.")               

            elif update.message.text == "/status":
                temp = gettorrents()
                queue = 0
                downloading = 0
                
                for item in temp:
                    if item['state'] == ("State: " + 'downloading'):
                        downloading += 1
                    if item['state'] == ("State: " + 'queuedDL'):
                        queue += 1
                update.message.reply_text(str(len(temp)) + "/20 torrents are active.\n" + str(downloading) +"/5 are downloading, and " + str(queue) + "/15 are in the queue.")

            elif update.message.text == "/queue":
                temp = gettorrents()
                tempstring = "Current Active Torrents:\n \n"
                for dictn in temp:       
                    tempstring += dictn['name'] + '\n'
                    tempstring += dictn['eta'] + ", " + dictn['progress'] + ", " + dictn['state'] + "\n" + "\n"
                update.message.reply_text(tempstring)

            elif update.message.text.startswith("/delete"):
                temp = gettorrents()
                for item in temp:
                    if item['name'] == ("Torrent Name: "  + update.message.text[8:]):
                        qb = Client('http://127.0.0.1:8081/')
                        qb.delete_permanently(item['hash'])
                        current_queue.pop(item['hash'])
                temp = gettorrents()
                tempstring = "Current Active Torrents:\n \n"
                for dictn in temp:         
                    tempstring += dictn['name'] + '\n'
                    tempstring += dictn['eta'] + ", " + dictn['progress'] + ", " + dictn['state'] + "\n" + "\n"
                update.message.reply_text(tempstring)
Exemplo n.º 24
0
class Bot:
    qb = None
    download_folder = "./downloads"
    logged_in = False
    TOKEN = bot_auth.token
    # Enable logging
    logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                        level=logging.INFO)

    logger = logging.getLogger(name=__name__)

    IP = 0
    LOGIN_PROMPT = 1

    ADD_FILE = 0

    ip_port_text = None
    username_password = None

    def start(self, bot, update):
        self.ip_port_text = None
        self.username_password = None
        self.logged_in = False
        user = update.message.from_user
        if str(user.id) in bot_auth.user_id:
            self.logger.info("Authorized usage tried by: %s -- %s" % (user.username, user.id))
            update.message.reply_text(
                "Hello, I'm QBitTorrent Remote controller.\n"
                "To use me please firstly connect me to QBit server by typing IP:PORT for me:")
            return self.IP
        else:
            self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id))
            update.message.reply_text(
                "You don't have rights to use me! Who the f*** are you?")
            return ConversationHandler.END

    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 login(self, bot, update):
        self.logger.info("Checking if message fits the RegEX")
        username_password = update.message.text
        self.username_password = username_password
        user = update.message.from_user
        if re.match('^[^ ]+ [^ ]+$', username_password):
            username_password_split = username_password.split(" ")
            self.logger.info("Trying to login with given username and password")
            try:
                self.qb.login(username=username_password_split[0], password=username_password_split[1])
                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("Username and Password was wrong")
                update.message.reply_text("Username and Password was wrong\n"
                                          "Please enter a new 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
            return ConversationHandler.END
        else:
            self.logger.info("Typed message does not match what is asked.")
            update.message.reply_text("Please enter a new username and password by seperating them with space.\n"
                                      "And make sure your username or password does not contain "
                                      "any space(\" \") character"
                                      "If you don't know username and password you can"
                                      " '/cancel'. and try again later")
            return self.LOGIN_PROMPT

    def reconnect(self, bot, update):
        user = update.message.from_user
        if self.ip_port_text is not None and not self.logged_in and str(user.id) in bot_auth.user_id:
            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("Trying to log in using previous info")
                    username_password_split = self.username_password.split(" ")
                    self.qb.login(username=username_password_split[0], password=username_password_split[1])
                    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("Logging in with old info was unsuccessful.")
                        update.message.reply_text("Logging in with old info was unsuccessful.\n"
                                                  "You can try again later (/reconnect)\nor type new info using /start")

            except exceptions.ConnectionError:
                self.logger.info("Connection refused.")
                update.message.reply_text("Connection to client IP address is refused."
                                          "\nPlease try again by typing /start"
                                          "\nOr try to /reconnect later.")
        elif str(user) not in bot_auth.user_id:
            self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id))
            update.message.reply_text(
                "You don't have rights to use me! Who the f*** are you?")
        elif self.logged_in:
            self.logger.info("User tried to use reconnect while already logged in.")
            update.message.reply_text("You are already logged in. You don't need to reconnect")

        elif self.ip_port_text is None:
            self.logger.info("User tried to use reconnect without any previous info.")
            update.message.reply_text("You don't have any previous info. \nPlease type /start to connect")

    def cancel(self, bot, update):
        user = update.message.from_user
        self.logger.info("User %s canceled the conversation." % user.first_name)
        update.message.reply_text('Bye! I hope we can talk again some day.')
        self.ip_port_text = None

        return ConversationHandler.END

    def list_downloading_torrents(self, bot, update):
        user = update.message.from_user
        try:
            if str(user.id) in bot_auth.user_id and self.logged_in:
                output = ""
                self.logger.info("%s tried listing downloading." % update.message.from_user)
                if len(self.qb.torrents()) > 0:
                    for torrent in self.qb.torrents(filter="downloading"):
                        output += "%s\n | Size: %.2f GB\n | Download Speed: %.1f MB/s\n | Downloaded: %s%%\n\n" % (torrent["name"],
                            float(torrent["size"]/1073741824),
                            float(torrent["dlspeed"]/1048576),
                            int(torrent["progress"]*100))
                    update.message.reply_text("Torrents currently downloading:\n%s" % output)
                else:
                    update.message.reply_text("There is no torrents to list.")
            elif not self.logged_in:
                self.logger.info("Usage without logging in tried by: %s -- %s" % (user.username, user.id))
                update.message.reply_text(
                    "You should first login by typing /start")
            else:
                self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id))
                update.message.reply_text(
                    "You don't have rights to use me! Who the f*** are you?")
        except exceptions.ConnectionError:
            self.logger.info("Connection is lost. Retrying to connect...")
            self.logged_in = False
            update.message.reply_text(
                "Ups. Connection to qBit Client is lost. \nRetrying to connect with previous info.")
            return self.reconnect(bot=bot, update=update)


# key            | type    | Description
# ---------------------------------------
# hash            string    Torrent hash
# name            string    Torrent name
# size            integer   Torrent size (bytes)
# progress        float     Torrent progress (%/100)
# dlspeed         integer   Torrent download speed (bytes/s)
# upspeed         integer   Torrent upload speed (bytes/s)
# priority        integer   Torrent priority. Returns -1 if queuing is disabled
# num_seeds       integer   Torrent seeds connected to
# num_complete    integer   Torrent seeds in the swarm
# num_leechs      integer   Torrent leechers connected to
# num_incomplete  integer   Torrent leechers in the swarm
# ratio           float     Torrent share ratio. Max ratio value: 9999.
# eta             integer   Torrent ETA (seconds)
# state           string    Torrent state. See possible values here below
# seq_dl          bool      True if sequential download is enabled
# f_l_piece_prio  bool      True if first last piece are prioritized

    def list(self, bot, update):
        user = update.message.from_user
        try:
            if str(user.id) in bot_auth.user_id and self.logged_in:
                output = ""
                self.logger.info("%s tried listing." % update.message.from_user)
                if len(self.qb.torrents()) > 0:
                    for torrent in self.qb.torrents():
                        output += "%s\n | Status: %s\n | Size: %.2f GB\n | Download Speed: %.1f MB/s\n | Downloaded: %s%%\n\n" % (torrent["name"],
                            torrent["state"].upper(),
                            float(torrent["size"]/1073741824),
                            float(torrent["dlspeed"]/1048576),
                            int(torrent["progress"]*100))
                    update.message.reply_text("Torrents currently downloading:\n%s" % output)
                else:
                    update.message.reply_text("There is no torrents to list.")
            elif not self.logged_in:
                self.logger.info("Usage without logging in tried by: %s -- %s" % (user.username, user.id))
                update.message.reply_text(
                    "You should first login by typing /start")
            else:
                self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id))
                update.message.reply_text(
                    "You don't have rights to use me! Who the f*** are you?")
        except exceptions.ConnectionError:
            self.logger.info("Connection is lost. Retrying to connect...")
            self.logged_in = False
            update.message.reply_text(
                "Ups. Connection to qBit Client is lost. \nRetrying to connect with previous info.")
            return self.reconnect(bot=bot, update=update)

    def pause(self, bot, update, args):
        user = update.message.from_user
        try:
            if str(user.id) in bot_auth.user_id and self.logged_in:
                torrents_to_pause = []
                torrents_copy = self.qb.torrents().copy()
                for arg in args:
                    for torrent in torrents_copy:
                        if re.match(arg, torrent["name"], re.IGNORECASE):
                            torrents_copy.remove(torrent)
                            torrents_to_pause.append(str(torrent["hash"]))

                self.qb.pause_multiple(torrents_to_pause)
                self.logger.info("Paused following: %s" % args)
                output = ""
                for torrent in torrents_to_pause:
                    output += "--%s, %s%%\n" % (torrent["name"], int(torrent["progress"]*100))
                update.message.reply_text("Following torrents paused:\n%s" % output)
            elif not self.logged_in:
                self.logger.info("Usage without logging in tried by: %s -- %s" % (user.username, user.id))
                update.message.reply_text(
                    "You should first login by typing /start")
            else:
                self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id))
                update.message.reply_text(
                    "You don't have rights to use me! Who the f*** are you?")
        except exceptions.ConnectionError:
            self.logger.info("Connection is lost. Retrying to connect...")
            self.logged_in = False
            update.message.reply_text(
                "Ups. Connection to qBit Client is lost. \nRetrying to connect with previous info.")
            return self.reconnect(bot=bot, update=update)

    def pause_all(self, bot, update):
        user = update.message.from_user
        try:
            if str(user.id) in bot_auth.user_id:
                self.qb.pause_all()
                self.logger.info("Paused all")
            elif not self.logged_in:
                self.logger.info("Usage without logging in tried by: %s -- %s" % (user.username, user.id))
                update.message.reply_text(
                    "You should first login by typing /start")
            else:
                self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id))
                update.message.reply_text(
                    "You don't have rights to use me! Who the f*** are you?")
        except exceptions.ConnectionError:
            self.logger.info("Connection is lost. Retrying to connect...")
            self.logged_in = False
            update.message.reply_text(
                "Ups. Connection to qBit Client is lost. \nRetrying to connect with previous info.")
            return self.reconnect(bot=bot, update=update)

    def resume(self, bot, update, args):
        user = update.message.from_user
        try:
            if str(user.id) in bot_auth.user_id:
                torrents_to_resume = []
                torrents_copy = self.qb.torrents().copy()
                for arg in args:
                    for torrent in torrents_copy:
                        if re.match(arg, torrent["name"], re.IGNORECASE):
                            torrents_copy.remove(torrent)
                            torrents_to_resume.append(str(torrent["hash"]))

                self.qb.resume_multiple(torrents_to_resume)
                self.logger.info("Paused following: %s" % args)
                output = ""
                for torrent in torrents_to_resume:
                    output += "--%s, %s%%\n" % (torrent["name"], int(torrent["progress"]*100))
                update.message.reply_text("Following torrents resumed:\n%s" % output)
            elif not self.logged_in:
                self.logger.info("Usage without logging in tried by: %s -- %s" % (user.username, user.id))
                update.message.reply_text(
                    "You should first login by typing /start")
            else:
                self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id))
                update.message.reply_text(
                    "You don't have rights to use me! Who the f*** are you?")
        except exceptions.ConnectionError:
            self.logger.info("Connection is lost. Retrying to connect...")
            self.logged_in = False
            update.message.reply_text(
                "Ups. Connection to qBit Client is lost. \nRetrying to connect with previous info.")
            return self.reconnect(bot=bot, update=update)

    def resume_all(self, bot, update, args):
        user = update.message.from_user
        try:
            if str(user.id) in bot_auth.user_id:
                self.qb.resume_all()
                self.logger.info("Resumed all")
            elif not self.logged_in:
                self.logger.info("Usage without logging in tried by: %s -- %s" % (user.username, user.id))
                update.message.reply_text(
                    "You should first login by typing /start")
            else:
                self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id))
                update.message.reply_text(
                    "You don't have rights to use me! Who the f*** are you?")
        except exceptions.ConnectionError:
            self.logger.info("Connection is lost. Retrying to connect...")
            self.logged_in = False
            update.message.reply_text(
                "Ups. Connection to qBit Client is lost. \nRetrying to connect with previous info.")
            return self.reconnect(bot=bot, update=update)

    def add(self, bot, update):
        user = update.message.from_user
        try:
            if str(user.id) in bot_auth.user_id:
                update.message.reply_text("Send .torrent file you want to download.")
                return self.ADD_FILE
            elif not self.logged_in:
                self.logger.info("Usage without logging in tried by: %s -- %s" % (user.username, user.id))
                update.message.reply_text(
                    "You should first login by typing /start")
            else:
                self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id))
                update.message.reply_text(
                    "You don't have rights to use me! Who the f*** are you?")
            return ConversationHandler.END
        except exceptions.ConnectionError:
            self.logger.info("Connection is lost. Retrying to connect...")
            self.logged_in = False
            update.message.reply_text(
                "Ups. Connection to qBit Client is lost. \nRetrying to connect with previous info.")
            self.reconnect(bot=bot, update=update)
            return ConversationHandler.END

    def add_file(self, bot, update):
        try:
            user = update.message.from_user
            if str(user.id) in bot_auth.user_id:
                update.message.reply_text("File received. ")
                file = bot.get_file(file_id=update.message.document.file_id)
                # print(file)
                document = update.message.document
                file_extension = document.file_name.split(".")[-1]
                if re.match("^torrent$", file_extension, re.IGNORECASE):
                    # file.
                    file.download(custom_path="%s/%s" % (self.download_folder, document.file_name))
                    file_read = open("%s/%s" % (self.download_folder, document.file_name), "rb")
                    self.logger.info("Torrent file downloaded to %s" % self.download_folder)
                    self.qb.download_from_file(file_read)
                    self.logger.info("Started downloading %s" % document.file_name)
                    update.message.reply_text("Downloading the file.")
            elif not self.logged_in:
                self.logger.info("Usage without logging in tried by: %s -- %s" % (user.username, user.id))
                update.message.reply_text(
                    "You should first login by typing /start")
            else:
                self.logger.info("Unauthorized usage tried by: %s -- %s" % (user.username, user.id))
                update.message.reply_text(
                    "You don't have rights to use me! Who the f*** are you?")

            return ConversationHandler.END
        except exceptions.ConnectionError:
            self.logger.info("Connection is lost. Retrying to connect...")
            self.logged_in = False
            update.message.reply_text(
                "Ups. Connection to qBit Client is lost. \nRetrying to connect with previous info.")
            self.reconnect(bot=bot, update=update)
            return ConversationHandler.END

    def help(self, bot, update):
        update.message.reply_text("Simple bot for using qBit client via Telegram.\n"
                                  "Available commands:\n"
                                  "/start\n"
                                  "--- Start logging in process with new info.\n"
                                  "/reconnect\n"
                                  "--- Try to reconnect using previously entered info.\n"
                                  "/pause NAME1 NAME2 NAME3 ...\n"
                                  "--- Pause torrents : NAME1, NAME2 etc.\n"
                                  "/pause_all\n"
                                  "--- Pause all torrents.\n"
                                  "/resume NAME1 NAME2 NAME3 ...\n"
                                  "--- Resume torrents : NAME1, NAME2 etc.\n"
                                  "/resume_all\n"
                                  "--- Resume all torrents. \n"
                                  "/list\n"
                                  "--- List all torrents.\n"
                                  "/downloading\n"
                                  "--- List all torrents with Downloading status\n"
                                  "/add\n"
                                  "--- Start downloading of a new .torrent file.\n"
                                  "/help\n"
                                  "--- Display this message.\n"
                                  "PS: NAME1 NAME2 etc. does *NOT* have to be FULL name.")

    def error(self, bot, update, error):
        self.logger.warn('Update "%s" caused error "%s"' % (update, error))

    def main(self):
        # Create the EventHandler and pass it your bot's token.
        updater = Updater(self.TOKEN)

        # Get the dispatcher to register handlers
        dp = updater.dispatcher

        # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO
        conv_handler_start = ConversationHandler(
            entry_points=[CommandHandler('start', self.start)],

            states={
                self.IP: [MessageHandler(Filters.text, self.ip)],
                self.LOGIN_PROMPT: [MessageHandler(Filters.text, self.login)]
            },

            fallbacks=[CommandHandler('cancel', self.cancel)]
        )
        conv_handler_torrent = ConversationHandler(
            entry_points=[CommandHandler("add", self.add)],

            states={
                self.ADD_FILE: [MessageHandler(Filters.document, self.add_file)]
            },

            fallbacks=[CommandHandler('cancel', self.cancel)]
        )
        # dp.add_handler()
        dp.add_handler(conv_handler_start)
        dp.add_handler(conv_handler_torrent)
        dp.add_handler(CommandHandler("downloading", self.list_downloading_torrents))
        dp.add_handler(CommandHandler("list", self.list))
        dp.add_handler(CommandHandler("pause", self.pause, pass_args=True))
        dp.add_handler(CommandHandler("resume", self.resume, pass_args=True))
        dp.add_handler(CommandHandler("pause_all", self.pause_all))
        dp.add_handler(CommandHandler("resume_all", self.resume_all, pass_args=True))
        dp.add_handler(CommandHandler("reconnect", self.reconnect))
        dp.add_handler(CommandHandler("help", self.help))
        # log all errors
        dp.add_error_handler(self.error)

        # Start the Bot
        updater.start_polling()

        # Run the bot until the you presses Ctrl-C or the process receives SIGINT,
        # SIGTERM or SIGABRT. This should be used most of the time, since
        # start_polling() is non-blocking and will stop the bot gracefully.
        updater.idle()
Exemplo n.º 25
0
Arquivo: qbt.py Projeto: llzx373/MyNAS
def list_torrents():
    bt = Client(qbittorrent_url)
    bt.login(qbittorrent_username, qbittorrent_password)
    return json_return(bt.torrents())
Exemplo n.º 26
0
import subprocess
from qbittorrent import Client

qb = Client('http://127.0.0.1:8090/')

torrents = qb.torrents()

while True:
    for torrent in torrents:
        if len(qb.torrents(filter='downloading')) == 0 and 'Connected' in subprocess.run(['nordvpn','status'], stdout=subprocess.PIPE).stdout.decode('utf-8'):
            subprocess.run(['nordvpn','disconnect'])
        if len(qb.torrents(filter='downloading')) > 0 and 'Disconnected' in subprocess.run(['nordvpn','status'], stdout=subprocess.PIPE).stdout.decode('utf-8'):
            subprocess.run(['nordvpn', 'connect'])
Exemplo n.º 27
0
from qbittorrent import Client
import re

qb = Client("@ de redirection du client")  #à modifier
qb.login("username", "password")  #à modifier

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()
Exemplo n.º 28
0
class QBittorrentClient(BTClientBase):
    def __init__(self,
                 rpc_address,
                 rpc_port,
                 username,
                 password,
                 config={'use_https': False}):
        self.rpc_address = rpc_address
        self.rpc_port = rpc_port
        self.username = username
        self.password = password

        if 'use_https' in config:
            self.use_https = config['use_https']
        else:
            self.use_https = False

        self.rpc_addr = str(rpc_address) + ':' + str(rpc_port) + '/'
        if self.use_https:
            self.rpc_addr = 'https://' + self.rpc_addr
        else:
            self.rpc_addr = 'http://' + self.rpc_addr

        self.client = Client(self.rpc_addr)
        self.connected = False

    def connect(self):
        login_ret = self.client.login(username=self.username,
                                      password=self.password)

        if login_ret is None:
            self.connected = True
            ret = ClientRet(ret_type=2)
        else:
            ret = ClientRet(ret_type=-2)

        return ret

    def add_torrent(self, torrent_path, download_path=None):
        if not self.connected:
            return ClientRet(ret_type=-2)

        abs_torrent_path = str(Path(torrent_path).resolve())
        buf = open(abs_torrent_path, 'rb')

        if download_path is None:
            try:
                api_ret = self.client.download_from_file(buf)
                if 'Ok.' in api_ret:
                    buf.close()
                    info_hash = torf.Torrent.read(abs_torrent_path).infohash

                    ret = ClientRet(ret_type=3, ret_value=info_hash)
                else:
                    ret = ClientRet(ret_type=-3)
            except:
                ret = ClientRet(ret_type=-3)
            finally:
                return ret
        else:
            try:
                abs_download_path = str(Path(download_path).resolve())
                api_ret = self.client.download_from_file(
                    buf, save_path=abs_download_path)
                if 'Ok.' in api_ret:
                    buf.close()
                    info_hash = torf.Torrent.read(abs_torrent_path).infohash

                    ret = ClientRet(ret_type=3, ret_value=info_hash)
                else:
                    ret = ClientRet(ret_type=-3)
            except:
                ret = ClientRet(ret_type=-3)
            finally:
                return ret

    def list_torrents(self):
        if not self.connected:
            return ClientRet(ret_type=-2)

        torrent_list = self.client.torrents()
        session_status = {}
        for torrent in torrent_list:
            is_finished = math.isclose(torrent['progress'], 1)
            torrent_status = TorrentStatus(torrent_id=torrent['hash'],
                                           is_finished=is_finished,
                                           name=torrent['name'])

            session_status[torrent['hash']] = torrent_status

        ret = ClientRet(ret_type=4, ret_value=session_status)

        return ret

    def get_torrent_status(self, idx):
        if not self.connected:
            return ClientRet(ret_type=-2)

        tlist = self.client.torrents()
        for torrent in tlist:
            if idx == torrent[
                    'hash']:  # No progress info in get_torrent() method, really...
                is_finished = math.isclose(torrent['progress'], 1)
                torrent_status = TorrentStatus(torrent_id=torrent['hash'],
                                               is_finished=is_finished,
                                               name=torrent['name'])

                ret = ClientRet(ret_type=6, ret_value=torrent_status)
                return ret

        return ClientRet(ret_type=-6)

    def del_torrent(self, idx, remove_data=True):
        if not self.connected:
            return ClientRet(ret_type=-2)

        try:
            if remove_data:
                self.client.delete_permanently(idx)
            else:
                self.client.delete(idx)
            ret = ClientRet(ret_type=5)
        except:
            ret = ClientRet(ret_type=-5)
        finally:
            return ret

    def disconnect(self):
        if self.connected:
            self.client.logout()
            self.connected = False
        ret = ClientRet(ret_type=0)
        return ret
Exemplo n.º 29
0
    seeder = soup_result_td[11].text
    
    return download_id, size, seeder

t=login()

for tr in getFreeTorrent(t,"sticky_top"):
    if 'Free' in str(tr.contents[3]) and 'hitandrun' not in str(tr.contents[3]):
        download_id, size, seeder=getInfo(tr)
        download_link = "https://ourbits.club/download.php?id=" + download_id + "&passkey=" + passkey + "&https=0"
        result = my_set.find_one({"id":download_id})
        link_list = [download_link]
        if result is None:
            qb.download_from_link(link_list)            
            my_set.insert_one({"id":download_id,"href":download_link,"size":size,"seeder":seeder,"top":1,"deal":0})
        else:
            my_set.update_one({"id":download_id},{"$set":{"seeder":seeder}})

for tr in getFreeTorrent(t,"sticky_normal"):
    if 'Free' in str(tr.contents[3]) and 'hitandrun' not in str(tr.contents[3]):
        download_id, size, seeder=getInfo(tr)
        download_link = "https://ourbits.club/download.php?id=" + download_id + "&passkey=" + passkey + "&https=0"
        link_list = [download_link]
        result = my_set.find_one({"id":download_id})
        if result is None:
            if len(qb.torrents(filter='downloading')) < 2:
                qb.download_from_link(link_list)                
            my_set.insert_one({"id":download_id,"href":download_link,"size":size,"seeder":seeder,"top":0,"deal":0}) 
        else:
            my_set.update_one({"id":download_id},{"$set":{"seeder":seeder}})            
class QBittorrentDownloader:
    """
    Class that uses the qBittorrent Server API to download torrents
    """
    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

    @classmethod
    def from_config(cls) -> "QBittorrentDownloader":
        """
        :return: A QBittorrentDownloader object based on the stored
                 configuration files
        """
        config = Config.load()
        return cls(config.qbittorrent_address, config.qbittorrent_username,
                   config.qbittorrent_password,
                   config.qbittorrent_download_dir)

    def download(self, torrents: List[TorrentDownload]):
        """
        Downloads a list of torrent files
        :param torrents: The torrents to download
        :return: None
        """
        for torrent in torrents:
            torrent_info = torrent.torrent_info

            print(f"Downloading Torrent: {torrent_info.filename}")

            if torrent_info.magnet_link is not None:
                self.client.download_from_link(torrent_info.magnet_link)
            else:
                assert torrent_info.torrent_file is not None
                torrent_file = torrent_info.torrent_file
                if not os.path.isfile(torrent_file):
                    torrent_file = "/tmp/torrentdltemp.torrent"
                    content = requests.get(torrent_info.torrent_file).content
                    with open(torrent_file, "wb") as f:
                        f.write(content)
                with open(torrent_file, "rb") as f:
                    self.client.download_from_file(f)

            time.sleep(1)

            while len(self.client.torrents()) > 0:
                for active in self.client.torrents():
                    if active["state"] not in [
                            "downloading", "metaDL", "stalledDL"
                    ]:
                        print("Done.     ")
                        torrent_path = os.path.join(self.download_dir,
                                                    active["name"])

                        if os.path.isdir(torrent_path):
                            children = [
                                os.path.join(torrent_path, x)
                                for x in os.listdir(torrent_path)
                            ]
                            children.sort(key=lambda x: os.path.getsize(x),
                                          reverse=True)
                            torrent_path = children[0]
                            ext = torrent_path.rsplit(".", 1)[1]
                            torrent.add_extension(ext)

                        self.client.delete(active["hash"])

                        if os.path.isdir(torrent.destination):
                            shutil.move(
                                torrent_path,
                                os.path.join(torrent.destination,
                                             os.path.basename(torrent_path)))
                        else:
                            shutil.move(torrent_path, torrent.destination)
                    else:
                        print(f"{(100 * active['progress']):.2f}%", end="\r")

                time.sleep(1)
Exemplo n.º 31
0
    else:
        return "WTF"


qb = Client("http://localhost:8080/")

downloadSpeed = qb.global_transfer_info["dl_info_speed"]
uploadSpeed = qb.global_transfer_info["up_info_speed"]

downloadSessionData = qb.global_transfer_info["dl_info_data"]
uploadSessionData = qb.global_transfer_info["up_info_data"]

table_data = [["qBittorrent-nox"],
              ["qBittorrent-nox Version:", qb.qbittorrent_version],
              ["Total number of torrents: ",
               len(qb.torrents(filter="all"))],
              [
                  "Total number of Completed torrents: ",
                  len(qb.torrents(filter="completed"))
              ],
              [
                  "Total number of Downloading torrents: ",
                  len(qb.torrents(filter="downloading"))
              ],
              [
                  "Total number of Paused torrents: ",
                  len(qb.torrents(filter="paused"))
              ], ["Download Speed: ",
                  speed_value(downloadSpeed)],
              ["Upload Speed: ", speed_value(uploadSpeed)],
              ["Session Download: ",
Exemplo n.º 32
0
class AutoTorrent:
    def __init__(self):
        self.init_google_sheets()
        self.init_qb()
        self.downloading = {}

    def init_google_sheets(self):
        creds = None
        # The file token.pickle stores the user's access and refresh tokens, and is
        # created automatically when the authorization flow completes for the first
        # time.
        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)
        # If there are no (valid) credentials available, let the user log in.
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'credentials.json', SCOPES)
                creds = flow.run_local_server(port=0)
            # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)
        self.google_sheets = build('sheets', 'v4', credentials=creds)

    def init_qb(self):
        self.qb = TorrentClient("http://127.0.0.1:8080/")
        self.qb.login("admin", "adminadmin")

    def get_movies(self):
        sheet = self.google_sheets.spreadsheets()
        result = sheet.values().get(spreadsheetId=SPREADSHEET_ID,
                                    range=RANGE_NAME).execute()
        values = result.get('values', [])

        if not values:
            print('No data found.')
        filtered = filter(
            lambda m: m[0] in ["No Descargada", "Auto Descargando"] and
            (len(m) < 5 or m[4] not in ["No", "Pocos Seeds"]), values)
        movies = map(lambda m: Movie(m[1], m[2]), filtered)
        return movies

    def download_movie(self, movie):
        torrent = movie.get_torrent()
        if not torrent:
            print("    Torrent not found for {}. Skipping".format(movie))
            self.update_movie_yts(movie, "No")
            return
        magnet = torrent.magnet
        path = movie.local_path
        if not os.path.isdir(path):
            os.mkdir(path)
        self.qb.download_from_link(magnet, savepath=path)
        self.update_movie(movie, "Auto Descargando")
        for t in self.qb.torrents():
            if os.path.normpath(t["save_path"]) == os.path.normpath(path):
                torrent_hash = t["hash"]
                break
        self.downloading[torrent_hash] = movie
        print("    Started downloading {}".format(movie))

    def update_movie(self, movie, status):
        sheet = self.google_sheets.spreadsheets()
        result = sheet.values().get(spreadsheetId=SPREADSHEET_ID,
                                    range=RANGE_NAME).execute()
        values = list(result.get('values', []))
        for value in values:
            if value[1] == movie.name and int(value[2]) == movie.year:
                value[0] = status
        body = {'values': values}
        sheet.values().update(spreadsheetId=SPREADSHEET_ID,
                              range=RANGE_NAME,
                              valueInputOption=VALUE_INPUT_OPTION,
                              body=body).execute()

    def update_movie_yts(self, movie, yts):
        sheet = self.google_sheets.spreadsheets()
        result = sheet.values().get(spreadsheetId=SPREADSHEET_ID,
                                    range=RANGE_NAME).execute()
        values = list(result.get('values', []))
        for value in values:
            if value[1] == movie.name and int(value[2]) == movie.year:
                if len(value) == 4:
                    value.append(yts)
                else:
                    value[4] = yts
        body = {'values': values}
        sheet.values().update(spreadsheetId=SPREADSHEET_ID,
                              range=RANGE_NAME,
                              valueInputOption=VALUE_INPUT_OPTION,
                              body=body).execute()

    def should_download(self):
        current_torrents = len(self.qb.torrents(filter="downloading"))
        less_than_max = current_torrents < MAX_CONCURRENT_DOWNLOADS
        just_started = len(self.downloading) < MAX_CONCURRENT_DOWNLOADS
        return less_than_max or just_started

    def start(self):
        movies = self.get_movies()
        while True:
            sleep(1)
            self.clean_torrents()
            if not self.should_download():
                continue
            movie = next(movies)
            print(movie)
            self.download_movie(movie)

    def clean_torrents(self):
        timed_out = []
        done = []
        for torrent in self.qb.torrents():
            if torrent["progress"] == 1:
                done.append(torrent["hash"])
            elif is_timed_out(torrent):
                timed_out.append(torrent["hash"])
        for h in timed_out:
            if h not in self.downloading:
                continue
            movie = self.downloading[h]
            print("{} timed out. Removing".format(movie))
            self.update_movie(movie, "No Descargada")
            self.update_movie_yts(movie, "Pocos Seeds")
            self.qb.delete(h)
            movie.delete_folder()
        for h in done:
            if h not in self.downloading:
                continue
            movie = self.downloading[h]
            self.update_movie(movie, "Descargada")
            self.qb.delete(h)
            movie.clean_folder()
            movie.move_to_drive()
            print("{} finished downloading. Moving to Google Drive".format(
                movie))