Exemple #1
0
    def test_connection(data):
        ''' Tests connectivity to Transmission
        data: dict of Transmission server information

        Return True on success or str error message on failure
        '''

        host = data['transmissionhost']
        port = data['transmissionport']
        user = data['transmissionuser']
        password = data['transmissionpass']

        try:
            client = transmissionrpc.Client(host,
                                            port,
                                            user=user,
                                            password=password)
            if type(client.rpc_version) == int:
                return True
            else:
                return 'Unable to connect.'
        except (SystemExit, KeyboardInterrupt):
            raise
        except Exception, e:
            logging.error(u'Transmission test_connection', exc_info=True)
            return '{}.'.format(e)
Exemple #2
0
    def cancel_download(downloadid):
        ''' Cancels download in client
        downloadid: int download id

        Returns bool
        '''
        logging.info('Cancelling download # {}'.format(downloadid))

        conf = core.CONFIG['Downloader']['Torrent']['Transmission']

        host = conf['host']
        port = conf['port']
        user = conf['user']
        password = conf['pass']

        client = transmissionrpc.Client(host,
                                        port,
                                        user=user,
                                        password=password)

        try:
            client.remove_torrent([downloadid], delete_data=True)
            return True
        except Exception as e:
            logging.error('Unable to cancel download.', exc_info=True)
            return False
def set_torrent_limits(downloadid):
    ''' Set seedIdleLimit, seedIdleMode, seedRatioLimit and seedRatioMode
    according to transmission settings

    downloadid: int download id

    Returns bool
    '''
    conf = core.CONFIG['Downloader']['Torrent']['Transmission']
    idle_limit = conf.get('seedidlelimit', '')
    ratio_limit = conf.get('seedratiolimit', '')

    args = {}
    if idle_limit == -1:
        args['seedIdleMode'] = 2
        idle_limit_desc = 'unlimited'
    elif idle_limit == '':
        idle_limit_desc = 'global setting'
    else:
        args['seedIdleMode'] = 1
        args['seedIdleLimit'] = idle_limit_desc = int(idle_limit * 60)

    if ratio_limit == -1:
        args['seedRatioMode'] = 2
        ratio_limit_desc = 'unlimited'
    elif ratio_limit == '':
        ratio_limit_desc = 'global setting'
    else:
        args['seedRatioMode'] = 1
        args['seedRatioLimit'] = ratio_limit_desc = ratio_limit

    logging.info(
        'Setting idle limit to {} and ratio limit to {} for torrent #{}'.
        format(idle_limit_desc, ratio_limit_desc, downloadid))

    if args:
        host = conf['host']
        port = conf['port']
        user = conf['user']
        password = conf['pass']

        try:
            client = transmissionrpc.Client(host,
                                            port,
                                            user=user,
                                            password=password)
            client.change_torrent(downloadid, **args)
            return True
        except (SystemExit, KeyboardInterrupt):
            raise
        except Exception as e:
            logging.error(
                'Unable to change torrent #{} in TransmissionRPC.'.format(
                    downloadid),
                exc_info=True)
            return False
    else:
        return True
Exemple #4
0
    def add_torrent(data):
        ''' Adds torrent or magnet to Transmission
        data: dict of torrrent/magnet information

        Adds torrents to /default/path/<category>

        Returns dict {'response': True, 'download_id': 'id'}
                     {'response': False', 'error': 'exception'}

        '''

        conf = core.CONFIG['Downloader']['Torrent']['Transmission']

        host = conf['host']
        port = conf['port']
        user = conf['user']
        password = conf['pass']

        client = transmissionrpc.Client(host,
                                        port,
                                        user=user,
                                        password=password)

        url = data['torrentfile']
        paused = conf['addpaused']
        bandwidthPriority = conf['priority']
        category = conf['category']

        priority_keys = {'Low': '-1', 'Normal': '0', 'High': '1'}

        bandwidthPriority = priority_keys[conf['priority']]

        download_dir = None
        if category:
            d = client.get_session().__dict__['_fields']['download_dir'][0]
            d_components = d.split('/')
            d_components.append(category)

            download_dir = '/'.join(d_components)

        try:
            download = client.add_torrent(url,
                                          paused=paused,
                                          bandwidthPriority=bandwidthPriority,
                                          download_dir=download_dir,
                                          timeout=30)
            download_id = download.hashString
            logging.info(
                'Torrent sent to TransmissionRPC - downloadid {}'.format(
                    download_id))
            return {'response': True, 'downloadid': download_id}
        except (SystemExit, KeyboardInterrupt):
            raise
        except Exception, e:
            logging.error(u'Unable to send torrent to TransmissionRPC.',
                          exc_info=True)
            return {'response': False, 'error': str(e)}
