Example #1
0
    def addEpisodesToTraktWatchList(self):
        trakt_data = []

        sickrage.app.log.debug(
            "WATCHLIST::ADD::START - Look for Episodes to Add to Trakt Watchlist"
        )

        for s in sickrage.app.showlist:
            for e in sickrage.app.main_db.get_many('tv_episodes', s.indexerid):
                if not e[
                        'status'] in Quality.SNATCHED + Quality.SNATCHED_PROPER + [
                            UNKNOWN
                        ] + [WANTED]:
                    continue
                trakt_id = IndexerApi(s.indexer).trakt_id
                if self._checkInList(trakt_id, str(e["showid"]), e["season"],
                                     e["episode"]):
                    sickrage.app.log.debug(
                        "Adding Episode %s S%02dE%02d to watchlist" %
                        (s.name, e["season"], e["episode"]))
                    trakt_data.append((e["showid"], s.indexer, s.name,
                                       s.startyear, e["season"], e["episode"]))

        if len(trakt_data):
            try:
                data = self.trakt_bulk_data_generate(trakt_data)
                srTraktAPI()["sync/watchlist"].add(data)
                self._getEpisodeWatchlist()
            except Exception as e:
                sickrage.app.log.warning(
                    "Could not connect to Trakt service. Error %s" % e)

        sickrage.app.log.debug(
            "WATCHLIST::ADD::FINISH - Look for Episodes to Add to Trakt Watchlist"
        )
Example #2
0
    def addShowToTraktWatchList(self):
        trakt_data = []

        sickrage.app.log.debug("SHOW_WATCHLIST::ADD::START - Look for Shows to Add to Trakt Watchlist")

        for show in sickrage.app.showlist:
            if not self._checkInList(IndexerApi(show.indexer).trakt_id, str(show.indexerid), 0, 0, 'Show'):
                sickrage.app.log.debug(
                    "Adding Show: Indexer %s %s - %s to Watchlist" % (
                        IndexerApi(show.indexer).trakt_id, str(show.indexerid), show.name))

                show_el = {'title': show.name,
                           'year': show.startyear,
                           'ids': {IndexerApi(show.indexer).trakt_id: show.indexerid}}

                trakt_data.append(show_el)

        if len(trakt_data):
            try:
                data = {'shows': trakt_data}
                srTraktAPI()["sync/watchlist"].add(data)
                self._getShowWatchlist()
            except Exception as e:
                sickrage.app.log.warning("Could not connect to Trakt service. Error: %s" % e)

        sickrage.app.log.debug("SHOW_WATCHLIST::ADD::FINISH - Look for Shows to Add to Trakt Watchlist")
Example #3
0
    def addShowToTraktLibrary(self, show_obj):
        """
        Sends a request to trakt indicating that the given show and all its episodes is part of our library.

        show_obj: The TVShow object to add to trakt
        """
        data = {}

        if not self.findShowMatch(show_obj.indexer, show_obj.indexerid):
            # URL parameters
            data = {
                'shows': [
                    {
                        'title': show_obj.name,
                        'year': show_obj.startyear,
                        'ids': {IndexerApi(show_obj.indexer).trakt_id: show_obj.indexerid}
                    }
                ]
            }

        if len(data):
            sickrage.app.log.debug("Adding %s to tv library" % show_obj.name)

            try:
                srTraktAPI()["sync/collection"].add(data)
            except Exception as e:
                sickrage.app.log.warning(
                    "Could not connect to Trakt service. Aborting adding show %s to Trakt library. Error: %s" % (
                        show_obj.name, repr(e)))
                return
Example #4
0
    def addShowToTraktLibrary(self, show_obj):
        """
        Sends a request to trakt indicating that the given show and all its episodes is part of our library.

        show_obj: The TVShow object to add to trakt
        """
        data = {}

        if not self.findShowMatch(show_obj.indexer, show_obj.indexerid):
            # URL parameters
            data = {
                'shows': [
                    {
                        'title': show_obj.name,
                        'year': show_obj.startyear,
                        'ids': {IndexerApi(show_obj.indexer).trakt_id: show_obj.indexerid}
                    }
                ]
            }

        if len(data):
            sickrage.app.log.debug("Adding %s to tv library" % show_obj.name)

            try:
                srTraktAPI()["sync/collection"].add(data)
            except Exception as e:
                sickrage.app.log.warning(
                    "Could not connect to Trakt service. Aborting adding show %s to Trakt library. Error: %s" % (
                        show_obj.name, repr(e)))
                return
