Пример #1
0
    def _format_string(self, pattern, replace_map):
        """
        Replaces all template strings with the correct value
        """

        result_name = pattern

        # do the replacements
        for cur_replacement in sorted(replace_map.keys(), reverse=True):
            result_name = result_name.replace(cur_replacement,
                                              sanitize_file_name(replace_map[cur_replacement]))
            result_name = result_name.replace(cur_replacement.lower(),
                                              sanitize_file_name(replace_map[cur_replacement].lower()))

        return result_name
Пример #2
0
    def test_encoding(self):
        rootDir = 'C:\\Temp\\TV'
        strings = ['Les Enfants De La T\xe9l\xe9', 'RT� One', "[France.5].Les.100.lieux.qu'il.faut.voir.-.Corrèze.(18.05.18)"]

        for s in strings:
            show_dir = os.path.join(rootDir, sanitize_file_name(s))
            self.assertIsInstance(show_dir, str)
Пример #3
0
    def get(self, *args, **kwargs):
        series_id = self.get_argument('series_id')
        show_name = self.get_argument('showName')

        if re.search(r'tt\d+', series_id):
            result = sickrage.app.series_providers[
                SeriesProviderID.THETVDB].search_by_id(series_id)
            if not result:
                return

            series_id = int(result['id'])

        if find_show(int(series_id), SeriesProviderID.THETVDB):
            sickrage.app.log.debug(
                f"{series_id} already exists in your show library, skipping!")
            return

        location = None
        if sickrage.app.config.general.root_dirs:
            root_dirs = sickrage.app.config.general.root_dirs.split('|')
            location = root_dirs[int(root_dirs[0]) + 1]

        if not location:
            sickrage.app.log.warning(
                "There was an error creating the show, no root directory setting found"
            )
            return _('No root directories setup, please go back and add one.')

        show_dir = os.path.join(location, sanitize_file_name(show_name))

        return self.redirect(
            url_concat(
                "/home/addShows/newShow", {
                    'show_to_add':
                    '{series_provider_id}|{show_dir}|{series_id}|{show_name}'.
                    format(
                        **{
                            'series_provider_id':
                            SeriesProviderID.THETVDB.name,
                            'show_dir': show_dir,
                            'series_id': series_id,
                            'show_name': show_name
                        })
                }))
Пример #4
0
    def add_default_show(indexer, indexer_id, name, status):
        """
        Adds a new show with the default settings
        """
        if not find_show(int(indexer_id)):
            sickrage.app.log.info("Adding show " + str(indexer_id))
            root_dirs = sickrage.app.config.root_dirs.split('|')

            try:
                location = root_dirs[int(root_dirs[0]) + 1]
            except Exception:
                location = None

            if location:
                showPath = os.path.join(location, sanitize_file_name(name))
                dir_exists = make_dir(showPath)

                if not dir_exists:
                    sickrage.app.log.warning(
                        "Unable to create the folder %s , can't add the show" %
                        showPath)
                    return
                else:
                    chmod_as_parent(showPath)

                sickrage.app.show_queue.add_show(
                    int(indexer),
                    int(indexer_id),
                    showPath,
                    default_status=status,
                    quality=int(sickrage.app.config.quality_default),
                    flatten_folders=int(
                        sickrage.app.config.flatten_folders_default),
                    paused=sickrage.app.config.trakt_start_paused,
                    default_status_after=status,
                    scene=sickrage.app.config.scene_default,
                    skip_downloaded=sickrage.app.config.skip_downloaded_default
                )
            else:
                sickrage.app.log.warning(
                    "There was an error creating the show, no root directory setting found"
                )
                return
Пример #5
0
    def formatted_filename(self, pattern=None, multi=None, anime_type=None):
        """
        Just the filename of the episode, formatted based on the naming settings
        """

        if pattern is None:
            # we only use ABD if it's enabled, this is an ABD show, AND this is not a multi-ep
            if self.show.air_by_date and sickrage.app.config.naming_custom_abd and not self.related_episodes:
                pattern = sickrage.app.config.naming_abd_pattern
            elif self.show.sports and sickrage.app.config.naming_custom_sports and not self.related_episodes:
                pattern = sickrage.app.config.naming_sports_pattern
            elif self.show.anime and sickrage.app.config.naming_custom_anime:
                pattern = sickrage.app.config.naming_anime_pattern
            else:
                pattern = sickrage.app.config.naming_pattern

        # split off the dirs only, if they exist
        name_groups = re.split(r'[\\/]', pattern)

        return sanitize_file_name(self._format_pattern(name_groups[-1], multi, anime_type))
Пример #6
0
    async def get(self, *args, **kwargs):
        indexer_id = self.get_argument('indexer_id')
        show_name = self.get_argument('showName')

        if re.search(r'tt\d+', indexer_id):
            l_indexer_api_parms = IndexerApi(1).api_params.copy()
            t = IndexerApi(1).indexer(**l_indexer_api_parms)
            indexer_id = t[indexer_id]['id']

        if find_show(int(indexer_id), session=self.db_session):
            return

        location = None
        if sickrage.app.config.root_dirs:
            root_dirs = sickrage.app.config.root_dirs.split('|')
            location = root_dirs[int(root_dirs[0]) + 1]

        if not location:
            sickrage.app.log.warning(
                "There was an error creating the show, no root directory setting found"
            )
            return self.write(
                _('No root directories setup, please go back and add one.'))

        show_dir = os.path.join(location, sanitize_file_name(show_name))

        response = await TornadoHTTP().get(
            url_concat(
                self.get_url("/home/addShows/newShow"), {
                    'show_to_add':
                    '1|{show_dir}|{indexer_id}|{show_name}'.format(
                        **{
                            'show_dir': show_dir,
                            'indexer_id': indexer_id,
                            'show_name': show_name
                        })
                }))

        return self.write(response.body)
