Ejemplo n.º 1
0
    def addShowToBlacklist(self, seriesid):
        # URL parameters
        data = {'shows': [{'ids': {'tvdb': seriesid}}]}

        trakt_settings = {
            'trakt_api_secret': app.TRAKT_API_SECRET,
            'trakt_api_key': app.TRAKT_API_KEY,
            'trakt_access_token': app.TRAKT_ACCESS_TOKEN,
            'trakt_refresh_token': app.TRAKT_REFRESH_TOKEN
        }

        show_name = get_showname_from_indexer(INDEXER_TVDBV2, seriesid)
        try:
            trakt_api = TraktApi(timeout=app.TRAKT_TIMEOUT,
                                 ssl_verify=app.SSL_VERIFY,
                                 **trakt_settings)
            trakt_api.request('users/{0}/lists/{1}/items'.format(
                app.TRAKT_USERNAME, app.TRAKT_BLACKLIST_NAME),
                              data,
                              method='POST')
            ui.notifications.message(
                'Success!', "Added show '{0}' to blacklist".format(show_name))
        except Exception as e:
            ui.notifications.error(
                'Error!',
                "Unable to add show '{0}' to blacklist. Check logs.".format(
                    show_name))
            logger.log(
                "Error while adding show '{0}' to trakt blacklist: {1}".format(
                    show_name, e), logger.WARNING)
