Esempio n. 1
0
def toggle_rpc(alias, enabled=True):
    """Enables or disables a given RPC.

    :param alias: str - PRC alias
    :param enabled: bool - flag to enable or disable
    :return:
    """
    rpc = RPCClassesRegistry.get(alias)
    if rpc is not None:
        TorrtConfig.update({'rpc': {alias: {'enabled': enabled}}})
        LOGGER.info('RPC `%s` enabled = %s', alias, enabled)
    else:
        LOGGER.info('RPC `%s` class is not registered', alias)
Esempio n. 2
0
def toggle_rpc(alias, enabled=True):
    """Enables or disables a given RPC.

    :param alias: str - PRC alias
    :param enabled: bool - flag to enable or disable
    :return:
    """
    rpc = RPCClassesRegistry.get(alias)
    if rpc is not None:
        TorrtConfig.update({'rpc': {alias: {'enabled': enabled}}})
        LOGGER.info('RPC `%s` enabled = %s', alias, enabled)
    else:
        LOGGER.info('RPC `%s` class is not registered', alias)
Esempio n. 3
0
def init_object_registries():
    """Initializes RPC and tracker objects registries with settings
    from configuration file.

    :return:
    """
    LOGGER.debug('Initializing objects registries from configuration file ...')
    cfg = TorrtConfig.load()

    for alias, rpc_settings in cfg['rpc'].items():
        rpc = RPCClassesRegistry.get(alias)
        if rpc is not None:
            obj = rpc.spawn_with_settings(rpc_settings)
            obj.register()

    for domain, tracker_settings in cfg['trackers'].items():
        tracker = TrackerClassesRegistry.get(domain)
        if tracker is not None:
            obj = tracker.spawn_with_settings(tracker_settings)
            obj.register()
Esempio n. 4
0
def init_object_registries():
    """Initializes RPC and tracker objects registries with settings
    from configuration file.

    :return:
    """
    LOGGER.debug('Initializing objects registries from configuration file ...')
    cfg = TorrtConfig.load()

    for alias, rpc_settings in cfg['rpc'].items():
        rpc = RPCClassesRegistry.get(alias)
        if rpc is not None:
            obj = rpc.spawn_with_settings(rpc_settings)
            obj.register()

    for domain, tracker_settings in cfg['trackers'].items():
        tracker = TrackerClassesRegistry.get(domain)
        if tracker is not None:
            obj = tracker.spawn_with_settings(tracker_settings)
            obj.register()
Esempio n. 5
0
def configure_rpc(rpc_alias, settings_dict):
    """Configures RPC using given settings.
    Saves successful configuration.

    :param rpc_alias: RPC alias
    :param settings_dict: settings dictionary to configure RPC with
    :return:
    """
    LOGGER.info('Configuring `%s` RPC ...', rpc_alias)

    rpc_class = RPCClassesRegistry.get(rpc_alias)
    if rpc_class is not None:
        rpc_obj = rpc_class.spawn_with_settings(settings_dict)
        version = rpc_obj.method_get_version()
        if version:
            rpc_obj.enabled = True
            rpc_obj.save_settings()
            LOGGER.info('RPC `%s` is configured', rpc_alias)
        else:
            LOGGER.error('RPC `%s` configuration failed. Check your settings', rpc_alias)
    else:
        LOGGER.error('RPC `%s` is unknown', rpc_alias)
Esempio n. 6
0
def configure_rpc(rpc_alias, settings_dict):
    """Configures RPC using given settings.
    Saves successful configuration.

    :param rpc_alias: RPC alias
    :param settings_dict: settings dictionary to configure RPC with
    :return:
    """
    LOGGER.info('Configuring `%s` RPC ...', rpc_alias)

    rpc_class = RPCClassesRegistry.get(rpc_alias)
    if rpc_class is not None:
        rpc_obj = rpc_class.spawn_with_settings(settings_dict)
        version = rpc_obj.method_get_version()
        if version:
            rpc_obj.enabled = True
            rpc_obj.save_settings()
            LOGGER.info('RPC `%s` is configured', rpc_alias)
        else:
            LOGGER.error('RPC `%s` configuration failed. Check your settings', rpc_alias)
    else:
        LOGGER.error('RPC `%s` is unknown', rpc_alias)
Esempio n. 7
0
        for torrent_info in result['torrents']:
            self.normalize_field_names(torrent_info)
        return result['torrents']

    def method_add_torrent(self, torrent, download_to=None):
        args = {
            'metainfo': base64encode(torrent),
        }
        if download_to is not None:
            args['download-dir'] = download_to
        return self.query(self.build_request_payload('torrent-add', args))  # torrent-added

    def method_remove_torrent(self, hash_str, with_data=False):
        args = {
            'ids': [hash_str],
            'delete-local-data': with_data
        }
        self.query(self.build_request_payload('torrent-remove', args))
        return True

    def method_get_version(self):
        result = self.query(self.build_request_payload('session-get', ['rpc-version-minimum']))
        return result['rpc-version-minimum']


class TransmissionRPCException(TorrtRPCException):
    """"""


