Exemplo n.º 1
0
 def _test_allPossibleShowNames(self, name, tvdbid=0, tvrname=None, expected=[]):
     s = Show(tvdbid)
     s.name = name
     s.tvrname = tvrname
     
     result = show_name_helpers.allPossibleShowNames(s)
     self.assertTrue(len(set(expected).intersection(set(result))) == len(expected))
    def execute(self):

        ShowQueueItem.execute(self)

        logger.log(u"Starting to add show "+self.showDir)

        try:
            # make sure the tvdb ids are valid
            try:
                ltvdb_api_parms = sickbeard.TVDB_API_PARMS.copy()
                if self.lang:
                    ltvdb_api_parms['language'] = self.lang
        
                t = tvdb_api.Tvdb(**ltvdb_api_parms)
                s = t[self.tvdb_id]
                if not s or not s['seriesname']:
                    ui.flash.error("Unable to add show", "Show in "+str(self.showDir)+" has no name on TVDB, probably the wrong language. Delete .nfo and add manually in the correct language.")
                    self._finishEarly()
                    return
            except tvdb_exceptions.tvdb_exception, e:
                ui.flash.error("Unable to add show", "Unable to look up the show in "+str(self.showDir)+" on TVDB, not using the NFO. Delete .nfo and add manually in the correct language.")
                self._finishEarly()
                return

            newShow = TVShow(self.tvdb_id, self.lang)
            newShow.loadFromTVDB()

            self.show = newShow

            # set up initial values
            self.show.location = self.showDir
            self.show.quality = self.quality if self.quality else sickbeard.QUALITY_DEFAULT
            self.show.seasonfolders = self.season_folders if self.season_folders != None else sickbeard.SEASON_FOLDERS_DEFAULT
            self.show.paused = False
Exemplo n.º 3
0
    def execute(self):

        ShowQueueItem.execute(self)

        logger.log(u"Starting to add show "+self.showDir)

        try:
            newShow = TVShow(self.tvdb_id, self.lang)
            newShow.loadFromTVDB()

            self.show = newShow

            # set up initial values
            self.show.location = self.showDir
            self.show.quality = sickbeard.QUALITY_DEFAULT
            self.show.seasonfolders = sickbeard.SEASON_FOLDERS_DEFAULT
            self.show.paused = False

        except tvdb_exceptions.tvdb_exception, e:
            logger.log(u"Unable to add show due to an error with TVDB: "+str(e).decode('utf-8'), logger.ERROR)
            if self.show:
                ui.flash.error("Unable to add "+str(self.show.name)+" due to an error with TVDB")
            else:
                ui.flash.error("Unable to add show due to an error with TVDB")
            self._finishEarly()
            return
Exemplo n.º 4
0
    def loadShowsFromDB():
        """
        Populates the showList with shows from the database
        """
        logging.debug("Loading initial show list")

        myDB = db.DBConnection()
        sqlResults = myDB.select("SELECT * FROM tv_shows")

        sickbeard.showList = []
        for sqlShow in sqlResults:
            try:
                curShow = TVShow(int(sqlShow[b"indexer"]), int(sqlShow[b"indexer_id"]))

                # Build internal name cache for show
                name_cache.buildNameCache(curShow)

                # get next episode info
                curShow.nextEpisode()

                # add show to internal show list
                sickbeard.showList.append(curShow)
            except Exception as e:
                logging.error(
                        "There was an error creating the show in " + sqlShow[b"location"] + ": " + str(e).decode(
                                'utf-8'))
                logging.debug(traceback.format_exc())
Exemplo n.º 5
0
class QueueItemAdd(QueueItem):
    def __init__(self, show=None):

        self.showDir = show

        # if we can't create the dir, bail
        if not os.path.isdir(self.showDir):
            if not helpers.makeDir(self.showDir):
                raise exceptions.NoNFOException("Unable to create the show dir " + self.showDir)

        if not os.path.isfile(os.path.join(self.showDir, "tvshow.nfo")):
            raise exceptions.NoNFOException("No tvshow.nfo found")

        # this will initialize self.show to None
        QueueItem.__init__(self, QueueActions.ADD)

        self.initialShow = TVShow(self.showDir)

    def _getName(self):
        if self.show == None:
            return self.showDir
        return self.show.name

    name = property(_getName)

    def _isLoading(self):
        if self.show == None:
            return True
        return False

    isLoading = property(_isLoading)

    def execute(self):

        QueueItem.execute(self)

        logger.log("Starting to add show "+self.showDir)

        otherShow = helpers.findCertainShow(sickbeard.showList, self.initialShow.tvdbid)
        if otherShow != None:
            logger.log("Show is already in your list, not adding it again")
            self.finish()
            return

        try:
            self.initialShow.getImages()
            self.initialShow.loadFromTVDB()
            
        except tvdb_exceptions.tvdb_exception, e:
            logger.log("Unable to add show due to an error with TVDB: "+str(e), logger.ERROR)
            webserve.flash.error("Unable to add "+str(self.initialShow.name)+" due to an error with TVDB")
            self._finishEarly()
            return
            
        except exceptions.NoNFOException:
            logger.log("Unable to load show from NFO", logger.ERROR)
            webserve.flash.error("Unable to add "+str(self.initialShow.name)+" from NFO, skipping")
            self._finishEarly()
            return
Exemplo n.º 6
0
    def execute(self):

        ShowQueueItem.execute(self)

        logger.log(u"Starting to add show " + self.showDir)

        try:
            # make sure the tvdb ids are valid
            try:
                ltvdb_api_parms = sickbeard.TVDB_API_PARMS.copy()
                if self.lang:
                    ltvdb_api_parms["language"] = self.lang

                logger.log(u"TVDB: " + repr(ltvdb_api_parms))

                t = tvdb_api.Tvdb(**ltvdb_api_parms)
                s = t[self.tvdb_id]

                # this usually only happens if they have an NFO in their show dir which gave us a TVDB ID that has no
                # proper english version of the show
                if not s or not s["seriesname"]:
                    ui.notifications.error(
                        "Unable to add show",
                        "Show in "
                        + self.showDir
                        + " has no name on TVDB, probably the wrong language. Delete .nfo and add manually in the correct language.",
                    )
                    self._finishEarly()
                    return
            except tvdb_exceptions.tvdb_exception, e:
                logger.log(u"Error contacting TVDB: " + ex(e), logger.ERROR)
                ui.notifications.error(
                    "Unable to add show",
                    "Unable to look up the show in "
                    + self.showDir
                    + " on TVDB, not using the NFO. Delete .nfo and add manually in the correct language.",
                )
                self._finishEarly()
                return

            # clear the name cache
            name_cache.clearCache()

            newShow = TVShow(self.tvdb_id, self.lang)
            newShow.loadFromTVDB()

            self.show = newShow

            # set up initial values
            self.show.location = self.showDir
            self.show.quality = self.quality if self.quality else sickbeard.QUALITY_DEFAULT
            self.show.flatten_folders = (
                self.flatten_folders if self.flatten_folders != None else sickbeard.FLATTEN_FOLDERS_DEFAULT
            )
            self.show.paused = False

            # be smartish about this
            if self.show.genre and "talk show" in self.show.genre.lower():
                self.show.air_by_date = 1
    def _test_allPossibleShowNames(self, name, tvdbid=0, tvrname=None, expected=[]):
        s = Show(tvdbid)
        s.name = name
        s.tvrname = tvrname
        result = show_name_helpers.allPossibleShowNames(s)
        
        result = [unicode(x) for x in sorted(result)]
        expected = [unicode(x) for x in sorted(expected)]

        #self.assertEqual(len(set(expected).intersection(set(result))), len(expected))
        self.assertEqual(result, expected)
Exemplo n.º 8
0
    def setUpClass(cls):
        cls.shows = []

        show = TVShow(1, 121361)
        show.name = "Italian Works"
        show.episodes = []
        episode = TVEpisode(show, 05, 10)
        episode.name = "Pines of Rome"
        episode.scene_season = 5
        episode.scene_episode = 10
        show.episodes.append(episode)
        cls.shows.append(show)
Exemplo n.º 9
0
class QueueItemAdd(QueueItem):
    def __init__(self, show=None):

        self.showDir = show

        # if we can't create the dir, bail
        if not os.path.isdir(self.showDir):
            if not helpers.makeDir(self.showDir):
                raise exceptions.NoNFOException("Unable to create the show dir " + self.showDir)

        if not os.path.isfile(os.path.join(self.showDir, "tvshow.nfo")):
            raise exceptions.NoNFOException("No tvshow.nfo found")

        # this will initialize self.show to None
        QueueItem.__init__(self, QueueActions.ADD)

        self.initialShow = TVShow(self.showDir)

    def _getName(self):
        if self.show == None:
            return self.showDir
        return self.show.name

    name = property(_getName)

    def _isLoading(self):
        if self.show == None:
            return True
        return False

    isLoading = property(_isLoading)

    def execute(self):

        QueueItem.execute(self)

        logger.log("Starting to add show "+self.showDir)

        try:
            self.initialShow.getImages()
            self.initialShow.loadFromTVDB()
            
        except tvdb_exceptions.tvdb_exception, e:
            logger.log("Unable to add show due to an error with TVDB: "+str(e), logger.ERROR)
            self.finish()
            return
            
        except exceptions.NoNFOException:
            logger.log("Unable to load show from NFO", logger.ERROR)
            # take the show out of the loading list
            self.finish()
            return
Exemplo n.º 10
0
    def test_process(self):
        show = TVShow(3)
        show.name = test.SHOWNAME
        show.location = test.SHOWDIR
        show.saveToDB()

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

        pp = PostProcessor(test.FILEPATH)
        self.assertTrue(pp.process())
Exemplo n.º 11
0
 def test(self):
     show = TVShow(tvdb_id)
     show.name = data[0]
     if data[1]:
         show.anime = 1
     show.saveToDB()
     showList = [show]
     sceneName = data[2]
     result = helpers.get_show_by_name(sceneName, showList, False)
     if not result:
         self.assertEqual(False, show.tvdbid)
         return False
     self.assertEqual(result.tvdbid, show.tvdbid)
Exemplo n.º 12
0
    def test_process(self):
        show = TVShow(1, 3)
        show.name = SHOWNAME
        show.location = SHOWDIR
        show.saveToDB()

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

        addNameToCache('show name', 3)
        self.pp = PostProcessor(FILEPATH, process_method='move')
        self.assertTrue(self.pp.process())
Exemplo n.º 13
0
def loadShowsFromDB():

	myDB = db.DBConnection()
	sqlResults = myDB.select("SELECT * FROM tv_shows")
	
	myShowList = []
	
	for sqlShow in sqlResults:
		try:
			curShow = TVShow(sqlShow["location"])
			curShow.saveToDB()
			sickbeard.showList.append(curShow)
		except Exception, e:
			logger.log("There was an error creating the show in "+sqlShow["location"]+": "+str(e), logger.ERROR)
			logger.log(traceback.format_exc(), logger.DEBUG)
Exemplo n.º 14
0
    def _test_all_possible_show_names(self, name, indexerid=0, expected=None):
        """
        Test all possible show names

        :param name:
        :param indexerid:
        :param expected:
        :return:
        """
        expected = [] if expected is None else expected
        show = Show(1, indexerid)
        show.name = name

        result = show_name_helpers.allPossibleShowNames(show)
        self.assertTrue(len(set(expected).intersection(set(result))) == len(expected))
Exemplo n.º 15
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 = Show(0)
            s.name = show_name
            self._test_isGoodName(scene_name, s)
Exemplo n.º 16
0
    def test_process(self):
        show = TVShow(1,3)
        show.name = test.SHOWNAME
        show.location = test.SHOWDIR
        show.saveToDB()

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

        addNameToCache('show name', 3)
        sickbeard.PROCESS_METHOD = 'move'

        pp = PostProcessor(test.FILEPATH)
        self.assertTrue(pp.process())
Exemplo n.º 17
0
    def test_is_good_name(self):
        """
        Perform good name tests
        """
        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 test_case in list_of_cases:
            scene_name, show_name = test_case
            show = Show(1, 0)
            show.name = show_name
            self._test_is_good_name(scene_name, show)
Exemplo n.º 18
0
    def test(self):
        global searchItems
        searchItems = curData["i"]
        show = TVShow(tvdbdid)
        show.name = show_name
        show.quality = curData["q"]
        show.saveToDB()
        sickbeard.showList.append(show)

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

        bestResult = search.findEpisode(episode, forceSearch)
        if not bestResult:
            self.assertEqual(curData["b"], bestResult)
        self.assertEqual(curData["b"], bestResult.name) #first is expected, second is choosen one
Exemplo n.º 19
0
    def load_shows_from_db():
        """
        Populates the showList with shows from the database
        """
        logger.log('Loading initial show list', logger.DEBUG)

        main_db_con = db.DBConnection()
        sql_results = main_db_con.select('SELECT indexer, indexer_id, location FROM tv_shows;')

        sickbeard.showList = []
        for sql_show in sql_results:
            try:
                cur_show = TVShow(sql_show[b'indexer'], sql_show[b'indexer_id'])
                cur_show.nextEpisode()
                sickbeard.showList.append(cur_show)
            except Exception as error:  # pylint: disable=broad-except
                logger.log('There was an error creating the show in {0}: Error {1}'.format
                           (sql_show[b'location'], error), logger.ERROR)
                logger.log(traceback.format_exc(), logger.DEBUG)
Exemplo n.º 20
0
    def test(self):
        global searchItems
        searchItems = curData['i']
        show = TVShow(1, tvdbdid)
        show.name = show_name
        show.quality = curData['q']
        show.saveToDB()
        sickbeard.showList.append(show)
        episode = None

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

        bestResult = search.search_providers(show, episode.season, episode.episode, forceSearch)
        if not bestResult:
            self.assertEqual(curData['b'], bestResult)
        self.assertEqual(curData['b'], bestResult.name) #first is expected, second is choosen one
Exemplo n.º 21
0
    def load_shows_from_db():
        """
        Populates the showList with shows from the database
        """

        logger.log(u'Loading initial show list')

        my_db = db.DBConnection()
        sql_results = my_db.select('SELECT * FROM tv_shows')

        sickbeard.showList = []
        for sqlShow in sql_results:
            try:
                cur_show = TVShow(int(sqlShow['indexer']), int(sqlShow['indexer_id']))
                cur_show.nextEpisode()
                sickbeard.showList.append(cur_show)
            except Exception as er:
                logger.log('There was an error creating the show in %s: %s' % (
                    sqlShow['location'], str(er).decode('utf-8', 'replace')), logger.ERROR)
Exemplo n.º 22
0
    def test_process(self):
        """
        Test process
        """
        show = TVShow(1, 3)
        show.name = test.SHOW_NAME
        show.location = test.SHOW_DIR
        show.saveToDB()

        sickbeard.showList = [show]
        episode = TVEpisode(show, test.SEASON, test.EPISODE)
        episode.name = "some episode name"
        episode.saveToDB()

        addNameToCache('show name', 3)
        sickbeard.PROCESS_METHOD = 'move'

        post_processor = PostProcessor(test.FILE_PATH)
        self.assertTrue(post_processor.process())
Exemplo n.º 23
0
    def loadShowsFromDB():
        """
        Populates the showList with shows from the database
        """
        logger.log(u"Loading initial show list", logger.DEBUG)

        myDB = db.DBConnection()
        sqlResults = myDB.select("SELECT indexer, indexer_id, location FROM tv_shows;")

        sickbeard.showList = []
        for sqlShow in sqlResults:
            try:
                curShow = TVShow(int(sqlShow["indexer"]), int(sqlShow["indexer_id"]))
                curShow.nextEpisode()
                sickbeard.showList.append(curShow)
            except Exception as e:
                logger.log(
                    u"There was an error creating the show in " + sqlShow["location"] + ": " + str(e).decode('utf-8'),
                    logger.ERROR)
                logger.log(traceback.format_exc(), logger.DEBUG)
