Skip to content

Commit 197ce16

Browse files
committed
switch over to urllib for API calls
1 parent 4f08246 commit 197ce16

File tree

4 files changed

+42
-36
lines changed

4 files changed

+42
-36
lines changed

addon.xml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
<requires>
77
<import addon="xbmc.python" version="3.0.0"/>
88
<import addon="xbmc.metadata" version="2.1.0"/>
9-
<import addon="script.module.requests" version="2.22.0+matrix.1" />
109
</requires>
1110
<extension point="xbmc.metadata.scraper.tvshows" library="main.py"/>
1211
<extension point="xbmc.addon.metadata">

libs/api_utils.py

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,10 @@
2020
from __future__ import absolute_import, unicode_literals
2121

2222
import json
23+
from urllib.request import Request, urlopen
24+
from urllib.error import URLError
25+
from urllib.parse import urlencode
2326
from pprint import pformat
24-
import requests
25-
from requests.exceptions import HTTPError
2627
from . import settings
2728
from .utils import logger
2829
try:
@@ -31,11 +32,11 @@
3132
except ImportError:
3233
pass
3334

34-
SESSION = requests.Session()
35+
HEADERS = {}
3536

3637

3738
def set_headers(headers):
38-
SESSION.headers.update(headers)
39+
HEADERS.update(headers)
3940

4041

