Advertisement
Guest User

Untitled

a guest
Nov 26th, 2012
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 30.38 KB | None | 0 0
  1. import xbmc, xbmcgui, xbmcaddon
  2. import re, sys, os, random, time
  3. try:
  4.     import json as simplejson
  5.     # test json has not loads, call error
  6.     if not hasattr( simplejson, "loads" ):
  7.         raise Exception( "Hmmm! Error with json %r" % dir( simplejson ) )
  8. except Exception, e:
  9.     print "[RandomAndLastItems] %s" % str( e )
  10.     import simplejson
  11. from xbmcgui import Window
  12. from xml.dom.minidom import parse
  13.  
  14. # Define global variables
  15. LIMIT = 10
  16. METHOD = "Random"
  17. MENU = ""
  18. PLAYLIST = ""
  19. PROPERTIE = ""
  20. RESUME = 'False'
  21. START_TIME = time.time()
  22. TYPE = ''
  23. UNWATCHED = 'False'
  24. WINDOW = xbmcgui.Window( 10000 )
  25.  
  26. def _videoResolution( _width, _height ):
  27.     if ( _width == 0 or _height == 0 ):
  28.         return ""
  29.     elif ( _width <= 720 and _height <= 480 ):
  30.         return "480"
  31.     # 720x576 (PAL) (768 when rescaled for square pixels)
  32.     elif ( _width <= 768 and _height <= 576 ):
  33.         return "576"
  34.     # 960x540 (sometimes 544 which is multiple of 16)
  35.     elif ( _width <= 960 and _height <= 544 ):
  36.         return "540"
  37.     # 1280x720
  38.     elif ( _width <= 1280 and _height <= 720 ):
  39.         return "720"
  40.     # 1920x1080
  41.     else:
  42.         return "1080"
  43.  
  44. def _getPlaylistType ():
  45.     global PLAYLIST
  46.     global TYPE
  47.     _doc = parse(xbmc.translatePath(PLAYLIST))
  48.     _type = _doc.getElementsByTagName('smartplaylist')[0].attributes.item(0).value
  49.     if _type == 'movies':
  50.        TYPE = 'Movie'
  51.     if _type == 'episodes' or _type == 'tvshows':
  52.        TYPE = 'Episode'
  53.     if _type == 'songs' or _type == 'albums':
  54.        TYPE = 'Music'
  55.  
  56. def _timeTook( t ):
  57.     t = ( time.time() - t )
  58.     if t >= 60: return "%.3fm" % ( t / 60.0 )
  59.     return "%.3fs" % ( t )
  60.  
  61. def _multiKeySort(_items, _columns):
  62.     from operator import itemgetter
  63.     _comparers = [ ((itemgetter(_col[1:].strip()), -1) if _col.startswith('-') else (itemgetter(_col.strip()), 1)) for _col in _columns]  
  64.     def _comparer(_left, _right):
  65.         for _fn, _mult in _comparers:
  66.             _result = cmp(_fn(_left), _fn(_right))
  67.             if _result:
  68.                 return _mult * _result
  69.         else:
  70.             return 0
  71.     return sorted(_items, cmp=_comparer)
  72.  
  73. def _watchedOrResume ( _total, _watched, _unwatched, _result, _file ):
  74.     global RESUME
  75.     global UNWATCHED
  76.     _total += 1
  77.     _playcount = _file['playcount']
  78.     if RESUME == 'True':
  79.         _resume = _file['resume']['position']
  80.     if _playcount == 0:
  81.         _unwatched += 1
  82.     else:
  83.         _watched += 1
  84.     if (UNWATCHED == 'False' and RESUME == 'False') or (UNWATCHED == 'True' and _playcount == 0) or (RESUME == 'True' and _resume != 0):
  85.         _result.append(_file)
  86.     return _total, _watched, _unwatched, _result
  87.  
  88. def _getMovies ( ):
  89.     global LIMIT
  90.     global METHOD
  91.     global MENU
  92.     global PLAYLIST
  93.     global PROPERTIE
  94.     global RESUME
  95.     global UNWATCHED
  96.     _result = []
  97.     _total = 0
  98.     _unwatched = 0
  99.     _watched = 0
  100.     # Request database using JSON
  101.     if PLAYLIST == "":
  102.         PLAYLIST = "videodb://1/2/"
  103.     _json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Files.GetDirectory", "params": {"directory": "%s", "media": "video", "properties": ["year", "runtime", "file", "playcount", "rating", "plot", "fanart", "thumbnail", "trailer", "streamdetails"]}, "id": 1}' %(PLAYLIST))
  104.     _json_query = unicode(_json_query, 'utf-8', errors='ignore')
  105.     _json_pl_response = simplejson.loads(_json_query)
  106.     # If request return some results
  107.     _files = _json_pl_response.get( "result", {} ).get( "files" )
  108.     if _files:
  109.         for _item in _files:
  110.             if _item['filetype'] == 'directory':
  111.                 _json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Files.GetDirectory", "params": {"directory": "%s", "media": "video", "properties": ["year", "runtime", "file", "playcount", "rating", "plot", "fanart", "thumbnail", "trailer", "streamdetails"]}, "id": 1}' %(_item['file']))
  112.                 _json_query = unicode(_json_query, 'utf-8', errors='ignore')
  113.                 _json_set_response = simplejson.loads(_json_query)
  114.                 _movies = _json_set_response.get( "result", {} ).get( "files" ) or []
  115.                 if not _movies:
  116.                     print("[RandomAndLastItems] ## MOVIESET %s COULD NOT BE LOADED ##" %(_item['file']))
  117.                     print("[RandomAndLastItems] JSON RESULT ", _json_set_response)
  118.                 for _movie in _movies:
  119.                     _playcount = _movie['playcount']
  120.                     if RESUME == 'True':
  121.                         _json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovieDetails", "params": {"movieid": %s, "properties": ["resume"]}, "id": 1}' %(_movie['id']))
  122.                         _json_query = unicode(_json_query, 'utf-8', errors='ignore')
  123.                         _json_detail_response = simplejson.loads(_json_query)
  124.                         _detail = _json_detail_response.get( "result", {} ).get( "moviedetails" ) or []
  125.                         _resume = _detail['resume']['position']
  126.                     else:
  127.                         _resume = 0
  128.                     _total += 1
  129.                     if _playcount == 0:
  130.                         _unwatched += 1
  131.                     else:
  132.                         _watched += 1
  133.                     if (UNWATCHED == 'False' and RESUME == 'False') or (UNWATCHED == 'True' and _playcount == 0) or (RESUME == 'True' and _resume != 0):
  134.                         _result.append(_movie)
  135.             else:
  136.                 _playcount = _item['playcount']
  137.                 if RESUME == 'True':
  138.                     _json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovieDetails", "params": {"movieid": %s, "properties": ["resume"]}, "id": 1}' %(_item['id']))
  139.                     _json_query = unicode(_json_query, 'utf-8', errors='ignore')
  140.                     _json_detail_response = simplejson.loads(_json_query)
  141.                     _detail = _json_detail_response.get( "result", {} ).get( "moviedetails" ) or []
  142.                     _resume = _detail['resume']['position']
  143.                 else:
  144.                     _resume = 0
  145.                 _total += 1
  146.                 if _playcount == 0:
  147.                     _unwatched += 1
  148.                 else:
  149.                     _watched += 1
  150.                 if (UNWATCHED == 'False' and RESUME == 'False') or (UNWATCHED == 'True' and _playcount == 0) or (RESUME == 'True' and _resume != 0):
  151.                     _result.append(_item)
  152.         if METHOD == 'Last':
  153.             _result = _multiKeySort(_result, ['-id'])
  154.         _setVideoProperties ( _total, _watched, _unwatched )
  155.         _count = 0
  156.         while _count < LIMIT:
  157.             # Check if we don't run out of items before LIMIT is reached
  158.             if len( _result ) == 0:
  159.                 break
  160.             # Select a random or the last item
  161.             if METHOD == 'Random':
  162.                 _movie = random.choice( _result )
  163.             else:
  164.                 _movie = _result[0]
  165.             # Remove item from JSON list
  166.             _result.remove( _movie )
  167.             _count += 1
  168.             title = _movie['label']
  169.             rating = str(round(float(_movie['rating']),1))
  170.             year = str(_movie['year'])
  171.             trailer = _movie['trailer']
  172.             plot = _movie['plot']
  173.             runtime = str(_movie['runtime'] / 60)
  174.             path = _movie['file']
  175.             file = os.path.split(path)[1]
  176.             pos = path.find(file)
  177.             rootpath = path[:pos]
  178.             thumb = _movie['thumbnail']
  179.             fanart = _movie['fanart']
  180.             try: height = _movie.get("streamdetails", [ {} ]).get( "video", [ {} ] )[0].get( "height",0 )
  181.             except: height = 0
  182.             try: width = _movie.get("streamdetails", [ {} ]).get( "video", [ {} ] )[0].get( "width",0 )
  183.             except: width = 0
  184.             resolution = _videoResolution( width, height )
  185.             # Set window properties
  186.             _setProperty( "%s.%d.Path"        % ( PROPERTIE, _count ), path )
  187.             _setProperty( "%s.%d.Thumb"       % ( PROPERTIE, _count ), thumb)
  188.             _setProperty( "%s.%d.Fanart"      % ( PROPERTIE, _count ), fanart)
  189.             _setProperty( "%s.%d.Plot"        % ( PROPERTIE, _count ), plot)
  190.             _setProperty( "%s.%d.Rating"      % ( PROPERTIE, _count ), rating)
  191.             _setProperty( "%s.%d.RunningTime" % ( PROPERTIE, _count ), runtime)
  192.             _setProperty( "%s.%d.Rootpath"    % ( PROPERTIE, _count ), rootpath )
  193.             _setProperty( "%s.%d.Title"       % ( PROPERTIE, _count ), title )
  194.             _setProperty( "%s.%d.Year"        % ( PROPERTIE, _count ), year)
  195.             _setProperty( "%s.%d.Trailer"     % ( PROPERTIE, _count ), trailer)
  196.             _setProperty( "%s.%d.Resolution"  % ( PROPERTIE, _count ), resolution)
  197.         if _count != LIMIT:
  198.             while _count < LIMIT:
  199.                 _count += 1
  200.                 _setProperty( "%s.%d.Path"        % ( PROPERTIE, _count ), "" )
  201.                 _setProperty( "%s.%d.Thumb"       % ( PROPERTIE, _count ), "" )
  202.                 _setProperty( "%s.%d.Fanart"      % ( PROPERTIE, _count ), "" )
  203.                 _setProperty( "%s.%d.Plot"        % ( PROPERTIE, _count ), "" )
  204.                 _setProperty( "%s.%d.Rating"      % ( PROPERTIE, _count ), "" )
  205.                 _setProperty( "%s.%d.RunningTime" % ( PROPERTIE, _count ), "" )
  206.                 _setProperty( "%s.%d.Rootpath"    % ( PROPERTIE, _count ), "" )
  207.                 _setProperty( "%s.%d.Title"       % ( PROPERTIE, _count ), "" )
  208.                 _setProperty( "%s.%d.Year"        % ( PROPERTIE, _count ), "" )
  209.                 _setProperty( "%s.%d.Trailer"     % ( PROPERTIE, _count ), "" )
  210.                 _setProperty( "%s.%d.Resolution"  % ( PROPERTIE, _count ), "" )
  211.     else:
  212.         print("[RandomAndLastItems] ## PLAYLIST %s COULD NOT BE LOADED ##" %(PLAYLIST))
  213.         print("[RandomAndLastItems] JSON RESULT ", _json_pl_response)
  214.  
  215. def _getEpisodesFromPlaylist ( ):
  216.     global LIMIT
  217.     global METHOD
  218.     global PLAYLIST
  219.     global RESUME
  220.     global UNWATCHED
  221.     _result = []
  222.     _total = 0
  223.     _unwatched = 0
  224.     _watched = 0
  225.     _tvshows = 0
  226.     _tvshowid = []
  227.     # Request database using JSON
  228.     _json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Files.GetDirectory", "params": {"directory": "%s", "media": "video", "properties": ["tvshowid", "runtime", "playcount", "season", "episode", "showtitle", "plot", "fanart", "thumbnail", "file", "rating", "title"] }, "id": 1}' %(PLAYLIST))
  229.     _json_query = unicode(_json_query, 'utf-8', errors='ignore')
  230.     _json_pl_response = simplejson.loads(_json_query)
  231.     _files = _json_pl_response.get( "result", {} ).get( "files" )
  232.     if _files:
  233.         for _file in _files:
  234.             if _file['type'] == 'tvshow':
  235.                 _tvshows += 1
  236.                 # La playlist fournie retourne des series il faut retrouver les episodes
  237.                 if RESUME == 'True':
  238.                     _json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": { "tvshowid": %s, "properties": ["resume", "runtime", "playcount", "season", "episode", "showtitle", "plot", "fanart", "thumbnail", "file", "rating", "title"] }, "id": 1}' %(_file['id']))
  239.                 else:
  240.                     _json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": { "tvshowid": %s, "properties": ["runtime", "playcount", "season", "episode", "showtitle", "plot", "fanart", "thumbnail", "file", "rating", "title"] }, "id": 1}' %(_file['id']))
  241.                 _json_query = unicode(_json_query, 'utf-8', errors='ignore')
  242.                 _json_response = simplejson.loads(_json_query)
  243.                 _episodes = _json_response.get( "result", {} ).get( "episodes" )
  244.                 if _episodes:
  245.                     for _episode in _episodes:
  246.                         # Add TV Show fanart and thumbnail for each episode
  247.                         #_episode["tvshowid"]=_file['id']
  248.                         _episode["tvshowfanart"]=_file['fanart']
  249.                         _episode["tvshowthumb"]=_file['thumbnail']
  250.                         _total, _watched, _unwatched, _result = _watchedOrResume ( _total, _watched, _unwatched, _result, _episode )
  251.                 else:
  252.                     print("[RandomAndLastItems] ## PLAYLIST %s COULD NOT BE LOADED ##" %(PLAYLIST))
  253.                     print("[RandomAndLastItems] JSON RESULT ", _json_response)
  254.             if _file['type'] == 'episode':
  255.                 _id = _file['tvshowid']
  256.                 if _id not in _tvshowid:
  257.                     _tvshows += 1
  258.                     _tvshowid.append(_id)
  259.                 # La playlist fournie retourne des episodes
  260.                 _total, _watched, _unwatched, _result = _watchedOrResume ( _total, _watched, _unwatched, _result, _file )
  261.         if METHOD == 'Last':
  262.             if _tvshowid:
  263.                 _result = _multiKeySort(_result, ['-id'])
  264.             else:
  265.                 _result = _multiKeySort(_result, ['-episodeid'])
  266.         _setVideoProperties ( _total, _watched, _unwatched )
  267.         _setTvShowsProperties ( _tvshows )
  268.         _count = 0
  269.         while _count < LIMIT:
  270.             # Check if we don't run out of items before LIMIT is reached
  271.             if len( _result ) == 0:
  272.                 break
  273.             # Select a random or the last item
  274.             if METHOD == 'Random':
  275.                 _episode = random.choice( _result )
  276.             else:
  277.                 _episode = _result[0]
  278.             # Remove item from JSON list
  279.             _result.remove( _episode )
  280.             _count += 1
  281.             if _episode.get("tvshowid") :
  282.                 _json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShowDetails", "params": { "tvshowid": %s, "properties": ["title", "fanart", "thumbnail"] }, "id": 1}' %(_episode['tvshowid']))
  283.                 _json_query = unicode(_json_query, 'utf-8', errors='ignore')
  284.                 _json_pl_response = simplejson.loads(_json_query)
  285.                 _tvshow = _json_pl_response.get( "result", {} ).get( "tvshowdetails" )
  286.                 _episode["tvshowfanart"]=_tvshow['fanart']
  287.                 _episode["tvshowthumb"]=_tvshow['thumbnail']
  288.             _setEpisodeProperties ( _episode, _count )
  289.         if _count != LIMIT:
  290.             while _count < LIMIT:
  291.                 _count += 1
  292.                 _setEpisodeProperties ( None, _count )
  293.     else:
  294.         print("[RandomAndLastItems] # 01 # PLAYLIST %s COULD NOT BE LOADED ##" %(PLAYLIST))
  295.         print("[RandomAndLastItems] JSON RESULT ", _json_pl_response)
  296.  
  297. def _getEpisodes ( ):
  298.     global LIMIT
  299.     global METHOD
  300.     global RESUME
  301.     global UNWATCHED
  302.     _result = []
  303.     _total = 0
  304.     _unwatched = 0
  305.     _watched = 0
  306.     _tvshows = 0
  307.     _tvshowid = []
  308.     # Request database using JSON
  309.     if RESUME == 'True':
  310.         _json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": { "properties": ["tvshowid", "resume", "runtime", "playcount", "season", "episode", "showtitle", "plot", "fanart", "thumbnail", "file", "rating", "title"] }, "id": 1}')
  311.     else:
  312.         _json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": { "properties": ["tvshowid", "runtime", "playcount", "season", "episode", "showtitle", "plot", "fanart", "thumbnail", "file", "rating", "title"] }, "id": 1}')
  313.     _json_query = unicode(_json_query, 'utf-8', errors='ignore')
  314.     _json_pl_response = simplejson.loads(_json_query)
  315.     # If request return some results
  316.     _episodes = _json_pl_response.get( "result", {} ).get( "episodes" )
  317.     if _episodes:
  318.         for _item in _episodes:
  319.             _id = _item['tvshowid']
  320.             if _id not in _tvshowid:
  321.                 _tvshows += 1
  322.                 _tvshowid.append(_id)
  323.             _total, _watched, _unwatched, _result = _watchedOrResume ( _total, _watched, _unwatched, _result, _item )
  324.         if METHOD == 'Last':
  325.             _result = _multiKeySort(_result, ['-episodeid'])
  326.         _setVideoProperties ( _total, _watched, _unwatched )
  327.         _setTvShowsProperties ( _tvshows )
  328.         _count = 0
  329.         while _count < LIMIT:
  330.             # Check if we don't run out of items before LIMIT is reached
  331.             if len( _result ) == 0:
  332.                 break
  333.             # Select a random or the last item
  334.             if METHOD == 'Random':
  335.                 _episode = random.choice( _result )
  336.             else:
  337.                 _episode = _result[0]
  338.             # Remove item from JSON list
  339.             _result.remove( _episode )
  340.             _count += 1
  341.             _json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShowDetails", "params": { "tvshowid": %s, "properties": ["title", "fanart", "thumbnail"] }, "id": 1}' %(_episode['tvshowid']))
  342.             _json_query = unicode(_json_query, 'utf-8', errors='ignore')
  343.             _json_pl_response = simplejson.loads(_json_query)
  344.             _tvshow = _json_pl_response.get( "result", {} ).get( "tvshowdetails" )
  345.             _episode["tvshowfanart"]=_tvshow['fanart']
  346.             _episode["tvshowthumb"]=_tvshow['thumbnail']
  347.             """
  348.            _json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetSeasons", "params": { "tvshowid": %s, "properties": ["season", "episode", "showtitle", "fanart", "thumbnail"] }, "id": 1}' %(_episode['tvshowid']))
  349.            _json_query = unicode(_json_query, 'utf-8', errors='ignore')
  350.            _json_pl_response = simplejson.loads(_json_query)
  351.            _seasons = _json_pl_response.get( "result", {} ).get( "seasons" )
  352.            print("##### SEASON = ", _seasons)
  353.            # ATTENTION, ca retourne toutes les saisons, il faudra boucler pour trouver la bonne saison par rapport a l episode
  354.            """
  355.             _setEpisodeProperties ( _episode, _count )
  356.         if _count != LIMIT:
  357.             while _count < LIMIT:
  358.                 _count += 1
  359.                 _setEpisodeProperties ( None, _count )
  360.     else:
  361.         print("[RandomAndLastItems] ## PLAYLIST %s COULD NOT BE LOADED ##" %(PLAYLIST))
  362.         print("[RandomAndLastItems] JSON RESULT ", _json_pl_response)
  363.  
  364. def _getAlbumsFromPlaylist ( ):
  365.     global LIMIT
  366.     global METHOD
  367.     global PLAYLIST
  368.     _result = []
  369.     _artists = 0
  370.     _artistsid = []
  371.     _albums = []
  372.     _albumsid = []
  373.     _songs = 0
  374.     # Request database using JSON
  375.     if PLAYLIST == "":
  376.         PLAYLIST = "musicdb://4/"
  377.     _json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Files.GetDirectory", "params": {"directory": "%s", "media": "music", "properties": ["title", "album", "albumid", "artist", "artistid", "file", "year", "thumbnail", "fanart"]}, "id": 1}' %(PLAYLIST))
  378.     _json_query = unicode(_json_query, 'utf-8', errors='ignore')
  379.     _json_pl_response = simplejson.loads(_json_query)
  380.     # If request return some results
  381.     _files = _json_pl_response.get( "result", {} ).get( "files" )
  382.     if _files:
  383.         for _file in _files:
  384.             if _file['type'] == 'album':
  385.                 _albumid = _file['id']
  386.                 # Album playlist so get path from songs
  387.                 _json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "AudioLibrary.GetSongs", "params": {"albumid": %s, "properties": ["file"]}, "id": 1}' %(_albumid))
  388.                 _json_query = unicode(_json_query, 'utf-8', errors='ignore')
  389.                 _json_pl_response = simplejson.loads(_json_query)
  390.                 _result = _json_pl_response.get( "result", {} ).get( "songs" )
  391.                 _songs += len(_result)
  392.                 if _result:
  393.                     _albumpath = os.path.split(_result[0]['file'])[0]
  394.                     _artistpath = os.path.split(_albumpath)[0]
  395.             else:
  396.                 _albumid = _file['albumid']
  397.                 _albumpath = os.path.split(_file['file'])[0]
  398.                 _artistpath = os.path.split(_albumpath)[0]
  399.                 _songs += 1
  400.             if _albumid not in _albumsid:
  401.                 _structure = {}
  402.                 _structure["id"] = _albumid
  403.                 _structure["album"] = _file['album']
  404.                 _structure["artist"] = _file['artist']
  405.                 _structure["year"] = _file['year']
  406.                 _structure["thumbnail"] = _file['thumbnail']
  407.                 _structure["fanart"] = _file['fanart']
  408.                 _structure["albumPath"] = _albumpath
  409.                 _structure["artistPath"] = _artistpath
  410.                 _albums.append(_structure)
  411.                 _albumsid.append(_albumid)
  412.             _artistid = _file['artistid']
  413.             if _artistid not in _artistsid:
  414.                 _artists += 1
  415.                 _artistsid.append(_artistid)
  416.         if METHOD == 'Last':
  417.             _albums = _multiKeySort(_albums, ['-id'])
  418.         _setMusicProperties ( _artists, len(_albums), _songs )
  419.         _count = 0
  420.         while _count < LIMIT:
  421.             # Check if we don't run out of items before LIMIT is reached
  422.             if len( _albums ) == 0:
  423.                 break
  424.             # Select a random or the last item
  425.             if METHOD == 'Random':
  426.                 _album = random.choice( _albums )
  427.             else:
  428.                 _album = _albums[0]
  429.             # Remove item from JSON list
  430.             _albums.remove( _album )
  431.             _count += 1
  432.             # Get album description
  433.             _json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "AudioLibrary.GetAlbumDetails", "params": {"albumid": %s, "properties": ["description"]}, "id": 1}' %(_albumid))
  434.             _json_query = unicode(_json_query, 'utf-8', errors='ignore')
  435.             _json_pl_response = simplejson.loads(_json_query)
  436.             _result = _json_pl_response.get( "result", {} ).get( "albumdetails" )
  437.             _albumdesc = _result.get ("description")
  438.             _album["albumDesc"] = _albumdesc
  439.             _setAlbumProperties ( _album, _count )
  440.         if _count != LIMIT:
  441.             while _count < LIMIT:
  442.                 _count += 1
  443.                 _setAlbumProperties ( None, _count )
  444.     else:
  445.         print("[RandomAndLastItems] ## PLAYLIST %s COULD NOT BE LOADED ##" %(PLAYLIST))
  446.         print("[RandomAndLastItems] JSON RESULT ", _json_pl_response)
  447.  
  448. def _clearProperties ( ):
  449.     global LIMIT
  450.     global METHOD
  451.     global MENU
  452.     global TYPE
  453.     global WINDOW
  454.     # Reset window properties
  455.     if TYPE == "Movie" or TYPE == "Episode":
  456.         WINDOW.clearProperty( "%s.Count" % ( PROPERTIE ) )
  457.         WINDOW.clearProperty( "%s.Watched" % ( PROPERTIE ) )
  458.         WINDOW.clearProperty( "%s.Unwatched" % ( PROPERTIE ) )
  459.     if TYPE == "Album" or TYPE == "Song":
  460.         WINDOW.clearProperty( "%s.Artists" % ( PROPERTIE ) )
  461.         WINDOW.clearProperty( "%s.Albums" % ( PROPERTIE ) )
  462.         WINDOW.clearProperty( "%s.Songs" % ( PROPERTIE ) )
  463.     for _count in range( LIMIT ):
  464.         WINDOW.clearProperty( "%s.%d.Path" % ( PROPERTIE, _count + 1 ) )
  465.         WINDOW.clearProperty( "%s.%d.Rootpath" % ( PROPERTIE, _count + 1 ) )
  466.         WINDOW.clearProperty( "%s.%d.Thumb" % ( PROPERTIE, _count + 1 ) )
  467.         WINDOW.clearProperty( "%s.%d.Fanart" % ( PROPERTIE, _count + 1 ) )
  468.         WINDOW.clearProperty( "%s.%d.Plot" % ( PROPERTIE, _count + 1 ) )
  469.         WINDOW.clearProperty( "%s.%d.Rating" % ( PROPERTIE, _count + 1 ) )
  470.         WINDOW.clearProperty( "%s.%d.RunningTime" % ( PROPERTIE, _count + 1 ) )
  471.         if TYPE == "Movie":
  472.             WINDOW.clearProperty( "%s.%d.Title" % ( PROPERTIE, _count + 1 ) )
  473.             WINDOW.clearProperty( "%s.%d.Year" % ( PROPERTIE, _count + 1 ) )
  474.             WINDOW.clearProperty( "%s.%d.Trailer" % ( PROPERTIE, _count + 1 ) )
  475.         if TYPE == "Episode":
  476.             WINDOW.clearProperty( "%s.%d.ShowTitle" % ( PROPERTIE, _count + 1 ) )
  477.             WINDOW.clearProperty( "%s.%d.EpisodeTitle" % ( PROPERTIE, _count + 1 ) )
  478.             WINDOW.clearProperty( "%s.%d.EpisodeNo" % ( PROPERTIE, _count + 1 ) )
  479.             WINDOW.clearProperty( "%s.%d.EpisodeSeason" % ( PROPERTIE, _count + 1 ) )
  480.             WINDOW.clearProperty( "%s.%d.EpisodeNumber" % ( PROPERTIE, _count + 1 ) )
  481.  
  482. def _setMusicProperties ( _artists, _albums, _songs ):
  483.     global PROPERTIE
  484.     global WINDOW
  485.     global TYPE
  486.     # Set window properties
  487.     _setProperty ( "%s.Artists" % ( PROPERTIE ), str( _artists ) )
  488.     _setProperty ( "%s.Albums" % ( PROPERTIE ), str( _albums ) )
  489.     _setProperty ( "%s.Songs" % ( PROPERTIE ), str( _songs ) )
  490.     _setProperty ( "%s.Type" % ( PROPERTIE ), TYPE )
  491.  
  492. def _setVideoProperties ( _total, _watched, _unwatched ):
  493.     global PROPERTIE
  494.     global WINDOW
  495.     global TYPE
  496.     # Set window properties
  497.     _setProperty ( "%s.Count" % ( PROPERTIE ), str( _total ) )
  498.     _setProperty ( "%s.Watched" % ( PROPERTIE ), str( _watched ) )
  499.     _setProperty ( "%s.Unwatched" % ( PROPERTIE ), str( _unwatched ) )
  500.     _setProperty ( "%s.Type" % ( PROPERTIE ), TYPE )
  501.  
  502. def _setTvShowsProperties ( _tvshows ):
  503.     global PROPERTIE
  504.     global WINDOW
  505.     # Set window properties
  506.     _setProperty ( "%s.TvShows" % ( PROPERTIE ), str( _tvshows ) )
  507.  
  508. def _setEpisodeProperties ( _episode, _count ):
  509.     global PROPERTIE
  510.     if _episode:
  511.         title = _episode['title']
  512.         rating = str(round(float(_episode['rating']),1))
  513.         plot = _episode['plot']
  514.         runtime = str(_episode['runtime'] / 60)
  515.         path = _episode['file']
  516.         file = os.path.split(path)[1]
  517.         pos = path.find(file)
  518.         rootpath = path[:pos]
  519.         long=len(rootpath)
  520.         rootpath=rootpath[:long-1]
  521.         file = os.path.split(rootpath)[1]
  522.         pos = rootpath.find(file)
  523.         rootpath = rootpath[:pos]
  524.         showtitle = _episode['showtitle']
  525.         season = str(_episode['season'])
  526.         seasonXX = "%.2d" % float(_episode['season'])
  527.         episode = "%.2d" % float(_episode['episode'])
  528.         episodeno = "s%se%s" % ( seasonXX,  episode, )
  529.         thumb = _episode['thumbnail']
  530.         fanart = _episode['fanart']
  531.         tvthumb = _episode['tvshowthumb']
  532.         tvfanart = _episode['tvshowfanart']
  533.     else:
  534.         title = ""
  535.         rating = ""
  536.         plot = ""
  537.         runtime = ""
  538.         path = ""
  539.         rootpath = ""
  540.         showtitle = ""
  541.         season = ""
  542.         episode = ""
  543.         episodeno = ""
  544.         thumb = ""
  545.         fanart = ""
  546.         tvthumb = ""
  547.         tvfanart = ""
  548.     # Set window properties
  549.     _setProperty( "%s.%d.Path"          % ( PROPERTIE, _count ), path )
  550.     _setProperty( "%s.%d.Thumb"         % ( PROPERTIE, _count ), thumb)
  551.     _setProperty( "%s.%d.Fanart"        % ( PROPERTIE, _count ), fanart)
  552.     _setProperty( "%s.%d.Plot"          % ( PROPERTIE, _count ), plot)
  553.     _setProperty( "%s.%d.Rating"        % ( PROPERTIE, _count ), rating)
  554.     _setProperty( "%s.%d.RunningTime"   % ( PROPERTIE, _count ), runtime)
  555.     _setProperty( "%s.%d.Rootpath"      % ( PROPERTIE, _count ), rootpath )
  556.     _setProperty( "%s.%d.ShowTitle"     % ( PROPERTIE, _count ), showtitle )
  557.     _setProperty( "%s.%d.EpisodeTitle"  % ( PROPERTIE, _count ), title )
  558.     _setProperty( "%s.%d.EpisodeNo"     % ( PROPERTIE, _count ), episodeno )
  559.     _setProperty( "%s.%d.EpisodeSeason" % ( PROPERTIE, _count ), season )
  560.     _setProperty( "%s.%d.EpisodeNumber" % ( PROPERTIE, _count ), episode )
  561.     _setProperty( "%s.%d.TVShowThumb"   % ( PROPERTIE, _count ), tvthumb)
  562.     _setProperty( "%s.%d.TVShowFanart"  % ( PROPERTIE, _count ), tvfanart)
  563.  
  564. def _setAlbumProperties ( _album, _count ):
  565.     global PROPERTIE
  566.     if _album:
  567.         album = _album['album']
  568.         artist = _album['artist']
  569.         year = _album['year']
  570.         thumb = _album['thumbnail']
  571.         fanart = _album['fanart']
  572.         artistPath = _album['artistPath']
  573.         albumPath = _album['albumPath']
  574.         albumDesc = _album['albumDesc']
  575.         playPath = "musicdb://3/%s/" %(_album['id'])
  576.     else:
  577.         album = ""
  578.         artist = ""
  579.         year = ""
  580.         thumb = ""
  581.         fanart = ""
  582.         artistPath = ""
  583.         albumPath = ""
  584.         albumDesc = ""
  585.         playPath = ""
  586.     # Set window properties
  587.     _setProperty( "%s.%d.Album"      % ( PROPERTIE, _count ), album )
  588.     _setProperty( "%s.%d.Artist"     % ( PROPERTIE, _count ), artist )
  589.     _setProperty( "%s.%d.Year"       % ( PROPERTIE, _count ), str(year) )
  590.     _setProperty( "%s.%d.Thumb"      % ( PROPERTIE, _count ), thumb)
  591.     _setProperty( "%s.%d.Fanart"     % ( PROPERTIE, _count ), fanart)
  592.     _setProperty( "%s.%d.ArtistPath" % ( PROPERTIE, _count ), artistPath)
  593.     _setProperty( "%s.%d.AlbumPath"  % ( PROPERTIE, _count ), albumPath)
  594.     _setProperty( "%s.%d.AlbumDesc"  % ( PROPERTIE, _count ), albumDesc)
  595.     _setProperty( "%s.%d.PlayPath"   % ( PROPERTIE, _count ), playPath)
  596.  
  597. def _setProperty ( _property, _value ):
  598.     global WINDOW
  599.     # Set window properties
  600.     WINDOW.setProperty ( _property, _value )
  601.  
  602. def _parse_argv ( ):
  603.     global METHOD
  604.     global MENU
  605.     global LIMIT
  606.     global PLAYLIST
  607.     global PROPERTIE
  608.     global RESUME
  609.     global TYPE
  610.     global UNWATCHED
  611.     # Extract parameters
  612.     for arg in sys.argv:
  613.         param = str(arg)
  614.         if 'limit=' in param:
  615.             LIMIT = int(param.replace('limit=', ''))
  616.         elif 'menu=' in param:
  617.             MENU = param.replace('menu=', '')
  618.         elif 'method=' in param:
  619.             METHOD = param.replace('method=', '')
  620.         elif 'playlist=' in param:
  621.             PLAYLIST = param.replace('playlist=', '')
  622.         elif 'propertie=' in param:
  623.             PROPERTIE = param.replace('propertie=', '')
  624.         elif 'type=' in param:
  625.             TYPE = param.replace('type=', '')
  626.         elif 'unwatched=' in param:
  627.             UNWATCHED = param.replace('unwatched=', '')
  628.         elif 'resume=' in param:
  629.             RESUME = param.replace('resume=', '')
  630.     # If playlist= parameter is set and not type= get type= from playlist
  631.     if TYPE == '' and PLAYLIST != '':
  632.         _getPlaylistType ();
  633.     if PROPERTIE == "":
  634.         PROPERTIE = "Playlist%s%s%s" % ( METHOD, TYPE, MENU )
  635.  
  636.  
  637. # Parse argv for any preferences
  638. _parse_argv()
  639. # Clear properties
  640. #_clearProperties()
  641. # Get movies and fill properties
  642. if TYPE == 'Movie':
  643.     _getMovies()
  644. elif TYPE == 'Episode':
  645.     if PLAYLIST == '':
  646.         _getEpisodes()
  647.     else:
  648.         _getEpisodesFromPlaylist()
  649. elif TYPE == 'Music':
  650.     _getAlbumsFromPlaylist()
  651. print( "Loading Playlist%sMovie%s started at %s and take %s" %( METHOD, MENU, time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime( START_TIME ) ), _timeTook( START_TIME ) ) )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement