forked from john-tornblom/plugin.video.tv3play.dk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mtgapi.py
270 lines (221 loc) · 7.55 KB
/
mtgapi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Simple MTGx API implementation.
"""
try:
import json
except ImportError:
import simplejson as json
import os
import sys
import urllib
import urllib2
try:
import xbmc
except:
class xbmc(object):
@staticmethod
def log(message):
sys.stdout.write(message)
sys.stdout.write('\n')
class JsonApiException(Exception):
pass
class JsonApi(object):
def call(self, url, arguments=None, queryParams=None):
"""
Build URL and call remote API
"""
if '{' in url:
url = url.format(**arguments)
if queryParams:
url += '?' + urllib.urlencode(queryParams)
if "limit" and "channel=9000" in url:
url += "&limit=100"
xbmc.log('Calling API: {0}'.format(url))
content = self._http_request(url)
if content is not None and content != '':
try:
ret = json.loads(content.decode('iso-8859-1').encode('utf-8'))
return ret
except Exception as ex:
raise JsonApiException(ex)
else:
return []
def _http_request(self, url):
try:
request = urllib2.Request(url, headers={
'user-agent': MtgApi.USER_AGENT,
'Content-Type': 'application/vnd.api+json'
})
connection = urllib2.urlopen(request)
content = connection.read()
connection.close()
return content
except Exception as ex:
raise JsonApiException(ex)
class MtgApi(object):
"""
API implementation for the MTG tv services
"""
CONFIG_URL = "https://playapi.mtgx.tv/v3/config/{channel}"
CHANNELS_URL = "https://playapi.mtgx.tv/v3/channels?country={country}"
ROOT_CHANNELS = {'no': 1550,
'se': 1209,
'dk': 3687,
'ee': 1375,
'lv': 1482,
'bg': 1933,
'lt': 3000}
REGIONS = ROOT_CHANNELS.keys()
USER_AGENT = "Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) " \
"AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10"
def __init__(self, region):
xbmc.log('Starting MtgApi for region {0}'.format(region))
self._json_api = JsonApi()
self._config = None
self._region = region or MtgApi.REGIONS[0]
self._load_config()
def _load_config(self):
"""
Loads and caches the configuration
"""
if not self._config:
self._config = self._json_api.call(MtgApi.CONFIG_URL, {'channel': MtgApi.ROOT_CHANNELS[self._region]})
def get_channels(self):
"""
Returns a dict of channels. Key is id, value is name
"""
chlist = self._json_api.call(MtgApi.CHANNELS_URL, {'country': self._region})
return {ch['id']: ch['name']
for ch in chlist['_embedded']['channels']}
def get_channel_icon(self, channel_id):
"""
Returns a url to the channel icon
"""
url = self._config['_links']['channel_bug']['href'].format(channel=channel_id)
url = url.replace("https","http")
return url
def get_categories(self):
"""
Returns a dict of categories. Key is id, value is name
"""
formats = next(view for view in self._config['views'] if view['name'] == 'formats')
categories = formats['filters']['categories']
ret = {}
for category in categories:
if ',' in category['value']:
continue
ret[category['value']] = category['title']
return ret
def get_shows(self, channel_id):
"""
Returns a list of shows
channel_id: a single id of a channel or a list of id's
"""
if not isinstance(channel_id, list):
channel_id = [channel_id]
formats = next(view for view in self._config['views'] if view['name'] == 'formats')
try:
url = formats['_links']['url']['href']
except KeyError:
return []
shows = []
while url:
data = self._json_api.call(url,
{'channels': ','.join(channel_id),
'categories': ''})
if '_embedded' not in data:
break
for show in data['_embedded']['formats']:
shows.append(show)
try:
url = data['_links']['next']['href']
except KeyError:
url = None
return shows
def get_seasons(self, show):
"""
Return a list of seasons for a given show
"""
if isinstance(show, str):
url = show
else:
try:
url = show['_links']['seasons']['href']
except KeyError:
return []
seasons = []
while url:
data = self._json_api.call(url)
for season in data['_embedded']['seasons']:
seasons.append(season)
try:
url = data['_links']['next']['href']
except KeyError:
url = None
return seasons
def get_episodes(self, season):
"""
Returns a list of episodes for a given season
"""
if isinstance(season, str):
url = season
else:
try:
url = season['_links']['videos']['href']
except KeyError:
return []
episodes = []
while url:
data = self._json_api.call(url)
for episode in data['_embedded']['videos']:
episodes.append(episode)
try:
url = data['_links']['next']['href']
except KeyError:
url = None
return episodes
def get_streams(self, episode):
"""
Returns a list of streams for a given episode
"""
try:
url = episode['_links']['stream']['href']
except KeyError:
return []
data = self._json_api.call(url)
try:
return data['streams']
except:
return {}
@staticmethod
def test():
"""
Runs a series of tests on the API
"""
sys.stdout.write(u'Regions: {0}\n'.format(", ".join(MtgApi.REGIONS)).encode('utf-8'))
region = 'no'
sys.stdout.write(u'Testing region: {0}\n'.format(region).encode('utf-8'))
api = MtgApi(region)
channels = api.get_channels();
for channel_id, channel_name in channels.iteritems():
sys.stdout.write(u' Channel: {0}\n'.format(channel_name).encode('utf-8'))
shows = api.get_shows(channel_id)
for show in shows:
sys.stdout.write(u' Show: {0}\n'.format(show['title']).encode('utf-8'))
seasons = api.get_seasons(show)
for season in seasons:
sys.stdout.write(u' Season: {0}\n'.format(season['title']).encode('utf-8'))
for episode in api.get_episodes(season):
sys.stdout.write(u' Episode: {0}\n'.format(episode['title']).encode('utf-8'))
api.get_streams(episode)
break
break
break
break
class MtgApiException(Exception):
pass
if __name__ == '__main__':
MtgApi.test()
sys.exit(0)