Ejemplo n.º 2
0
    def test_notify(username, blacklist_name=None):
        """Send a test notification to trakt with the given authentication info and returns a boolean.

        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:
            trakt_settings = {
                'trakt_api_secret': app.TRAKT_API_SECRET,
                'trakt_api_key': app.TRAKT_API_KEY,
                'trakt_access_token': app.TRAKT_ACCESS_TOKEN,
                'trakt_refresh_token': app.TRAKT_REFRESH_TOKEN
            }

            trakt_api = TraktApi(app.SSL_VERIFY, app.TRAKT_TIMEOUT,
                                 **trakt_settings)
            trakt_api.validate_account()
            if blacklist_name and blacklist_name is not None:
                trakt_lists = trakt_api.request('users/' + username + '/lists')
                found = False
                for trakt_list in trakt_lists:
                    if trakt_list['ids']['slug'] == blacklist_name:
                        return 'Test notice sent successfully to Trakt'
                if not found:
                    return "Trakt blacklist doesn't exists"
            else:
                return 'Test notice sent successfully to Trakt'
        except (TokenExpiredException, TraktException, AuthException) as error:
            log.warning('Unable to test TRAKT: {0}', error.message)
            return 'Test notice failed to Trakt: {0}'.format(error.message)
Ejemplo n.º 3
0
    def test_notify(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:
            trakt_settings = {'trakt_api_secret': app.TRAKT_API_SECRET,
                              'trakt_api_key': app.TRAKT_API_KEY,
                              'trakt_access_token': app.TRAKT_ACCESS_TOKEN}

            trakt_api = TraktApi(app.SSL_VERIFY, app.TRAKT_TIMEOUT, **trakt_settings)
            trakt_api.validate_account()
            if blacklist_name and blacklist_name is not None:
                trakt_lists = trakt_api.request('users/' + username + '/lists')
                found = False
                for trakt_list in trakt_lists:
                    if trakt_list['ids']['slug'] == blacklist_name:
                        return 'Test notice sent successfully to Trakt'
                if not found:
                    return "Trakt blacklist doesn't exists"
            else:
                return 'Test notice sent successfully to Trakt'
        except (TraktException, AuthException, ServerBusy) as trakt_ex:
            logger.log('Could not connect to Trakt service: {0}'.format(ex(trakt_ex)), logger.WARNING)
            return 'Test notice failed to Trakt: {0}'.format(ex(trakt_ex))
Ejemplo n.º 4
0
def get_trakt_externals(externals):
    """Small trakt api wrapper, to request trakt externals using multiple external id's.

    :param externals: Dictionary of key/value pairs with external id's.
    """
    def trakt_request(api, trakt_url):
        """Perform the request and handle possible token refresh."""
        try:
            trakt_result = api.request(trakt_url) or []
            if api.access_token_refreshed:
                app.TRAKT_ACCESS_TOKEN = api.access_token
                app.TRAKT_REFRESH_TOKEN = api.refresh_token
                app.instance.save_config()
        except (AuthException, TraktException, TokenExpiredException) as e:
            log.info(u'Could not use Trakt to enrich with externals: {0}',
                     e.message or e)
            return []
        else:
            return trakt_result

    trakt_settings = {
        'trakt_api_key': app.TRAKT_API_KEY,
        'trakt_api_secret': app.TRAKT_API_SECRET,
        'trakt_access_token': app.TRAKT_ACCESS_TOKEN,
        'trakt_refresh_token': app.TRAKT_REFRESH_TOKEN
    }
    trakt_api = TraktApi(app.SSL_VERIFY, app.TRAKT_TIMEOUT, **trakt_settings)

    id_lookup = '/search/{external_key}/{external_value}?type=show'
    trakt_mapping = {
        'tvdb_id': 'tvdb',
        'imdb_id': 'imdb',
        'tmdb_id': 'tmdb',
        'trakt_id': 'trakt'
    }
    trakt_mapping_rev = {v: k for k, v in trakt_mapping.items()}

    for external_key in externals:
        if not trakt_mapping.get(external_key) or not externals[external_key]:
            continue

        url = id_lookup.format(external_key=trakt_mapping[external_key],
                               external_value=externals[external_key])
        log.debug(
            u'Looking for externals using Trakt and {indexer} id {number}', {
                'indexer': trakt_mapping[external_key],
                'number': externals[external_key],
            })
        result = trakt_request(trakt_api, url)
        if result and len(result) and result[0].get(
                'show') and result[0]['show'].get('ids'):
            ids = {
                trakt_mapping_rev[k]: v
                for k, v in result[0]['show'].get('ids').items()
                if v and trakt_mapping_rev.get(k)
            }
            return ids
    return {}
Ejemplo n.º 5
0
 def __init__(self):
     trakt_settings = {'trakt_api_key': app.TRAKT_API_KEY,
                       'trakt_api_secret': app.TRAKT_API_SECRET,
                       'trakt_access_token': app.TRAKT_ACCESS_TOKEN}
     self.trakt_api = TraktApi(app.SSL_VERIFY, app.TRAKT_TIMEOUT, **trakt_settings)
     self.todoWanted = []
     self.show_watchlist = {}
     self.episode_watchlist = {}
     self.collection_list = {}
     self.amActive = False
Ejemplo n.º 6
0
    def update_library(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
        """

        trakt_id = app.indexerApi(ep_obj.show.indexer).config['trakt_id']
        # Create a trakt settings dict
        trakt_settings = {'trakt_api_secret': app.TRAKT_API_SECRET,
                          'trakt_api_key': app.TRAKT_API_KEY,
                          'trakt_access_token': app.TRAKT_ACCESS_TOKEN}

        trakt_api = TraktApi(app.SSL_VERIFY, app.TRAKT_TIMEOUT, **trakt_settings)

        if app.USE_TRAKT:
            try:
                # URL parameters
                data = {
                    'shows': [
                        {
                            'title': ep_obj.show.name,
                            'year': ep_obj.show.startyear,
                            'ids': {},
                        }
                    ]
                }

                if trakt_id == 'tvdb_id':
                    data['shows'][0]['ids']['tvdb'] = ep_obj.show.indexerid
                else:
                    data['shows'][0]['ids']['tvrage'] = ep_obj.show.indexerid

                if app.TRAKT_SYNC_WATCHLIST:
                    if app.TRAKT_REMOVE_SERIESLIST:
                        trakt_api.request('sync/watchlist/remove', data, method='POST')

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

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

                if app.TRAKT_SYNC_WATCHLIST:
                    if app.TRAKT_REMOVE_WATCHLIST:
                        trakt_api.request('sync/watchlist/remove', data, method='POST')

                # update library
                trakt_api.request('sync/collection', data, method='POST')

            except (TraktException, AuthException, ServerBusy) as trakt_ex:
                logger.log('Could not connect to Trakt service: {0}'.format(ex(trakt_ex)), logger.WARNING)
