/[projects]/misc/xbmc/plugin.video.todic/default.py
ViewVC logotype

Contents of /misc/xbmc/plugin.video.todic/default.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3259 - (show annotations) (download) (as text)
Sun Mar 10 21:37:47 2019 UTC (5 years, 2 months ago) by torben
File MIME type: text/x-python
File size: 14547 byte(s)
debug: print version on plugin launch
1
2 # This Python file uses the following encoding: utf-8
3
4 '''
5 Todic plugin for XBMC
6 Version 1.8.1
7 '''
8
9 import sys
10 import os
11
12
13 import xbmc
14 import xbmcaddon
15 import xbmcgui
16 import xbmcplugin
17 import urllib
18 import urllib2
19
20 # import pprint
21
22 from xml.dom.minidom import parseString
23 from time import time
24
25 __addon__ = xbmcaddon.Addon(id='plugin.video.todic')
26 __key__ = __addon__.getSetting('xbmckey').lower()
27 __entrypoint__ = __addon__.getSetting('entrypoint').lower()
28 __backend__ = "https://todic.dk/xbmc.php?xbmckey=" + __key__
29
30
31 if __entrypoint__ == "alternative":
32 __backend__ = "https://alt.todic.dk/xbmc.php?xbmckey=" + __key__
33
34 if __entrypoint__ == "testing":
35 __backend__ = "https://todic.dk/xbmc-beta.php?xbmckey=" + __key__
36
37 print( "[Todic] entrypoint: " + __entrypoint__ )
38 print( "[Todic] backend: " + __backend__ )
39 print( "[Todic] version: " + __addon__.getAddonInfo('version') )
40
41 fanartImage = os.path.join(__addon__.getAddonInfo('path'), 'movie_bg_blur.jpg')
42 datapath = xbmc.translatePath(
43 'special://profile/addon_data/plugin.video.todic/')
44
45 ADDON_PATH = __addon__.getAddonInfo('path')
46 SkinMasterPath = os.path.join(ADDON_PATH, 'skins') + '/'
47 MySkinPath = (os.path.join(SkinMasterPath, '720p')) + '/'
48 MySkin = 'main.xml'
49
50
51 class TodicMovieDialog(xbmcgui.WindowXMLDialog):
52
53 def __new__(cls):
54 return super(TodicMovieDialog, cls).__new__(cls, "main.xml", ADDON_PATH)
55
56 def __init__(self):
57 super(TodicMovieDialog, self).__init__()
58 self.position = 0
59
60 def onClick(self, controlId):
61 print( "[Todic] MovieDialog OnClick: " + str(controlId) )
62
63 if (controlId == 50):
64 self.close()
65 play_real_video(self.url, self.name, 0)
66
67 if (controlId == 51):
68 self.close()
69 play_real_video(self.url, self.name, self.position)
70
71 if (controlId == 98):
72 self.close()
73
74 def onInit(self):
75
76 print( "[Todic] MovieDialog onInit" )
77 self.getControl(1).setLabel(self.name)
78 self.getControl(2).setLabel(self.moviegroups)
79 self.getControl(3).setLabel(self.description)
80 self.getControl(10).setLabel(self.playlength)
81 self.getControl(11).setLabel(self.codecdetails)
82
83 if (self.position > 0):
84 self.getControl(51).setVisible(True)
85 self.getControl(50).setPosition(100, 570)
86 self.getControl(51).setPosition(450, 570)
87 self.getControl(50).controlLeft( self.getControl(51) )
88 self.getControl(50).controlRight( self.getControl(51) )
89 else:
90 self.getControl(51).setVisible(False)
91
92 #orig_img_width = self.getControl(40).getWidth()
93 #self.starwidth = (float(self.imdbrating) / 10.0) * orig_img_width
94 #self.getControl(40).setWidth(int(self.starwidth))
95
96 def setDetailsDoc(self, detailsDoc):
97 print( "[Todic] MovieDialog setDetailsDoc:")
98 self.imdbrating = getText(detailsDoc.getElementsByTagName("imdbrating"))
99 self.moviegroups = getText(detailsDoc.getElementsByTagName("moviegroups"))
100 self.playlength = getText(detailsDoc.getElementsByTagName("playlength"))
101 self.codecdetails = getText(detailsDoc.getElementsByTagName("codecdetails"))
102 self.position = int( getText(detailsDoc.getElementsByTagName("position")) )
103
104 def setUrl(self, url):
105 self.url = url
106
107 def setName(self, name):
108 self.name = name
109
110 def setDescription(self, description):
111 self.description = description
112
113
114 class TodicPlayer(xbmc.Player):
115
116 def __init__(self, *args, **kwargs):
117 # xbmc.Player.__init__(selv,*args,**kwargs)
118 xbmc.Player.__init__(self)
119 self.stopped = False
120 self.started = False
121 self.playingPosition = 0.0
122 self.lastReport = 0
123 print( "[TodicPlayer] init")
124
125 def onPlayBackStarted(self):
126 self.started = True
127 print( "[TodicPlayer] : started")
128
129 #When user presses stop, we report back the the position registered in the last call to self.tick()
130 def onPlayBackStopped(self):
131 self.stopped = True
132 print( "[TodicPlayer] : stopped")
133 self.reportPlaytime("stopped")
134
135 def onPlayBackPaused(self):
136 print( "[TodicPlayer] : paused")
137 self.reportPlaytime("paused")
138
139 def onPlayBackResumed(self):
140 print( "[TodicPlayer] : resumed")
141 self.reportPlaytime("resumed")
142
143
144 def onPlayBackEnded(self):
145 self.stopped = True
146 print( "[TodicPlayer] : ended")
147 self.reportPlaytime("ended")
148
149 def tick(self):
150 #print "[Todic] Tick: " + str( self.isPlaying() )
151 if ( self.isPlaying() ):
152 tmpTime = self.getTime()
153
154 #only report time if it has changed in the mean time
155 if tmpTime != self.playingPosition:
156 self.playingPosition = tmpTime
157 now = time()
158 #print "[Todic] tick " + str(now) + " " + str(self.lastReport) + " : " +str(now - self.lastReport)
159 if ( (now - self.lastReport) > 60.0):
160 self.lastReport = now
161 self.reportPlaytime("playing")
162
163 def reportPlaytime(self, subaction):
164 if (self.playingPosition > 60):
165 url = __backend__ + "&action=playbacktime&subaction=" + subaction + "&time=" + str( self.playingPosition )
166 print( "[Todic] reportPlaytime:" + url)
167 open_url_safe(url)
168
169
170
171 def getText2(nodelist):
172 rc = []
173 for node in nodelist:
174 if node.nodeType == node.TEXT_NODE:
175 rc.append(node.data)
176 else:
177 rc.append(getText(node.childNodes))
178 return ''.join(rc)
179
180
181 def getText(nodelist):
182 if nodelist.length == 0:
183 return ''
184 else:
185 if nodelist[0].childNodes.length == 0:
186 return ''
187 else:
188 return nodelist[0].childNodes[0].nodeValue
189
190
191
192 def SaveFile(path, data):
193 file = open(path, 'w')
194 file.write(data)
195 file.close()
196
197
198
199 def open_url(url):
200 req = urllib2.Request(url)
201 content = urllib2.urlopen(req)
202 data = content.read()
203 content.close()
204 return data
205
206
207 # wraps open url in a catch-all exception handler
208 # usefull for periodic back-reporting that should not interrupt the program flow
209 def open_url_safe(url):
210 try:
211 return open_url(url)
212 except:
213 print( "[Todic] Some error during open_url call to ", url)
214
215
216
217 def rootMenu():
218 kodi_ver = xbmc.getInfoLabel('System.BuildVersion')
219 plugin_ver = __addon__.getAddonInfo('version')
220 msgurl = __backend__ + "&action=messages&kodi=" + urllib.quote_plus(kodi_ver) + "&todicplugin=" + urllib.quote_plus(plugin_ver)
221
222 msg = open_url(msgurl)
223 msg = msg.strip()
224
225 if msg != "":
226 dialog = xbmcgui.Dialog()
227 dialog.ok('XBMC Todic', msg)
228
229 buildList(__backend__, "", False) # call default list
230
231 # Adde xtra items to root menu
232 listitem = xbmcgui.ListItem(
233 label="Søg Film ...", iconImage='DefaultFolder.png', thumbnailImage='DefaultFolder.png')
234 listitem.setProperty('Fanart_Image', fanartImage)
235
236 u = sys.argv[0] + "?mode=10&name="
237 xbmcplugin.addDirectoryItem(
238 handle=int(sys.argv[1]), url=u, listitem=listitem, isFolder=True)
239
240 # add search series
241 listitem = xbmcgui.ListItem(
242 label="Søg Serier ...", iconImage='DefaultFolder.png', thumbnailImage='DefaultFolder.png')
243 listitem.setProperty('Fanart_Image', fanartImage)
244
245 u = sys.argv[0] + "?mode=11&name="
246 xbmcplugin.addDirectoryItem(
247 handle=int(sys.argv[1]), url=u, listitem=listitem, isFolder=True)
248
249 xbmcplugin.endOfDirectory(int(sys.argv[1]))
250
251
252 def buildList(url, title, endlist=True):
253 print( '[Todic]:' + str(url) )
254
255 link = open_url(url)
256 doc = parseString(link)
257 ty = doc.getElementsByTagName("meta")[0].getAttribute("type")
258 print( '[Todic]' + str(ty))
259
260 if ty == 'clipList':
261 mode = '50'
262 folder = False
263 else:
264 mode = '1'
265 folder = True
266
267 entries = doc.getElementsByTagName("entry")
268 l = len(entries)
269
270 for entry in entries:
271 name = getText(entry.getElementsByTagName("title"))
272 url = getText(entry.getElementsByTagName("url"))
273 thumb = getText(entry.getElementsByTagName("cover"))
274 playcount = getText(entry.getElementsByTagName("playcount"))
275
276
277 if playcount == '':
278 playcount = '0'
279 playcount = int(playcount)
280
281 # print "name:" + name
282 # print "url:" + url
283 # print "thumb:" + thumb
284 listitem = xbmcgui.ListItem(
285 label=name, label2='test', iconImage='DefaultFolder.png')
286 listitem.setProperty('Fanart_Image', fanartImage)
287 listitem.addContextMenuItems([('Refresh', 'Container.Refresh')])
288
289 if mode == '50':
290 infoLabels = {}
291 infoLabels['title'] = name
292 infoLabels['playcount'] = playcount
293 if playcount > 0:
294 listitem.setArt( {'thumb': thumb} ) #not pretty - but at least we can show a different icon for unwatched/watched in kodi18
295 listitem.setInfo('video', infoLabels)
296
297 name = name.encode('UTF-8')
298
299 u = sys.argv[0] + "?mode=" + urllib.quote(mode) + "&name=" + urllib.quote(
300 name) + "&url=" + urllib.quote(url)
301 xbmcplugin.addDirectoryItem(
302 handle=int(sys.argv[1]), url=u, listitem=listitem, isFolder=folder, totalItems=l)
303
304 if (endlist == True):
305 xbmcplugin.endOfDirectory(int(sys.argv[1]))
306
307
308 def play_video(url, name):
309 description = ""
310 playPosition = 0
311 savedPosition = 0
312 try:
313 param1 = parse_parameter_string(url)
314 clipkey = param1["clipkey"]
315
316 print( "[Todic] ClipKey:" + clipkey)
317 detailurl = __backend__ + "&action=clipdetails&clipkey=" + clipkey
318 print( "[Todic] detailURL = " + detailurl)
319
320 xml = open_url(detailurl)
321
322 clipDetailsDoc = parseString(xml)
323 savedPosition = int( getText(clipDetailsDoc.getElementsByTagName("position")) )
324 description = getText(clipDetailsDoc.getElementsByTagName("description"))
325 except:
326 print( "[Todic] Unexpected error:", sys.exc_info()[0] )
327
328 if (description == None or description == ""):
329 if (savedPosition > 0):
330 dialog = xbmcgui.Dialog()
331 #yes / true -afspil fra position
332 answer = dialog.yesno(heading='Todic', line1='Afspil fra sidste position', nolabel='Fra start', yeslabel='Fortsæt')
333 if (answer == True):
334 playPosition = savedPosition
335
336 play_real_video(url, name, playPosition)
337
338 else:
339 d = TodicMovieDialog()
340 d.setDetailsDoc(clipDetailsDoc)
341 d.setName(name)
342 d.setUrl(url)
343 d.setDescription(description)
344
345 d.doModal()
346
347
348 def play_real_video(url, name, position):
349 xml = open_url(url)
350 print( '[Todic] url: ' + str(url) )
351 print( '[Todic] xml: ' + xml )
352 print( '[Todic] pos: ' + str(position) )
353
354 doc = parseString(xml)
355 url = getText(doc.getElementsByTagName("url"))
356
357 subtitleurl = getText(doc.getElementsByTagName("subtitles"))
358
359
360 print( '[Todic] subs: ' + str(subtitleurl) )
361
362 image = xbmc.getInfoImage('ListItem.Thumb')
363 listitem = xbmcgui.ListItem(
364 label=name, iconImage='DefaultVideo.png', thumbnailImage=image)
365 listitem.setInfo(type="Video", infoLabels={"Title": name})
366
367 listitem.setProperty('StartOffset', str(position) )
368
369 if len(subtitleurl) > 0:
370 listitem.setSubtitles([subtitleurl])
371
372 player = TodicPlayer()
373 player.play(str(url), listitem)
374
375
376 #Holder python kørernde indtil at det bliver bedt om at stoppe
377 while (not xbmc.abortRequested):
378 player.tick()
379 xbmc.sleep(500)
380
381
382
383 def search():
384 search = getUserInput("Todic Søgning")
385
386 if (search != None and search != ""):
387 url = __backend__ + "&action=search&search=" + \
388 urllib.quote_plus(search)
389
390 # print "[Todic] Search start: " + search
391 # print "[Todic] Search url: " + url
392
393 buildList(url, "søgning")
394
395
396 def searchSeries():
397 search = getUserInput("Todic Serie Søgning")
398
399 if (search != None and search != ""):
400 url = __backend__ + "&action=searchseries&search=" + \
401 urllib.quote_plus(search)
402
403 # print "[Todic] Search start: " + search
404 # print "[Todic] Search url: " + url
405
406 buildList(url, "serie søgning")
407
408
409 #=================================== Tool Box =======================================
410 # shows a more userfriendly notification
411 def showMessage(heading, message):
412 duration = 15 * 1000
413 xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s)' %
414 (heading, message, duration))
415
416
417 # raise a keyboard for user input
418 def getUserInput(title="Input", default="", hidden=False):
419 result = None
420
421 # Fix for when this functions is called with default=None
422 if not default:
423 default = ""
424
425 keyboard = xbmc.Keyboard(default, title)
426 keyboard.setHiddenInput(hidden)
427 keyboard.doModal()
428
429 if keyboard.isConfirmed():
430 result = keyboard.getText()
431
432 return result
433
434
435 def get_params():
436 return parse_parameter_string(sys.argv[2])
437
438
439 def parse_parameter_string(paramstring):
440 param = []
441 if len(paramstring) >= 2:
442 params = paramstring
443 cleanedparams = params.replace('?', '')
444 if (params[len(params) - 1] == '/'):
445 params = params[0:len(params) - 2]
446 pairsofparams = cleanedparams.split('&')
447 param = {}
448 for i in range(len(pairsofparams)):
449 splitparams = {}
450 splitparams = pairsofparams[i].split('=')
451 if (len(splitparams)) == 2:
452 param[splitparams[0]] = splitparams[1]
453 return param
454
455
456 params = get_params()
457 url = None
458 name = None
459 mode = None
460
461
462 #print params
463
464 try:
465 url = urllib.unquote_plus(params["url"])
466 except:
467 pass
468 try:
469 name = urllib.unquote_plus(params["name"])
470 except:
471 pass
472 try:
473 mode = int(params["mode"])
474 except:
475 pass
476
477
478
479
480 try:
481 open_url("http://todic.dk")
482 except:
483 showMessage("Fejl", "Kunne ikke forbinde til todic.dk")
484 exit()
485
486
487 if url == 'refresh':
488 # xbmc.output("[tvserver] Container.Refresh") #20130418 xbmc.output virker
489 # ikke med XBMC12
490 xbmc.executebuiltin("Container.Refresh")
491
492
493 elif mode == None:
494 # build main menu
495 rootMenu()
496
497 elif mode == 1:
498 # build list of movie starting letters
499 buildList(url, name)
500
501 elif mode == 10:
502 search()
503
504 elif mode == 11:
505 searchSeries()
506
507
508 elif mode == 50:
509 play_video(url, name)

  ViewVC Help
Powered by ViewVC 1.1.20