RPCClassesRegistry.add(TransmissionRPC)
Esempio n. 8
0
                torrents_info[torrent_data[0]] = {
                    'hash': torrent_data[0],
                    'name': torrent_data[2],
                    'download_to': torrent_data[26]
                }

        return torrents_info

    def method_add_torrent(self, torrent, download_to=None):
        # NB: `download_to` is ignored, as existing API approach to it is crippled.
        file_data = {'torrent_file': ('from_torrt.torrent', torrent)}
        return self.query(self.build_params(action='add-file'), file_data)

    def method_remove_torrent(self, hash_str, with_data=False):
        action = 'remove'
        if with_data:
            action = 'removedata'
        self.query(self.build_params(action=action, params={'hash': hash_str}))
        return True

    def method_get_version(self):
        result = self.query(self.build_params(action='getversion'))
        return result['version']['ui_version']


class UTorrentRPCException(TorrtRPCException):
    """"""


RPCClassesRegistry.add(UTorrentRPC)
Esempio n. 9
0
File: main.py Progetto: riorao/torrt
def process_commands():

    def settings_dict_from_list(lst):
        settings_dict = {}
        for s in lst:
            splitted = s.split('=')
            settings_dict[splitted[0]] = splitted[1]
        return settings_dict

    arg_parser = argparse.ArgumentParser('torrt', description='Automates torrent updates for you.', version='.'.join(map(str, VERSION)))
    arg_parser.add_argument('--verbose', help='Switch to show debug messages', dest='verbose', action='store_true')

    subp_main = arg_parser.add_subparsers(title='Supported commands', dest='command')

    subp_main.add_parser('list_rpc', help='Shows known RPCs aliases')
    subp_main.add_parser('list_trackers', help='Shows known trackers aliases')
    subp_main.add_parser('list_torrents', help='Shows torrents registered for updates')

    parser_configure_tracker = subp_main.add_parser('configure_tracker', help='Sets torrent tracker settings (login credentials, etc.)', description='E.g.: configure_tracker rutracker.org username=idle password=pSW0rt')
    parser_configure_tracker.add_argument('tracker_alias', help='Tracker alias (usually domain) to apply settings to')
    parser_configure_tracker.add_argument('settings', help='Settings string, format: setting1=val1 setting2=val2. Supported settings (any of): username, password', nargs='*')

    parser_configure_rpc = subp_main.add_parser('configure_rpc', help='Sets RPCs settings (login credentials, etc.)', description='E.g.: configure_rpc transmission user=idle password=pSW0rt')
    parser_configure_rpc.add_argument('rpc_alias', help='RPC alias to apply settings to')
    parser_configure_rpc.add_argument('settings', help='Settings string, format: setting1=val1 setting2=val2. Supported settings (any of): url, host, port, user, password', nargs='*')

    parser_walk = subp_main.add_parser('walk', help='Walks through registered torrents and performs automatic updates')
    parser_walk.add_argument('-f', help='Forces walk. Forced walks do not respect walk interval settings', dest='forced', action='store_true')

    parser_set_interval = subp_main.add_parser('set_walk_interval', help='Sets an interval *in hours* between consecutive torrent updates checks')
    parser_set_interval.add_argument('walk_interval', help='Interval *in hours* between consecutive torrent updates checks')

    parser_enable_rpc = subp_main.add_parser('enable_rpc', help='Enables RPC by its alias')
    parser_enable_rpc.add_argument('alias', help='Alias of RPC to enable')

    parser_disable_rpc = subp_main.add_parser('disable_rpc', help='Disables RPC by its alias')
    parser_disable_rpc.add_argument('alias', help='Alias of RPC to disable')

    parser_add_torrent = subp_main.add_parser('add_torrent', help='Adds torrent from an URL both to torrt and torrent clients')
    parser_add_torrent.add_argument('url', help='URL to download torrent from')
    parser_add_torrent.add_argument('-d', help='Destination path to download torrent contents into (in filesystem where torrent client daemon works)', dest='download_to', default=None)

    parser_remove_torrent = subp_main.add_parser('remove_torrent', help='Removes torrent by its hash both from torrt and torrent clients')
    parser_remove_torrent.add_argument('hash', help='Torrent identifying hash')
    parser_remove_torrent.add_argument('-d', help='If set data downloaded for torrent will also be removed', dest='delete_data', action='store_true')

    parser_register_torrent = subp_main.add_parser('register_torrent', help='Registers torrent within torrt by its hash (for torrents already existing at torrent clients)')
    parser_register_torrent.add_argument('hash', help='Torrent identifying hash')

    parser_unregister_torrent = subp_main.add_parser('unregister_torrent', help='Unregisters torrent from torrt by its hash')
    parser_unregister_torrent.add_argument('hash', help='Torrent identifying hash')

    args = arg_parser.parse_args()
    args = vars(args)

    loggin_level = logging.INFO
    if args['verbose']:
        loggin_level = logging.DEBUG

    configure_logging(loggin_level)
    bootstrap()

    if args['command'] == 'enable_rpc':
        toggle_rpc(args['alias'], True)

    elif args['command'] == 'disable_rpc':
        toggle_rpc(args['alias'], False)

    elif args['command'] == 'list_trackers':

        for tracker_alias, tracker in TrackerClassesRegistry.get().items():
            LOGGER.info(tracker_alias)

    elif args['command'] == 'list_rpc':
        rpc_statuses = {}

        for rpc_alias, rpc in RPCClassesRegistry.get().items():
            rpc_statuses[rpc_alias] = 'unconfigured'

        for rpc_alias, rpc in RPCObjectsRegistry.get().items():
            rpc_statuses[rpc_alias] = 'enabled' if rpc.enabled else 'disabled'

        for rpc_alias, rpc_status in rpc_statuses.items():
            LOGGER.info('%s\t status=%s' % (rpc_alias, rpc_status))

    elif args['command'] == 'list_torrents':
        for torrent_hash, torrent_data in get_registerd_torrents().items():
            LOGGER.info('%s\t%s' % (torrent_hash, torrent_data['name']))

    elif args['command'] == 'walk':
        walk(forced=args['forced'], silent=True)

    elif args['command'] == 'set_walk_interval':
        set_walk_interval(args['walk_interval'])

    elif args['command'] == 'add_torrent':
        add_torrent_from_url(args['url'], args['download_to'])

    elif args['command'] == 'remove_torrent':
        remove_torrent(args['hash'], args['delete_data'])

    elif args['command'] == 'register_torrent':
        register_torrent(args['hash'])

    elif args['command'] == 'unregister_torrent':
        unregister_torrent(args['hash'])

    elif args['command'] == 'configure_rpc':
        configure_rpc(args['rpc_alias'], settings_dict_from_list(args['settings']))

    elif args['command'] == 'configure_tracker':
        configure_tracker(args['tracker_alias'], settings_dict_from_list(args['settings']))
