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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1647 by torben, Sat Dec 3 13:53:47 2011 UTC revision 3151 by torben, Thu Nov 24 19:55:00 2016 UTC
# Line 1  Line 1 
1    
2    # This Python file uses the following encoding: utf-8
3    
4  '''  '''
5      Todic plugin for XBMC      Todic plugin for XBMC
6      Version 0.0.2      Version 0.0.21b
7  '''  '''
8    
9  import sys  import sys
10  import cgi as urlparse  import os
11    
12    
13  import xbmc  import xbmc
14  import xbmcaddon  import xbmcaddon
15  import xbmcgui  import xbmcgui
16  import xbmcplugin  import xbmcplugin
17  import urllib  import urllib
18  import urllib2, re  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')  __addon__ = xbmcaddon.Addon(id='plugin.video.todic')
26  __key__ = __addon__.getSetting('xbmckey').lower()  __key__ = __addon__.getSetting('xbmckey').lower()
27  __backend__ = "http://todic.dk/xbmc.php?xbmckey=" + __key__  __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    
89    
90        def fetchClipDetails(self):
91            param1 = parse_parameter_string(self.url)
92    
93            self.clipkey = param1["clipkey"]
94            print "CLIPKEY:" + self.clipkey
95            detailurl = __backend__ + "&action=clipdetails&clipkey=" + self.clipkey
96            print "[Todic] detailURL = " + detailurl
97    
98            xml = open_url(detailurl)
99    
100            doc = parseString(xml)
101            self.imdbrating = getText(doc.getElementsByTagName("imdbrating"))
102            self.moviegroups = getText(doc.getElementsByTagName("moviegroups"))
103            self.playlength = getText(doc.getElementsByTagName("playlength"))
104            self.codecdetails = getText(doc.getElementsByTagName("codecdetails"))
105            self.position = int( getText(doc.getElementsByTagName("position")) )
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, xbmc.PLAYER_CORE_MPLAYER)
119            self.stopped = False
120            self.started = False
121            self.playingPosition = 0.0
122            self.lastReport = 0
123            print "[TodicPlayer] init"
124    
125    #       @catchall
126        def onPlayBackStarted(self):
127            self.started = True
128            print "[TodicPlayer] : started"
129    #               super.onPlayBackStarted()
130    
131        #When user presses stop, we report back the the position registered in the last call to self.tick()
132        def onPlayBackStopped(self):
133            self.stopped = True
134            print "[TodicPlayer] : stopped"
135            self.reportPlaytime("stopped")
136    #        url = __backend__ + "&action=playbacktime&subaction=stopped&time=" + str( self.playingPosition )
137    #        open_url_safe(url)
138    
139    
140        def onPlayBackEnded(self):
141            self.stopped = True
142            print "[TodicPlayer] : ended"
143            self.reportPlaytime("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("playing")
155    
156                
157    
158    
159        def reportPlaytime(self, subaction):
160            if (self.playingPosition > 60):
161                url = __backend__ + "&action=playbacktime&subaction=" + subaction + "&time=" + str( self.playingPosition )
162                print "[Todic] reportPlaytime:" + url
163                open_url_safe(url)
164    
165                    
166    
167    
168    def getText2(nodelist):
169        rc = []
170        for node in nodelist:
171            if node.nodeType == node.TEXT_NODE:
172                rc.append(node.data)
173            else:
174                rc.append(getText(node.childNodes))
175        return ''.join(rc)
176    
177    
178    def getText(nodelist):
179        if nodelist.length == 0:
180            return ''
181        else:
182            if nodelist[0].childNodes.length == 0:
183                return ''
184            else:
185                return nodelist[0].childNodes[0].nodeValue
186    
187    
188    
189    def SaveFile(path, data):
190        file = open(path, 'w')
191        file.write(data)
192        file.close()
193    
194    
195    
196  def open_url(url):  def open_url(url):
197          req = urllib2.Request(url)      req = urllib2.Request(url)
198          content = urllib2.urlopen(req)      content = urllib2.urlopen(req)
199          data = content.read()      data = content.read()
200          content.close()      content.close()
201          return data      return data
202    
203    
204    # wraps open url in a catch-all exception handler
205    # usefull for periodic back-reporting that should not interrupt the program flow
206    def open_url_safe(url):
207        try:
208            return open_url(url)
209        except:
210            print "[Todic ]Some error during open_url call to ", url
211    
212    
213    
214  def rootMenu():  def rootMenu():
215          link = open_url(__backend__)  
216          m=re.compile('<title>(.+?)</title><url>(.+?)</url>').findall(link)      msg = open_url(__backend__ + "&action=messages")
217          l = len(m)      msg = msg.strip()
218          for name,url in m:  
219                  listitem = xbmcgui.ListItem(label = name, iconImage = 'DefaultFolder.png', thumbnailImage = 'DefaultFolder.png')      if msg != "":
220                  u = sys.argv[0] + "?mode=1&name=" + urllib.quote_plus(name) + "&url=" + urllib.quote_plus(url)          dialog = xbmcgui.Dialog()
221                  ok = xbmcplugin.addDirectoryItem(handle = int(sys.argv[1]), url = u, listitem = listitem, isFolder = True, totalItems = l)          dialog.ok('XBMC Todic', msg)
222    
223          listitem = xbmcgui.ListItem(label = "Søg film ...", iconImage = 'DefaultFolder.png', thumbnailImage = 'DefaultFolder.png')      buildList(__backend__, "", False)  # call default list
224          u = sys.argv[0] + "?mode=10&name=" + urllib.quote_plus(name)  
225          ok = xbmcplugin.addDirectoryItem(handle = int(sys.argv[1]), url = u, listitem = listitem, isFolder = True, totalItems = l)      # Adde xtra items to root menu
226        listitem = xbmcgui.ListItem(
227          xbmcplugin.endOfDirectory(int(sys.argv[1]))          label="Søg film ...", iconImage='DefaultFolder.png', thumbnailImage='DefaultFolder.png')
228        listitem.setProperty('Fanart_Image', fanartImage)
229    
230  def buildList(url,title):      u = sys.argv[0] + "?mode=10&name="
231          print '[TODIC]:'+str(url)              xbmcplugin.addDirectoryItem(
232          link = open_url(url)          handle=int(sys.argv[1]), url=u, listitem=listitem, isFolder=True)
233          ty=re.compile('<meta type=\'(.+?)\'').findall(link)  
234          print '[TODIC]'+str(ty[0])      # add search series
235        listitem = xbmcgui.ListItem(
236          if ty[0] == 'clipList':          label="Søg Serier ...", iconImage='DefaultFolder.png', thumbnailImage='DefaultFolder.png')
237                  mode = '50'      listitem.setProperty('Fanart_Image', fanartImage)
238                  folder = False  
239        u = sys.argv[0] + "?mode=11&name="
240        xbmcplugin.addDirectoryItem(
241            handle=int(sys.argv[1]), url=u, listitem=listitem, isFolder=True)
242    
243        xbmcplugin.endOfDirectory(int(sys.argv[1]))
244    
245    
246    def buildList(url, title, endlist=True):
247        print '[TODIC]:' + str(url)
248    
249        link = open_url(url)
250        doc = parseString(link)
251        ty = doc.getElementsByTagName("meta")[0].getAttribute("type")
252        print '[TODIC]' + str(ty)
253    
254        if ty == 'clipList':
255            mode = '50'
256            folder = False
257        else:
258            mode = '1'
259            folder = True
260    
261        entries = doc.getElementsByTagName("entry")
262        l = len(entries)
263        description = ''
264        for entry in entries:
265            name = getText(entry.getElementsByTagName("title"))
266            url = getText(entry.getElementsByTagName("url"))
267            thumb = getText(entry.getElementsByTagName("cover"))
268            description = getText(entry.getElementsByTagName("description"))
269            playcount = getText(entry.getElementsByTagName("playcount"))
270    
271    
272            if playcount == '':
273                playcount = '0'
274            playcount = int(playcount)
275    
276    # print "name:" + name
277    #               print "url:" + url
278    #               print "thumb:" + thumb
279    #               print "description:" + description
280            listitem = xbmcgui.ListItem(
281                label=name, label2='test', iconImage='DefaultFolder.png', thumbnailImage=thumb)
282            listitem.setProperty('Fanart_Image', fanartImage)
283            if mode == '50':
284                infoLabels = {}
285                infoLabels['title'] = name
286                infoLabels['plot'] = description
287                infoLabels['playcount'] = playcount
288                listitem.setInfo('video', infoLabels)
289    
290            name = name.encode('UTF-8')
291            description = description.encode('UTF-8')
292    
293            u = sys.argv[0] + "?mode=" + urllib.quote(mode) + "&name=" + urllib.quote(
294                name) + "&url=" + urllib.quote(url) + "&description=" + urllib.quote(description)
295            xbmcplugin.addDirectoryItem(
296                handle=int(sys.argv[1]), url=u, listitem=listitem, isFolder=folder, totalItems=l)
297    
298        if (endlist == True):
299            xbmcplugin.endOfDirectory(int(sys.argv[1]))
300    
301    
302    def play_video(url, name, description):
303        if (description == None or description == ""):
304            play_real_video(url, name, 0)
305        else:
306            d = TodicMovieDialog()
307            d.setUrl(url)
308            d.setName(name)
309            d.setDescription(description)
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:          else:
361                  mode = '1'              player.disableSubtitles()
362                  folder = True  
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          m=re.compile('<title>(.+?)</title><url>(.+?)</url><cover>(.+?)</cover><description>(.*)</description>').findall(link)              print "[Todic] totalTime " +  str( player.getTotalTime() )
369          l=len(m)              player.seekTime(position)
         for name,url,thumb,description in m:                          
                 infoLabels = {}  
                 infoLabels['title'] = name  
                 infoLabels['plot'] = description          
   
                 listitem = xbmcgui.ListItem(label = name, label2='test', iconImage = 'DefaultFolder.png', thumbnailImage = thumb)  
                 listitem.setInfo('video', infoLabels)  
                 u = sys.argv[0] + "?mode=" + urllib.quote_plus(mode) + "&name=" + urllib.quote_plus(name) + "&url=" + urllib.quote_plus(url)  
                 ok = xbmcplugin.addDirectoryItem(handle = int(sys.argv[1]), url = u, listitem = listitem, isFolder = folder, totalItems = l)  
         xbmcplugin.endOfDirectory(int(sys.argv[1]))  
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    
 def play_video(url, name):  
         link = open_url(url)  
         match=re.compile('<url>(.+?)</url>').findall(link)  
         url = match[0]  
         print '[TODIC]:'+str(url)  
         image = xbmc.getInfoImage( 'ListItem.Thumb' )  
         listitem = xbmcgui.ListItem(label = name , iconImage = 'DefaultVideo.png', thumbnailImage = image)  
 #       listitem = xbmcgui.ListItem(label = name , iconImage = 'DefaultVideo.png', thumbnailImage = 'DefaultVideo.png')  
         listitem.setInfo( type = "Video", infoLabels={ "Title": name } )  
         xbmc.Player(xbmc.PLAYER_CORE_AUTO).play(str(url), listitem)  
         xbmc.sleep(200)  
378    
379  def search():  def search():
380          search = getUserInput("Todic Søgning")      search = getUserInput("Todic Søgning")
381    
382          if (search != None and search != ""):      if (search != None and search != ""):
383                  url = __backend__ + "&action=search&search=" + urllib.quote_plus(search)          url = __backend__ + "&action=search&search=" + \
384                urllib.quote_plus(search)
385    
386                  #print "[TODIC] Search start: " + search          # print "[TODIC] Search start: " + search
387                  #print "[TODIC] Search url: " + url          # print "[TODIC] Search url: " + url
388    
389                  buildList(url, "søgning")          buildList(url, "søgning")
390    
           
391    
392    def searchSeries():
393        search = getUserInput("Todic Serie Søgning")
394    
395                        if (search != None and search != ""):
396  #=================================== Tool Box =======================================          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  # shows a more userfriendly notification
407  def showMessage(heading, message):  def showMessage(heading, message):
408          duration = 15*1000      duration = 15 * 1000
409          xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s)' % ( heading, message, duration) )      xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s)' %
410                            (heading, message, duration))
411    
412    
413  # raise a keyboard for user input  # raise a keyboard for user input
414  def getUserInput(title = "Input", default="", hidden=False):  def getUserInput(title="Input", default="", hidden=False):
415          result = None      result = None
416    
417          # Fix for when this functions is called with default=None      # Fix for when this functions is called with default=None
418          if not default:      if not default:
419                  default = ""          default = ""
420                            
421          keyboard = xbmc.Keyboard(default, title)      keyboard = xbmc.Keyboard(default, title)
422          keyboard.setHiddenInput(hidden)      keyboard.setHiddenInput(hidden)
423          keyboard.doModal()      keyboard.doModal()
424                    
425          if keyboard.isConfirmed():      if keyboard.isConfirmed():
426                  result = keyboard.getText()          result = keyboard.getText()
427                    
428          return result      return result
429    
430    
431  def get_params():  def get_params():
432          param=[]      return parse_parameter_string(sys.argv[2])
433          paramstring=sys.argv[2]  
434          if len(paramstring)>=2:  
435                  params=sys.argv[2]  def parse_parameter_string(paramstring):
436                  cleanedparams=params.replace('?','')      param = []
437                  if (params[len(params)-1]=='/'):      if len(paramstring) >= 2:
438                          params=params[0:len(params)-2]          params = paramstring
439                  pairsofparams=cleanedparams.split('&')          cleanedparams = params.replace('?', '')
440                  param={}          if (params[len(params) - 1] == '/'):
441                  for i in range(len(pairsofparams)):              params = params[0:len(params) - 2]
442                          splitparams={}          pairsofparams = cleanedparams.split('&')
443                          splitparams=pairsofparams[i].split('=')          param = {}
444                          if (len(splitparams))==2:          for i in range(len(pairsofparams)):
445                                  param[splitparams[0]]=splitparams[1]                                                  splitparams = {}
446          return param              splitparams = pairsofparams[i].split('=')
447                if (len(splitparams)) == 2:
448                    param[splitparams[0]] = splitparams[1]
449        return param
450    
 params = get_params()  
 url = None  
 name = None  
 mode = None  