Пример #7
0
    async def post(self, *args, **kwargs):
        """
        Receive tvdb id, dir, and other options and create a show from them. If extra show dirs are
        provided then it forwards back to newShow, if not it goes to /home.
        """

        whichSeries = self.get_argument('whichSeries', None)
        rootDir = self.get_argument('rootDir', None)
        fullShowPath = self.get_argument('fullShowPath', None)
        providedName = self.get_argument('providedName', None)
        indexerLang = self.get_argument('indexerLang', None)
        defaultStatus = self.get_argument('defaultStatus', None)
        quality_preset = self.get_argument('quality_preset', None)
        anyQualities = self.get_arguments('anyQualities')
        bestQualities = self.get_arguments('bestQualities')
        flatten_folders = self.get_argument('flatten_folders', None)
        subtitles = self.get_argument('subtitles', None)
        sub_use_sr_metadata = self.get_argument('sub_use_sr_metadata', None)
        other_shows = self.get_arguments('other_shows')
        skipShow = self.get_argument('skipShow', None)
        providedIndexer = self.get_argument('providedIndexer', None)
        anime = self.get_argument('anime', None)
        scene = self.get_argument('scene', None)
        blacklist = self.get_argument('blacklist', None)
        whitelist = self.get_argument('whitelist', None)
        defaultStatusAfter = self.get_argument('defaultStatusAfter', None)
        skip_downloaded = self.get_argument('skip_downloaded', None)
        add_show_year = self.get_argument('add_show_year', None)

        indexerLang = indexerLang or sickrage.app.config.indexer_default_language

        # if we're skipping then behave accordingly
        if skipShow:
            return self.write(await self.finish_add_show(other_shows))

        if not whichSeries:
            return self.redirect("/home/")

        # figure out what show we're adding and where
        series_pieces = whichSeries.split('|')
        if (whichSeries and rootDir
                or whichSeries and fullShowPath) and len(series_pieces) > 1:
            if len(series_pieces) < 6:
                sickrage.app.log.error(
                    'Unable to add show due to show selection. Not anough arguments: %s'
                    % (repr(series_pieces)))
                sickrage.app.alerts.error(
                    _('Unknown error. Unable to add show due to problem with show selection.'
                      ))
                return self.redirect('/home/addShows/existingShows/')

            indexer = int(series_pieces[1])
            indexer_id = int(series_pieces[3])
            show_name = series_pieces[4]
        else:
            indexer = int(providedIndexer
                          or sickrage.app.config.indexer_default)
            indexer_id = int(whichSeries)
            if fullShowPath:
                show_name = os.path.basename(os.path.normpath(fullShowPath))
            else:
                show_name = providedName

        # use the whole path if it's given, or else append the show name to the root dir to get the full show path
        if fullShowPath:
            show_dir = os.path.normpath(fullShowPath)
        else:
            show_dir = os.path.join(rootDir, sanitize_file_name(show_name))
            if add_show_year and not re.match(r'.*\(\d+\)$',
                                              show_dir) and re.search(
                                                  r'\d{4}', series_pieces[5]):
                show_dir = "{} ({})".format(
                    show_dir,
                    re.search(r'\d{4}', series_pieces[5]).group(0))

        # blanket policy - if the dir exists you should have used "add existing show" numbnuts
        if os.path.isdir(show_dir) and not fullShowPath:
            sickrage.app.alerts.error(
                _("Unable to add show"),
                _("Folder ") + show_dir + _(" exists already"))
            return self.redirect('/home/addShows/existingShows/')

        # don't create show dir if config says not to
        if sickrage.app.config.add_shows_wo_dir:
            sickrage.app.log.info("Skipping initial creation of " + show_dir +
                                  " due to SiCKRAGE configuation setting")
        else:
            dir_exists = make_dir(show_dir)
            if not dir_exists:
                sickrage.app.log.warning("Unable to create the folder " +
                                         show_dir + ", can't add the show")
                sickrage.app.alerts.error(
                    _("Unable to add show"),
                    _("Unable to create the folder " + show_dir +
                      ", can't add the show"))

                # Don't redirect to default page because user wants to see the new show
                return self.redirect("/home/")
            else:
                chmod_as_parent(show_dir)

        # prepare the inputs for passing along
        scene = checkbox_to_value(scene)
        anime = checkbox_to_value(anime)
        flatten_folders = checkbox_to_value(flatten_folders)
        subtitles = checkbox_to_value(subtitles)
        sub_use_sr_metadata = checkbox_to_value(sub_use_sr_metadata)
        skip_downloaded = checkbox_to_value(skip_downloaded)

        if whitelist:
            whitelist = short_group_names(whitelist)
        if blacklist:
            blacklist = short_group_names(blacklist)

        newQuality = try_int(quality_preset, None)
        if not newQuality:
            newQuality = Quality.combine_qualities(map(int, anyQualities),
                                                   map(int, bestQualities))

        # add the show
        sickrage.app.show_queue.add_show(
            indexer=indexer,
            indexer_id=indexer_id,
            showDir=show_dir,
            default_status=int(defaultStatus),
            quality=newQuality,
            flatten_folders=flatten_folders,
            lang=indexerLang,
            subtitles=subtitles,
            sub_use_sr_metadata=sub_use_sr_metadata,
            anime=anime,
            scene=scene,
            paused=None,
            blacklist=blacklist,
            whitelist=whitelist,
            default_status_after=int(defaultStatusAfter),
            skip_downloaded=skip_downloaded)

        sickrage.app.alerts.message(
            _('Adding Show'),
            _('Adding the specified show into ') + show_dir)

        return self.write(await self.finish_add_show(other_shows))