Esempio n. 10
0
        return torrents_info

    def method_add_torrent(self, torrent, download_to=None):

        file_data = {'torrents': torrent}
        if download_to is not None:
            file_data.update({'savepath': download_to})

        return self.auth_query(self.build_params(action='add_torrent'),
                               file_data)

    def method_remove_torrent(self, hash_str, with_data=False):
        action = 'rem_torrent'
        if with_data:
            action = 'rem_torrent_with_data'

        data = {'hashes': hash_str}
        self.auth_query(self.build_params(action, {'data': data}))
        return True

    def method_get_version(self):
        result = self.auth_query(self.build_params(action='api_version_path'))
        return result.text


class QBittorrentRPCException(TorrtRPCException):
    """"""


RPCClassesRegistry.add(QBittorrentRPC)
Esempio n. 11
0
    def method_add_torrent(self, torrent, download_to=None):

        file_data = {'torrents': torrent}
        if download_to is not None:
            file_data.update({'savepath': download_to})

        return self.auth_query(self.build_params(action='add_torrent'), file_data)

    def method_remove_torrent(self, hash_str, with_data=False):
        action = 'rem_torrent'
        if with_data:
            action = 'rem_torrent_with_data'

        data = {
            'hashes': hash_str
        }
        self.auth_query(self.build_params(action, {'data': data}))
        return True

    def method_get_version(self):
        result = self.auth_query(self.build_params(action='api_version_path'))
        return result.text


class QBittorrentRPCException(TorrtRPCException):
    """"""