def get_torrents_status(stalled_for=None, progress={}):
    ''' Get torrents and calculate status

    Returns list
    '''
    conf = core.CONFIG['Downloader']['Torrent']['Transmission']

    logging.info('Get torrents from transmissionrpc')

    host = conf['host']
    port = conf['port']
    user = conf['user']
    password = conf['pass']

    try:
        torrents = []

        client = transmissionrpc.Client(host,
                                        port,
                                        user=user,
                                        password=password)

        now = int(datetime.timestamp(datetime.now()))
        fields = [
            'id', 'hashString', 'isFinished', 'isStalled', 'status',
            'percentDone', 'name', 'downloadedEver'
        ]
        for torrent in client.get_torrents(arguments=fields):
            data = {
                'hash': torrent._fields['hashString'].value,
                'status': torrent.status,
                'name': torrent._get_name_string(),
                'progress': torrent._fields['downloadedEver'].value
            }
            if torrent.status == 'stopped' and torrent._fields[
                    'isFinished'].value:
                data['status'] = 'finished'
            elif torrent.status == 'downloading' and stalled_for and data[
                    'hash'] in progress:
                torrent_progress = progress[data['hash']]
                if data['progress'] == torrent_progress[
                        'progress'] and now > torrent_progress[
                            'time'] + stalled_for * 3600:
                    data['status'] = 'stalled'
            torrents.append(data)

        return torrents
    except (SystemExit, KeyboardInterrupt):
        raise
    except Exception as e:
        logging.error('Unable to list torrents from TransmissionRPC.',
                      exc_info=True)
        return []
Exemple #6
0
def sendTORRENT(torrent):

    ###################################################################################################

    params = {}
    change_params = {}

    ###################################################################################################

    if sickbeard.TORRENT_PAUSED:
        params['paused'] = 1

    ###################################################################################################

    if not (sickbeard.TORRENT_PATH == ''):
        params['download_dir'] = sickbeard.TORRENT_PATH

    ###################################################################################################

    if not (sickbeard.TORRENT_RATIO == ''):
        change_params['seedRatioLimit'] = sickbeard.TORRENT_RATIO
    else:
        change_params['seedRatioMode'] = 1

    ###################################################################################################

    host = sickbeard.TORRENT_HOST
    if not host.startswith('http'):
        host = 'http://' + sickbeard.TORRENT_HOST
    host = urlparse(host)
    session = None
    if hasattr(torrent.provider, 'session'):
        session = torrent.provider.session
    else:
        session = requests.Session()

    ###################################################################################################

    if session:
        ###################################################################################################

        try:
            address = host.hostname
            if host.scheme:
                address = host.scheme + '://' + address
            if host.port:
                address += ':' + str(host.port)
            if host.path in ['', '/']:
                address += '/transmission/rpc'
            else:
                address += host.path
            tc = transmissionrpc.Client(address, host.port,
                                        sickbeard.TORRENT_USERNAME,
                                        sickbeard.TORRENT_PASSWORD)
            logger.log("[Transmission] Login With Transmission, Successful.",
                       logger.DEBUG)
        except transmissionrpc.TransmissionError, e:
            logger.log("[Transmission] Login With Transmission, Failed.",
                       logger.ERROR)
            return False

        ###################################################################################################

        # [GV] My fix for User agent on torcache.  <<<<<<< HEAD
        #if not magnet:
        #    try:
        #        headers = {'User-Agent': 'Mozilla', 'referer': torrent.url}
        #        r = session.get(torrent.url, verify=False, headers=headers)
        ###################################################################################################

        if not torrent.url.startswith("magnet:"):
            try:
                headers = {
                    'User-Agent': sickbeard.common.USER_AGENT,
                    'Referer': torrent.url
                }

                r = session.get(torrent.url,
                                verify=False,
                                headers=headers,
                                timeout=60)
                logger.log("[Transmission] Succesfully Downloaded Torrent...",
                           logger.DEBUG)
            except (requests.exceptions.ConnectionError,
                    requests.exceptions.HTTPError), e:
                logger.log("[Transmission] Download Error  - " + str(e),
                           logger.ERROR)
                return False
