예제 #1
0
    def test_clean_url(self):
        log = logging.getLogger(__name__)
        test = namedtuple('test', 'expected_result dirty clean')

        url_tests = [
            test(True, "https://subdomain.domain.tld/endpoint", "https://subdomain.domain.tld/endpoint"),  # does not add a final /
            test(True, "http://www.example.com/folder/", "http://www.example.com/folder/"),  # does not remove the final /
            test(True, "google.com/xml.rpc", "http://google.com/xml.rpc"),  # add scheme if missing
            test(True, "google.com", "http://google.com/"),  # add scheme if missing and final / if its just the domain
            test(True, "scgi:///home/user/.config/path/socket", "scgi:///home/user/.config/path/socket"),  # scgi identified as scheme
            test(True, None, ''),  # None URL returns empty string
            test(False, "https://subdomain.domain.tld/endpoint", "http://subdomain.domain.tld/endpoint"),  # does not change schemes from https to http
            test(False, "http://subdomain.domain.tld/endpoint", "https://subdomain.domain.tld/endpoint"),  # ...or vice versa
            test(False, "google.com/xml.rpc", "google.com/xml.rpc"),  # scheme is always added
            test(False, "google.com", "https://google.com/"),  # does not default to https
            test(False, "http://www.example.com/folder/", "http://www.example.com/folder"),  # does not strip final /
            test(False, "scgi:///home/user/.config/path/socket", "scgi:///home/user/.config/path/socket/"),  # does not add a final /
            test(AttributeError, 1, 1),  # None URL returns empty string
        ]

        for test_url in url_tests:
            if issubclass(type(Exception), type(test_url.expected_result)):
                with self.assertRaises(test_url.expected_result):
                    self.assertEqual(config.clean_url(test_url.dirty), test_url.clean)
            elif test_url.expected_result is True:
                self.assertEqual(config.clean_url(test_url.dirty), test_url.clean)
            elif test_url.expected_result is False:
                self.assertNotEqual(config.clean_url(test_url.dirty), test_url.clean)
            else:
                log.error('Test not defined for %s', test_url)
예제 #2
0
    def test_clean_url(self):
        log = logging.getLogger(__name__)
        test = namedtuple('test', 'expected_result dirty clean')

        url_tests = [
            test(True, "https://subdomain.domain.tld/endpoint",
                 "https://subdomain.domain.tld/endpoint"
                 ),  # does not add a final /
            test(True, "http://www.example.com/folder/",
                 "http://www.example.com/folder/"
                 ),  # does not remove the final /
            test(True, "google.com/xml.rpc",
                 "http://google.com/xml.rpc"),  # add scheme if missing
            test(True, "google.com", "http://google.com/"
                 ),  # add scheme if missing and final / if its just the domain
            test(True, "scgi:///home/user/.config/path/socket",
                 "scgi:///home/user/.config/path/socket"
                 ),  # scgi identified as scheme
            test(True, None, ''),  # None URL returns empty string
            test(False, "https://subdomain.domain.tld/endpoint",
                 "http://subdomain.domain.tld/endpoint"
                 ),  # does not change schemes from https to http
            test(False, "http://subdomain.domain.tld/endpoint",
                 "https://subdomain.domain.tld/endpoint"),  # ...or vice versa
            test(False, "google.com/xml.rpc",
                 "google.com/xml.rpc"),  # scheme is always added
            test(False, "google.com",
                 "https://google.com/"),  # does not default to https
            test(False, "http://www.example.com/folder/",
                 "http://www.example.com/folder"),  # does not strip final /
            test(False, "scgi:///home/user/.config/path/socket",
                 "scgi:///home/user/.config/path/socket/"
                 ),  # does not add a final /
            test(AttributeError, 1, 1),  # None URL returns empty string
        ]

        for test_url in url_tests:
            if issubclass(type(Exception), type(test_url.expected_result)):
                with self.assertRaises(test_url.expected_result):
                    self.assertEqual(config.clean_url(test_url.dirty),
                                     test_url.clean)
            elif test_url.expected_result is True:
                self.assertEqual(config.clean_url(test_url.dirty),
                                 test_url.clean)
            elif test_url.expected_result is False:
                self.assertNotEqual(config.clean_url(test_url.dirty),
                                    test_url.clean)
            else:
                log.error('Test not defined for %s', test_url)
예제 #3
0
    def saveNewznabProvider(name, url, api_key=''):
        """
        Save a Newznab Provider
        """

        if not name or not url:
            return '0'

        provider_dict = dict(
            zip([x.name for x in app.newznabProviderList],
                app.newznabProviderList))

        if name in provider_dict:
            if not provider_dict[name].default:
                provider_dict[name].name = name
                provider_dict[name].url = config.clean_url(url)

            provider_dict[name].api_key = api_key
            # a 0 in the api key spot indicates that no api key is needed
            if api_key == '0':
                provider_dict[name].needs_auth = False
            else:
                provider_dict[name].needs_auth = True

            return '|'.join([
                provider_dict[name].get_id(),
                provider_dict[name].config_string()
            ])

        else:
            new_provider = NewznabProvider(name, url, api_key=api_key)
            app.newznabProviderList.append(new_provider)
            return '|'.join(
                [new_provider.get_id(),
                 new_provider.config_string()])
예제 #4
0
    def _save_rsstorrent_providers(providers_settings):
        providers = []
        settings = providers_settings.split('!!!')
        providers_dict = dict(
            list(zip([x.get_id() for x in app.torrentRssProviderList], app.torrentRssProviderList)))

        for provider_settings in settings:
            if not provider_settings:
                continue

            name, url, cookies, title_tag = provider_settings.split('|')
            url = config.clean_url(url)

            new_provider = TorrentRssProvider(name, url=url, cookies=cookies, title_tag=title_tag)
            provider_id = new_provider.get_id()

            # if it already exists then update it
            if provider_id in providers_dict:
                providers_dict[provider_id].name = name
                providers_dict[provider_id].url = url
                providers_dict[provider_id].cookies = cookies
                providers_dict[provider_id].title_tag = title_tag
            else:
                app.torrentRssProviderList.append(new_provider)

            providers.append(provider_id)

        # delete anything that is missing
        for provider in app.torrentRssProviderList:
            if provider.get_id() not in providers:
                app.torrentRssProviderList.remove(provider)

        # Update the torrentrss provider list
        app.TORRENTRSS_PROVIDERS = [provider.name for provider in app.torrentRssProviderList]
예제 #5
0
    def saveTorrentRssProvider(name, url, cookies, title_tag):
        """
        Save a Torrent Provider
        """

        if not name or not url:
            return '0'

        provider_dict = dict(
            zip([x.name for x in app.torrentRssProviderList],
                app.torrentRssProviderList))

        if name in provider_dict:
            provider_dict[name].name = name
            provider_dict[name].url = config.clean_url(url)
            provider_dict[name].cookies = cookies
            provider_dict[name].title_tag = title_tag

            return '|'.join([
                provider_dict[name].get_id(),
                provider_dict[name].config_string()
            ])

        else:
            new_provider = TorrentRssProvider(name, url, cookies, title_tag)
            app.torrentRssProviderList.append(new_provider)
            return '|'.join(
                [new_provider.get_id(),
                 new_provider.config_string()])
예제 #6
0
    def _save_rsstorrent_providers(providers_settings):
        providers = []
        settings = providers_settings.split('!!!')
        providers_dict = dict(
            list(zip([x.get_id() for x in app.torrentRssProviderList], app.torrentRssProviderList)))

        for provider_settings in settings:
            if not provider_settings:
                continue

            name, url, cookies, title_tag = provider_settings.split('|')
            url = config.clean_url(url)

            new_provider = TorrentRssProvider(name, url=url, cookies=cookies, title_tag=title_tag)
            provider_id = new_provider.get_id()

            # if it already exists then update it
            if provider_id in providers_dict:
                providers_dict[provider_id].name = name
                providers_dict[provider_id].url = url
                providers_dict[provider_id].cookies = cookies
                providers_dict[provider_id].title_tag = title_tag
            else:
                app.torrentRssProviderList.append(new_provider)

            providers.append(provider_id)

        # delete anything that is missing
        for provider in app.torrentRssProviderList:
            if provider.get_id() not in providers:
                app.torrentRssProviderList.remove(provider)

        # Update the torrentrss provider list
        app.TORRENTRSS_PROVIDERS = [provider.name for provider in app.torrentRssProviderList]
예제 #7
0
    def saveNewznabProvider(name, url, api_key=''):
        """Save a Newznab Provider."""
        if not name or not url:
            return '0'

        provider_dict = dict(list(zip([x.name for x in app.newznabProviderList], app.newznabProviderList)))

        if name in provider_dict:
            if not provider_dict[name].default:
                provider_dict[name].name = name
                provider_dict[name].url = config.clean_url(url)

            provider_dict[name].api_key = api_key
            # a 0 in the api key spot indicates that no api key is needed
            if api_key == '0':
                provider_dict[name].needs_auth = False
            else:
                provider_dict[name].needs_auth = True

            return '|'.join([provider_dict[name].get_id(), provider_dict[name].config_string()])

        else:
            new_provider = NewznabProvider(name, url, api_key=api_key)
            app.newznabProviderList.append(new_provider)
            return '|'.join([new_provider.get_id(), new_provider.config_string()])
예제 #8
0
파일: providers.py 프로젝트: zapru/Medusa
    def _save_newznab_providers(providers_settings):
        providers = []
        settings = providers_settings.split('!!!')
        providers_dict = dict(
            list(
                zip([x.get_id() for x in app.newznabProviderList],
                    app.newznabProviderList)))

        for provider_settings in settings:
            if not provider_settings:
                continue

            name, url, api_key, categories = provider_settings.split('|')
            url = config.clean_url(url)
            categories = split_and_strip(categories)

            new_provider = NewznabProvider(name,
                                           url=url,
                                           api_key=api_key,
                                           cat_ids=categories)
            provider_id = new_provider.get_id()

            # if it already exists then update it
            if provider_id in providers_dict:
                providers_dict[provider_id].name = name
                providers_dict[provider_id].url = url
                providers_dict[provider_id].api_key = api_key
                providers_dict[provider_id].cat_ids = categories
                # a 0 in the key spot indicates that no key is needed
                if api_key == '0':
                    providers_dict[provider_id].needs_auth = False
                else:
                    providers_dict[provider_id].needs_auth = True
            else:
                app.newznabProviderList.append(new_provider)

            providers.append(provider_id)

        # delete anything that is missing
        for provider in app.newznabProviderList:
            if provider.get_id() not in providers:
                app.newznabProviderList.remove(provider)

        # Update the custom newznab provider list
        NewznabProvider.save_newznab_providers()
예제 #9
0
파일: providers.py 프로젝트: zapru/Medusa
    def _save_torznab_providers(providers_settings):
        providers = []
        settings = providers_settings.split('!!!')
        providers_dict = dict(
            list(
                zip([x.get_id() for x in app.torznab_providers_list],
                    app.torznab_providers_list)))

        for provider_settings in settings:
            if not provider_settings:
                continue

            name, url, api_key, categories, caps = provider_settings.split('|')
            url = config.clean_url(url)
            categories = split_and_strip(categories)
            caps = split_and_strip(caps)

            new_provider = TorznabProvider(name,
                                           url=url,
                                           api_key=api_key,
                                           cat_ids=categories,
                                           cap_tv_search=caps)
            provider_id = new_provider.get_id()

            # if it already exists then update it
            if provider_id in providers_dict:
                providers_dict[provider_id].name = name
                providers_dict[provider_id].url = url
                providers_dict[provider_id].api_key = api_key
                providers_dict[provider_id].cat_ids = categories
                providers_dict[provider_id].cap_tv_search = caps
            else:
                app.torznab_providers_list.append(new_provider)

            providers.append(provider_id)

        # delete anything that is missing
        for provider in app.torznab_providers_list:
            if provider.get_id() not in providers:
                app.torznab_providers_list.remove(provider)

        app.TORZNAB_PROVIDERS = [
            provider.name for provider in app.torznab_providers_list
        ]