RPCClassesRegistry.add(QBittorrentRPC)
Esempio n. 12
0
def process_commands():
    def settings_dict_from_list(lst):
        settings_dict = {}
        for s in lst:
            splitted = s.split('=')
            settings_dict[splitted[0]] = splitted[1]
        return settings_dict

    arg_parser = argparse.ArgumentParser(
        'torrt', description='Automates torrent updates for you.')
    arg_parser.add_argument('--version',
                            action='version',
                            version='%(prog)s ' + '.'.join(map(str, VERSION)))

    subp_main = arg_parser.add_subparsers(title='Supported commands',
                                          dest='command')

    subp_main.add_parser('list_rpc', help='Shows known RPCs aliases')
    subp_main.add_parser('list_trackers', help='Shows known trackers aliases')
    subp_main.add_parser('list_torrents',
                         help='Shows torrents registered for updates')
    subp_main.add_parser('list_notifiers', help='Shows configured notifiers')

    parser_configure_tracker = subp_main.add_parser(
        'configure_tracker',
        help='Sets torrent tracker settings (login credentials, etc.)',
        description=
        'E.g.: configure_tracker rutracker.org username=idle password=pSW0rt')
    parser_configure_tracker.add_argument(
        'tracker_alias',
        help='Tracker alias (usually domain) to apply settings to')
    parser_configure_tracker.add_argument(
        'settings',
        help='Settings string, format: setting1=val1 setting2=val2. '
        'Supported settings (any of): username, password',
        nargs='*')

    parser_configure_rpc = subp_main.add_parser(
        'configure_rpc',
        help='Sets RPCs settings (login credentials, etc.)',
        description='E.g.: configure_rpc transmission user=idle password=pSW0rt'
    )
    parser_configure_rpc.add_argument('rpc_alias',
                                      help='RPC alias to apply settings to')
    parser_configure_rpc.add_argument(
        'settings',
        help='Settings string, format: setting1=val1 setting2=val2. '
        'Supported settings (any of): url, host, port, user, password',
        nargs='*')

    parser_configure_notifier = subp_main.add_parser(
        'configure_notifier',
        help='Sets Notifiers settings (smtp credentials, etc.)',
        description=
        'E.g.: configure_notifier email [email protected] user=idle password=pSW0rt'
    )
    parser_configure_notifier.add_argument(
        'notifier_alias', help='Notifier alias to apply settings to')
    parser_configure_notifier.add_argument(
        'settings',
        help='Settings string, format: setting1=val1 setting2=val2. '
        'Supported settings for email notifier (any of): email, host, port, use_tls, user, password.'
        'Supported settings for telegram notifier: token, chat_id.',
        nargs='*')

    parser_configure_bot = subp_main.add_parser(
        'configure_bot',
        help='Sets Bot settings (token, etc.)',
        description='E.g.: configure_bot telegram token=YourBotSuperToken')
    parser_configure_bot.add_argument('bot_alias',
                                      help='Bot alias to apply settings to')
    parser_configure_bot.add_argument(
        'settings',
        help='Settings string, format: setting1=val1 setting2=val2. '
        'Supported settings for telegram bot: token.',
        nargs='*')

    parser_walk = subp_main.add_parser(
        'walk',
        help='Walks through registered torrents and performs automatic updates'
    )
    parser_walk.add_argument(
        '-f',
        help='Forces walk. Forced walks do not respect walk interval settings',
        dest='forced',
        action='store_true')
    parser_walk.add_argument(
        '--dump',
        help=
        'Dump web pages scraped by torrt into current or a given directory',
        dest='dump')

    parser_run_bots = subp_main.add_parser('run_bots',
                                           help='Run registered bots')
    parser_run_bots.add_argument('aliases',
                                 help='Bots to run aliases',
                                 nargs='*')

    parser_set_interval = subp_main.add_parser(
        'set_walk_interval',
        help=
        'Sets an interval *in hours* between consecutive torrent updates checks'
    )
    parser_set_interval.add_argument(
        'walk_interval',
        help='Interval *in hours* between consecutive torrent updates checks')

    parser_enable_rpc = subp_main.add_parser('enable_rpc',
                                             help='Enables RPC by its alias')
    parser_enable_rpc.add_argument('alias', help='Alias of RPC to enable')

    parser_disable_rpc = subp_main.add_parser('disable_rpc',
                                              help='Disables RPC by its alias')
    parser_disable_rpc.add_argument('alias', help='Alias of RPC to disable')

    parser_add_torrent = subp_main.add_parser(
        'add_torrent',
        help='Adds torrent from an URL both to torrt and torrent clients')
    parser_add_torrent.add_argument('url', help='URL to download torrent from')
    parser_add_torrent.add_argument(
        '-d',
        help=
        'Destination path to download torrent contents into (in filesystem where torrent client daemon works)',
        dest='download_to',
        default=None)
    parser_add_torrent.add_argument(
        '--dump',
        help=
        'Dump web pages scraped by torrt into current or a given directory',
        dest='dump')

    parser_remove_torrent = subp_main.add_parser(
        'remove_torrent',
        help='Removes torrent by its hash both from torrt and torrent clients')
    parser_remove_torrent.add_argument('hash', help='Torrent identifying hash')
    parser_remove_torrent.add_argument(
        '-d',
        help='If set data downloaded for torrent will also be removed',
        dest='delete_data',
        action='store_true')

    parser_register_torrent = subp_main.add_parser(
        'register_torrent',
        help=
        'Registers torrent within torrt by its hash (for torrents already existing at torrent clients)'
    )
    parser_register_torrent.add_argument('hash',
                                         help='Torrent identifying hash')
    parser_register_torrent.add_argument('-u',
                                         dest='url',
                                         default=None,
                                         help='URL to download torrent from')

    parser_unregister_torrent = subp_main.add_parser(
        'unregister_torrent',
        help='Unregisters torrent from torrt by its hash')
    parser_unregister_torrent.add_argument('hash',
                                           help='Torrent identifying hash')

    parser_remove_notifier = subp_main.add_parser(
        'remove_notifier', help='Remove configured notifier by its alias')
    parser_remove_notifier.add_argument('alias',
                                        help='Alias of notifier to remove')

    for parser in subp_main.choices.values():
        parser.add_argument('--verbose',
                            help='Switch to show debug messages',
                            dest='verbose',
                            action='store_true')

    args = arg_parser.parse_args()
    args = vars(args)

    configure_logging(logging.DEBUG if args.get('verbose') else logging.INFO)

    bootstrap()

    dump_into = args.get('dump')

    if dump_into:
        GlobalParam.set('dump_into', path.abspath(dump_into))

    if args['command'] == 'enable_rpc':
        toggle_rpc(args['alias'], True)

    elif args['command'] == 'disable_rpc':
        toggle_rpc(args['alias'], False)

    elif args['command'] == 'list_trackers':

        for tracker_alias, _ in TrackerClassesRegistry.get().items():
            LOGGER.info(tracker_alias)

    elif args['command'] == 'list_rpc':
        rpc_statuses = {}

        for rpc_alias, rpc in RPCClassesRegistry.get().items():
            rpc_statuses[rpc_alias] = 'unconfigured'

        for rpc_alias, rpc in RPCObjectsRegistry.get().items():
            rpc_statuses[rpc_alias] = 'enabled' if rpc.enabled else 'disabled'

        for rpc_alias, rpc_status in rpc_statuses.items():
            LOGGER.info(f'{rpc_alias}\t status={rpc_status}')

    elif args['command'] == 'list_torrents':
        for torrent_hash, torrent_data in get_registered_torrents().items():
            LOGGER.info(f"{torrent_hash}\t{torrent_data['name']}")

    elif args['command'] == 'list_notifiers':
        notifiers = {}
        for notifier_alias in NotifierClassesRegistry.get().keys():
            notifiers[notifier_alias] = 'unconfigured'

        for notifier_alias in NotifierObjectsRegistry.get().keys():
            notifiers[notifier_alias] = 'enabled'

        for notifier_alias, notifier_status in notifiers.items():
            LOGGER.info(f"{notifier_alias}\t status={notifier_status}")

    elif args['command'] == 'walk':
        walk(forced=args['forced'], silent=True)

    elif args['command'] == 'set_walk_interval':
        set_walk_interval(args['walk_interval'])

    elif args['command'] == 'add_torrent':
        add_torrent_from_url(args['url'], args['download_to'])

    elif args['command'] == 'remove_torrent':
        remove_torrent(args['hash'], args['delete_data'])

    elif args['command'] == 'register_torrent':
        register_torrent(args['hash'], url=args['url'])

    elif args['command'] == 'unregister_torrent':
        unregister_torrent(args['hash'])

    elif args['command'] == 'configure_rpc':
        configure_rpc(args['rpc_alias'],
                      settings_dict_from_list(args['settings']))

    elif args['command'] == 'configure_tracker':
        configure_tracker(args['tracker_alias'],
                          settings_dict_from_list(args['settings']))

    elif args['command'] == 'configure_notifier':
        configure_notifier(args['notifier_alias'],
                           settings_dict_from_list(args['settings']))

    elif args['command'] == 'remove_notifier':
        remove_notifier(args['alias'])

    elif args['command'] == 'configure_bot':
        configure_bot(args['bot_alias'],
                      settings_dict_from_list(args['settings']))

    elif args['command'] == 'run_bots':
        run_bots(args['aliases'])