Пример #8
0
    def post(self):
        data = json_decode(self.request.body)

        is_existing = data.get('isExisting', 'false')

        root_directory = data.get('rootDirectory', None)
        series_id = data.get('seriesId', None)
        series_name = data.get('seriesName', None)
        series_directory = data.get('seriesDirectory', None)
        first_aired = data.get('firstAired', None)
        series_provider_slug = data.get('seriesProviderSlug', None)
        series_provider_language = data.get('seriesProviderLanguage', None)
        default_status = data.get('defaultStatus', None)
        default_status_after = data.get('defaultStatusAfter', None)
        quality_preset = data.get('qualityPreset', None)
        allowed_qualities = data.get('allowedQualities', [])
        preferred_qualities = data.get('preferredQualities', [])
        subtitles = self._parse_boolean(
            data.get('subtitles', sickrage.app.config.subtitles.default))
        sub_use_sr_metadata = self._parse_boolean(
            data.get('subUseSrMetadata', 'false'))
        flatten_folders = self._parse_boolean(
            data.get('flattenFolders',
                     sickrage.app.config.general.flatten_folders_default))
        is_anime = self._parse_boolean(
            data.get('isAnime', sickrage.app.config.general.anime_default))
        is_scene = self._parse_boolean(
            data.get('isScene', sickrage.app.config.general.scene_default))
        search_format = data.get(
            'searchFormat',
            sickrage.app.config.general.search_format_default.name)
        dvd_order = self._parse_boolean(data.get('dvdOrder', 'false'))
        skip_downloaded = self._parse_boolean(
            data.get('skipDownloaded',
                     sickrage.app.config.general.skip_downloaded_default))
        add_show_year = self._parse_boolean(data.get('addShowYear', 'false'))

        if not series_id:
            return self.send_error(
                400, error=f"Missing seriesId parameter: {series_id}")

        series_provider_id = SeriesProviderID.by_slug(series_provider_slug)
        if not series_provider_id:
            return self.send_error(
                404,
                error="Unable to identify a series provider using provided slug"
            )

        series = find_show(int(series_id), series_provider_id)
        if series:
            return self.send_error(400,
                                   error=f"Already exists series: {series_id}")

        if is_existing and not series_directory:
            return self.send_error(400,
                                   error="Missing seriesDirectory parameter")

        if not is_existing:
            series_directory = os.path.join(root_directory,
                                            sanitize_file_name(series_name))

            if first_aired:
                series_year = re.search(r'\d{4}', first_aired)
                if add_show_year and not re.match(
                        r'.*\(\d+\)$', series_directory) and series_year:
                    series_directory = f"{series_directory} ({series_year.group()})"

            if os.path.isdir(series_directory):
                sickrage.app.alerts.error(
                    _("Unable to add show"),
                    _("Folder ") + series_directory + _(" exists already"))
                return self.send_error(
                    400,
                    error=f"Show directory {series_directory} already exists!")

            if not make_dir(series_directory):
                sickrage.app.log.warning(
                    f"Unable to create the folder {series_directory}, can't add the show"
                )
                sickrage.app.alerts.error(
                    _("Unable to add show"),
                    _(f"Unable to create the folder {series_directory}, can't add the show"
                      ))
                return self.send_error(
                    400,
                    error=
                    f"Unable to create the show folder {series_directory}, can't add the show"
                )

        chmod_as_parent(series_directory)

        try:
            new_quality = Qualities[quality_preset.upper()]
        except KeyError:
            new_quality = Quality.combine_qualities(
                [Qualities[x.upper()] for x in allowed_qualities],
                [Qualities[x.upper()] for x in preferred_qualities])

        sickrage.app.show_queue.add_show(
            series_provider_id=series_provider_id,
            series_id=int(series_id),
            showDir=series_directory,
            default_status=EpisodeStatus[default_status.upper()],
            default_status_after=EpisodeStatus[default_status_after.upper()],
            quality=new_quality,
            flatten_folders=flatten_folders,
            lang=series_provider_language,
            subtitles=subtitles,
            sub_use_sr_metadata=sub_use_sr_metadata,
            anime=is_anime,
            dvd_order=dvd_order,
            search_format=SearchFormat[search_format.upper()],
            paused=False,
            # blacklist=blacklist,
            # whitelist=whitelist,
            scene=is_scene,
            skip_downloaded=skip_downloaded)

        sickrage.app.alerts.message(
            _('Adding Show'),
            _(f'Adding the specified show into {series_directory}'))

        return self.write_json({'message': True})
Пример #9
0
 def make_filename(self, name):
     return os.path.join(sickrage.app.config.nzb_dir, '{}.nzb'.format(sanitize_file_name(name)))