/[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 1649 by torben, Sun Dec 4 15:06:39 2011 UTC revision 3149 by torben, Thu Nov 24 18:19:02 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.21
7  '''  '''
8    
9  import sys  import sys
 import cgi as urlparse  
10  import os  import os
11    
12    
# Line 13  import xbmcaddon Line 15  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'), 'fanart.jpg')  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  def open_url(url):          #orig_img_width = self.getControl(40).getWidth()
80          req = urllib2.Request(url)          #self.starwidth = (float(self.imdbrating) / 10.0) * orig_img_width
81          content = urllib2.urlopen(req)          #self.getControl(40).setWidth(int(self.starwidth))
82          data = content.read()  
83          content.close()      def setUrl(self, url):
84          return data          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            url = __backend__ + "&action=playbacktime&subaction=" + subaction + "&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    
 def rootMenu():  
185    
         buildList(__backend__, "") # call default list  
186    
187          # Adde xtra items to root menu  def SaveFile(path, data):
188          listitem = xbmcgui.ListItem(label = "Søg film ...", iconImage = 'DefaultFolder.png', thumbnailImage = 'DefaultFolder.png')      file = open(path, 'w')
189          listitem.setProperty('Fanart_Image', fanartImage)      file.write(data)
190        file.close()
191    
         u = sys.argv[0] + "?mode=10&name="  
         ok = xbmcplugin.addDirectoryItem(handle = int(sys.argv[1]), url = u, listitem = listitem, isFolder = True)  
192    
         xbmcplugin.endOfDirectory(int(sys.argv[1]))  
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  def buildList(url,title):      msg = open_url(__backend__ + "&action=messages")
215          print '[TODIC]:'+str(url)              msg = msg.strip()
         link = open_url(url)  
         ty=re.compile('<meta type=\'(.+?)\'').findall(link)  
         print '[TODIC]'+str(ty[0])  
216    
217          if ty[0] == 'clipList':      if msg != "":
218                  mode = '50'          dialog = xbmcgui.Dialog()
219                  folder = False          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    
269    
270            if playcount == '':
271                playcount = '0'
272            playcount = int(playcount)
273    
274    # print "name:" + name
275    #               print "url:" + url
276    #               print "thumb:" + thumb
277    #               print "description:" + description
278            listitem = xbmcgui.ListItem(
279                label=name, label2='test', iconImage='DefaultFolder.png', thumbnailImage=thumb)
280            listitem.setProperty('Fanart_Image', fanartImage)
281            if mode == '50':
282                infoLabels = {}
283                infoLabels['title'] = name
284                infoLabels['plot'] = description
285                infoLabels['playcount'] = playcount
286                listitem.setInfo('video', infoLabels)
287    
288            name = name.encode('UTF-8')
289            description = description.encode('UTF-8')
290    
291            u = sys.argv[0] + "?mode=" + urllib.quote(mode) + "&name=" + urllib.quote(
292                name) + "&url=" + urllib.quote(url) + "&description=" + urllib.quote(description)
293            xbmcplugin.addDirectoryItem(
294                handle=int(sys.argv[1]), url=u, listitem=listitem, isFolder=folder, totalItems=l)
295    
296        if (endlist == True):
297            xbmcplugin.endOfDirectory(int(sys.argv[1]))
298    
299    
300    def play_video(url, name, description):
301        if (description == None or description == ""):
302            play_real_video(url, name, 0)
303        else:
304            d = TodicMovieDialog()
305            d.setUrl(url)
306            d.setName(name)
307            d.setDescription(description)
308    
309            d.doModal()
310    
311    
312    def play_real_video(url, name, position):
313        xml = open_url(url)
314        print '[Todic] url: ' + str(url)
315        print '[Todic] xml: ' + xml
316        print '[Todic] pos: ' + str(position)
317    
318        doc = parseString(xml)
319        url = getText(doc.getElementsByTagName("url"))
320    
321        subtitleurl = getText(doc.getElementsByTagName("subtitles"))
322        subtitlesfile = os.path.join(datapath, 'temp.srt')
323    
324        # if old srt file exists delete it first
325        if os.path.isfile(subtitlesfile):
326            os.unlink(subtitlesfile)
327    
328        print '[TODIC] subs: ' + str(subtitleurl)
329        if len(subtitleurl) > 0:
330            subtitles = open_url(subtitleurl)
331            SaveFile(subtitlesfile, subtitles)
332            print 'TODIC downloaded subtitles'
333    
334        image = xbmc.getInfoImage('ListItem.Thumb')
335        listitem = xbmcgui.ListItem(
336            label=name, iconImage='DefaultVideo.png', thumbnailImage=image)
337        listitem.setInfo(type="Video", infoLabels={"Title": name})
338        listitem.setProperty('ResumeTime', '300')
339        listitem.setProperty('TotalTime', '3000')
340    
341        player = TodicPlayer(xbmc.PLAYER_CORE_AUTO)
342        player.play(str(url), listitem)
343    
344        # kan ikke loade subtitles hvis foerend playeren koerer
345        count = 0
346        while not xbmc.Player().isPlaying():
347            xbmc.sleep(250)
348            count += 1
349            if count > 10:
350                break
351    
352    
353    
354        if xbmc.Player().isPlaying():
355            if os.path.isfile(subtitlesfile):
356                player.setSubtitles(subtitlesfile)
357                print 'TODIC started subtitles'
358          else:          else:
359                  mode = '1'              player.disableSubtitles()
                 folder = True  
360    
         m=re.compile('<title>(.+?)</title><url>(.+?)</url><cover>(.+?)</cover><description>(.*)</description>').findall(link)  
         l=len(m)  
         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)  
                 listitem.setProperty('Fanart_Image', fanartImage)  
   
                 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]))  
361    
362            if (position > 0):
363                while (player.getTotalTime() == 0.0): #Vent indtil vi har beregnet hvor langt klippet er
364                    xbmc.sleep(250)
365    
366                print "[Todic] totalTime " +  str( player.getTotalTime() )
367                player.seekTime(position)
368    
369    
370        #Holder python kørernde indtil at det bliver bedt om at stoppe
371        while (not xbmc.abortRequested):
372            player.tick()
373            xbmc.sleep(500)
374    
375    
 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)  
376    
377  def search():  def search():
378          search = getUserInput("Todic Søgning")      search = getUserInput("Todic Søgning")
379    
380          if (search != None and search != ""):      if (search != None and search != ""):
381                  url = __backend__ + "&action=search&search=" + urllib.quote_plus(search)          url = __backend__ + "&action=search&search=" + \
382                urllib.quote_plus(search)
383    
384                  #print "[TODIC] Search start: " + search          # print "[TODIC] Search start: " + search
385                  #print "[TODIC] Search url: " + url          # print "[TODIC] Search url: " + url
386    
387                  buildList(url, "søgning")          buildList(url, "søgning")
388    
           
389    
390    def searchSeries():
391        search = getUserInput("Todic Serie Søgning")
392    
393                        if (search != None and search != ""):
394  #=================================== Tool Box =======================================          url = __backend__ + "&action=searchseries&search=" + \
395                urllib.quote_plus(search)
396    
397            # print "[TODIC] Search start: " + search
398            # print "[TODIC] Search url: " + url
399    
400            buildList(url, "serie søgning")
401    
402    
403    #=================================== Tool Box =======================================
404  # shows a more userfriendly notification  # shows a more userfriendly notification
405  def showMessage(heading, message):  def showMessage(heading, message):
406          duration = 15*1000      duration = 15 * 1000
407          xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s)' % ( heading, message, duration) )      xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s)' %
408                            (heading, message, duration))
409    
410    
411  # raise a keyboard for user input  # raise a keyboard for user input
412  def getUserInput(title = "Input", default="", hidden=False):  def getUserInput(title="Input", default="", hidden=False):
413          result = None      result = None
414    
415          # Fix for when this functions is called with default=None      # Fix for when this functions is called with default=None
416          if not default:      if not default:
417                  default = ""          default = ""
418                            
419          keyboard = xbmc.Keyboard(default, title)      keyboard = xbmc.Keyboard(default, title)
420          keyboard.setHiddenInput(hidden)      keyboard.setHiddenInput(hidden)
421          keyboard.doModal()      keyboard.doModal()
422                    
423          if keyboard.isConfirmed():      if keyboard.isConfirmed():
424                  result = keyboard.getText()          result = keyboard.getText()
425                    
426          return result      return result
427    
428    
429  def get_params():  def get_params():
430          param=[]      return parse_parameter_string(sys.argv[2])
431          paramstring=sys.argv[2]  
432          if len(paramstring)>=2:  
433                  params=sys.argv[2]  def parse_parameter_string(paramstring):
434                  cleanedparams=params.replace('?','')      param = []
435                  if (params[len(params)-1]=='/'):      if len(paramstring) >= 2:
436                          params=params[0:len(params)-2]          params = paramstring
437                  pairsofparams=cleanedparams.split('&')          cleanedparams = params.replace('?', '')
438                  param={}          if (params[len(params) - 1] == '/'):
439                  for i in range(len(pairsofparams)):              params = params[0:len(params) - 2]
440                          splitparams={}          pairsofparams = cleanedparams.split('&')
441                          splitparams=pairsofparams[i].split('=')          param = {}
442                          if (len(splitparams))==2:          for i in range(len(pairsofparams)):
443                                  param[splitparams[0]]=splitparams[1]                                                  splitparams = {}
444          return param              splitparams = pairsofparams[i].split('=')
445                if (len(splitparams)) == 2:
446                    param[splitparams[0]] = splitparams[1]
447        return param
448    
 params = get_params()  
 url = None  
 name = None  
 mode = None  