예제 #10
0
    def saveTorrentRssProvider(name, url, cookies, title_tag):
        """Save a Torrent Provider."""
        if not name or not url:
            return '0'

        provider_dict = dict(list(zip([x.name for x in app.torrentRssProviderList], app.torrentRssProviderList)))

        if name in provider_dict:
            provider_dict[name].name = name
            provider_dict[name].url = config.clean_url(url)
            provider_dict[name].cookies = cookies
            provider_dict[name].title_tag = title_tag

            return '|'.join([provider_dict[name].get_id(), provider_dict[name].config_string()])

        else:
            new_provider = TorrentRssProvider(name, url, cookies, title_tag)
            app.torrentRssProviderList.append(new_provider)
            return '|'.join([new_provider.get_id(), new_provider.config_string()])
예제 #11
0
파일: handler.py 프로젝트: Tailslide/Medusa
    def testTorrent(torrent_method=None,
                    host=None,
                    username=None,
                    password=None):
        # @TODO: Move this to the validation section of each PATCH/PUT method for torrents
        host = config.clean_url(host)

        try:
            client = torrent.get_client_class(torrent_method)

            _, acces_msg = client(host, username,
                                  password).test_authentication()
        except Exception as error:
            logger.log(
                'Error while testing {torrent} connection: {error}'.format(
                    torrent=torrent_method or 'torrent', error=error),
                logger.WARNING)
            return 'Error while testing connection. Check warning logs.'

        return acces_msg
예제 #12
0
파일: handler.py 프로젝트: Tailslide/Medusa
    def testSABnzbd(host=None, username=None, password=None, apikey=None):
        host = config.clean_url(host)

        try:
            connection, acces_msg = sab.get_sab_access_method(host)
        except Exception as error:
            logger.log(
                'Error while testing SABnzbd connection: {error}'.format(
                    error=error), logger.WARNING)
            return 'Error while testing connection. Check warning logs.'

        if connection:
            authed, auth_msg = sab.test_authentication(host, username,
                                                       password, apikey)
            if authed:
                return 'Success. Connected and authenticated'
            else:
                return 'Authentication failed. SABnzbd expects {access!r} as authentication method, {auth}'.format(
                    access=acces_msg, auth=auth_msg)
        else:
            return 'Unable to connect to host'
예제 #13
0
    def _save_newznab_providers(providers_settings):
        providers = []
        settings = providers_settings.split('!!!')
        providers_dict = dict(
            list(zip([x.get_id() for x in app.newznabProviderList], app.newznabProviderList)))

        for provider_settings in settings:
            if not provider_settings:
                continue

            name, url, api_key, categories = provider_settings.split('|')
            url = config.clean_url(url)
            categories = split_and_strip(categories)

            new_provider = NewznabProvider(name, url=url, api_key=api_key, cat_ids=categories)
            provider_id = new_provider.get_id()

            # if it already exists then update it
            if provider_id in providers_dict:
                providers_dict[provider_id].name = name
                providers_dict[provider_id].url = url
                providers_dict[provider_id].api_key = api_key
                providers_dict[provider_id].cat_ids = categories
                # a 0 in the key spot indicates that no key is needed
                if api_key == '0':
                    providers_dict[provider_id].needs_auth = False
                else:
                    providers_dict[provider_id].needs_auth = True
            else:
                app.newznabProviderList.append(new_provider)

            providers.append(provider_id)

        # delete anything that is missing
        for provider in app.newznabProviderList:
            if provider.get_id() not in providers:
                app.newznabProviderList.remove(provider)

        # Update the custom newznab provider list
        NewznabProvider.save_newznab_providers()
예제 #14
0
    def _save_torznab_providers(providers_settings):
        providers = []
        settings = providers_settings.split('!!!')
        providers_dict = dict(
            list(zip([x.get_id() for x in app.torznab_providers_list], app.torznab_providers_list)))

        for provider_settings in settings:
            if not provider_settings:
                continue

            name, url, api_key, categories, caps = provider_settings.split('|')
            url = config.clean_url(url)
            categories = split_and_strip(categories)
            caps = split_and_strip(caps)

            new_provider = TorznabProvider(name, url=url, api_key=api_key, cat_ids=categories,
                                           cap_tv_search=caps)
            provider_id = new_provider.get_id()

            # if it already exists then update it
            if provider_id in providers_dict:
                providers_dict[provider_id].name = name
                providers_dict[provider_id].url = url
                providers_dict[provider_id].api_key = api_key
                providers_dict[provider_id].cat_ids = categories
                providers_dict[provider_id].cap_tv_search = caps
            else:
                app.torznab_providers_list.append(new_provider)

            providers.append(provider_id)

        # delete anything that is missing
        for provider in app.torznab_providers_list:
            if provider.get_id() not in providers:
                app.torznab_providers_list.remove(provider)

        app.TORZNAB_PROVIDERS = [provider.name for provider in app.torznab_providers_list]
