Beispiel #1
0
def get_indexer_absolute_numbering_for_xem(indexer_id,
                                           indexer,
                                           sceneAbsoluteNumber,
                                           scene_season=None):
    """
    Reverse of find_xem_numbering: lookup a tvdb season and episode using scene numbering

    :param indexer_id: int
    :param sceneAbsoluteNumber: int
    :return: int
    """
    if indexer_id is None or sceneAbsoluteNumber is None:
        return sceneAbsoluteNumber

    indexer_id = int(indexer_id)
    indexer = int(indexer)

    xem_refresh(indexer_id, indexer)

    if scene_season is None:
        rows = main_db.MainDB().select(
            "SELECT absolute_number FROM tv_episodes WHERE indexer = ? AND showid = ? AND scene_absolute_number = ?",
            [indexer, indexer_id, sceneAbsoluteNumber])
    else:
        rows = main_db.MainDB().select(
            "SELECT absolute_number FROM tv_episodes WHERE indexer = ? AND showid = ? AND scene_absolute_number = ? AND scene_season = ?",
            [indexer, indexer_id, sceneAbsoluteNumber, scene_season])

    if rows:
        return int(rows[0][b"absolute_number"])

    return sceneAbsoluteNumber
Beispiel #2
0
def setUp_test_db(force=False):
    """upgrades the db to the latest version
    """

    global TESTDB_INITALIZED

    if not TESTDB_INITALIZED or force:
        # remove old db files
        tearDown_test_db()

        # upgrade main
        main_db.MainDB().InitialSchema().upgrade()

        # sanity check main
        main_db.MainDB().SanityCheck()

        # upgrade cache
        cache_db.CacheDB().InitialSchema().upgrade()

        # upgrade failed
        failed_db.FailedDB().InitialSchema().upgrade()

        # populate scene exceiptions table
        # retrieve_exceptions(False, False)

        TESTDB_INITALIZED = True
Beispiel #3
0
def get_indexer_absolute_numbering(indexer_id,
                                   indexer,
                                   sceneAbsoluteNumber,
                                   fallback_to_xem=True,
                                   scene_season=None):
    """
    Returns a tuple, (season, episode, absolute_number) with the TVDB absolute numbering for (sceneAbsoluteNumber)
    (this works like the reverse of get_absolute_numbering)
    """
    if indexer_id is None or sceneAbsoluteNumber is None:
        return sceneAbsoluteNumber

    indexer_id = int(indexer_id)
    indexer = int(indexer)

    if scene_season is None:
        rows = main_db.MainDB().select(
            "SELECT absolute_number FROM scene_numbering WHERE indexer = ? AND indexer_id = ? AND scene_absolute_number = ?",
            [indexer, indexer_id, sceneAbsoluteNumber])
    else:
        rows = main_db.MainDB().select(
            "SELECT absolute_number FROM scene_numbering WHERE indexer = ? AND indexer_id = ? AND scene_absolute_number = ? AND scene_season = ?",
            [indexer, indexer_id, sceneAbsoluteNumber, scene_season])

    if rows:
        return int(rows[0][b"absolute_number"])
    else:
        if fallback_to_xem:
            return get_indexer_absolute_numbering_for_xem(
                indexer_id, indexer, sceneAbsoluteNumber, scene_season)
        return sceneAbsoluteNumber
Beispiel #4
0
def already_postprocessed(dirName, videofile, force, result):
    """
    Check if we already post processed a file

    :param dirName: Directory a file resides in
    :param videofile: File name
    :param force: Force checking when already checking (currently unused)
    :param result: True if file is already postprocessed, False if not
    :return:
    """
    if force:
        return False

    # Avoid processing the same dir again if we use a process method <> move
    if main_db.MainDB().select(
            "SELECT * FROM tv_episodes WHERE release_name = ?", [dirName]):
        # result.output += logHelper(u"You're trying to post process a dir that's already been processed, skipping", LOGGER.DEBUG)
        return True

    else:
        if main_db.MainDB().select(
                "SELECT * FROM tv_episodes WHERE release_name = ?",
            [videofile.rpartition('.')[0]]):
            # result.output += logHelper(u"You're trying to post process a video that's already been processed, skipping", LOGGER.DEBUG)
            return True

        # Needed if we have downloaded the same episode @ different quality
        # But we need to make sure we check the history of the episode we're going to PP, and not others
        np = NameParser(dirName, tryIndexers=True)
        try:
            parse_result = np.parse(dirName)
        except:
            parse_result = False

        search_sql = "SELECT tv_episodes.indexerid, history.resource FROM tv_episodes INNER JOIN history ON history.showid=tv_episodes.showid"  # This part is always the same
        search_sql += " WHERE history.season=tv_episodes.season and history.episode=tv_episodes.episode"
        # If we find a showid, a season number, and one or more episode numbers then we need to use those in the query
        if parse_result and (parse_result.show.indexerid
                             and parse_result.episode_numbers
                             and parse_result.season_number):
            search_sql += " and tv_episodes.showid = '" + str(
                parse_result.show.indexerid
            ) + "' and tv_episodes.season = '" + str(
                parse_result.season_number
            ) + "' and tv_episodes.episode = '" + str(
                parse_result.episode_numbers[0]) + "'"

        search_sql += " and tv_episodes.status IN (" + ",".join(
            [str(x) for x in Quality.DOWNLOADED]) + ")"
        search_sql += " and history.resource LIKE ?"
        if main_db.MainDB().select(search_sql, ['%' + videofile]):
            # result.output += logHelper(u"You're trying to post process a video that's already been processed, skipping", LOGGER.DEBUG)
            return True

    return False
Beispiel #5
0
    def get(self, limit=100, action=None):
        """
        :param limit: The maximum number of elements to return
        :param action: The type of action to filter in the history. Either 'downloaded' or 'snatched'. Anything else or
                        no value will return everything (up to ``limit``)
        :return: The last ``limit`` elements of type ``action`` in the history
        """

        action = action.lower() if isinstance(action, str) else ''
        limit = int(limit)

        if action == 'downloaded':
            actions = Quality.DOWNLOADED
        elif action == 'snatched':
            actions = Quality.SNATCHED
        else:
            actions = []

        common_sql = 'SELECT action, date, episode, provider, h.quality, resource, season, show_name, showid ' \
                     'FROM history h, tv_shows s ' \
                     'WHERE h.showid = s.indexer_id '
        filter_sql = 'AND action in (' + ','.join(['?'] * len(actions)) + ') '
        order_sql = 'ORDER BY date DESC '

        if limit == 0:
            if len(actions) > 0:
                results = main_db.MainDB().select(
                    common_sql + filter_sql + order_sql, actions)
            else:
                results = main_db.MainDB().select(common_sql + order_sql)
        else:
            if len(actions) > 0:
                results = main_db.MainDB().select(
                    common_sql + filter_sql + order_sql + 'LIMIT ?',
                    actions + [limit])
            else:
                results = main_db.MainDB().select(
                    common_sql + order_sql + 'LIMIT ?', [limit])

        data = []
        for result in results:
            data.append({
                'action': result[b'action'],
                'date': result[b'date'],
                'episode': result[b'episode'],
                'provider': result[b'provider'],
                'quality': result[b'quality'],
                'resource': result[b'resource'],
                'season': result[b'season'],
                'show_id': result[b'showid'],
                'show_name': result[b'show_name']
            })

        return data
Beispiel #6
0
    def _set_lastBacklog(self, when):

        sickrage.srLogger.debug("Setting the last backlog in the DB to " +
                                str(when))

        sqlResults = main_db.MainDB().select("SELECT * FROM info")

        if len(sqlResults) == 0:
            main_db.MainDB().action(
                "INSERT INTO info (last_backlog, last_indexer) VALUES (?,?)",
                [str(when), 0])
        else:
            main_db.MainDB().action("UPDATE info SET last_backlog=" +
                                    str(when))
Beispiel #7
0
def get_xem_absolute_numbering_for_show(indexer_id, indexer):
    """
    Returns a dict of (season, episode) : (sceneSeason, sceneEpisode) mappings
    for an entire show.  Both the keys and values of the dict are tuples.
    Will be empty if there are no scene numbers set in xem
    """
    if indexer_id is None:
        return {}

    indexer_id = int(indexer_id)
    indexer = int(indexer)

    xem_refresh(indexer_id, indexer)

    result = {}

    rows = main_db.MainDB().select(
        'SELECT absolute_number, scene_absolute_number FROM tv_episodes WHERE indexer = ? AND showid = ? AND scene_absolute_number != 0 ORDER BY absolute_number',
        [indexer, indexer_id])

    for row in rows:
        absolute_number = int(row[b'absolute_number'])
        scene_absolute_number = int(row[b'scene_absolute_number'])

        result[absolute_number] = scene_absolute_number

    return result
Beispiel #8
0
    def _del_all_keywords(self, table):
        """
        DB: Remove all keywords for current show

        :param table: SQL table remove keywords from
        """
        main_db.MainDB().action('DELETE FROM [' + table + '] WHERE show_id = ?', [self.show_id])
Beispiel #9
0
    def addEpisodeToTraktWatchList(self):
        if sickrage.srConfig.TRAKT_SYNC_WATCHLIST and sickrage.srConfig.USE_TRAKT:
            sickrage.srLogger.debug("WATCHLIST::ADD::START - Look for Episodes to Add to Trakt Watchlist")

            sql_selection = 'SELECT tv_shows.indexer, tv_shows.startyear, showid, show_name, season, episode FROM tv_episodes,tv_shows WHERE tv_shows.indexer_id = tv_episodes.showid AND tv_episodes.status IN (' + ','.join(
                    [str(x) for x in Quality.SNATCHED + Quality.SNATCHED_PROPER + [WANTED]]) + ')'
            episodes = main_db.MainDB().select(sql_selection)

            if episodes is not None:
                trakt_data = []

                for cur_episode in episodes:
                    trakt_id = sickrage.srCore.INDEXER_API(cur_episode[b"indexer"]).config[b'trakt_id']

                    if not self._checkInList(trakt_id, str(cur_episode[b"showid"]), str(cur_episode[b"season"]),
                                             str(cur_episode[b"episode"])):
                        sickrage.srLogger.debug("Adding Episode %s S%02dE%02d to watchlist" %
                                                 (cur_episode[b"show_name"], cur_episode[b"season"], cur_episode[b"episode"]))
                        trakt_data.append((cur_episode[b"showid"], cur_episode[b"indexer"], cur_episode[b"show_name"],
                                           cur_episode[b"startyear"], cur_episode[b"season"],
                                           cur_episode[b"episode"]))

                if len(trakt_data):
                    try:
                        data = self.trakt_bulk_data_generate(trakt_data)
                        self.trakt_api.traktRequest("sync/watchlist", data, method='POST')
                        self._getEpisodeWatchlist()
                    except traktException as e:
                        sickrage.srLogger.warning("Could not connect to Trakt service. Error %s" % e)

            sickrage.srLogger.debug("WATCHLIST::ADD::FINISH - Look for Episodes to Add to Trakt Watchlist")
Beispiel #10
0
    def removeEpisodeFromTraktCollection(self):
        if sickrage.srConfig.TRAKT_SYNC_REMOVE and sickrage.srConfig.TRAKT_SYNC and sickrage.srConfig.USE_TRAKT:
            sickrage.srLogger.debug("COLLECTION::REMOVE::START - Look for Episodes to Remove From Trakt Collection")

            sql_selection = 'SELECT tv_shows.indexer, tv_shows.startyear, showid, show_name, season, episode, tv_episodes.status, tv_episodes.location FROM tv_episodes,tv_shows WHERE tv_shows.indexer_id = tv_episodes.showid'
            episodes = main_db.MainDB().select(sql_selection)

            if episodes is not None:
                trakt_data = []

                for cur_episode in episodes:
                    trakt_id = sickrage.srCore.INDEXER_API(cur_episode[b"indexer"]).config[b'trakt_id']

                    if self._checkInList(trakt_id, str(cur_episode[b"showid"]), str(cur_episode[b"season"]),
                                         str(cur_episode[b"episode"]), List='Collection'):
                        if cur_episode[b"location"] == '':
                            sickrage.srLogger.debug("Removing Episode %s S%02dE%02d from collection" %
                                                     (cur_episode[b"show_name"], cur_episode[b"season"], cur_episode[b"episode"]))
                            trakt_data.append(
                                    (cur_episode[b"showid"], cur_episode[b"indexer"], cur_episode[b"show_name"],
                                     cur_episode[b"startyear"], cur_episode[b"season"], cur_episode[b"episode"]))

                if len(trakt_data):
                    try:
                        data = self.trakt_bulk_data_generate(trakt_data)
                        self.trakt_api.traktRequest("sync/collection/remove", data, method='POST')
                        self._getShowCollection()
                    except traktException as e:
                        sickrage.srLogger.warning("Could not connect to Trakt service. Error: %s" % e)

            sickrage.srLogger.debug("COLLECTION::REMOVE::FINISH - Look for Episodes to Remove From Trakt Collection")
Beispiel #11
0
    def _logHistoryItem(action,
                        showid,
                        season,
                        episode,
                        quality,
                        resource,
                        provider,
                        version=-1):
        """
        Insert a history item in DB

        :param action: action taken (snatch, download, etc)
        :param showid: showid this entry is about
        :param season: show season
        :param episode: show episode
        :param quality: media quality
        :param resource: resource used
        :param provider: provider used
        :param version: tracked version of file (defaults to -1)
        """
        logDate = datetime.today().strftime(History.date_format)
        resource = resource

        main_db.MainDB().action(
            "INSERT INTO history (action, date, showid, season, episode, quality, resource, provider, version) VALUES (?,?,?,?,?,?,?,?,?)",
            [
                action, logDate, showid, season, episode, quality, resource,
                provider, version
            ])
Beispiel #12
0
def get_xem_numbering_for_show(indexer_id, indexer):
    """
    Returns a dict of (season, episode) : (sceneSeason, sceneEpisode) mappings
    for an entire show.  Both the keys and values of the dict are tuples.
    Will be empty if there are no scene numbers set in xem
    """
    if indexer_id is None:
        return {}

    indexer_id = int(indexer_id)
    indexer = int(indexer)

    xem_refresh(indexer_id, indexer)

    rows = main_db.MainDB().select(
        'SELECT season, episode, scene_season, scene_episode FROM tv_episodes WHERE indexer = ? AND showid = ? AND (scene_season OR scene_episode) != 0 ORDER BY season, episode',
        [indexer, indexer_id])

    result = {}
    for row in rows:
        season = int(row[b'season'])
        episode = int(row[b'episode'])
        scene_season = int(row[b'scene_season'])
        scene_episode = int(row[b'scene_episode'])

        result[(season, episode)] = (scene_season, scene_episode)

    return result
Beispiel #13
0
def get_indexer_numbering_for_xem(indexer_id, indexer, sceneSeason,
                                  sceneEpisode):
    """
    Reverse of find_xem_numbering: lookup a tvdb season and episode using scene numbering

    :param indexer_id: int
    :param sceneSeason: int
    :param sceneEpisode: int
    :return: (int, int) a tuple of (season, episode)
    """
    if indexer_id is None or sceneSeason is None or sceneEpisode is None:
        return sceneSeason, sceneEpisode

    indexer_id = int(indexer_id)
    indexer = int(indexer)

    xem_refresh(indexer_id, indexer)

    rows = main_db.MainDB().select(
        "SELECT season, episode FROM tv_episodes WHERE indexer = ? AND showid = ? AND scene_season = ? AND scene_episode = ?",
        [indexer, indexer_id, sceneSeason, sceneEpisode])

    if rows:
        return int(rows[0][b"season"]), int(rows[0][b"episode"])

    return sceneSeason, sceneEpisode
Beispiel #14
0
def get_absolute_number_from_season_and_episode(show, season, episode):
    """
    Find the absolute number for a show episode

    :param show: Show object
    :param season: Season number
    :param episode: Episode number
    :return: The absolute number
    """

    absolute_number = None

    if season and episode:
        sql = "SELECT * FROM tv_episodes WHERE showid = ? AND season = ? AND episode = ?"
        sqlResults = main_db.MainDB().select(sql,
                                             [show.indexerid, season, episode])

        if len(sqlResults) == 1:
            absolute_number = int(sqlResults[0][b"absolute_number"])
            sickrage.srLogger.debug(
                "Found absolute number %s for show %s S%02dE%02d" %
                (absolute_number, show.name, season, episode))
        else:
            sickrage.srLogger.debug(
                "No entries for absolute number for show %s S%02dE%02d" %
                (show.name, season, episode))

    return absolute_number
Beispiel #15
0
def get_indexer_numbering(indexer_id,
                          indexer,
                          sceneSeason,
                          sceneEpisode,
                          fallback_to_xem=True):
    """
    Returns a tuple, (season, episode) with the TVDB numbering for (sceneSeason, sceneEpisode)
    (this works like the reverse of get_scene_numbering)
    """
    if indexer_id is None or sceneSeason is None or sceneEpisode is None:
        return sceneSeason, sceneEpisode

    indexer_id = int(indexer_id)
    indexer = int(indexer)

    rows = main_db.MainDB().select(
        "SELECT season, episode FROM scene_numbering WHERE indexer = ? AND indexer_id = ? AND scene_season = ? AND scene_episode = ?",
        [indexer, indexer_id, sceneSeason, sceneEpisode])

    if rows:
        return int(rows[0][b"season"]), int(rows[0][b"episode"])
    else:
        if fallback_to_xem:
            return get_indexer_numbering_for_xem(indexer_id, indexer,
                                                 sceneSeason, sceneEpisode)
        return sceneSeason, sceneEpisode
Beispiel #16
0
def searchDBForShow(regShowName, log=False):
    """
    Searches if show names are present in the DB

    :param regShowName: list of show names to look for
    :param log: Boolean, log debug results of search (defaults to False)
    :return: Indexer ID of found show
    """

    showNames = [re.sub('[. -]', ' ', regShowName)]

    yearRegex = r"([^()]+?)\s*(\()?(\d{4})(?(2)\))$"

    for showName in showNames:

        sqlResults = main_db.MainDB().select(
            "SELECT * FROM tv_shows WHERE show_name LIKE ?", [showName])

        if len(sqlResults) == 1:
            return int(sqlResults[0][b"indexer_id"])
        else:
            # if we didn't get exactly one result then try again with the year stripped off if possible
            match = re.match(yearRegex, showName)
            if match and match.group(1):
                if log:
                    sickrage.srLogger.debug(
                        "Unable to match original name but trying to manually strip and specify show year"
                    )
                sqlResults = main_db.MainDB().select(
                    "SELECT * FROM tv_shows WHERE (show_name LIKE ?) AND startyear = ?",
                    [match.group(1) + '%',
                     match.group(3)])

            if len(sqlResults) == 0:
                if log:
                    sickrage.srLogger.debug(
                        "Unable to match a record in the DB for " + showName)
                continue
            elif len(sqlResults) > 1:
                if log:
                    sickrage.srLogger.debug(
                        "Multiple results for " + showName +
                        " in the DB, unable to match show name")
                continue
            else:
                return int(sqlResults[0][b"indexer_id"])
Beispiel #17
0
    def _set_lastProperSearch(self, when):
        """
        Record last propersearch in DB

        :param when: When was the last proper search
        """

        sickrage.srLogger.debug(
            "Setting the last Proper search in the DB to " + str(when))

        sqlResults = main_db.MainDB().select("SELECT * FROM info")

        if len(sqlResults) == 0:
            main_db.MainDB().action(
                "INSERT INTO info (last_backlog, last_indexer, last_proper_search) VALUES (?,?,?)",
                [0, 0, str(when)])
        else:
            main_db.MainDB().action("UPDATE info SET last_proper_search=" +
                                    str(when))
Beispiel #18
0
    def _add_keywords(self, table, values):
        """
        DB: Adds keywords into database for current show

        :param table: SQL table to add keywords to
        :param values: Values to be inserted in table
        """
        for value in values:
            main_db.MainDB().action('INSERT INTO [' + table + '] (show_id, keyword) VALUES (?,?)',
                                    [self.show_id, value])
Beispiel #19
0
    def trim(self):
        """
        Remove all elements older than 30 days from the history
        """

        main_db.MainDB().action(
            'DELETE '
            'FROM history '
            'WHERE date < ?',
            [(datetime.today() - timedelta(days=30)).strftime(
                History.date_format)])
Beispiel #20
0
def set_scene_numbering(indexer_id,
                        indexer,
                        season=None,
                        episode=None,
                        absolute_number=None,
                        sceneSeason=None,
                        sceneEpisode=None,
                        sceneAbsolute=None):
    """
    Set scene numbering for a season/episode.
    To clear the scene numbering, leave both sceneSeason and sceneEpisode as None.
    """
    if indexer_id is None:
        return

    indexer_id = int(indexer_id)
    indexer = int(indexer)

    if season and episode:
        main_db.MainDB().action(
            "INSERT OR IGNORE INTO scene_numbering (indexer, indexer_id, season, episode) VALUES (?,?,?,?)",
            [indexer, indexer_id, season, episode])

        main_db.MainDB().action(
            "UPDATE scene_numbering SET scene_season = ?, scene_episode = ? WHERE indexer = ? AND indexer_id = ? AND season = ? AND episode = ?",
            [sceneSeason, sceneEpisode, indexer, indexer_id, season, episode])
    elif absolute_number:
        main_db.MainDB().action(
            "INSERT OR IGNORE INTO scene_numbering (indexer, indexer_id, absolute_number) VALUES (?,?,?)",
            [indexer, indexer_id, absolute_number])

        main_db.MainDB().action(
            "UPDATE scene_numbering SET scene_absolute_number = ? WHERE indexer = ? AND indexer_id = ? AND absolute_number = ?",
            [sceneAbsolute, indexer, indexer_id, absolute_number])

    # Reload data from DB so that cache and db are in sync
    show = findCertainShow(sickrage.srCore.SHOWLIST, indexer_id)
    show.flushEpisodes()
Beispiel #21
0
    def _get_lastProperSearch():
        """
        Find last propersearch from DB
        """

        sqlResults = main_db.MainDB().select("SELECT * FROM info")

        try:
            last_proper_search = date.fromordinal(
                int(sqlResults[0][b"last_proper_search"]))
        except:
            return date.fromordinal(1)

        return last_proper_search
