Exemplo n.º 1
0
    def get_list_items(self):
        arguments = g.REQUEST_PARAMS['action_args']
        media_type = g.REQUEST_PARAMS.get('media_type', arguments.get('type'))
        ignore_cache = True
        if g.REQUEST_PARAMS.get('from_widget') and g.REQUEST_PARAMS.get(
                'from_widget').lower() == "true":
            widget_loaded_setting = "widget_loaded.{}.{}".format(
                media_type, arguments)
            if not g.get_bool_runtime_setting(widget_loaded_setting):
                ignore_cache = False
                g.set_runtime_setting(widget_loaded_setting, True)
        list_items = self.lists_database.get_list_content(
            arguments['username'],
            arguments['trakt_id'],
            self._backwards_compatibility(media_type),
            ignore_cache=ignore_cache,
            page=g.PAGE,
            no_paging=self.no_paging)

        if not list_items:
            g.log(
                'Failed to pull list {} from Trakt/Database'.format(
                    arguments['trakt_id']), 'error')
            g.cancel_directory()
            return

        if media_type in ['tvshow', 'shows']:
            self.builder.show_list_builder(list_items,
                                           no_paging=self.no_paging)
        elif media_type in ['movie', 'movies']:
            self.builder.movie_menu_builder(list_items,
                                            no_paging=self.no_paging)
Exemplo n.º 2
0
    def shows_genres(self):
        g.add_directory_item(
            g.get_language_string(30045),
            action="showGenresGet",
            menu_item={
                "art":
                dict.fromkeys(['icon', 'poster', 'thumb', 'fanart'],
                              g.GENRES_PATH + "list.png")
            })
        genres = self.trakt_api.get_json_cached("genres/shows",
                                                extended="full")

        if genres is None:
            g.cancel_directory()
            return

        for i in genres:
            g.add_directory_item(
                i["name"],
                action="showGenresGet",
                action_args=i["slug"],
                menu_item={
                    "art":
                    dict.fromkeys(['icon', 'poster', 'thumb', 'fanart'],
                                  "{}{}.png".format(g.GENRES_PATH, i["slug"]))
                })
        g.close_directory(g.CONTENT_GENRES)
Exemplo n.º 3
0
    def shows_by_actor(self, actor):
        if not actor:
            k = xbmc.Keyboard("", g.get_language_string(30013))
            k.doModal()
            query = k.getText() if k.isConfirmed() else None
            del k
            if not query:
                g.cancel_directory()
                return
        else:
            query = tools.unquote(actor)

        if g.get_bool_setting("searchHistory"):
            SearchHistory().add_search_history("showActor", query)
        query = g.deaccent_string(query)
        query = query.replace(" ", "-")
        query = tools.quote_plus(query)

        self.list_builder.show_list_builder(
            self.trakt.get_json_paged("people/{}/shows".format(query),
                                      extended="full",
                                      page=g.PAGE),
            hide_watched=False,
            hide_unaired=False,
        )
Exemplo n.º 4
0
    def _common_menu_builder(self,
                             trakt_list,
                             content_type,
                             action="getSources",
                             **params):
        if len(trakt_list) == 0:
            g.log("We received no titles to build a list", "warning")
            g.cancel_directory()
            return

        list_items = []
        smart_play = params.pop("smart_play", False)
        no_paging = params.pop("no_paging", False)
        sort = params.pop("sort", False)
        prepend_date = params.pop("prepend_date", False)
        mixed_list = params.pop("mixed_list", False)
        next_args = params.pop("next_args", None)

        params.pop("hide_unaired", None)
        params.pop("hide_watched", None)
        try:
            params["bulk_add"] = True
            list_items = [
                g.add_directory_item(item.get("name"),
                                     action=action,
                                     menu_item=item,
                                     action_args=item.get("args"),
                                     **params) for item in
                self._post_process_list(trakt_list, prepend_date, mixed_list)
                if item is not None
            ]

            if smart_play:
                return list_items
            else:
                xbmcplugin.addDirectoryItems(g.PLUGIN_HANDLE, list_items,
                                             len(list_items))
        except Exception as e:
            g.log_stacktrace()
            if not smart_play:
                g.cancel_directory()
            raise e

        finally:
            if not smart_play:
                if (not (g.FROM_WIDGET
                         and g.get_bool_setting("general.widget.hide_next"))
                        and not no_paging
                        and len(list_items) >= self.page_limit):
                    g.REQUEST_PARAMS["page"] = g.PAGE + 1
                    if next_args:
                        g.REQUEST_PARAMS["action_args"] = next_args
                    elif g.REQUEST_PARAMS.get("action_args") is not None:
                        g.REQUEST_PARAMS["action_args"] = g.REQUEST_PARAMS.get(
                            "action_args")
                    params = g.REQUEST_PARAMS
                    params.update({"special_sort": "bottom"})
                    g.add_directory_item(g.get_language_string(30016),
                                         **params)
                g.close_directory(content_type, sort=sort)
