Exemplo n.º 1
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.º 2
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)
    # Run a qbittorrent action after conversion.
    if settings.qBittorrent['actionafter']:
        # currently only support resuming or deleting torrent
        if settings.qBittorrent['actionafter'] == 'resume':
            log.debug("Sending action %s to qBittorrent" %
                      settings.qBittorrent['actionafter'])
            qb.resume(torrent_hash)
        elif settings.qBittorrent['actionafter'] == 'delete':
            # this will delete the torrent from qBittorrent but it WILL NOT delete the data
            log.debug("Sending action %s to qBittorrent" %
                      settings.qBittorrent['actionafter'])
            qb.delete(torrent_hash)
        elif settings.qBittorrent['actionafter'] == 'deletedata':
            # this will delete the torrent from qBittorrent and delete data
            log.debug("Sending action %s to qBittorrent" %
                      settings.qBittorrent['actionafter'])
            qb.delete_permanently(torrent_hash)

    if delete_dir:
        if os.path.exists(delete_dir):
            try:
                os.rmdir(delete_dir)
                log.debug("Successfully removed tempoary directory %s." %
                          delete_dir)
            except:
                log.exception("Unable to delete temporary directory")
except:
    log.exception("Unexpected exception.")
    sys.exit(1)
Exemplo n.º 4
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.º 5
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)
class my_qBittorrent(object):
    def __init__(self,config):
        self.config = config
        username = self.config.get('global','webui_username')
        password = self.config.get('global','webui_password')
        webui_url = self.config.get('global','webui_url')
        self.torrentHash = []
        self.torrentData = []
        self.client = Client(webui_url)
        self.client.login(username, password)
        self.getTorrentInfo()
        self.getTorrentSeedTime()
    
    def getTorrentInfo(self):
        self.torrents = self.client.torrents(filter = 'completed')
        for torrent in self.torrents:
            self.torrentHash.append(torrent['hash'])
        return
        
    def getTorrentSeedTime(self):
        for torrentHash in self.torrentHash:
            torrentDict = {'hash':torrentHash,'info':self.client.get_torrent(torrentHash)}
            self.torrentData.append(torrentDict)
        return
    
    def deleteTorrentPerm(self,torrentHash):
        self.client.delete_permanently(torrentHash)
        return
    
    def getSingleTorrentInfo(self,torrentHash):
        torrentDict = {'hash':torrentHash,'info':self.client.get_torrent(torrentHash)}
        return torrentDict
    
    def seedTimeFilter(self,torrentHash,seedTime=1):
        seedTimeConv = seedTime*3600
        torrentInfo = self.getSingleTorrentInfo(torrentHash)
        seedingTime = torrentInfo['info']['seeding_time']
        if seedingTime > seedTimeConv:
            return True
        return False
    
    def trackerFilter(self,torrentHash,tracker = None):
        #add the tracker exception
        if tracker:
            rawInfo = self.client.get_torrent_trackers(torrentHash)
            torrentTracker = rawInfo[0]['url']
            if tracker in torrentTracker:
                return True
        return False
    
    def addedTimeFilter(self,torrentHash,addedTime = 1):
        #default day
        torrentInfo = self.getSingleTorrentInfo(torrentHash)
        addedTimeConv = addedTime*24*3600
        timeElapsed = torrentInfo['info']['time_elapsed']
        if timeElapsed > addedTimeConv:
            return True
        return False
    
    def integratedFilterAndExecute(self,torrentHash,tacker = None, lowerLimit = None):
        seed_time = self.config.getint('filter','seeding_time')
        if not lowerLimit:
            if not self.trackerFilter(torrentHash, tracker = tacker):
                if self.seedTimeFilter(torrentHash, seedTime = seed_time):
                    self.deleteTorrentPerm(torrentHash)
                    
        else:
            if not self.trackerFilter(torrentHash, tracker = tacker):
                if self.seedTimeFilter(torrentHash, seedTime = seed_time) and self.filterUploadSpeed(torrentHash, lowerLimit = lowerLimit):
                    self.deleteTorrentPerm(torrentHash)
    
    def Traversal(self):
        tracker = self.config.get('filter','exception_tracker')
        lowerLimit = self.config.get('filter','upload_speed')
        for torrentHash in self.torrentHash:
            self.integratedFilterAndExecute(torrentHash,tracker,lowerLimit = lowerLimit)

    def getUploadSpeed(self,torrentHash):
        torrentInfo = self.getSingleTorrentInfo(torrentHash)
        torrentUpSpeed = torrentInfo['up_speed']
        return torrentUpSpeed

    def filterUploadSpeed(self,torrentHash,lowerLimit = None):
        torrentUpSpeed = self.getUploadSpeed(torrentHash)
        if lowerLimit:
            if torrentUpSpeed < lowerLimit:
                return True
            else:
                return False
        return False