forked from Pati/plugin.video.tvnow.de
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnavigation.py
384 lines (355 loc) · 17.8 KB
/
navigation.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import xbmc, xbmcgui, xbmcplugin, xbmcaddon, xbmcvfs
import requests
try:
import urllib.parse as ul
except:
import urllib as ul
import json
import datetime
import time
import re
import resources.lib.common as common
from sendung import Sendung
import tvnow
apiBase = "https://bff.apigw.tvnow.de"
formatImageURL = "https://ais.tvnow.de/tvnow/format/{fid}_formatlogo/408x229/image.jpg"
episodeImageURL = "https://ais.tvnow.de/tvnow/movie/{eid}/408x229/image.jpg"
addon_handle = int(sys.argv[1])
try:
#py2
icon_file = xbmc.translatePath(xbmcaddon.Addon().getAddonInfo('path')+'/icon.png').decode('utf-8')
except:
icon_file = xbmc.translatePath(xbmcaddon.Addon().getAddonInfo('path')+'/icon.png')
xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_NONE)
xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL)
addon = xbmcaddon.Addon()
plotEnabled = addon.getSetting('plot_enabled') == "true"
def parseDateTime(str):
try:
m = re.search(r'[A-z]+\.\s+([0-9]+).([0-9]+).([0-9]+),\s+([0-9]+):([0-9]+)', str)
if m:
return datetime.datetime(int(m.group(3)),int(m.group(2)), int(m.group(1)), int(m.group(4)), int(m.group(5)))
except:
return None
def buildDirectoryName(data):
dirName = ""
episode = data["items"][0]
if "ecommerce" in episode:
ecommerce = episode["ecommerce"]
if "teaserFormatName" in ecommerce:
dirName = ecommerce["teaserFormatName"]
if "ecommerce" in data and "rowName" in data["ecommerce"]:
dirName = "%s - %s" % (dirName, data["ecommerce"]["rowName"])
return dirName
def getEpName(episode, info):
epNameSuffix = ""
epNamePrefix = ""
epName = ""
if "ecommerce" in episode:
ecommerce = episode["ecommerce"]
if "teaserEpisodeAirtime" in ecommerce:
dt = parseDateTime(ecommerce["teaserEpisodeAirtime"])
epNameSuffix = ecommerce["teaserEpisodeAirtime"]
if dt:
info["date"] = dt.strftime('%Y-%m-%d')
info["premiered"] = dt.strftime('%Y-%m-%d')
info["aired"] = dt.strftime('%Y-%m-%d')
info["dateadded"] = str(dt)
if "teaserEpisodeNumber" in ecommerce:
epNamePrefix = ecommerce["teaserEpisodeNumber"]
if "teaserEpisodeName" in ecommerce:
epName = ecommerce["teaserEpisodeName"]
elif "teaserName" in ecommerce:
epName = ecommerce["teaserName"]
epString = ""
if epNamePrefix != "":
epString = "%s: " % epNamePrefix
if epName != "":
epString = "%s%s" % (epString, epName)
else:
epName = "%s%s" % (epString, episode['headline'])
if epNameSuffix != "":
epString = "%s (%s)" % (epString, epNameSuffix)
return epString, info
class Navigation():
def __init__(self,db):
self.db = db
self.showPremium = (addon.getSetting('premium') == "true")
self.showlive = (addon.getSetting('liveFree') == "true")
self.showLivePay = (addon.getSetting('livePay') == "true")
def getInfoLabel(self, data, movie=False):
info = {}
info['title'] = data.get('headline', '')
if not data.get('year_of_production', '') == '':
info['year'] = data.get('year_of_production', '')
if movie:
if "description" in data:
info['plot'] = data.get('description', '').replace('\n', '').strip()
elif "seo" in data:
info['plot'] = data["seo"].get('text', '').replace('\n', '').strip()
info['plot'] = re.sub('<[^<]+?>', '', info['plot'])
else:
info['plot'] = data.get('text', '').replace('\n', '').strip()
return info
def login(self):
keyboard = xbmc.Keyboard('', 'E-Mail-Adresse')
keyboard.doModal()
if keyboard.isConfirmed() and keyboard.getText():
username = keyboard.getText()
password = self.setLoginPW()
if password != '':
TvNow = tvnow.TvNow()
if TvNow.sendLogin(username, password):
xbmcgui.Dialog().notification('Login erfolgreich', 'Angemeldet als "' + username + '".', icon=xbmcgui.NOTIFICATION_INFO)
return True
else:
return False
def search(self):
keyboard = xbmc.Keyboard('', 'Suchbegriff')
keyboard.doModal()
if keyboard.isConfirmed() and keyboard.getText():
query = keyboard.getText()
if query != '':
self.listSearchResult(query)
def setLoginPW(self):
keyboard = xbmc.Keyboard('', 'Passwort', True)
keyboard.doModal(60000)
if keyboard.isConfirmed() and keyboard.getText() and len(keyboard.getText()) >= 6:
password = keyboard.getText()
return password
return ''
def listDictCategories(self, dicttype=""):
d = self.db.getDict(dicttype)
for item in sorted(d.keys()):
url = common.build_url({'action': 'listDict'.encode('utf-8'), 'id': item, 'dict'.encode('utf-8') : dicttype.encode('utf-8')})
li = xbmcgui.ListItem(item)
li.setArt({'icon': icon_file})
xbmcplugin.addDirectoryItem(handle=addon_handle, url=url,
listitem=li, isFolder=True)
xbmcplugin.endOfDirectory(addon_handle, cacheToDisc=True)
def listDict(self, dictkey,dicttype=""):
d = self.db.getDict(dicttype)
for item in d[dictkey]:
url = common.build_url({'action': 'listPage'.encode('utf-8'), 'id': item.sid.encode('utf-8')})
li = xbmcgui.ListItem(item.title)
sid = item.sid.split("-")[-1]
imgurl = formatImageURL.replace("{fid}",str(sid))
li.setArt({'poster': imgurl, 'icon': icon_file})
xbmcplugin.addDirectoryItem(handle=addon_handle, url=url,
listitem=li, isFolder=True)
xbmcplugin.endOfDirectory(addon_handle, cacheToDisc=True)
def listLiveTV(self):
tvNow = tvnow.TvNow()
if tvNow.login():
url = apiBase + "/epg?isKids=false"
r = requests.get(url)
data = r.json()
for item in data["items"]:
baseJSON = item["station"][0]["now"]
stationName = baseJSON["station"]
stationID = baseJSON["id"]
payTV = item["pay"]
xbmcplugin.setPluginCategory(addon_handle, "LiveTV")
xbmcplugin.setContent(addon_handle, 'episodes')
if self.showlive and (payTV == False or self.showLivePay):
url = common.build_url({'action': 'playLive', 'vod_url': stationID})
li = xbmcgui.ListItem()
li.setProperty('IsPlayable', 'true')
li.setInfo('video', "")
li.setLabel('%s' % (stationName))
li.setArt({'poster': baseJSON["epgImage"]["path"]})
xbmcplugin.addDirectoryItem(handle=addon_handle, url=url,
listitem=li, isFolder=False)
xbmcplugin.endOfDirectory(addon_handle, cacheToDisc=True)
def rootDir(self):
url = common.build_url({'action': 'listDictCats', 'id': 'Az'})
li = xbmcgui.ListItem()
li.setLabel('Sendungen A-Z')
xbmcplugin.addDirectoryItem(handle=addon_handle, url=url,
listitem=li, isFolder=True)
url = common.build_url({'action': 'listDictCats', 'id': 'station'})
li = xbmcgui.ListItem()
li.setLabel('Sendungen nach Sender')
xbmcplugin.addDirectoryItem(handle=addon_handle, url=url,
listitem=li, isFolder=True)
url = common.build_url({'action': 'listLive'})
li = xbmcgui.ListItem()
li.setLabel('LiveTV')
xbmcplugin.addDirectoryItem(handle=addon_handle, url=url,
listitem=li, isFolder=True)
url = common.build_url({'action': 'search'})
li = xbmcgui.ListItem()
li.setLabel('Suche')
xbmcplugin.addDirectoryItem(handle=addon_handle, url=url,
listitem=li, isFolder=True)
xbmcplugin.endOfDirectory(addon_handle, cacheToDisc=True)
def listEpisodesFromSeasonByYear(self, year, month, serial_url):
url = apiBase + serial_url + "?year=" + year + '&month=' + month
r = requests.get(url)
data = r.json()
totalItems = len(data['items'])
if totalItems > 0:
xbmcplugin.setContent(addon_handle, 'EPISODES')
xbmcplugin.setPluginCategory(addon_handle,buildDirectoryName(data))
xbmcplugin.addSortMethod(addon_handle, xbmcplugin.SORT_METHOD_DATEADDED)
for episode in data['items']:
if self.showPremium or episode["isPremium"] == False:
li = xbmcgui.ListItem()
li.setProperty('IsPlayable', 'true')
videoId = episode['videoId']
fID = serial_url.split('/')[-1]
if plotEnabled:
url = "{}/{}/{}?episodeId={}".format(apiBase, "module/teaserrow/format/highlight",fID, videoId)
r = requests.get(url)
data = r.json()
epData = data["items"][0]
else:
epData = episode
info = self.getInfoLabel(epData)
epName, info = getEpName(episode, info)
info['title'] = epName
li.setInfo('video',info)
li.setLabel('%s' % (epName))
li.setArt({'poster': episodeImageURL.replace("{eid}",str(episode['id'])), 'clearlogo': formatImageURL.replace("{fid}",str(fID))})
url = common.build_url({'action': 'playVod', 'vod_url': episode["videoId"]})
xbmcplugin.addDirectoryItem(handle=addon_handle, url=url,
listitem=li, isFolder=False, totalItems=totalItems )
xbmcplugin.endOfDirectory(addon_handle, cacheToDisc=True)
def listEpisodesFromSeason(self, season_id, serial_url):
url = apiBase + serial_url + "?season=" + season_id
r = requests.get(url)
data = r.json()
if len(data['items']) > 0:
xbmcplugin.setContent(addon_handle, 'episodes')
xbmcplugin.setPluginCategory(addon_handle,buildDirectoryName(data))
for episode in data['items']:
if self.showPremium or not "isPremium" in episode or episode["isPremium"] == False:
li = xbmcgui.ListItem()
li.setProperty('IsPlayable', 'true')
if not "videoId" in episode:
continue
videoId = episode['videoId']
fID = serial_url.split('/')[-1]
if plotEnabled:
url = "{}/{}/{}?episodeId={}".format(apiBase, "module/teaserrow/format/highlight",fID, videoId)
r = requests.get(url)
data = r.json()
if "items" in data and len(data["items"]) > 0:
epData = data["items"][0]
else:
epData = episode
else:
epData = episode
info = self.getInfoLabel(epData)
epName, info = getEpName(episode, info)
info['title'] = epName
li.setInfo('video', info)
li.setLabel(epName)
artDict = {}
artDict['icon'] = formatImageURL.replace("{fid}",str(fID))
if "id" in episode:
artDict['poster'] = episodeImageURL.replace("{eid}",str(episode['id']))
li.setArt(artDict)
url = common.build_url({'action': 'playVod', 'vod_url': episode["videoId"]})
xbmcplugin.addDirectoryItem(handle=addon_handle, url=url,
listitem=li, isFolder=False)
xbmcplugin.endOfDirectory(addon_handle, cacheToDisc=True)
def listSearchResult(self, query):
url = "{}/search/{}".format(apiBase, ul.quote(query))
r = requests.get(url)
data = r.json()
for item in data["items"]:
if "url" in item and "title" in item:
url = common.build_url({'action': 'listPage'.encode('utf-8'), 'id': item['url'].encode('utf-8')})
li = xbmcgui.ListItem(item['title'])
sid = item['url'].split("-")[-1]
imgurl = formatImageURL.replace("{fid}",str(sid))
li.setArt({'poster': imgurl, 'icon' : icon_file})
xbmcplugin.addDirectoryItem(handle=addon_handle, url=url,
listitem=li, isFolder=True)
xbmcplugin.endOfDirectory(addon_handle, cacheToDisc=True)
def listSeasonsFromserial(self, serial_url):
modulUrl = ""
clean_title = "<No Title>"
movieMetadata = False
movieMetadataURL = -1
movieID = -1
url = apiBase + "/page" + serial_url
r = requests.get(url)
data = r.json()
serial_url = ""
if "title" in data:
clean_title = data['title'].replace("im Online Stream ansehen | TVNOW","")
xbmcplugin.setPluginCategory(addon_handle, clean_title)
for module in data["modules"]:
if module["moduleLayout"] == "default":
movieID = module["id"]
if module["moduleLayout"] == "format_season_navigation" :
modulUrl = module["moduleUrl"]
if module["moduleLayout"] == "format_episode":
serial_url = module["moduleUrl"]
if module["moduleLayout"] == "format_navigation" and modulUrl == "":
modulUrl = module["moduleUrl"]
if module["moduleLayout"] == "moviemetadata":
movieMetadata = True
movieMetadataURL = module["moduleUrl"]
if "id" in data:
serial_id = data["id"]
if modulUrl != "" and serial_url != "":
xbmcplugin.setContent(addon_handle, 'seasons')
url = apiBase + modulUrl
r = requests.get(url)
nav_data = r.json()
navigation = nav_data.get("items", nav_data.get("seasons", {}))
for items in navigation:
if "months" in items and "year" in items:
for month in reversed(items["months"]):
url = common.build_url({'action': 'listSeasonByYear', 'year': int(items['year']), 'month': month["month"] , 'id' : serial_url.encode('utf-8')})
label = '%s - %s - %s' % (clean_title, month["name"], items['year'])
li = xbmcgui.ListItem(label=label)
li.setProperty('IsPlayable', 'false')
li.setArt({'poster': formatImageURL.replace("{fid}",str(serial_id))})
xbmcplugin.addDirectoryItem(handle=addon_handle, url=url,
listitem=li, isFolder=True)
elif "season" in items:
url = common.build_url({'action': 'listSeason'.encode('utf-8'), 'season_id': int(items["season"]), 'id' : serial_url.encode('utf-8')})
label = items.get("text", '%s - Staffel %s' % (clean_title, items["season"]))
li = xbmcgui.ListItem(label=label)
li.setProperty('IsPlayable', 'false')
li.setArt({'poster': formatImageURL.replace("{fid}",str(serial_id))})
xbmcplugin.addDirectoryItem(handle=addon_handle, url=url,
listitem=li, isFolder=True)
elif movieMetadata != -1 and movieID != -1:
if "title" in data:
title_stripped = data['title'].replace("im Online Stream | TVNOW","")
else:
title_stripped = "<No Title>"
if movieMetadata:
url = apiBase + movieMetadataURL
r = requests.get(url)
if r.status_code == 200:
data = r.json()
if not "headline" in data:
data["headline"] = title_stripped
else:
if "configuration" in data and "isPremium" in data["configuration"]:
data["isPremium"] = data["configuration"]["isPremium"]
else: #Fallback
data["isPremium"] = False
xbmcplugin.setPluginCategory(addon_handle, title_stripped)
xbmcplugin.setContent(addon_handle, 'episodes')
if self.showPremium or not "isPremium" in data or data["isPremium"] == False:
url = common.build_url({'action': 'playVod', 'vod_url': movieID})
li = xbmcgui.ListItem()
li.setProperty('IsPlayable', 'true')
li.setLabel('%s' % (title_stripped))
info = self.getInfoLabel(data, True)
li.setInfo('video', info)
li.setArt({'poster': formatImageURL.replace("{fid}",str(serial_id))})
xbmcplugin.addDirectoryItem(handle=addon_handle, url=url,
listitem=li, isFolder=False)
xbmcplugin.endOfDirectory(addon_handle, cacheToDisc=True)