4142
def load_info(url, params=None, default=None, resp_type = 'json'):
@@ -49,18 +50,24 @@ def load_info(url, params=None, default=None, resp_type = 'json'):
4950
:resp_type: what to return to the calling function
5051
:return: API response or default on error
5152
"""
52-
logger.debug('Calling URL "{}" with params {}'.format(url, params))
53+
if params:
54+
url = url + '?' + urlencode(params)
55+
logger.debug('Calling URL "{}"'.format(url))
56+
req = Request(url, headers=HEADERS)
5357
try:
54-
response = SESSION.get(url, params=params)
55-
except HTTPError as exc:
56-
logger.error('the site returned an error: {}'.format(exc))
58+
response = urlopen(req)
59+
except URLError as e:
60+
if hasattr(e, 'reason'):
61+
logger.debug('failed to reach the remote site\nReason: {}'.format(e.reason))
62+
elif hasattr(e, 'code'):
63+
logger.debug('remote site unable to fulfill the request\nError code: {}'.format(e.code))
5764
response = None
5865
if response is None:
5966
resp = default
6067
elif resp_type.lower() == 'json':
61-
resp = response.json()
68+
resp = json.loads(response.read().decode('utf-8'))
6269
else:
63-
resp = response.text
70+
resp = response.read().decode('utf-8')
6471
if settings.VERBOSELOG:
6572
logger.debug('the api response:\n{}'.format(pformat(resp)))
6673
return resp

libs/tmdb.py

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -34,19 +34,20 @@
3434
('User-Agent', 'Kodi TV Show scraper by Team Kodi; contact pkscout@kodi.tv'),
3535
('Accept', 'application/json'),
3636
)
37-
api_utils.set_headers(HEADERS)
37+
api_utils.set_headers(dict(HEADERS))
3838

39-
BASE_URL = 'https://api.themoviedb.org/3/{}?api_key=%s&language=%s' % (settings.TMDB_CLOWNCAR, settings.LANG)
39+
TMDB_PARAMS = {'api_key': settings.TMDB_CLOWNCAR, 'language': settings.LANG}
40+
BASE_URL = 'https://api.themoviedb.org/3/{}'
4041
EPISODE_GROUP_URL = BASE_URL.format('tv/episode_group/{}')
4142
SEARCH_URL = BASE_URL.format('search/tv')
4243
FIND_URL = BASE_URL.format('find/{}')
4344
SHOW_URL = BASE_URL.format('tv/{}')
4445
SEASON_URL = BASE_URL.format('tv/{}/season/{}')
4546
EPISODE_URL = BASE_URL.format('tv/{}/season/{}/episode/{}')
47+
FANARTTV_URL = 'https://webservice.fanart.tv/v3/tv/{}'
48+
FANARTTV_PARAMS = {'api_key': settings.FANARTTV_CLOWNCAR}
4649
if settings.FANARTTV_CLIENTKEY:
47-
FANARTTV_URL = 'https://webservice.fanart.tv/v3/tv/{}?api_key=%s&client_key=%s' % (settings.FANARTTV_CLOWNCAR, settings.FANARTTV_CLIENTKEY)
48-
else:
49-
FANARTTV_URL = 'https://webservice.fanart.tv/v3/tv/{}?api_key=%s' % settings.FANARTTV_CLOWNCAR
50+
FANARTTV_PARAMS['client_key'] = settings.FANARTTV_CLIENTKEY
5051

5152

5253
def search_show(title, year=None):
@@ -58,23 +59,23 @@ def search_show(title, year=None):
5859
: param year: the year to search (optional)
5960
:return: a list with found TV shows
6061
"""
62+
params = TMDB_PARAMS
6163
results = []
6264
ext_media_id = data_utils.parse_media_id(title)
6365
if ext_media_id:
6466
logger.debug('using %s of %s to find show' % (ext_media_id['type'], ext_media_id['title']))
6567
if ext_media_id['type'] == 'tmdb_id':
6668
search_url = SHOW_URL.format(ext_media_id['title'])
67-
params = {}
6869
else:
6970
search_url = FIND_URL.format(ext_media_id['title'])
70-
params = {'external_source':ext_media_id['type']}
71+
params['external_source'] = ext_media_id['type']
7172
else:
7273
logger.debug('using title of %s to find show' % title)
7374
search_url = SEARCH_URL
74-
params = {'query': title}
75+
params['query'] = title
7576
if year:
76-
params.update({'first_air_date_year': str(year)})
77-
resp = api_utils.load_info(search_url, params)
77+
params['first_air_date_year'] = str(year)
78+
resp = api_utils.load_info(search_url, params=params)
7879
if resp is not None:
7980
if ext_media_id:
8081
if ext_media_id['type'] == 'tmdb_id':
@@ -96,7 +97,7 @@ def load_episode_list(show_info, season_map, ep_grouping):
9697
if ep_grouping is not None:
9798
logger.debug('Getting episodes with episode grouping of ' + ep_grouping)
9899
episode_group_url = EPISODE_GROUP_URL.format(ep_grouping)
99-
custom_order = api_utils.load_info(episode_group_url)
100+
custom_order = api_utils.load_info(episode_group_url, params=TMDB_PARAMS)
100101
if custom_order is not None:
101102
show_info['seasons'] = []
102103
season_num = 1
@@ -143,19 +144,17 @@ def load_show_info(show_id, ep_grouping=None):
143144
if show_info is None:
144145
logger.debug('no cache file found, loading from scratch')
145146
show_url = SHOW_URL.format(show_id)
146-
params = {}
147+
params = TMDB_PARAMS
147148
params['append_to_response'] = 'credits,content_ratings,external_ids,images'
148149
params['include_image_language'] = '%s,en,null' % settings.LANG[0:2]
149-
show_info = api_utils.load_info(show_url, params)
150+
show_info = api_utils.load_info(show_url, params=params)
150151
if show_info is None:
151152
return None
152153
season_map = {}
154+
params['append_to_response'] = 'credits,images'
153155
for season in show_info.get('seasons', []):
154156
season_url = SEASON_URL.format(show_id, season['season_number'])
155-
params = {}
156-
params['append_to_response'] = 'credits,images'
157-
params['include_image_language'] = '%s,en,null' % settings.LANG[0:2]
158-
season_info = api_utils.load_info(season_url, params, default={})
157+
season_info = api_utils.load_info(season_url, params=params, default={})
159158
season_info['images'] = _sort_image_types(season_info.get('images', {}))
160159
season_map[str(season['season_number'])] = season_info
161160
show_info = load_episode_list(show_info, season_map, ep_grouping)
@@ -197,10 +196,10 @@ def load_episode_info(show_id, episode_id):
197196
return None
198197
# this ensures we are using the season/ep from the episode grouping if provided
199198
ep_url = EPISODE_URL.format(show_info['id'], episode_info['org_seasonnum'], episode_info['org_epnum'])
200-
params = {}
199+
params = TMDB_PARAMS
201200
params['append_to_response'] = 'credits,external_ids,images'
202201
params['include_image_language'] = '%s,en,null' % settings.LANG[0:2]
203-
ep_return = api_utils.load_info(ep_url, params)
202+
ep_return = api_utils.load_info(ep_url, params=params)
204203
if ep_return is None:
205204
return None
206205
ep_return['images'] = _sort_image_types(ep_return.get('images', {}))
@@ -256,7 +255,7 @@ def load_fanarttv_art(show_info):
256255
break
257256
if tvdb_id and artwork_enabled:
258257
fanarttv_url = FANARTTV_URL.format(tvdb_id)
259-
artwork = api_utils.load_info(fanarttv_url)
258+
artwork = api_utils.load_info(fanarttv_url, params=FANARTTV_PARAMS)
260259
if artwork is None:
261260
return show_info
262261
for fanarttv_type, tmdb_type in settings.FANARTTV_MAPPING.items():

libs/traktratings.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,20 +36,21 @@
3636
('trakt-api-version', '2'),
3737
('Content-Type', 'application/json'),
3838
)
39-
api_utils.set_headers(HEADERS)
39+
api_utils.set_headers(dict(HEADERS))
4040

41-
BASE_URL = 'https://api.trakt.tv/shows/{}'
42-
SHOW_URL = BASE_URL + '?extended=full'
43-
EP_URL = BASE_URL + '/seasons/{}/episodes/{}/ratings'
41+
SHOW_URL = 'https://api.trakt.tv/shows/{}'
42+
EP_URL = SHOW_URL + '/seasons/{}/episodes/{}/ratings'
4443

4544

4645
def get_details(imdb_id, season=None, episode=None):
4746
result = {}
4847
if season and episode:
4948
url = EP_URL.format(imdb_id, season, episode)
49+
params = None
5050
else:
5151
url = SHOW_URL.format(imdb_id)
52-
resp = api_utils.load_info(url, default={})
52+
params = {'extended': 'full'}
53+
resp = api_utils.load_info(url, params=params, default={})
5354
rating =resp.get('rating')
5455
votes = resp.get('votes')
5556
if votes and rating:

0 commit comments

Comments
 (0)