Ejemplo n.º 7
0
    def fetch_popular_shows(self, page_url=None, trakt_list=None):
        """Get a list of popular shows from different Trakt lists based on a provided trakt_list.

        :param page_url: the page url opened to the base api url, for retreiving a specific list
        :param trakt_list: a description of the trakt list
        :return: A list of RecommendedShow objects, an empty list of none returned
        :throw: ``Exception`` if an Exception is thrown not handled by the libtrats exceptions
        """
        trending_shows = []
        removed_from_medusa = []

        # Create a trakt settings dict
        trakt_settings = {
            'trakt_api_secret': app.TRAKT_API_SECRET,
            'trakt_api_key': app.TRAKT_API_KEY,
            'trakt_access_token': app.TRAKT_ACCESS_TOKEN,
            'trakt_refresh_token': app.TRAKT_REFRESH_TOKEN
        }

        trakt_api = TraktApi(timeout=app.TRAKT_TIMEOUT,
                             ssl_verify=app.SSL_VERIFY,
                             **trakt_settings)

        try:
            not_liked_show = ''
            if app.TRAKT_ACCESS_TOKEN != '':
                library_shows = self.fetch_and_refresh_token(trakt_api, 'sync/watched/shows?extended=noseasons') + \
                    self.fetch_and_refresh_token(trakt_api, 'sync/collection/shows?extended=full')

                medusa_shows = [
                    show.indexerid for show in app.showList if show.indexerid
                ]
                removed_from_medusa = [
                    lshow['show']['ids']['tvdb'] for lshow in library_shows
                    if lshow['show']['ids']['tvdb'] not in medusa_shows
                ]

                if app.TRAKT_BLACKLIST_NAME is not None and app.TRAKT_BLACKLIST_NAME:
                    not_liked_show = trakt_api.request(
                        'users/' + app.TRAKT_USERNAME + '/lists/' +
                        app.TRAKT_BLACKLIST_NAME + '/items') or []
                else:
                    log.debug('Trakt blacklist name is empty')

            if trakt_list not in ['recommended', 'newshow', 'newseason']:
                limit_show = '?limit=' + text_type(100 +
                                                   len(not_liked_show)) + '&'
            else:
                limit_show = '?'

            series = self.fetch_and_refresh_token(
                trakt_api,
                page_url + limit_show + 'extended=full,images') or []

            # Let's trigger a cache cleanup.
            missing_posters.clean()

            for show in series:
                try:
                    if 'show' not in show:
                        show['show'] = show

                    if not_liked_show:
                        if show['show']['ids']['tvdb'] in (
                                s['show']['ids']['tvdb']
                                for s in not_liked_show
                                if s['type'] == 'show'):
                            continue
                    else:
                        trending_shows.append(
                            self._create_recommended_show(
                                show,
                                storage_key=b'trakt_{0}'.format(
                                    show['show']['ids']['trakt'])))

                except MultipleShowObjectsException:
                    continue

            # Update the dogpile index. This will allow us to retrieve all stored dogpile shows from the dbm.
            update_recommended_series_cache_index(
                'trakt', [binary_type(s.series_id) for s in trending_shows])
            blacklist = app.TRAKT_BLACKLIST_NAME not in ''

        except TraktException as error:
            log.warning('Could not connect to Trakt service: {0}', error)
            raise

        return blacklist, trending_shows, removed_from_medusa
Ejemplo n.º 8
0
    def update_library(ep_obj):
        """Send a request to trakt indicating that the given episode is part of our library.

        ep_obj: The Episode object to add to trakt
        """
        # Check if TRAKT supports that indexer
        if not get_trakt_indexer(ep_obj.series.indexer):
            return

        # Create a trakt settings dict
        trakt_settings = {
            'trakt_api_secret': app.TRAKT_API_SECRET,
            'trakt_api_key': app.TRAKT_API_KEY,
            'trakt_access_token': app.TRAKT_ACCESS_TOKEN,
            'trakt_refresh_token': app.TRAKT_REFRESH_TOKEN
        }

        trakt_api = TraktApi(app.SSL_VERIFY, app.TRAKT_TIMEOUT,
                             **trakt_settings)

        if app.USE_TRAKT:
            try:
                # URL parameters
                title = get_title_without_year(ep_obj.series.name,
                                               ep_obj.series.start_year)
                data = {
                    'shows': [{
                        'title': title,
                        'year': ep_obj.series.start_year,
                        'ids': {},
                    }]
                }

                data['shows'][0]['ids'][get_trakt_indexer(
                    ep_obj.series.indexer)] = ep_obj.series.indexerid

                if app.TRAKT_SYNC_WATCHLIST:
                    if app.TRAKT_REMOVE_SERIESLIST:
                        trakt_api.request('sync/watchlist/remove',
                                          data,
                                          method='POST')

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

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

                if app.TRAKT_SYNC_WATCHLIST:
                    if app.TRAKT_REMOVE_WATCHLIST:
                        trakt_api.request('sync/watchlist/remove',
                                          data,
                                          method='POST')

                # update library
                trakt_api.request('sync/collection', data, method='POST')

            except (TokenExpiredException, TraktException,
                    AuthException) as error:
                log.debug('Unable to update Trakt: {0}', error.message)