Beispiel #22
0
def makeSceneSearchString(show, ep_obj):
    numseasons = 0

    numseasonsSQlResult = main_db.MainDB().select(
        "SELECT COUNT(DISTINCT season) as numseasons FROM tv_episodes WHERE showid = ? and season != 0",
        [show.indexerid])
    if numseasonsSQlResult:
        numseasons = int(numseasonsSQlResult[0][0])

    # see if we should use dates instead of episodes
    if (show.air_by_date
            or show.sports) and ep_obj.airdate != date.fromordinal(1):
        epStrings = [str(ep_obj.airdate)]
    elif show.is_anime:
        epStrings = [
            "%02i" %
            int(ep_obj.scene_absolute_number
                if ep_obj.scene_absolute_number > 0 else ep_obj.scene_episode)
        ]
    else:
        epStrings = [
            "S%02iE%02i" %
            (int(ep_obj.scene_season), int(ep_obj.scene_episode)),
            "%ix%02i" % (int(ep_obj.scene_season), int(ep_obj.scene_episode))
        ]

    # for single-season shows just search for the show name -- if total ep count (exclude s0) is less than 11
    # due to the amount of qualities and releases, it is easy to go over the 50 result limit on rss feeds otherwise
    if numseasons == 1 and not ep_obj.show.is_anime:
        epStrings = ['']

    showNames = set(makeSceneShowSearchStrings(show, ep_obj.scene_season))

    toReturn = []

    for curShow in showNames:
        for curEpString in epStrings:
            if ep_obj.show.is_anime:
                if ep_obj.show.release_groups is not None:
                    if len(ep_obj.show.release_groups.whitelist) > 0:
                        for keyword in ep_obj.show.release_groups.whitelist:
                            toReturn.append(keyword + '.' + curShow + '.' +
                                            curEpString)
                    elif len(ep_obj.show.release_groups.blacklist) == 0:
                        # If we have neither whitelist or blacklist we just append what we have
                        toReturn.append(curShow + '.' + curEpString)
            else:
                toReturn.append(curShow + '.' + curEpString)

    return toReturn
Beispiel #23
0
    def loadFromDB(self):
        """
        Populates the showList with shows from the database
        """

        sqlResults = main_db.MainDB().select("SELECT * FROM tv_shows")

        for sqlShow in sqlResults:
            try:
                curShow = TVShow(int(sqlShow[b"indexer"]),
                                 int(sqlShow[b"indexer_id"]))
                curShow.saveToDB()
                curShow.loadFromDB(skipNFO=True)
                sickrage.srCore.SHOWLIST.append(curShow)
            except Exception as e:
                print "There was an error creating the show"
Beispiel #24
0
def find_scene_absolute_numbering(indexer_id, indexer, absolute_number):
    """
    Same as get_scene_numbering(), but returns None if scene numbering is not set
    """
    if indexer_id is None or absolute_number is None:
        return absolute_number

    indexer_id = int(indexer_id)
    indexer = int(indexer)

    rows = main_db.MainDB().select(
        "SELECT scene_absolute_number FROM scene_numbering WHERE indexer = ? AND indexer_id = ? AND absolute_number = ? AND scene_absolute_number != 0",
        [indexer, indexer_id, absolute_number])

    if rows:
        return int(rows[0][b"scene_absolute_number"])
Beispiel #25
0
def find_scene_numbering(indexer_id, indexer, season, episode):
    """
    Same as get_scene_numbering(), but returns None if scene numbering is not set
    """
    if indexer_id is None or season is None or episode is None:
        return season, episode

    indexer_id = int(indexer_id)
    indexer = int(indexer)

    rows = main_db.MainDB().select(
        "SELECT scene_season, scene_episode FROM scene_numbering WHERE indexer = ? AND indexer_id = ? AND season = ? AND episode = ? AND (scene_season OR scene_episode) != 0",
        [indexer, indexer_id, season, episode])

    if rows:
        return int(rows[0][b"scene_season"]), int(rows[0][b"scene_episode"])