Example #5
0
    def addShowToTraktWatchList(self):
        trakt_data = []

        sickrage.app.log.debug("SHOW_WATCHLIST::ADD::START - Look for Shows to Add to Trakt Watchlist")

        for show in sickrage.app.showlist:
            if not self._checkInList(IndexerApi(show.indexer).trakt_id, str(show.indexerid), 0, 0, 'Show'):
                sickrage.app.log.debug(
                    "Adding Show: Indexer %s %s - %s to Watchlist" % (
                        IndexerApi(show.indexer).trakt_id, str(show.indexerid), show.name))

                show_el = {'title': show.name,
                           'year': show.startyear,
                           'ids': {IndexerApi(show.indexer).trakt_id: show.indexerid}}

                trakt_data.append(show_el)

        if len(trakt_data):
            try:
                data = {'shows': trakt_data}
                srTraktAPI()["sync/watchlist"].add(data)
                self._getShowWatchlist()
            except Exception as e:
                sickrage.app.log.warning("Could not connect to Trakt service. Error: %s" % e)

        sickrage.app.log.debug("SHOW_WATCHLIST::ADD::FINISH - Look for Shows to Add to Trakt Watchlist")
Example #6
0
    def removeEpisodesFromTraktWatchList(self):
        trakt_data = []

        sickrage.app.log.debug(
            "WATCHLIST::REMOVE::START - Look for Episodes to Remove from Trakt Watchlist"
        )

        for s in sickrage.app.showlist:
            for e in sickrage.app.main_db.get_many('tv_episodes', s.indexerid):
                trakt_id = IndexerApi(s.indexer).trakt_id
                if self._checkInList(trakt_id, str(e["showid"]), e["season"],
                                     e["episode"]):
                    sickrage.app.log.debug(
                        "Removing Episode %s S%02dE%02d from watchlist" %
                        (s.name, e["season"], e["episode"]))
                    trakt_data.append((e["showid"], s.indexer, s.name,
                                       s.startyear, e["season"], e["episode"]))

        if len(trakt_data):
            try:
                data = self.trakt_bulk_data_generate(trakt_data)
                srTraktAPI()["sync/watchlist"].remove(data)
                self._getEpisodeWatchlist()
            except Exception as e:
                sickrage.app.log.warning(
                    "Could not connect to Trakt service. Error: %s" % e)

        sickrage.app.log.debug(
            "WATCHLIST::REMOVE::FINISH - Look for Episodes to Remove from Trakt Watchlist"
        )
Example #7
0
    def removeEpisodesFromTraktCollection(self):
        trakt_data = []

        sickrage.app.log.debug(
            "COLLECTION::REMOVE::START - Look for Episodes to Remove From Trakt Collection"
        )

        for s in sickrage.app.showlist:
            for e in sickrage.app.main_db.get_many('tv_episodes', s.indexerid):
                if e["location"]: continue
                trakt_id = IndexerApi(s.indexer).trakt_id
                if self._checkInList(trakt_id, str(e["showid"]), e["season"],
                                     e["episode"], 'Collection'):
                    sickrage.app.log.debug(
                        "Removing Episode %s S%02dE%02d from collection" %
                        (s.name, e["season"], e["episode"]))
                    trakt_data.append((e["showid"], s.indexer, s.name,
                                       s.startyear, e["season"], e["episode"]))

        if len(trakt_data):
            try:
                srTraktAPI()["sync/collection"].remove(
                    self.trakt_bulk_data_generate(trakt_data))
                self._getShowCollection()
            except Exception as e:
                sickrage.app.log.warning(
                    "Could not connect to Trakt service. Error: %s" % e)

        sickrage.app.log.debug(
            "COLLECTION::REMOVE::FINISH - Look for Episodes to Remove From Trakt Collection"
        )
Example #8
0
    def removeShowFromTraktLibrary(self, show_obj):
        if self.findShowMatch(show_obj.indexer, show_obj.indexerid):
            # URL parameters
            data = {
                'shows': [
                    {
                        'title': show_obj.name,
                        'year': show_obj.startyear,
                        'ids': {IndexerApi(show_obj.indexer).trakt_id: show_obj.indexerid}
                    }
                ]
            }

            sickrage.app.log.debug("Removing %s from tv library" % show_obj.name)

            try:
                srTraktAPI()["sync/collection"].remove(data)
            except Exception as e:
                sickrage.app.log.warning(
                    "Could not connect to Trakt service. Aborting removing show %s from Trakt library. Error: %s" % (
                        show_obj.name, repr(e)))
Example #9
0
 def _getShowWatchlist(self):
     """
     Get Watchlist and parse once into addressable structure
     """
     try:
         sickrage.app.log.debug("Getting Show Watchlist")
         self.ShowWatchlist = srTraktAPI()["sync/watchlist"].shows() or {}
     except Exception as e:
         sickrage.app.log.warning(
             "Could not connect to trakt service, cannot download Show Watchlist: %s" % repr(e))
         return False
     return True
Example #10
0
 def _getShowWatchlist(self):
     """
     Get Watchlist and parse once into addressable structure
     """
     try:
         sickrage.app.log.debug("Getting Show Watchlist")
         self.ShowWatchlist = srTraktAPI()["sync/watchlist"].shows() or {}
     except Exception as e:
         sickrage.app.log.warning(
             "Could not connect to trakt service, cannot download Show Watchlist: %s" % repr(e))
         return False
     return True
Example #11
0
    def addEpisodesToTraktCollection(self):
        trakt_data = []

        sickrage.app.log.debug("COLLECTION::SYNC::START - Look for Episodes to Add to Trakt Collection")

        for s in sickrage.app.showlist:
            for e in sickrage.app.main_db.get_many('tv_episodes', s.indexerid):
                trakt_id = IndexerApi(s.indexer).trakt_id
                if not self._checkInList(trakt_id, str(e["showid"]), e["season"], e["episode"], 'Collection'):
                    sickrage.app.log.debug(
                        "Adding Episode %s S%02dE%02d to collection" % (s.name, e["season"], e["episode"]))
                    trakt_data.append((e["showid"], s.indexer, s.name, s.startyear, e["season"], e["episode"]))

        if len(trakt_data):
            try:
                srTraktAPI()["sync/collection"].add(self.trakt_bulk_data_generate(trakt_data))
                self._getShowCollection()
            except Exception as e:
                sickrage.app.log.warning("Could not connect to Trakt service. Error: %s" % e)

        sickrage.app.log.debug("COLLECTION::ADD::FINISH - Look for Episodes to Add to Trakt Collection")
Example #12
0
    def removeShowFromTraktLibrary(self, show_obj):
        if self.findShowMatch(show_obj.indexer, show_obj.indexerid):
            # URL parameters
            data = {
                'shows': [
                    {
                        'title': show_obj.name,
                        'year': show_obj.startyear,
                        'ids': {IndexerApi(show_obj.indexer).trakt_id: show_obj.indexerid}
                    }
                ]
            }

            sickrage.app.log.debug("Removing %s from tv library" % show_obj.name)

            try:
                srTraktAPI()["sync/collection"].remove(data)
            except Exception as e:
                sickrage.app.log.warning(
                    "Could not connect to Trakt service. Aborting removing show %s from Trakt library. Error: %s" % (
                        show_obj.name, repr(e)))
Example #13
0
    def addEpisodesToTraktCollection(self):
        trakt_data = []

        sickrage.app.log.debug(
            "COLLECTION::SYNC::START - Look for Episodes to Add to Trakt Collection"
        )

        for s in [
                x['doc']
                for x in sickrage.app.main_db.db.all('tv_shows', with_doc=True)
        ]:
            for e in [
                    e['doc'] for e in sickrage.app.main_db.db.get_many(
                        'tv_episodes', s['indexer_id'], with_doc=True)
            ]:

                trakt_id = IndexerApi(s["indexer"]).trakt_id
                if not self._checkInList(trakt_id, str(
                        e["showid"]), e["season"], e["episode"], 'Collection'):
                    sickrage.app.log.debug(
                        "Adding Episode %s S%02dE%02d to collection" %
                        (s["show_name"], e["season"], e["episode"]))
                    trakt_data.append(
                        (e["showid"], s["indexer"], s["show_name"],
                         s["startyear"], e["season"], e["episode"]))

        if len(trakt_data):
            try:
                srTraktAPI()["sync/collection"].add(
                    self.trakt_bulk_data_generate(trakt_data))
                self._getShowCollection()
            except Exception as e:
                sickrage.app.log.warning(
                    "Could not connect to Trakt service. Error: %s" % e)

        sickrage.app.log.debug(
            "COLLECTION::ADD::FINISH - Look for Episodes to Add to Trakt Collection"
        )
Example #14
0
    def addEpisodesToTraktWatchList(self):
        trakt_data = []

        sickrage.app.log.debug("WATCHLIST::ADD::START - Look for Episodes to Add to Trakt Watchlist")

        for s in sickrage.app.showlist:
            for e in sickrage.app.main_db.get_many('tv_episodes', s.indexerid):
                if not e['status'] in Quality.SNATCHED + Quality.SNATCHED_PROPER + [UNKNOWN] + [WANTED]: continue
                trakt_id = IndexerApi(s.indexer).trakt_id
                if self._checkInList(trakt_id, str(e["showid"]), e["season"], e["episode"]):
                    sickrage.app.log.debug(
                        "Adding Episode %s S%02dE%02d to watchlist" % (s.name, e["season"], e["episode"]))
                    trakt_data.append((e["showid"], s.indexer, s.name, s.startyear, e["season"], e["episode"]))

        if len(trakt_data):
            try:
                data = self.trakt_bulk_data_generate(trakt_data)
                srTraktAPI()["sync/watchlist"].add(data)
                self._getEpisodeWatchlist()
            except Exception as e:
                sickrage.app.log.warning("Could not connect to Trakt service. Error %s" % e)

        sickrage.app.log.debug("WATCHLIST::ADD::FINISH - Look for Episodes to Add to Trakt Watchlist")
Example #15
0
    def removeEpisodesFromTraktWatchList(self):
        trakt_data = []

        sickrage.app.log.debug(
            "WATCHLIST::REMOVE::START - Look for Episodes to Remove from Trakt Watchlist")

        for s in sickrage.app.showlist:
            for e in sickrage.app.main_db.get_many('tv_episodes', s.indexerid):
                trakt_id = IndexerApi(s.indexer).trakt_id
                if self._checkInList(trakt_id, str(e["showid"]), e["season"], e["episode"]):
                    sickrage.app.log.debug(
                        "Removing Episode %s S%02dE%02d from watchlist" % (s.name, e["season"], e["episode"]))
                    trakt_data.append((e["showid"], s.indexer, s.name, s.startyear, e["season"], e["episode"]))

        if len(trakt_data):
            try:
                data = self.trakt_bulk_data_generate(trakt_data)
                srTraktAPI()["sync/watchlist"].remove(data)
                self._getEpisodeWatchlist()
            except Exception as e:
                sickrage.app.log.warning("Could not connect to Trakt service. Error: %s" % e)

        sickrage.app.log.debug(
            "WATCHLIST::REMOVE::FINISH - Look for Episodes to Remove from Trakt Watchlist")
Example #16
0
    def findShowMatch(self, indexer, indexerid):
        traktShow = None

        try:
            library = srTraktAPI()["sync/collection"].shows() or {}
            if not library:
                sickrage.app.log.debug("No shows found in your library, aborting library update")
                return

            traktShow = [x for __, x in library.items() if
                         int(indexerid) == int(x.ids[IndexerApi(indexer).trakt_id])]
        except Exception as e:
            sickrage.app.log.warning(
                "Could not connect to Trakt service. Aborting library check. Error: %s" % repr(e))

        return traktShow
Example #17
0
    def findShowMatch(self, indexer, indexerid):
        traktShow = None

        try:
            library = srTraktAPI()["sync/collection"].shows() or {}
            if not library:
                sickrage.app.log.debug("No shows found in your library, aborting library update")
                return

            traktShow = [x for __, x in library.items() if
                         int(indexerid) == int(x.ids[IndexerApi(indexer).trakt_id])]
        except Exception as e:
            sickrage.app.log.warning(
                "Could not connect to Trakt service. Aborting library check. Error: %s" % repr(e))

        return traktShow
Example #18
0
    def get_show(self, name):
        show = None
        show_id = 0
        fromCache = False

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

        try:
            # check cache for show
            cache = sickrage.app.name_cache.get(name)
            if cache:
                fromCache = True
                show_id = cache

            # try indexers
            if not show_id and self.tryIndexers:
                try:
                    show_id1 = int(IndexerApi().searchForShowID(
                        full_sanitizeSceneName(name))[2])
                    show_id2 = int(srTraktAPI()['search'].query(
                        full_sanitizeSceneName(name), 'show')[0].ids['tvdb'])
                    show_id = (show_id, show_id1)[show_id1 == show_id2]
                except Exception:
                    pass

            # try scene exceptions
            if not show_id:
                try:
                    show_id = get_scene_exception_by_name(name)[0]
                except Exception:
                    pass

            # create show object
            show = findCertainShow(sickrage.app.showlist,
                                   int(show_id)) if show_id else None

            # add show to cache
            if show and not fromCache:
                sickrage.app.name_cache.put(name, show.indexerid)
        except Exception as e:
            sickrage.app.log.debug(
                "Error when attempting to find show: %s in SiCKRAGE. Error: %r "
                % (name, repr(e)))

        return show, show_id or 0
Example #19
0
    def removeShowFromSickRage(self):
        sickrage.app.log.debug("SHOW_SICKRAGE::REMOVE::START - Look for Shows to remove from SiCKRAGE")

        for show in sickrage.app.showlist:
            if show.status == "Ended":
                try:
                    progress = srTraktAPI()["shows"].get(show.imdbid)
                except Exception as e:
                    sickrage.app.log.warning(
                        "Could not connect to Trakt service. Aborting removing show %s from SiCKRAGE. Error: %s" % (
                            show.name, repr(e)))
                    return

                if progress.status in ['canceled', 'ended']:
                    sickrage.app.show_queue.removeShow(show, full=True)
                    sickrage.app.log.debug("Show: %s has been removed from SiCKRAGE" % show.name)

        sickrage.app.log.debug("SHOW_SICKRAGE::REMOVE::FINISH - Trakt Show Watchlist")
Example #20
0
    def removeShowFromSickRage(self):
        sickrage.app.log.debug("SHOW_SICKRAGE::REMOVE::START - Look for Shows to remove from SiCKRAGE")

        for show in sickrage.app.showlist:
            if show.status == "Ended":
                try:
                    progress = srTraktAPI()["shows"].get(show.imdbid)
                except Exception as e:
                    sickrage.app.log.warning(
                        "Could not connect to Trakt service. Aborting removing show %s from SiCKRAGE. Error: %s" % (
                            show.name, repr(e)))
                    return

                if progress.status in ['canceled', 'ended']:
                    sickrage.app.show_queue.removeShow(show, full=True)
                    sickrage.app.log.debug("Show: %s has been removed from SiCKRAGE" % show.name)

        sickrage.app.log.debug("SHOW_SICKRAGE::REMOVE::FINISH - Trakt Show Watchlist")
Example #21
0
    def test_notify(self, username, blacklist_name=None):
        """
        Sends a test notification to trakt with the given authentication info and returns a boolean
        representing success.

        api: The api string to use
        username: The username to use
        blacklist_name: slug of trakt list used to hide not interested show

        Returns: True if the request succeeded, False otherwise
        """
        try:
            if blacklist_name and blacklist_name is not None:
                if not srTraktAPI()["users/me/lists/{list}".format(list=blacklist_name)].get():
                    return "Trakt blacklist doesn't exists"
            return "Test notice sent successfully to Trakt"
        except Exception as e:
            sickrage.app.log.warning("Could not connect to Trakt service: %s" % e)
            return "Test notice failed to Trakt: %s" % e
Example #22
0
    def test_notify(self, username, blacklist_name=None):
        """
        Sends a test notification to trakt with the given authentication info and returns a boolean
        representing success.

        api: The api string to use
        username: The username to use
        blacklist_name: slug of trakt list used to hide not interested show

        Returns: True if the request succeeded, False otherwise
        """
        try:
            if blacklist_name and blacklist_name is not None:
                if not srTraktAPI()["users/me/lists/{list}".format(list=blacklist_name)].get():
                    return "Trakt blacklist doesn't exists"
            return "Test notice sent successfully to Trakt"
        except Exception as e:
            sickrage.srCore.srLogger.warning("Could not connect to Trakt service: %s" % e)
            return "Test notice failed to Trakt: %s" % e
Example #23
0
    def get_show(self, name):
        show = None
        show_id = 0
        fromCache = False

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

        try:
            # check cache for show
            cache = sickrage.app.name_cache.get(name)
            if cache:
                fromCache = True
                show_id = cache

            # try indexers
            if not show_id and self.tryIndexers:
                try:
                    show_id1 = int(IndexerApi().searchForShowID(full_sanitizeSceneName(name))[2])
                    show_id2 = int(srTraktAPI()['search'].query(full_sanitizeSceneName(name), 'show')[0].ids['tvdb'])
                    show_id = (show_id, show_id1)[show_id1 == show_id2]
                except Exception:
                    pass

            # try scene exceptions
            if not show_id:
                try:
                    show_id = get_scene_exception_by_name(name)[0]
                except Exception:
                    pass

            # create show object
            show = findCertainShow(sickrage.app.showlist, int(show_id)) if show_id else None

            # add show to cache
            if show and not fromCache:
                sickrage.app.name_cache.put(name, show.indexerid)
        except Exception as e:
            sickrage.app.log.debug(
                "Error when attempting to find show: %s in SiCKRAGE. Error: %r " % (name, repr(e)))

        return show, show_id or 0
Example #24
0
    def update_library(self, ep_obj):
        """
        Sends a request to trakt indicating that the given episode is part of our library.

        ep_obj: The TVEpisode object to add to trakt
        """

        if sickrage.app.config.use_trakt:
            try:
                # URL parameters
                data = {
                    'shows': [{
                        'title': ep_obj.show.name,
                        'year': ep_obj.show.startyear,
                        'ids': {
                            IndexerApi(ep_obj.show.indexer).trakt_id:
                            ep_obj.show.indexerid
                        },
                    }]
                }

                if sickrage.app.config.trakt_sync_watchlist:
                    if sickrage.app.config.trakt_remove_serieslist:
                        srTraktAPI()["sync/watchlist"].remove(data)

                # Add Season and Episode + Related Episodes
                data['shows'][0]['seasons'] = [{
                    'number': ep_obj.season,
                    'episodes': []
                }]

                for relEp_Obj in [ep_obj] + ep_obj.relatedEps:
                    data['shows'][0]['seasons'][0]['episodes'].append(
                        {'number': relEp_Obj.episode})

                if sickrage.app.config.trakt_sync_watchlist:
                    if sickrage.app.config.trakt_remove_watchlist:
                        srTraktAPI()["sync/watchlist"].remove(data)

                # update library
                srTraktAPI()["sync/collection"].add(data)

            except Exception as e:
                sickrage.app.log.warning(
                    "Could not connect to Trakt service: %s" % e)
