Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add assorted authenticated methods.

This adds methods for setting ratings and favorite status against
movies, as well as pulling lists of movies for which those have been
set. This adds a bypass in the cache to not operate on anything with a
lifetime of '0'.
(cherry picked from commit fb7c7cd)
  • Loading branch information...
commit 81dabbc40b0b3fdc1b542a9d7fe9da74f0fbbefd 1 parent 9439a82
@wagnerrp wagnerrp authored
View
2  mythtv/bindings/python/tmdb3/tmdb3/cache.py
@@ -102,6 +102,8 @@ def __call__(self, *args, **kwargs):
raise TMDBCacheError('Cache.Cached must be provided a '+\
'callable object.')
return self.__class__(self.cache, self.callback, args[0])
+ elif self.inst.lifetime == 0:
+ return self.func(*args, **kwargs)
else:
key = self.callback()
data = self.cache.get(key)
View
6 mythtv/bindings/python/tmdb3/tmdb3/request.py
@@ -81,11 +81,17 @@ def new(self, **kwargs):
obj.lifetime = self.lifetime
return obj
+ def add_data(self, data):
+ """Provide data to be sent with POST."""
+ urllib2.Request.add_data(self, urlencode(data))
+
def open(self):
"""Open a file object to the specified URL."""
try:
if DEBUG:
print 'loading '+self.get_full_url()
+ if self.has_data():
+ print ' '+self.get_data()
return urllib2.urlopen(self)
except urllib2.HTTPError, e:
raise TMDBHTTPError(str(e))
View
61 mythtv/bindings/python/tmdb3/tmdb3/tmdb_api.py
@@ -22,7 +22,7 @@
Preliminary API specifications can be found at
http://help.themoviedb.org/kb/api/about-3"""
-__version__="v0.5.0"
+__version__="v0.6.0"
# 0.1.0 Initial development
# 0.2.0 Add caching mechanism for API queries
# 0.2.1 Temporary work around for broken search paging
@@ -42,6 +42,7 @@
# 0.4.5 Add locale fallthrough for images and alternate titles
# 0.4.6 Add slice support for search results
# 0.5.0 Rework cache framework and improve file cache performance
+# 0.6.0 Add user authentication support
from request import set_key, Request
from util import Datapoint, Datalist, Datadict, Element
@@ -64,26 +65,22 @@ def _populate(self):
Configuration = Configuration()
class Account( Element ):
- session = Datapoint('session', initarg=1, default=None)
-
- def _populate_account(self):
- if self.session is None:
- self.session = get_session()
- return Request('account', session_id=self.session.sessionid)
+ def _populate(self):
+ return Request('account', session_id=self._session.sessionid)
- id = Datapoint('id', poller=_populate_account)
- adult = Datapoint('include_adult', poller=_populate_account)
- country = Datapoint('iso_3166_1', poller=_populate_account)
- language = Datapoint('iso_639_1', poller=_populate_account)
- name = Datapoint('name', poller=_populate_account)
- username = Datapoint('username', poller=_populate_account)
+ id = Datapoint('id')
+ adult = Datapoint('include_adult')
+ country = Datapoint('iso_3166_1')
+ language = Datapoint('iso_639_1')
+ name = Datapoint('name')
+ username = Datapoint('username')
@property
def locale(self):
return get_locale(self.language, self.country)
def __repr__(self):
- return "<{0} {1.name}>".format(self.__class__.__name__, self)
+ return '<{0} "{1.name}">'.format(self.__class__.__name__, self)
def searchMovie(query, locale=None, adult=False):
return MovieSearchResult(
@@ -342,6 +339,28 @@ def toprated(cls, locale=None):
return res
@classmethod
+ def favorites(cls, session=None):
+ if session is None:
+ session = get_session()
+ account = Account(session=session)
+ res = MovieSearchResult(
+ Request('account/{0}/favorite_movies'.format(account.id),
+ session_id=session.sessionid))
+ res._name = "Favorites"
+ return res
+
+ @classmethod
+ def ratedmovies(cls, session=None):
+ if session is None:
+ session = get_session()
+ account = Account(session=session)
+ res = MovieSearchResult(
+ Request('account/{0}/rated_movies'.format(account.id),
+ session_id=session.sessionid))
+ res._name = "Movies You Rated"
+ return res
+
+ @classmethod
def fromIMDB(cls, imdbid, locale=None):
try:
# assume string
@@ -414,6 +433,20 @@ def _populate_translations(self):
apple_trailers = Datalist('quicktime', handler=AppleTrailer, poller=_populate_trailers)
translations = Datalist('translations', handler=Translation, poller=_populate_translations)
+ def setFavorite(self, value):
+ req = Request('account/{0}/favorite'.format(Account(session=self._session).id), session_id=self._session.sessionid)
+ req.add_data({'movie_id':self.id, 'favorite':str(bool(value)).lower()})
+ req.lifetime = 0
+ req.readJSON()
+
+ def setRating(self, value):
+ if not (0 <= value <= 10):
+ raise TMDBError("Ratings must be between '0' and '10'.")
+ req = Request('movie/{0}/favorite'.format(self.id), session_id=self._session.sessionid)
+ req.lifetime = 0
+ req.add_data({'value':value})
+ req.readJSON()
+
def __repr__(self):
if self.title is not None:
s = u"'{0}'".format(self.title)
View
9 tmdb3/tmdb_auth.py
@@ -60,6 +60,7 @@ def fromIso(cls, isotime, sep='T'):
return cls(*dt)
from request import Request
+from tmdb_exceptions import *
syssession = None
@@ -89,14 +90,14 @@ def __init__(self, sessionid):
def sessionid(self):
if self._sessionid is None:
if self._authtoken is None:
- raise RuntimeError("No Auth Token to produce Session for")
+ raise TMDBError("No Auth Token to produce Session for")
# TODO: check authtokenexpiration against current time
req = Request('authentication/session/new', \
request_token=self._authtoken)
req.lifetime = 0
dat = req.readJSON()
if not dat['success']:
- raise RuntimeError("Session generation failed")
+ raise TMDBError("Session generation failed")
self._sessionid = dat['session_id']
return self._sessionid
@@ -113,13 +114,13 @@ def sessionid(self, value):
@property
def authtoken(self):
if self.authenticated:
- raise RuntimeError("Session is already authenticated")
+ raise TMDBError("Session is already authenticated")
if self._authtoken is None:
req = Request('authentication/token/new')
req.lifetime = 0
dat = req.readJSON()
if not dat['success']:
- raise RuntimeError("Auth Token request failed")
+ raise TMDBError("Auth Token request failed")
self._authtoken = dat['request_token']
self._authtokenexpiration = datetime.fromIso(dat['expires_at'])
return self._authtoken
Please sign in to comment.
Something went wrong with that request. Please try again.