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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.20