예제 #15
0
파일: search.py 프로젝트: thomas2902/Medusa
    def saveSearch(self,
                   use_nzbs=None,
                   use_torrents=None,
                   nzb_dir=None,
                   sab_username=None,
                   sab_password=None,
                   sab_apikey=None,
                   sab_category=None,
                   sab_category_anime=None,
                   sab_category_backlog=None,
                   sab_category_anime_backlog=None,
                   sab_host=None,
                   nzbget_username=None,
                   nzbget_password=None,
                   nzbget_category=None,
                   nzbget_category_backlog=None,
                   nzbget_category_anime=None,
                   nzbget_category_anime_backlog=None,
                   nzbget_priority=None,
                   nzbget_host=None,
                   nzbget_use_https=None,
                   backlog_days=None,
                   backlog_frequency=None,
                   dailysearch_frequency=None,
                   nzb_method=None,
                   torrent_method=None,
                   usenet_retention=None,
                   download_propers=None,
                   check_propers_interval=None,
                   allow_high_priority=None,
                   sab_forced=None,
                   remove_from_client=None,
                   randomize_providers=None,
                   use_failed_downloads=None,
                   delete_failed=None,
                   propers_search_days=None,
                   torrent_dir=None,
                   torrent_username=None,
                   torrent_password=None,
                   torrent_host=None,
                   torrent_label=None,
                   torrent_label_anime=None,
                   torrent_path=None,
                   torrent_verify_cert=None,
                   torrent_seed_time=None,
                   torrent_paused=None,
                   torrent_high_bandwidth=None,
                   torrent_rpcurl=None,
                   torrent_auth_type=None,
                   ignore_words=None,
                   torrent_checker_frequency=None,
                   preferred_words=None,
                   undesired_words=None,
                   trackers_list=None,
                   require_words=None,
                   ignored_subs_list=None,
                   ignore_und_subs=None,
                   cache_trimming=None,
                   max_cache_age=None,
                   torrent_seed_location=None):
        """
        Save Search related settings
        """

        results = []

        if not config.change_NZB_DIR(nzb_dir):
            results += [
                'Unable to create directory {dir}, dir not changed.'.format(
                    dir=os.path.normpath(nzb_dir))
            ]

        if not config.change_TORRENT_DIR(torrent_dir):
            results += [
                'Unable to create directory {dir}, dir not changed.'.format(
                    dir=os.path.normpath(torrent_dir))
            ]

        config.change_DAILYSEARCH_FREQUENCY(dailysearch_frequency)
        config.change_TORRENT_CHECKER_FREQUENCY(torrent_checker_frequency)
        config.change_BACKLOG_FREQUENCY(backlog_frequency)
        app.BACKLOG_DAYS = try_int(backlog_days, 7)

        app.CACHE_TRIMMING = config.checkbox_to_value(cache_trimming)
        app.MAX_CACHE_AGE = try_int(max_cache_age, 0)

        app.USE_NZBS = config.checkbox_to_value(use_nzbs)
        app.USE_TORRENTS = config.checkbox_to_value(use_torrents)

        app.NZB_METHOD = nzb_method
        app.TORRENT_METHOD = torrent_method
        app.USENET_RETENTION = try_int(usenet_retention, 500)

        if app.TORRENT_METHOD != 'blackhole' and app.TORRENT_METHOD in (
                'transmission', 'deluge', 'deluged'):
            config.change_remove_from_client(remove_from_client)
        else:
            config.change_remove_from_client('false')

        app.IGNORE_WORDS = [_.strip() for _ in ignore_words.split(',')
                            ] if ignore_words else []
        app.PREFERRED_WORDS = [_.strip() for _ in preferred_words.split(',')
                               ] if preferred_words else []
        app.UNDESIRED_WORDS = [_.strip() for _ in undesired_words.split(',')
                               ] if undesired_words else []
        app.TRACKERS_LIST = [_.strip() for _ in trackers_list.split(',')
                             ] if trackers_list else []
        app.REQUIRE_WORDS = [_.strip() for _ in require_words.split(',')
                             ] if require_words else []
        app.IGNORED_SUBS_LIST = [
            _.strip() for _ in ignored_subs_list.split(',')
        ] if ignored_subs_list else []
        app.IGNORE_UND_SUBS = config.checkbox_to_value(ignore_und_subs)

        app.RANDOMIZE_PROVIDERS = config.checkbox_to_value(randomize_providers)

        config.change_DOWNLOAD_PROPERS(download_propers)
        app.PROPERS_SEARCH_DAYS = try_int(propers_search_days, 2)
        config.change_PROPERS_FREQUENCY(check_propers_interval)

        app.ALLOW_HIGH_PRIORITY = config.checkbox_to_value(allow_high_priority)

        app.USE_FAILED_DOWNLOADS = config.checkbox_to_value(
            use_failed_downloads)
        app.DELETE_FAILED = config.checkbox_to_value(delete_failed)

        app.SAB_USERNAME = sab_username
        app.SAB_PASSWORD = sab_password
        app.SAB_APIKEY = sab_apikey.strip()
        app.SAB_CATEGORY = sab_category
        app.SAB_CATEGORY_BACKLOG = sab_category_backlog
        app.SAB_CATEGORY_ANIME = sab_category_anime
        app.SAB_CATEGORY_ANIME_BACKLOG = sab_category_anime_backlog
        app.SAB_HOST = config.clean_url(sab_host)
        app.SAB_FORCED = config.checkbox_to_value(sab_forced)

        app.NZBGET_USERNAME = nzbget_username
        app.NZBGET_PASSWORD = nzbget_password
        app.NZBGET_CATEGORY = nzbget_category
        app.NZBGET_CATEGORY_BACKLOG = nzbget_category_backlog
        app.NZBGET_CATEGORY_ANIME = nzbget_category_anime
        app.NZBGET_CATEGORY_ANIME_BACKLOG = nzbget_category_anime_backlog
        app.NZBGET_HOST = config.clean_host(nzbget_host)
        app.NZBGET_USE_HTTPS = config.checkbox_to_value(nzbget_use_https)
        app.NZBGET_PRIORITY = try_int(nzbget_priority, 100)

        app.TORRENT_USERNAME = torrent_username
        app.TORRENT_PASSWORD = torrent_password
        app.TORRENT_LABEL = torrent_label
        app.TORRENT_LABEL_ANIME = torrent_label_anime
        app.TORRENT_VERIFY_CERT = config.checkbox_to_value(torrent_verify_cert)
        app.TORRENT_PATH = torrent_path.rstrip('/\\')
        app.TORRENT_SEED_TIME = torrent_seed_time
        app.TORRENT_PAUSED = config.checkbox_to_value(torrent_paused)
        app.TORRENT_HIGH_BANDWIDTH = config.checkbox_to_value(
            torrent_high_bandwidth)
        app.TORRENT_HOST = config.clean_url(torrent_host)
        app.TORRENT_RPCURL = torrent_rpcurl
        app.TORRENT_AUTH_TYPE = torrent_auth_type
        app.TORRENT_SEED_LOCATION = torrent_seed_location.rstrip('/\\')

        app.instance.save_config()

        if results:
            for x in results:
                logger.log(x, logger.ERROR)
            ui.notifications.error('Error(s) Saving Configuration',
                                   '<br>\n'.join(results))
        else:
            ui.notifications.message('Configuration Saved',
                                     os.path.join(app.CONFIG_FILE))

        return self.redirect('/config/search/')
