Exemplo n.º 1
0
def test_per_arg_validator():
    b_validator = PerArgValidator("b", lambda b: b in ["abc", "xyz"])
    c_validator = PerArgValidator("c", lambda c: "x" in c)
    p = Path("a/!b/?c", {}, validators=[b_validator, c_validator])

    assert b_validator.validate(path=p, b="xyz") is None

    with pytest.raises(ArgumentError):
        b_validator.validate(path=p, b="any")

    assert c_validator.validate(path=p, b="xyz") is None
    assert c_validator.validate(path=p, b="any") is None

    with pytest.raises(ArgumentError):
        c_validator.validate(path=p, b="any", c="y")
Exemplo n.º 2
0
def test_multiple_validators_for_field():
    p = Path(
        "?a",
        {},
        validators=[
            PerArgValidator("a", lambda x: x > 10),
            PerArgValidator("a", lambda x: x % 3 == 0),
        ],
    )

    assert p.is_valid(None, a=30)

    for val in [6, 13]:
        with pytest.raises(ArgumentError):
            p.is_valid(None, a=val)
Exemplo n.º 3
0
    def _make_path(self, resource_path: str, return_type: Any) -> Path:
        extra_validators: List[Validator] = []
        if "?period" in resource_path:
            extra_validators.append(
                PerArgValidator("period", lambda p: p in PERIOD_VALUES))

        return Path(
            self.name + "/" + resource_path,
            return_type,
            extended=["full"],
            filters=COMMON_FILTERS,
            pagination=True,
            validators=extra_validators,
        )
Exemplo n.º 4
0
class EpisodesI(SuiteInterface):
    name = "episodes"

    paths = {
        "get_episode": Path(
            "shows/!id/seasons/!season/episodes/!episode",
            Episode,
            extended=["full"],
            validators=[ID_VALIDATOR, SEASON_ID_VALIDATOR, EPISODE_ID_VALIDATOR],
        ),
        "get_translations": Path(
            "shows/!id/seasons/!season/episodes/!episode/translations/?language",
            [EpisodeTranslation],
            validators=[
                ID_VALIDATOR,
                SEASON_ID_VALIDATOR,
                EPISODE_ID_VALIDATOR,
                PerArgValidator("language", lambda s: isinstance(s, str)),
            ],
        ),
        "get_comments": Path(
            "shows/!id/seasons/!season/episodes/!episode/comments/?sort",
            [Comment],
            validators=[
                ID_VALIDATOR,
                SEASON_ID_VALIDATOR,
                EPISODE_ID_VALIDATOR,
                PerArgValidator("sort", lambda s: s in COMMENT_SORT_VALUES),
            ],
            pagination=True,
        ),
        "get_lists": Path(
            "shows/!id/seasons/!season/episodes/!episode/lists/?type/?sort",
            [TraktList],
            validators=[
                ID_VALIDATOR,
                SEASON_ID_VALIDATOR,
                EPISODE_ID_VALIDATOR,
                PerArgValidator("type", lambda t: t in LIST_TYPE_VALUES),
                PerArgValidator("sort", lambda s: s in LIST_SORT_VALUES),
            ],
            pagination=True,
        ),
        "get_ratings": Path(
            "shows/!id/seasons/!season/episodes/!episode/ratings",
            RatingsSummary,
            validators=[ID_VALIDATOR, SEASON_ID_VALIDATOR, EPISODE_ID_VALIDATOR],
        ),
        "get_stats": Path(
            "shows/!id/seasons/!season/episodes/!episode/stats",
            SeasonEpisodeStats,
            validators=[ID_VALIDATOR, SEASON_ID_VALIDATOR, EPISODE_ID_VALIDATOR],
        ),
        "get_users_watching": Path(
            "shows/!id/seasons/!season/episodes/!episode/watching",
            [User],
            extended=["full"],
            validators=[ID_VALIDATOR, SEASON_ID_VALIDATOR, EPISODE_ID_VALIDATOR],
        ),
    }

    def get_episode(
        self,
        *,
        show: Union[Show, str, int],
        season: Union[Season, str, int],
        episode: Union[Episode, int, str],
        **kwargs
    ) -> Season:
        id = self._generic_get_id(show)
        season = self._generic_get_id(season)
        episode = self._generic_get_id(episode)
        return self.run("get_episode", **kwargs, id=id, season=season, episode=episode)

    def get_comments(
        self,
        *,
        show: Union[Show, str, int],
        season: Union[Season, str, int],
        episode: Union[Episode, int, str],
        sort: str = "newest",
        **kwargs
    ) -> PaginationIterator[Comment]:
        id = self._generic_get_id(show)
        season = self._generic_get_id(season)
        episode = self._generic_get_id(episode)
        return self.run(
            "get_comments", **kwargs, sort=sort, id=id, season=season, episode=episode
        )

    def get_translations(
        self,
        *,
        show: Union[Show, str, int],
        season: Union[Season, str, int],
        episode: Union[Episode, int, str],
        sort: str = "newest",
        **kwargs
    ) -> List[Comment]:
        id = self._generic_get_id(show)
        season = self._generic_get_id(season)
        episode = self._generic_get_id(episode)
        return self.run(
            "get_translations",
            **kwargs,
            sort=sort,
            id=id,
            season=season,
            episode=episode
        )

    def get_lists(
        self,
        *,
        show: Union[Show, str, int],
        season: Union[Season, str, int],
        episode: Union[Episode, int, str],
        type: str = "personal",
        sort: str = "popular",
        **kwargs
    ) -> PaginationIterator[TraktList]:
        id = self._generic_get_id(show)
        season = self._generic_get_id(season)
        episode = self._generic_get_id(episode)
        return self.run(
            "get_lists",
            **kwargs,
            type=type,
            sort=sort,
            id=id,
            season=season,
            episode=episode
        )

    def get_ratings(
        self,
        *,
        show: Union[Show, str, int],
        season: Union[Season, str, int],
        episode: Union[Episode, int, str],
        **kwargs
    ) -> RatingsSummary:
        id = self._generic_get_id(show)
        season = self._generic_get_id(season)
        episode = self._generic_get_id(episode)
        return self.run("get_ratings", **kwargs, id=id, season=season, episode=episode)

    def get_stats(
        self,
        *,
        show: Union[Show, str, int],
        season: Union[Season, str, int],
        episode: Union[Episode, int, str],
        **kwargs
    ) -> SeasonEpisodeStats:
        id = self._generic_get_id(show)
        season = self._generic_get_id(season)
        episode = self._generic_get_id(episode)
        return self.run("get_stats", **kwargs, id=id, season=season, episode=episode)

    def get_users_watching(
        self,
        *,
        show: Union[Show, str, int],
        season: Union[Season, str, int],
        episode: Union[Episode, int, str],
        **kwargs
    ) -> List[User]:
        id = self._generic_get_id(show)
        season = self._generic_get_id(season)
        episode = self._generic_get_id(episode)
        return self.run(
            "get_users_watching", **kwargs, id=id, season=season, episode=episode
        )
Exemplo n.º 5
0
from typing import List, Union

from trakt.core.models import Movie
from trakt.core.paths.path import Path
from trakt.core.paths.response_structs import Show
from trakt.core.paths.suite_interface import SuiteInterface
from trakt.core.paths.validators import AuthRequiredValidator, PerArgValidator

IGNORE_COLLECTED_VALIDATOR = PerArgValidator(
    "ignore_collected", lambda i: isinstance(i, bool)
)
ID_VALIDATOR = PerArgValidator("id", lambda c: isinstance(c, (int, str)))


class RecommendationsI(SuiteInterface):
    name = "recommendations"

    paths = {
        "get_movie_recommendations": Path(
            "recommendations/movies",
            [Movie],
            validators=[AuthRequiredValidator(), IGNORE_COLLECTED_VALIDATOR],
            extended=["full"],
            qargs=["ignore_collected"],
        ),
        "hide_movie": Path(
            "recommendations/movies/!id",
            {},
            methods="DELETE",
            validators=[AuthRequiredValidator(), ID_VALIDATOR],
        ),
Exemplo n.º 6
0
class MoviesI(SuiteInterface):
    name = "movies"

    base_paths = {
        "get_trending": ["trending", [TrendingMovie]],
        "get_popular": ["popular", [Movie]],
        "get_most_played": ["played/?period", [MovieWithStats]],
        "get_most_watched": ["watched/?period", [MovieWithStats]],
        "get_most_collected": ["collected/?period", [MovieWithStats]],
        "get_most_anticipated": ["anticipated", [AnticipatedMovie]],
    }

    paths = {
        "get_box_office":
        Path("movies/boxoffice", [BoxOffice],
             extended=["full"],
             cache_level="basic"),
        "get_recently_updated":
        Path(
            "movies/updates/?start_date",
            [UpdatedMovie],
            extended=["full"],
            pagination=True,
            validators=[PerArgValidator("start_date", is_date)],
        ),
        "get_summary":
        Path("movies/!id", Movie, extended=["full"], cache_level="basic"),
        "get_aliases":
        Path("movies/!id/aliases", [Alias], cache_level="basic"),
        "get_releases":
        Path(
            "movies/!id/releases/?country",
            [MovieRelease],
            validators=[
                PerArgValidator("country",
                                lambda c: isinstance(c, str) and len(c) == 2)
            ],
            cache_level="basic",
        ),
        "get_translations":
        Path(
            "movies/!id/translations/?language",
            [MovieTranslation],
            validators=[
                PerArgValidator("language",
                                lambda c: isinstance(c, str) and len(c) == 2)
            ],
            cache_level="basic",
        ),
        "get_comments":
        Path(
            "movies/!id/comments/?sort",
            [Comment],
            validators=[
                PerArgValidator("sort", lambda s: s in COMMENT_SORT_VALUES)
            ],
            pagination=True,
        ),
        "get_lists":
        Path(
            "movies/!id/lists/?type/?sort",
            [TraktList],
            validators=[
                PerArgValidator("type", lambda t: t in LIST_TYPE_VALUES),
                PerArgValidator("sort", lambda s: s in LIST_SORT_VALUES),
            ],
            pagination=True,
        ),
        "get_people":
        Path("movies/!id/people",
             CastCrewList,
             extended=["full"],
             cache_level="basic"),
        "get_ratings":
        Path("movies/!id/ratings", RatingsSummary),
        "get_related":
        Path(
            "movies/!id/related",
            [Movie],
            extended=["full"],
            pagination=True,
            cache_level="basic",
        ),
        "get_stats":
        Path("movies/!id/stats", MovieStats),
        "get_users_watching":
        Path("movies/!id/watching", [User], extended=["full"]),
    }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for k, r in self.base_paths.items():
            self.paths[k] = self._make_path(*r)

    def _make_path(self, resource_path: str, return_type: Any) -> Path:
        extra_validators: List[Validator] = []
        if "?period" in resource_path:
            extra_validators.append(
                PerArgValidator("period", lambda p: p in PERIOD_VALUES))

        return Path(
            self.name + "/" + resource_path,
            return_type,
            extended=["full"],
            filters=COMMON_FILTERS,
            pagination=True,
            validators=extra_validators,
        )

    def get_trending(self, **kwargs) -> PaginationIterator[TrendingMovie]:
        return self.run("get_trending", **kwargs)

    def get_popular(self, **kwargs) -> PaginationIterator[Movie]:
        return self.run("get_popular", **kwargs)

    def get_most_played(self,
                        *,
                        period: str = "weekly",
                        **kwargs) -> PaginationIterator[MovieWithStats]:
        return self.run("get_most_played", **kwargs, period=period)

    def get_most_watched(self,
                         *,
                         period: str = "weekly",
                         **kwargs) -> PaginationIterator[MovieWithStats]:
        return self.run("get_most_watched", **kwargs, period=period)

    def get_most_collected(self,
                           *,
                           period: str = "weekly",
                           **kwargs) -> PaginationIterator[MovieWithStats]:
        return self.run("get_most_collected", **kwargs, period=period)

    def get_most_anticipated(self,
                             **kwargs) -> PaginationIterator[AnticipatedMovie]:
        return self.run("get_most_anticipated", **kwargs)

    def get_box_office(self, **kwargs) -> List[BoxOffice]:
        return self.run("get_box_office", **kwargs)

    def get_recently_updated(self,
                             *,
                             start_date: Optional[str] = None,
                             **kwargs) -> PaginationIterator[UpdatedMovie]:
        return self.run("get_recently_updated",
                        **kwargs,
                        start_date=start_date)

    def get_summary(self, *, movie: Union[Movie, str, int], **kwargs) -> Movie:
        movie_id = self._get_movie_id(movie)
        return self.run("get_summary", **kwargs, id=movie_id)

    def get_aliases(self, *, movie: Union[Movie, str, int],
                    **kwargs) -> List[Alias]:
        movie_id = self._get_movie_id(movie)
        return self.run("get_aliases", **kwargs, id=movie_id)

    def get_releases(self,
                     *,
                     movie: Union[Movie, str, int],
                     country: Optional[str] = None,
                     **kwargs) -> List[MovieRelease]:
        extra_kwargs = {"id": self._get_movie_id(movie)}
        if country:
            extra_kwargs["country"] = country

        return self.run("get_releases", **kwargs, **extra_kwargs)

    def get_translations(self,
                         *,
                         movie: Union[Movie, str, int],
                         language: Optional[str] = None,
                         **kwargs) -> List[MovieTranslation]:
        extra_kwargs = {"id": self._get_movie_id(movie)}
        if language:
            extra_kwargs["language"] = language

        return self.run("get_translations", **kwargs, **extra_kwargs)

    def get_comments(self,
                     *,
                     movie: Union[Movie, str, int],
                     sort: str = "newest",
                     **kwargs) -> PaginationIterator[Comment]:
        movie_id = self._get_movie_id(movie)
        return self.run("get_comments", **kwargs, sort=sort, id=movie_id)

    def get_lists(self,
                  *,
                  movie: Union[Movie, str, int],
                  type: str = "personal",
                  sort: str = "popular",
                  **kwargs) -> PaginationIterator[TraktList]:
        movie_id = self._get_movie_id(movie)
        return self.run("get_lists",
                        **kwargs,
                        type=type,
                        sort=sort,
                        id=movie_id)

    def get_people(self, *, movie: Union[Movie, str, int],
                   **kwargs) -> CastCrewList:
        return self.run("get_people", **kwargs, id=self._get_movie_id(movie))

    def get_ratings(self, *, movie: Union[Movie, str, int],
                    **kwargs) -> RatingsSummary:
        return self.run("get_ratings", **kwargs, id=self._get_movie_id(movie))

    def get_related(self, *, movie: Union[Movie, str, int],
                    **kwargs) -> PaginationIterator[Movie]:
        return self.run("get_related", **kwargs, id=self._get_movie_id(movie))

    def get_stats(self, *, movie: Union[Movie, str, int],
                  **kwargs) -> MovieStats:
        return self.run("get_stats", **kwargs, id=self._get_movie_id(movie))

    def get_users_watching(self, *, movie: Union[Movie, str, int],
                           **kwargs) -> List[User]:
        return self.run("get_users_watching",
                        **kwargs,
                        id=self._get_movie_id(movie))

    def _get_movie_id(self, movie: Union[Movie, str, int]) -> str:
        return str(self._generic_get_id(movie))
Exemplo n.º 7
0
class ShowsI(SuiteInterface):
    name = "shows"

    base_paths = {
        "get_trending": ["trending", [TrendingShow]],
        "get_popular": ["popular", [Show]],
        "get_most_played": ["played/?period", [ShowWithStats]],
        "get_most_watched": ["watched/?period", [ShowWithStats]],
        "get_most_collected": ["collected/?period", [ShowWithStats]],
        "get_most_anticipated": ["anticipated", [AnticipatedShow]],
    }

    paths = {
        "get_recently_updated":
        Path(
            "shows/updates/?start_date",
            [UpdatedShow],
            extended=["full"],
            pagination=True,
            validators=[PerArgValidator("start_date", is_date)],
        ),
        "get_summary":
        Path(
            "shows/!id",
            Show,
            extended=["full"],
            validators=[ID_VALIDATOR],
            cache_level="basic",
        ),
        "get_aliases":
        Path("shows/!id/aliases", [Alias],
             validators=[ID_VALIDATOR],
             cache_level="basic"),
        "get_translations":
        Path(
            "shows/!id/translations/?language",
            [ShowTranslation],
            validators=[
                ID_VALIDATOR,
                PerArgValidator("language",
                                lambda c: isinstance(c, str) and len(c) == 2),
            ],
            cache_level="basic",
        ),
        "get_comments":
        Path(
            "shows/!id/comments/?sort",
            [Comment],
            validators=[
                ID_VALIDATOR,
                PerArgValidator("sort", lambda s: s in COMMENT_SORT_VALUES),
            ],
            pagination=True,
        ),
        "get_lists":
        Path(
            "shows/!id/lists/?type/?sort",
            [TraktList],
            validators=[
                ID_VALIDATOR,
                PerArgValidator("type", lambda t: t in LIST_TYPE_VALUES),
                PerArgValidator("sort", lambda s: s in LIST_SORT_VALUES),
            ],
            pagination=True,
        ),
        "get_collection_progress":
        Path(
            "shows/!id/progress/collection",
            ShowCollectionProgress,
            validators=PROGRESS_VALIDATORS,
            qargs=["hidden", "specials", "count_specials", "last_activity"],
        ),
        "get_watched_progress":
        Path(
            "shows/!id/progress/watched",
            ShowWatchedProgress,
            validators=PROGRESS_VALIDATORS,
            qargs=["hidden", "specials", "count_specials", "last_activity"],
        ),
        "get_people":
        Path(
            "shows/!id/people",
            CastCrewList,
            extended=["full"],
            validators=[ID_VALIDATOR],
            cache_level="basic",
        ),
        "get_ratings":
        Path("shows/!id/ratings", RatingsSummary, validators=[ID_VALIDATOR]),
        "get_related":
        Path(
            "shows/!id/related",
            [Show],
            extended=["full"],
            pagination=True,
            validators=[ID_VALIDATOR],
            cache_level="basic",
        ),
        "get_stats":
        Path("shows/!id/stats", ShowStats, validators=[ID_VALIDATOR]),
        "get_users_watching":
        Path("shows/!id/watching", [User],
             extended=["full"],
             validators=[ID_VALIDATOR]),
        "get_next_episode":
        Path(
            "shows/!id/next_episode",
            Union[Episode, Dict[str, Any]],
            extended=["full"],
            validators=[ID_VALIDATOR],
        ),
        "get_last_episode":
        Path(
            "shows/!id/last_episode",
            Union[Episode, Dict[str, Any]],
            extended=["full"],
            validators=[ID_VALIDATOR],
        ),
    }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for k, r in self.base_paths.items():
            self.paths[k] = self._make_path(*r)

    def _make_path(self, resource_path: str, return_type: Any) -> Path:
        extra_validators: List[Validator] = []
        if "?period" in resource_path:
            extra_validators.append(
                PerArgValidator("period", lambda p: p in PERIOD_VALUES))

        return Path(
            self.name + "/" + resource_path,
            return_type,
            extended=["full"],
            filters=COMMON_FILTERS | SHOWS_FILTERS,
            pagination=True,
            validators=extra_validators,
        )

    def get_trending(self, **kwargs) -> PaginationIterator[TrendingShow]:
        return self.run("get_trending", **kwargs)

    def get_popular(self, **kwargs) -> PaginationIterator[Show]:
        return self.run("get_popular", **kwargs)

    def get_most_played(self,
                        *,
                        period: str = "weekly",
                        **kwargs) -> PaginationIterator[ShowWithStats]:
        return self.run("get_most_played", **kwargs, period=period)

    def get_most_watched(self,
                         *,
                         period: str = "weekly",
                         **kwargs) -> PaginationIterator[ShowWithStats]:
        return self.run("get_most_watched", **kwargs, period=period)

    def get_most_collected(self,
                           *,
                           period: str = "weekly",
                           **kwargs) -> PaginationIterator[ShowWithStats]:
        return self.run("get_most_collected", **kwargs, period=period)

    def get_most_anticipated(self,
                             **kwargs) -> PaginationIterator[AnticipatedShow]:
        return self.run("get_most_anticipated", **kwargs)

    def get_recently_updated(self,
                             *,
                             start_date: Optional[str] = None,
                             **kwargs) -> PaginationIterator[UpdatedShow]:
        return self.run("get_recently_updated",
                        **kwargs,
                        start_date=start_date)

    def get_summary(self, *, show: Union[Show, str, int],
                    **kwargs) -> PaginationIterator[Show]:
        id = self._generic_get_id(show)
        return self.run("get_summary", **kwargs, id=id)

    def get_aliases(self, *, show: Union[Show, str, int],
                    **kwargs) -> List[Alias]:
        id = self._generic_get_id(show)
        return self.run("get_aliases", **kwargs, id=id)

    def get_translations(self,
                         *,
                         show: Union[Show, str, int],
                         language: Optional[str] = None,
                         **kwargs) -> List[ShowTranslation]:
        extra_kwargs = {"id": self._generic_get_id(show)}
        if language:
            extra_kwargs["language"] = language

        return self.run("get_translations", **kwargs, **extra_kwargs)

    def get_comments(self,
                     *,
                     show: Union[Show, str, int],
                     sort: str = "newest",
                     **kwargs) -> PaginationIterator[Comment]:
        id = self._generic_get_id(show)
        return self.run("get_comments", **kwargs, sort=sort, id=id)

    def get_lists(self,
                  *,
                  show: Union[Show, str, int],
                  type: str = "personal",
                  sort: str = "popular",
                  **kwargs) -> PaginationIterator[TraktList]:
        id = self._generic_get_id(show)
        return self.run("get_lists", **kwargs, type=type, sort=sort, id=id)

    def get_collection_progress(self,
                                *,
                                show: Union[Show, str, int],
                                hidden: bool = False,
                                specials: bool = False,
                                count_specials: bool = True,
                                **kwargs) -> ShowCollectionProgress:
        return self.run("get_collection_progress",
                        **kwargs,
                        id=self._generic_get_id(show),
                        hidden=hidden,
                        specials=specials,
                        count_specials=count_specials)

    def get_watched_progress(self,
                             *,
                             show: Union[Show, str, int],
                             hidden: bool = False,
                             specials: bool = False,
                             count_specials: bool = True,
                             **kwargs) -> ShowCollectionProgress:
        return self.run("get_watched_progress",
                        **kwargs,
                        id=self._generic_get_id(show),
                        hidden=hidden,
                        specials=specials,
                        count_specials=count_specials)

    def get_people(self, *, show: Union[Show, str, int],
                   **kwargs) -> CastCrewList:
        return self.run("get_people", **kwargs, id=self._generic_get_id(show))

    def get_ratings(self, *, show: Union[Show, str, int],
                    **kwargs) -> RatingsSummary:
        return self.run("get_ratings", **kwargs, id=self._generic_get_id(show))

    def get_related(self, *, show: Union[Show, str, int],
                    **kwargs) -> PaginationIterator[Show]:
        return self.run("get_related", **kwargs, id=self._generic_get_id(show))

    def get_stats(self, *, show: Union[Show, str, int], **kwargs) -> ShowStats:
        return self.run("get_stats", **kwargs, id=self._generic_get_id(show))

    def get_users_watching(self, *, show: Union[Show, str, int],
                           **kwargs) -> List[User]:
        return self.run("get_users_watching",
                        **kwargs,
                        id=self._generic_get_id(show))

    def get_next_episode(self, *, show: Union[Show, str, int],
                         **kwargs) -> Optional[Episode]:
        resp = self.run("get_next_episode",
                        **kwargs,
                        id=self._generic_get_id(show),
                        return_extras=True)

        return None if resp.code == 204 else resp.parsed

    def get_last_episode(self, *, show: Union[Show, str, int],
                         **kwargs) -> Optional[Episode]:
        resp = self.run("get_last_episode",
                        **kwargs,
                        id=self._generic_get_id(show),
                        return_extras=True)

        return None if resp.code == 204 else resp.parsed
Exemplo n.º 8
0
class CalendarsI(SuiteInterface):
    name = "calendars"

    base_paths = {
        "get_shows": ["all/shows/?start_date/?days", [EpisodePremiere]],
        "get_my_shows": ["my/shows/?start_date/?days", [EpisodePremiere]],
        "get_new_shows":
        ["all/shows/new/?start_date/?days", [EpisodePremiere]],
        "get_my_new_shows":
        ["my/shows/new/?start_date/?days", [EpisodePremiere]],
        "get_season_premieres": [
            "all/shows/premieres/?start_date/?days",
            [EpisodePremiere],
        ],
        "get_my_season_premieres": [
            "my/shows/premieres/?start_date/?days",
            [EpisodePremiere],
        ],
        "get_movies": ["all/movies/?start_date/?days", [MoviePremiere]],
        "get_my_movies": ["my/movies/?start_date/?days", [MoviePremiere]],
        "get_dvd_releases": ["all/dvd/?start_date/?days", [MoviePremiere]],
        "get_my_dvd_releases": ["my/dvd/?start_date/?days", [MoviePremiere]],
    }

    COMMON_VALIDATORS: List[Validator] = [
        PerArgValidator("days", lambda t: isinstance(t, int)),
        PerArgValidator("start_date",
                        lambda t: re.match(r"\d{4}-\d{2}-\d{2}", t)),
    ]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.paths = {
            k: self._make_path(*r)
            for k, r in self.base_paths.items()
        }

    def _make_path(self, resource_path: str, return_type: Any) -> Path:
        extra_validators = [AuthRequiredValidator()
                            ] if "my/" in resource_path else []

        return Path(
            "calendars/" + resource_path,
            return_type,
            extended=["full"],
            filters=COMMON_FILTERS | SHOWS_FILTERS,
            validators=self.COMMON_VALIDATORS +
            extra_validators,  # type: ignore
        )

    def get_shows(self, **kwargs: Any) -> List[EpisodePremiere]:
        return self.run("get_shows", **kwargs)

    def get_my_shows(self, **kwargs: Any) -> List[EpisodePremiere]:
        return self.run("get_my_shows", **kwargs)

    def get_new_shows(self, **kwargs: Any) -> List[EpisodePremiere]:
        return self.run("get_new_shows", **kwargs)

    def get_my_new_shows(self, **kwargs: Any) -> List[EpisodePremiere]:
        return self.run("get_my_new_shows", **kwargs)

    def get_season_premieres(self, **kwargs: Any) -> List[EpisodePremiere]:
        return self.run("get_season_premieres", **kwargs)

    def get_my_season_premieres(self, **kwargs: Any) -> List[EpisodePremiere]:
        return self.run("get_my_season_premieres", **kwargs)

    def get_movies(self, **kwargs: Any) -> List[MoviePremiere]:
        return self.run("get_movies", **kwargs)

    def get_my_movies(self, **kwargs: Any) -> List[MoviePremiere]:
        return self.run("get_my_movies", **kwargs)

    def get_dvd_releases(self, **kwargs: Any) -> List[MoviePremiere]:
        return self.run("get_dvd_releases", **kwargs)

    def get_my_dvd_releases(self, **kwargs: Any) -> List[MoviePremiere]:
        return self.run("get_my_dvd_releases", **kwargs)
Exemplo n.º 9
0
    TraktList,
    TrendingShow,
    UpdatedShow,
    User,
)
from trakt.core.paths.suite_interface import SuiteInterface
from trakt.core.paths.validators import (
    COMMON_FILTERS,
    SHOWS_FILTERS,
    AuthRequiredValidator,
    PerArgValidator,
    Validator,
    is_date,
)

ID_VALIDATOR = PerArgValidator("id", lambda i: isinstance(i, (int, str)))

PROGRESS_VALIDATORS: List[Validator] = [
    AuthRequiredValidator(),
    ID_VALIDATOR,
    PerArgValidator("hidden", lambda t: isinstance(t, bool)),
    PerArgValidator("specials", lambda t: isinstance(t, bool)),
    PerArgValidator("count_specials", lambda t: isinstance(t, bool)),
    PerArgValidator("last_activity", lambda t: t in {"collected", "watched"}),
]

if TYPE_CHECKING:  # pragma: no cover
    from trakt.core.executors import PaginationIterator


class ShowsI(SuiteInterface):
Exemplo n.º 10
0
from typing import List, Union

from trakt.core.models import Person, TraktList
from trakt.core.paths.endpoint_mappings.movies import LIST_SORT_VALUES, LIST_TYPE_VALUES
from trakt.core.paths.path import Path
from trakt.core.paths.response_structs import MovieCredits, ShowCredits
from trakt.core.paths.suite_interface import SuiteInterface
from trakt.core.paths.validators import PerArgValidator

PERSON_ID_VALIDATOR = PerArgValidator("id",
                                      lambda c: isinstance(c, (int, str)))


class PeopleI(SuiteInterface):
    name = "people"

    paths = {
        "get_person":
        Path(
            "people/!id",
            Person,
            validators=[PERSON_ID_VALIDATOR],
            extended=["full"],
            cache_level="basic",
        ),
        "get_movie_credits":
        Path(
            "people/!id/movies",
            MovieCredits,
            validators=[PERSON_ID_VALIDATOR],
            extended=["full"],
Exemplo n.º 11
0
class SearchI(SuiteInterface):
    name = "search"

    paths = {
        "text_query":
        Path(  # type: ignore
            "search/!type",
            [SearchResult],
            extended=["full"],
            filters=ALL_FILTERS,
            pagination=True,
            validators=[
                PerArgValidator(
                    "type",
                    lambda t: all(x in MEDIA_TYPES for x in t.split(","))),
                PerArgValidator("query", lambda q: isinstance(q, str) and q),
                PerArgValidator(
                    "fields",
                    lambda f: all(x in POSSIBLE_FIELDS for x in f.split(","))),
            ],
            qargs=["fields"],
            cache_level="basic",
        ),
        "id_lookup":
        Path(  # type: ignore
            "search/!id_type/!id",
            [SearchResult],
            extended=["full"],
            filters=ALL_FILTERS,
            pagination=True,
            validators=[
                PerArgValidator("id", lambda t: isinstance(t, (int, str))),
                PerArgValidator("id_type", lambda it: it in ID_TYPES),
                PerArgValidator(
                    "type",
                    lambda f: all(x in MEDIA_TYPES for x in f.split(","))),
            ],
            qargs=["type"],
            cache_level="basic",
        ),
    }

    def text_query(self,
                   type: Union[str, List[str]],
                   query: str,
                   fields: Optional[Union[str, List[str]]] = None,
                   **kwargs) -> PaginationIterator[SearchResult]:
        type = [type] if isinstance(type, str) else type
        type = ",".join(type)
        req = {"type": type, "query": query}

        if fields:
            fields = [fields] if isinstance(fields, str) else fields
            req["fields"] = ",".join(fields)

        return self.run("text_query", **kwargs, **req)

    def id_lookup(self,
                  id_type: str,
                  id: Union[str, int],
                  type: Optional[Union[str, List[str]]] = None,
                  **kwargs) -> PaginationIterator[SearchResult]:
        req = {"id_type": id_type, "id": id}

        if type:
            type = [type] if isinstance(type, str) else type
            req["type"] = ",".join(type)

        return self.run("id_lookup", **kwargs, **req)
Exemplo n.º 12
0
from typing import Any, Dict, Optional, Union

from trakt.core.exceptions import ArgumentError
from trakt.core.models import Episode, Movie
from trakt.core.paths.path import Path
from trakt.core.paths.response_structs import EpisodeScrobble, MovieScrobble, Show
from trakt.core.paths.suite_interface import SuiteInterface
from trakt.core.paths.validators import AuthRequiredValidator, PerArgValidator

PROGRESS_VALIDATOR = PerArgValidator(
    "progress", lambda p: isinstance(p, (int, float)) and 100 >= p >= 0
)


class ScrobbleI(SuiteInterface):
    name = "scrobble"

    base_paths = {
        "start_scrobble_movie": ["start", MovieScrobble],
        "start_scrobble_episode": ["start", EpisodeScrobble],
        "pause_scrobble_movie": ["pause", MovieScrobble],
        "pause_scrobble_episode": ["pause", EpisodeScrobble],
        "stop_scrobble_movie": ["stop", MovieScrobble],
        "stop_scrobble_episode": ["stop", EpisodeScrobble],
    }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for k, r in self.base_paths.items():
            self.paths[k] = self._make_path(*r)
Exemplo n.º 13
0
from typing import Any, Dict, Optional, Union

from trakt.core.decorators import auth_required
from trakt.core.exceptions import ArgumentError
from trakt.core.models import Episode, Movie
from trakt.core.paths.path import Path
from trakt.core.paths.response_structs import (
    EpisodeCheckin,
    MovieCheckin,
    Sharing,
    Show,
)
from trakt.core.paths.suite_interface import SuiteInterface
from trakt.core.paths.validators import AuthRequiredValidator, PerArgValidator

MESSAGE_VALIDATOR = PerArgValidator("message", lambda m: isinstance(m, str))


class CheckinI(SuiteInterface):
    name = "checkin"

    paths = {
        "delete_active_checkins": Path(
            "checkin", {}, methods="DELETE", validators=[AuthRequiredValidator()]
        ),
        "check_into_episode": Path(
            "checkin",
            EpisodeCheckin,
            methods="POST",
            validators=[AuthRequiredValidator(), MESSAGE_VALIDATOR],
        ),
Exemplo n.º 14
0
from typing import TYPE_CHECKING, Any, List

from trakt.core.paths.path import Path
from trakt.core.paths.response_structs import (
    Certification,
    Country,
    Genre,
    Language,
    ListResponse,
    Network,
)
from trakt.core.paths.suite_interface import SuiteInterface
from trakt.core.paths.validators import PerArgValidator

TYPE_MOVIES_SHOWS = PerArgValidator("type", lambda t: t in {"shows", "movies"})

if TYPE_CHECKING:  # pragma: no cover
    from trakt.core.executors import PaginationIterator


class CountriesI(SuiteInterface):
    name = "countries"

    paths = {
        "get_countries": Path(
            "countries/!type",
            [Country],
            aliases=["get_countries", ""],
            validators=[TYPE_MOVIES_SHOWS],
            cache_level="basic",
Exemplo n.º 15
0
class SeasonsI(SuiteInterface):
    name = "seasons"

    paths = {
        "get_all_seasons":
        Path(
            "shows/!id/seasons",
            [Season],
            extended=["full", "episodes"],
            validators=[ID_VALIDATOR],
            cache_level="basic",
        ),
        "get_season":
        Path(
            "shows/!id/seasons/!season",
            [Episode],
            extended=["full", "episodes"],
            validators=[
                ID_VALIDATOR,
                SEASON_ID_VALIDATOR,
                PerArgValidator(
                    "translations",
                    lambda t: isinstance(t, str) and
                    (t == "all" or len(t) == 2),
                ),
            ],
            qargs=["translations"],
            cache_level="basic",
        ),
        "get_comments":
        Path(
            "shows/!id/seasons/!season/comments/?sort",
            [Comment],
            validators=[
                ID_VALIDATOR,
                SEASON_ID_VALIDATOR,
                PerArgValidator("sort", lambda s: s in COMMENT_SORT_VALUES),
            ],
            pagination=True,
        ),
        "get_lists":
        Path(
            "shows/!id/seasons/!season/lists/?type/?sort",
            [TraktList],
            validators=[
                ID_VALIDATOR,
                SEASON_ID_VALIDATOR,
                PerArgValidator("type", lambda t: t in LIST_TYPE_VALUES),
                PerArgValidator("sort", lambda s: s in LIST_SORT_VALUES),
            ],
            pagination=True,
        ),
        "get_ratings":
        Path(
            "shows/!id/seasons/!season/ratings",
            RatingsSummary,
            validators=[ID_VALIDATOR, SEASON_ID_VALIDATOR],
        ),
        "get_stats":
        Path(
            "shows/!id/seasons/!season/stats",
            SeasonEpisodeStats,
            validators=[ID_VALIDATOR, SEASON_ID_VALIDATOR],
        ),
        "get_users_watching":
        Path(
            "shows/!id/seasons/!season/watching",
            [User],
            extended=["full"],
            validators=[ID_VALIDATOR, SEASON_ID_VALIDATOR],
        ),
    }

    def get_all_seasons(self, *, show: Union[Show, str, int],
                        season: Union[Season, str,
                                      int], **kwargs) -> List[Season]:
        id = self._generic_get_id(show)
        season = self._generic_get_id(season)
        return self.run("get_all_seasons", **kwargs, id=id, season=season)

    def get_season(self, *, show: Union[Show, str, int],
                   season: Union[Season, str, int], **kwargs) -> List[Episode]:
        id = self._generic_get_id(show)
        season = self._generic_get_id(season)
        return self.run("get_season", **kwargs, id=id, season=season)

    def get_comments(self,
                     *,
                     show: Union[Show, str, int],
                     season: Union[Season, str, int],
                     sort: str = "newest",
                     **kwargs) -> PaginationIterator[Comment]:
        id = self._generic_get_id(show)
        season = self._generic_get_id(season)
        return self.run("get_comments",
                        **kwargs,
                        sort=sort,
                        id=id,
                        season=season)

    def get_lists(self,
                  *,
                  show: Union[Show, str, int],
                  season: Union[Season, str, int],
                  type: str = "personal",
                  sort: str = "popular",
                  **kwargs) -> PaginationIterator[TraktList]:
        id = self._generic_get_id(show)
        season = self._generic_get_id(season)
        return self.run("get_lists",
                        **kwargs,
                        type=type,
                        sort=sort,
                        id=id,
                        season=season)

    def get_ratings(self, *, show: Union[Show, str,
                                         int], season: Union[Season, str, int],
                    **kwargs) -> RatingsSummary:
        id = self._generic_get_id(show)
        season = self._generic_get_id(season)
        return self.run("get_ratings", **kwargs, id=id, season=season)

    def get_stats(self, *, show: Union[Show, str,
                                       int], season: Union[Season, str, int],
                  **kwargs) -> SeasonEpisodeStats:
        id = self._generic_get_id(show)
        season = self._generic_get_id(season)
        return self.run("get_stats", **kwargs, id=id, season=season)

    def get_users_watching(self, *, show: Union[Show, str, int],
                           season: Union[Season, str,
                                         int], **kwargs) -> List[User]:
        id = self._generic_get_id(show)
        season = self._generic_get_id(season)
        return self.run("get_users_watching", **kwargs, id=id, season=season)
Exemplo n.º 16
0
    COMMENT_SORT_VALUES,
    LIST_SORT_VALUES,
    LIST_TYPE_VALUES,
)
from trakt.core.paths.path import Path
from trakt.core.paths.response_structs import (
    RatingsSummary,
    SeasonEpisodeStats,
    Show,
    TraktList,
    User,
)
from trakt.core.paths.suite_interface import SuiteInterface
from trakt.core.paths.validators import PerArgValidator

ID_VALIDATOR = PerArgValidator("id", lambda i: isinstance(i, (int, str)))
SEASON_ID_VALIDATOR = PerArgValidator("season", lambda i: isinstance(i, int))
if TYPE_CHECKING:  # pragma: no cover
    from trakt.core.executors import PaginationIterator


class SeasonsI(SuiteInterface):
    name = "seasons"

    paths = {
        "get_all_seasons":
        Path(
            "shows/!id/seasons",
            [Season],
            extended=["full", "episodes"],
            validators=[ID_VALIDATOR],
Exemplo n.º 17
0
    CommentLiker,
    CommentResponse,
    Sharing,
)
from trakt.core.paths.suite_interface import SuiteInterface
from trakt.core.paths.validators import (
    AuthRequiredValidator,
    PerArgValidator,
    Validator,
)

if TYPE_CHECKING:  # pragma: no cover
    from trakt.core.executors import PaginationIterator

COMMENT_TEXT_VALIDATOR = PerArgValidator(
    "comment", lambda c: isinstance(c, str) and len(c.split(" ")) > 4
)
COMMENT_ID_VALIDATOR = PerArgValidator("id", lambda c: isinstance(c, int))

COMMENT_TYPES = ["all", "reviews", "shouts"]
MEDIA_TYPES = ["all", "movies", "shows", "seasons", "episodes", "lists"]

TRENDING_RECENT_UPDATED_VALIDATORS: List[Validator] = [
    PerArgValidator("comment_type", lambda c: c in COMMENT_TYPES),
    PerArgValidator("type", lambda c: c in MEDIA_TYPES),
    PerArgValidator("include_replies", lambda i: isinstance(i, bool)),
]


class CommentsI(SuiteInterface):
    name = "comments"
Exemplo n.º 18
0
class PeopleI(SuiteInterface):
    name = "people"

    paths = {
        "get_person":
        Path(
            "people/!id",
            Person,
            validators=[PERSON_ID_VALIDATOR],
            extended=["full"],
            cache_level="basic",
        ),
        "get_movie_credits":
        Path(
            "people/!id/movies",
            MovieCredits,
            validators=[PERSON_ID_VALIDATOR],
            extended=["full"],
            cache_level="basic",
        ),
        "get_show_credits":
        Path(
            "people/!id/shows",
            ShowCredits,
            validators=[PERSON_ID_VALIDATOR],
            extended=["full"],
            cache_level="basic",
        ),
        "get_lists":
        Path(
            "people/!id/lists/?type/?sort",
            [TraktList],
            validators=[
                PERSON_ID_VALIDATOR,
                PerArgValidator("type", lambda t: t in LIST_TYPE_VALUES),
                PerArgValidator("sort", lambda s: s in LIST_SORT_VALUES),
            ],
            extended=["full"],
            cache_level="basic",
        ),
    }

    def get_person(self, person: Union[Person, str, int], **kwargs) -> Person:
        id = self._get_person_id(person)
        return self.run("get_person", **kwargs, id=id)

    def get_movie_credits(self, person: Union[Person, str, int],
                          **kwargs) -> MovieCredits:
        id = self._get_person_id(person)
        return self.run("get_movie_credits", **kwargs, id=id)

    def get_show_credits(self, person: Union[Person, str, int],
                         **kwargs) -> ShowCredits:
        id = self._get_person_id(person)
        return self.run("get_show_credits", **kwargs, id=id)

    def get_lists(self, person: Union[Person, str, int],
                  **kwargs) -> List[TraktList]:
        id = self._get_person_id(person)
        return self.run("get_lists", **kwargs, id=id)

    def _get_person_id(self, p: Union[Person, int, str]) -> str:
        return str(self._generic_get_id(item=p))