Ejemplo n.º 9
0
    def update_watchlist(show_obj=None,
                         s=None,
                         e=None,
                         data_show=None,
                         data_episode=None,
                         update='add'):
        """Send a request to trakt indicating that the given episode is part of our library.

        show_obj: The Series object to add to trakt
        s: season number
        e: episode number
        data_show: structured object of shows trakt type
        data_episode: structured object of episodes trakt type
        update: type o action add or remove
        """
        # Check if TRAKT supports that indexer
        if not get_trakt_indexer(show_obj.indexer):
            return

        trakt_settings = {
            'trakt_api_secret': app.TRAKT_API_SECRET,
            'trakt_api_key': app.TRAKT_API_KEY,
            'trakt_access_token': app.TRAKT_ACCESS_TOKEN,
            'trakt_refresh_token': app.TRAKT_REFRESH_TOKEN
        }

        trakt_api = TraktApi(app.SSL_VERIFY, app.TRAKT_TIMEOUT,
                             **trakt_settings)

        if app.USE_TRAKT:

            data = {}
            try:
                # URL parameters
                if show_obj is not None:
                    title = get_title_without_year(show_obj.name,
                                                   show_obj.start_year)
                    data = {
                        'shows': [{
                            'title': title,
                            'year': show_obj.start_year,
                            'ids': {},
                        }]
                    }
                    data['shows'][0]['ids'][get_trakt_indexer(
                        show_obj.indexer)] = show_obj.indexerid
                elif data_show is not None:
                    data.update(data_show)
                else:
                    log.warning(
                        "There's a coding problem contact developer. It's needed to be provided at"
                        " least 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:
                    # trakt URL parameters
                    season = {
                        'season': [{
                            'number': s,
                        }]
                    }

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

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

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

                trakt_url = 'sync/watchlist'
                if update == 'remove':
                    trakt_url += '/remove'

                trakt_api.request(trakt_url, data, method='POST')

            except (TokenExpiredException, TraktException,
                    AuthException) as error:
                log.debug('Unable to update Trakt watchlist: {0}',
                          error.message)
                return False

        return True
Ejemplo n.º 10
0
    def fetch_popular_shows(self, page_url=None, trakt_list=None):  # pylint: disable=too-many-nested-blocks,too-many-branches
        """Get a list of popular shows from different Trakt lists based on a provided trakt_list.

        :param page_url: the page url opened to the base api url, for retreiving a specific list
        :param trakt_list: a description of the trakt list
        :return: A list of RecommendedShow objects, an empty list of none returned
        :throw: ``Exception`` if an Exception is thrown not handled by the libtrats exceptions
        """
        trending_shows = []
        removed_from_medusa = []

        # Create a trakt settings dict
        trakt_settings = {
            'trakt_api_secret': app.TRAKT_API_SECRET,
            'trakt_api_key': app.TRAKT_API_KEY,
            'trakt_access_token': app.TRAKT_ACCESS_TOKEN
        }

        trakt_api = TraktApi(timeout=app.TRAKT_TIMEOUT,
                             ssl_verify=app.SSL_VERIFY,
                             **trakt_settings)

        try:  # pylint: disable=too-many-nested-blocks
            not_liked_show = ''
            if app.TRAKT_ACCESS_TOKEN != '':
                library_shows = self.fetch_and_refresh_token(trakt_api, 'sync/watched/shows?extended=noseasons') + \
                    self.fetch_and_refresh_token(trakt_api, 'sync/collection/shows?extended=full')

                medusa_shows = [
                    show.indexerid for show in app.showList if show.indexerid
                ]
                removed_from_medusa = [
                    lshow['show']['ids']['tvdb'] for lshow in library_shows
                    if lshow['show']['ids']['tvdb'] not in medusa_shows
                ]

                if app.TRAKT_BLACKLIST_NAME is not None and app.TRAKT_BLACKLIST_NAME:
                    not_liked_show = trakt_api.request(
                        'users/' + app.TRAKT_USERNAME + '/lists/' +
                        app.TRAKT_BLACKLIST_NAME + '/items') or []
                else:
                    logger.log('Trakt blacklist name is empty', logger.DEBUG)

            if trakt_list not in ['recommended', 'newshow', 'newseason']:
                limit_show = '?limit=' + str(100 + len(not_liked_show)) + '&'
            else:
                limit_show = '?'

            shows = self.fetch_and_refresh_token(
                trakt_api,
                page_url + limit_show + 'extended=full,images') or []

            for show in shows:
                try:
                    if 'show' not in show:
                        show['show'] = show

                    if not_liked_show:
                        if show['show']['ids']['tvdb'] not in (
                                show['show']['ids']['tvdb']
                                for show in not_liked_show
                                if show['type'] == 'show'):
                            trending_shows.append(
                                self._create_recommended_show(show))
                    else:
                        trending_shows.append(
                            self._create_recommended_show(show))

                except MultipleShowObjectsException:
                    continue

            blacklist = app.TRAKT_BLACKLIST_NAME not in ''

        except TraktException as e:
            logger.log('Could not connect to Trakt service: %s' % ex(e),
                       logger.WARNING)
            raise

        return blacklist, trending_shows, removed_from_medusa
Ejemplo n.º 11
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 = app.indexerApi(self.indexer).api_params.copy()
            if self.lang:
                lINDEXER_API_PARMS['language'] = self.lang

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

            t = app.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,
                            app.indexerApi(self.indexer).name), logger.ERROR)

                ui.notifications.error(
                    "Unable to add show",
                    "Show in " + self.showDir + " has no name on " +
                    str(app.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(app.indexerApi(self.indexer).name) +
                           " but contains no season/episode data.")
                ui.notifications.error(
                    "Unable to add show", "Show " + str(s['seriesname']) +
                    " is on " + str(app.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, app.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, api.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, app.indexerApi(
                    self.indexer).name, self.indexer_id))

            if app.USE_TRAKT:

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

                try:
                    trakt_api.traktRequest("sync/watchlist/remove",
                                           data,
                                           method='POST')
                except TraktException as e:
                    logger.log(
                        "Could not remove show '{0}' from watchlist. Error: {1}"
                        .format(title, e), logger.WARNING)

            self._finishEarly()
            return

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

            self.show = newShow

            # set up initial values
            self.show.location = self.showDir
            self.show.subtitles = self.subtitles if self.subtitles is not None else app.SUBTITLES_DEFAULT
            self.show.quality = self.quality if self.quality else app.QUALITY_DEFAULT
            self.show.flatten_folders = self.flatten_folders if self.flatten_folders is not None else app.FLATTEN_FOLDERS_DEFAULT
            self.show.anime = self.anime if self.anime is not None else app.ANIME_DEFAULT
            self.show.scene = self.scene if self.scene is not None else app.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 app.indexer_exception as e:
            logger.log(
                u"Unable to add show due to an error with " +
                app.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 " +
                                       app.indexerApi(self.indexer).name + "")
            else:
                ui.notifications.error(
                    "Unable to add show due to an error with " +
                    app.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.load_imdb_info()
        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.save_to_db()
        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
        app.showList.append(self.show)

        try:
            self.show.load_episodes_from_indexer()
        except Exception as e:
            logger.log(
                u"Error with " + app.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.load_episodes_from_dir()
        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"
            )
            app.backlogSearchScheduler.action.searchBacklog([self.show])

        self.show.write_metadata()
        self.show.update_metadata()
        self.show.populate_cache()

        self.show.flush_episodes()

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

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

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

        # Load XEM data to DB for show
        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 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()
Ejemplo n.º 12
0
    def update_watchlist(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 trakt type
        data_episode: structured object of episodes trakt type
        update: type o action add or remove
        """

        trakt_settings = {
            'trakt_api_secret': app.TRAKT_API_SECRET,
            'trakt_api_key': app.TRAKT_API_KEY,
            'trakt_access_token': app.TRAKT_ACCESS_TOKEN,
            'trakt_refresh_token': app.TRAKT_REFRESH_TOKEN
        }

        trakt_api = TraktApi(app.SSL_VERIFY, app.TRAKT_TIMEOUT,
                             **trakt_settings)

        if app.USE_TRAKT:

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

                    if trakt_id == 'tvdb_id':
                        data['shows'][0]['ids']['tvdb'] = show_obj.indexerid
                    else:
                        data['shows'][0]['ids']['tvrage'] = show_obj.indexerid
                elif data_show is not None:
                    data.update(data_show)
                else:
                    logger.log(
                        "There's a coding problem contact developer. "
                        "It's needed to be provided at least one of the two: data_show or show_obj",
                        logger.WARNING)
                    return False

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

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

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

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

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

                trakt_url = 'sync/watchlist'
                if update == 'remove':
                    trakt_url += '/remove'

                trakt_api.request(trakt_url, data, method='POST')

            except (TraktException, AuthException, ServerBusy) as trakt_ex:
                logger.log(
                    'Could not connect to Trakt service: {0}'.format(
                        ex(trakt_ex)), logger.WARNING)
                return False

        return True