Exemplo n.º 24
0
    def load_shows_from_db():
        """
        Populates the showList with shows from the database
        """
        logger.log("Loading initial show list", logger.DEBUG)  # pylint: disable=no-member

        main_db_con = db.DBConnection()
        sql_results = main_db_con.select("SELECT indexer, indexer_id, location FROM tv_shows;")

        sickbeard.showList = []
        for sql_show in sql_results:
            try:
                cur_show = TVShow(sql_show[b"indexer"], sql_show[b"indexer_id"])
                cur_show.nextEpisode()
                sickbeard.showList.append(cur_show)
            except Exception as error_msg:  # pylint: disable=broad-except
                logger.log(
                    "There was an error creating the show in %s: %s"
                    % (sql_show[b"location"], str(error_msg).decode()),  # pylint: disable=no-member
                    logger.ERROR,
                )
                logger.log(traceback.format_exc(), logger.DEBUG)  # pylint: disable=no-member
Exemplo n.º 25
0
    def do_test():
        """
        Test to perform
        """
        global search_items  # pylint: disable=global-statement
        search_items = cur_data["i"]
        show = TVShow(1, tvdb_id)
        show.name = show_name
        show.quality = cur_data["q"]
        show.saveToDB()
        sickbeard.showList.append(show)
        episode = None

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

        best_result = search.searchProviders(show, episode.episode, force_search)
        if not best_result:
            assert cur_data["b"] == best_result
        # pylint: disable=no-member
        assert cur_data["b"] == best_result.name  # first is expected, second is chosen one
Exemplo n.º 26
0
 def test_set_name(self):
     """
     test set name
     """
     show = TVShow(1, 1, "en")
     show.name = "newName"
     show.saveToDB()
     show.loadFromDB()
     self.assertEqual(show.name, "newName")
Exemplo n.º 27
0
 def test_set_name(self):
     """
     test set name
     """
     show = TVShow(1, 1, "en")
     show.name = "newName"
     show.save_to_db()
     show._load_from_db()
     self.assertEqual(show.name, "newName")
Exemplo n.º 28
0
    def loadShowsFromDB(self):
        """
        Populates the showList with shows from the database
        """

        logger.log(u"Loading initial show list")

        myDB = db.DBConnection()
        sqlResults = myDB.select("SELECT * FROM tv_shows")

        sickbeard.showList = []
        for sqlShow in sqlResults:
            try:
                curShow = TVShow(int(sqlShow["indexer"]), int(sqlShow["indexer_id"]))
                curShow.nextEpisode()
                sickbeard.showList.append(curShow)
            except Exception, e:
                logger.log(
                    u"There was an error creating the show in "
                    + sqlShow["location"]
                    + ": "
                    + str(e).decode("utf-8", "replace"),
                    logger.ERROR,
                )
Exemplo n.º 29
0
    def setUpClass(cls):
        num_legacy_shows = 3
        num_shows = 3
        num_episodes_per_show = 5
        cls.mydb = db.DBConnection()
        cls.legacy_shows = []
        cls.shows = []

        # Per-show-notifications were originally added for email notifications only.  To add
        # this feature to other notifiers, it was necessary to alter the way text is stored in
        # one of the DB columns.  Therefore, to test properly, we must create some shows that
        # store emails in the old method (legacy method) and then other shows that will use
        # the new method.
        for show_counter in range(100, 100+num_legacy_shows):
            show = TVShow(1, show_counter)
            show.name = "Show "+str(show_counter)
            show.episodes = []
            for episode_counter in range(0, num_episodes_per_show):
                episode = TVEpisode(show, test.SEASON, episode_counter)
                episode.name = "Episode "+str(episode_counter+1)
                episode.quality = "SDTV"
                show.episodes.append(episode)
            show.saveToDB()
            cls.legacy_shows.append(show)

        for show_counter in range(200, 200+num_shows):
            show = TVShow(1, show_counter)
            show.name = "Show "+str(show_counter)
            show.episodes = []
            for episode_counter in range(0, num_episodes_per_show):
                episode = TVEpisode(show, test.SEASON, episode_counter)
                episode.name = "Episode "+str(episode_counter+1)
                episode.quality = "SDTV"
                show.episodes.append(episode)
            show.saveToDB()
            cls.shows.append(show)
Exemplo n.º 30
0
    def __init__(self, show=None):

        self.showDir = show

        # if we can't create the dir, bail
        if not os.path.isdir(self.showDir):
            if not helpers.makeDir(self.showDir):
                raise exceptions.NoNFOException("Unable to create the show dir " + self.showDir)

        if not os.path.isfile(os.path.join(self.showDir, "tvshow.nfo")):
            raise exceptions.NoNFOException("No tvshow.nfo found")

        # this will initialize self.show to None
        QueueItem.__init__(self, QueueActions.ADD)

        self.initialShow = TVShow(self.showDir)
Exemplo n.º 31
0
    def test_change_indexerid(self):
        show = TVShow(1, 1, "en")
        show.name = "show name"
        show.tvrname = "show name"
        show.network = "cbs"
        show.genre = "crime"
        show.runtime = 40
        show.status = "5"
        show.airs = "monday"
        show.startyear = 1987

        show.saveToDB()
        show.loadFromDB(skipNFO=True)

        show.indexerid = 2
        show.saveToDB()
        show.loadFromDB(skipNFO=True)

        self.assertEqual(show.indexerid, 2)
Exemplo n.º 32
0
 def test_set_name(self):
     show = TVShow(1, 1, "en")
     show.name = "newName"
     show.saveToDB()
     show.loadFromDB(skipNFO=True)
     self.assertEqual(show.name, "newName")
Exemplo n.º 33
0
 def test_getEpisode():
     show_obj = TVShow(1, 1, 'en')
     show_obj.name = 'show name'
     show_obj.tvrname = 'show name'
     show_obj.network = 'cbs'
     show_obj.genre = 'crime'
     show_obj.runtime = 40
     show_obj.status = '5'
     show_obj.airs = 'monday'
     show_obj.startyear = 1987
     show_obj.save_to_db()
     sickbeard.showList = [show_obj]
     sickbeard.showDict = {show_obj.sid_int: show_obj}
Exemplo n.º 34
0
    def test_change_indexerid(self):
        show = TVShow(1, 1, 'en')
        show.name = 'show name'
        show.tvrname = 'show name'
        show.network = 'cbs'
        show.genre = 'crime'
        show.runtime = 40
        show.status = '5'
        show.airs = 'monday'
        show.startyear = 1987

        show.saveToDB()
        show.loadFromDB(skipNFO=True)

        show.indexerid = 2
        show.saveToDB()
        show.loadFromDB(skipNFO=True)

        self.assertEqual(show.indexerid, 2)
Exemplo n.º 35
0
    def execute(self):

        ShowQueueItem.execute(self)

        logger.log(u"Starting to add show " + self.showDir)

        try:
            # make sure the tvdb ids are valid
            try:
                ltvdb_api_parms = sickbeard.TVDB_API_PARMS.copy()
                if self.lang:
                    ltvdb_api_parms['language'] = self.lang

                logger.log(u"TVDB: " + repr(ltvdb_api_parms))

                t = tvdb_api.Tvdb(**ltvdb_api_parms)
                s = t[self.tvdb_id]

                # this usually only happens if they have an NFO in their show dir which gave us a TVDB ID that has no proper english version of the show
                if not s['seriesname']:
                    logger.log(
                        u"Show in " + self.showDir +
                        " has no name on TVDB, probably the wrong language used to search with.",
                        logger.ERROR)
                    ui.notifications.error(
                        "Unable to add show", "Show in " + self.showDir +
                        " has no name on TVDB, 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:
                    logger.log(
                        u"Show " + str(s['seriesname']) +
                        " is on TVDB but contains no season/episode data.",
                        logger.ERROR)
                    ui.notifications.error(
                        "Unable to add show", "Show " + str(s['seriesname']) +
                        " is on TVDB but contains no season/episode data.")
                    self._finishEarly()
                    return
            except tvdb_exceptions.tvdb_exception, e:
                logger.log(u"Error contacting TVDB: " + ex(e), logger.ERROR)
                ui.notifications.error(
                    "Unable to add show",
                    "Unable to look up the show in " + self.showDir +
                    " on TVDB, not using the NFO. Delete .nfo and add manually in the correct language."
                )
                self._finishEarly()
                return

            # clear the name cache
            name_cache.clearCache()

            newShow = TVShow(self.tvdb_id, self.lang)
            newShow.loadFromTVDB()

            self.show = newShow

            # set up initial values
            self.show.location = self.showDir
            self.show.quality = self.quality if self.quality else sickbeard.QUALITY_DEFAULT
            self.show.flatten_folder = self.flatten_folder if self.flatten_folder != None else sickbeard.FLATTEN_FOLDERS_DEFAULT
            self.show.anime = self.anime if self.anime != None else sickbeard.ANIME_DEFAULT
            self.show.paused = 0

            # be smartish about this
            if self.show.genre and "talk show" in self.show.genre.lower():
                self.show.air_by_date = 1
Exemplo n.º 36
0
 def test_getEpisode(self):
     show = TVShow(1, 1, 'en')
     show.name = 'show name'
     show.tvrname = 'show name'
     show.network = 'cbs'
     show.genre = 'crime'
     show.runtime = 40
     show.status = '5'
     show.airs = 'monday'
     show.startyear = 1987
     show.saveToDB()
     sickbeard.showList = [show]
Exemplo n.º 37
0
 def test_init_indexerid(self):
     """
     test init indexer id
     """
     show = TVShow(1, 1, "en")
     self.assertEqual(show.indexerid, 1)
Exemplo n.º 38
0
 def test_set_name(self):
     show_obj = TVShow(1, 1, 'en')
     show_obj.name = 'newName'
     show_obj.save_to_db()
     show_obj.load_from_db()
     self.assertEqual(show_obj.name, 'newName')
Exemplo n.º 39
0
    def _test_allPossibleShowNames(self, name, indexerid=0, expected=[]):
        s = Show(1, indexerid)
        s.name = name

        result = show_name_helpers.allPossibleShowNames(s)
        self.assertTrue(len(set(expected).intersection(set(result))) == len(expected))
Exemplo n.º 40
0
    def do_test(self):
        """
        Test to perform
        """
        show = TVShow(1, int(cur_data["tvdbid"]))
        show.name = cur_name
        show.quality = common.ANY | common.Quality.UNKNOWN | common.Quality.RAWHDTV
        show.saveToDB()
        sickbeard.showList.append(show)

        for ep_number in cur_data["e"]:
            episode = TVEpisode(show, cur_data["s"], ep_number)
            episode.status = common.WANTED

            # We aren't updating scene numbers, so fake it here
            episode.scene_season = cur_data["s"]
            episode.scene_episode = ep_number

            episode.saveToDB()

            cur_provider.show = show
            season_strings = cur_provider._get_season_search_strings(episode)  # pylint: disable=protected-access
            episode_strings = cur_provider._get_episode_search_strings(episode)  # pylint: disable=protected-access

            fail = False
            cur_string = ''
            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!" % cur_provider.name
                    print cur_string
                    fail = True
                    continue

            if fail:
                continue

            try:
                assert season_strings == cur_data["s_strings"]
                assert episode_strings == cur_data["e_strings"]
            except AssertionError:
                print " %s is using a wrong string format!" % cur_provider.name
                print cur_string
                continue

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

            # print search_strings

            if not cur_provider.public:
                continue

            items = cur_provider.search(search_strings)  # pylint: disable=protected-access
            if not items:
                print "No results from cur_provider?"
                continue

            title, url = cur_provider._get_title_and_url(items[0])  # pylint: disable=protected-access
            for word in show.name.split(" "):
                if not word.lower() in title.lower():
                    print "Show cur_name not in title: %s. URL: %s" % (title,
                                                                       url)
                    continue

            if not url:
                print "url is empty"
                continue

            quality = cur_provider.get_quality(items[0])
            size = cur_provider._get_size(items[0])  # pylint: disable=protected-access

            if not show.quality & quality:
                print "Quality not in common.ANY, %r %s" % (quality, size)
                continue
Exemplo n.º 41
0
 def test_init_indexerid(self):
     show = TVShow(1, 1, 'en')
     self.assertEqual(show.indexerid, 1)
Exemplo n.º 42
0
    def test(self):
        show = TVShow(1, int(curData[b"tvdbid"]))
        show.name = name
        show.quality = c.ANY | c.Quality.UNKNOWN | c.Quality.RAWHDTV
        show.saveToDB()
        sickbeard.showList.append(show)

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

            # We arent updating scene numbers, so fake it here
            episode.scene_season = curData[b"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[b"s_strings"])
                assert (episode_strings == curData[b"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._doSearch(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 common.ANY, %r" % quality)
                continue
Exemplo n.º 43
0
    def run(self):

        ShowQueueItem.run(self)

        logger.log(u'Starting to add show ' + self.showDir)
        # make sure the Indexer IDs are valid
        try:

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

            logger.log(u'' + str(sickbeard.indexerApi(self.indexer).name) +
                       ': ' + repr(lINDEXER_API_PARMS))

            t = sickbeard.indexerApi(
                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:
                logger.log(
                    u'Show in ' + self.showDir + ' has no name on ' +
                    str(sickbeard.indexerApi(self.indexer).name) +
                    ', probably the wrong language used to search with.',
                    logger.ERROR)
                ui.notifications.error(
                    'Unable to add show',
                    'Show in ' + self.showDir + ' has no name on ' +
                    str(sickbeard.indexerApi(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:
                logger.log(
                    u'Show ' + str(s['seriesname']) + ' is on ' +
                    str(sickbeard.indexerApi(self.indexer).name) +
                    ' but contains no season/episode data.', logger.ERROR)
                ui.notifications.error(
                    'Unable to add show', 'Show ' + str(s['seriesname']) +
                    ' is on ' + str(sickbeard.indexerApi(self.indexer).name) +
                    ' but contains no season/episode data.')
                self._finishEarly()
                return
        except Exception as e:
            logger.log(
                u'Unable to find show ID:' + str(self.indexer_id) +
                ' on Indexer: ' + str(sickbeard.indexerApi(self.indexer).name),
                logger.ERROR)
            ui.notifications.error(
                'Unable to add show',
                'Unable to look up the show in ' + self.showDir + ' on ' +
                str(sickbeard.indexerApi(self.indexer).name) + ' using ID ' +
                str(self.indexer_id) +
                ', not using the NFO. Delete .nfo and try adding manually again.'
            )
            self._finishEarly()
            return

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

            self.show = newShow

            # set up initial values
            self.show.location = self.showDir
            self.show.subtitles = self.subtitles if None is not self.subtitles else sickbeard.SUBTITLES_DEFAULT
            self.show.quality = self.quality if self.quality else sickbeard.QUALITY_DEFAULT
            self.show.flatten_folders = self.flatten_folders if None is not self.flatten_folders else sickbeard.FLATTEN_FOLDERS_DEFAULT
            self.show.anime = self.anime if None is not self.anime else sickbeard.ANIME_DEFAULT
            self.show.scene = self.scene if None is not self.scene else sickbeard.SCENE_DEFAULT
            self.show.paused = self.paused if None is not self.paused else False
            self.show.tag = self.tag if None is not self.tag else 'Show List'

            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 sickbeard.indexer_exception as e:
            logger.log(
                u'Unable to add show due to an error with ' +
                sickbeard.indexerApi(self.indexer).name + ': ' + ex(e),
                logger.ERROR)
            if self.show:
                ui.notifications.error(
                    'Unable to add ' + str(self.show.name) +
                    ' due to an error with ' +
                    sickbeard.indexerApi(self.indexer).name + '')
            else:
                ui.notifications.error(
                    'Unable to add show due to an error with ' +
                    sickbeard.indexerApi(self.indexer).name + '')
            self._finishEarly()
            return

        except exceptions.MultipleShowObjectsException:
            logger.log(
                u'The show in ' + self.showDir +
                ' is already in your show list, skipping', logger.ERROR)
            ui.notifications.error(
                'Show skipped', 'The show in ' + self.showDir +
                ' is already in your show list')
            self._finishEarly()
            return

        except Exception as e:
            logger.log(u'Error trying to add show: ' + ex(e), logger.ERROR)
            logger.log(traceback.format_exc(), logger.DEBUG)
            self._finishEarly()
            raise

        self.show.load_imdb_info()

        try:
            self.show.saveToDB()
        except Exception as e:
            logger.log(u'Error saving the show to the database: ' + ex(e),
                       logger.ERROR)
            logger.log(traceback.format_exc(), logger.DEBUG)
            self._finishEarly()
            raise

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

        try:
            self.show.loadEpisodesFromIndexer()
        except Exception as e:
            logger.log(
                u'Error with ' + sickbeard.indexerApi(self.show.indexer).name +
                ', not creating episode list: ' + ex(e), logger.ERROR)
            logger.log(traceback.format_exc(), logger.DEBUG)

        try:
            self.show.loadEpisodesFromDir()
        except Exception as e:
            logger.log(u'Error searching directory for episodes: ' + ex(e),
                       logger.ERROR)
            logger.log(traceback.format_exc(), logger.DEBUG)

        # if they gave a custom status then change all the eps to it
        my_db = db.DBConnection()
        if self.default_status != SKIPPED:
            logger.log(
                u'Setting all episodes to the specified default status: ' +
                str(self.default_status))
            my_db.action(
                'UPDATE tv_episodes SET status = ? WHERE status = ? AND showid = ? AND season != 0',
                [self.default_status, SKIPPED, self.show.indexerid])

        # if they gave a number to start or number to end as wanted, then change those eps to it
        def get_wanted(db_obj, wanted_max, latest):
            actual = 0
            if wanted_max:
                select_id = 'FROM [tv_episodes] t5 JOIN (SELECT t3.indexerid, t3.status, t3.season*1000000+t3.episode AS t3_se, t2.start_season FROM [tv_episodes] t3'\
                            + ' JOIN (SELECT t1.showid, M%s(t1.season) AS start_season' % ('IN', 'AX')[latest]\
                            + ', MAX(t1.airdate) AS airdate, t1.episode, t1.season*1000000+t1.episode AS se FROM [tv_episodes] t1'\
                            + ' WHERE %s=t1.showid' % self.show.indexerid\
                            + ' AND 0<t1.season AND t1.status NOT IN (%s)) AS t2' % UNAIRED\
                            + ' ON t2.showid=t3.showid AND 0<t3.season AND t2.se>=t3_se ORDER BY t3_se %sSC' % ('A', 'DE')[latest]\
                            + ' %s) as t4' % (' LIMIT %s' % wanted_max, '')[-1 == wanted_max]\
                            + ' ON t4.indexerid=t5.indexerid'\
                            + '%s' % ('', ' AND t4.start_season=t5.season')[-1 == wanted_max]\
                            + ' AND t4.status NOT IN (%s)' % ','.join([str(x) for x in sickbeard.common.Quality.DOWNLOADED + [WANTED]])
                select = 'SELECT t5.indexerid as indexerid, t5.season as season, t5.episode as episode, t5.status as status ' + select_id
                update = 'UPDATE [tv_episodes] SET status=%s WHERE indexerid IN (SELECT t5.indexerid %s)' % (
                    WANTED, select_id)

                wanted_updates = db_obj.select(select)
                db_obj.action(update)
                result = db_obj.select(
                    'SELECT changes() as last FROM [tv_episodes]')
                for cur_result in result:
                    actual = cur_result['last']
                    break

                action_log = 'didn\'t find any episodes that need to be set wanted'
                if actual:
                    action_log = ('updated %s %s episodes > %s' % (
                        (((('%s of %s' % (actual, wanted_max)),
                           ('%s of max %s limited' %
                            (actual, wanted_max)))[10 == wanted_max]),
                         ('max %s available' % actual))[-1 == wanted_max],
                        ('first season', 'latest')[latest], ','.join(
                            [('S%02dE%02d=%d' %
                              (a['season'], a['episode'], a['status']))
                             for a in wanted_updates])))
                logger.log('Get wanted ' + action_log)
            return actual

        items_wanted = get_wanted(my_db,
                                  self.default_wanted_begin,
                                  latest=False)
        items_wanted += get_wanted(my_db,
                                   self.default_wanted_latest,
                                   latest=True)

        msg = ' the specified show into ' + self.showDir
        # if started with WANTED eps then run the backlog
        if WANTED == self.default_status or items_wanted:
            logger.log(
                u'Launching backlog for this show since episodes are WANTED')
            sickbeard.backlogSearchScheduler.action.searchBacklog(
                [self.show])  #@UndefinedVariable
            ui.notifications.message(
                'Show added/search',
                'Adding and searching for episodes of' + msg)
        else:
            ui.notifications.message('Show added', 'Adding' + msg)

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

        self.show.flushEpisodes()

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

            # add show to trakt.tv library
            if sickbeard.TRAKT_SYNC:
                sickbeard.traktCheckerScheduler.action.addShowToTraktLibrary(
                    self.show)

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

        # update internal name cache
        name_cache.buildNameCache(self.show)

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

        self.finish()
Exemplo n.º 44
0
    def setUpClass(cls):
        num_legacy_shows = 3
        num_shows = 3
        num_episodes_per_show = 5
        cls.mydb = db.DBConnection()
        cls.legacy_shows = []
        cls.shows = []

        # Per-show-notifications were originally added for email notifications only.  To add
        # this feature to other notifiers, it was necessary to alter the way text is stored in
        # one of the DB columns.  Therefore, to test properly, we must create some shows that
        # store emails in the old method (legacy method) and then other shows that will use
        # the new method.
        for show_counter in range(100, 100 + num_legacy_shows):
            show = TVShow(1, show_counter)
            show.name = "Show " + str(show_counter)
            show.episodes = []
            for episode_counter in range(0, num_episodes_per_show):
                episode = TVEpisode(show, test.SEASON, episode_counter)
                episode.name = "Episode " + str(episode_counter + 1)
                episode.quality = "SDTV"
                show.episodes.append(episode)
            show.saveToDB()
            cls.legacy_shows.append(show)

        for show_counter in range(200, 200 + num_shows):
            show = TVShow(1, show_counter)
            show.name = "Show " + str(show_counter)
            show.episodes = []
            for episode_counter in range(0, num_episodes_per_show):
                episode = TVEpisode(show, test.SEASON, episode_counter)
                episode.name = "Episode " + str(episode_counter + 1)
                episode.quality = "SDTV"
                show.episodes.append(episode)
            show.saveToDB()
            cls.shows.append(show)
Exemplo n.º 45
0
    def run(self):

        ShowQueueItem.run(self)

        logger.log(u"Starting to add show {0}".format(
            "by ShowDir: {0}".format(self.showDir) if self.
            showDir else "by Indexer Id: {0}".format(self.indexer_id)))
        # make sure the Indexer IDs are valid
        try:

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

            logger.log(u"" + str(sickbeard.indexerApi(self.indexer).name) +
                       ": " + repr(lINDEXER_API_PARMS))

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

            # Let's try to create the show Dir if it's not provided. This way we force the show dir to build build using the
            # Indexers provided series name
            if not self.showDir and self.root_dir:
                show_name = get_showname_from_indexer(self.indexer,
                                                      self.indexer_id,
                                                      self.lang)
                if show_name:
                    self.showDir = ek(os.path.join, self.root_dir,
                                      sanitize_filename(show_name))
                    dir_exists = makeDir(self.showDir)
                    if not dir_exists:
                        logger.log(
                            u"Unable to create the folder {0}, can't add the show"
                            .format(self.showDir))
                        return

                    chmodAsParent(self.showDir)
                else:
                    logger.log(
                        u"Unable to get a show {0}, can't add the show".format(
                            self.showDir))
                    return

            # 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:
                logger.log(
                    u"Show in {} has no name on {}, probably searched with the wrong language."
                    .format(self.showDir,
                            sickbeard.indexerApi(self.indexer).name),
                    logger.ERROR)

                ui.notifications.error(
                    "Unable to add show",
                    "Show in " + self.showDir + " has no name on " +
                    str(sickbeard.indexerApi(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:
                logger.log(u"Show " + str(s['seriesname']) + " is on " +
                           str(sickbeard.indexerApi(self.indexer).name) +
                           " but contains no season/episode data.")
                ui.notifications.error(
                    "Unable to add show", "Show " + str(s['seriesname']) +
                    " is on " + str(sickbeard.indexerApi(self.indexer).name) +
                    " but contains no season/episode data.")
                self._finishEarly()
                return
        except Exception as e:
            logger.log(
                u"%s Error while loading information from indexer %s. Error: %r"
                % (self.indexer_id, sickbeard.indexerApi(
                    self.indexer).name, ex(e)), logger.ERROR)
            # logger.log(u"Show name with ID %s doesn't exist on %s anymore. If you are using trakt, it will be removed from your TRAKT watchlist. If you are adding manually, try removing the nfo and adding again" %
            #            (self.indexer_id, sickbeard.indexerApi(self.indexer).name), logger.WARNING)

            ui.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, sickbeard.indexerApi(
                    self.indexer).name, self.indexer_id))

            if sickbeard.USE_TRAKT:

                trakt_id = sickbeard.indexerApi(
                    self.indexer).config['trakt_id']
                trakt_api = TraktAPI(sickbeard.SSL_VERIFY,
                                     sickbeard.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')

            self._finishEarly()
            return

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

            self.show = newShow

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

            # set up default new/missing episode status
            logger.log(
                u"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 sickbeard.indexer_exception as e:
            logger.log(
                u"Unable to add show due to an error with " +
                sickbeard.indexerApi(self.indexer).name + ": " + ex(e),
                logger.ERROR)
            if self.show:
                ui.notifications.error(
                    "Unable to add " + str(self.show.name) +
                    " due to an error with " +
                    sickbeard.indexerApi(self.indexer).name + "")
            else:
                ui.notifications.error(
                    "Unable to add show due to an error with " +
                    sickbeard.indexerApi(self.indexer).name + "")
            self._finishEarly()
            return

        except MultipleShowObjectsException:
            logger.log(
                u"The show in " + self.showDir +
                " is already in your show list, skipping", logger.WARNING)
            ui.notifications.error(
                'Show skipped', "The show in " + self.showDir +
                " is already in your show list")
            self._finishEarly()
            return

        except Exception as e:
            logger.log(u"Error trying to add show: " + ex(e), logger.ERROR)
            logger.log(traceback.format_exc(), logger.DEBUG)
            self._finishEarly()
            raise

        logger.log(u"Retrieving show info from IMDb", logger.DEBUG)
        try:
            self.show.loadIMDbInfo()
        except imdb_exceptions.IMDbError as e:
            logger.log(u" Something wrong on IMDb api: " + ex(e),
                       logger.WARNING)
        except Exception as e:
            logger.log(u"Error loading IMDb info: " + ex(e), logger.ERROR)

        try:
            self.show.saveToDB()
        except Exception as e:
            logger.log(u"Error saving the show to the database: " + ex(e),
                       logger.ERROR)
            logger.log(traceback.format_exc(), logger.DEBUG)
            self._finishEarly()
            raise

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

        try:
            self.show.loadEpisodesFromIndexer()
        except Exception as e:
            logger.log(
                u"Error with " + sickbeard.indexerApi(self.show.indexer).name +
                ", not creating episode list: " + ex(e), logger.ERROR)
            logger.log(traceback.format_exc(), logger.DEBUG)

        # update internal name cache
        name_cache.buildNameCache(self.show)

        try:
            self.show.loadEpisodesFromDir()
        except Exception as e:
            logger.log(u"Error searching dir for episodes: " + ex(e),
                       logger.ERROR)
            logger.log(traceback.format_exc(), logger.DEBUG)

        # 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:
            logger.log(
                u"Launching backlog for this show since its episodes are WANTED"
            )
            sickbeard.backlogSearchScheduler.action.searchBacklog([self.show])

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

        self.show.flushEpisodes()

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

            # add show to trakt.tv library
            if sickbeard.TRAKT_SYNC:
                sickbeard.traktCheckerScheduler.action.addShowToTraktLibrary(
                    self.show)

            if sickbeard.TRAKT_SYNC_WATCHLIST:
                logger.log(u"update watchlist")
                notifiers.trakt_notifier.update_watchlist(show_obj=self.show)

        # Load XEM data to DB for show
        sickbeard.scene_numbering.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 sickbeard.scene_numbering.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()
Exemplo n.º 46
0
    def test_change_indexerid(self):
        show_obj = TVShow(1, 1, 'en')
        show_obj.name = 'show name'
        show_obj.tvrname = 'show name'
        show_obj.network = 'cbs'
        show_obj.genre = 'crime'
        show_obj.runtime = 40
        show_obj.status = '5'
        show_obj.airs = 'monday'
        show_obj.startyear = 1987

        show_obj.save_to_db()
        show_obj.load_from_db()

        show_obj.prodid = 2
        show_obj.save_to_db()
        show_obj.load_from_db()

        self.assertEqual(show_obj.prodid, 2)
Exemplo n.º 47
0
class QueueItemAdd(ShowQueueItem):
    def __init__(self, indexer, indexer_id, showDir, default_status, quality,
                 flatten_folders, lang, subtitles, refresh):

        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.refresh = refresh

        self.show = None

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

    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 == 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 == None:
            return True
        return False

    isLoading = property(_isLoading)

    def execute(self):

        ShowQueueItem.execute(self)

        logger.log(u"Starting to add show " + self.showDir)
        # make sure the indexer ids are valid
        try:

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

            logger.log(u"" + sickbeard.indexerApi(self.indexer).name + ": " +
                       repr(lINDEXER_API_PARMS))

            t = sickbeard.indexerApi(
                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:
                logger.log(
                    u"Show in " + self.showDir + " has no name on " +
                    sickbeard.indexerApi(self.indexer).name +
                    ", probably the wrong language used to search with.",
                    logger.ERROR)
                ui.notifications.error(
                    "Unable to add show",
                    "Show in " + self.showDir + " has no name on " +
                    sickbeard.indexerApi(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:
                logger.log(
                    u"Show " + str(s['seriesname']) + " is on " +
                    sickbeard.indexerApi(self.indexer).name +
                    " but contains no season/episode data.", logger.ERROR)
                ui.notifications.error(
                    "Unable to add show", "Show " + str(s['seriesname']) +
                    " is on " + sickbeard.indexerApi(self.indexer).name +
                    " but contains no season/episode data.")
                self._finishEarly()
                return
        except Exception, e:
            logger.log(
                u"Unable to find show ID:" + str(self.indexer_id) +
                " on Indexer: " + sickbeard.indexerApi(self.indexer).name,
                logger.ERROR)
            ui.notifications.error(
                "Unable to add show",
                "Unable to look up the show in " + self.showDir + " on " +
                sickbeard.indexerApi(self.indexer).name + " using ID " +
                str(self.indexer_id) +
                ", not using the NFO. Delete .nfo and try adding manually again."
            )
            self._finishEarly()
            return

        try:
            # clear the name cache
            name_cache.clearCache()

            newShow = TVShow(self.indexer, self.indexer_id, self.lang)
            newShow.loadFromIndexer()

            self.show = newShow

            # set up initial values
            self.show.location = self.showDir
            self.show.subtitles = self.subtitles if self.subtitles != None else sickbeard.SUBTITLES_DEFAULT
            self.show.quality = self.quality if self.quality else sickbeard.QUALITY_DEFAULT
            self.show.flatten_folders = self.flatten_folders if self.flatten_folders != None else sickbeard.FLATTEN_FOLDERS_DEFAULT
            self.show.paused = False

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

        except sickbeard.indexer_exception, e:
            logger.log(
                u"Unable to add show due to an error with " +
                sickbeard.indexerApi(self.indexer).name + ": " + ex(e),
                logger.ERROR)
            if self.show:
                ui.notifications.error(
                    "Unable to add " + str(self.show.name) +
                    " due to an error with " +
                    sickbeard.indexerApi(self.indexer).name + "")
            else:
                ui.notifications.error(
                    "Unable to add show due to an error with " +
                    sickbeard.indexerApi(self.indexer).name + "")
            self._finishEarly()
            return
Exemplo n.º 48
0
 def test_init_indexerid(self):
     show_obj = TVShow(1, 1, 'en')
     self.assertEqual(show_obj.prodid, 1)
Exemplo n.º 49
0
    def test_change_indexerid(self):
        """
        test change indexer id
        """
        show = TVShow(1, 1, "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()

        show.indexerid = 2
        show.saveToDB()
        show.loadFromDB()

        self.assertEqual(show.indexerid, 2)
Exemplo n.º 50
0
 def test_getEpisode(self):
     show_obj = TVShow(1, 1, 'en')
     show_obj.name = 'show name'
     show_obj.tvrname = 'show name'
     show_obj.network = 'cbs'
     show_obj.genre = 'crime'
     show_obj.runtime = 40
     show_obj.status = '5'
     show_obj.airs = 'monday'
     show_obj.startyear = 1987
     sickbeard.showList = [show_obj]
     sickbeard.showDict = {show_obj.sid_int: show_obj}
     show_obj.sxe_ep_obj[1] = {}
     show_obj.sxe_ep_obj[1][1] = TVEpisode(show_obj, 1, 1, '16)')
     show_obj.sxe_ep_obj[1][1].dirty = False
     show_obj.sxe_ep_obj[1][1].name = None
     self.assertEqual(show_obj.sxe_ep_obj[1][1].dirty, False)
     self.assertEqual(
         show_obj.sxe_ep_obj[1][1]._format_pattern(
             '%SN - %Sx%0E - %EN - %QN'),
         'show name - 1x01 - tba - Unknown')
     show_obj.sxe_ep_obj[1][1].dirty = False
     show_obj.sxe_ep_obj[1][1].name = 'ep name'
     self.assertEqual(show_obj.sxe_ep_obj[1][1].dirty, True)
     self.assertEqual(
         show_obj.sxe_ep_obj[1][1]._format_pattern(
             '%SN - %Sx%0E - %EN - %QN'),
         'show name - 1x01 - ep name - Unknown')
Exemplo n.º 51
0
 def test_set_name(self):
     show = TVShow(1, 1, 'en')
     show.name = 'newName'
     show.saveToDB()
     show.loadFromDB(skipNFO=True)
     self.assertEqual(show.name, 'newName')
Exemplo n.º 52
0
 def test_getEpisode(self):
     show = TVShow(1, 1, "en")
     show.name = "show name"
     show.tvrname = "show name"
     show.network = "cbs"
     show.genre = "crime"
     show.runtime = 40
     show.status = "5"
     show.airs = "monday"
     show.startyear = 1987
     show.saveToDB()
     sickbeard.showList = [show]
Exemplo n.º 53
0
 def test_get_episode():
     """
     Test get episodes
     """
     show = TVShow(1, 1, "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()
     sickbeard.showList = [show]
Exemplo n.º 54
0
    def run(self):  # pylint: disable=too-many-branches, too-many-statements, too-many-return-statements

        ShowQueueItem.run(self)

        if self.showDir:
            assert isinstance(self.showDir, unicode)

        logger.log('Starting to add show {0}'.format(
            'by ShowDir: {0}'.format(self.showDir) if self.
            showDir else 'by Indexer Id: {0}'.format(self.indexer_id)))
        # make sure the Indexer IDs are valid
        try:

            lINDEXER_API_PARMS = sickbeard.indexerApi(
                self.indexer).api_params.copy()
            lINDEXER_API_PARMS[
                'language'] = self.lang or sickbeard.INDEXER_DEFAULT_LANGUAGE

            logger.log('{0}: {1!r}'.format(
                sickbeard.indexerApi(self.indexer).name, lINDEXER_API_PARMS))

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

            # Let's try to create the show Dir if it's not provided. This way we force the show dir to build build using the
            # Indexers provided series name
            if self.root_dir and not self.showDir:
                show_name = get_showname_from_indexer(self.indexer,
                                                      self.indexer_id,
                                                      self.lang)
                if not show_name:
                    logger.log(
                        'Unable to get a show {0}, can\'t add the show'.format(
                            self.showDir))
                    return

                self.showDir = ek(os.path.join, self.root_dir,
                                  sanitize_filename(show_name))

                dir_exists = makeDir(self.showDir)
                if not dir_exists:
                    logger.log(
                        'Unable to create the folder {0}, can\'t add the show'.
                        format(self.showDir))
                    return

                chmodAsParent(self.showDir)

            # 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:
                error_string = 'Show in {0} has no name on {1}, probably searched with the wrong language. Delete .nfo and add manually in the correct language.'.format(
                    self.showDir,
                    sickbeard.indexerApi(self.indexer).name)

                logger.log(error_string, logger.WARNING)
                ui.notifications.error('Unable to add show', error_string)

                self._finishEarly()
                return

            # if the show has no episodes/seasons
            if not s:
                error_string = 'Show {0} is on {1} but contains no season/episode data.'.format(
                    s[b'seriesname'],
                    sickbeard.indexerApi(self.indexer).name)

                logger.log(error_string)
                ui.notifications.error('Unable to add show', error_string)

                self._finishEarly()
                return
        except Exception as error:
            error_string = 'Unable to look up the show in {0} on {1} using ID {2}, not using the NFO. Delete .nfo and try adding manually again.'.format(
                self.showDir,
                sickbeard.indexerApi(self.indexer).name, self.indexer_id)

            logger.log('{0}: {1}'.format(error_string, error), logger.ERROR)
            ui.notifications.error('Unable to add show', error_string)

            if sickbeard.USE_TRAKT:
                trakt_id = sickbeard.indexerApi(
                    self.indexer).config[b'trakt_id']
                trakt_api = TraktAPI(sickbeard.SSL_VERIFY,
                                     sickbeard.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:
            try:
                newShow = TVShow(self.indexer, self.indexer_id, self.lang)
            except MultipleShowObjectsException as error:
                # If we have the show in our list, but the location is wrong, lets fix it and refresh!
                existing_show = Show.find(sickbeard.showList, self.indexer_id)
                if existing_show and not ek(os.path.isdir,
                                            existing_show._location):  # pylint: disable=protected-access
                    newShow = existing_show
                else:
                    raise error

            newShow.loadFromIndexer()

            self.show = newShow

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

            # set up default new/missing episode status
            logger.log(
                'Setting all episodes to the specified default status: {0}'.
                format(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 sickbeard.indexer_exception as error:
            error_string = 'Unable to add {0} due to an error with {1}'.format(
                self.show.name if self.show else 'show',
                sickbeard.indexerApi(self.indexer).name)

            logger.log('{0}: {1}'.format(error_string, error), logger.ERROR)
            ui.notifications.error('Unable to add show', error_string)

            self._finishEarly()
            return

        except MultipleShowObjectsException:
            error_string = 'The show in {0} is already in your show list, skipping'.format(
                self.showDir)
            logger.log(error_string, logger.WARNING)
            ui.notifications.error('Show skipped', error_string)

            self._finishEarly()
            return

        except Exception as error:
            logger.log('Error trying to add show: {0}'.format(error),
                       logger.ERROR)
            logger.log(traceback.format_exc(), logger.DEBUG)
            self._finishEarly()
            raise

        logger.log('Retrieving show info from IMDb', logger.DEBUG)
        try:
            self.show.loadIMDbInfo()
        except imdb_exceptions.IMDbError as error:
            logger.log(' Something wrong on IMDb api: {0}'.format(error),
                       logger.WARNING)
        except Exception as error:
            logger.log('Error loading IMDb info: {0}'.format(error),
                       logger.ERROR)

        try:
            self.show.saveToDB()
        except Exception as error:
            logger.log(
                'Error saving the show to the database: {0}'.format(error),
                logger.ERROR)
            logger.log(traceback.format_exc(), logger.DEBUG)
            self._finishEarly()
            raise

        # add it to the show list
        if not Show.find(sickbeard.showList, self.indexer_id):
            sickbeard.showList.append(self.show)

        try:
            self.show.loadEpisodesFromIndexer()
        except Exception as error:
            logger.log(
                'Error with {0}, not creating episode list: {1}'.format(
                    sickbeard.indexerApi(self.show.indexer).name, error),
                logger.ERROR)
            logger.log(traceback.format_exc(), logger.DEBUG)

        # update internal name cache
        name_cache.buildNameCache(self.show)

        try:
            self.show.loadEpisodesFromDir()
        except Exception as error:
            logger.log('Error searching dir for episodes: {0}'.format(error),
                       logger.ERROR)
            logger.log(traceback.format_exc(), logger.DEBUG)

        # 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:
            logger.log(
                'Launching backlog for this show since its episodes are WANTED'
            )
            sickbeard.backlogSearchScheduler.action.searchBacklog([self.show])

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

        self.show.flushEpisodes()

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

            # add show to trakt.tv library
            if sickbeard.TRAKT_SYNC:
                sickbeard.traktCheckerScheduler.action.addShowToTraktLibrary(
                    self.show)

            if sickbeard.TRAKT_SYNC_WATCHLIST:
                logger.log('update watchlist')
                notifiers.trakt_notifier.update_watchlist(show_obj=self.show)

        # Load XEM data to DB for show
        sickbeard.scene_numbering.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 sickbeard.scene_numbering.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()
Exemplo n.º 55
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 = generic_queue.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 == 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 == None:
            return True
        return False

    isLoading = property(_isLoading)

    def run(self):

        ShowQueueItem.run(self)

        logger.log(u"Starting to add show " + self.showDir)
        # make sure the Indexer IDs are valid
        try:

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

            logger.log(u"" + str(sickbeard.indexerApi(self.indexer).name) +
                       ": " + repr(lINDEXER_API_PARMS))

            t = sickbeard.indexerApi(
                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:
                logger.log(
                    u"Show in " + self.showDir + " has no name on " +
                    str(sickbeard.indexerApi(self.indexer).name) +
                    ", probably the wrong language used to search with.",
                    logger.ERROR)
                ui.notifications.error(
                    "Unable to add show",
                    "Show in " + self.showDir + " has no name on " +
                    str(sickbeard.indexerApi(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:
                logger.log(
                    u"Show " + str(s['seriesname']) + " is on " +
                    str(sickbeard.indexerApi(self.indexer).name) +
                    " but contains no season/episode data.", logger.ERROR)
                ui.notifications.error(
                    "Unable to add show", "Show " + str(s['seriesname']) +
                    " is on " + str(sickbeard.indexerApi(self.indexer).name) +
                    " but contains no season/episode data.")
                self._finishEarly()
                return
        except Exception, e:
            logger.log(
                u"Show name with ID %s doesn't exist on %s anymore. If you are using trakt, it will be removed from your TRAKT watchlist. If you are adding manually, try removing the nfo and adding again"
                % (self.indexer_id, sickbeard.indexerApi(self.indexer).name),
                logger.ERROR)

            ui.notifications.error(
                "Unable to add show",
                "Unable to look up the show in " + self.showDir + " on " +
                str(sickbeard.indexerApi(self.indexer).name) + " using ID " +
                str(self.indexer_id) +
                ", not using the NFO. Delete .nfo and try adding manually again."
            )

            if sickbeard.USE_TRAKT:

                trakt_id = sickbeard.indexerApi(
                    self.indexer).config['trakt_id']
                trakt_api = TraktAPI(sickbeard.SSL_VERIFY,
                                     sickbeard.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')

            self._finishEarly()
            return

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

            self.show = newShow

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

            # set up default new/missing episode status
            logger.log(
                u"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 sickbeard.indexer_exception, e:
            logger.log(
                u"Unable to add show due to an error with " +
                sickbeard.indexerApi(self.indexer).name + ": " + ex(e),
                logger.ERROR)
            if self.show:
                ui.notifications.error(
                    "Unable to add " + str(self.show.name) +
                    " due to an error with " +
                    sickbeard.indexerApi(self.indexer).name + "")
            else:
                ui.notifications.error(
                    "Unable to add show due to an error with " +
                    sickbeard.indexerApi(self.indexer).name + "")
            self._finishEarly()
            return
Exemplo n.º 56
0
class QueueItemAdd(ShowQueueItem):
    def __init__(self, indexer, indexer_id, showDir, default_status, quality,
                 flatten_folders, lang, subtitles, anime, scene, paused,
                 blacklist, whitelist):

        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

        if sickbeard.TRAKT_USE_ROLLING_DOWNLOAD and sickbeard.USE_TRAKT:
            self.paused = sickbeard.TRAKT_ROLLING_ADD_PAUSED

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

        self.show = None

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

    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 == 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 == None:
            return True
        return False

    isLoading = property(_isLoading)

    def run(self):

        ShowQueueItem.run(self)

        logger.log(u"Starting to add show " + self.showDir)
        # make sure the Indexer IDs are valid
        try:

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

            logger.log(u"" + str(sickbeard.indexerApi(self.indexer).name) +
                       ": " + repr(lINDEXER_API_PARMS))

            t = sickbeard.indexerApi(
                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:
                logger.log(
                    u"Show in " + self.showDir + " has no name on " +
                    str(sickbeard.indexerApi(self.indexer).name) +
                    ", probably the wrong language used to search with.",
                    logger.ERROR)
                ui.notifications.error(
                    "Unable to add show",
                    "Show in " + self.showDir + " has no name on " +
                    str(sickbeard.indexerApi(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:
                logger.log(
                    u"Show " + str(s['seriesname']) + " is on " +
                    str(sickbeard.indexerApi(self.indexer).name) +
                    " but contains no season/episode data.", logger.ERROR)
                ui.notifications.error(
                    "Unable to add show", "Show " + str(s['seriesname']) +
                    " is on " + str(sickbeard.indexerApi(self.indexer).name) +
                    " but contains no season/episode data.")
                self._finishEarly()
                return
        except Exception, e:
            logger.log(
                u"Unable to find show ID:" + str(self.indexer_id) +
                " on Indexer: " + str(sickbeard.indexerApi(self.indexer).name),
                logger.ERROR)
            ui.notifications.error(
                "Unable to add show",
                "Unable to look up the show in " + self.showDir + " on " +
                str(sickbeard.indexerApi(self.indexer).name) + " using ID " +
                str(self.indexer_id) +
                ", not using the NFO. Delete .nfo and try adding manually again."
            )
            self._finishEarly()
            return

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

            self.show = newShow

            # set up initial values
            self.show.location = self.showDir
            self.show.subtitles = self.subtitles if self.subtitles != None else sickbeard.SUBTITLES_DEFAULT
            self.show.quality = self.quality if self.quality else sickbeard.QUALITY_DEFAULT
            self.show.flatten_folders = self.flatten_folders if self.flatten_folders != None else sickbeard.FLATTEN_FOLDERS_DEFAULT
            self.show.anime = self.anime if self.anime != None else sickbeard.ANIME_DEFAULT
            self.show.scene = self.scene if self.scene != None else sickbeard.SCENE_DEFAULT
            self.show.paused = self.paused if self.paused != None else False

            # set up default new/missing episode status
            logger.log(
                u"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 sickbeard.indexer_exception, e:
            logger.log(
                u"Unable to add show due to an error with " +
                sickbeard.indexerApi(self.indexer).name + ": " + ex(e),
                logger.ERROR)
            if self.show:
                ui.notifications.error(
                    "Unable to add " + str(self.show.name) +
                    " due to an error with " +
                    sickbeard.indexerApi(self.indexer).name + "")
            else:
                ui.notifications.error(
                    "Unable to add show due to an error with " +
                    sickbeard.indexerApi(self.indexer).name + "")
            self._finishEarly()
            return