Example #25
0
    def update_library(self, ep_obj):
        """
        Sends a request to trakt indicating that the given episode is part of our library.

        ep_obj: The TVEpisode object to add to trakt
        """

        if sickrage.app.config.use_trakt:
            try:
                # URL parameters
                data = {
                    'shows': [
                        {
                            'title': ep_obj.show.name,
                            'year': ep_obj.show.startyear,
                            'ids': {IndexerApi(ep_obj.show.indexer).trakt_id: ep_obj.show.indexerid},
                        }
                    ]
                }

                if sickrage.app.config.trakt_sync_watchlist:
                    if sickrage.app.config.trakt_remove_serieslist:
                        srTraktAPI()["sync/watchlist"].remove(data)

                # Add Season and Episode + Related Episodes
                data['shows'][0]['seasons'] = [{'number': ep_obj.season, 'episodes': []}]

                for relEp_Obj in [ep_obj] + ep_obj.relatedEps:
                    data['shows'][0]['seasons'][0]['episodes'].append({'number': relEp_Obj.episode})

                if sickrage.app.config.trakt_sync_watchlist:
                    if sickrage.app.config.trakt_remove_watchlist:
                        srTraktAPI()["sync/watchlist"].remove(data)

                # update library
                srTraktAPI()["sync/collection"].add(data)

            except Exception as e:
                sickrage.app.log.warning("Could not connect to Trakt service: %s" % e)
Example #26
0
    def run(self):
        start_time = time.time()

        sickrage.app.log.info(
            "Started adding show {} from show dir: {}".format(
                self.show_name, self.showDir))

        index_name = IndexerApi(self.indexer).name

        # make sure the Indexer IDs are valid
        try:

            lINDEXER_API_PARMS = IndexerApi(self.indexer).api_params.copy()
            lINDEXER_API_PARMS['cache'] = False
            lINDEXER_API_PARMS[
                'language'] = self.lang or sickrage.app.config.indexer_default_language

            sickrage.app.log.info("{}: {}".format(index_name,
                                                  repr(lINDEXER_API_PARMS)))

            t = IndexerApi(self.indexer).indexer(**lINDEXER_API_PARMS)

            try:
                s = t[self.indexer_id]
            except indexer_error:
                s = None

            if not s:
                return self._finish_early()

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

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

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

            if sickrage.app.config.use_trakt:
                title = self.showDir.split("/")[-1]

                data = {
                    'shows': [{
                        'title': title,
                        'ids': {
                            IndexerApi(self.indexer).trakt_id: self.indexer_id
                        }
                    }]
                }

                srTraktAPI()["sync/watchlist"].remove(data)

            return self._finish_early()

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

            self.show.load_from_indexer()

            # set up initial values
            self.show.location = self.showDir
            self.show.subtitles = self.subtitles or sickrage.app.config.subtitles_default
            self.show.subtitles_sr_metadata = self.subtitles_sr_metadata
            self.show.quality = self.quality or sickrage.app.config.quality_default
            self.show.flatten_folders = self.flatten_folders or sickrage.app.config.flatten_folders_default
            self.show.anime = self.anime or sickrage.app.config.anime_default
            self.show.scene = self.scene or sickrage.app.config.scene_default
            self.show.skip_downloaded = self.skip_downloaded or sickrage.app.config.skip_downloaded_default
            self.show.paused = self.paused or False

            # set up default new/missing episode status
            sickrage.app.log.info(
                "Setting all current episodes to the specified default status: "
                + str(self.default_status))

            self.show.default_ep_status = self.default_status

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

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

        except indexer_exception as e:
            sickrage.app.log.warning(
                "Unable to add show due to an error with " +
                IndexerApi(self.indexer).name + ": {}".format(e))
            if self.show:
                sickrage.app.alerts.error(
                    _("Unable to add ") + str(self.show.name) +
                    _(" due to an error with ") +
                    IndexerApi(self.indexer).name + "")
            else:
                sickrage.app.alerts.error(
                    _("Unable to add show due to an error with ") +
                    IndexerApi(self.indexer).name + "")
            return self._finish_early()

        except MultipleShowObjectsException:
            sickrage.app.log.warning("The show in " + self.showDir +
                                     " is already in your show list, skipping")
            sickrage.app.alerts.error(
                _('Show skipped'),
                _("The show in ") + self.showDir +
                _(" is already in your show list"))
            return self._finish_early()

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

        try:
            sickrage.app.log.debug(
                "Attempting to retrieve show info from IMDb")
            self.show.load_imdb_info()
        except Exception as e:
            sickrage.app.log.error("Error loading IMDb info: {}".format(e))

        try:
            self.show.save_to_db()
        except Exception as e:
            sickrage.app.log.error(
                "Error saving the show to the database: {}".format(e))
            sickrage.app.log.debug(traceback.format_exc())
            raise self._finish_early()

        # add it to the show list
        if not findCertainShow(self.indexer_id):
            sickrage.app.showlist.append(self.show)

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

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

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

        self.show.write_metadata(force=True)
        self.show.populate_cache()

        if sickrage.app.config.use_trakt:
            # if there are specific episodes that need to be added by trakt
            sickrage.app.trakt_searcher.manageNewShow(self.show)

            # add show to trakt.tv library
            if sickrage.app.config.trakt_sync:
                sickrage.app.trakt_searcher.addShowToTraktLibrary(self.show)

            if sickrage.app.config.trakt_sync_watchlist:
                sickrage.app.log.info("update watchlist")
                sickrage.app.notifier_providers['trakt'].update_watchlist(
                    show_obj=self.show)

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

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

        self.show.default_ep_status = self.default_status_after

        self.show.save_to_db()

        sickrage.app.name_cache.build(self.show)

        sickrage.app.quicksearch_cache.add_show(self.show.indexerid)

        self.finish()

        sickrage.app.log.info(
            "Finished adding show {} in {}s from show dir: {}".format(
                self.show_name, round(time.time() - start_time, 2),
                self.showDir))
