Skip to content

Commit

Permalink
Refactor: Add IdsMixin to replace extract_ids() utility method (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
glensc authored Dec 11, 2022
2 parents db97e2c + 137e639 commit e6df575
Show file tree
Hide file tree
Showing 7 changed files with 93 additions and 92 deletions.
5 changes: 2 additions & 3 deletions trakt/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from trakt.core import get
from trakt.movies import Movie
from trakt.tv import TVEpisode, TVShow
from trakt.utils import extract_ids, now, airs_date
from trakt.utils import now, airs_date

__author__ = 'Jon Nappi'
__all__ = ['Calendar', 'PremiereCalendar', 'MyPremiereCalendar',
Expand Down Expand Up @@ -72,7 +72,6 @@ def _build(self, data):
first_aired = cal_item.get('first_aired')
season = episode.get('season')
ep_num = episode.get('number')
extract_ids(show_data)
show_data.update(show_data)
e_data = {
'airs_at': airs_date(first_aired),
Expand All @@ -82,7 +81,7 @@ def _build(self, data):
}
self._calendar.append(
TVEpisode(show_data['title'], season, ep_num,
show_id=show_data['trakt'], **e_data)
show_id=show_data['ids']['trakt'], **e_data)
)
self._calendar = sorted(self._calendar, key=lambda x: x.airs_at)

Expand Down
49 changes: 49 additions & 0 deletions trakt/mixins.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# -*- coding: utf-8 -*-
"""Contains various MixIns"""

__author__ = 'Jon Nappi, Elan Ruusamäe'


class IdsMixin:
"""
Provides Mixin to translate "ids" array
to appropriate provider ids in base class.
This is replacement for extract_ids() utility method.
"""

__ids = ['imdb', 'slug', 'tmdb', 'trakt']

def __init__(self):
self._ids = {}

@property
def ids(self):
"""
Accessor to the trakt, imdb, and tmdb ids,
as well as the trakt.tv slug
"""
ids = {k: getattr(self, k, None) for k in self.__ids}
return {
'ids': ids
}

@property
def imdb(self):
return self._ids.get('imdb', None)

@property
def tmdb(self):
return self._ids.get('tmdb', None)

@property
def trakt(self):
return self._ids.get('trakt', None)

@property
def tvdb(self):
return self._ids.get('tvdb', None)

@property
def tvrage(self):
return self._ids.get('tvrage', None)
20 changes: 5 additions & 15 deletions trakt/movies.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
"""Interfaces to all of the Movie objects offered by the Trakt.tv API"""
from collections import namedtuple
from trakt.core import Alias, Comment, Genre, get, delete
from trakt.mixins import IdsMixin
from trakt.sync import (Scrobbler, comment, rate, add_to_history,
remove_from_history, add_to_watchlist,
remove_from_watchlist, add_to_collection,
remove_from_collection, search, checkin_media,
delete_checkin)
from trakt.people import Person
from trakt.utils import slugify, now, extract_ids
from trakt.utils import slugify, now

__author__ = 'Jon Nappi'
__all__ = ['dismiss_recommendation', 'get_recommended_movies', 'genres',
Expand Down Expand Up @@ -36,7 +37,6 @@ def get_recommended_movies():
data = yield 'recommendations/movies'
movies = []
for movie in data:
extract_ids(movie)
movies.append(Movie(**movie))
yield movies

Expand Down Expand Up @@ -71,7 +71,6 @@ def updated_movies(timestamp=None):
to_ret = []
for movie in data:
mov = movie.pop('movie')
extract_ids(mov)
mov.update({'updated_at': movie.pop('updated_at')})
to_ret.append(Movie(**mov))
yield to_ret
Expand All @@ -81,7 +80,7 @@ def updated_movies(timestamp=None):
'note', 'release_type'])


class Movie:
class Movie(IdsMixin):
"""A Class representing a Movie object"""
def __init__(self, title, year=None, slug=None, **kwargs):
super().__init__()
Expand All @@ -93,13 +92,13 @@ def __init__(self, title, year=None, slug=None, **kwargs):
else:
self.slug = slug or slugify(self.title)

self.released = self.tmdb_id = self.imdb_id = self.duration = None
self.trakt = self.trakt_id = self.tagline = self.overview = self.runtime = None
self.updated_at = self.trailer = self.homepage = self.rating = None
self.votes = self.language = self.available_translations = None
self.genres = self.certification = None
self._comments = self._images = self._aliases = self._people = None
self._ratings = self._releases = self._translations = None
self.tmdb_id = self.imdb_id = None # @deprecated: unused
self.trakt_id = None # @deprecated: unused

if len(kwargs) > 0:
self._build(kwargs)
Expand All @@ -125,7 +124,6 @@ def _get(self):

def _build(self, data):
"""Build this :class:`Movie` object with the data in *data*"""
extract_ids(data)
for key, val in data.items():
if hasattr(self, '_' + key):
setattr(self, '_' + key, val)
Expand Down Expand Up @@ -186,14 +184,6 @@ def crew(self):
"""All of the crew members that worked on this :class:`Movie`"""
return [p for p in self.people if getattr(p, 'job')]

@property
def ids(self):
"""Accessor to the trakt, imdb, and tmdb ids, as well as the trakt.tv
slug
"""
return {'ids': {'trakt': self.trakt, 'slug': self.slug,
'imdb': self.imdb, 'tmdb': self.tmdb}}

@property
@get
def images(self):
Expand Down
18 changes: 6 additions & 12 deletions trakt/people.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
# -*- coding: utf-8 -*-
"""Interfaces to all of the People objects offered by the Trakt.tv API"""
from trakt.core import get
from trakt.mixins import IdsMixin
from trakt.sync import search
from trakt.utils import extract_ids, slugify
from trakt.utils import slugify

__author__ = 'Jon Nappi'
__all__ = ['Person', 'ActingCredit', 'CrewCredit', 'Credits', 'MovieCredits',
'TVCredits']


class Person:
class Person(IdsMixin):
"""A Class representing a trakt.tv Person such as an Actor or Director"""
def __init__(self, name, slug=None, **kwargs):
super().__init__()
self.name = name
self.biography = self.birthplace = self.tmdb_id = self.birthday = None
self.biography = self.birthplace = self.birthday = None
self.death = self.homepage = None
self.job = self.character = self._images = self._movie_credits = None
self._tv_credits = None
self.slug = slug or slugify(self.name)
self.tmdb_id = None # @deprecated: unused

if len(kwargs) > 0:
self._build(kwargs)
Expand Down Expand Up @@ -59,22 +62,13 @@ def _get(self):
self._build(data)

def _build(self, data):
extract_ids(data)
for key, val in data.items():
try:
setattr(self, key, val)
except AttributeError as ae:
if not hasattr(self, '_' + key):
raise ae

@property
def ids(self):
"""Accessor to the trakt, imdb, and tmdb ids, as well as the trakt.tv
slug
"""
return {'ids': {'trakt': self.trakt, 'slug': self.slug,
'imdb': self.imdb, 'tmdb': self.tmdb}}

@property
@get
def images(self):
Expand Down
8 changes: 1 addition & 7 deletions trakt/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from deprecated import deprecated

from trakt.core import get, post, delete
from trakt.utils import slugify, extract_ids, timestamp
from trakt.utils import slugify, timestamp


__author__ = 'Jon Nappi'
Expand Down Expand Up @@ -211,7 +211,6 @@ def get_search_results(query, search_type=None, slugify_query=False):
# need to import Scrobblers
results = []
for media_item in data:
extract_ids(media_item)
result = SearchResult(media_item['type'], media_item['score'])
if media_item['type'] == 'movie':
from trakt.movies import Movie
Expand Down Expand Up @@ -280,15 +279,11 @@ def search_by_id(query, id_type='imdb', media_type=None, slugify_query=False):
query=query, source=source, media_type=media_type)
data = yield uri

for media_item in data:
extract_ids(media_item)

results = []
for d in data:
if 'episode' in d:
from trakt.tv import TVEpisode
show = d.pop('show')
extract_ids(d['episode'])
results.append(TVEpisode(show.get('title', None),
show_id=show['ids'].get('trakt'),
**d.pop('episode')))
Expand Down Expand Up @@ -342,7 +337,6 @@ def get_watchlist(list_type=None, sort=None):
if 'episode' in d:
from trakt.tv import TVEpisode
show = d.pop('show')
extract_ids(d['episode'])
results.append(TVEpisode(show.get('title', None),
show_id=show.get('trakt', None),
**d['episode']))
Expand Down
46 changes: 14 additions & 32 deletions trakt/tv.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@