Exemplo n.º 5
0
    def movies_genre_list(self, args):
        if args is None:
            genre_display_list = []
            genres = self.trakt_api.get_json_cached("genres/movies")
            for genre in genres:
                gi = xbmcgui.ListItem(genre["name"])
                gi.setArt(
                    {"thumb": "{}{}.png".format(g.GENRES_PATH, genre["slug"])})
                genre_display_list.append(gi)
            genre_multiselect = xbmcgui.Dialog().multiselect(
                "{}: {}".format(g.ADDON_NAME, g.get_language_string(30303)),
                genre_display_list,
                useDetails=True)
            if genre_multiselect is None:
                return
            genre_string = ",".join(
                [genres[i]["slug"] for i in genre_multiselect])
        else:
            genre_string = tools.unquote(args)

        trakt_list = self.movies_database.extract_trakt_page(
            "movies/{}".format("trending" if g.get_int_setting(
                "general.genres.endpoint.movies") == 0 else "popular"),
            genres=genre_string,
            page=g.PAGE,
            extended="full")

        if trakt_list is None:
            g.cancel_directory()
            return

        self.list_builder.movie_menu_builder(trakt_list,
                                             next_args=genre_string)
Exemplo n.º 6
0
    def shows_genre_list(self, args):
        trakt_endpoint = ("trending"
                          if g.get_int_setting("general.genres.endpoint") == 0
                          else "popular")
        if args is None:
            genre_display_list = []
            genre_string = ""
            genres = self.trakt.get_json_cached("genres/shows")

            for genre in genres:
                genre_display_list.append(genre["name"])
            genre_multiselect = xbmcgui.Dialog().multiselect(
                "{}: {}".format(g.ADDON_NAME, g.get_language_string(30330)),
                genre_display_list,
            )

            if genre_multiselect is None:
                return
            for selection in genre_multiselect:
                genre_string += ", {}".format(genres[selection]["slug"])
            genre_string = genre_string[2:]
        else:
            genre_string = tools.unquote(args)

        trakt_list = self.shows_database.extract_trakt_page(
            "shows/{}".format(trakt_endpoint),
            genres=genre_string,
            page=g.PAGE,
            extended="full")

        if trakt_list is None:
            g.cancel_directory()
            return

        self.list_builder.show_list_builder(trakt_list, next_args=genre_string)
    def movies_genre_list(self, args):
        trakt_endpoint = (
            "trending"
            if g.get_int_setting("general.genres.endpoint") == 0
            else "popular"
        )
        if args is None:
            genre_display_list = []
            genres = self.trakt.get_json("genres/movies")
            for genre in genres:
                genre_display_list.append(genre["name"])
            genre_multiselect = xbmcgui.Dialog().multiselect(
                "{}: {}".format(g.ADDON_NAME, g.get_language_string(30330)),
                genre_display_list,
            )
            if genre_multiselect is None:
                return
            genre_string = ",".join([genres[i]["slug"] for i in genre_multiselect])
        else:
            genre_string = tools.unquote(args)

        trakt_list = self.trakt.get_json_cached(
            "movies/{}".format(trakt_endpoint),
            page=g.PAGE,
            extended="full"
        )

        if trakt_list is None:
            g.cancel_directory()
            return

        self.list_builder.movie_menu_builder(trakt_list, next_args=genre_string)
Exemplo n.º 8
0
    def shows_search(self, query=None):
        if not query:
            query = g.get_keyboard_input(g.get_language_string(30013))
            if not query:
                g.cancel_directory()
                return

        if g.get_bool_setting("searchHistory"):
            self.search_history.add_search_history("tvshow", query)
        self.shows_search_results(query)
Exemplo n.º 9
0
    def movies_search(self, query=None):
        if query is None:
            query = g.get_keyboard_input(heading=g.get_language_string(30013))
            if not query:
                g.cancel_directory()
                return

        if g.get_bool_setting("searchHistory"):
            self.search_history.add_search_history("movie", query)

        self.movies_search_results(query)
 def movies_genres(self):
     g.add_directory_item(g.get_language_string(30046), action="movieGenresGet")
     genres = self.trakt.get_json("genres/movies")
     if genres is None:
         g.cancel_directory()
         return
     for i in genres:
         g.add_directory_item(
             i["name"], action="movieGenresGet", action_args=i["slug"]
         )
     g.close_directory(g.CONTENT_GENRES)
Exemplo n.º 11
0
    def shows_genres(self):
        g.add_directory_item(g.get_language_string(30046), action="showGenresGet")
        genres = self.trakt.get_json_cached("genres/shows", extended="full")

        if genres is None:
            g.cancel_directory()
            return

        for i in genres:
            g.add_directory_item(
                i["name"], action="showGenresGet", action_args=i["slug"]
            )
        g.close_directory(g.CONTENT_GENRES)
Exemplo n.º 12
0
    def shows_search(self, query=None):
        if not query:
            k = xbmc.Keyboard("", g.get_language_string(30013))
            k.doModal()
            query = k.getText() if k.isConfirmed() else None
            del k
            if not query:
                g.cancel_directory()
                return

        query = g.decode_py2(query)
        if g.get_bool_setting("searchHistory"):
            SearchHistory().add_search_history("tvshow", query)
        query = g.deaccent_string(g.display_string(query))
        self.shows_search_results(query)
Exemplo n.º 13
0
 def shows_search_results(self, query):
     trakt_list = self.trakt.get_json_paged(
         "search/show",
         query=query,
         page=g.PAGE,
         extended="full",
         field="title",
     )
     if not trakt_list:
         g.cancel_directory()
         return
     self.list_builder.show_list_builder([
         show for show in trakt_list
         if float(show["trakt_object"]["info"]["score"]) > 0
     ])
 def movies_search_results(self, query):
     trakt_list = self.trakt.get_json_paged(
         "search/movie", query=tools.unquote(query), extended="full", page=g.PAGE
     )
     if not trakt_list:
         g.cancel_directory()
         return
     self.list_builder.movie_menu_builder(
         [
             movie
             for movie in trakt_list
             if float(movie["trakt_object"]["info"]["score"]) > 0
         ],
         hide_watched=False,
         hide_unaired=False,
     )
Exemplo n.º 15
0
    def movies_search(self, query=None):
        if query is None:
            k = xbmc.Keyboard("", g.get_language_string(30013))
            k.doModal()
            query = k.getText() if k.isConfirmed() else None
            del k
            if not query:
                g.cancel_directory()
                return

        query = query
        if g.get_bool_setting("searchHistory"):
            SearchHistory().add_search_history("movie", query)
        query = g.deaccent_string(query)
        query = tools.quote(query)

        self.movies_search_results(query)
Exemplo n.º 16
0
    def shows_search_results(self, query):
        trakt_list = self.shows_database.extract_trakt_page("search/show",
                                                            query=query,
                                                            page=g.PAGE,
                                                            extended="full",
                                                            field="title",
                                                            hide_unaired=False,
                                                            hide_watched=False)

        if not trakt_list:
            g.cancel_directory()
            return
        self.list_builder.show_list_builder([
            show for show in trakt_list
            if float(show["trakt_object"]["info"]["score"]) > 0
        ],
                                            hide_unaired=False,
                                            hide_watched=False)
Exemplo n.º 17
0
    def movies_search_results(self, query):
        trakt_list = self.movies_database.extract_trakt_page(
            "search/movie",
            query=query,
            extended="full",
            page=g.PAGE,
            hide_watched=False,
            hide_unaired=False,
        )

        if not trakt_list:
            g.cancel_directory()
            return
        self.list_builder.movie_menu_builder(
            [
                movie for movie in trakt_list
                if float(movie["trakt_object"]["info"]["score"]) > 0
            ],
            hide_watched=False,
            hide_unaired=False,
        )
Exemplo n.º 18
0
    def shows_by_actor(self, query):
        if not query:
            query = g.get_keyboard_input(g.get_language_string(30013))
            if not query:
                g.cancel_directory()
                return

        if g.get_bool_setting("searchHistory"):
            self.search_history.add_search_history("showActor", query)

        query = g.transliterate_string(query)
        # Try to deal with transliterated chinese actor names as some character -> word transliterations can be joined
        # I have no idea of the rules and it could well be arbitrary
        # This approach will only work if only one pair of adjoining transliterated chars are joined
        name_parts = query.split()
        for i in range(len(name_parts), 0, -1):
            query = "-".join(name_parts[:i]) + "-".join(name_parts[i:i + 1])
            query = tools.quote_plus(query)

            trakt_list = self.shows_database.extract_trakt_page(
                "people/{}/shows".format(query),
                extended="full",
                page=g.PAGE,
                hide_watched=False,
                hide_unaired=False,
            )
            if not trakt_list:
                continue
            else:
                break

        try:
            if not trakt_list or 'trakt_id' not in trakt_list[0]:
                raise KeyError
        except KeyError:
            g.cancel_directory()
            return
        self.list_builder.show_list_builder(trakt_list,
                                            hide_watched=False,
                                            hide_unaired=False)
Exemplo n.º 19
0
    def get_list_items(self):
        arguments = g.REQUEST_PARAMS['action_args']
        media_type = g.REQUEST_PARAMS.get('media_type', arguments.get('type'))
        list_items = self.lists_database.get_list_content(
            arguments['username'],
            arguments['trakt_id'],
            self._backwards_compatibility(media_type),
            page=g.PAGE,
            no_paging=self.no_paging)

        if not list_items:
            g.log(
                'Failed to pull list {} from Trakt/Database'.format(
                    arguments['trakt_id']), 'error')
            g.cancel_directory()
            return

        if media_type in ['tvshow', 'shows']:
            self.builder.show_list_builder(list_items,
                                           no_paging=self.no_paging)
        elif media_type in ['movie', 'movies']:
            self.builder.movie_menu_builder(list_items,
                                            no_paging=self.no_paging)
Exemplo n.º 20
0
    def wrapper(*args, **kwargs):
        """
        Wrapper method for decorator
        :param args: method args
        :param kwargs: method kwargs
        :return:
        """
        method_class = args[0]
        method_class._load_settings()
        import requests
        try:
            response = func(*args, **kwargs)
            if response.status_code in [200, 201, 204]:
                return response

            if (response.status_code == 400 and response.url
                    == "https://api.trakt.tv/oauth/device/token"):
                return response
            if (response.status_code == 400
                    and response.url == "https://api.trakt.tv/oauth/token"):
                _reset_trakt_auth()
                raise Exception("Unable to refresh Trakt auth")

            if response.status_code == 403:
                g.log(
                    "Trakt: invalid API key or unapproved app, resetting auth",
                    "error")
                _reset_trakt_auth()
                g.cancel_directory()
                return None

            if response.status_code == 401:
                import inspect

                if inspect.stack(1)[1][3] == "try_refresh_token":
                    xbmcgui.Dialog().notification(g.ADDON_NAME,
                                                  g.get_language_string(30340))
                    g.log(
                        "Attempts to refresh Trakt token have failed. User intervention is required",
                        "error",
                    )
                else:
                    try:
                        with GlobalLock("trakt.oauth",
                                        run_once=True,
                                        check_sum=method_class.access_token):
                            if method_class.refresh_token is not None:
                                method_class.try_refresh_token(True)
                            if (method_class.refresh_token is None
                                    and method_class.username is not None):
                                xbmcgui.Dialog().ok(
                                    g.ADDON_NAME, g.get_language_string(30340))
                    except RanOnceAlready:
                        pass
                    if method_class.refresh_token is not None:
                        return func(*args, **kwargs)

            if response.status_code == 423:
                xbmcgui.Dialog().notification(
                    g.ADDON_NAME, TRAKT_STATUS_CODES.get(response.status_code))
                g.log(
                    "Locked User Account - Contact Trakt support",
                    "error",
                )

            g.log(
                "Trakt returned a {} ({}): while requesting {}".format(
                    response.status_code,
                    TRAKT_STATUS_CODES.get(response.status_code,
                                           "*Unknown status code*"),
                    response.url,
                ),
                "error",
            )

            return response
        except requests.exceptions.ConnectionError as e:
            _log_connection_error(args, kwargs, e)
            raise
        except Exception as e:
            _connection_failure_dialog()
            _log_connection_error(args, kwargs, e)
            raise