Esempio n. 13
0
                                       [hashes, fields]))

        for torrent_info in result['torrents']:
            self.normalize_field_names(torrent_info)

        return result['torrents']

    def method_add_torrent(self, torrent, download_to=None):
        torrent_dump = base64encode(torrent).decode('utf-8')
        return self.query(
            self.build_request_payload(
                'webapi.add_torrent',
                [torrent_dump, {
                    'download_location': download_to
                }]))

    def method_remove_torrent(self, hash_str, with_data=False):
        return self.query(
            self.build_request_payload('webapi.remove_torrent',
                                       [hash_str, with_data]))

    def method_get_version(self):
        return self.query(self.build_request_payload('webapi.get_api_version'))


class DelugeRPCException(TorrtRPCException):
    """"""


RPCClassesRegistry.add(DelugeRPC)
Esempio n. 14
0
def process_commands():
    def settings_dict_from_list(lst):
        settings_dict = {}
        for s in lst:
            splitted = s.split('=')
            settings_dict[splitted[0]] = splitted[1]
        return settings_dict

    arg_parser = argparse.ArgumentParser(
        'torrt',
        description='Automates torrent updates for you.',
        version='.'.join(map(str, VERSION)))
    arg_parser.add_argument('--verbose',
                            help='Switch to show debug messages',
                            dest='verbose',
                            action='store_true')

    subp_main = arg_parser.add_subparsers(title='Supported commands',
                                          dest='command')

    subp_main.add_parser('list_rpc', help='Shows known RPCs aliases')
    subp_main.add_parser('list_trackers', help='Shows known trackers aliases')
    subp_main.add_parser('list_torrents',
                         help='Shows torrents registered for updates')

    parser_configure_tracker = subp_main.add_parser(
        'configure_tracker',
        help='Sets torrent tracker settings (login credentials, etc.)',
        description=
        'E.g.: configure_tracker rutracker.org username=idle password=pSW0rt')
    parser_configure_tracker.add_argument(
        'tracker_alias',
        help='Tracker alias (usually domain) to apply settings to')
    parser_configure_tracker.add_argument(
        'settings',
        help='Settings string, format: setting1=val1 setting2=val2. '
        'Supported settings (any of): username, password',
        nargs='*')

    parser_configure_rpc = subp_main.add_parser(
        'configure_rpc',
        help='Sets RPCs settings (login credentials, etc.)',
        description='E.g.: configure_rpc transmission user=idle password=pSW0rt'
    )
    parser_configure_rpc.add_argument('rpc_alias',
                                      help='RPC alias to apply settings to')
    parser_configure_rpc.add_argument(
        'settings',
        help='Settings string, format: setting1=val1 setting2=val2. '
        'Supported settings (any of): url, host, port, user, password',
        nargs='*')

    parser_walk = subp_main.add_parser(
        'walk',
        help='Walks through registered torrents and performs automatic updates'
    )
    parser_walk.add_argument(
        '-f',
        help='Forces walk. Forced walks do not respect walk interval settings',
        dest='forced',
        action='store_true')

    parser_set_interval = subp_main.add_parser(
        'set_walk_interval',
        help=
        'Sets an interval *in hours* between consecutive torrent updates checks'
    )
    parser_set_interval.add_argument(
        'walk_interval',
        help='Interval *in hours* between consecutive torrent updates checks')

    parser_enable_rpc = subp_main.add_parser('enable_rpc',
                                             help='Enables RPC by its alias')
    parser_enable_rpc.add_argument('alias', help='Alias of RPC to enable')

    parser_disable_rpc = subp_main.add_parser('disable_rpc',
                                              help='Disables RPC by its alias')
    parser_disable_rpc.add_argument('alias', help='Alias of RPC to disable')

    parser_add_torrent = subp_main.add_parser(
        'add_torrent',
        help='Adds torrent from an URL both to torrt and torrent clients')
    parser_add_torrent.add_argument('url', help='URL to download torrent from')
    parser_add_torrent.add_argument(
        '-d',
        help=
        'Destination path to download torrent contents into (in filesystem where torrent client daemon works)',
        dest='download_to',
        default=None)

    parser_remove_torrent = subp_main.add_parser(
        'remove_torrent',
        help='Removes torrent by its hash both from torrt and torrent clients')
    parser_remove_torrent.add_argument('hash', help='Torrent identifying hash')
    parser_remove_torrent.add_argument(
        '-d',
        help='If set data downloaded for torrent will also be removed',
        dest='delete_data',
        action='store_true')

    parser_register_torrent = subp_main.add_parser(
        'register_torrent',
        help=
        'Registers torrent within torrt by its hash (for torrents already existing at torrent clients)'
    )
    parser_register_torrent.add_argument('hash',
                                         help='Torrent identifying hash')

    parser_unregister_torrent = subp_main.add_parser(
        'unregister_torrent',
        help='Unregisters torrent from torrt by its hash')
    parser_unregister_torrent.add_argument('hash',
                                           help='Torrent identifying hash')

    args = arg_parser.parse_args()
    args = vars(args)

    loggin_level = logging.INFO
    if args['verbose']:
        loggin_level = logging.DEBUG

    configure_logging(loggin_level)
    bootstrap()

    if args['command'] == 'enable_rpc':
        toggle_rpc(args['alias'], True)

    elif args['command'] == 'disable_rpc':
        toggle_rpc(args['alias'], False)

    elif args['command'] == 'list_trackers':

        for tracker_alias, _ in TrackerClassesRegistry.get().items():
            LOGGER.info(tracker_alias)

    elif args['command'] == 'list_rpc':
        rpc_statuses = {}

        for rpc_alias, rpc in RPCClassesRegistry.get().items():
            rpc_statuses[rpc_alias] = 'unconfigured'

        for rpc_alias, rpc in RPCObjectsRegistry.get().items():
            rpc_statuses[rpc_alias] = 'enabled' if rpc.enabled else 'disabled'

        for rpc_alias, rpc_status in rpc_statuses.items():
            LOGGER.info('%s\t status=%s', rpc_alias, rpc_status)

    elif args['command'] == 'list_torrents':
        for torrent_hash, torrent_data in get_registerd_torrents().items():
            LOGGER.info('%s\t%s', torrent_hash, torrent_data['name'])

    elif args['command'] == 'walk':
        walk(forced=args['forced'], silent=True)

    elif args['command'] == 'set_walk_interval':
        set_walk_interval(args['walk_interval'])

    elif args['command'] == 'add_torrent':
        add_torrent_from_url(args['url'], args['download_to'])

    elif args['command'] == 'remove_torrent':
        remove_torrent(args['hash'], args['delete_data'])

    elif args['command'] == 'register_torrent':
        register_torrent(args['hash'])

    elif args['command'] == 'unregister_torrent':
        unregister_torrent(args['hash'])

    elif args['command'] == 'configure_rpc':
        configure_rpc(args['rpc_alias'],
                      settings_dict_from_list(args['settings']))

    elif args['command'] == 'configure_tracker':
        configure_tracker(args['tracker_alias'],
                          settings_dict_from_list(args['settings']))