Exemple #7
0
def testAuthentication(host, username, password):

    try:
        if not host.startswith('http'):
            host = 'http://' + host
        host = urlparse(host)
    except Exception, e:
        return False, u"[Transmission] Host properties are not filled in correctly."

    try:
        address = host.hostname
        if host.scheme:
            address = host.scheme + '://' + address
        if host.port:
            address += ':' + str(host.port)
        if host.path in ['', '/']:
            address += '/transmission/rpc'
        else:
            address += host.path
        tc = transmissionrpc.Client(address, host.port,
                                    sickbeard.TORRENT_USERNAME,
                                    sickbeard.TORRENT_PASSWORD)
        return True, u"[Transmission] Success: Connected and Authenticated. RPC version: " + str(
            tc.rpc_version)
    except Exception, e:
        return False, u"[Transmission] testAuthentication() Error: " + str(e)


###################################################################################################
def sendTORRENT(torrent):

    ###################################################################################################

    magnet = 0
    params = {}
    change_params = {}

    ###################################################################################################

    if sickbeard.TORRENT_PAUSED:
        params['paused'] = 1

    ###################################################################################################

    if not (sickbeard.TORRENT_PATH == ''):
        params['download_dir'] = sickbeard.TORRENT_PATH

    ###################################################################################################

    if not (sickbeard.TORRENT_RATIO == ''):
        change_params['seedRatioLimit'] = sickbeard.TORRENT_RATIO
    else:
        change_params['seedRatioMode'] = 1

    ###################################################################################################

    host = sickbeard.TORRENT_HOST
    if not host.startswith('http'):
        host = 'http://' + sickbeard.TORRENT_HOST
    host = urlparse(host)
    session = None
    if hasattr(torrent.provider, 'session'):
        session = torrent.provider.session
    else:
        session = requests.Session()

    if torrent.url.startswith("magnet:"):
        magnet = 1

    ###################################################################################################

    if session:
        ###################################################################################################

        try:
            address = host.hostname
            if host.scheme:
                address = host.scheme + '://' + address
            if host.port:
                address += ':' + str(host.port)
            if host.path in ['', '/']:
                address += '/transmission/rpc'
            else:
                address += host.path
            tc = transmissionrpc.Client(address, host.port,
                                        sickbeard.TORRENT_USERNAME,
                                        sickbeard.TORRENT_PASSWORD)
            logger.log("[Transmission] Login With Transmission, Successful.",
                       logger.DEBUG)
        except transmissionrpc.TransmissionError, e:
            logger.log("[Transmission] Login With Transmission, Failed.",
                       logger.ERROR)
            return False

        ###################################################################################################

        if not magnet:
            try:
                r = session.get(torrent.url, verify=False)
                logger.log("[Transmission] Succesfully Downloaded Torrent...",
                           logger.DEBUG)
            except (requests.exceptions.ConnectionError,
                    requests.exceptions.HTTPError), e:
                logger.log("[Transmission] Download Error  - " + ex(e),
                           logger.ERROR)
                return False
Exemple #9
0
        ###################################################################################################

    else:
        logger.log("[Transmission] Error No Requests Session.", logger.ERROR)
        return False, u"[Transmission] Error No Requests Session."
    logger.log("[Transmission] Completed Transaction.", logger.DEBUG)
    return True, u"[Transmission] Completed Transction."


###################################################################################################


def testAuthentication(host, username, password):

    try:
        host = urlparse(host)
    except Exception, e:
        return False, u"[Transmission] Host properties are not filled in correctly."

    try:
        tc = transmissionrpc.Client(host.hostname, host.port,
                                    sickbeard.TORRENT_USERNAME,
                                    sickbeard.TORRENT_PASSWORD)
        return True, u"[Transmission] Success: Connected and Authenticated. RPC version: " + str(
            tc.rpc_version)
    except Exception, e:
        return False, u"[Transmission] testAuthentication() Error: " + ex(e)


###################################################################################################