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

Legend:
Removed from v.1650  
changed lines
  Added in v.3153

  ViewVC Help
Powered by ViewVC 1.1.20