451    
452  params = get_params()  params = get_params()
453  url = None  url = None
454  name = None  name = None
455  mode = None  mode = None
456    description = None
457    
458    
459    #print params
460    
461  try:  try:
462          url = urllib.unquote_plus(params["url"])      url = urllib.unquote_plus(params["url"])
463  except:  except:
464          pass      pass
465  try:  try:
466          name = urllib.unquote_plus(params["name"])      name = urllib.unquote_plus(params["name"])
467  except:  except:
468          pass      pass
469  try:  try:
470          mode = int(params["mode"])      mode = int(params["mode"])
471  except:  except:
472          pass      pass
473    try:
474        description = urllib.unquote_plus(params["description"])
475    except:
476        pass
477    
478    
 if mode == None:  
         #build main menu  
         rootMenu()  
         
 elif mode == 1:  
         #build list of movie starting letters  
         buildList(url, name)  
479    
 elif mode == 10:  
         search()  
           
480    
481  elif mode == 50:  try:
482          play_video(url, name)      open_url("http://todic.dk")
483    except:
484        showMessage("Fejl", "Kunne ikke forbinde til todic.dk")
485        exit()
486    
487    
488    if url == 'refresh':
489        # xbmc.output("[tvserver] Container.Refresh") #20130418 xbmc.output virker
490        # ikke med XBMC12
491        xbmc.executebuiltin("Container.Refresh")
492    
493    
494  # xbmcplugin.endOfDirectory(int(sys.argv[1]))  elif mode == None:
495        # build main menu
496        rootMenu()
497    
498    elif mode == 1:
499        # build list of movie starting letters
500        buildList(url, name)
501    
502    elif mode == 10:
503        search()
504    
505    elif mode == 11:
506        searchSeries()
507    
508    
509    elif mode == 50:
510        play_video(url, name, description)

Legend:
Removed from v.1647  
changed lines
  Added in v.3151

  ViewVC Help
Powered by ViewVC 1.1.20