from trakt.core import Airs, Alias, Comment, Genre, delete, get
from trakt.errors import NotFoundException
from trakt.mixins import IdsMixin
from trakt.sync import (Scrobbler, rate, comment, add_to_collection,
add_to_watchlist, add_to_history, remove_from_history,
remove_from_collection, remove_from_watchlist, search,
checkin_media, delete_checkin)
from trakt.utils import slugify, extract_ids, airs_date
from trakt.utils import slugify, airs_date
from trakt.people import Person

__author__ = 'Jon Nappi'
Expand Down Expand Up @@ -197,15 +198,15 @@ def anticipated_shows(page=1, limit=10, extended=None):
yield [TVShow(**show['show']) for show in data]


class TVShow:
class TVShow(IdsMixin):
"""A Class representing a TV Show object."""

def __init__(self, title='', slug=None, **kwargs):
super().__init__()
self.media_type = 'shows'
self.top_watchers = self.top_episodes = self.year = self.tvdb = None
self.imdb = self.genres = self.certification = self.network = None
self.trakt = self.tmdb = self._aliases = self._comments = None
self.top_watchers = self.top_episodes = self.year = None
self.genres = self.certification = self.network = None
self._aliases = self._comments = None
self._images = self._people = self._ratings = self._translations = None
self._seasons = None
self._last_episode = self._next_episode = None
Expand All @@ -219,6 +220,9 @@ def __init__(self, title='', slug=None, **kwargs):

@property
def slug(self):
if self._ids.get('slug', None) is not None:
return self._ids['slug']

if self._slug is not None:
return self._slug

Expand All @@ -244,7 +248,6 @@ def _get(self):
self._build(data)

def _build(self, data):
extract_ids(data)
for key, val in data.items():
if hasattr(self, '_' + key):
setattr(self, '_' + key, val)
Expand Down Expand Up @@ -363,16 +366,6 @@ def crew(self):
"""All of the crew members that worked on this :class:`TVShow`"""
return [p for p in self.people if getattr(p, 'job')]

@property
def ids(self):
"""Accessor to the trakt, imdb, and tmdb ids, as well as the trakt.tv
slug
"""
return {'ids': {
'trakt': self.trakt, 'slug': self.slug, 'imdb': self.imdb,
'tmdb': self.tmdb, 'tvdb': self.tvdb
}}

@property
@get
def images(self):
Expand Down Expand Up @@ -434,8 +427,6 @@ def seasons(self):
data = yield self.ext + '/seasons?extended=episodes'
self._seasons = []
for season in data:
extract_ids(season)

# Prepare episodes
episodes = []
for ep in season.pop('episodes', []):
Expand All @@ -447,6 +438,7 @@ def seasons(self):
number = season.pop('number')
season = TVSeason(self.title, number, self.slug, **season)
self._seasons.append(season)

yield self._seasons

@property
Expand Down Expand Up @@ -562,7 +554,7 @@ def __str__(self):
__repr__ = __str__


class TVSeason:
class TVSeason(IdsMixin):
"""Container for TV Seasons"""

def __init__(self, show, season=1, slug=None, **kwargs):
Expand Down Expand Up @@ -702,7 +694,7 @@ def __len__(self):
__repr__ = __str__


class TVEpisode:
class TVEpisode(IdsMixin):
"""Container for TV Episodes"""

def __init__(self, show, season, number=-1, **kwargs):
Expand All @@ -713,8 +705,8 @@ def __init__(self, show, season, number=-1, **kwargs):
self.number = number
self.overview = self.title = self.year = self.number_abs = None
self.first_aired = self.last_updated = None
self.trakt = self.tmdb = self.tvdb = self.imdb = None
self.tvrage = self._stats = self._images = self._comments = None
self.runtime = None
self._stats = self._images = self._comments = None
self._translations = self._ratings = None
if len(kwargs) > 0:
self._build(kwargs)
Expand All @@ -732,7 +724,6 @@ def _get(self):

def _build(self, data):
"""Build this :class:`TVEpisode` object with the data in *data*"""
extract_ids(data)
for key, val in data.items():
if hasattr(self, '_' + key):
setattr(self, '_' + key, val)
Expand Down Expand Up @@ -782,15 +773,6 @@ def search(title, year=None):
"""
return search(title, search_type='episode', year=year)

@property
def ids(self):
"""Accessor to the trakt, imdb, and tmdb ids, as well as the trakt.tv
slug
"""
return {'ids': {
'trakt': self.trakt, 'imdb': self.imdb, 'tmdb': self.tmdb
}}

@property
@get
def images(self):
Expand Down
Loading

0 comments on commit e6df575

Please sign in to comment.