Advertisement
Guest User

Untitled

a guest
Nov 26th, 2012
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 67.04 KB | None | 0 0
  1. from time import strptime, mktime, gmtime, strftime, localtime
  2. from operator import itemgetter
  3. import itertools
  4. import sys, itertools, re, os, random, inspect
  5. import copy
  6. if sys.version_info < (2, 7):
  7.     import simplejson
  8. else:
  9.     import json as simplejson
  10. import xbmc, xbmcgui, xbmcaddon
  11. # http://mail.python.org/pipermail/python-list/2009-June/596197.html
  12. import _strptime
  13. from threading import Thread
  14. import aioupdate
  15. import aiorecents
  16. from aioupdate import Uprandom
  17.  
  18. __addon__        = xbmcaddon.Addon()
  19. __addonid__      = __addon__.getAddonInfo('id')
  20. __addonversion__ = __addon__.getAddonInfo('version')
  21. __settings__   = xbmcaddon.Addon(id='script.allinone')
  22.  
  23.  
  24.  
  25. def log(message):
  26.     xbmc.log(msg=message)
  27. class Main:
  28.     def __init__( self ):
  29.         log("iniciou o allinone")        
  30.         self._parse_argv()
  31.         self._firstrun()
  32.         if self.PLAYLISTEPISODE or self.UPALLINONE:
  33.            self._actionaio()
  34.         elif self.ALBUMID:
  35.             self._play_album( self.ALBUMID )
  36.         else:
  37.            self._init_vars()
  38.            x= self.WINDOW.getProperty('LatestEpisode.4.EpisodeTitle')
  39.            xbmc.log(msg=x)
  40.            self.WINDOW.clearProperty('AllInOne_Running')
  41.            self._fetch_info()
  42.            self.WINDOW.setProperty('AllInOne_UpRandom', '1')
  43.            xbmc.sleep(2000)
  44.            self.WINDOW.setProperty('AllInOne_Running', 'True')
  45.            self._daemon()
  46.     def _parse_argv( self ):
  47.         #get all params send from skinner
  48.         try:
  49.             params = dict( arg.split( "=" ) for arg in sys.argv[ 1 ].split( "&" ) )
  50.         except:
  51.             params = {}
  52.         self.MOVIESRANDOMGET = params.get( "moviesrandomget", "" )
  53.         self.MOVIES =  __settings__.getSetting("MovieProgress")
  54.         self.MOVIESRANDOM = __settings__.getSetting("MovieRandom")
  55.         self.EPISODES = __settings__.getSetting("EpisodeProgress")
  56.         self.EPISODESRANDOM = __settings__.getSetting("EpisodeRandom")
  57.         self.EPISODESRANDOMTYPE = __settings__.getSetting("TypeEpisodeRandom")
  58.         self.EPISODESRANDOMGET = params.get( "episodesrandomget", "" )
  59.         self.MUSICVIDEOS = __settings__.getSetting("ConcertsRandom")
  60.         self.MUSICVIDEOSRANDOMGET = params.get("musicvideosrandomget", "")
  61.         self.MUSICRANDOMGET = params.get("musicrandomget", "")
  62.         self.LIMIT = 10
  63.         self.PLAYLISTEPISODE = params.get("playlistepisode", "")
  64.         self.UPALLINONE = params.get('upallinone','')
  65.         self.ALBUMS = __settings__.getSetting("MusicProgress")
  66.         self.ALBUMSRANDOM = __settings__.getSetting("MusicRandom")
  67.         self.ALBUMID = params.get( "albumid", "" )
  68.         self.RECENTS = params.get("recents", "")
  69.         self.RECENTSUPDATE = params.get("recentsupdate", "")
  70.         self.EPISODEBARHIDE = __settings__.getSetting("EpisodeBarHide")
  71.        
  72.     def _firstrun(self):
  73.         if ( not xbmcgui.Window( 10000 ).getProperty('AllInOne_UpRandom')):
  74.            estadoupdateinicial = xbmcgui.Window( 10000 ).getProperty('AllInOne_UpRandom')
  75.            xbmc.log(msg="uprandom inicial igual  a %s" % estadoupdateinicial)
  76.            xbmcgui.Window( 10000 ).setProperty('AllInOne_UpRandom', '0')
  77.         if self.RECENTS == 'true':  
  78.            aiorecents.Main()
  79.            #t = callfetchrecents()
  80.            #t.start()
  81.            #t.join()
  82.            
  83.     def _actionaio( self ):
  84.         if self.UPALLINONE:
  85.            if xbmcgui.Window( 10000 ).getProperty('AllInOne_UpRandom') == '1':
  86.               buttonid = str(xbmcgui.Window( 10000 ).getFocusId())
  87.               xbmcgui.Window( 10000 ).setProperty('AllInOne_UpRandomButtonId', buttonid)
  88.               if self.MOVIESRANDOMGET == 'true':
  89.                  xbmcgui.Window( 10000 ).setProperty('AllInOne_UpRandomMovies', '1')
  90.                  xbmc.log(msg="passou no random upallinone movies")
  91.               else:
  92.                  xbmcgui.Window( 10000 ).clearProperty('AllInOne_UpRandomMovies')
  93.               if self.EPISODESRANDOMGET == 'true':
  94.                  xbmcgui.Window( 10000 ).setProperty('AllInOne_UpRandomEpisodes', '1')
  95.               else:
  96.                  xbmcgui.Window( 10000 ).clearProperty('AllInOne_UpRandomEpisodes')
  97.               if self.MUSICVIDEOSRANDOMGET == 'true':
  98.                  xbmcgui.Window( 10000 ).setProperty('AllInOne_UpRandomMusicVideos', '1')
  99.               else:
  100.                  xbmcgui.Window( 10000 ).clearProperty('AllInOne_UpRandomMusicVideos')
  101.               if self.MUSICRANDOMGET == 'true':
  102.                  xbmcgui.Window( 10000 ).setProperty('AllInOne_UpRandomMusic', '1')
  103.               else:
  104.                  xbmcgui.Window( 10000 ).clearProperty('AllInOne_UpRandomMusic')
  105.               xbmcgui.Window( 10000 ).setProperty('AllInOne_UpRandom', '2')
  106.               xbmc.sleep(900)
  107.               xbmcgui.Window( 10000 ).setProperty('AllInOne_UpRandom', '1')  
  108.        
  109.     def _init_vars( self ):
  110.         self.WINDOW = xbmcgui.Window( 10000 )          
  111.         self.Player = MyPlayer( action = self._update, movies = ( self.MOVIES == 'true' ), episodes = ( self.EPISODES == 'true' ), albums = ( self.ALBUMS == 'true' ))
  112.         #self.Uprandom = UpdateRandom(upaction = self._fetch_randomup)  
  113.        
  114.     def _fetch_info( self ):        
  115.         if self.MOVIES == 'true' or self.MOVIESRANDOM == 'true':
  116.             self._fetch_movies()
  117.             if self.MOVIES == 'true':
  118.                self._fetch_moviesprogress()
  119.             if self.WINDOW.getProperty('AllInOne_UpRandom') == "0" and self.MOVIESRANDOM == 'true':
  120.                self._fetch_moviesrandom()                      
  121.         if self.MOVIES == 'true':            
  122.             self._clearproperties_moviesprogress()
  123.             self._setproperties_moviesprogress()
  124.         if self.MOVIES == 'false':
  125.             self._clearproperties_moviesprogress()        
  126.         if self.WINDOW.getProperty('AllInOne_UpRandom') == "0" and self.MOVIESRANDOM == 'true':
  127.             self._clearproperties_moviesrandom()
  128.             self._setproperties_moviesrandom()
  129.         if self.MOVIESRANDOM == 'false':
  130.             self._clearproperties_moviesrandom()        
  131.         if self.EPISODES == 'true' or self.EPISODESRANDOM == 'true':                      
  132.             self._fetch_tvshows()
  133.             if self.EPISODES == 'true' or self.EPISODESRANDOMTYPE == 'INPROGRESS':
  134.                self._fetch_episodes()
  135.             if self.WINDOW.getProperty('AllInOne_UpRandom') == "0" and self.EPISODESRANDOM == 'true':
  136.                if self.EPISODESRANDOMTYPE == 'ALL':
  137.                   self._fetch_episodesrandom()
  138.                if self.EPISODESRANDOMTYPE == 'INPROGRESS':
  139.                   self._fetch_episodesrandomprogress()
  140.         if self.EPISODES == 'true':
  141.             self._clearproperties_episodesprogress()
  142.             self._setproperties_episodesprogress()
  143.         if self.EPISODES == 'false':
  144.             self._clearproperties_episodesprogress()
  145.         if self.WINDOW.getProperty('AllInOne_UpRandom') == "0" and self.EPISODESRANDOM == 'true':
  146.             self._clearproperties_episodesrandom()
  147.             self._setproperties_episodesrandom()
  148.         if self.EPISODESRANDOM == 'false':
  149.             self._clearproperties_episodesrandom()    
  150.         if self.MUSICVIDEOS == 'true':
  151.             self._fetch_musicvideos()
  152.             if self.WINDOW.getProperty('AllInOne_UpRandom') == "0":
  153.                self._fetch_musicvideosrandom()  
  154.         if self.MUSICVIDEOS == 'true':
  155.             if self.WINDOW.getProperty('AllInOne_UpRandom') == "0":
  156.                self._clearproperties_musicvideosrandom()
  157.                self._setproperties_musicvideosrandom()
  158.         if self.MUSICVIDEOS == 'false':
  159.             self._clearproperties_musicvideosrandom()
  160.         if self.ALBUMS == 'true' or self.ALBUMSRANDOM == 'true':
  161.             self._fetch_songsbase()
  162.             if self.WINDOW.getProperty('AllInOne_UpRandom') == "0" and self.ALBUMSRANDOM == 'true':
  163.                self._fetch_songsrandom()
  164.                self._fetch_albunsrandom()
  165.             self._fetch_songs()
  166.             self._fetch_albums()
  167.         if self.ALBUMS == 'true':
  168.             self._clearproperties_albumprogress()
  169.             self._setproperties_albumprogress()
  170.         if self.ALBUMS == 'false':
  171.             self._clearproperties_albumprogress()
  172.         if self.WINDOW.getProperty('AllInOne_UpRandom') == "0" and self.ALBUMSRANDOM == 'true':
  173.             self._clearproperties_albunsrandom()
  174.             self._clearproperties_songsrandom()
  175.             self._setproperties_songsrandom()
  176.             self._setproperties_albunsrandom()
  177.         if self.ALBUMSRANDOM == 'false':
  178.             self._clearproperties_albunsrandom()            
  179.             self._clearproperties_songsrandom()
  180.                
  181.     def _fetch_randomup(self):
  182.          if xbmcgui.Window( 10000 ).getProperty('AllInOne_UpRandomMovies')== '1':
  183.             self._fetch_moviesrandom()
  184.             self._clearproperties_moviesrandom()                                
  185.             self._setproperties_moviesrandom()
  186.          if xbmcgui.Window( 10000 ).getProperty('AllInOne_UpRandomEpisodes')== '1':
  187.             if self.EPISODESRANDOMTYPE == 'ALL':
  188.                self._fetch_episodesrandom()
  189.             if self.EPISODESRANDOMTYPE == 'INPROGRESS':
  190.                self._fetch_episodesrandomprogress()
  191.             self._clearproperties_episodesrandom()
  192.             self._setproperties_episodesrandom()
  193.          if xbmcgui.Window( 10000 ).getProperty('AllInOne_UpRandomMusicVideos')== '1':
  194.             self._fetch_musicvideosrandom()
  195.             self._clearproperties_musicvideosrandom()
  196.             self._setproperties_musicvideosrandom()
  197.          if xbmcgui.Window( 10000 ).getProperty('AllInOne_UpRandomMusic')== '1':
  198.             self._fetch_songsrandom()
  199.             self._fetch_albunsrandom()
  200.             self._clearproperties_albunsrandom()
  201.             self._clearproperties_songsrandom()
  202.             self._setproperties_songsrandom()
  203.             self._setproperties_albunsrandom()  
  204.          
  205.     def _fetch_movies( self ):
  206.         self.movies = []
  207.         json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": {"properties": ["title", "resume", "genre", "studio", "tagline", "runtime", "fanart", "thumbnail", "file", "plot", "plotoutline", "year", "lastplayed", "rating", "trailer", "mpaa"]}, "id": 1}')
  208.         json_query = unicode(json_query, 'utf-8', errors='ignore')
  209.         json_response = simplejson.loads(json_query)
  210.         if json_response.has_key('result') and json_response['result'].has_key('movies'):
  211.             for item in json_response['result']['movies']:
  212.                     title = item['title']
  213.                     year = str(item['year'])
  214.                     genre = item['genre']
  215.                     studio = item['studio']
  216.                     plot = item['plot']
  217.                     plotoutline = item['plotoutline']
  218.                     tagline = item['tagline']
  219.                     runtime = str(item['runtime'] / 60)
  220.                     fanart = item['fanart']
  221.                     thumbnail = item['thumbnail']
  222.                     path = item['file']
  223.                     rating = str(round(float(item['rating']),1))
  224.                     trailer = item['trailer']
  225.                     mpaa = item['mpaa']
  226.                     resumeposition = str(int(item['resume']['position']))
  227.                     if item.has_key('resume') and item['resume']['position'] > 0:
  228.                         percentplayed = str(int(item['resume']['position']*100) / int(item['resume']['total']))
  229.                     else:
  230.                         percentplayed = "0"
  231.                     if item.has_key('resume'):
  232.                         # catch exceptions where the lastplayed isn't returned by json-rpc (bug?)
  233.                         lastplayed = item['lastplayed']
  234.                     else:
  235.                         lastplayed = ''
  236.                     if lastplayed == '':
  237.                         # catch exceptions where the item has been partially played, but playdate wasn't stored in the db
  238.                         lastplayed = '0'
  239.                     else:
  240.                         datetime = strptime(lastplayed, "%Y-%m-%d %H:%M:%S")
  241.                         lastplayed = str(mktime(datetime))
  242.                     self.movies.append([title, year, genre, studio, plot, plotoutline, tagline, runtime, fanart, thumbnail, path, rating, lastplayed, percentplayed, trailer, resumeposition, mpaa])
  243.         xbmc.log(msg="xxxxxxxxxxxxxxxxxx terminou de preencher os filmesxxxxxxxxxxxxxxxxxxxxxxxxx")
  244.     def _fetch_moviesrandom( self ):
  245.         self.moviesrandombase = list(self.movies)
  246.         self.moviesrandomlist = []
  247.         count = 0
  248.         while count < self.LIMIT:
  249.               if len(self.moviesrandombase) == 0:
  250.                  break
  251.               count += 1
  252.               randomitem = random.choice( self.moviesrandombase )
  253.               title = randomitem[0]
  254.               year = randomitem[1]
  255.               genre = randomitem[2]
  256.               studio = randomitem[3]
  257.               plot = randomitem[4]
  258.               plotoutline = randomitem[5]
  259.               tagline = randomitem[6]
  260.               runtime = randomitem[7]
  261.               fanart = randomitem[8]
  262.               thumbnail = randomitem[9]
  263.               path = randomitem[10]
  264.               rating = randomitem[11]
  265.               lastplayed = randomitem[12]
  266.               percentplayed = randomitem[13]
  267.               trailer = randomitem[14]
  268.               mpaa = randomitem[16]
  269.               self.moviesrandomlist.append([title, year, genre, studio, plot, plotoutline, tagline, runtime, fanart, thumbnail, path, rating, percentplayed, trailer, lastplayed, mpaa])
  270.               self.moviesrandombase.remove(randomitem)
  271.         self._clearproperties_moviesrandom()
  272.         self._setproperties_moviesrandom()
  273.  
  274.     def _fetch_moviesprogress( self ):
  275.        self.moviesprogress = self.movies
  276.        self.moviesprogresslist = []
  277.        for itemprogress in self.moviesprogress:
  278.            if int(itemprogress[15]) > 0:
  279.               title = itemprogress[0]
  280.               year = itemprogress[1]
  281.               genre = itemprogress[2]
  282.               studio = itemprogress[3]
  283.               plot = itemprogress[4]
  284.               plotoutline = itemprogress[5]
  285.               tagline = itemprogress[6]
  286.               runtime = itemprogress[7]
  287.               fanart = itemprogress[8]
  288.               thumbnail = itemprogress[9]
  289.               path = itemprogress[10]
  290.               rating = itemprogress[11]
  291.               lastplayed = itemprogress[12]
  292.               percentplayed = itemprogress[13]
  293.               trailer = itemprogress[14]
  294.               mpaa = itemprogress[16]
  295.               self.moviesprogresslist.append([lastplayed, title, year, genre, studio, plot, plotoutline, tagline, runtime, fanart, thumbnail, path, rating, percentplayed, trailer, mpaa])
  296.               self.moviesprogresslist.sort(reverse = True)
  297.            
  298.     def _fetch_tvshows( self ):
  299.         self.tvshows = []
  300.         self.episodesrandombase = []
  301.         # fetch all episodes in one query
  302.         json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"properties": ["title", "playcount", "plot", "season", "episode", "showtitle", "file", "lastplayed", "rating", "tvshowid"], "sort": {"method": "episode"} }, "id": 1}' )
  303.         json_query = unicode(json_query, 'utf-8', errors='ignore')
  304.         json_response = simplejson.loads(json_query)
  305.         if json_response.has_key('result') and json_response['result'].has_key('episodes'):
  306.             json_response = json_response['result']['episodes']
  307.             # our list is sorted by episode number, secondary we sort by tvshow title (itertools.groupy needs contiguous items) and split it into seperate lists for each tvshow
  308.             episodes = [list(group) for key,group in itertools.groupby(sorted(json_response, key=itemgetter('showtitle')), key=itemgetter('showtitle'))]
  309.             self.episodesrandombase = list(json_response)
  310.         # fetch all tvshows, sorted by title
  311.         json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties": ["title", "studio", "thumbnail", "fanart"], "sort": {"method": "title"}}, "id": 1}')
  312.         json_query = unicode(json_query, 'utf-8', errors='ignore')
  313.         json_response = simplejson.loads(json_query)
  314.         if json_response.has_key('result') and json_response['result'].has_key('tvshows'):
  315.             for count, tvshow in enumerate(json_response['result']['tvshows']):
  316.                 item = [tvshow['tvshowid'], tvshow['thumbnail'], tvshow['studio'], tvshow['title'], tvshow['fanart'], []]
  317.                 for episodelist in episodes:
  318.                     if episodelist[0]['showtitle'] == item[3]:
  319.                         item[5] = episodelist
  320.                         break
  321.                 self.tvshows.append(item)
  322.  
  323.     def _fetch_seasonthumb( self, tvshowid, seasonnumber ):
  324.         json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetSeasons", "params": {"properties": ["season", "thumbnail"], "tvshowid":%s }, "id": 1}' % tvshowid)
  325.         json_query = unicode(json_query, 'utf-8', errors='ignore')
  326.         json_response = simplejson.loads(json_query)
  327.         if json_response.has_key('result') and json_response['result'].has_key('seasons'):
  328.             for item in json_response['result']['seasons']:
  329.                 season = "%.2d" % float(item['season'])
  330.                 if season == seasonnumber:
  331.                     thumbnail = item['thumbnail']
  332.                     xbmc.log(msg="retornou o thumbnail")
  333.                     return thumbnail
  334.                    
  335.     def _fetch_episodepercent( self, tvshowid, seasonnumber, episodenumber ):
  336.         json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"properties": ["episode", "season", "resume"], "tvshowid":%s }, "id": 1}' % tvshowid)
  337.         json_query = unicode(json_query, 'utf-8', errors='ignore')
  338.         json_response = simplejson.loads(json_query)
  339.         if json_response.has_key('result') and json_response['result'] != None and json_response['result'].has_key('episodes'):
  340.             for epipercent in json_response['result']['episodes']:
  341.                 season = "%.2d" % float(epipercent['season'])
  342.                 episode = "%.2d" % float(epipercent['episode'])
  343.                 if season == seasonnumber and episode == episodenumber:
  344.                     try:
  345.                        percentplayed = str(int(epipercent['resume']['position']*100) / int(epipercent['resume']['total']))
  346.                        return percentplayed
  347.                     except:
  348.                        percentplayed = "0"
  349.                        return percentplayed
  350.                        
  351.     def _fetch_episodethumb( self, tvshowid, seasonnumber, episodenumber,):
  352.         json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"properties": ["episode", "season", "thumbnail"], "tvshowid":%s }, "id": 1}' % tvshowid)
  353.         json_query = unicode(json_query, 'utf-8', errors='ignore')
  354.         json_response = simplejson.loads(json_query)
  355.         if json_response.has_key('result') and json_response['result'] != None and json_response['result'].has_key('episodes'):
  356.             for image in json_response['result']['episodes']:
  357.                 season = "%.2d" % float(image['season'])
  358.                 episode = "%.2d" % float(image['episode'])
  359.                 if season == seasonnumber and episode == episodenumber:                  
  360.                    thumbnail = image['thumbnail']
  361.                    xbmc.log(msg="retornou o EPISODE thumbnail")
  362.                    return  thumbnail                  
  363.  
  364.     def _fetch_episodes( self ):
  365.         self.episodes = []
  366.         self.eprandomprgbase = []
  367.         for tvshow in self.tvshows:
  368.             lastplayed = ""
  369.             episode_sorter = lambda item: (int(item['season']), int(item['episode']))
  370.             for key, group in itertools.groupby(sorted(tvshow[5], key=episode_sorter), episode_sorter):
  371.                 playcount = 0
  372.                 for item in sorted(group, key=lambda x: (x['lastplayed'], x['episodeid'])):
  373.                     # sort first by lastplayed, so we're certain to always get the latest played item upon final iteration of the loop. Then sort by episodeid, mainly for the case where lastplayed is empty for all items, and we want the latest episodeid to be the one chosen (higher episodeid equals being added later to xbmc)
  374.                     playcount += int(item['playcount'])
  375.                 if playcount != 0:
  376.                     # this episode has been watched, record play date (we need it for sorting the final list) and continue to next episode
  377.                     lastplayed = item['lastplayed']
  378.                     if lastplayed == '':
  379.                         # catch exceptions where the episode has been played, but playdate wasn't stored in the db
  380.                         lastplayed = '0'
  381.                     else:
  382.                         datetime = strptime(lastplayed, "%Y-%m-%d %H:%M:%S")
  383.                         lastplayed = str(mktime(datetime))
  384.                     continue
  385.                 else:
  386.                     # this is the first unwatched episode, check if the episode is partially watched
  387.                     playdate = item['lastplayed']
  388.                     if (lastplayed == "") and (playdate == ""):
  389.                         # it's a tv show with 0 watched episodes, continue to the next tv show
  390.                         break
  391.                     else:
  392.                         # this is the episode we need
  393.                         title = item['title']
  394.                         episode = "%.2d" % float(item['episode'])
  395.                         path = item['file']
  396.                         plot = item['plot']
  397.                         season = "%.2d" % float(item['season'])
  398.                         thumbnail = ''
  399.                         showtitle = item['showtitle']
  400.                         rating = str(round(float(item['rating']),1))
  401.                         episodeno = "s%se%s" % ( season,  episode, )
  402.                         if not playdate == '':
  403.                             # if the episode is partially watched, use it's playdate for sorting
  404.                             datetime = strptime(playdate, "%Y-%m-%d %H:%M:%S")
  405.                             lastplayed = str(mktime(datetime))
  406.                             resumable = "True"
  407.                         else:
  408.                             resumable = "False"
  409.                         tvshowid = tvshow[0]
  410.                         showthumb = tvshow[1]
  411.                         studio = tvshow[2]
  412.                         fanart = tvshow[4]
  413.                         seasonthumb = ''
  414.                         percentplayed = '0'
  415.                         self.episodes.append([lastplayed, title, episode, season, plot, showtitle, path, thumbnail, fanart, episodeno, studio, showthumb, seasonthumb, resumable, rating, playcount, tvshowid, percentplayed])
  416.                         # we have found our episode, collected all data, so continue to next tv show
  417.                         break
  418.         self.episodes.sort(reverse=True)
  419.         self.eprandomprgbase = list(self.episodes)
  420.         # only fetch seasonthumbs for items that will actually show up in the skin
  421.         for count, episode in enumerate( self.episodes ):
  422.             count += 1
  423.             tvshowid = episode[16]
  424.             season = episode[3]
  425.             episodenumber = episode[2]
  426.             episode[12] = self._fetch_seasonthumb(tvshowid, season)
  427.             if self.EPISODEBARHIDE == 'false':
  428.                episode[17] = self._fetch_episodepercent(tvshowid, season, episodenumber)
  429.             episode[7] = self._fetch_episodethumb(tvshowid, season, episodenumber)
  430.             teste1 = str(episode[17])
  431.             if count == 10:
  432.                 # stop here if our list contains more items
  433.                 break
  434.         log("episode list: %s items" % len(self.episodes))
  435.        
  436.     def _fetch_episodesrandom( self ):
  437.         self.episodesrandomlistbase = list(self.eprandomprgbase)
  438.         self.episodesrandomlist = []  
  439.         count = 0
  440.         while count < self.LIMIT:
  441.              if len(self.episodesrandomlistbase) == 0:
  442.                 return
  443.              count += 1
  444.              randomitem = random.choice( self.episodesrandomlistbase )
  445.              title = randomitem['title']
  446.              showtitle = randomitem['showtitle']
  447.              season = "%.2d" % float(randomitem['season'])
  448.              episode = "%.2d" % float(randomitem['episode'])
  449.              rating = str(round(float(randomitem['rating']),1))
  450.              plot = randomitem['plot']
  451.              path = randomitem['file']
  452.              thumb =''
  453.              fanart = ''
  454.              episodeno = "s%se%s" % ( season,  episode, )
  455.              tvshowid = randomitem['tvshowid']
  456.              seasonthumb = ''
  457.              self.episodesrandomlist.append([title, showtitle, season, episode, rating, plot, path, thumb, fanart, episodeno, seasonthumb, tvshowid])
  458.              self.episodesrandomlistbase.remove(randomitem)
  459.         for count, episode in enumerate( self.episodesrandomlist ):
  460.             count += 1
  461.             tvshowid = episode[11]
  462.             season = episode[2]
  463.             episodenumber = episode[3]
  464.             episode[10] = self._fetch_seasonthumb(tvshowid, season)
  465.             episode[7] = self._fetch_episodethumb(tvshowid, season, episodenumber)            
  466.             if count == 10:
  467.                 # stop here if our list contains more items
  468.                 break    
  469.    
  470.     def _fetch_episodesrandomprogress( self ):
  471.         self.episodesrandomlistbase = list(self.eprandomprgbase)
  472.         self.episodesrandomlist = []  
  473.         count = 0
  474.         while count < self.LIMIT:
  475.              if len(self.episodesrandomlistbase) == 0:
  476.                 return
  477.              count += 1
  478.              randomitem = random.choice( self.episodesrandomlistbase )
  479.              title = randomitem[1]
  480.              showtitle = randomitem[5]
  481.              season = randomitem[3]
  482.              episode = randomitem[2]
  483.              rating = randomitem[14]
  484.              plot = randomitem[4]
  485.              path = randomitem[6]
  486.              thumb =''
  487.              fanart = randomitem[8]
  488.              episodeno = randomitem[9]
  489.              tvshowid = randomitem[16]
  490.              seasonthumb = ''
  491.              self.episodesrandomlist.append([title, showtitle, season, episode, rating, plot, path, thumb, fanart, episodeno, seasonthumb, tvshowid])
  492.              self.episodesrandomlistbase.remove(randomitem)
  493. #0lastplayed, 1title, 2episode, 3season, 4plot, 5showtitle, 6path, 7thumbnail, 8fanart, 9episodeno, 10studio, 11showthumb, 12seasonthumb, 13resumable, 14rating, 15playcount, 16tvshowid, 17percentplayed]
  494.         for count, episode in enumerate( self.episodesrandomlist ):
  495.             count += 1
  496.             tvshowid = episode[11]
  497.             season = episode[2]
  498.             episodenumber = episode[3]
  499.             episode[10] = self._fetch_seasonthumb(tvshowid, season)
  500.             episode[7] = self._fetch_episodethumb(tvshowid, season, episodenumber)            
  501.             if count == 10:
  502.                 # stop here if our list contains more items
  503.                 break
  504.                
  505.     def _fetch_musicvideos( self ):
  506.         self.musicvideos = []
  507.         json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMusicVideos", "params": {"properties": ["title", "resume", "genre", "studio", "runtime", "fanart", "thumbnail", "file", "plot", "year", "lastplayed", "playcount"]}, "id": 1}')
  508.         json_query = unicode(json_query, 'utf-8', errors='ignore')
  509.         json_response = simplejson.loads(json_query)
  510.         if json_response.has_key('result') and json_response['result'] != None and json_response['result'].has_key('musicvideos'):
  511.             for item in json_response['result']['musicvideos']:
  512.                     title = item['title']
  513.                     year = str(item['year'])
  514.                     genre = item['genre']
  515.                     studio = item['studio']
  516.                     plot = item['plot']
  517.                     runtime = str(item['runtime'] / 60)
  518.                     fanart = item['fanart']
  519.                     thumbnail = item['thumbnail']
  520.                     path = item['file']
  521.                     resumeposition = str(int(item['resume']['position']))
  522.                     if item.has_key('resume') and item['resume']['position'] > 0:
  523.                         percentplayed = str(int(item['resume']['position']*100) / int(item['resume']['total']))
  524.                     else:
  525.                         percentplayed = "0"
  526.                     if item.has_key('resume'):
  527.                         # catch exceptions where the lastplayed isn't returned by json-rpc (bug?)
  528.                         lastplayed = item['lastplayed']
  529.                     else:
  530.                         lastplayed = ''
  531.                     if lastplayed == '':
  532.                         # catch exceptions where the item has been partially played, but playdate wasn't stored in the db
  533.                         lastplayed = '0'
  534.                     else:
  535.                         datetime = strptime(lastplayed, "%Y-%m-%d %H:%M:%S")
  536.                         lastplayed = str(mktime(datetime))
  537.                     self.musicvideos.append([title, year, genre, studio, plot, runtime, fanart, thumbnail, path, lastplayed, percentplayed, resumeposition])      
  538.  
  539.     def _fetch_musicvideosrandom( self ):
  540.         self.musicvideosrandombase = list(self.musicvideos)
  541.         self.musicvideosrandomlist = []
  542.         count = 0
  543.         while count < self.LIMIT:
  544.               if len(self.musicvideosrandombase) == 0:
  545.                  break
  546.               count += 1
  547.               randomitem = random.choice( self.musicvideosrandombase )
  548.               title = randomitem[0]
  549.               year = randomitem[1]
  550.               genre = randomitem[2]
  551.               studio = randomitem[3]
  552.               plot = randomitem[4]
  553.               runtime = randomitem[5]
  554.               fanart = randomitem[6]
  555.               thumbnail = randomitem[7]
  556.               path = randomitem[8]
  557.               lastplayed = randomitem[9]
  558.               percentplayed = randomitem[10]
  559.               self.musicvideosrandomlist.append([title, year, genre, studio, plot, runtime, fanart, thumbnail, path, percentplayed, lastplayed])
  560.               self.musicvideosrandombase.remove(randomitem)        
  561.            
  562.     def _fetch_songsbase( self ):
  563.         self.songsbase = []
  564.         json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "AudioLibrary.GetSongs", "params": {"properties": ["title", "artist", "fanart", "thumbnail", "year", "genre", "file", "albumid"]}, "id": 1}')
  565.         json_query = unicode(json_query, 'utf-8', errors='ignore')
  566.         json_response = simplejson.loads(json_query)
  567.         if json_response.has_key('result') and (json_response['result'] != None) and  (json_response['result'].has_key('songs')):
  568.             for item in json_response['result']['songs']:
  569.                   title = item['title']
  570.                   artist = item['artist']
  571.                   fanart = item['fanart']
  572.                   thumbnail = item['thumbnail']
  573.                   year = str(item['year'])
  574.                   genre = item['genre']
  575.                   path = item['file']
  576.                   albumid = str(item['albumid'])
  577.                   countrandom = ""
  578.                   self.songsbase.append([title, artist, fanart, thumbnail, year, genre, countrandom, path, albumid])
  579.                  
  580.     def _fetch_songsrandom( self ):
  581.         self.songsrandombase = list(self.songsbase)
  582.         self.songsrandomlist = []
  583.         repeatalbum = {}
  584.         count = 0
  585.         while count < self.LIMIT:
  586.               if len(self.songsrandombase) == 0:
  587.                  break
  588.               count += 1
  589.               randomitem = random.choice( self.songsrandombase )
  590.               title = randomitem[0]
  591.               artist = randomitem[1]
  592.               fanart = randomitem[2]
  593.               thumbnail = randomitem[3]
  594.               year = str(randomitem[4])
  595.               genre = randomitem[5]
  596.               countrandom = str(count)
  597.               path = randomitem[7]
  598.               albumid = str(randomitem[8])
  599.               if albumid in repeatalbum:
  600.                  self.songsrandombase.remove(randomitem)
  601.                  count  -= 1
  602.                  continue
  603.               repeatalbum[albumid] = 1
  604.               self.songsrandomlist.append([title, artist, fanart, thumbnail, year, genre, countrandom, path, albumid])
  605.               self.songsrandombase.remove(randomitem)
  606.              
  607.     def _fetch_albunsrandom( self ):
  608.         self.albunsrandom = []
  609.         for count, albumsongs in enumerate( self.songsrandomlist ):
  610.            json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "AudioLibrary.GetAlbumDetails", "params": {"properties": ["title", "artist", "fanart", "thumbnail", "year", "genre", "albumlabel"], "albumid":%s }, "id": 1}' % albumsongs[8])
  611.            json_query = unicode(json_query, 'utf-8', errors='ignore')
  612.            json_response = simplejson.loads(json_query)
  613.            if json_response.has_key('result') and (json_response['result'] != None) and  (json_response['result'].has_key('albumdetails')):
  614.                     randomitem = json_response['result']['albumdetails']
  615.                     albumlabel = randomitem['albumlabel']
  616.                     title = randomitem['title']
  617.                     artist = randomitem['artist']
  618.                     fanart = randomitem['fanart']
  619.                     thumbnail = randomitem['thumbnail']
  620.                     year = str(randomitem['year'])
  621.                     genre = randomitem['genre']
  622.                     albumid = albumsongs[8]
  623.                     playlistpath = "musicdb://3/%s/" % albumid
  624.                     #playlistpath = 'XBMC.RunScript(' + __addonid__ + ',albumid=' + albumid + ')'
  625.                     self.albunsrandom.append([title, artist, fanart, thumbnail, year, genre, playlistpath, albumid ])                                                                      
  626.                              
  627.     def _fetch_songs( self ):
  628.         self.albumsids = {}
  629.         previousid = ''
  630.         json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "AudioLibrary.GetSongs", "params": {"properties": ["playcount", "albumid"], "sort": { "method": "album" } }, "id": 1}')
  631.         json_query = unicode(json_query, 'utf-8', errors='ignore')
  632.         json_response = simplejson.loads(json_query)
  633.         if json_response.has_key('result') and (json_response['result'] != None) and (json_response['result'].has_key('songs')):
  634.             for item in json_response['result']['songs']:
  635.                 albumid = item['albumid']
  636.                 if albumid != '':
  637.                     # ignore single tracks that do not belong to an album
  638.                     if albumid != previousid:
  639.                         # new album
  640.                         albumplaycount = 0
  641.                         playcount = item['playcount']
  642.                         albumplaycount = albumplaycount + playcount
  643.                         previousid = albumid
  644.                     else:
  645.                         # song from the same album
  646.                         playcount = item['playcount']
  647.                         albumplaycount = albumplaycount + playcount
  648.                     if playcount != 0:
  649.                         # don't add unplayed items
  650.                         self.albumsids.update({albumid: albumplaycount})
  651.         self.albumsids = sorted(self.albumsids.items(), key=itemgetter(1))
  652.         self.albumsids.reverse()
  653.  
  654.     def _fetch_albums( self ):
  655.         self.albums = []
  656.         for count, albumid in enumerate( self.albumsids ):
  657.             count += 1
  658.             json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "AudioLibrary.GetAlbumDetails", "params": {"properties": ["title", "description", "albumlabel", "artist", "genre", "year", "thumbnail", "fanart", "rating"], "albumid":%s }, "id": 1}' % albumid[0])
  659.             json_query = unicode(json_query, 'utf-8', errors='ignore')
  660.             json_response = simplejson.loads(json_query)
  661.             if json_response.has_key('result') and (json_response['result'] != None) and json_response['result'].has_key('albumdetails'):
  662.                 item = json_response['result']['albumdetails']
  663.                 description = item['description']
  664.                 album = item['title']
  665.                 albumlabel = item['albumlabel']
  666.                 artist = item['artist']
  667.                 genre = item['genre']
  668.                 year = str(item['year'])
  669.                 thumbnail = item['thumbnail']
  670.                 fanart = item['fanart']
  671.                 rating = str(item['rating'])
  672.                 stralbumid = str(albumid[0])
  673.                 if rating == '48':
  674.                     rating = ''
  675.                 path = "musicdb://3/%s/" % stralbumid    
  676.                 #path = 'XBMC.RunScript(' + __addonid__ + ',albumid=' + str(albumid[0]) + ')'
  677.                 self.albums.append((album, artist, genre, year, albumlabel, description, rating, thumbnail, fanart, path))
  678.             if count == int(self.LIMIT):
  679.                 # stop here if our list contains more items
  680.                 break                
  681.  
  682.     def _play_album( self, ID ):
  683.         json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "AudioLibrary.GetSongs", "params": {"properties": ["file", "fanart", "thumbnail"], "albumid":%s }, "id": 1}' % ID)
  684.         json_query = unicode(json_query, 'utf-8', errors='ignore')
  685.         json_response = simplejson.loads(json_query)
  686.         # create a playlist
  687.         playlist = xbmc.PlayList(0)
  688.         # clear the playlist
  689.         playlist.clear()
  690.         if json_response.has_key('result') and json_response['result'].has_key('songs'):
  691.             for item in json_response['result']['songs']:
  692.                 song = item['file']
  693.                 fanart = item['fanart']
  694.                 thumbnail= item['thumbnail']
  695.                 # create playlist item
  696.                 listitem = xbmcgui.ListItem()
  697.                 # add fanart image to the playlist item
  698.                 listitem.setProperty( "fanart_image", fanart )
  699.                 # add item to the playlist
  700.                 playlist.add( url=song, listitem=listitem )
  701.             # play the playlist
  702.             xbmc.Player().play( playlist )
  703.  
  704.     def _daemon( self ):
  705.         # keep running until xbmc exits or another instance is started
  706.         while (not xbmc.abortRequested) and self.WINDOW.getProperty('AllInOne_Running') == 'True':
  707.             buttonid = xbmcgui.Window( 10000 ).getProperty('AllInOne_UpRandomButtonId')
  708.             buttonget = str(xbmcgui.Window( 10000 ).getFocusId())            
  709.             if buttonid == buttonget and xbmcgui.Window( 10000 ).getProperty('AllInOne_UpRandom') == "2":
  710.                self._fetch_randomup()
  711.             if xbmc.getCondVisibility('Library.IsScanningMusic') or xbmc.getCondVisibility('Library.IsScanningVideo') :
  712.                while xbmc.getCondVisibility('Window.IsVisible(10112)') or xbmc.getCondVisibility('Window.IsVisible(10133)'):
  713.                     xbmc.sleep(500)
  714.                aiorecents.Main()
  715.             xbmc.sleep(1000)
  716.         if xbmc.abortRequested:
  717.             log('script stopped: xbmc quit')
  718.         else:
  719.             log('script stopped: new script instance started')          
  720.            
  721.     def _setproperties_moviesrandom( self ):
  722.         for count, movie in enumerate( self.moviesrandomlist ):
  723.             count += 1
  724.             self.WINDOW.setProperty( "AllinOne_MovieRandom.%d.Title" % ( count ), movie[0] )
  725.             self.WINDOW.setProperty( "AllinOne_MovieRandom.%d.Year" % ( count ), movie[1] )        
  726.             self.WINDOW.setProperty( "AllinOne_MovieRandom.%d.Genre" % ( count ), movie[2][0] )
  727.             self.WINDOW.setProperty( "AllinOne_MovieRandom.%d.Studio" % ( count ), movie[3][0] )
  728.             self.WINDOW.setProperty( "AllinOne_MovieRandom.%d.Plot" % ( count ), movie[4] )
  729.             self.WINDOW.setProperty( "AllinOne_MovieRandom.%d.PlotOutline" % ( count ), movie[5] )
  730.             self.WINDOW.setProperty( "AllinOne_MovieRandom.%d.Tagline" % ( count ), movie[6] )
  731.             self.WINDOW.setProperty( "AllinOne_MovieRandom.%d.RunningTime" % ( count ), movie[7] )
  732.             self.WINDOW.setProperty( "AllinOne_MovieRandom.%d.Fanart" % ( count ), movie[8] )
  733.             self.WINDOW.setProperty( "AllinOne_MovieRandom.%d.Thumb" % ( count ), movie[9] )
  734.             self.WINDOW.setProperty( "AllinOne_MovieRandom.%d.Path" % ( count ), movie[10] )
  735.             self.WINDOW.setProperty( "AllinOne_MovieRandom.%d.Rating" % ( count ), movie[11] )
  736.             self.WINDOW.setProperty( "AllinOne_MovieRandom.%d.PercentPlayed" % ( count ), movie[12] )
  737.             self.WINDOW.setProperty( "AllinOne_MovieRandom.%d.Trailer" % ( count ), movie[13] )
  738.             self.WINDOW.setProperty( "AllinOne_MovieRandom.%d.MPAA" % ( count ), movie[15] )
  739.             if count == self.LIMIT:
  740.                break      
  741.                              
  742.     def _setproperties_moviesprogress( self ):
  743.         for count, movie in enumerate( self.moviesprogresslist ):
  744.             count += 1
  745.             self.WINDOW.setProperty( "AllinOne_MovieProgress.%d.Title" % ( count ), movie[1] )
  746.             self.WINDOW.setProperty( "AllinOne_MovieProgress.%d.Year" % ( count ), movie[2] )
  747.             self.WINDOW.setProperty( "AllinOne_MovieProgress.%d.Genre" % ( count ), movie[3][0] )
  748.             self.WINDOW.setProperty( "AllinOne_MovieProgress.%d.Studio" % ( count ), movie[4][0] )
  749.             self.WINDOW.setProperty( "AllinOne_MovieProgress.%d.Plot" % ( count ), movie[5] )
  750.             self.WINDOW.setProperty( "AllinOne_MovieProgress.%d.PlotOutline" % ( count ), movie[6] )
  751.             self.WINDOW.setProperty( "AllinOne_MovieProgress.%d.Tagline" % ( count ), movie[7] )
  752.             self.WINDOW.setProperty( "AllinOne_MovieProgress.%d.RunningTime" % ( count ), movie[8] )
  753.             self.WINDOW.setProperty( "AllinOne_MovieProgress.%d.Fanart" % ( count ), movie[9] )
  754.             self.WINDOW.setProperty( "AllinOne_MovieProgress.%d.Thumb" % ( count ), movie[10] )
  755.             self.WINDOW.setProperty( "AllinOne_MovieProgress.%d.Path" % ( count ), movie[11] )
  756.             self.WINDOW.setProperty( "AllinOne_MovieProgress.%d.Rating" % ( count ), movie[12] )
  757.             self.WINDOW.setProperty( "AllinOne_MovieProgress.%d.PercentPlayed" % ( count ), movie[13] )
  758.             self.WINDOW.setProperty( "AllinOne_MovieProgress.%d.Trailer" % ( count ), movie[14] )
  759.             self.WINDOW.setProperty( "AllinOne_MovieProgress.%d.MPAA" % ( count ), movie[15] )
  760.             if count == self.LIMIT:
  761.                break    
  762.         xbmc.log(msg="terminou filmes em progress")
  763.     def _setproperties_episodesprogress( self ):
  764.         for count, episode in enumerate( self.episodes ):
  765.             count += 1
  766.             self.WINDOW.setProperty( "AllinOne_EpisodeProgress.%d.Title" % ( count ), episode[1] )
  767.             self.WINDOW.setProperty( "AllinOne_EpisodeProgress.%d.Episode" % ( count ), episode[2] )
  768.             self.WINDOW.setProperty( "AllinOne_EpisodeProgress.%d.Season" % ( count ), episode[3] )
  769.             self.WINDOW.setProperty( "AllinOne_EpisodeProgress.%d.Plot" % ( count ), episode[4] )
  770.             self.WINDOW.setProperty( "AllinOne_EpisodeProgress.%d.TVShowTitle" % ( count ), episode[5] )
  771.             self.WINDOW.setProperty( "AllinOne_EpisodeProgress.%d.Path" % ( count ), episode[6] )
  772.             self.WINDOW.setProperty( "AllinOne_EpisodeProgress.%d.Thumb" % ( count ), episode[7] )
  773.             self.WINDOW.setProperty( "AllinOne_EpisodeProgress.%d.Fanart" % ( count ), episode[8] )
  774.             self.WINDOW.setProperty( "AllinOne_EpisodeProgress.%d.EpisodeNo" % ( count ), episode[9] )
  775.             self.WINDOW.setProperty( "AllinOne_EpisodeProgress.%d.Studio" % ( count ), episode[10][0] )
  776.             self.WINDOW.setProperty( "AllinOne_EpisodeProgress.%d.TvshowThumb" % ( count ), episode[11] )
  777.             self.WINDOW.setProperty( "AllinOne_EpisodeProgress.%d.SeasonThumb" % ( count ), episode[12] )
  778.             self.WINDOW.setProperty( "AllinOne_EpisodeProgress.%d.IsResumable" % ( count ), episode[13] )
  779.             self.WINDOW.setProperty( "AllinOne_EpisodeProgress.%d.Rating" % ( count ), episode[14] )
  780.             self.WINDOW.setProperty( "AllinOne_EpisodeProgress.%d.PercentPlayed" % ( count ), episode[17] )
  781.             if count == self.LIMIT:
  782.                break
  783.            
  784.     def _setproperties_episodesrandom( self ):
  785.         for count, episode in enumerate( self.episodesrandomlist ):
  786.             count += 1
  787.             #[0title, 1showtitle, 2season, 3episode, 4rating, 5plot, 6path, 7thumb, 8fanart, 9episodeno])
  788.             self.WINDOW.setProperty( "AllinOne_EpisodeRandom.%d.Title" % ( count ), episode[0] )
  789.             self.WINDOW.setProperty( "AllinOne_EpisodeRandom.%d.Episode" % ( count ), episode[3] )
  790.             self.WINDOW.setProperty( "AllinOne_EpisodeRandom.%d.Season" % ( count ), episode[2] )
  791.             self.WINDOW.setProperty( "AllinOne_EpisodeRandom.%d.Plot" % ( count ), episode[5] )
  792.             self.WINDOW.setProperty( "AllinOne_EpisodeRandom.%d.TVShowTitle" % ( count ), episode[1] )
  793.             self.WINDOW.setProperty( "AllinOne_EpisodeRandom.%d.Path" % ( count ), episode[6] )
  794.             self.WINDOW.setProperty( "AllinOne_EpisodeRandom.%d.Thumb" % ( count ), episode[7] )
  795.             self.WINDOW.setProperty( "AllinOne_EpisodeRandom.%d.Fanart" % ( count ), episode[8] )
  796.             self.WINDOW.setProperty( "AllinOne_EpisodeRandom.%d.EpisodeNo" % ( count ), episode[9] )
  797.             #self.WINDOW.setProperty( "AllinOne_EpisodeRandom.%d.Studio" % ( count ), episode[10] )
  798.             #self.WINDOW.setProperty( "AllinOne_EpisodeRandom.%d.TvshowThumb" % ( count ), episode[11] )
  799.             self.WINDOW.setProperty( "AllinOne_EpisodeRandom.%d.SeasonThumb" % ( count ), episode[10] )
  800.             #self.WINDOW.setProperty( "AllinOne_EpisodeRandom.%d.IsResumable" % ( count ), episode[13] )
  801.             self.WINDOW.setProperty( "AllinOne_EpisodeRandom.%d.Rating" % ( count ), episode[4] )
  802.             #self.WINDOW.setProperty( "AllinOne_EpisodeRandom.%d.PercentPlayed" % ( count ), episode[17] )            
  803.             if count == self.LIMIT:
  804.                break
  805.    
  806.     def _setproperties_musicvideosrandom( self ):
  807.         for count, musicvideo in enumerate( self.musicvideosrandomlist ):
  808.             count += 1
  809.             self.WINDOW.setProperty( "AllinOne_MusicVideoRandom.%d.Title" % ( count ), musicvideo[0] )
  810.             self.WINDOW.setProperty( "AllinOne_MusicVideoRandom.%d.Year" % ( count ), musicvideo[1] )          
  811.             self.WINDOW.setProperty( "AllinOne_MusicVideoRandom.%d.Genre" % ( count ), musicvideo[2][0] )
  812.             self.WINDOW.setProperty( "AllinOne_MusicVideoRandom.%d.Studio" % ( count ), musicvideo[3][0] )
  813.             self.WINDOW.setProperty( "AllinOne_MusicVideoRandom.%d.Plot" % ( count ), musicvideo[4] )
  814.             self.WINDOW.setProperty( "AllinOne_MusicVideoRandom.%d.RunningTime" % ( count ), musicvideo[5] )
  815.             self.WINDOW.setProperty( "AllinOne_MusicVideoRandom.%d.Fanart" % ( count ), musicvideo[6] )
  816.             self.WINDOW.setProperty( "AllinOne_MusicVideoRandom.%d.Thumb" % ( count ), musicvideo[7] )
  817.             self.WINDOW.setProperty( "AllinOne_MusicVideoRandom.%d.Path" % ( count ), musicvideo[8] )
  818.             self.WINDOW.setProperty( "AllinOne_MusicVideoRandom.%d.PercentPlayed" % ( count ), musicvideo[9] )
  819.             if count == self.LIMIT:
  820.                break              
  821.  
  822.     def _setproperties_songsrandom( self ):
  823.         for count, songs in enumerate( self.songsrandomlist ):
  824.             count += 1
  825.             self.WINDOW.setProperty( "AllinOne_SongRandom.%d.Title" % ( count ), songs[0] )
  826.             self.WINDOW.setProperty( "AllinOne_SongRandom.%d.Artist" % ( count ), songs[1][0] )  
  827.             self.WINDOW.setProperty( "AllinOne_SongRandom.%d.Genre" % ( count ), songs[5][0] )
  828.             self.WINDOW.setProperty( "AllinOne_SongRandom.%d.Year" % ( count ), songs[4] )
  829.             self.WINDOW.setProperty( "AllinOne_SongRandom.%d.Thumb" % ( count ), songs[3] )
  830.             self.WINDOW.setProperty( "AllinOne_SongRandom.%d.Fanart" % ( count ), songs[2] )
  831.             self.WINDOW.setProperty( "AllinOne_SongRandom.%d.Path" % ( count ), songs[7] )
  832.             if count == int(self.LIMIT):
  833.                 # stop here if our list contains more items
  834.                 break
  835.            
  836.     def _setproperties_albunsrandom( self ):
  837.         for count, album in enumerate( self.albunsrandom ):
  838.             count += 1
  839.             self.WINDOW.setProperty( "AllinOne_AlbumRandom.%d.Title" % ( count ), album[0] )
  840.             self.WINDOW.setProperty( "AllinOne_AlbumRandom.%d.Artist" % ( count ), album[1][0] )
  841.             self.WINDOW.setProperty( "AllinOne_AlbumRandom.%d.Genre" % ( count ), album[5][0] )
  842.             self.WINDOW.setProperty( "AllinOne_AlbumRandom.%d.Year" % ( count ), album[4] )
  843.             self.WINDOW.setProperty( "AllinOne_AlbumRandom.%d.Thumb" % ( count ), album[3] )
  844.             self.WINDOW.setProperty( "AllinOne_AlbumRandom.%d.Fanart" % ( count ), album[2] )
  845.             self.WINDOW.setProperty( "AllinOne_AlbumRandom.%d.Path" % ( count ), album[6] )
  846.             if count == int(self.LIMIT):
  847.                 # stop here if our list contains more items
  848.                 break      
  849.  
  850.     def _setproperties_albumprogress( self ):
  851.         for count, album in enumerate( self.albums ):
  852.             count += 1
  853.             self.WINDOW.setProperty( "AllinOne_AlbumProgress.%d.Title" % ( count ), album[0] )
  854.             self.WINDOW.setProperty( "AllinOne_AlbumProgress.%d.Artist" % ( count ), album[1][0] )
  855.             self.WINDOW.setProperty( "AllinOne_AlbumProgress.%d.Genre" % ( count ), album[2][0] )
  856.             self.WINDOW.setProperty( "AllinOne_AlbumProgress.%d.Year" % ( count ), album[3] )
  857.             self.WINDOW.setProperty( "AllinOne_AlbumProgress.%d.Album_Label" % ( count ), album[4] )
  858.             self.WINDOW.setProperty( "AllinOne_AlbumProgress.%d.Album_Description" % ( count ), album[5] )
  859.             self.WINDOW.setProperty( "AllinOne_AlbumProgress.%d.Rating" % ( count ), album[6] )
  860.             self.WINDOW.setProperty( "AllinOne_AlbumProgress.%d.Thumb" % ( count ), album[7] )
  861.             self.WINDOW.setProperty( "AllinOne_AlbumProgress.%d.Fanart" % ( count ), album[8] )
  862.             self.WINDOW.setProperty( "AllinOne_AlbumProgress.%d.Path" % ( count ), album[9] )
  863.             if count == int(self.LIMIT):
  864.                 # stop here if our list contains more items
  865.                 break
  866.            
  867.     def _clearproperties_moviesrandom( self ):
  868.         for count in range (self.LIMIT):
  869.             count += 1
  870.             self.WINDOW.clearProperty( "AllinOne_MovieRandom.%d.Title" % ( count ) )
  871.            
  872.     def _clearproperties_moviesprogress( self ):
  873.         for count in range (self.LIMIT):
  874.             count += 1
  875.             self.WINDOW.clearProperty( "AllinOne_MovieProgress.%d.Title" % ( count ) )
  876.  
  877.     def _clearproperties_episodesprogress( self ):
  878.         for count in range( (self.LIMIT) ):
  879.             count += 1
  880.             self.WINDOW.clearProperty( "AllinOne_EpisodeProgress.%d.Title" % ( count ) )
  881.            
  882.     def _clearproperties_episodesrandom( self ):
  883.         for count in range((self.LIMIT) ):
  884.             count += 1
  885.             self.WINDOW.clearProperty( "AllinOne_EpisodeRandom.%d.Title" % ( count ) )
  886.    
  887.     def _clearproperties_musicvideosrandom( self ):
  888.         for count in range((self.LIMIT) ):
  889.             count += 1
  890.             self.WINDOW.clearProperty( "AllinOne_MusicVideoRandom.%d.Title" % ( count ) )
  891.            
  892.     def _clearproperties_musicvideosrecents( self ):
  893.         for count in range((self.LIMIT) ):
  894.             count += 1
  895.             self.WINDOW.clearProperty( "AllinOne_MusicVideoRecents.%d.Title" % ( count ) )
  896.            
  897.     def _clearproperties_albunsrandom( self ):
  898.         for count in range((self.LIMIT) ):
  899.             count += 1
  900.             self.WINDOW.clearProperty( "AllinOne_AlbumRandom.%d.Title" % ( count ) )
  901.            
  902.     def _clearproperties_songsrandom( self ):
  903.         for count in range((self.LIMIT) ):
  904.             count += 1
  905.             self.WINDOW.clearProperty( "AllinOne_SongRandom.%d.Title" % ( count ) )                
  906.            
  907.     def _clearproperties_albumprogress( self ):
  908.         for count in range((self.LIMIT) ):
  909.             count += 1
  910.             self.WINDOW.clearProperty( "AllinOne_AlbumProgress.%d.Title" % ( count ) )                                                
  911.            
  912.     def _update( self, type, item, ended ):
  913.       if self.MOVIES == 'true':
  914.         if type == 'movie':
  915.             xbmc.log(msg="iniciou o uptdate de filmes")
  916.             found = False
  917.             # Delete movie progress from lists
  918.             for count, movie in enumerate( self.moviesprogresslist ):
  919.                 if movie[11] == item[11]:
  920.                     item[9] = movie[9]
  921.                     item[10] = movie[10]
  922.                     item[14] = movie[14]
  923.                     item[15] = movie[15]
  924.                     del self.moviesprogresslist[count]
  925.                     found = True
  926.                     break
  927.             # If movie has a resume point, add it at the beginning
  928.             if not ended:
  929.                 if found:
  930.                     self.moviesprogresslist.insert( 0, item )
  931.                 else:
  932.                     for newprogress in self.movies:
  933.                         if newprogress[10] == item[11]:
  934.                             item[9] = newprogress[8]
  935.                             item[10] = newprogress[9]
  936.                             item[14] = newprogress[14]
  937.                             item[15] = newprogress[16]
  938.                             self.moviesprogresslist.insert( 0, item )
  939.                             break
  940. # movies [0title, 1year, 2genre, 3studio, 4plot, 5plotoutline, 6tagline, 7runtime, 8fanart, 9thumbnail, 10path, 11rating, 12lastplayed, 13percentplayed, 14trailer, 15resumeposition
  941. # item[0"", 1title, 2year, 3genre, 4studio, 5plot, 6plotoutline, 7tagline, 8runtime, 9"", 10"", 11path, 12rating, 13"", 14""]
  942. # progress[0lastplayed, 1title, 2year, 3genre, 4studio, 5plot, 6plotoutline, 7tagline, 8runtime, 9fanart, 10thumbnail, 11path, 12rating, 13percentplayed, 14trailer])
  943.  
  944.             self._clearproperties_moviesprogress()
  945.             self._setproperties_moviesprogress()
  946.         elif type == 'episode':
  947.           if self.EPISODES == 'true':
  948.             # Only update if it was a new, unwatched episode
  949.             if item[15] == 0:
  950.                 for tvshow in self.tvshows:
  951.                     xbmc.log(msg="passou na condicional 441")
  952.                     # If tv show names match, set missing values
  953.                     if tvshow[3] == item[5]:
  954.                         # se a serie ja se encontra na lista tvshow
  955.                         fanart = tvshow[4]
  956.                         item[8] = fanart
  957.                         item[10] = tvshow[2]
  958.                         item[11] = tvshow[1]
  959.                         tvshowid = tvshow[0]
  960.                         item[16] = tvshowid
  961.                         if self.EPISODEBARHIDE == 'true':
  962.                            item[17] = '0'
  963.                         # Delete episode from watch list episodes
  964.                         new = True
  965.                         xbmc.log(msg="passou na condicional 451")
  966.                         for count, episode in enumerate( self.episodes ):
  967.                             # Se a serie ja se encontra na lista episodes
  968.                             if episode[5] == item[5]:
  969.                                 # record our seasonthumb here since we need it later on
  970.                                 seasonthumb = episode[12]
  971.                                 item[12] = seasonthumb
  972.                                 item[7] = episode[7]
  973.                                 for epthumb in tvshow[5]:
  974.                                     seasonnumber = "%.2d" % float(epthumb['season'])
  975.                                     episodenumber = "%.2d" % float(epthumb['episode'])
  976.                                     if episodenumber == item[2] and seasonnumber == item[3]:
  977.                                         item[7] = self._fetch_episodethumb(tvshowid, seasonnumber, episodenumber)
  978.                                 xbmc.log(msg="passou na condicional 464")
  979.                                 del self.episodes[count]
  980.                                 new = False
  981.                                 break
  982.                         # If the show is marked as watched, check for a new episode to add
  983.                         # else add the episode at the beginning of the list
  984.                         if ended:
  985.                             xbmc.log(msg="passou na condicional 472")
  986.                             update = False
  987.                             insert = False
  988.                             for ep in tvshow[5]:
  989.                                 xbmc.log(msg="passou na condicional 475")
  990.                                 seasonnumber = "%.2d" % float(ep['season'])
  991.                                 episodenumber = "%.2d" % float(ep['episode'])
  992.                                 if ( episodenumber != item[2] or seasonnumber != item[3] ) and ep['playcount'] == 0:
  993.                                     if seasonnumber != item[3]:
  994.                                         # our new episode is from the next season, so fetch seasonthumb
  995.                                         seasonthumb = self._fetch_seasonthumb(tvshowid, seasonnumber)
  996.                                     xbmc.log(msg="passou na condicional 482")
  997.                                     percentplayed = '0'
  998.                                     if self.EPISODEBARHIDE == 'false':
  999.                                        percentplayed = self._fetch_episodepercent(tvshowid, seasonnumber, episodenumber)                                    
  1000.                                     thumbnail = self._fetch_episodethumb(tvshowid, seasonnumber, episodenumber)
  1001.                                     self.episodes.insert( 0, [ep['lastplayed'], ep['title'], episodenumber, seasonnumber, ep['plot'], ep['showtitle'], ep['file'], thumbnail, fanart, "s%se%s" % ( seasonnumber,  episodenumber, ), tvshow[2], tvshow[1], seasonthumb, "True", str(round(float(ep['rating']),1)), ep['playcount'],tvshowid, percentplayed] )
  1002.                                     insert = True
  1003.                                     if update:
  1004.                                         xbmc.log(msg="passou na condicional 472")
  1005.                                         break
  1006.                                 elif episodenumber == item[2] and seasonnumber == item[3]:
  1007.                                     xbmc.log(msg="passou na condicional 492")
  1008.                                     ep['playcount'] = 1
  1009.                                     update = True
  1010.                                     if insert:
  1011.                                         break
  1012.                         else:
  1013.                             # If the episode wasn't in the watch list before, set season and episode thumb
  1014.                             if new:
  1015.                                 xbmc.log(msg="passou na condicional 494")
  1016.                                 for ep in tvshow[5]:
  1017.                                     seasonnumber = "%.2d" % float(ep['season'])
  1018.                                     episodenumber = "%.2d" % float(ep['episode'])
  1019.                                     if episodenumber == item[2] and seasonnumber == item[3]:
  1020.                                         item[7] = self._fetch_episodethumb(tvshowid, seasonnumber, episodenumber)
  1021.                                         item[12] = self._fetch_seasonthumb(tvshowid, seasonnumber)
  1022.                                         #item[17] = self._fetch_episodepercent(tvshowid, seasonnumber, episodenumber)
  1023.                                         break
  1024.                             self.episodes.insert( 0, item )
  1025.                         break
  1026.                 self._clearproperties_episodesprogress()
  1027.                 xbmc.log(msg="limpou os dados no update")
  1028.                 self._setproperties_episodesprogress()
  1029.                 xbmc.log(msg="setou os dados no update")
  1030.         elif type == 'album':
  1031.             xbmc.sleep(1000)
  1032.             self._fetch_songs()
  1033.             self._fetch_albums()
  1034.             self._clearproperties_albumprogress()
  1035.             self._setproperties_albumprogress()                    
  1036.            
  1037. class MyPlayer(xbmc.Player):
  1038.     def __init__( self, *args, **kwargs ):
  1039.         xbmc.Player.__init__( self )
  1040.         self.action = kwargs[ "action" ]
  1041.         self.movies = kwargs[ "movies" ]
  1042.         self.episodes = kwargs[ "episodes" ]
  1043.         self.albums = kwargs[ "albums" ]
  1044.         self.substrings = [ '-trailer', 'http://' ]
  1045.         self.timer = ""
  1046.         self.initValues()
  1047.            
  1048.     def onPlayBackStarted( self ):
  1049.         # Set values based on the file content
  1050.         if ( self.isPlayingAudio() ):
  1051.             self.setValues( 'album' )  
  1052.         else:
  1053.             # Stop timer thread on start
  1054.             self.stopTimer()
  1055.             # Update if an item was played (player is playing a playlist)
  1056.             if len(self.item) > 0:
  1057.                 if self.type == 'movie' and self.movies:
  1058.                     self.action( 'movie', self.item, ( self.time < 3*60 or self.totalTime * 0.9 <= self.time ) )
  1059.                 if self.type == 'episode' and self.episodes:
  1060.                     self.action( 'episode', self.item, ( self.totalTime * 0.9 <= self.time ) )
  1061.                 self.initValues()  
  1062.             # Start timer thread
  1063.             self.timer = Thread(target=self.startTimer)
  1064.             self.timer.start()
  1065.             if xbmc.getCondVisibility( 'VideoPlayer.Content(movies)' ):
  1066.                 filename = ''
  1067.                 isMovie = True
  1068.                 try:
  1069.                     filename = self.getPlayingFile()
  1070.                 except:
  1071.                     pass
  1072.                 if filename != '':
  1073.                     for string in self.substrings:
  1074.                         if string in filename:
  1075.                             isMovie = False
  1076.                             break
  1077.                 if isMovie:
  1078.                     self.setValues( 'movie' )
  1079.             elif xbmc.getCondVisibility( 'VideoPlayer.Content(episodes)' ):
  1080.                 # Check for tv show title and season to make sure it's really an episode
  1081.                 if xbmc.getInfoLabel('VideoPlayer.Season') != "" and xbmc.getInfoLabel('VideoPlayer.TVShowTitle') != "":
  1082.                     self.setValues( 'episode' )
  1083.  
  1084.     def onPlayBackEnded( self ):
  1085.         self.stopTimer()
  1086.         if self.type == 'album' and self.albums:
  1087.             self.action( 'album', self.item, True )
  1088.         if self.type == 'movie' and self.movies:
  1089.             self.action( 'movie', self.item, True )
  1090.         if self.type == 'episode' and self.episodes:
  1091.             self.action( 'episode', self.item, True )
  1092.         self.initValues()
  1093.  
  1094.     def onPlayBackStopped( self ):
  1095.         self.stopTimer()
  1096.         if self.type == 'album' and self.albums:
  1097.             self.action( 'album', self.item, True )
  1098.         if self.type == 'movie' and self.movies:
  1099.             percentmovie = (int(self.time) * 100) / int(self.totalTime)
  1100.             percentmovie = str(percentmovie)
  1101.            
  1102.             self.item[13] = percentmovie
  1103.             xbmc.log(msg="tempo supostamente total filmes " + percentmovie)
  1104.             self.action( 'movie', self.item, ( self.time < 3*60 or self.totalTime * 0.90 <= self.time ) )
  1105.         if self.type == 'episode' and self.episodes:
  1106.             percstopepisode = (int(self.time) * 100) / int(self.totalTime)
  1107.             percstopepisode = str(percstopepisode)
  1108.             self.item[17] = percstopepisode
  1109.             xbmc.log(msg="tempo supostamente total episodes" + percstopepisode)
  1110.             self.action( 'episode', self.item, ( self.totalTime * 0.90 <= self.time ) )
  1111.         self.initValues()
  1112.  
  1113.     def setValues( self, type ):
  1114.         self.type = type
  1115.         self.totalTime = 0
  1116.         try:
  1117.             self.totalTime = self.getTotalTime()
  1118.         except:
  1119.             pass
  1120.         if type == 'movie':
  1121.             title = xbmc.getInfoLabel('VideoPlayer.Title')
  1122.             year = xbmc.getInfoLabel('VideoPlayer.Year')
  1123.             genre = xbmc.getInfoLabel('VideoPlayer.Genre')
  1124.             studio = xbmc.getInfoLabel('VideoPlayer.Studio')
  1125.             plot = xbmc.getInfoLabel('VideoPlayer.Plot')
  1126.             plotoutline = xbmc.getInfoLabel('VideoPlayer.PlotOutline')
  1127.             tagline = xbmc.getInfoLabel('VideoPlayer.TagLine')
  1128.             runtime = xbmc.getInfoLabel('VideoPlayer.Duration')
  1129.             path = xbmc.getInfoLabel('Player.Filenameandpath')
  1130.             rating = str(xbmc.getInfoLabel('VideoPlayer.Rating'))
  1131.             self.item = ["", title, year, genre, studio, plot, plotoutline, tagline, runtime, "", "", path, rating, "", "", ""]
  1132.         elif type == 'episode':
  1133.             title = xbmc.getInfoLabel('VideoPlayer.Title')
  1134.             episode = "%.2d" % float(xbmc.getInfoLabel('VideoPlayer.Episode'))
  1135.             path = xbmc.getInfoLabel('Player.Filenameandpath')
  1136.             plot = xbmc.getInfoLabel('VideoPlayer.Plot')
  1137.             season = "%.2d" % float(xbmc.getInfoLabel('VideoPlayer.Season'))
  1138.             showtitle = xbmc.getInfoLabel('VideoPlayer.TVShowTitle')
  1139.             rating = str(xbmc.getInfoLabel('VideoPlayer.Rating'))
  1140.             episodeno = "s%se%s" % ( season,  episode, )
  1141.             studio = xbmc.getInfoLabel('VideoPlayer.Studio')
  1142.             playcount = xbmc.getInfoLabel('VideoPlayer.PlayCount')
  1143.             if playcount != "":
  1144.                 playcount = int(playcount)
  1145.             else:
  1146.                 playcount = 0
  1147.             self.item = ["", title, episode, season, plot, showtitle, path, "", "", episodeno, "", "", "", "True", rating, playcount, "", ""]
  1148.                
  1149.         elif type == 'album':
  1150.             pass
  1151.  
  1152.     def initValues( self ):
  1153.         self.item = []
  1154.         self.type = ""
  1155.         self.time = 0
  1156.         self.totaltime = 0
  1157.  
  1158.     def startTimer( self ):
  1159.         runtime = 0
  1160.         self.shutdown = False
  1161.         setTime = False
  1162.         while( self.isPlaying() and self.shutdown == False ):
  1163.             try:
  1164.                 runtime = self.getTime()
  1165.                 setTime = True
  1166.             except:
  1167.                 setTime = False
  1168.             if (runtime <= 2):
  1169.                 xbmc.sleep(5000)
  1170.             else:
  1171.                 xbmc.sleep(1000)
  1172.             if setTime:
  1173.                 self.time = runtime
  1174.  
  1175.     def stopTimer( self ):
  1176.         if self.timer != "":
  1177.             self.shutdown = True
  1178.             xbmc.sleep(100)
  1179.             if self.timer.isAlive():
  1180.                 self.timer.join()
  1181.                
  1182.          
  1183. class UpdateRandom(aioupdate.Uprandom):
  1184.       def __init__( self, *args, **kwargs ):
  1185.           aioupdate.Uprandom.__init__( self )
  1186.           self.WINDOW = xbmcgui.Window( 10000 )
  1187.           self.upaction = kwargs["upaction"]
  1188.           self.strupaction = str(self.upaction)
  1189.       def _upmovierandom(self):
  1190.           self.upaction()
  1191.  
  1192. class callfetchrecents(Thread):
  1193.     def __init__ (self):
  1194.         Thread.__init__(self)
  1195.     def run(self):
  1196.         aiorecents.Main()
  1197.                                              
  1198. if ( __name__ == "__main__" ):
  1199.     log('script version %s started' % __addonversion__)
  1200.     Main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement