Пример #1
0
    def _test_allPossibleShowNames(self, name, indexerid=0, expected=[]):
        s = TVShow(1, indexerid)
        s.name = name

        result = show_names.allPossibleShowNames(s)
        self.assertTrue(
            len(set(expected).intersection(set(result))) == len(expected))
Пример #2
0
class AnimeTests(SiCKRAGETestDBCase):
    def setUp(self):
        super(AnimeTests, self).setUp()
        self.show = TVShow(1, 1, 'en')
        self.show.anime = True
        self.show.saveToDB()

    def _test_names(self, np, section, transform=None, verbose=False):
        """
        Performs a test

        :param name_parser: to use for test
        :param section:
        :param transform:
        :param verbose:
        :return:
        """
        if VERBOSE or verbose:
            print()
            print('Running', section, 'tests')
        for cur_test_base in anime_test_cases[section]:
            if transform:
                cur_test = transform(cur_test_base)
                np.file_name = cur_test
            else:
                cur_test = cur_test_base
            if VERBOSE or verbose:
                print('Testing', cur_test)

            result = anime_test_cases[section][cur_test_base]
            np.showObj.name = result.series_name if result else None
            if not result:
                self.assertRaises(InvalidNameException, np.parse, cur_test)
                return
            else:
                result.which_regex = {section}
                test_result = np.parse(cur_test)

            if DEBUG or verbose:
                print('air_by_date:', test_result.is_air_by_date, 'air_date:',
                      test_result.air_date)
                print('anime:', test_result.is_anime, 'ab_episode_numbers:',
                      test_result.ab_episode_numbers)
                print(test_result)
                print(result)

            self.assertEqual(
                test_result.which_regex, {section},
                '{} : {} != {}'.format(cur_test, test_result.which_regex,
                                       {section}))
            self.assertEqual(
                test_result, result,
                '{} : {} != {}'.format(cur_test, test_result, result))

    def test_anime_sxxexx_file_names(self):
        """
        Test anime SxxExx file names
        """
        np = NameParser(showObj=self.show, validate_show=False)
        self._test_names(np, 'anime_SxxExx', lambda x: x + '.avi')
Пример #3
0
 def __init__(self, something):
     super(UnicodeTests, self).__init__(something)
     self.setUp()
     self.show = TVShow(1, 1, 'en')
     self.show.name = "The Big Bang Theory"
     self.show.saveToDB()
     self.show.loadFromDB(skipNFO=True)
Пример #4
0
    def test_process(self):
        show = TVShow(3, 1)
        show.name = self.SHOWNAME
        show.location = self.SHOWDIR
        sickrage.app.showlist = [show]

        self.post_processor = PostProcessor(self.FILEPATH, process_method='move')
        self.post_processor._log = _log
        self.assertTrue(self.post_processor.process)
Пример #5
0
    def test_init_empty_db(self):
        show = TVShow(1, 0001, "en")
        show.saveToDB()
        show.loadFromDB(skipNFO=True)

        ep = TVEpisode(show, 1, 1)
        ep.name = "asdasdasdajkaj"
        ep.saveToDB()
        ep.loadFromDB(1, 1)
        self.assertEqual(ep.name, "asdasdasdajkaj")
Пример #6
0
    def _test_allPossibleShowNames(self, name, indexer_id=0, expected=None):
        if expected is None:
            expected = []

        s = TVShow(indexer_id, 1)
        s.name = name

        result = show_names.all_possible_show_names(s)
        self.assertTrue(
            len(set(expected).intersection(set(result))) == len(expected))
Пример #7
0
    def _test_allPossibleShowNames(self, name, indexerid=0, expected=None):
        if expected is None:
            expected = []

        s = TVShow(1, indexerid)
        s.name = name
        s.save_to_db()

        result = show_names.allPossibleShowNames(s)
        self.assertTrue(len(set(expected).intersection(set(result))) == len(expected))
Пример #8
0
    def _test_allPossibleShowNames(self, name, indexerid=0, expected=None):
        if expected is None:
            expected = []

        s = TVShow(1, indexerid)
        s.name = name
        s.save_to_db()

        result = show_names.allPossibleShowNames(s)
        self.assertTrue(
            len(set(expected).intersection(set(result))) == len(expected))
Пример #9
0
 def test_getEpisode(self):
     show = TVShow(0o001, 1)
     show.name = "show name"
     show.network = "cbs"
     show.genre = "crime"
     show.runtime = 40
     show.status = "Ended"
     show.default_ep_status = "5"
     show.airs = "monday"
     show.startyear = 1987
     sickrage.app.showlist = [show]
Пример #10
0
class AnimeTests(tests.SiCKRAGETestDBCase):
    def setUp(self):
        super(AnimeTests, self).setUp()
        self.show = TVShow(1, 1, 'en')
        self.show.anime = True
        self.show.save_to_db()

    def _test_names(self, np, section, transform=None, verbose=False):
        """
        Performs a test

        :param name_parser: to use for test
        :param section:
        :param transform:
        :param verbose:
        :return:
        """
        if VERBOSE or verbose:
            print()
            print('Running', section, 'tests')
        for cur_test_base in anime_test_cases[section]:
            if transform:
                cur_test = transform(cur_test_base)
                np.file_name = cur_test
            else:
                cur_test = cur_test_base
            if VERBOSE or verbose:
                print('Testing', cur_test)

            result = anime_test_cases[section][cur_test_base]
            np.showObj.name = result.series_name if result else None
            if not result:
                self.assertRaises(InvalidNameException, np.parse, cur_test)
                return
            else:
                result.which_regex = {section}
                test_result = np.parse(cur_test)

            if DEBUG or verbose:
                print('air_by_date:', test_result.is_air_by_date, 'air_date:', test_result.air_date)
                print('anime:', test_result.is_anime, 'ab_episode_numbers:', test_result.ab_episode_numbers)
                print(test_result)
                print(result)

            self.assertEqual(test_result.which_regex, {section},
                             '{} : {} != {}'.format(cur_test, test_result.which_regex, {section}))
            self.assertEqual(test_result, result, '{} : {} != {}'.format(cur_test, test_result, result))

    def test_anime_sxxexx_file_names(self):
        """
        Test anime SxxExx file names
        """
        np = NameParser(showObj=self.show, validate_show=False)
        self._test_names(np, 'anime_SxxExx', lambda x: x + '.avi')
Пример #11
0
    def test_process(self):
        show = TVShow(3, 1)
        show.name = self.SHOWNAME
        show.location = self.SHOWDIR
        sickrage.app.showlist = [show]
        ep = TVEpisode(show, self.SEASON, self.EPISODE)
        ep.name = "some ep name"
        ep.save()

        self.post_processor = PostProcessor(self.FILEPATH, process_method='move')
        self.post_processor._log = _log
        self.assertTrue(self.post_processor.process)
Пример #12
0
    def load_shows(self):
        """
        Populates the showlist with shows from the database
        """

        for dbData in [x['doc'] for x in self.main_db.db.all('tv_shows', with_doc=True)]:
            try:
                self.log.debug("Loading data for show: [{}]".format(dbData['show_name']))
                show = TVShow(int(dbData['indexer']), int(dbData['indexer_id']))
                show.nextEpisode()
                self.showlist += [show]
            except Exception as e:
                self.log.error("Show error in [%s]: %s" % (dbData['location'], e.message))
Пример #13
0
    def load_shows(self):
        """
        Populates the showlist with shows from the database
        """

        for dbData in [x['doc'] for x in self.main_db.db.all('tv_shows', with_doc=True)]:
            try:
                self.log.debug("Loading data for show: [{}]".format(dbData['show_name']))
                show = TVShow(int(dbData['indexer']), int(dbData['indexer_id']))
                show.nextEpisode()
                self.showlist += [show]
            except Exception as e:
                self.log.error("Show error in [%s]: %s" % (dbData['location'], e.message))
Пример #14
0
    def loadFromDB(self):
        """
        Populates the showList with shows from the database
        """

        for s in [s['doc'] for s in sickrage.srCore.mainDB.db.all('tv_shows', with_doc=True)]:
            try:
                curShow = TVShow(int(s["indexer"]), int(s["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"
Пример #15
0
    def test_process(self):
        show = TVShow(1, 3)
        show.name = SHOWNAME
        show.location = SHOWDIR
        show.saveToDB()

        sickrage.showList = [show]
        ep = TVEpisode(show, SEASON, EPISODE)
        ep.name = "some ep name"
        ep.saveToDB()

        sickrage.NAMECACHE.addNameToCache("show name", 3)
        self.pp = PostProcessor(FILEPATH, process_method="move")
        self.assertTrue(self.pp.process)
Пример #16
0
    def load_shows(self):
        """
        Populates the showlist with shows from the database
        """

        for dbData in [x['doc'] for x in self.mainDB.db.all('tv_shows', with_doc=True)]:
            try:
                self.srLogger.debug("Loading data for show: [%s]", dbData['show_name'])
                show = TVShow(int(dbData['indexer']), int(dbData['indexer_id']))
                show.nextEpisode()
                self.NAMECACHE.build(show)
                self.SHOWLIST += [show]
            except Exception as e:
                self.srLogger.error("Show error in [%s]: %s" % (dbData['location'], e.message))
Пример #17
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["indexer"]), int(sqlShow["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"
Пример #18
0
    def test_isGoodName(self):
        list_of_cases = [('Show.Name.S01E02.Test-Test', 'Show/Name'),
                         ('Show.Name.S01E02.Test-Test', 'Show. Name'),
                         ('Show.Name.S01E02.Test-Test', 'Show- Name'),
                         ('Show.Name.Part.IV.Test-Test', 'Show Name'),
                         ('Show.Name.S01.Test-Test', 'Show Name'),
                         ('Show.Name.E02.Test-Test', 'Show: Name'),
                         ('Show Name Season 2 Test', 'Show: Name')]

        for testCase in list_of_cases:
            scene_name, show_name = testCase
            s = TVShow(1, 0)
            s.name = show_name
            s.saveToDB()
            self._test_isGoodName(scene_name, s)
Пример #19
0
    def test_isGoodName(self):
        list_of_cases = [('Show.Name.S01E02.Test-Test', 'Show/Name'),
                         ('Show.Name.S01E02.Test-Test', 'Show. Name'),
                         ('Show.Name.S01E02.Test-Test', 'Show- Name'),
                         ('Show.Name.Part.IV.Test-Test', 'Show Name'),
                         ('Show.Name.S01.Test-Test', 'Show Name'),
                         ('Show.Name.E02.Test-Test', 'Show: Name'),
                         ('Show Name Season 2 Test', 'Show: Name')]

        for testCase in list_of_cases:
            scene_name, show_name = testCase
            s = TVShow(1, 0)
            s.name = show_name
            s.save_to_db()
            self._test_isGoodName(scene_name, s)
Пример #20
0
    def load_shows(self):
        threading.currentThread().setName('CORE')

        session = self.main_db.session()

        self.log.info('Loading initial shows list')

        self.loading_shows = True

        self.shows = {}
        for query in session.query(MainDB.TVShow).with_entities(
                MainDB.TVShow.series_id, MainDB.TVShow.series_provider_id,
                MainDB.TVShow.name, MainDB.TVShow.location):
            try:
                # if not os.path.isdir(query.location) and self.config.general.create_missing_show_dirs:
                #     make_dir(query.location)

                self.log.info('Loading show {}'.format(query.name))
                self.shows.update({
                    (query.series_id, query.series_provider_id):
                    TVShow(query.series_id, query.series_provider_id)
                })
            except Exception as e:
                self.log.debug('There was an error loading show: {}'.format(
                    query.name))

        self.loading_shows = False

        self.log.info('Loading initial shows list finished')
Пример #21
0
        def setUp(self):
            super(ProviderTests.ProviderTest, self).setUp()
            self.show = TVShow(
                1,
                test_string_overrides.get(self.provider.name,
                                          {'ID': 82066})['ID'], "en")
            self.show.name = test_string_overrides.get(
                self.provider.name, {'Name': 'Fringe'})['Name']
            self.show.anime = test_string_overrides.get(
                self.provider.name, {'Anime': False})['Anime']

            self.ep = TVEpisode(
                self.show,
                test_string_overrides.get(self.provider.name,
                                          {'Season': 1})['Season'],
                test_string_overrides.get(self.provider.name,
                                          {'Episode': 1})['Episode'])
            self.ep.absolute_number = test_string_overrides.get(
                self.provider.name, {'ABS': 0})['ABS']
            self.ep.scene_season = self.ep.season
            self.ep.scene_episode = self.ep.episode
            self.ep.scene_absolute_number = self.ep.absolute_number

            self.provider.username = self.username
            self.provider.password = self.password
Пример #22
0
    def load_shows(self):
        threading.currentThread().setName('CORE')

        session = self.main_db.session()

        self.log.info('Loading initial shows list')

        self.loading_shows = True

        self.shows = {}
        for query in session.query(MainDB.TVShow).with_entities(
                MainDB.TVShow.indexer_id, MainDB.TVShow.indexer,
                MainDB.TVShow.name):
            try:
                self.log.info('Loading show {} and building caches'.format(
                    query.name))
                self.shows.update({
                    (query.indexer_id, query.indexer):
                    TVShow(query.indexer_id, query.indexer)
                })
                self.quicksearch_cache.add_show(query.indexer_id)
            except Exception as e:
                self.log.debug('There was an error loading show: {}'.format(
                    query.name))

        self.loading_shows = False

        self.log.info('Loading initial shows list finished')
Пример #23
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["indexer"]),
                                 int(sqlShow["indexer_id"]))
                self.srLogger.debug("Loading data for show: [{}]".format(
                    curshow.name))
                curshow.nextEpisode()
                self.SHOWLIST += [curshow]
            except Exception as e:
                self.srLogger.error("Show error in [{}]: {}".format(
                    sqlShow["location"], e.message))
Пример #24
0
 def __init__(self, something):
     super(UnicodeTests, self).__init__(something)
     self.setUp()
     self.show = TVShow(1, 1, "en")
     self.show.name = "The Big Bang Theory"
     self.show.saveToDB()
     self.show.loadFromDB(skipNFO=True)
Пример #25
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["indexer"]), int(sqlShow["indexer_id"]))
                self.srLogger.debug("Loading data for show: [{}]".format(curshow.name))
                #self.NAMECACHE.buildNameCache(curshow)
                curshow.nextEpisode()
                self.SHOWLIST += [curshow]
            except Exception as e:
                self.srLogger.error(
                    "There was an error creating the show in {}: {}".format(sqlShow["location"], e.message))
                self.srLogger.debug(traceback.format_exc())
Пример #26
0
class UnicodeTests(tests.SiCKRAGETestDBCase):
    def setUp(self):
        super(UnicodeTests, self).setUp()
        self.show = TVShow(1, 1, 'en')
        self.show.name = "The Big Bang Theory"
        self.show.save_to_db()

    def _test_unicode(self, name, result):
        np = NameParser(True, showObj=self.show, validate_show=False)
        parse_result = np.parse(name)

        # this shouldn't raise an exception
        repr(str(parse_result))
        self.assertEqual(parse_result.extra_info, result.extra_info)

    def test_unicode(self):
        for (name, result) in unicode_test_cases:
            self._test_unicode(name, result)
Пример #27
0
class UnicodeTests(SiCKRAGETestDBCase):
    def setUp(self):
        super(UnicodeTests, self).setUp()
        self.show = TVShow(1, 1, 'en')
        self.show.name = "The Big Bang Theory"
        self.show.saveToDB()

    def _test_unicode(self, name, result):
        np = NameParser(True, showObj=self.show, validate_show=False)
        parse_result = np.parse(name)

        # this shouldn't raise an exception
        repr(str(parse_result))
        self.assertEqual(parse_result.extra_info, result.extra_info)

    def test_unicode(self):
        for (name, result) in unicode_test_cases:
            self._test_unicode(name, result)
Пример #28
0
    def test(self):
        global searchItems
        searchItems = curData[b"i"]
        show = TVShow(1, tvdbdid)
        show.name = show_name
        show.quality = curData[b"q"]
        show.saveToDB()
        sickrage.showList.append(show)
        episode = None

        for epNumber in curData[b"e"]:
            episode = TVEpisode(show, curData[b"s"], epNumber)
            episode.status = WANTED
            episode.saveToDB()

        bestResult = searchProviders(show, episode.episode, forceSearch)
        if not bestResult:
            self.assertEqual(curData[b"b"], bestResult)
        self.assertEqual(curData[b"b"], bestResult.name)  # first is expected, second is choosen one
Пример #29
0
def load_shows():
    """
    Populates the showlist with shows from the database
    """

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

    return showlist
Пример #30
0
    def _test_allPossibleShowNames(self, name, indexerid=0, expected=[]):
        s = TVShow(1, indexerid)
        s.name = name
        s.saveToDB()
        s.loadFromDB(skipNFO=True)

        result = show_names.allPossibleShowNames(s)
        self.assertTrue(
            len(set(expected).intersection(set(result))) == len(expected))
Пример #31
0
class UnicodeTests(SiCKRAGETestDBCase):
    def __init__(self, something):
        super(UnicodeTests, self).__init__(something)
        self.setUp()
        self.show = TVShow(1, 1, "en")
        self.show.name = "The Big Bang Theory"
        self.show.saveToDB()
        self.show.loadFromDB(skipNFO=True)

    def _test_unicode(self, name, result):
        np = NameParser(True, showObj=self.show)
        parse_result = np.parse(name)

        # this shouldn't raise an exception
        repr(str(parse_result))
        self.assertEqual(parse_result.extra_info, result.extra_info)

    def test_unicode(self):
        for (name, result) in unicode_test_cases:
            self._test_unicode(name, result)
Пример #32
0
    def get_show(self, name):
        show = None
        show_id = None
        show_names = [name]

        if not all([name, sickrage.app.showlist]):
            return show, show_id

        def cache_lookup(term):
            return sickrage.app.name_cache.get(term)

        def scene_exception_lookup(term):
            return get_scene_exception_by_name(term)[0]

        def indexer_lookup(term):
            show_id1 = int(IndexerApi().searchForShowID(
                full_sanitizeSceneName(term))[2])
            show_id2 = int(srTraktAPI()['search'].query(
                full_sanitizeSceneName(term), 'show')[0].ids['tvdb'])
            return (None, show_id1)[show_id1 == show_id2]

        show_names.append(strip_accents(name))
        show_names.append(strip_accents(name).replace("'", " "))

        for show_name in set(show_names):
            lookup_list = [
                lambda: cache_lookup(show_name),
                lambda: scene_exception_lookup(show_name),
                lambda: indexer_lookup(show_name),
            ]

            # lookup show id
            for lookup in lookup_list:
                try:
                    show_id = int(lookup())
                    if show_id == 0:
                        continue

                    sickrage.app.name_cache.put(show_name, show_id)

                    if not show:
                        if self.validate_show:
                            show = findCertainShow(show_id)
                        else:
                            from sickrage.core.tv.show import TVShow
                            show = TVShow(1, show_id)
                except Exception:
                    pass

            if show_id is None:
                # ignore show name by caching it with a indexerid of 0
                sickrage.app.name_cache.put(show_name, 0)

        return show, show_id or 0
Пример #33
0
class UnicodeTests(SiCKRAGETestDBCase):
    def __init__(self, something):
        super(UnicodeTests, self).__init__(something)
        self.setUp()
        self.show = TVShow(1, 1, 'en')
        self.show.name = "The Big Bang Theory"
        self.show.saveToDB()
        self.show.loadFromDB(skipNFO=True)

    def _test_unicode(self, name, result):
        np = NameParser(True, showObj=self.show)
        parse_result = np.parse(name)

        # this shouldn't raise an exception
        repr(str(parse_result))
        self.assertEqual(parse_result.extra_info, result.extra_info)

    def test_unicode(self):
        for (name, result) in unicode_test_cases:
            self._test_unicode(name, result)
Пример #34
0
    def get_show(self, name):
        show = None
        show_id = None
        show_names = [name]

        if not all([name, sickrage.app.showlist]):
            return show, show_id

        def cache_lookup(term):
            return sickrage.app.name_cache.get(term)

        def scene_exception_lookup(term):
            return get_scene_exception_by_name(term)[0]

        def showlist_lookup(term):
            try:
                return search_showlist_by_name(term).indexerid
            except MultipleShowObjectsException:
                return None

        show_names.append(strip_accents(name))
        show_names.append(strip_accents(name).replace("'", " "))

        for show_name in set(show_names):
            lookup_list = [
                lambda: cache_lookup(show_name),
                lambda: scene_exception_lookup(show_name),
                lambda: showlist_lookup(show_name),
            ]

            # lookup show id
            for lookup in lookup_list:
                try:
                    show_id = int(lookup())
                    if show_id == 0:
                        continue

                    sickrage.app.name_cache.put(show_name, show_id)

                    if not show:
                        if self.validate_show:
                            show = findCertainShow(show_id)
                        else:
                            from sickrage.core.tv.show import TVShow
                            show = TVShow(1, show_id)
                except Exception:
                    pass

            if show_id is None:
                # ignore show name by caching it with a indexerid of 0
                sickrage.app.name_cache.put(show_name, 0)

        return show, show_id or 0
Пример #35
0
    def test_process(self):
        show = TVShow(1, 3)
        show.name = SHOWNAME
        show.location = SHOWDIR
        show.saveToDB()
        show.loadFromDB(skipNFO=True)
        sickrage.srCore.SHOWLIST = [show]
        ep = TVEpisode(show, SEASON, EPISODE)
        ep.name = "some ep name"
        ep.saveToDB()

        sickrage.srCore.NAMECACHE.addNameToCache('show name', 3)
        self.pp = PostProcessor(FILEPATH, process_method='move')
        self.assertTrue(self.pp.process)
Пример #36
0
    def setUp(self, session=None):
        super(DBBasicTests, self).setUp()
        show = TVShow(**{'indexer': 1, 'indexer_id': 0o0001, 'lang': 'en'})
        session.add(show)
        session.safe_commit()

        ep = TVEpisode(
            **{
                'showid': show.indexer_id,
                'indexer': 1,
                'season': 1,
                'episode': 1,
                'location': ''
            })
        session.add(ep)
        ep.indexer_id = 1
        ep.name = "test episode 1"
        ep.airdate = datetime.date.fromordinal(733832)
        ep.status = UNAIRED
        session.safe_commit()

        ep = TVEpisode(
            **{
                'showid': show.indexer_id,
                'indexer': 1,
                'season': 1,
                'episode': 2,
                'location': ''
            })
        session.add(ep)
        ep.indexer_id = 2
        ep.name = "test episode 2"
        ep.airdate = datetime.date.fromordinal(733832)
        ep.status = UNAIRED
        session.safe_commit()

        ep = TVEpisode(
            **{
                'showid': show.indexer_id,
                'indexer': 1,
                'season': 1,
                'episode': 3,
                'location': ''
            })
        session.add(ep)
        ep.indexer_id = 3
        ep.name = "test episode 3"
        ep.airdate = datetime.date.fromordinal(733832)
        ep.status = UNAIRED
        session.safe_commit()
Пример #37
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"]))
                sickrage.showList.append(curShow)
            except Exception as e:
                print "There was an error creating the show"
Пример #38
0
    def load_shows(self):
        """
        Populates the showlist and quicksearch cache with shows and episodes from the database
        """

        self.quicksearch_cache.load()

        for dbData in self.main_db.all('tv_shows'):
            try:
                self.log.debug("Loading data for show: [{}]".format(dbData['show_name']))
                self.showlist.append(TVShow(int(dbData['indexer']), int(dbData['indexer_id'])))
                self.quicksearch_cache.add_show(dbData['indexer_id'])
            except Exception as e:
                self.log.debug("Show error in [%s]: %s" % (dbData['location'], str(e)))
Пример #39
0
def load_shows():
    """
    Populates the showlist with shows from the database
    """

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

    return showlist
Пример #40
0
    def _test_allPossibleShowNames(self, name, indexerid=0, expected=[]):
        s = TVShow(1, indexerid)
        s.name = name
        s.saveToDB()
        s.loadFromDB(skipNFO=True)


        result = show_names.allPossibleShowNames(s)
        self.assertTrue(len(set(expected).intersection(set(result))) == len(expected))
Пример #41
0
    def load_shows(self):
        """
        Populates the showlist with shows from the database
        """

        for dbData in self.main_db.all('tv_shows'):
            try:
                self.log.debug("Loading data for show: [{}]".format(
                    dbData['show_name']))
                self.showlist += [
                    TVShow(int(dbData['indexer']), int(dbData['indexer_id']))
                ]
            except Exception as e:
                self.log.error("Show error in [%s]: %s" %
                               (dbData['location'], e.message))
Пример #42
0
    def test_process(self):
        show = TVShow(1, 3)
        show.name = SHOWNAME
        show.location = SHOWDIR
        show.saveToDB()
        show.loadFromDB(skipNFO=True)
        sickrage.srCore.SHOWLIST = [show]
        ep = TVEpisode(show, SEASON, EPISODE)
        ep.name = "some ep name"
        ep.saveToDB()

        sickrage.srCore.NAMECACHE.put('show name', 3)
        self.pp = PostProcessor(FILEPATH, process_method='move')
        self.assertTrue(self.pp.process)
Пример #43
0
    def test_process(self):
        show = TVShow(1, 3)
        show.name = self.SHOWNAME
        show.location = self.SHOWDIR
        show.save_to_db()
        sickrage.app.showlist = [show]

        sickrage.app.name_cache.put('show name', 3)
        self.post_processor = PostProcessor(self.FILEPATH, process_method='move')
        self.post_processor._log = _log
        self.assertTrue(self.post_processor.process)
Пример #44
0
    def loadFromDB(self):
        """
        Populates the showList with shows from the database
        """

        for s in [s['doc'] for s in MainDB().db.all('tv_shows', with_doc=True)]:
            try:
                curShow = TVShow(int(s["indexer"]), int(s["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"
Пример #45
0
    def test(self):
        global searchItems
        searchItems = curData["i"]
        show = TVShow(1, tvdbdid)
        show.name = show_name
        show.quality = curData["q"]
        show.saveToDB()
        show.loadFromDB(skipNFO=True)
        sickrage.srCore.SHOWLIST.append(show)
        episode = None

        for epNumber in curData["e"]:
            episode = TVEpisode(show, curData["s"], epNumber)
            episode.status = WANTED
            episode.saveToDB()

        bestResult = searchProviders(show, episode.episode, forceSearch)
        if not bestResult:
            self.assertEqual(curData["b"], bestResult)
        self.assertEqual(curData["b"], bestResult.name)  # first is expected, second is choosen one
Пример #46
0
    def test_process(self):
        show = TVShow(1, 3)
        show.name = self.SHOWNAME
        show.location = self.SHOWDIR
        show.saveToDB()
        sickrage.app.showlist = [show]
        ep = TVEpisode(show, self.SEASON, self.EPISODE)
        ep.name = "some ep name"
        ep.saveToDB()

        sickrage.app.name_cache.put('show name', 3)
        self.pp = PostProcessor(self.FILEPATH, process_method='move')
        self.assertTrue(self.pp.process)
Пример #47
0
    def test_isGoodName(self):
        listOfcases = [('Show.Name.S01E02.Test-Test', 'Show/Name'),
                       ('Show.Name.S01E02.Test-Test', 'Show. Name'),
                       ('Show.Name.S01E02.Test-Test', 'Show- Name'),
                       ('Show.Name.Part.IV.Test-Test', 'Show Name'),
                       ('Show.Name.S01.Test-Test', 'Show Name'),
                       ('Show.Name.E02.Test-Test', 'Show: Name'),
                       ('Show Name Season 2 Test', 'Show: Name'),
                       ]

        for testCase in listOfcases:
            scene_name, show_name = testCase
            s = TVShow(1, 0)
            s.name = show_name
            s.saveToDB()
            s.loadFromDB(skipNFO=True)
            self._test_isGoodName(scene_name, s)
            del s
Пример #48
0
    def run(self):
        super(QueueItemAdd, self).run()

        sickrage.srCore.srLogger.info("Started adding show {}".format(self.showDir))

        index_name = srIndexerApi(self.indexer).name

        # make sure the Indexer IDs are valid
        try:

            lINDEXER_API_PARMS = srIndexerApi(self.indexer).api_params.copy()
            if self.lang:
                lINDEXER_API_PARMS['language'] = self.lang

            sickrage.srCore.srLogger.info("{}: {}".format(index_name, repr(lINDEXER_API_PARMS)))

            t = srIndexerApi(self.indexer).indexer(**lINDEXER_API_PARMS)
            s = t[self.indexer_id]

            # this usually only happens if they have an NFO in their show dir which gave us a Indexer ID that has no proper english version of the show
            if not getattr(s, 'seriesname'):
                sickrage.srCore.srLogger.error(
                    "Show in {} has no name on {}, probably the wrong language used to search with".format(self.showDir,
                                                                                                           index_name))
                sickrage.srCore.srNotifications.error("Unable to add show",
                                                      "Show in {} has no name on {}, probably the wrong language. Delete .nfo and add manually in the correct language".format(
                                                          self.showDir, index_name))
                return self._finishEarly()

            # if the show has no episodes/seasons
            if not len(s):
                sickrage.srCore.srLogger.error("Show " + str(s['seriesname']) + " is on " + str(
                    srIndexerApi(self.indexer).name) + " but contains no season/episode data.")
                sickrage.srCore.srNotifications.error("Unable to add show",
                                                      "Show " + str(s['seriesname']) + " is on " + str(srIndexerApi(
                                                          self.indexer).name) + " but contains no season/episode data.")
                return self._finishEarly()
        except Exception as e:
            sickrage.srCore.srLogger.error(
                "{}: Error while loading information from indexer {}. Error: {}".format(self.indexer_id, index_name,
                                                                                        e.message))

            sickrage.srCore.srNotifications.error(
                "Unable to add show",
                "Unable to look up the show in {} on {} using ID {}, not using the NFO. Delete .nfo and try adding manually again.".format(
                    self.showDir, index_name, self.indexer_id)
            )

            if sickrage.srCore.srConfig.USE_TRAKT:

                trakt_id = srIndexerApi(self.indexer).config['trakt_id']
                trakt_api = TraktAPI(sickrage.srCore.srConfig.SSL_VERIFY, sickrage.srCore.srConfig.TRAKT_TIMEOUT)

                title = self.showDir.split("/")[-1]
                data = {
                    'shows': [
                        {
                            'title': title,
                            'ids': {}
                        }
                    ]
                }
                if trakt_id == 'tvdb_id':
                    data['shows'][0]['ids']['tvdb'] = self.indexer_id
                else:
                    data['shows'][0]['ids']['tvrage'] = self.indexer_id

                trakt_api.traktRequest("sync/watchlist/remove", data, method='POST')

            return self._finishEarly()

        try:
            self.show = TVShow(self.indexer, self.indexer_id, self.lang)
            self.show.loadFromIndexer()

            # set up initial values
            self.show.location = self.showDir
            self.show.subtitles = self.subtitles or sickrage.srCore.srConfig.SUBTITLES_DEFAULT
            self.show.quality = self.quality or sickrage.srCore.srConfig.QUALITY_DEFAULT
            self.show.flatten_folders = self.flatten_folders or sickrage.srCore.srConfig.FLATTEN_FOLDERS_DEFAULT
            self.show.anime = self.anime or sickrage.srCore.srConfig.ANIME_DEFAULT
            self.show.scene = self.scene or sickrage.srCore.srConfig.SCENE_DEFAULT
            self.show.archive_firstmatch = self.archive or sickrage.srCore.srConfig.ARCHIVE_DEFAULT
            self.show.paused = self.paused or False

            # set up default new/missing episode status
            sickrage.srCore.srLogger.info(
                "Setting all current episodes to the specified default status: " + str(self.default_status))
            self.show.default_ep_status = self.default_status

            if self.show.anime:
                self.show.release_groups = BlackAndWhiteList(self.show.indexerid)
                if self.blacklist:
                    self.show.release_groups.set_black_keywords(self.blacklist)
                if self.whitelist:
                    self.show.release_groups.set_white_keywords(self.whitelist)

                    # # be smartish about this
                    # if self.show.genre and "talk show" in self.show.genre.lower():
                    #     self.show.air_by_date = 1
                    # if self.show.genre and "documentary" in self.show.genre.lower():
                    #     self.show.air_by_date = 0
                    # if self.show.classification and "sports" in self.show.classification.lower():
                    #     self.show.sports = 1

        except indexer_exception as e:
            sickrage.srCore.srLogger.error(
                "Unable to add show due to an error with " + srIndexerApi(
                    self.indexer).name + ": {}".format(e.message))
            if self.show:
                sickrage.srCore.srNotifications.error(
                    "Unable to add " + str(self.show.name) + " due to an error with " + srIndexerApi(
                        self.indexer).name + "")
            else:
                sickrage.srCore.srNotifications.error(
                    "Unable to add show due to an error with " + srIndexerApi(self.indexer).name + "")
            return self._finishEarly()

        except MultipleShowObjectsException:
            sickrage.srCore.srLogger.warning("The show in " + self.showDir + " is already in your show list, skipping")
            sickrage.srCore.srNotifications.error('Show skipped',
                                                  "The show in " + self.showDir + " is already in your show list")
            return self._finishEarly()

        except Exception as e:
            sickrage.srCore.srLogger.error("Error trying to add show: {}".format(e.message))
            sickrage.srCore.srLogger.debug(traceback.format_exc())
            raise self._finishEarly()

        sickrage.srCore.srLogger.debug("Retrieving show info from TMDb")
        try:
            self.show.loadTMDbInfo()
        except Exception as e:
            sickrage.srCore.srLogger.error("Error loading TMDb info: {}".format(e.message))
            try:
                sickrage.srCore.srLogger.debug("Attempting to retrieve show info from IMDb")
                self.show.loadIMDbInfo()
            except Exception as e:
                sickrage.srCore.srLogger.error("Error loading IMDb info: {}".format(e.message))

        # Load XEM data to DB for show
        xem_refresh(self.show.indexerid, self.show.indexer, force=True)

        # check if show has XEM mapping so we can determin if searches should go by scene numbering or indexer numbering.
        if not self.scene and get_xem_numbering_for_show(self.show.indexerid, self.show.indexer):
            self.show.scene = 1

        try:
            self.show.saveToDB()
        except Exception as e:
            sickrage.srCore.srLogger.error("Error saving the show to the database: {}".format(e.message))
            sickrage.srCore.srLogger.debug(traceback.format_exc())
            raise self._finishEarly()

        # add it to the show list
        sickrage.srCore.SHOWLIST.append(self.show)

        try:
            self.show.loadEpisodesFromIndexer()
        except Exception as e:
            sickrage.srCore.srLogger.error(
                "Error with " + srIndexerApi(
                    self.show.indexer).name + ", not creating episode list: {}".format(e.message))
            sickrage.srCore.srLogger.debug(traceback.format_exc())

        try:
            self.show.loadEpisodesFromDir()
        except Exception as e:
            sickrage.srCore.srLogger.debug("Error searching dir for episodes: {}".format(e.message))
            sickrage.srCore.srLogger.debug(traceback.format_exc())

        # if they set default ep status to WANTED then run the backlog to search for episodes
        if self.show.default_ep_status == WANTED:
            sickrage.srCore.srLogger.info("Launching backlog for this show since its episodes are WANTED")
            sickrage.srCore.BACKLOGSEARCHER.searchBacklog([self.show])

        self.show.writeMetadata()
        self.show.updateMetadata()
        self.show.populateCache()

        if sickrage.srCore.srConfig.USE_TRAKT:
            # if there are specific episodes that need to be added by trakt
            sickrage.srCore.TRAKTSEARCHER.manageNewShow(self.show)

            # add show to trakt.tv library
            if sickrage.srCore.srConfig.TRAKT_SYNC:
                sickrage.srCore.TRAKTSEARCHER.addShowToTraktLibrary(self.show)

            if sickrage.srCore.srConfig.TRAKT_SYNC_WATCHLIST:
                sickrage.srCore.srLogger.info("update watchlist")
                sickrage.srCore.notifiersDict.trakt_notifier.update_watchlist(show_obj=self.show)

        # After initial add, set to default_status_after.
        sickrage.srCore.srLogger.info(
            "Setting all future episodes to the specified default status: " + str(self.default_status_after))
        self.show.default_ep_status = self.default_status_after

        self.show.saveToDB()

        sickrage.srCore.NAMECACHE.buildNameCache(self.show)

        sickrage.srCore.srLogger.info("Finished adding show {}".format(self.showDir))
Пример #49
0
 def setUp(self):
     super(AnimeTests, self).setUp()
     self.show = TVShow(1, 1, 'en')
     self.show.anime = True
     self.show.save_to_db()
Пример #50
0
 def setUp(self):
     super(UnicodeTests, self).setUp()
     self.show = TVShow(1, 1, 'en')
     self.show.name = "The Big Bang Theory"
     self.show.save_to_db()
Пример #51
0
 def setUp(self):
     super(BasicTests, self).setUp()
     self.show = TVShow(1, 1, 'en')
     self.show.save_to_db()
Пример #52
0
class BasicTests(tests.SiCKRAGETestDBCase):
    def setUp(self):
        super(BasicTests, self).setUp()
        self.show = TVShow(1, 1, 'en')
        self.show.save_to_db()

    def _test_names(self, np, section, transform=None, verbose=False):
        if VERBOSE or verbose:
            print('Running', section, 'tests')
        for cur_test_base in simple_test_cases[section]:
            if transform:
                cur_test = transform(cur_test_base)
                np.file_name = cur_test
            else:
                cur_test = cur_test_base
            if VERBOSE or verbose:
                print('Testing', cur_test)

            result = simple_test_cases[section][cur_test_base]
            np.showObj.name = result.series_name if result else None
            if not result:
                self.assertRaises(InvalidNameException, np.parse, cur_test)
                return
            else:
                result.which_regex = {section}
                test_result = np.parse(cur_test)

            if DEBUG or verbose:
                print('air_by_date:', test_result.is_air_by_date, 'air_date:', test_result.air_date)
                print('anime:', test_result.is_anime, 'ab_episode_numbers:', test_result.ab_episode_numbers)
                print(test_result)
                print(result)
            self.assertEqual(test_result.which_regex, {section})
            self.assertEqual(str(test_result), str(result))

    def test_standard_names(self):
        np = NameParser(True, showObj=self.show, validate_show=False)
        self._test_names(np, 'standard')

    def test_standard_repeat_names(self):
        np = NameParser(False, showObj=self.show, validate_show=False)
        self._test_names(np, 'standard_repeat')

    def test_fov_names(self):
        np = NameParser(False, showObj=self.show, validate_show=False)
        self._test_names(np, 'fov')

    def test_fov_repeat_names(self):
        np = NameParser(False, showObj=self.show, validate_show=False)
        self._test_names(np, 'fov_repeat')

    def test_stupid_names(self):
        np = NameParser(False, showObj=self.show, validate_show=False)
        self._test_names(np, 'stupid')

    def test_no_season_names(self):
        np = NameParser(False, showObj=self.show, validate_show=False)
        self._test_names(np, 'no_season')

    def test_no_season_general_names(self):
        np = NameParser(False, showObj=self.show, validate_show=False)
        self._test_names(np, 'no_season_general')

    def test_no_season_multi_ep_names(self):
        np = NameParser(False, showObj=self.show, validate_show=False)
        self._test_names(np, 'no_season_multi_ep')

    def test_season_only_names(self):
        np = NameParser(False, showObj=self.show, validate_show=False)
        self._test_names(np, 'season_only')

    def test_standard_file_names(self):
        np = NameParser(showObj=self.show, validate_show=False)
        self._test_names(np, 'standard', lambda x: x + '.avi')

    def test_standard_repeat_file_names(self):
        np = NameParser(showObj=self.show, validate_show=False)
        self._test_names(np, 'standard_repeat', lambda x: x + '.avi')

    def test_fov_file_names(self):
        np = NameParser(showObj=self.show, validate_show=False)
        self._test_names(np, 'fov', lambda x: x + '.avi')

    def test_fov_repeat_file_names(self):
        np = NameParser(showObj=self.show, validate_show=False)
        self._test_names(np, 'fov_repeat', lambda x: x + '.avi')

    def test_stupid_file_names(self):
        np = NameParser(showObj=self.show, validate_show=False)
        self._test_names(np, 'stupid', lambda x: x + '.avi')

    def test_no_season_file_names(self):
        np = NameParser(showObj=self.show, validate_show=False)
        self._test_names(np, 'no_season', lambda x: x + '.avi')

    def test_no_season_general_file_names(self):
        np = NameParser(showObj=self.show, validate_show=False)
        self._test_names(np, 'no_season_general', lambda x: x + '.avi')

    def test_no_season_multi_ep_file_names(self):
        np = NameParser(showObj=self.show, validate_show=False)
        self._test_names(np, 'no_season_multi_ep', lambda x: x + '.avi')

    def test_season_only_file_names(self):
        np = NameParser(showObj=self.show, validate_show=False)
        self._test_names(np, 'season_only', lambda x: x + '.avi')

    def test_combination_names(self):
        pass
Пример #53
0
class QueueItemAdd(ShowQueueItem):
    def __init__(self, indexer, indexer_id, showDir, default_status, quality, flatten_folders, lang, subtitles, anime,
                 scene, paused, blacklist, whitelist, default_status_after, archive):

        self.indexer = indexer
        self.indexer_id = indexer_id
        self.showDir = showDir
        self.default_status = default_status
        self.quality = quality
        self.flatten_folders = flatten_folders
        self.lang = lang
        self.subtitles = subtitles
        self.anime = anime
        self.scene = scene
        self.paused = paused
        self.blacklist = blacklist
        self.whitelist = whitelist
        self.default_status_after = default_status_after
        self.archive = archive

        self.show = None

        # this will initialize self.show to None
        ShowQueueItem.__init__(self, ShowQueueActions.ADD, self.show)

        # Process add show in priority
        self.priority = QueuePriorities.HIGH

    def _getName(self):
        """
        Returns the show name if there is a show object created, if not returns
        the dir that the show is being added to.
        """
        if self.show is None:
            return self.showDir
        return self.show.name

    show_name = property(_getName)

    def _isLoading(self):
        """
        Returns True if we've gotten far enough to have a show object, or False
        if we still only know the folder name.
        """
        if self.show is None:
            return True
        return False

    isLoading = property(_isLoading)

    def run(self):

        ShowQueueItem.run(self)

        sickrage.LOGGER.info("Starting to add show {}".format(self.showDir))
        # make sure the Indexer IDs are valid
        try:

            lINDEXER_API_PARMS = sickrage.INDEXER_API(self.indexer).api_params.copy()
            if self.lang:
                lINDEXER_API_PARMS[b'language'] = self.lang

            sickrage.LOGGER.info("" + str(sickrage.INDEXER_API(self.indexer).name) + ": " + repr(lINDEXER_API_PARMS))

            t = sickrage.INDEXER_API(self.indexer).indexer(**lINDEXER_API_PARMS)
            s = t[self.indexer_id]

            # this usually only happens if they have an NFO in their show dir which gave us a Indexer ID that has no proper english version of the show
            if getattr(s, 'seriesname', None) is None:
                sickrage.LOGGER.error("Show in " + self.showDir + " has no name on " + str(
                        sickrage.INDEXER_API(self.indexer).name) + ", probably the wrong language used to search with.")
                notifications.error("Unable to add show",
                                       "Show in " + self.showDir + " has no name on " + str(sickrage.INDEXER_API(
                                               self.indexer).name) + ", probably the wrong language. Delete .nfo and add manually in the correct language.")
                self._finishEarly()
                return
            # if the show has no episodes/seasons
            if not s:
                sickrage.LOGGER.error("Show " + str(s[b'seriesname']) + " is on " + str(
                        sickrage.INDEXER_API(self.indexer).name) + " but contains no season/episode data.")
                notifications.error("Unable to add show",
                                       "Show " + str(s[b'seriesname']) + " is on " + str(sickrage.INDEXER_API(
                                               self.indexer).name) + " but contains no season/episode data.")
                self._finishEarly()
                return
        except Exception as e:
            sickrage.LOGGER.error("%s Error while loading information from indexer %s. Error: %r" % (
                self.indexer_id, sickrage.INDEXER_API(self.indexer).name, e))

            notifications.error(
                    "Unable to add show",
                    "Unable to look up the show in %s on %s using ID %s, not using the NFO. Delete .nfo and try adding manually again." %
                    (self.showDir, sickrage.INDEXER_API(self.indexer).name, self.indexer_id)
            )

            if sickrage.USE_TRAKT:

                trakt_id = sickrage.INDEXER_API(self.indexer).config[b'trakt_id']
                trakt_api = TraktAPI(sickrage.SSL_VERIFY, sickrage.TRAKT_TIMEOUT)

                title = self.showDir.split("/")[-1]
                data = {
                    'shows': [
                        {
                            'title': title,
                            'ids': {}
                        }
                    ]
                }
                if trakt_id == 'tvdb_id':
                    data[b'shows'][0][b'ids'][b'tvdb'] = self.indexer_id
                else:
                    data[b'shows'][0][b'ids'][b'tvrage'] = self.indexer_id

                trakt_api.traktRequest("sync/watchlist/remove", data, method='POST')

            self._finishEarly()
            return

        try:
            self.show = TVShow(self.indexer, self.indexer_id, self.lang)
            self.show.loadFromIndexer()

            # set up initial values
            self.show.location = self.showDir
            self.show.subtitles = self.subtitles if self.subtitles is not None else sickrage.SUBTITLES_DEFAULT
            self.show.quality = self.quality if self.quality else sickrage.QUALITY_DEFAULT
            self.show.flatten_folders = self.flatten_folders if self.flatten_folders is not None else sickrage.FLATTEN_FOLDERS_DEFAULT
            self.show.anime = self.anime if self.anime is not None else sickrage.ANIME_DEFAULT
            self.show.scene = self.scene if self.scene is not None else sickrage.SCENE_DEFAULT
            self.show.archive_firstmatch = self.archive if self.archive is not None else sickrage.ARCHIVE_DEFAULT
            self.show.paused = self.paused if self.paused is not None else False

            # set up default new/missing episode status
            sickrage.LOGGER.info("Setting all episodes to the specified default status: " + str(self.show.default_ep_status))
            self.show.default_ep_status = self.default_status

            if self.show.anime:
                self.show.release_groups = BlackAndWhiteList(self.show.indexerid)
                if self.blacklist:
                    self.show.release_groups.set_black_keywords(self.blacklist)
                if self.whitelist:
                    self.show.release_groups.set_white_keywords(self.whitelist)

                    # # be smartish about this
                    # if self.show.genre and "talk show" in self.show.genre.lower():
                    #     self.show.air_by_date = 1
                    # if self.show.genre and "documentary" in self.show.genre.lower():
                    #     self.show.air_by_date = 0
                    # if self.show.classification and "sports" in self.show.classification.lower():
                    #     self.show.sports = 1

        except indexer_exception as e:
            sickrage.LOGGER.error(
                    "Unable to add show due to an error with " + sickrage.INDEXER_API(
                            self.indexer).name + ": {}".format(e))
            if self.show:
                notifications.error(
                        "Unable to add " + str(self.show.name) + " due to an error with " + sickrage.INDEXER_API(
                                self.indexer).name + "")
            else:
                notifications.error(
                        "Unable to add show due to an error with " + sickrage.INDEXER_API(self.indexer).name + "")
            self._finishEarly()
            return

        except MultipleShowObjectsException:
            sickrage.LOGGER.warning("The show in " + self.showDir + " is already in your show list, skipping")
            notifications.error('Show skipped', "The show in " + self.showDir + " is already in your show list")
            self._finishEarly()
            return

        except Exception as e:
            sickrage.LOGGER.error("Error trying to add show: {}".format(e))
            sickrage.LOGGER.debug(traceback.format_exc())
            self._finishEarly()
            raise

        sickrage.LOGGER.debug("Retrieving show info from TMDb")
        try:
            self.show.loadTMDbInfo()
        except Exception as e:
            sickrage.LOGGER.error("Error loading TMDb info: {}".format(e))
            try:
                sickrage.LOGGER.debug("Attempting to retrieve show info from IMDb")
                self.show.loadIMDbInfo()
            except Exception as e:
                sickrage.LOGGER.error("Error loading IMDb info: {}".format(e))

        try:
            self.show.saveToDB()
        except Exception as e:
            sickrage.LOGGER.error("Error saving the show to the database: {}".format(e))
            sickrage.LOGGER.debug(traceback.format_exc())
            self._finishEarly()
            raise

        # add it to the show list
        sickrage.showList.append(self.show)

        try:
            self.show.loadEpisodesFromIndexer()
        except Exception as e:
            sickrage.LOGGER.error(
                    "Error with " + sickrage.INDEXER_API(
                            self.show.indexer).name + ", not creating episode list: {}".format(e))
            sickrage.LOGGER.debug(traceback.format_exc())

        # update internal name cache
        sickrage.NAMECACHE.buildNameCache()

        try:
            self.show.loadEpisodesFromDir()
        except Exception as e:
            sickrage.LOGGER.error("Error searching dir for episodes: {}".format(e))
            sickrage.LOGGER.debug(traceback.format_exc())

        # if they set default ep status to WANTED then run the backlog to search for episodes
        # FIXME: This needs to be a backlog queue item!!!
        if self.show.default_ep_status == WANTED:
            sickrage.LOGGER.info("Launching backlog for this show since its episodes are WANTED")
            sickrage.BACKLOGSEARCHER.searchBacklog([self.show])

        self.show.writeMetadata()
        self.show.updateMetadata()
        self.show.populateCache()

        self.show.flushEpisodes()

        if sickrage.USE_TRAKT:
            # if there are specific episodes that need to be added by trakt
            sickrage.TRAKTSEARCHER.manageNewShow(self.show)

            # add show to trakt.tv library
            if sickrage.TRAKT_SYNC:
                sickrage.TRAKTSEARCHER.addShowToTraktLibrary(self.show)

            if sickrage.TRAKT_SYNC_WATCHLIST:
                sickrage.LOGGER.info("update watchlist")
                sickrage.NOTIFIERS.trakt_notifier.update_watchlist(show_obj=self.show)

        # Load XEM data to DB for show
        xem_refresh(self.show.indexerid, self.show.indexer, force=True)

        # check if show has XEM mapping so we can determin if searches should go by scene numbering or indexer numbering.
        if not self.scene and get_xem_numbering_for_show(self.show.indexerid,
                                                         self.show.indexer):
            self.show.scene = 1

        # After initial add, set to default_status_after.
        self.show.default_ep_status = self.default_status_after

        self.finish()

    def _finishEarly(self):
        if self.show is not None:
            sickrage.SHOWQUEUE.removeShow(self.show)

        self.finish()
Пример #54
0
    def _test_allPossibleShowNames(self, name, indexerid=0, expected=[]):
        s = TVShow(1, indexerid)
        s.name = name

        result = show_names.allPossibleShowNames(s)
        self.assertTrue(len(set(expected).intersection(set(result))) == len(expected))
Пример #55
0
 def test_getEpisode(self):
     show = TVShow(1, 0001, "en")
     show.name = "show name"
     show.network = "cbs"
     show.genre = "crime"
     show.runtime = 40
     show.status = "Ended"
     show.default_ep_status = "5"
     show.airs = "monday"
     show.startyear = 1987
     show.saveToDB()
     show.loadFromDB(skipNFO=True)
     sickrage.app.showlist = [show]
Пример #56
0
    def test(self):
        show = TVShow(1, int(curData["tvdbid"]))
        show.name = name
        show.quality = ANY | Quality.UNKNOWN | Quality.RAWHDTV
        show.saveToDB()
        show.loadFromDB(skipNFO=True)

        sickrage.srCore.SHOWLIST.append(show)

        for epNumber in curData["e"]:
            episode = TVEpisode(show, curData["s"], epNumber)
            episode.status = WANTED

            # We arent updating scene numbers, so fake it here
            episode.scene_season = curData["s"]
            episode.scene_episode = epNumber

            episode.saveToDB()

            provider.show = show
            season_strings = provider._get_season_search_strings(episode)
            episode_strings = provider._get_episode_search_strings(episode)

            fail = False
            for cur_string in season_strings, episode_strings:
                if not all([isinstance(cur_string, list), isinstance(cur_string[0], dict)]):
                    print(" %s is using a wrong string format!" % provider.name)
                    print(cur_string)
                    fail = True
                    continue

            if fail:
                continue

            try:
                assert (season_strings == curData["s_strings"])
                assert (episode_strings == curData["e_strings"])
            except AssertionError:
                continue

            search_strings = episode_strings[0]
            # search_strings.update(season_strings[0])
            # search_strings.update({"RSS":['']})

            # print search_strings

            if not provider.public:
                continue

            items = provider.search(search_strings)
            if not items:
                print("No results from provider?")
                continue

            title, url = provider._get_title_and_url(items[0])
            for word in show.name.split(" "):
                if not word.lower() in title.lower():
                    print("Show name not in title: %s. URL: %s" % (title, url))
                    continue

            if not url:
                print("url is empty")
                continue

            quality = provider.getQuality(items[0])
            size = provider._get_size(items[0])
            if not show.quality & quality:
                print("Quality not in ANY, %r" % quality)
                continue
Пример #57
0
 def test_set_name(self):
     show = TVShow(1, 0001, "en")
     show.name = "newName"
     show.saveToDB()
     show.loadFromDB(skipNFO=True)
     self.assertEqual(show.name, "newName")
Пример #58
0
    def test_change_indexerid(self):
        show = TVShow(1, 0001, "en")
        show.name = "show name"
        show.network = "cbs"
        show.genre = "crime"
        show.runtime = 40
        show.status = "Ended"
        show.default_ep_status = "5"
        show.airs = "monday"
        show.startyear = 1987
        show.indexerid = 0002
        show.saveToDB()
        show.loadFromDB(skipNFO=True)

        self.assertEqual(show.indexerid, 0002)
Пример #59
0
    def test_init_indexerid(self):
        show = TVShow(1, 0001, "en")
        show.saveToDB()
        show.loadFromDB(skipNFO=True)

        self.assertEqual(show.indexerid, 0001)