예제 #16
0
파일: search.py 프로젝트: pymedusa/SickRage
    def saveSearch(self, use_nzbs=None, use_torrents=None, nzb_dir=None, sab_username=None, sab_password=None,
                   sab_apikey=None, sab_category=None, sab_category_anime=None, sab_category_backlog=None,
                   sab_category_anime_backlog=None, sab_host=None, nzbget_username=None, nzbget_password=None,
                   nzbget_category=None, nzbget_category_backlog=None, nzbget_category_anime=None,
                   nzbget_category_anime_backlog=None, nzbget_priority=None, nzbget_host=None,
                   nzbget_use_https=None, backlog_days=None, backlog_frequency=None, dailysearch_frequency=None,
                   nzb_method=None, torrent_method=None, usenet_retention=None, download_propers=None,
                   check_propers_interval=None, allow_high_priority=None, sab_forced=None, remove_from_client=None,
                   randomize_providers=None, use_failed_downloads=None, delete_failed=None, propers_search_days=None,
                   torrent_dir=None, torrent_username=None, torrent_password=None, torrent_host=None,
                   torrent_label=None, torrent_label_anime=None, torrent_path=None, torrent_verify_cert=None,
                   torrent_seed_time=None, torrent_paused=None, torrent_high_bandwidth=None,
                   torrent_rpcurl=None, torrent_auth_type=None, ignore_words=None, torrent_checker_frequency=None,
                   preferred_words=None, undesired_words=None, trackers_list=None, require_words=None,
                   ignored_subs_list=None, ignore_und_subs=None, cache_trimming=None, max_cache_age=None,
                   torrent_seed_location=None):
        """
        Save Search related settings
        """

        results = []

        if not config.change_NZB_DIR(nzb_dir):
            results += ['Unable to create directory {dir}, dir not changed.'.format(dir=os.path.normpath(nzb_dir))]

        if not config.change_TORRENT_DIR(torrent_dir):
            results += ['Unable to create directory {dir}, dir not changed.'.format(dir=os.path.normpath(torrent_dir))]

        config.change_DAILYSEARCH_FREQUENCY(dailysearch_frequency)
        config.change_TORRENT_CHECKER_FREQUENCY(torrent_checker_frequency)
        config.change_BACKLOG_FREQUENCY(backlog_frequency)
        app.BACKLOG_DAYS = try_int(backlog_days, 7)

        app.CACHE_TRIMMING = config.checkbox_to_value(cache_trimming)
        app.MAX_CACHE_AGE = try_int(max_cache_age, 0)

        app.USE_NZBS = config.checkbox_to_value(use_nzbs)
        app.USE_TORRENTS = config.checkbox_to_value(use_torrents)

        app.NZB_METHOD = nzb_method
        app.TORRENT_METHOD = torrent_method
        app.USENET_RETENTION = try_int(usenet_retention, 500)

        if app.TORRENT_METHOD != 'blackhole' and app.TORRENT_METHOD in ('transmission', 'deluge', 'deluged'):
            config.change_remove_from_client(remove_from_client)
        else:
            config.change_remove_from_client('false')

        app.IGNORE_WORDS = [_.strip() for _ in ignore_words.split(',')] if ignore_words else []
        app.PREFERRED_WORDS = [_.strip() for _ in preferred_words.split(',')] if preferred_words else []
        app.UNDESIRED_WORDS = [_.strip() for _ in undesired_words.split(',')] if undesired_words else []
        app.TRACKERS_LIST = [_.strip() for _ in trackers_list.split(',')] if trackers_list else []
        app.REQUIRE_WORDS = [_.strip() for _ in require_words.split(',')] if require_words else []
        app.IGNORED_SUBS_LIST = [_.strip() for _ in ignored_subs_list.split(',')] if ignored_subs_list else []
        app.IGNORE_UND_SUBS = config.checkbox_to_value(ignore_und_subs)

        app.RANDOMIZE_PROVIDERS = config.checkbox_to_value(randomize_providers)

        config.change_DOWNLOAD_PROPERS(download_propers)
        app.PROPERS_SEARCH_DAYS = try_int(propers_search_days, 2)
        config.change_PROPERS_FREQUENCY(check_propers_interval)

        app.ALLOW_HIGH_PRIORITY = config.checkbox_to_value(allow_high_priority)

        app.USE_FAILED_DOWNLOADS = config.checkbox_to_value(use_failed_downloads)
        app.DELETE_FAILED = config.checkbox_to_value(delete_failed)

        app.SAB_USERNAME = sab_username
        app.SAB_PASSWORD = sab_password
        app.SAB_APIKEY = sab_apikey.strip()
        app.SAB_CATEGORY = sab_category
        app.SAB_CATEGORY_BACKLOG = sab_category_backlog
        app.SAB_CATEGORY_ANIME = sab_category_anime
        app.SAB_CATEGORY_ANIME_BACKLOG = sab_category_anime_backlog
        app.SAB_HOST = config.clean_url(sab_host)
        app.SAB_FORCED = config.checkbox_to_value(sab_forced)

        app.NZBGET_USERNAME = nzbget_username
        app.NZBGET_PASSWORD = nzbget_password
        app.NZBGET_CATEGORY = nzbget_category
        app.NZBGET_CATEGORY_BACKLOG = nzbget_category_backlog
        app.NZBGET_CATEGORY_ANIME = nzbget_category_anime
        app.NZBGET_CATEGORY_ANIME_BACKLOG = nzbget_category_anime_backlog
        app.NZBGET_HOST = config.clean_host(nzbget_host)
        app.NZBGET_USE_HTTPS = config.checkbox_to_value(nzbget_use_https)
        app.NZBGET_PRIORITY = try_int(nzbget_priority, 100)

        app.TORRENT_USERNAME = torrent_username
        app.TORRENT_PASSWORD = torrent_password
        app.TORRENT_LABEL = torrent_label
        app.TORRENT_LABEL_ANIME = torrent_label_anime
        app.TORRENT_VERIFY_CERT = config.checkbox_to_value(torrent_verify_cert)
        app.TORRENT_PATH = torrent_path.rstrip('/\\')
        app.TORRENT_SEED_TIME = torrent_seed_time
        app.TORRENT_PAUSED = config.checkbox_to_value(torrent_paused)
        app.TORRENT_HIGH_BANDWIDTH = config.checkbox_to_value(torrent_high_bandwidth)
        app.TORRENT_HOST = config.clean_url(torrent_host)
        app.TORRENT_RPCURL = torrent_rpcurl
        app.TORRENT_AUTH_TYPE = torrent_auth_type
        app.TORRENT_SEED_LOCATION = torrent_seed_location.rstrip('/\\')

        app.instance.save_config()

        if results:
            for x in results:
                logger.log(x, logger.ERROR)
            ui.notifications.error('Error(s) Saving Configuration',
                                   '<br>\n'.join(results))
        else:
            ui.notifications.message('Configuration Saved', os.path.join(app.CONFIG_FILE))

        return self.redirect('/config/search/')
