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

  ViewVC Help
Powered by ViewVC 1.1.20