Esempio n. 15
0
        result = self.query(self.build_request_payload('torrent-get', args))
        for torrent_info in result['torrents']:
            self.normalize_field_names(torrent_info)
        return result['torrents']

    def method_add_torrent(self, torrent, download_to=None):
        args = {
            'metainfo': base64encode(torrent),
        }
        if download_to is not None:
            args['download-dir'] = download_to
        return self.query(self.build_request_payload('torrent-add',
                                                     args))  # torrent-added

    def method_remove_torrent(self, hash_str, with_data=False):
        args = {'ids': [hash_str], 'delete-local-data': with_data}
        self.query(self.build_request_payload('torrent-remove', args))
        return True

    def method_get_version(self):
        result = self.query(
            self.build_request_payload('session-get', ['rpc-version-minimum']))
        return result['rpc-version-minimum']


class TransmissionRPCException(TorrtRPCException):
    """"""


RPCClassesRegistry.add(TransmissionRPC)
Esempio n. 16
0
                torrents_info[torrent_data[0]] = {
                    'hash': torrent_data[0],
                    'name': torrent_data[2],
                    'download_to': torrent_data[26]
                }

        return torrents_info

    def method_add_torrent(self, torrent, download_to=None):
        # NB: `download_to` is ignored, as existing API approach to it is crippled.
        file_data = {'torrent_file': ('from_torrt.torrent', torrent)}
        return self.query(self.build_params(action='add-file'), file_data)

    def method_remove_torrent(self, hash_str, with_data=False):
        action = 'remove'
        if with_data:
            action = 'removedata'
        self.query(self.build_params(action=action, params={'hash': hash_str}))
        return True

    def method_get_version(self):
        result = self.query(self.build_params(action='getversion'))
        return result['version']['ui_version']


