示例#1
0
def new_episode_finder():
    curDate = datetime.date.today()
    if tz_updater.network_dict:
        curDate += datetime.timedelta(days=1)
    else:
        curDate += datetime.timedelta(days=2)

    curTime = datetime.datetime.now(sickrage.app.tz)

    show = None

    for episode in sickrage.app.main_db.all('tv_episodes'):
        if not all([
                episode['status'] == common.UNAIRED, episode['season'] > 0,
                episode['airdate'] > 1
        ]):
            continue

        if not show or int(episode["showid"]) != show.indexerid:
            show = findCertainShow(int(episode["showid"]))

        # for when there is orphaned series in the database but not loaded into our showlist
        if not show or show.paused:
            continue

        air_date = datetime.date.fromordinal(episode['airdate'])
        air_date += datetime.timedelta(days=show.search_delay)
        if not curDate.toordinal() >= air_date.toordinal():
            continue

        if show.airs and show.network:
            # This is how you assure it is always converted to local time
            air_time = tz_updater.parse_date_time(
                episode['airdate'], show.airs,
                show.network).astimezone(sickrage.app.tz)

            # filter out any episodes that haven't started airing yet,
            # but set them to the default status while they are airing
            # so they are snatched faster
            if air_time > curTime:
                continue

        ep_obj = show.getEpisode(int(episode['season']),
                                 int(episode['episode']))
        with ep_obj.lock:
            ep_obj.status = show.default_ep_status if ep_obj.season else common.SKIPPED
            sickrage.app.log.info(
                'Setting status ({status}) for show airing today: {name} {special}'
                .format(
                    name=ep_obj.pretty_name(),
                    status=common.statusStrings[ep_obj.status],
                    special='(specials are not supported)'
                    if not ep_obj.season else '',
                ))

            ep_obj.saveToDB()
示例#2
0
    def airdateModifyStamp(self):
        """
        Make the modify date and time of a file reflect the show air date and time.
        Note: Also called from postProcessor

        """

        if not self.show.airs and self.show.network:
            return

        airdate_ordinal = self.airdate.toordinal()
        if airdate_ordinal < 1:
            return

        airdatetime = tz_updater.parse_date_time(airdate_ordinal, self.show.airs, self.show.network)

        if sickrage.FILE_TIMESTAMP_TIMEZONE == 'local':
            airdatetime = airdatetime.astimezone(tz_updater.sr_timezone)

        filemtime = datetime.datetime.fromtimestamp(os.path.getmtime(self.location)).replace(
                tzinfo=tz_updater.sr_timezone)

        if filemtime != airdatetime:
            import time

            airdatetime = airdatetime.timetuple()
            sickrage.LOGGER.debug(str(self.show.indexerid) + ": About to modify date of '" + self.location +
                          "' to show air date " + time.strftime("%b %d,%Y (%H:%M)", airdatetime))
            try:
                if touchFile(self.location, time.mktime(airdatetime)):
                    sickrage.LOGGER.info(
                            str(self.show.indexerid) + ": Changed modify date of " + os.path.basename(self.location)
                            + " to show air date " + time.strftime("%b %d,%Y (%H:%M)", airdatetime))
                else:
                    sickrage.LOGGER.error(
                            str(self.show.indexerid) + ": Unable to modify date of " + os.path.basename(
                                self.location)
                            + " to show air date " + time.strftime("%b %d,%Y (%H:%M)", airdatetime))
            except Exception:
                sickrage.LOGGER.error(
                        str(self.show.indexerid) + ": Failed to modify date of '" + os.path.basename(self.location)
                        + "' to show air date " + time.strftime("%b %d,%Y (%H:%M)", airdatetime))
示例#3
0
    def get_coming_episodes(categories, sort, group, paused=False):
        """
        :param categories: The categories of coming episodes. See ``ComingEpisodes.categories``
        :param sort: The sort to apply to the coming episodes. See ``ComingEpisodes.sorts``
        :param group: ``True`` to group the coming episodes by category, ``False`` otherwise
        :param paused: ``True`` to include paused shows, ``False`` otherwise
        :return: The list of coming episodes
        """

        paused = sickrage.COMING_EPS_DISPLAY_PAUSED or paused

        if not isinstance(categories, list):
            categories = categories.split('|')

        if sort not in ComingEpisodes.sorts.keys():
            sort = 'date'

        today = date.today().toordinal()
        next_week = (date.today() + timedelta(days=7)).toordinal()
        recently = (date.today() - timedelta(days=sickrage.COMING_EPS_MISSED_RANGE)).toordinal()
        qualities_list = Quality.DOWNLOADED + \
                         Quality.SNATCHED + \
                         Quality.SNATCHED_BEST + \
                         Quality.SNATCHED_PROPER + \
                         Quality.ARCHIVED + \
                         Quality.IGNORED

        fields_to_select = ', '.join(
                ['airdate', 'airs', 'description', 'episode', 'imdb_id', 'e.indexer', 'indexer_id', 'name', 'network',
                 'paused', 'quality', 'runtime', 'season', 'show_name', 'showid', 's.status']
        )
        results = main_db.MainDB().select(
                'SELECT %s ' % fields_to_select +
                'FROM tv_episodes e, tv_shows s '
                'WHERE season != 0 '
                'AND airdate >= ? '
                'AND airdate < ? '
                'AND s.indexer_id = e.showid '
                'AND e.status NOT IN (' + ','.join(['?'] * len(qualities_list)) + ')',
                [today, next_week] + qualities_list
        )

        done_shows_list = [int(result[b'showid']) for result in results]
        placeholder = ','.join(['?'] * len(done_shows_list))
        placeholder2 = ','.join(
                ['?'] * len(Quality.DOWNLOADED + Quality.SNATCHED + Quality.SNATCHED_BEST + Quality.SNATCHED_PROPER))

        results += main_db.MainDB().select(
                'SELECT %s ' % fields_to_select +
                'FROM tv_episodes e, tv_shows s '
                'WHERE season != 0 '
                'AND showid NOT IN (' + placeholder + ') '
                                                      'AND s.indexer_id = e.showid '
                                                      'AND airdate = (SELECT airdate '
                                                      'FROM tv_episodes inner_e '
                                                      'WHERE inner_e.season != 0 '
                                                      'AND inner_e.showid = e.showid '
                                                      'AND inner_e.airdate >= ? '
                                                      'ORDER BY inner_e.airdate ASC LIMIT 1) '
                                                      'AND e.status NOT IN (' + placeholder2 + ')',
                done_shows_list + [
                    next_week] + Quality.DOWNLOADED + Quality.SNATCHED + Quality.SNATCHED_BEST + Quality.SNATCHED_PROPER
        )

        results += main_db.MainDB().select(
                'SELECT %s ' % fields_to_select +
                'FROM tv_episodes e, tv_shows s '
                'WHERE season != 0 '
                'AND s.indexer_id = e.showid '
                'AND airdate < ? '
                'AND airdate >= ? '
                'AND e.status IN (?,?) '
                'AND e.status NOT IN (' + ','.join(['?'] * len(qualities_list)) + ')',
                [today, recently, WANTED, UNAIRED] + qualities_list
        )

        results = [dict(result) for result in results]

        for index, item in enumerate(results):
            results[index][b'localtime'] = srDateTime.convert_to_setting(
                    parse_date_time(item[b'airdate'], item[b'airs'], item[b'network']))

        results.sort(ComingEpisodes.sorts[sort])

        if not group:
            return results

        grouped_results = {category: [] for category in categories}

        for result in results:
            if result[b'paused'] and not paused:
                continue

            result[b'airs'] = str(result[b'airs']).replace('am', ' AM').replace('pm', ' PM').replace('  ', ' ')
            result[b'airdate'] = result[b'localtime'].toordinal()

            if result[b'airdate'] < today:
                category = 'missed'
            elif result[b'airdate'] >= next_week:
                category = 'later'
            elif result[b'airdate'] == today:
                category = 'today'
            else:
                category = 'soon'

            if len(categories) > 0 and category not in categories:
                continue

            if not result[b'network']:
                result[b'network'] = ''

            result[b'quality'] = get_quality_string(result[b'quality'])
            result[b'airs'] = srDateTime.srftime(result[b'localtime'], t_preset=timeFormat).lstrip('0').replace(' 0',
                                                                                                                ' ')
            result[b'weekday'] = 1 + date.fromordinal(result[b'airdate']).weekday()
            result[b'tvdbid'] = result[b'indexer_id']
            result[b'airdate'] = srDateTime.srfdate(result[b'localtime'], d_preset=dateFormat)
            result[b'localtime'] = result[b'localtime'].toordinal()

            grouped_results[category].append(result)

        return grouped_results
示例#4
0
    def run(self, force=False):
        """
        Runs the daily searcher, queuing selected episodes for search
        :param force: Force search
        """
        if self.amActive:
            return

        self.amActive = True

        # set thread name
        threading.currentThread().setName(self.name)

        # trim failed download history
        if sickrage.srCore.srConfig.USE_FAILED_DOWNLOADS:
            FailedHistory.trimHistory()

        sickrage.srCore.srLogger.info(
            "Searching for new released episodes ...")

        curDate = (datetime.date.today() +
                   datetime.timedelta(days=2)).toordinal()
        if tz_updater.load_network_dict():
            curDate = (datetime.date.today() +
                       datetime.timedelta(days=1)).toordinal()

        curTime = datetime.datetime.now(tz_updater.sr_timezone)

        show = None
        for dbData in [
                x['doc'] for x in MainDB().db.all('tv_episodes', with_doc=True)
                if x['doc']['status'] in [UNAIRED, WANTED] and
                x['doc']['season'] > 0 and curDate >= x['doc']['airdate'] > 1
        ]:
            try:
                if not show or int(dbData['showid']) != show.indexerid:
                    show = findCertainShow(sickrage.srCore.SHOWLIST,
                                           int(dbData['showid']))

                # for when there is orphaned series in the database but not loaded into our showlist
                if not show or show.paused:
                    continue

            except MultipleShowObjectsException:
                sickrage.srCore.srLogger.info(
                    "ERROR: expected to find a single show matching " +
                    str(dbData['showid']))
                continue

            if show.airs and show.network:
                # This is how you assure it is always converted to local time
                air_time = tz_updater.parse_date_time(
                    dbData['airdate'], show.airs, show.network,
                    dateOnly=True).astimezone(tz_updater.sr_timezone)

                # filter out any episodes that haven't started airing yet,
                # but set them to the default status while they are airing
                # so they are snatched faster
                if air_time > curTime:
                    continue

            ep = show.getEpisode(int(dbData['season']), int(dbData['episode']))
            with ep.lock:
                if ep.season == 0:
                    sickrage.srCore.srLogger.info(
                        "New episode " + ep.prettyName() +
                        " airs today, setting status to SKIPPED because is a special season"
                    )
                    ep.status = SKIPPED
                else:
                    sickrage.srCore.srLogger.info(
                        "New episode %s airs today, setting to default episode status for this show: %s"
                        % (ep.prettyName(),
                           statusStrings[ep.show.default_ep_status]))
                    ep.status = ep.show.default_ep_status

                ep.saveToDB()
        else:
            sickrage.srCore.srLogger.info("No new released episodes found ...")

        # queue episode for daily search
        sickrage.srCore.SEARCHQUEUE.put(DailySearchQueueItem())

        self.amActive = False
    def get_coming_episodes(categories, sort, group, paused=False):
        """
        :param categories: The categories of coming episodes. See ``ComingEpisodes.categories``
        :param sort: The sort to apply to the coming episodes. See ``ComingEpisodes.sorts``
        :param group: ``True`` to group the coming episodes by category, ``False`` otherwise
        :param paused: ``True`` to include paused shows, ``False`` otherwise
        :return: The list of coming episodes
        """

        paused = sickrage.srCore.srConfig.COMING_EPS_DISPLAY_PAUSED or paused

        if not isinstance(categories, list):
            categories = categories.split('|')

        if sort not in ComingEpisodes.sorts.keys():
            sort = 'date'

        today = datetime.date.today().toordinal()
        next_week = (datetime.date.today() + datetime.timedelta(days=7)).toordinal()

        recently = (
            datetime.date.today() - datetime.timedelta(
                days=sickrage.srCore.srConfig.COMING_EPS_MISSED_RANGE)).toordinal()

        qualities_list = Quality.DOWNLOADED + \
                         Quality.SNATCHED + \
                         Quality.SNATCHED_BEST + \
                         Quality.SNATCHED_PROPER + \
                         Quality.ARCHIVED + \
                         Quality.IGNORED

        results = []
        for s in [s['doc'] for s in sickrage.srCore.mainDB.db.all('tv_shows', with_doc=True)]:
            for e in [e['doc'] for e in sickrage.srCore.mainDB.db.get_many('tv_episodes', s['indexer_id'], with_doc=True)
                      if e['doc']['season'] != 0
                      and today <= e['doc']['airdate'] < next_week
                      and e['doc']['status'] not in qualities_list]:
                results += [{
                    'airdate': e['airdate'],
                    'airs': s['airs'],
                    'description': e['description'],
                    'episode': e['episode'],
                    'imdb_id': s['imdb_id'],
                    'indexer': e['indexer'],
                    'indexer_id': s['indexer_id'],
                    'name': e['name'],
                    'network': s['network'],
                    'paused': s['paused'],
                    'quality': s['quality'],
                    'runtime': s['runtime'],
                    'season': e['season'],
                    'show_name': s['show_name'],
                    'showid': e['showid'],
                    'status': s['status']
                }]

        done_shows_list = [int(result['showid']) for result in results]

        for s in [s['doc'] for s in sickrage.srCore.mainDB.db.all('tv_shows', with_doc=True)]:
            for e in [e['doc'] for e in sickrage.srCore.mainDB.db.get_many('tv_episodes', s['indexer_id'], with_doc=True)
                      if e['doc']['season'] != 0
                      and e['doc']['showid'] not in done_shows_list
                      and e['doc']['airdate'] >= next_week
                      and e['doc']['status'] not in Quality.DOWNLOADED + Quality.SNATCHED + Quality.SNATCHED_BEST + Quality.SNATCHED_PROPER]:
                results += [{
                    'airdate': e['airdate'],
                    'airs': s['airs'],
                    'description': e['description'],
                    'episode': e['episode'],
                    'imdb_id': s['imdb_id'],
                    'indexer': e['indexer'],
                    'indexer_id': s['indexer_id'],
                    'name': e['name'],
                    'network': s['network'],
                    'paused': s['paused'],
                    'quality': s['quality'],
                    'runtime': s['runtime'],
                    'season': e['season'],
                    'show_name': s['show_name'],
                    'showid': e['showid'],
                    'status': s['status']
                }]

        for s in [s['doc'] for s in sickrage.srCore.mainDB.db.all('tv_shows', with_doc=True)]:
            for e in [e['doc'] for e in sickrage.srCore.mainDB.db.get_many('tv_episodes', s['indexer_id'], with_doc=True)
                      if e['doc']['season'] != 0
                      and today > e['doc']['airdate'] >= recently
                      and e['doc']['status'] in [WANTED, UNAIRED] and e['doc']['status'] not in qualities_list]:
                results += [{
                    'airdate': e['airdate'],
                    'airs': s['airs'],
                    'description': e['description'],
                    'episode': e['episode'],
                    'imdb_id': s['imdb_id'],
                    'indexer': e['indexer'],
                    'indexer_id': s['indexer_id'],
                    'name': e['name'],
                    'network': s['network'],
                    'paused': s['paused'],
                    'quality': s['quality'],
                    'runtime': s['runtime'],
                    'season': e['season'],
                    'show_name': s['show_name'],
                    'showid': e['showid'],
                    'status': s['status']
                }]

        for index, item in enumerate(results):
            results[index]['localtime'] = srDateTime.convert_to_setting(
                parse_date_time(item['airdate'], item['airs'], item['network']))

        results.sort(ComingEpisodes.sorts[sort])

        if not group:
            return results

        grouped_results = {category: [] for category in categories}

        for result in results:
            if result['paused'] and not paused:
                continue

            result['airs'] = str(result['airs']).replace('am', ' AM').replace('pm', ' PM').replace('  ', ' ')
            result['airdate'] = result['localtime'].toordinal()

            if result['airdate'] < today:
                category = 'missed'
            elif result['airdate'] >= next_week:
                category = 'later'
            elif result['airdate'] == today:
                category = 'today'
            else:
                category = 'soon'

            if len(categories) > 0 and category not in categories:
                continue

            if not result['network']:
                result['network'] = ''

            result['quality'] = get_quality_string(result['quality'])
            result['airs'] = srDateTime.srftime(result['localtime'], t_preset=timeFormat).lstrip('0').replace(' 0',
                                                                                                              ' ')
            result['weekday'] = 1 + datetime.date.fromordinal(result['airdate']).weekday()
            result['tvdbid'] = result['indexer_id']
            result['airdate'] = srDateTime.srfdate(result['localtime'], d_preset=dateFormat)
            result['localtime'] = result['localtime'].toordinal()

            grouped_results[category].append(result)

        return grouped_results
示例#6
0
    def get_coming_episodes(categories, sort, group, paused=False):
        """
        :param categories: The categories of coming episodes. See ``ComingEpisodes.categories``
        :param sort: The sort to apply to the coming episodes. See ``ComingEpisodes.sorts``
        :param group: ``True`` to group the coming episodes by category, ``False`` otherwise
        :param paused: ``True`` to include paused shows, ``False`` otherwise
        :return: The list of coming episodes
        """
        def result(show, episode):
            return [{
                'airdate': episode['airdate'],
                'airs': show.airs,
                'description': episode['description'],
                'episode': episode['episode'],
                'imdb_id': show.imdbid,
                'indexer': episode['indexer'],
                'indexer_id': show.indexerid,
                'name': episode['name'],
                'network': show.network,
                'paused': show.paused,
                'quality': show.quality,
                'runtime': show.runtime,
                'season': episode['season'],
                'show_name': show.name,
                'showid': episode['showid'],
                'status': show.status
            }]

        paused = sickrage.app.config.coming_eps_display_paused or paused

        if not isinstance(categories, list):
            categories = categories.split('|')

        if sort not in ComingEpisodes.sorts.keys():
            sort = 'date'

        today = datetime.date.today().toordinal()
        next_week = (datetime.date.today() +
                     datetime.timedelta(days=7)).toordinal()

        recently = (datetime.date.today() - datetime.timedelta(
            days=sickrage.app.config.coming_eps_missed_range)).toordinal()

        qualities_list = Quality.DOWNLOADED + \
                         Quality.SNATCHED + \
                         Quality.SNATCHED_BEST + \
                         Quality.SNATCHED_PROPER + \
                         Quality.ARCHIVED + \
                         Quality.IGNORED

        results = []
        for s in sickrage.app.showlist:
            for e in sickrage.app.main_db.get_many('tv_episodes', s.indexerid):
                if e['season'] != 0 and today <= e['airdate'] < next_week and e[
                        'status'] not in qualities_list:
                    results += result(s, e)

                if e['season'] != 0 and e['showid'] not in [int(r['showid']) for r in results] \
                        and e['airdate'] >= next_week and e['status'] \
                        not in Quality.DOWNLOADED + Quality.SNATCHED + Quality.SNATCHED_BEST + Quality.SNATCHED_PROPER:
                    results += result(s, e)

                if e['season'] != 0 and today > e['airdate'] >= recently \
                        and e['status'] in [WANTED, UNAIRED] and e['status'] not in qualities_list:
                    results += result(s, e)

        for index, item in enumerate(results):
            results[index]['localtime'] = srDateTime(parse_date_time(
                item['airdate'], item['airs'], item['network']),
                                                     convert=True).dt

        results.sort(ComingEpisodes.sorts[sort])

        if not group:
            return results

        grouped_results = {category: [] for category in categories}

        for result in results:
            if result['paused'] and not paused:
                continue

            result['airs'] = str(result['airs']).replace('am', ' AM').replace(
                'pm', ' PM').replace('  ', ' ')
            result['airdate'] = result['localtime'].toordinal()

            if result['airdate'] < today:
                category = 'missed'
            elif result['airdate'] >= next_week:
                category = 'later'
            elif result['airdate'] == today:
                category = 'today'
            else:
                category = 'soon'

            if len(categories) > 0 and category not in categories:
                continue

            if not result['network']:
                result['network'] = ''

            result['quality'] = get_quality_string(result['quality'])
            result['airs'] = srDateTime(result['localtime']).srftime(
                t_preset=timeFormat).lstrip('0').replace(' 0', ' ')
            result['weekday'] = 1 + datetime.date.fromordinal(
                result['airdate']).weekday()
            result['tvdbid'] = result['indexer_id']
            result['airdate'] = srDateTime(
                result['localtime']).srfdate(d_preset=dateFormat)
            result['localtime'] = result['localtime'].toordinal()

            grouped_results[category].append(result)

        return grouped_results
示例#7
0
    def get_coming_episodes(categories, sort, group, paused=False):
        """
        :param categories: The categories of coming episodes. See ``ComingEpisodes.categories``
        :param sort: The sort to apply to the coming episodes. See ``ComingEpisodes.sorts``
        :param group: ``True`` to group the coming episodes by category, ``False`` otherwise
        :param paused: ``True`` to include paused shows, ``False`` otherwise
        :return: The list of coming episodes
        """

        paused = sickrage.COMING_EPS_DISPLAY_PAUSED or paused

        if not isinstance(categories, list):
            categories = categories.split('|')

        if sort not in ComingEpisodes.sorts.keys():
            sort = 'date'

        today = date.today().toordinal()
        next_week = (date.today() + timedelta(days=7)).toordinal()
        recently = (
            date.today() -
            timedelta(days=sickrage.COMING_EPS_MISSED_RANGE)).toordinal()
        qualities_list = Quality.DOWNLOADED + \
                         Quality.SNATCHED + \
                         Quality.SNATCHED_BEST + \
                         Quality.SNATCHED_PROPER + \
                         Quality.ARCHIVED + \
                         Quality.IGNORED

        fields_to_select = ', '.join([
            'airdate', 'airs', 'description', 'episode', 'imdb_id',
            'e.indexer', 'indexer_id', 'name', 'network', 'paused', 'quality',
            'runtime', 'season', 'show_name', 'showid', 's.status'
        ])
        results = main_db.MainDB().select(
            'SELECT %s ' % fields_to_select + 'FROM tv_episodes e, tv_shows s '
            'WHERE season != 0 '
            'AND airdate >= ? '
            'AND airdate < ? '
            'AND s.indexer_id = e.showid '
            'AND e.status NOT IN (' + ','.join(['?'] * len(qualities_list)) +
            ')', [today, next_week] + qualities_list)

        done_shows_list = [int(result[b'showid']) for result in results]
        placeholder = ','.join(['?'] * len(done_shows_list))
        placeholder2 = ','.join(
            ['?'] * len(Quality.DOWNLOADED + Quality.SNATCHED +
                        Quality.SNATCHED_BEST + Quality.SNATCHED_PROPER))

        results += main_db.MainDB().select(
            'SELECT %s ' % fields_to_select + 'FROM tv_episodes e, tv_shows s '
            'WHERE season != 0 '
            'AND showid NOT IN (' + placeholder + ') '
            'AND s.indexer_id = e.showid '
            'AND airdate = (SELECT airdate '
            'FROM tv_episodes inner_e '
            'WHERE inner_e.season != 0 '
            'AND inner_e.showid = e.showid '
            'AND inner_e.airdate >= ? '
            'ORDER BY inner_e.airdate ASC LIMIT 1) '
            'AND e.status NOT IN (' + placeholder2 + ')',
            done_shows_list + [next_week] + Quality.DOWNLOADED +
            Quality.SNATCHED + Quality.SNATCHED_BEST + Quality.SNATCHED_PROPER)

        results += main_db.MainDB().select(
            'SELECT %s ' % fields_to_select + 'FROM tv_episodes e, tv_shows s '
            'WHERE season != 0 '
            'AND s.indexer_id = e.showid '
            'AND airdate < ? '
            'AND airdate >= ? '
            'AND e.status IN (?,?) '
            'AND e.status NOT IN (' + ','.join(['?'] * len(qualities_list)) +
            ')', [today, recently, WANTED, UNAIRED] + qualities_list)

        results = [dict(result) for result in results]

        for index, item in enumerate(results):
            results[index][b'localtime'] = srDateTime.convert_to_setting(
                parse_date_time(item[b'airdate'], item[b'airs'],
                                item[b'network']))

        results.sort(ComingEpisodes.sorts[sort])

        if not group:
            return results

        grouped_results = {category: [] for category in categories}

        for result in results:
            if result[b'paused'] and not paused:
                continue

            result[b'airs'] = str(result[b'airs']).replace(
                'am', ' AM').replace('pm', ' PM').replace('  ', ' ')
            result[b'airdate'] = result[b'localtime'].toordinal()

            if result[b'airdate'] < today:
                category = 'missed'
            elif result[b'airdate'] >= next_week:
                category = 'later'
            elif result[b'airdate'] == today:
                category = 'today'
            else:
                category = 'soon'

            if len(categories) > 0 and category not in categories:
                continue

            if not result[b'network']:
                result[b'network'] = ''

            result[b'quality'] = get_quality_string(result[b'quality'])
            result[b'airs'] = srDateTime.srftime(
                result[b'localtime'],
                t_preset=timeFormat).lstrip('0').replace(' 0', ' ')
            result[b'weekday'] = 1 + date.fromordinal(
                result[b'airdate']).weekday()
            result[b'tvdbid'] = result[b'indexer_id']
            result[b'airdate'] = srDateTime.srfdate(result[b'localtime'],
                                                    d_preset=dateFormat)
            result[b'localtime'] = result[b'localtime'].toordinal()

            grouped_results[category].append(result)

        return grouped_results
示例#8
0
    def run(self, force=False):
        """
        Runs the daily searcher, queuing selected episodes for search
        :param force: Force search
        """
        if self.amActive:
            return

        self.amActive = True

        # trim failed download history
        if sickrage.USE_FAILED_DOWNLOADS:
            FailedHistory.trimHistory()

        sickrage.LOGGER.info("Searching for new released episodes ...")

        if tz_updater.network_dict:
            curDate = (datetime.date.today() +
                       datetime.timedelta(days=1)).toordinal()
        else:
            curDate = (datetime.date.today() +
                       datetime.timedelta(days=2)).toordinal()

        curTime = datetime.datetime.now(tz_updater.sr_timezone)

        sqlResults = main_db.MainDB().select(
            "SELECT * FROM tv_episodes WHERE status = ? AND season > 0 AND (airdate <= ? AND airdate > 1)",
            [UNAIRED, curDate])

        sql_l = []
        show = None

        for sqlEp in sqlResults:
            try:
                if not show or int(sqlEp[b"showid"]) != show.indexerid:
                    show = findCertainShow(sickrage.showList,
                                           int(sqlEp[b"showid"]))

                # for when there is orphaned series in the database but not loaded into our showlist
                if not show or show.paused:
                    continue

            except MultipleShowObjectsException:
                sickrage.LOGGER.info(
                    "ERROR: expected to find a single show matching " +
                    str(sqlEp[b'showid']))
                continue

            if show.airs and show.network:
                # This is how you assure it is always converted to local time
                air_time = tz_updater.parse_date_time(
                    sqlEp[b'airdate'], show.airs,
                    show.network).astimezone(tz_updater.sr_timezone)

                # filter out any episodes that haven't started airing yet,
                # but set them to the default status while they are airing
                # so they are snatched faster
                if air_time > curTime:
                    continue

            ep = show.getEpisode(int(sqlEp[b"season"]), int(sqlEp[b"episode"]))
            with ep.lock:
                if ep.season == 0:
                    sickrage.LOGGER.info(
                        "New episode " + ep.prettyName() +
                        " airs today, setting status to SKIPPED because is a special season"
                    )
                    ep.status = SKIPPED
                else:
                    sickrage.LOGGER.info(
                        "New episode %s airs today, setting to default episode status for this show: %s"
                        % (ep.prettyName(),
                           statusStrings[ep.show.default_ep_status]))
                    ep.status = ep.show.default_ep_status

                sql_l.append(ep.get_sql())

        if len(sql_l) > 0:
            main_db.MainDB().mass_action(sql_l)
        else:
            sickrage.LOGGER.info("No new released episodes found ...")

        # queue episode for daily search
        dailysearch_queue_item = DailySearchQueueItem()
        sickrage.SEARCHQUEUE.add_item(dailysearch_queue_item)

        self.amActive = False
示例#9
0
    def run(self, force=False):
        """
        Runs the daily searcher, queuing selected episodes for search
        :param force: Force search
        """
        if self.amActive or sickrage.srCore.srConfig.DEVELOPER and not force:
            return

        self.amActive = True

        # set thread name
        threading.currentThread().setName(self.name)

        # trim failed download history
        if sickrage.srCore.srConfig.USE_FAILED_DOWNLOADS:
            FailedHistory.trimHistory()

        sickrage.srCore.srLogger.info("{}: Searching for new released episodes".format(self.name))

        curDate = datetime.date.today()
        curDate += datetime.timedelta(days=2)
        if tz_updater.load_network_dict():
            curDate += datetime.timedelta(days=1)

        curTime = datetime.datetime.now(tz_updater.sr_timezone)

        show = None

        episodes = [x['doc'] for x in sickrage.srCore.mainDB.db.all('tv_episodes', with_doc=True)
                    if x['doc']['status'] == UNAIRED
                    and x['doc']['season'] > 0
                    and curDate.toordinal() >= x['doc']['airdate'] > 1]

        for episode in episodes:
            if not show or int(episode["showid"]) != show.indexerid:
                show = findCertainShow(sickrage.srCore.SHOWLIST, int(episode["showid"]))

            # for when there is orphaned series in the database but not loaded into our showlist
            if not show or show.paused:
                continue

            if show.airs and show.network:
                # This is how you assure it is always converted to local time
                air_time = tz_updater.parse_date_time(
                    episode['airdate'], show.airs, show.network, dateOnly=True
                ).astimezone(tz_updater.sr_timezone)

                # filter out any episodes that haven't started airing yet,
                # but set them to the default status while they are airing
                # so they are snatched faster
                if air_time > curTime: continue

            ep = show.getEpisode(int(episode['season']), int(episode['episode']))
            with ep.lock:
                if ep.season == 0:
                    sickrage.srCore.srLogger.info(
                        "New episode {} airs today, setting status to SKIPPED because is a special season".format(
                            ep.prettyName()))
                    ep.status = SKIPPED
                else:
                    sickrage.srCore.srLogger.info(
                        "New episode {} airs today, setting to default episode status for this show: {}".format(
                            ep.prettyName(), statusStrings[ep.show.default_ep_status]))
                    ep.status = ep.show.default_ep_status

                ep.saveToDB()
        else:
            sickrage.srCore.srLogger.info("{}: No new released episodes found".format(self.name))

        # queue episode for daily search
        sickrage.srCore.SEARCHQUEUE.put(DailySearchQueueItem())

        self.amActive = False
示例#10
0
    def get_coming_episodes(categories, sort, group, paused=False):
        """
        :param categories: The categories of coming episodes. See ``ComingEpisodes.categories``
        :param sort: The sort to apply to the coming episodes. See ``ComingEpisodes.sorts``
        :param group: ``True`` to group the coming episodes by category, ``False`` otherwise
        :param paused: ``True`` to include paused shows, ``False`` otherwise
        :return: The list of coming episodes
        """

        paused = sickrage.srCore.srConfig.COMING_EPS_DISPLAY_PAUSED or paused

        if not isinstance(categories, list):
            categories = categories.split('|')

        if sort not in ComingEpisodes.sorts.keys():
            sort = 'date'

        today = datetime.date.today().toordinal()
        next_week = (datetime.date.today() +
                     datetime.timedelta(days=7)).toordinal()

        recently = (datetime.date.today() - datetime.timedelta(
            days=sickrage.srCore.srConfig.COMING_EPS_MISSED_RANGE)
                    ).toordinal()

        qualities_list = Quality.DOWNLOADED + \
                         Quality.SNATCHED + \
                         Quality.SNATCHED_BEST + \
                         Quality.SNATCHED_PROPER + \
                         Quality.ARCHIVED + \
                         Quality.IGNORED

        results = []
        for s in [
                s['doc'] for s in sickrage.srCore.mainDB.db.all('tv_shows',
                                                                with_doc=True)
        ]:
            for e in [
                    e['doc'] for e in sickrage.srCore.mainDB.db.get_many(
                        'tv_episodes', s['indexer_id'], with_doc=True)
                    if e['doc']['season'] != 0 and today <= e['doc']['airdate']
                    < next_week and e['doc']['status'] not in qualities_list
            ]:
                results += [{
                    'airdate': e['airdate'],
                    'airs': s['airs'],
                    'description': e['description'],
                    'episode': e['episode'],
                    'imdb_id': s['imdb_id'],
                    'indexer': e['indexer'],
                    'indexer_id': s['indexer_id'],
                    'name': e['name'],
                    'network': s['network'],
                    'paused': s['paused'],
                    'quality': s['quality'],
                    'runtime': s['runtime'],
                    'season': e['season'],
                    'show_name': s['show_name'],
                    'showid': e['showid'],
                    'status': s['status']
                }]

        done_shows_list = [int(result['showid']) for result in results]

        for s in [
                s['doc'] for s in sickrage.srCore.mainDB.db.all('tv_shows',
                                                                with_doc=True)
        ]:
            for e in [
                    e['doc'] for e in sickrage.srCore.mainDB.db.get_many(
                        'tv_episodes', s['indexer_id'], with_doc=True)
                    if e['doc']['season'] != 0 and e['doc']['showid'] not in
                    done_shows_list and e['doc']['airdate'] >= next_week
                    and e['doc']['status'] not in Quality.DOWNLOADED +
                    Quality.SNATCHED + Quality.SNATCHED_BEST +
                    Quality.SNATCHED_PROPER
            ]:
                results += [{
                    'airdate': e['airdate'],
                    'airs': s['airs'],
                    'description': e['description'],
                    'episode': e['episode'],
                    'imdb_id': s['imdb_id'],
                    'indexer': e['indexer'],
                    'indexer_id': s['indexer_id'],
                    'name': e['name'],
                    'network': s['network'],
                    'paused': s['paused'],
                    'quality': s['quality'],
                    'runtime': s['runtime'],
                    'season': e['season'],
                    'show_name': s['show_name'],
                    'showid': e['showid'],
                    'status': s['status']
                }]

        for s in [
                s['doc'] for s in sickrage.srCore.mainDB.db.all('tv_shows',
                                                                with_doc=True)
        ]:
            for e in [
                    e['doc'] for e in sickrage.srCore.mainDB.db.get_many(
                        'tv_episodes', s['indexer_id'], with_doc=True)
                    if e['doc']['season'] != 0 and today > e['doc']['airdate']
                    >= recently and e['doc']['status'] in [WANTED, UNAIRED]
                    and e['doc']['status'] not in qualities_list
            ]:
                results += [{
                    'airdate': e['airdate'],
                    'airs': s['airs'],
                    'description': e['description'],
                    'episode': e['episode'],
                    'imdb_id': s['imdb_id'],
                    'indexer': e['indexer'],
                    'indexer_id': s['indexer_id'],
                    'name': e['name'],
                    'network': s['network'],
                    'paused': s['paused'],
                    'quality': s['quality'],
                    'runtime': s['runtime'],
                    'season': e['season'],
                    'show_name': s['show_name'],
                    'showid': e['showid'],
                    'status': s['status']
                }]

        for index, item in enumerate(results):
            results[index]['localtime'] = srDateTime.convert_to_setting(
                parse_date_time(item['airdate'], item['airs'],
                                item['network']))

        results.sort(ComingEpisodes.sorts[sort])

        if not group:
            return results

        grouped_results = {category: [] for category in categories}

        for result in results:
            if result['paused'] and not paused:
                continue

            result['airs'] = str(result['airs']).replace('am', ' AM').replace(
                'pm', ' PM').replace('  ', ' ')
            result['airdate'] = result['localtime'].toordinal()

            if result['airdate'] < today:
                category = 'missed'
            elif result['airdate'] >= next_week:
                category = 'later'
            elif result['airdate'] == today:
                category = 'today'
            else:
                category = 'soon'

            if len(categories) > 0 and category not in categories:
                continue

            if not result['network']:
                result['network'] = ''

            result['quality'] = get_quality_string(result['quality'])
            result['airs'] = srDateTime.srftime(
                result['localtime'],
                t_preset=timeFormat).lstrip('0').replace(' 0', ' ')
            result['weekday'] = 1 + datetime.date.fromordinal(
                result['airdate']).weekday()
            result['tvdbid'] = result['indexer_id']
            result['airdate'] = srDateTime.srfdate(result['localtime'],
                                                   d_preset=dateFormat)
            result['localtime'] = result['localtime'].toordinal()

            grouped_results[category].append(result)

        return grouped_results
示例#11
0
    def run(self, force=False):
        """
        Runs the daily searcher, queuing selected episodes for search
        :param force: Force search
        """
        if self.amActive or sickrage.app.developer and not force:
            return

        self.amActive = True

        # set thread name
        threading.currentThread().setName(self.name)

        # trim failed download history
        if sickrage.app.config.use_failed_downloads:
            FailedHistory.trimHistory()

        sickrage.app.log.info("Searching for new released episodes")

        curDate = datetime.date.today()
        curDate += datetime.timedelta(days=2)
        if tz_updater.load_network_dict():
            curDate += datetime.timedelta(days=1)

        curTime = datetime.datetime.now(sickrage.app.tz)

        show = None

        episodes = [
            x['doc']
            for x in sickrage.app.main_db.db.all('tv_episodes', with_doc=True)
            if x['doc']['status'] == common.UNAIRED and x['doc']['season'] > 0
            and curDate.toordinal() >= x['doc']['airdate'] > 1
        ]

        new_episodes = False
        for episode in episodes:
            if not show or int(episode["showid"]) != show.indexerid:
                show = findCertainShow(sickrage.app.showlist,
                                       int(episode["showid"]))

            # for when there is orphaned series in the database but not loaded into our showlist
            if not show or show.paused:
                continue

            if show.airs and show.network:
                # This is how you assure it is always converted to local time
                air_time = tz_updater.parse_date_time(
                    episode['airdate'], show.airs, show.network,
                    dateOnly=True).astimezone(sickrage.app.tz)

                # filter out any episodes that haven't started airing yet,
                # but set them to the default status while they are airing
                # so they are snatched faster
                if air_time > curTime: continue

            ep_obj = show.getEpisode(int(episode['season']),
                                     int(episode['episode']))
            with ep_obj.lock:
                ep_obj.status = show.default_ep_status if ep_obj.season else common.SKIPPED
                sickrage.app.log.info(
                    'Setting status ({status}) for show airing today: {name} {special}'
                    .format(
                        name=ep_obj.pretty_name(),
                        status=common.statusStrings[ep_obj.status],
                        special='(specials are not supported)'
                        if not ep_obj.season else '',
                    ))

                ep_obj.saveToDB()
                new_episodes = True

        if not new_episodes:
            sickrage.app.log.info("No new released episodes found")

        # queue episode for daily search
        sickrage.app.search_queue.put(DailySearchQueueItem())

        self.amActive = False
示例#12
0
    def run(self, force=False):
        """
        Runs the daily searcher, queuing selected episodes for search
        :param force: Force search
        """
        if self.amActive:
            return

        self.amActive = True

        # trim failed download history
        if sickrage.USE_FAILED_DOWNLOADS:
            FailedHistory.trimHistory()

        sickrage.LOGGER.info("Searching for new released episodes ...")

        if tz_updater.network_dict:
            curDate = (datetime.date.today() + datetime.timedelta(days=1)).toordinal()
        else:
            curDate = (datetime.date.today() + datetime.timedelta(days=2)).toordinal()

        curTime = datetime.datetime.now(tz_updater.sr_timezone)

        sqlResults = main_db.MainDB().select(
                "SELECT * FROM tv_episodes WHERE status = ? AND season > 0 AND (airdate <= ? AND airdate > 1)",
                [UNAIRED, curDate])

        sql_l = []
        show = None

        for sqlEp in sqlResults:
            try:
                if not show or int(sqlEp[b"showid"]) != show.indexerid:
                    show = findCertainShow(sickrage.showList, int(sqlEp[b"showid"]))

                # for when there is orphaned series in the database but not loaded into our showlist
                if not show or show.paused:
                    continue

            except MultipleShowObjectsException:
                sickrage.LOGGER.info("ERROR: expected to find a single show matching " + str(sqlEp[b'showid']))
                continue

            if show.airs and show.network:
                # This is how you assure it is always converted to local time
                air_time = tz_updater.parse_date_time(sqlEp[b'airdate'], show.airs, show.network).astimezone(
                        tz_updater.sr_timezone)

                # filter out any episodes that haven't started airing yet,
                # but set them to the default status while they are airing
                # so they are snatched faster
                if air_time > curTime:
                    continue

            ep = show.getEpisode(int(sqlEp[b"season"]), int(sqlEp[b"episode"]))
            with ep.lock:
                if ep.season == 0:
                    sickrage.LOGGER.info(
                            "New episode " + ep.prettyName() + " airs today, setting status to SKIPPED because is a special season")
                    ep.status = SKIPPED
                else:
                    sickrage.LOGGER.info("New episode %s airs today, setting to default episode status for this show: %s" % (
                        ep.prettyName(), statusStrings[ep.show.default_ep_status]))
                    ep.status = ep.show.default_ep_status

                sql_l.append(ep.get_sql())

        if len(sql_l) > 0:
            main_db.MainDB().mass_action(sql_l)
        else:
            sickrage.LOGGER.info("No new released episodes found ...")

        # queue episode for daily search
        dailysearch_queue_item = DailySearchQueueItem()
        sickrage.SEARCHQUEUE.add_item(dailysearch_queue_item)

        self.amActive = False
示例#13
0
    def run(self, force=False):
        """
        Runs the daily searcher, queuing selected episodes for search
        :param force: Force search
        """
        if self.amActive or sickrage.app.developer and not force:
            return

        self.amActive = True

        # set thread name
        threading.currentThread().setName(self.name)

        # trim failed download history
        if sickrage.app.config.use_failed_downloads:
            FailedHistory.trimHistory()

        sickrage.app.log.info("Searching for new released episodes")

        curDate = datetime.date.today()
        curDate += datetime.timedelta(days=2)
        if tz_updater.load_network_dict():
            curDate += datetime.timedelta(days=1)

        curTime = datetime.datetime.now(sickrage.app.tz)

        show = None

        episodes = [x['doc'] for x in sickrage.app.main_db.db.all('tv_episodes', with_doc=True)
                    if x['doc']['status'] == common.UNAIRED
                    and x['doc']['season'] > 0
                    and curDate.toordinal() >= x['doc']['airdate'] > 1]

        new_episodes = False
        for episode in episodes:
            if not show or int(episode["showid"]) != show.indexerid:
                show = findCertainShow(sickrage.app.showlist, int(episode["showid"]))

            # for when there is orphaned series in the database but not loaded into our showlist
            if not show or show.paused:
                continue

            if show.airs and show.network:
                # This is how you assure it is always converted to local time
                air_time = tz_updater.parse_date_time(
                    episode['airdate'], show.airs, show.network, dateOnly=True
                ).astimezone(sickrage.app.tz)

                # filter out any episodes that haven't started airing yet,
                # but set them to the default status while they are airing
                # so they are snatched faster
                if air_time > curTime: continue

            ep_obj = show.getEpisode(int(episode['season']), int(episode['episode']))
            with ep_obj.lock:
                ep_obj.status = show.default_ep_status if ep_obj.season else common.SKIPPED
                sickrage.app.log.info('Setting status ({status}) for show airing today: {name} {special}'.format(
                    name=ep_obj.pretty_name(),
                    status=common.statusStrings[ep_obj.status],
                    special='(specials are not supported)' if not ep_obj.season else '',
                ))

                ep_obj.saveToDB()
                new_episodes = True

        if not new_episodes:
            sickrage.app.log.info("No new released episodes found")

        # queue episode for daily search
        sickrage.app.search_queue.put(DailySearchQueueItem())

        self.amActive = False
示例#14
0
    def run(self, force=False):
        """
        Runs the daily searcher, queuing selected episodes for search
        :param force: Force search
        """
        if self.amActive:
            return

        self.amActive = True

        # set thread name
        threading.currentThread().setName(self.name)

        # trim failed download history
        if sickrage.srCore.srConfig.USE_FAILED_DOWNLOADS:
            FailedHistory.trimHistory()

        sickrage.srCore.srLogger.info("Searching for new released episodes ...")

        curDate = (datetime.date.today() + datetime.timedelta(days=2)).toordinal()
        if tz_updater.load_network_dict():
            curDate = (datetime.date.today() + datetime.timedelta(days=1)).toordinal()

        curTime = datetime.datetime.now(tz_updater.sr_timezone)

        show = None
        for dbData in [x['doc'] for x in sickrage.srCore.mainDB.db.all('tv_episodes', with_doc=True)
                       if x['doc']['status'] in [UNAIRED, WANTED]
                       and x['doc']['season'] > 0
                       and curDate >= x['doc']['airdate'] > 1]:
            try:
                if not show or int(dbData['showid']) != show.indexerid:
                    show = findCertainShow(sickrage.srCore.SHOWLIST, int(dbData['showid']))

                # for when there is orphaned series in the database but not loaded into our showlist
                if not show or show.paused:
                    continue

            except MultipleShowObjectsException:
                sickrage.srCore.srLogger.info("ERROR: expected to find a single show matching " + str(dbData['showid']))
                continue

            if show.airs and show.network:
                # This is how you assure it is always converted to local time
                air_time = tz_updater.parse_date_time(dbData['airdate'], show.airs, show.network,
                                                      dateOnly=True).astimezone(tz_updater.sr_timezone)

                # filter out any episodes that haven't started airing yet,
                # but set them to the default status while they are airing
                # so they are snatched faster
                if air_time > curTime:
                    continue

            ep = show.getEpisode(int(dbData['season']), int(dbData['episode']))
            with ep.lock:
                if ep.season == 0:
                    sickrage.srCore.srLogger.info(
                        "New episode " + ep.prettyName() + " airs today, setting status to SKIPPED because is a special season")
                    ep.status = SKIPPED
                else:
                    sickrage.srCore.srLogger.info(
                        "New episode %s airs today, setting to default episode status for this show: %s" % (
                            ep.prettyName(), statusStrings[ep.show.default_ep_status]))
                    ep.status = ep.show.default_ep_status

                ep.saveToDB()
        else:
            sickrage.srCore.srLogger.info("No new released episodes found ...")

        # queue episode for daily search
        sickrage.srCore.SEARCHQUEUE.put(DailySearchQueueItem())

        self.amActive = False