Example #27
0
    def update_watchlist(self, show_obj=None, s=None, e=None, data_show=None, data_episode=None, update="add"):

        """
        Sends a request to trakt indicating that the given episode is part of our library.

        show_obj: The TVShow object to add to trakt
        s: season number
        e: episode number
        data_show: structured object of shows traktv type
        data_episode: structured object of episodes traktv type
        update: type o action add or remove
        """

        if sickrage.app.config.use_trakt:
            data = {}
            try:
                # URL parameters
                if show_obj is not None:
                    data = {
                        'shows': [
                            {
                                'title': show_obj.name,
                                'year': show_obj.startyear,
                                'ids': {IndexerApi(show_obj.indexer).trakt_id: show_obj.indexerid},
                            }
                        ]
                    }

                elif data_show is not None:
                    data.update(data_show)
                else:
                    sickrage.app.log.warning(
                        "there's a coding problem contact developer. It's needed to be provided at lest one of the two: data_show or show_obj")
                    return False

                if data_episode is not None:
                    data['shows'][0].update(data_episode)

                elif s is not None:
                    # traktv URL parameters
                    season = {
                        'season': [
                            {
                                'number': s,
                            }
                        ]
                    }

                    if e is not None:
                        # traktv URL parameters
                        episode = {
                            'episodes': [
                                {
                                    'number': e
                                }
                            ]
                        }

                        season['season'][0].update(episode)

                    data['shows'][0].update(season)

                trakt_url = "sync/watchlist"
                if update == "remove":
                    srTraktAPI()[trakt_url].remove(data)
                else:
                    srTraktAPI()[trakt_url].add(data)

            except Exception as e:
                sickrage.app.log.warning("Could not connect to Trakt service: %s" % e)
                return False

        return True
Example #28
0
    def run(self):
        sickrage.app.log.info("Started adding show {} from show dir: {}".format(self.show_name, self.showDir))

        index_name = IndexerApi(self.indexer).name

        # make sure the Indexer IDs are valid
        try:

            lINDEXER_API_PARMS = IndexerApi(self.indexer).api_params.copy()
            lINDEXER_API_PARMS['cache'] = False
            lINDEXER_API_PARMS['language'] = self.lang or sickrage.app.config.indexer_default_language

            sickrage.app.log.info("{}: {}".format(index_name, repr(lINDEXER_API_PARMS)))

            t = IndexerApi(self.indexer).indexer(**lINDEXER_API_PARMS)
            s = t[self.indexer_id]
            if not s: return self._finishEarly()

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

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

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

            if sickrage.app.config.use_trakt:
                title = self.showDir.split("/")[-1]

                data = {
                    'shows': [
                        {
                            'title': title,
                            'ids': {IndexerApi(self.indexer).trakt_id: self.indexer_id}
                        }
                    ]
                }

                srTraktAPI()["sync/watchlist"].remove(data)

            return self._finishEarly()

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

            self.show.loadFromIndexer()

            # set up initial values
            self.show.location = self.showDir
            self.show.subtitles = self.subtitles or sickrage.app.config.subtitles_default
            self.show.subtitles_sr_metadata = self.subtitles_sr_metadata
            self.show.quality = self.quality or sickrage.app.config.quality_default
            self.show.flatten_folders = self.flatten_folders or sickrage.app.config.flatten_folders_default
            self.show.anime = self.anime or sickrage.app.config.anime_default
            self.show.scene = self.scene or sickrage.app.config.scene_default
            self.show.archive_firstmatch = self.archive or sickrage.app.config.archive_default
            self.show.paused = self.paused or False

            # set up default new/missing episode status
            sickrage.app.log.info(
                "Setting all current episodes to the specified default status: " + str(self.default_status))

            self.show.default_ep_status = self.default_status

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

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

        except indexer_exception as e:
            sickrage.app.log.error(
                "Unable to add show due to an error with " + IndexerApi(
                    self.indexer).name + ": {}".format(e.message))
            if self.show:
                sickrage.app.alerts.error(
                    _("Unable to add ") + str(self.show.name) + _(" due to an error with ") + IndexerApi(
                        self.indexer).name + "")
            else:
                sickrage.app.alerts.error(
                    _("Unable to add show due to an error with ") + IndexerApi(self.indexer).name + "")
            return self._finishEarly()

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

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

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

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

        # add it to the show list
        if not findCertainShow(sickrage.app.showlist, self.indexer_id): sickrage.app.showlist.append(self.show)

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

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

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

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

        if sickrage.app.config.use_trakt:
            # if there are specific episodes that need to be added by trakt
            sickrage.app.trakt_searcher.manageNewShow(self.show)

            # add show to trakt.tv library
            if sickrage.app.config.trakt_sync:
                sickrage.app.trakt_searcher.addShowToTraktLibrary(self.show)

            if sickrage.app.config.trakt_sync_watchlist:
                sickrage.app.log.info("update watchlist")
                sickrage.app.notifier_providers['trakt'].update_watchlist(show_obj=self.show)

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

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

        self.show.default_ep_status = self.default_status_after

        self.show.saveToDB()

        sickrage.app.name_cache.build(self.show)

        self.finish()

        sickrage.app.log.info(
            "Finished adding show {} in {}s from show dir: {}".format(self.show_name,
                                                                      round(time.time() - self.startTime, 2),
                                                                      self.showDir))