class UTorrentRPCException(TorrtRPCException):
    """"""


RPCClassesRegistry.add(UTorrentRPC)
Esempio n. 17
0
    def method_get_torrents(self, hashes=None):
        fields = ['name', 'comment', 'hash', 'save_path']
        result = self.query(self.build_request_payload('webapi.get_torrents',  [hashes, fields]))

        for torrent_info in result['torrents']:
            self.normalize_field_names(torrent_info)

        return result['torrents']

    def method_add_torrent(self, torrent, download_to=None):
        torrent_dump = base64encode(torrent).decode('utf-8')
        return self.query(
            self.build_request_payload(
                'webapi.add_torrent', [torrent_dump, {'download_location': download_to}]
            )
        )

    def method_remove_torrent(self, hash_str, with_data=False):
        return self.query(self.build_request_payload('webapi.remove_torrent', [hash_str, with_data]))

    def method_get_version(self):
        return self.query(self.build_request_payload('webapi.get_api_version'))


class DelugeRPCException(TorrtRPCException):
    """"""


RPCClassesRegistry.add(DelugeRPC)
Esempio n. 18
0
def process_commands():
    def settings_dict_from_list(lst):
        settings_dict = {}
        for s in lst:
            splitted = s.split('=')
            settings_dict[splitted[0]] = splitted[1]
        return settings_dict

    arg_parser = argparse.ArgumentParser('torrt', description='Automates torrent updates for you.')
    arg_parser.add_argument('--version', action='version', version='%(prog)s ' + '.'.join(map(str, VERSION)))

    subp_main = arg_parser.add_subparsers(title='Supported commands', dest='command')

    subp_main.add_parser('list_rpc', help='Shows known RPCs aliases')
    subp_main.add_parser('list_trackers', help='Shows known trackers aliases')
    subp_main.add_parser('list_torrents', help='Shows torrents registered for updates')
    subp_main.add_parser('list_notifiers', help='Shows configured notifiers')

    parser_configure_tracker = subp_main.add_parser(
        'configure_tracker', help='Sets torrent tracker settings (login credentials, etc.)',
        description='E.g.: configure_tracker rutracker.org username=idle password=pSW0rt')
    parser_configure_tracker.add_argument(
        'tracker_alias', help='Tracker alias (usually domain) to apply settings to')
    parser_configure_tracker.add_argument(
        'settings',
        help='Settings string, format: setting1=val1 setting2=val2. '
             'Supported settings (any of): username, password',
        nargs='*')

    parser_configure_rpc = subp_main.add_parser(
        'configure_rpc', help='Sets RPCs settings (login credentials, etc.)',
        description='E.g.: configure_rpc transmission user=idle password=pSW0rt')
    parser_configure_rpc.add_argument(
        'rpc_alias', help='RPC alias to apply settings to')
    parser_configure_rpc.add_argument(
        'settings',
        help='Settings string, format: setting1=val1 setting2=val2. '
             'Supported settings (any of): url, host, port, user, password',
        nargs='*')

    parser_configure_notifier = subp_main.add_parser(
        'configure_notifier', help='Sets Notifiers settings (smtp credentials, etc.)',
        description='E.g.: configure_notifier email [email protected] user=idle password=pSW0rt')
    parser_configure_notifier.add_argument(
        'notifier_alias', help='Notifier alias to apply settings to')
    parser_configure_notifier.add_argument(
        'settings',
        help='Settings string, format: setting1=val1 setting2=val2. '
             'Supported settings for email notifier (any of): email, host, port, use_tls, user, password.'
             'Supported settings for telegram notifier: token, chat_id.',
        nargs='*')

    parser_configure_bot = subp_main.add_parser(
        'configure_bot', help='Sets Bot settings (token, etc.)',
        description='E.g.: configure_bot telegram token=YourBotSuperToken')
    parser_configure_bot.add_argument(
        'bot_alias', help='Bot alias to apply settings to')
    parser_configure_bot.add_argument(
        'settings',
        help='Settings string, format: setting1=val1 setting2=val2. '
             'Supported settings for telegram bot: token.',
        nargs='*')

    parser_walk = subp_main.add_parser(
        'walk', help='Walks through registered torrents and performs automatic updates')
    parser_walk.add_argument(
        '-f', help='Forces walk. Forced walks do not respect walk interval settings', dest='forced',
        action='store_true')
    parser_walk.add_argument(
        '--dump', help='Dump web pages scraped by torrt into current or a given directory', dest='dump')

    parser_run_bots = subp_main.add_parser(
        'run_bots', help='Run registered bots')
    parser_run_bots.add_argument(
        'aliases', help='Bots to run aliases',
        nargs='*')

    parser_set_interval = subp_main.add_parser(
        'set_walk_interval', help='Sets an interval *in hours* between consecutive torrent updates checks')
    parser_set_interval.add_argument(
        'walk_interval', help='Interval *in hours* between consecutive torrent updates checks')

    parser_enable_rpc = subp_main.add_parser('enable_rpc', help='Enables RPC by its alias')
    parser_enable_rpc.add_argument('alias', help='Alias of RPC to enable')

    parser_disable_rpc = subp_main.add_parser('disable_rpc', help='Disables RPC by its alias')
    parser_disable_rpc.add_argument('alias', help='Alias of RPC to disable')

    parser_add_torrent = subp_main.add_parser(
        'add_torrent', help='Adds torrent from an URL both to torrt and torrent clients')
    parser_add_torrent.add_argument(
        'url', help='URL to download torrent from')
    parser_add_torrent.add_argument(
        '-d',
        help='Destination path to download torrent contents into (in filesystem where torrent client daemon works)',
        dest='download_to', default=None)

    parser_remove_torrent = subp_main.add_parser(
        'remove_torrent', help='Removes torrent by its hash both from torrt and torrent clients')
    parser_remove_torrent.add_argument(
        'hash', help='Torrent identifying hash')
    parser_remove_torrent.add_argument(
        '-d', help='If set data downloaded for torrent will also be removed',
        dest='delete_data', action='store_true')

    parser_register_torrent = subp_main.add_parser(
        'register_torrent',
        help='Registers torrent within torrt by its hash (for torrents already existing at torrent clients)')
    parser_register_torrent.add_argument(
        'hash', help='Torrent identifying hash')
    parser_register_torrent.add_argument(
        '-u', dest='url', default=None, help='URL to download torrent from')

    parser_unregister_torrent = subp_main.add_parser(
        'unregister_torrent', help='Unregisters torrent from torrt by its hash')
    parser_unregister_torrent.add_argument(
        'hash', help='Torrent identifying hash')

    parser_remove_notifier = subp_main.add_parser(
        'remove_notifier', help='Remove configured notifier by its alias')
    parser_remove_notifier.add_argument('alias', help='Alias of notifier to remove')

    for parser in subp_main.choices.values():
        parser.add_argument('--verbose', help='Switch to show debug messages', dest='verbose', action='store_true')

    args = arg_parser.parse_args()
    args = vars(args)

    configure_logging(logging.DEBUG if args.get('verbose') else logging.INFO)

    bootstrap()

    if args['command'] == 'enable_rpc':
        toggle_rpc(args['alias'], True)

    elif args['command'] == 'disable_rpc':
        toggle_rpc(args['alias'], False)

    elif args['command'] == 'list_trackers':

        for tracker_alias, _ in TrackerClassesRegistry.get().items():
            LOGGER.info(tracker_alias)

    elif args['command'] == 'list_rpc':
        rpc_statuses = {}

        for rpc_alias, rpc in RPCClassesRegistry.get().items():
            rpc_statuses[rpc_alias] = 'unconfigured'

        for rpc_alias, rpc in RPCObjectsRegistry.get().items():
            rpc_statuses[rpc_alias] = 'enabled' if rpc.enabled else 'disabled'

        for rpc_alias, rpc_status in rpc_statuses.items():
            LOGGER.info('%s\t status=%s', rpc_alias, rpc_status)

    elif args['command'] == 'list_torrents':
        for torrent_hash, torrent_data in get_registered_torrents().items():
            LOGGER.info('%s\t%s', torrent_hash, torrent_data['name'])

    elif args['command'] == 'list_notifiers':
        notifiers = {}
        for notifier_alias in NotifierClassesRegistry.get().keys():
            notifiers[notifier_alias] = 'unconfigured'

        for notifier_alias in NotifierObjectsRegistry.get().keys():
            notifiers[notifier_alias] = 'enabled'

        for notifier_alias, notifier_status in notifiers.items():
            LOGGER.info('%s\t status=%s', notifier_alias, notifier_status)

    elif args['command'] == 'walk':
        dump_into = args.get('dump')

        if dump_into:
            GlobalParam.set('dump_into', path.abspath(dump_into))

        walk(forced=args['forced'], silent=True)

    elif args['command'] == 'set_walk_interval':
        set_walk_interval(args['walk_interval'])

    elif args['command'] == 'add_torrent':
        add_torrent_from_url(args['url'], args['download_to'])

    elif args['command'] == 'remove_torrent':
        remove_torrent(args['hash'], args['delete_data'])

    elif args['command'] == 'register_torrent':
        register_torrent(args['hash'], url=args['url'])

    elif args['command'] == 'unregister_torrent':
        unregister_torrent(args['hash'])

    elif args['command'] == 'configure_rpc':
        configure_rpc(args['rpc_alias'], settings_dict_from_list(args['settings']))

    elif args['command'] == 'configure_tracker':
        configure_tracker(args['tracker_alias'], settings_dict_from_list(args['settings']))

    elif args['command'] == 'configure_notifier':
        configure_notifier(args['notifier_alias'], settings_dict_from_list(args['settings']))

    elif args['command'] == 'remove_notifier':
        remove_notifier(args['alias'])

    elif args['command'] == 'configure_bot':
        configure_bot(args['bot_alias'], settings_dict_from_list(args['settings']))

    elif args['command'] == 'run_bots':
        run_bots(args['aliases'])