Beispiel #26
0
    def _get_segments(self, show, fromDate):
        if show.paused:
            sickrage.srLogger.debug(
                "Skipping backlog for {show_name} because the show is paused".
                format(show_name=show.name))
            return {}

        anyQualities, bestQualities = Quality.splitQuality(
            show.quality)  # @UnusedVariable

        sickrage.srLogger.debug(
            "Seeing if we need anything from {show_name}".format(
                show_name=show.name))

        sqlResults = main_db.MainDB().select(
            "SELECT status, season, episode FROM tv_episodes WHERE season > 0 AND airdate > ? AND showid = ?",
            [fromDate.toordinal(), show.indexerid])

        # check through the list of statuses to see if we want any
        wanted = {}
        for result in sqlResults:
            curCompositeStatus = int(result[b"status"] or -1)
            curStatus, curQuality = Quality.splitCompositeStatus(
                curCompositeStatus)

            if bestQualities:
                highestBestQuality = max(bestQualities)
                lowestBestQuality = min(bestQualities)
            else:
                highestBestQuality = 0
                lowestBestQuality = 0

            # if we need a better one then say yes
            if (curStatus in (DOWNLOADED, SNATCHED, SNATCHED_PROPER) and
                    curQuality < highestBestQuality) or curStatus == WANTED:
                epObj = show.getEpisode(int(result[b"season"]),
                                        int(result[b"episode"]))

                # only fetch if not archive on first match, or if show is lowest than the lower expected quality
                if (epObj.show.archive_firstmatch == 0
                        or curQuality < lowestBestQuality):
                    if epObj.season not in wanted:
                        wanted[epObj.season] = [epObj]
                    else:
                        wanted[epObj.season].append(epObj)

        return wanted
Beispiel #27
0
    def load_shows(self):
        """
        Populates the showlist with shows from the database
        """

        for sqlShow in main_db.MainDB().select("SELECT * FROM tv_shows"):
            try:
                curshow = TVShow(int(sqlShow[b"indexer"]), int(sqlShow[b"indexer_id"]))
                sickrage.srLogger.debug("Loading data for show: [{}]".format(curshow.name))
                self.NAMECACHE.buildNameCache(curshow)
                curshow.nextEpisode()
                self.SHOWLIST += [curshow]
            except Exception as e:
                sickrage.srLogger.error(
                    "There was an error creating the show in {}: {}".format(sqlShow[b"location"], e.message))
                sickrage.srLogger.debug(traceback.format_exc())
                continue
Beispiel #28
0
    def _get_lastBacklog(self):

        sickrage.srLogger.debug("Retrieving the last check time from the DB")

        sqlResults = main_db.MainDB().select("SELECT * FROM info")

        if len(sqlResults) == 0:
            lastBacklog = 1
        elif sqlResults[0][b"last_backlog"] is None or sqlResults[0][
                b"last_backlog"] == "":
            lastBacklog = 1
        else:
            lastBacklog = int(sqlResults[0][b"last_backlog"])
            if lastBacklog > date.today().toordinal():
                lastBacklog = 1

        self._lastBacklog = lastBacklog
        return self._lastBacklog
Beispiel #29
0
    def _load_list(self, table):
        """
        DB: Fetch keywords for current show

        :param table: Table to fetch list of keywords from

        :return: keywords in list
        """
        sqlResults = main_db.MainDB().select('SELECT keyword FROM [' + table + '] WHERE show_id = ?', [self.show_id])
        if not sqlResults or not len(sqlResults):
            return []
        groups = []
        for result in sqlResults:
            groups.append(result[b"keyword"])

        sickrage.srLogger.debug('BWL: ' + str(self.show_id) + ' loaded keywords from ' + table + ': ' + str(groups))

        return groups
Beispiel #30
0
    def _is_season_pack(name):

        try:
            myParser = NameParser(tryIndexers=True)
            parse_result = myParser.parse(name)
        except InvalidNameException:
            sickrage.srLogger.debug(
                "Unable to parse the filename %s into a valid episode" % name)
            return False
        except InvalidShowException:
            sickrage.srLogger.debug(
                "Unable to parse the filename %s into a valid show" % name)
            return False

        sql_selection = "SELECT count(*) AS count FROM tv_episodes WHERE showid = ? AND season = ?"
        episodes = main_db.MainDB().select(
            sql_selection,
            [parse_result.show.indexerid, parse_result.season_number])
        if int(episodes[0][b'count']) == len(parse_result.episode_numbers):
            return True