1
0
mirror of https://github.com/moparisthebest/SickRage synced 2024-08-13 16:53:54 -04:00
SickRage/lib/trakt/trakt.py

77 lines
2.8 KiB
Python
Raw Normal View History

2014-11-28 17:07:26 -05:00
import requests
2015-01-25 15:14:57 -05:00
import json
from sickbeard import logger
2014-11-28 17:07:26 -05:00
from exceptions import traktException, traktAuthException, traktServerBusy
2014-11-28 17:07:26 -05:00
class TraktAPI():
2015-01-25 15:14:57 -05:00
def __init__(self, apikey, username=None, password=None, timeout=5):
2014-11-28 17:07:26 -05:00
self.username = username
self.password = password
self.timeout = timeout
2015-01-25 15:14:57 -05:00
self.api_url = 'https://api.trakt.tv/'
self.headers = {
'Content-Type': 'application/json',
'trakt-api-version': '2',
'trakt-api-key': apikey,
}
2014-11-28 17:07:26 -05:00
def validateAccount(self):
2015-01-25 15:14:57 -05:00
if hasattr(self, 'token'):
del(self.token)
data = {
'login': self.username,
'password': self.password
}
try:
resp = requests.request('POST', self.api_url+"auth/login",
headers=self.headers, data=json.dumps(data))
resp.raise_for_status()
resp = resp.json()
except (requests.HTTPError, requests.ConnectionError) as e:
if e.response.status_code == 401:
raise traktAuthException(e)
if 'token' in resp:
self.token = resp['token']
return True
return False
2014-11-28 17:07:26 -05:00
2015-01-25 15:14:57 -05:00
def traktRequest(self, path, data=None, method='GET'):
url = self.api_url + path
headers = self.headers
if not getattr(self, 'token', None):
self.validateAccount()
headers['trakt-user-login'] = self.username
headers['trakt-user-token'] = self.token
2014-11-28 17:07:26 -05:00
# request the URL from trakt and parse the result as json
try:
2015-01-25 15:14:57 -05:00
resp = requests.request(method, url, headers=headers, data=json.dumps(data) if data else [])
2014-11-28 17:07:26 -05:00
# 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:
2015-01-25 15:14:57 -05:00
if e.response.status_code == 502:
# Retry the request, cloudflare had a proxying issue
logger.log(u"Retrying trakt api request: %s" % path, logger.WARNING)
self.traktRequest(path, data, method)
elif e.response.status_code == 401:
raise traktAuthException(e)
2014-11-29 06:09:49 -05:00
elif e.response.status_code == 503:
raise traktServerBusy(e)
2014-11-28 17:07:26 -05:00
else:
raise traktException(e)
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