449    
450  params = get_params()  params = get_params()
451  url = None  url = None
452  name = None  name = None
453  mode = None  mode = None
454    description = None
455    
456    
457    #print params
458    
459    try:
460        url = urllib.unquote_plus(params["url"])
461    except:
462        pass
463  try:  try:
464          url = urllib.unquote_plus(params["url"])      name = urllib.unquote_plus(params["name"])
465  except:  except:
466          pass      pass
467  try:  try:
468          name = urllib.unquote_plus(params["name"])      mode = int(params["mode"])
469  except:  except:
470          pass      pass
471  try:  try:
472          mode = int(params["mode"])      description = urllib.unquote_plus(params["description"])
473  except:  except:
474          pass      pass
475    
476    
 if mode == None:  
         #build main menu  
         rootMenu()  
         
 elif mode == 1:  
         #build list of movie starting letters  
         buildList(url, name)  
477    
 elif mode == 10:  
         search()  
           
478    
479  elif mode == 50:  try:
480          play_video(url, name)      open_url("http://todic.dk")
481    except:
482        showMessage("Fejl", "Kunne ikke forbinde til todic.dk")
483        exit()
484    
485    
486    if url == 'refresh':
487        # xbmc.output("[tvserver] Container.Refresh") #20130418 xbmc.output virker
488        # ikke med XBMC12
489        xbmc.executebuiltin("Container.Refresh")
490    
491    
492  # xbmcplugin.endOfDirectory(int(sys.argv[1]))  elif mode == None:
493        # build main menu
494        rootMenu()
495    
496    elif mode == 1:
497        # build list of movie starting letters
498        buildList(url, name)
499    
500    elif mode == 10:
501        search()
502    
503    elif mode == 11:
504        searchSeries()
505    
506    
507    elif mode == 50:
508        play_video(url, name, description)

Legend:
Removed from v.1649  
changed lines
  Added in v.3149

  ViewVC Help
Powered by ViewVC 1.1.20