2014-11-28 17:07:26 -05:00
|
|
|
import requests
|
|
|
|
|
2014-11-29 06:09:49 -05:00
|
|
|
from requests.auth import HTTPBasicAuth
|
2014-11-28 17:13:06 -05:00
|
|
|
from exceptions import traktException, traktAuthException, traktServerBusy
|
2014-11-28 17:07:26 -05:00
|
|
|
|
|
|
|
class TraktAPI():
|
|
|
|
def __init__(self, apikey, username=None, password=None, use_https=False, timeout=5):
|
|
|
|
self.apikey = apikey
|
|
|
|
self.username = username
|
|
|
|
self.password = password
|
|
|
|
|
|
|
|
self.protocol = 'https://' if use_https else 'http://'
|
|
|
|
self.timeout = timeout
|
|
|
|
|
|
|
|
def validateAccount(self):
|
2014-11-29 06:09:49 -05:00
|
|
|
return self.traktRequest("account/test/%APIKEY%")
|
2014-11-28 17:07:26 -05:00
|
|
|
|
|
|
|
def traktRequest(self, url, data=None):
|
|
|
|
base_url = self.protocol + 'api.trakt.tv/%s' % url.replace('%APIKEY%', self.apikey).replace('%USER%',
|
|
|
|
self.username)
|
|
|
|
|
|
|
|
# request the URL from trakt and parse the result as json
|
|
|
|
try:
|
|
|
|
resp = requests.get(base_url,
|
2014-11-29 06:09:49 -05:00
|
|
|
auth=HTTPBasicAuth(self.username, self.password),
|
2014-11-28 17:07:26 -05:00
|
|
|
data=data if data else [])
|
|
|
|
|
|
|
|
# check for http errors and raise if any are present
|
|
|
|
resp.raise_for_status()
|
|
|
|
|
|
|
|
# convert response to json
|
|
|
|
resp = resp.json()
|
|
|
|
except (requests.HTTPError, requests.ConnectionError) as e:
|
2014-11-29 06:09:49 -05:00
|
|
|
if e.response.status_code == 401:
|
|
|
|
raise traktAuthException(e.message)
|
|
|
|
elif e.response.status_code == 503:
|
|
|
|
raise traktServerBusy(e.message)
|
2014-11-28 17:07:26 -05:00
|
|
|
else:
|
2014-11-29 06:09:49 -05:00
|
|
|
raise traktException(e.message)
|
2014-11-28 17:07:26 -05:00
|
|
|
|
|
|
|
# check and confirm trakt call did not fail
|
|
|
|
if isinstance(resp, dict) and resp.get('status', False) == 'failure':
|
|
|
|
if 'message' in resp:
|
|
|
|
raise traktException(resp['message'])
|
|
|
|
if 'error' in resp:
|
|
|
|
raise traktException(resp['error'])
|
|
|
|
else:
|
|
|
|
raise traktException('Unknown Error')
|
|
|
|
|
|
|
|
return resp
|