예제 #17
0
    def saveProviders(self,
                      newznab_string='',
                      torrentrss_string='',
                      provider_order=None,
                      **kwargs):
        """
        Save Provider related settings
        """
        results = []

        provider_str_list = provider_order.split()
        provider_list = []

        newznab_provider_dict = dict(
            zip([x.get_id() for x in app.newznabProviderList],
                app.newznabProviderList))

        finished_names = []

        # add all the newznab info we got into our list
        if newznab_string:
            for curNewznabProviderStr in newznab_string.split('!!!'):

                if not curNewznabProviderStr:
                    continue

                cur_name, cur_url, cur_key, cur_cat = curNewznabProviderStr.split(
                    '|')
                cur_url = config.clean_url(cur_url)

                new_provider = NewznabProvider(cur_name,
                                               cur_url,
                                               api_key=cur_key,
                                               cat_ids=cur_cat)

                cur_id = new_provider.get_id()

                # if it already exists then update it
                if cur_id in newznab_provider_dict:
                    newznab_provider_dict[cur_id].name = cur_name
                    newznab_provider_dict[cur_id].url = cur_url
                    newznab_provider_dict[cur_id].api_key = cur_key
                    newznab_provider_dict[cur_id].cat_ids = split_and_strip(
                        cur_cat)
                    # a 0 in the key spot indicates that no key is needed
                    if cur_key == '0':
                        newznab_provider_dict[cur_id].needs_auth = False
                    else:
                        newznab_provider_dict[cur_id].needs_auth = True

                    try:
                        newznab_provider_dict[cur_id].search_mode = str(
                            kwargs['{id}_search_mode'.format(
                                id=cur_id)]).strip()
                    except (AttributeError, KeyError):
                        pass  # these exceptions are actually catching unselected checkboxes

                    try:
                        newznab_provider_dict[
                            cur_id].search_fallback = config.checkbox_to_value(
                                kwargs['{id}_search_fallback'.format(
                                    id=cur_id)])
                    except (AttributeError, KeyError):
                        newznab_provider_dict[
                            cur_id].search_fallback = 0  # these exceptions are actually catching unselected checkboxes

                    try:
                        newznab_provider_dict[
                            cur_id].enable_daily = config.checkbox_to_value(
                                kwargs['{id}_enable_daily'.format(id=cur_id)])
                    except (AttributeError, KeyError):
                        newznab_provider_dict[
                            cur_id].enable_daily = 0  # these exceptions are actually catching unselected checkboxes

                    try:
                        newznab_provider_dict[
                            cur_id].enable_manualsearch = config.checkbox_to_value(
                                kwargs['{id}_enable_manualsearch'.format(
                                    id=cur_id)])
                    except (AttributeError, KeyError):
                        newznab_provider_dict[
                            cur_id].enable_manualsearch = 0  # these exceptions are actually catching unselected checkboxes

                    try:
                        newznab_provider_dict[
                            cur_id].enable_backlog = config.checkbox_to_value(
                                kwargs['{id}_enable_backlog'.format(
                                    id=cur_id)])
                    except (AttributeError, KeyError):
                        newznab_provider_dict[
                            cur_id].enable_backlog = 0  # these exceptions are actually catching unselected checkboxes

                else:
                    app.newznabProviderList.append(new_provider)

                finished_names.append(cur_id)

        # delete anything that is missing
        for cur_provider in app.newznabProviderList:
            if cur_provider.get_id() not in finished_names:
                app.newznabProviderList.remove(cur_provider)

        # Update the custom newznab provider list
        NewznabProvider.save_newnab_providers()

        torrent_rss_provider_dict = dict(
            zip([x.get_id() for x in app.torrentRssProviderList],
                app.torrentRssProviderList))
        finished_names = []

        if torrentrss_string:
            for curTorrentRssProviderStr in torrentrss_string.split('!!!'):

                if not curTorrentRssProviderStr:
                    continue

                cur_name, cur_url, cur_cookies, cur_title_tag = curTorrentRssProviderStr.split(
                    '|')
                cur_url = config.clean_url(cur_url)

                new_provider = TorrentRssProvider(cur_name, cur_url,
                                                  cur_cookies, cur_title_tag)

                cur_id = new_provider.get_id()

                # if it already exists then update it
                if cur_id in torrent_rss_provider_dict:
                    torrent_rss_provider_dict[cur_id].name = cur_name
                    torrent_rss_provider_dict[cur_id].url = cur_url
                    torrent_rss_provider_dict[cur_id].cookies = cur_cookies
                    torrent_rss_provider_dict[
                        cur_id].curTitleTAG = cur_title_tag
                else:
                    app.torrentRssProviderList.append(new_provider)

                finished_names.append(cur_id)

        # delete anything that is missing
        for cur_provider in app.torrentRssProviderList:
            if cur_provider.get_id() not in finished_names:
                app.torrentRssProviderList.remove(cur_provider)

        # Update the torrentrss provider list
        app.TORRENTRSS_PROVIDERS = [
            provider.name for provider in app.torrentRssProviderList
        ]

        disabled_list = []
        # do the enable/disable
        for cur_providerStr in provider_str_list:
            cur_provider, cur_enabled = cur_providerStr.split(':')
            cur_enabled = try_int(cur_enabled)

            cur_prov_obj = [
                x for x in providers.sorted_provider_list()
                if x.get_id() == cur_provider and hasattr(x, 'enabled')
            ]
            if cur_prov_obj:
                cur_prov_obj[0].enabled = bool(cur_enabled)

            if cur_enabled:
                provider_list.append(cur_provider)
            else:
                disabled_list.append(cur_provider)

            if cur_provider in newznab_provider_dict:
                newznab_provider_dict[cur_provider].enabled = bool(cur_enabled)
            elif cur_provider in torrent_rss_provider_dict:
                torrent_rss_provider_dict[cur_provider].enabled = bool(
                    cur_enabled)

        provider_list.extend(disabled_list)

        # dynamically load provider settings
        for cur_torrent_provider in [
                prov for prov in providers.sorted_provider_list()
                if prov.provider_type == GenericProvider.TORRENT
        ]:

            if hasattr(cur_torrent_provider, 'custom_url'):
                try:
                    cur_torrent_provider.custom_url = str(
                        kwargs['{id}_custom_url'.format(
                            id=cur_torrent_provider.get_id())]).strip()
                except (AttributeError, KeyError):
                    cur_torrent_provider.custom_url = None  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'minseed'):
                try:
                    cur_torrent_provider.minseed = int(
                        str(kwargs['{id}_minseed'.format(
                            id=cur_torrent_provider.get_id())]).strip())
                except (AttributeError, KeyError):
                    cur_torrent_provider.minseed = 0  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'minleech'):
                try:
                    cur_torrent_provider.minleech = int(
                        str(kwargs['{id}_minleech'.format(
                            id=cur_torrent_provider.get_id())]).strip())
                except (AttributeError, KeyError):
                    cur_torrent_provider.minleech = 0  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'ratio'):
                try:
                    ratio = float(
                        str(kwargs['{id}_ratio'.format(
                            id=cur_torrent_provider.get_id())]).strip())
                    cur_torrent_provider.ratio = (ratio, -1)[ratio < 0]
                except (AttributeError, KeyError, ValueError):
                    cur_torrent_provider.ratio = None  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'digest'):
                try:
                    cur_torrent_provider.digest = str(
                        kwargs['{id}_digest'.format(
                            id=cur_torrent_provider.get_id())]).strip()
                except (AttributeError, KeyError):
                    cur_torrent_provider.digest = None  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'hash'):
                try:
                    cur_torrent_provider.hash = str(kwargs['{id}_hash'.format(
                        id=cur_torrent_provider.get_id())]).strip()
                except (AttributeError, KeyError):
                    cur_torrent_provider.hash = None  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'api_key'):
                try:
                    cur_torrent_provider.api_key = str(
                        kwargs['{id}_api_key'.format(
                            id=cur_torrent_provider.get_id())]).strip()
                except (AttributeError, KeyError):
                    cur_torrent_provider.api_key = None  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'username'):
                try:
                    cur_torrent_provider.username = str(
                        kwargs['{id}_username'.format(
                            id=cur_torrent_provider.get_id())]).strip()
                except (AttributeError, KeyError):
                    cur_torrent_provider.username = None  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'password'):
                try:
                    cur_torrent_provider.password = str(
                        kwargs['{id}_password'.format(
                            id=cur_torrent_provider.get_id())]).strip()
                except (AttributeError, KeyError):
                    cur_torrent_provider.password = None  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'passkey'):
                try:
                    cur_torrent_provider.passkey = str(
                        kwargs['{id}_passkey'.format(
                            id=cur_torrent_provider.get_id())]).strip()
                except (AttributeError, KeyError):
                    cur_torrent_provider.passkey = None  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'pin'):
                try:
                    cur_torrent_provider.pin = str(kwargs['{id}_pin'.format(
                        id=cur_torrent_provider.get_id())]).strip()
                except (AttributeError, KeyError):
                    cur_torrent_provider.pin = None  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'confirmed'):
                try:
                    cur_torrent_provider.confirmed = config.checkbox_to_value(
                        kwargs['{id}_confirmed'.format(
                            id=cur_torrent_provider.get_id())])
                except (AttributeError, KeyError):
                    cur_torrent_provider.confirmed = 0  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'ranked'):
                try:
                    cur_torrent_provider.ranked = config.checkbox_to_value(
                        kwargs['{id}_ranked'.format(
                            id=cur_torrent_provider.get_id())])
                except (AttributeError, KeyError):
                    cur_torrent_provider.ranked = 0  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'engrelease'):
                try:
                    cur_torrent_provider.engrelease = config.checkbox_to_value(
                        kwargs['{id}_engrelease'.format(
                            id=cur_torrent_provider.get_id())])
                except (AttributeError, KeyError):
                    cur_torrent_provider.engrelease = 0  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'onlyspasearch'):
                try:
                    cur_torrent_provider.onlyspasearch = config.checkbox_to_value(
                        kwargs['{id}_onlyspasearch'.format(
                            id=cur_torrent_provider.get_id())])
                except (AttributeError, KeyError):
                    cur_torrent_provider.onlyspasearch = 0  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'sorting'):
                try:
                    cur_torrent_provider.sorting = str(
                        kwargs['{id}_sorting'.format(
                            id=cur_torrent_provider.get_id())]).strip()
                except (AttributeError, KeyError):
                    cur_torrent_provider.sorting = 'seeders'  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'freeleech'):
                try:
                    cur_torrent_provider.freeleech = config.checkbox_to_value(
                        kwargs['{id}_freeleech'.format(
                            id=cur_torrent_provider.get_id())])
                except (AttributeError, KeyError):
                    cur_torrent_provider.freeleech = 0  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'search_mode'):
                try:
                    cur_torrent_provider.search_mode = str(
                        kwargs['{id}_search_mode'.format(
                            id=cur_torrent_provider.get_id())]).strip()
                except (AttributeError, KeyError):
                    cur_torrent_provider.search_mode = 'eponly'  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'search_fallback'):
                try:
                    cur_torrent_provider.search_fallback = config.checkbox_to_value(
                        kwargs['{id}_search_fallback'.format(
                            id=cur_torrent_provider.get_id())])
                except (AttributeError, KeyError):
                    cur_torrent_provider.search_fallback = 0  # these exceptions are catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'enable_daily'):
                try:
                    cur_torrent_provider.enable_daily = config.checkbox_to_value(
                        kwargs['{id}_enable_daily'.format(
                            id=cur_torrent_provider.get_id())])
                except (AttributeError, KeyError):
                    cur_torrent_provider.enable_daily = 0  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'enable_manualsearch'):
                try:
                    cur_torrent_provider.enable_manualsearch = config.checkbox_to_value(
                        kwargs['{id}_enable_manualsearch'.format(
                            id=cur_torrent_provider.get_id())])
                except (AttributeError, KeyError):
                    cur_torrent_provider.enable_manualsearch = 0  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'enable_backlog'):
                try:
                    cur_torrent_provider.enable_backlog = config.checkbox_to_value(
                        kwargs['{id}_enable_backlog'.format(
                            id=cur_torrent_provider.get_id())])
                except (AttributeError, KeyError):
                    cur_torrent_provider.enable_backlog = 0  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'cat'):
                try:
                    cur_torrent_provider.cat = int(
                        str(kwargs['{id}_cat'.format(
                            id=cur_torrent_provider.get_id())]).strip())
                except (AttributeError, KeyError):
                    cur_torrent_provider.cat = 0  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_torrent_provider, 'subtitle'):
                try:
                    cur_torrent_provider.subtitle = config.checkbox_to_value(
                        kwargs['{id}_subtitle'.format(
                            id=cur_torrent_provider.get_id())])
                except (AttributeError, KeyError):
                    cur_torrent_provider.subtitle = 0  # these exceptions are actually catching unselected checkboxes

            if cur_torrent_provider.enable_cookies:
                try:
                    cur_torrent_provider.cookies = str(
                        kwargs['{id}_cookies'.format(
                            id=cur_torrent_provider.get_id())]).strip()
                except (AttributeError, KeyError):
                    pass  # I don't want to configure a default value here, as it can also be configured intially as a custom rss torrent provider

        for cur_nzb_provider in [
                prov for prov in providers.sorted_provider_list()
                if prov.provider_type == GenericProvider.NZB
        ]:

            # We don't want to overwrite the api key, as that's not available in the second tab for newznab providers.
            if hasattr(cur_nzb_provider, 'api_key') and not isinstance(
                    cur_nzb_provider, NewznabProvider):
                try:
                    cur_nzb_provider.api_key = str(
                        kwargs['{id}_api_key'.format(
                            id=cur_nzb_provider.get_id())]).strip()
                except (AttributeError, KeyError):
                    cur_nzb_provider.api_key = None  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_nzb_provider, 'username'):
                try:
                    cur_nzb_provider.username = str(
                        kwargs['{id}_username'.format(
                            id=cur_nzb_provider.get_id())]).strip()
                except (AttributeError, KeyError):
                    cur_nzb_provider.username = None  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_nzb_provider, 'search_mode'):
                try:
                    cur_nzb_provider.search_mode = str(
                        kwargs['{id}_search_mode'.format(
                            id=cur_nzb_provider.get_id())]).strip()
                except (AttributeError, KeyError):
                    cur_nzb_provider.search_mode = 'eponly'  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_nzb_provider, 'search_fallback'):
                try:
                    cur_nzb_provider.search_fallback = config.checkbox_to_value(
                        kwargs['{id}_search_fallback'.format(
                            id=cur_nzb_provider.get_id())])
                except (AttributeError, KeyError):
                    cur_nzb_provider.search_fallback = 0  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_nzb_provider, 'enable_daily'):
                try:
                    cur_nzb_provider.enable_daily = config.checkbox_to_value(
                        kwargs['{id}_enable_daily'.format(
                            id=cur_nzb_provider.get_id())])
                except (AttributeError, KeyError):
                    cur_nzb_provider.enable_daily = 0  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_nzb_provider, 'enable_manualsearch'):
                try:
                    cur_nzb_provider.enable_manualsearch = config.checkbox_to_value(
                        kwargs['{id}_enable_manualsearch'.format(
                            id=cur_nzb_provider.get_id())])
                except (AttributeError, KeyError):
                    cur_nzb_provider.enable_manualsearch = 0  # these exceptions are actually catching unselected checkboxes

            if hasattr(cur_nzb_provider, 'enable_backlog'):
                try:
                    cur_nzb_provider.enable_backlog = config.checkbox_to_value(
                        kwargs['{id}_enable_backlog'.format(
                            id=cur_nzb_provider.get_id())])
                except (AttributeError, KeyError):
                    cur_nzb_provider.enable_backlog = 0  # these exceptions are actually catching unselected checkboxes

        # app.NEWZNAB_DATA = '!!!'.join([x.config_string() for x in app.newznabProviderList])
        app.PROVIDER_ORDER = provider_list

        app.instance.save_config()

        if results:
            for x in results:
                logger.log(x, logger.ERROR)
            ui.notifications.error('Error(s) Saving Configuration',
                                   '<br>\n'.join(results))
        else:
            ui.notifications.message('Configuration Saved',
                                     os.path.join(app.CONFIG_FILE))

        return self.redirect('/config/providers/')