Example #29
0
    def run(self):
        sickrage.srCore.srLogger.info(
            "Started adding show {} from show dir: {}".format(
                self.show_name, self.showDir))

        index_name = srIndexerApi(self.indexer).name

        # make sure the Indexer IDs are valid
        try:

            lINDEXER_API_PARMS = srIndexerApi(self.indexer).api_params.copy()
            lINDEXER_API_PARMS['cache'] = False
            lINDEXER_API_PARMS[
                'language'] = self.lang or sickrage.srCore.srConfig.INDEXER_DEFAULT_LANGUAGE

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

            t = srIndexerApi(self.indexer).indexer(**lINDEXER_API_PARMS)
            s = t[self.indexer_id]
            if not s: return self._finishEarly()

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

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

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

            if sickrage.srCore.srConfig.USE_TRAKT:
                title = self.showDir.split("/")[-1]

                data = {
                    'shows': [{
                        'title': title,
                        'ids': {
                            srIndexerApi(self.indexer).trakt_id:
                            self.indexer_id
                        }
                    }]
                }

                srTraktAPI()["sync/watchlist"].remove(data)

            return self._finishEarly()

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

            self.show.loadFromIndexer()

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

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

            self.show.default_ep_status = self.default_status

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

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

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

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

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

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

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

        # add it to the show list
        if not findCertainShow(sickrage.srCore.SHOWLIST, self.indexer_id):
            sickrage.srCore.SHOWLIST.append(self.show)

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

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

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

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

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

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

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

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

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

        self.show.default_ep_status = self.default_status_after

        self.show.saveToDB()

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

        self.finish()

        sickrage.srCore.srLogger.info(
            "Finished adding show {} in {}s from show dir: {}".format(
                self.show_name, round(time.time() - self.startTime, 2),
                self.showDir))
Example #30
0
 def indexer_lookup(term):
     show_id1 = int(IndexerApi().searchForShowID(
         full_sanitizeSceneName(term))[2])
     show_id2 = int(srTraktAPI()['search'].query(
         full_sanitizeSceneName(term), 'show')[0].ids['tvdb'])
     return (None, show_id1)[show_id1 == show_id2]
Example #31
0
    def update_watchlist(self,
                         show_obj=None,
                         s=None,
                         e=None,
                         data_show=None,
                         data_episode=None,
                         update="add"):
        """
        Sends a request to trakt indicating that the given episode is part of our library.

        show_obj: The TVShow object to add to trakt
        s: season number
        e: episode number
        data_show: structured object of shows traktv type
        data_episode: structured object of episodes traktv type
        update: type o action add or remove
        """

        if sickrage.app.config.use_trakt:
            data = {}
            try:
                # URL parameters
                if show_obj is not None:
                    data = {
                        'shows': [{
                            'title': show_obj.name,
                            'year': show_obj.startyear,
                            'ids': {
                                IndexerApi(show_obj.indexer).trakt_id:
                                show_obj.indexerid
                            },
                        }]
                    }

                elif data_show is not None:
                    data.update(data_show)
                else:
                    sickrage.app.log.warning(
                        "there's a coding problem contact developer. It's needed to be provided at lest one of the two: data_show or show_obj"
                    )
                    return False

                if data_episode is not None:
                    data['shows'][0].update(data_episode)

                elif s is not None:
                    # traktv URL parameters
                    season = {
                        'season': [{
                            'number': s,
                        }]
                    }

                    if e is not None:
                        # traktv URL parameters
                        episode = {'episodes': [{'number': e}]}

                        season['season'][0].update(episode)

                    data['shows'][0].update(season)

                trakt_url = "sync/watchlist"
                if update == "remove":
                    srTraktAPI()[trakt_url].remove(data)
                else:
                    srTraktAPI()[trakt_url].add(data)

            except Exception as e:
                sickrage.app.log.warning(
                    "Could not connect to Trakt service: %s" % e)
                return False

        return True