Example #1
1
    def _get_episode_url(self, show_url, video):
        params = urlparse.parse_qs(show_url)
        cmd = '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"tvshowid": %s, "season": %s, "filter": {"field": "%s", "operator": "is", "value": "%s"}, \
        "limits": { "start" : 0, "end": 25 }, "properties" : ["title", "season", "episode", "file", "streamdetails"], "sort": { "order": "ascending", "method": "label", "ignorearticle": true }}, "id": "libTvShows"}'
        base_url = 'video_type=%s&id=%s'
        episodes = []
        force_title = self._force_title(video)
        if not force_title:
            run = cmd % (params['id'][0], video.season, 'episode', video.episode)
            meta = xbmc.executeJSONRPC(run)
            meta = json.loads(meta)
            log_utils.log('Episode Meta: %s' % (meta), log_utils.LOGDEBUG)
            if 'result' in meta and 'episodes' in meta['result']:
                episodes = meta['result']['episodes']
        else:
            log_utils.log('Skipping S&E matching as title search is forced on: %s' % (video.trakt_id), log_utils.LOGDEBUG)

        if (force_title or kodi.get_setting('title-fallback') == 'true') and video.ep_title and not episodes:
            run = cmd % (params['id'][0], video.season, 'title', video.ep_title)
            meta = xbmc.executeJSONRPC(run)
            meta = json.loads(meta)
            log_utils.log('Episode Title Meta: %s' % (meta), log_utils.LOGDEBUG)
            if 'result' in meta and 'episodes' in meta['result']:
                episodes = meta['result']['episodes']

        for episode in episodes:
            if episode['file'].endswith('.strm'):
                continue
            
            return base_url % (video.video_type, episode['episodeid'])
Example #2
0
def FullScreenXBMC():
	#Logutil.log("Toggle to Full Screen mode", util.LOG_LEVEL_INFO)
	#this brings xbmc back
	try:
		xbmc.executehttpapi("Action(199)")
	except:
		xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Input.ExecuteAction","params":{"action":"togglefullscreen"},"id":"1"}')
 def _finalize_download( self, tmp_path ):
     try:
         if ( tmp_path != self.filepath ):
             # copy the trailer
             msg1 = self.Addon.getLocalizedString( 30503 ) % ( os.path.split( self.filepath )[ 1 ], )
             msg2 = self.Addon.getLocalizedString( 30502 ) % ( os.path.split( self.filepath )[ 0 ], )
             pDialog.update( -1, msg1, msg2 )
             # necessary for dialog to update
             xbmc.sleep( 50 )
             # use JSON RPC for file copying
             xbmc.executeJSONRPC( "FileCopy(%s,%s)" % ( tmp_path, self.filepath.encode( "utf-8" ), ) )
             # remove temporary cache file
             os.remove( tmp_path )
             # create conf file for better MPlayer playback only when trailer saved on xbox and not progressive
             if ( not self.filepath.startswith( "smb://" ) and not self.args.trailer_url.endswith( "p.mov" ) and not os.path.isfile( self.filepath + ".conf" ) and os.environ.get( "OS", "xbox" ) == "xbox" ):
                 f = open( self.filepath + ".conf" , "w" )
                 f.write( "nocache=1" )
                 f.close()
             # copy the thumbnail
             thumbpath = os.path.splitext( self.filepath )[ 0 ] + ".tbn"
             msg1 = self.Addon.getLocalizedString( 30503 ) % ( os.path.split( thumbpath )[ 1 ], )
             pDialog.update( -1, msg1, msg2 )
             # necessary for dialog to update
             xbmc.sleep( 50 )
             xbmc.executeJSONRPC( "FileCopy(%s,%s)" % ( g_thumbnail, thumbpath.encode( "utf-8" ), ) )
         # we succeeded
         return True
     except:
         print "ERROR: %s::%s (%d) - %s" % ( self.__class__.__name__, sys.exc_info()[ 2 ].tb_frame.f_code.co_name, sys.exc_info()[ 2 ].tb_lineno, sys.exc_info()[ 1 ], )
         return False
Example #4
0
def JumpToLetter(letter):
    if not xbmc.getInfoLabel("ListItem.Sortletter")[0] == letter:
        xbmc.executebuiltin("SetFocus(50)")
        if letter in ["A", "B", "C", "2"]:
            jumpsms_id = "2"
        elif letter in ["D", "E", "F", "3"]:
            jumpsms_id = "3"
        elif letter in ["G", "H", "I", "4"]:
            jumpsms_id = "4"
        elif letter in ["J", "K", "L", "5"]:
            jumpsms_id = "5"
        elif letter in ["M", "N", "O", "6"]:
            jumpsms_id = "6"
        elif letter in ["P", "Q", "R", "S", "7"]:
            jumpsms_id = "7"
        elif letter in ["T", "U", "V", "8"]:
            jumpsms_id = "8"
        elif letter in ["W", "X", "Y", "Z", "9"]:
            jumpsms_id = "9"
        else:
            jumpsms_id = None
        if jumpsms_id:
            for i in range(1, 5):
                # xbmc.executebuiltin("jumpsms" + jumpsms_id)
                xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Input.ExecuteAction", "params": { "action": "jumpsms%s" }, "id": 1 }' % (jumpsms_id))
                # prettyprint(response)
                xbmc.sleep(15)
                if xbmc.getInfoLabel("ListItem.Sortletter")[0] == letter:
                    break
        xbmc.executebuiltin("SetFocus(24000)")
Example #5
0
    def updateVideoRefreshRate(self, themePlayList):
        # Check if the setting is enabled to switch the refresh rate
        if not Settings.blockRefreshRateChange():
            self.original_refreshrate = 0
            return

        log("ThemePlayer: Checking for update of refresh rate")

        try:
            # Check if we have any videos in the PlayList
            hasVideoFiles = True
            i = 0
            while i < themePlayList.size():
                if Settings.isVideoFile(themePlayList[i].getfilename()):
                    hasVideoFiles = True
                    break
                i = i + 1

            if hasVideoFiles:
                # Save off the existing refresh setting
                jsonresponse = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Settings.GetSettingValue",  "params": { "setting": "videoplayer.adjustrefreshrate" }, "id": 1}')
                data = simplejson.loads(jsonresponse)
                if 'result' in data:
                    if 'value' in data['result']:
                        self.original_refreshrate = data['result']['value']
                        # Check if the refresh rate is currently set
                        log("ThemePlayer: Video refresh rate currently set to %d" % self.original_refreshrate)

                # Check if the refresh rate is currently set, if it is, then we need
                if self.original_refreshrate != 0:
                    # Disable the refresh rate setting
                    log("ThemePlayer: Disabling refresh rate")
                    xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Settings.SetSettingValue",  "params": { "setting": "videoplayer.adjustrefreshrate", "value": 0 }, "id": 1}')
        except:
            log("ThemePlayer: Failed to process video refresh")
Example #6
0
def AddArtToLibrary(type, media, folder, limit, silent=False):
    json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.Get%ss", "params": {"properties": ["art", "file"], "sort": { "method": "label" } }, "id": 1}' % media.lower())
    json_query = unicode(json_query, 'utf-8', errors='ignore')
    json_response = simplejson.loads(json_query)
    if (json_response['result'] is not None) and ('%ss' % (media.lower()) in json_response['result']):
        # iterate through the results
        if not silent:
            progressDialog = xbmcgui.DialogProgress(ADDON_LANGUAGE(32016))
            progressDialog.create(ADDON_LANGUAGE(32016))
        for count, item in enumerate(json_response['result']['%ss' % media.lower()]):
            if not silent:
                if progressDialog.iscanceled():
                    return
            path = os.path.join(media_path(item['file']).encode("utf-8"), folder)
            file_list = xbmcvfs.listdir(path)[1]
            for i, file in enumerate(file_list):
                if i + 1 > limit:
                    break
                if not silent:
                    progressDialog.update((count * 100) / json_response['result']['limits']['total'], ADDON_LANGUAGE(32011) + ' %s: %s %i' % (item["label"], type, i + 1))
                    if progressDialog.iscanceled():
                        return
                # just in case someone uses backslahes in the path
                # fixes problems mentioned on some german forum
                file_path = os.path.join(path, file).encode('string-escape')
                if xbmcvfs.exists(file_path) and item['art'].get('%s%i' % (type, i), '') == "":
                    xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.Set%sDetails", "params": { "%sid": %i, "art": { "%s%i": "%s" }}, "id": 1 }' %
                                        (media, media.lower(), item.get('%sid' % media.lower()), type, i + 1, file_path))
Example #7
0
def getSeasonCast():
    import json

    dbid  = xbmc.getInfoLabel('%sListItem.DBID' % getPrefix())

    if dbid < 0:
        return []

    query = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "VideoLibrary.GetSeasonDetails", "params": {"seasonid": %s, "properties": ["tvshowid"]}, "id": 1 }' % dbid)
    query = unicode(query, 'utf-8', errors='ignore')

    j = json.loads(query)

    if 'result' not in j: #usually caused by the 'All Seasons' item
        dbid  = str(int(dbid) + 2) #this seems to give Season 1 which will suffice
        query = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "VideoLibrary.GetSeasonDetails", "params": {"seasonid": %s, "properties": ["tvshowid"]}, "id": 1 }' % dbid)
        query = unicode(query, 'utf-8', errors='ignore')

        j = json.loads(query)

        if 'result' not in j:
            return []

    seasonID = j['result']['seasondetails']['seasonid']
    tvshowID = j['result']['seasondetails']['tvshowid']

    return getTVShowCast(tvshowID)
def get_tv_files(called_from_tv_menu, progress, done):
    result = eval(xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "id": 1}'))
    if 'tvshows' not in result['result']:
        return []
        
    tv_shows = result['result']['tvshows']
    files = []

    for tv_show in tv_shows:
        show_id = tv_show['tvshowid']
        show_name = clean_path(tv_show['label'])
        log("%s" % show_name, xbmc.LOGINFO)
        displaystring = __language__(30209) + show_name
        log("%s" % displaystring, xbmc.LOGINFO)
        progress.update(done, displaystring.encode('utf-8')) 

        episode_result = eval(xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"tvshowid": %d, "properties": ["file"]}, "id": 1}' % show_id))

        try:
            episodes = episode_result['result']['episodes']
            files.extend([ clean_path(e['file']) for e in episodes ])
        except KeyError:
            if called_from_tv_menu and __scriptdebug__:
                displaystring = __language__(30209) + show_name
                xbmcgui.Dialog().ok(__language__(30203), displaystring.encode('utf-8'), __language__(30204))

    return files
def getPlaylistLengthFromXBMCPlayer(playerid):
    if playerid == -1:
        return 1 #Default player (-1) can't be checked properly
    if playerid < 0 or playerid > 2:
        Debug("[Util] getPlaylistLengthFromXBMCPlayer, invalid playerid: "+str(playerid))
        return 0
    rpccmd = json.dumps({'jsonrpc': '2.0', 'method': 'Player.GetProperties','params':{'playerid': playerid, 'properties':['playlistid']}, 'id': 1})
    result = xbmc.executeJSONRPC(rpccmd)
    result = json.loads(result)
    # check for error
    try:
        error = result['error']
        Debug("[Util] getPlaylistLengthFromXBMCPlayer, Player.GetProperties: " + str(error))
        return 0
    except KeyError:
        pass # no error
    playlistid = result['result']['playlistid']
    
    rpccmd = json.dumps({'jsonrpc': '2.0', 'method': 'Playlist.GetProperties','params':{'playlistid': playlistid, 'properties': ['size']}, 'id': 1})
    result = xbmc.executeJSONRPC(rpccmd)
    result = json.loads(result)
    # check for error
    try:
        error = result['error']
        Debug("[Util] getPlaylistLengthFromXBMCPlayer, Playlist.GetProperties: " + str(error))
        return 0
    except KeyError:
        pass # no error
    
    return result['result']['size']
    def getNowPlaying(self):
        # Get the active player
        result = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "id": 1, "method": "Player.GetActivePlayers"}')
        result = unicode(result, 'utf-8', errors='ignore')
        self.logMsg("Got active player " + result, 2)
        result = json.loads(result)

        # Seems to work too fast loop whilst waiting for it to become active
        while not result["result"]:
            result = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "id": 1, "method": "Player.GetActivePlayers"}')
            result = unicode(result, 'utf-8', errors='ignore')
            self.logMsg("Got active player " + result, 2)
            result = json.loads(result)

        if 'result' in result and result["result"][0] is not None:
            playerid = result["result"][0]["playerid"]

            # Get details of the playing media
            self.logMsg("Getting details of now  playing media", 1)
            result = xbmc.executeJSONRPC(
                '{"jsonrpc": "2.0", "id": 1, "method": "Player.GetItem", "params": {"playerid": ' + str(
                    playerid) + ', "properties": ["showtitle", "tvshowid", "episode", "season", "playcount","genre"] } }')
            result = unicode(result, 'utf-8', errors='ignore')
            self.logMsg("Got details of now playing media" + result, 2)

            result = json.loads(result)
            return result
Example #11
0
 def __init__(self):
     self._parse_argv()
     # check how we were executed
     if self.MOVIEID:
         xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Player.Open", "params": { "item": { "movieid": %d }, "options":{ "resume": %s } }, "id": 1 }' % (int(self.MOVIEID), self.RESUME))
     elif self.EPISODEID:
         xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Player.Open", "params": { "item": { "episodeid": %d }, "options":{ "resume": %s }  }, "id": 1 }' % (int(self.EPISODEID), self.RESUME))
     elif self.MUSICVIDEOID:
         xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Player.Open", "params": { "item": { "musicvideoid": %d } }, "id": 1 }' % int(self.MUSICVIDEOID))
     elif self.ALBUMID:
         xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Player.Open", "params": { "item": { "albumid": %d } }, "id": 1 }' % int(self.ALBUMID))
     elif self.SONGID:
         xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Player.Open", "params": { "item": { "songid": %d } }, "id": 1 }' % int(self.SONGID))
     else:
         self._init_vars()
         self._init_property()
         # clear our property, if another instance is already running it should stop now
         self.WINDOW.clearProperty('SkinWidgets_Running')
         a_total = datetime.datetime.now()
         self._fetch_info_randomitems()
         self._fetch_info_recommended()
         self._fetch_info_recentitems()
         b_total = datetime.datetime.now()
         c_total = b_total - a_total
         log('Total time needed for all queries: %s' % c_total)
         # give a possible other instance some time to notice the empty property
         self.WINDOW.setProperty('SkinWidgets_Running', 'true')
         self._daemon()
Example #12
0
 def _fetch_song(self, request):
     if not xbmc.abortRequested:
         json_string = '{"jsonrpc": "2.0", "id": 1, "method": "AudioLibrary.GetSongs", "params": {"properties": ["title", "playcount", "artist", "album", "year", "file", "thumbnail", "fanart", "rating"], "filter": {"field": "playcount", "operator": "lessthan", "value": "1"}, "limits": {"end": %d},' %self.LIMIT
         if request == 'RandomSong' and self.RANDOMITEMS_UNPLAYED == "True":
             json_query = xbmc.executeJSONRPC('%s "sort": {"method": "random"}}}'  %json_string)
         else:
             json_query = xbmc.executeJSONRPC('%s  "sort": {"method": "random"}}}'  %json_string)
         json_query = unicode(json_query, 'utf-8', errors='ignore')
         json_query = simplejson.loads(json_query)
         if json_query.has_key('result') and json_query['result'].has_key('songs'):
             self._clear_properties(request)
             count = 0
             for item in json_query['result']['songs']:
                 count += 1
                 play = 'XBMC.RunScript(' + __addonid__ + ',songid=' + str(item.get('songid')) + ')'
                 path = media_path(item['file'])
                 self.WINDOW.setProperty("%s.%d.Title"       % (request, count), item['title'])
                 self.WINDOW.setProperty("%s.%d.Artist"      % (request, count), " / ".join(item['artist']))
                 self.WINDOW.setProperty("%s.%d.Year"        % (request, count), str(item['year']))
                 self.WINDOW.setProperty("%s.%d.Rating"      % (request, count), str(int(item['rating'])-48))
                 self.WINDOW.setProperty("%s.%d.Album"       % (request, count), item['album'])
                 self.WINDOW.setProperty("%s.%d.Thumb"       % (request, count), item['thumbnail']) #remove
                 self.WINDOW.setProperty("%s.%d.Fanart"      % (request, count), item['fanart']) #remove
                 self.WINDOW.setProperty("%s.%d.Art(thumb)"  % (request, count), item['thumbnail'])
                 self.WINDOW.setProperty("%s.%d.Art(fanart)" % (request, count), item['fanart'])
                 self.WINDOW.setProperty("%s.%d.File"        % (request, count), item['file'])
                 self.WINDOW.setProperty("%s.%d.Path"        % (request, count), path)
                 self.WINDOW.setProperty("%s.%d.Play"        % (request, count), play)
         del json_query
Example #13
0
def getNextUpEpisodes(tagname,limit):
    count=0
    addonSettings = xbmcaddon.Addon(id='plugin.video.emby')
    #if the addon is called with nextup parameter, we return the nextepisodes list of the given tagname
    xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
    # First we get a list of all the in-progress TV shows - filtered by tag
    json_query_string = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": { "sort": { "order": "descending", "method": "lastplayed" }, "filter": {"and": [{"operator":"true", "field":"inprogress", "value":""}, {"operator": "contains", "field": "tag", "value": "%s"}]}, "properties": [ "title", "studio", "mpaa", "file", "art" ]  }, "id": "libTvShows"}' %tagname)
    
    json_result = json.loads(json_query_string)
    # If we found any, find the oldest unwatched show for each one.
    if json_result.has_key('result') and json_result['result'].has_key('tvshows'):
        for item in json_result['result']['tvshows']:

            # If Ignore Specials is true only choose episodes from seasons greater than 0.
            if addonSettings.getSetting("ignoreSpecialsNextEpisodes")=="true":
                json_query2 = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": { "tvshowid": %d, "sort": {"method":"episode"}, "filter": {"and": [ {"field": "playcount", "operator": "lessthan", "value":"1"}, {"field": "season", "operator": "greaterthan", "value": "0"} ]}, "properties": [ "title", "playcount", "season", "episode", "showtitle", "plot", "file", "rating", "resume", "tvshowid", "art", "streamdetails", "firstaired", "runtime", "writer", "dateadded", "lastplayed" ], "limits":{"end":1}}, "id": "1"}' %item['tvshowid'])
            else:
                json_query2 = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": { "tvshowid": %d, "sort": {"method":"episode"}, "filter": {"field": "playcount", "operator": "lessthan", "value":"1"}, "properties": [ "title", "playcount", "season", "episode", "showtitle", "plot", "file", "rating", "resume", "tvshowid", "art", "streamdetails", "firstaired", "runtime", "writer", "dateadded", "lastplayed" ], "limits":{"end":1}}, "id": "1"}' %item['tvshowid'])

            if json_query2:
                json_query2 = json.loads(json_query2)
                if json_query2.has_key('result') and json_query2['result'].has_key('episodes'):
                    for item in json_query2['result']['episodes']:
                        liz = createListItem(item)
                        xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=item['file'], listitem=liz)
                        count +=1
            if count == limit:
                break
    xbmcplugin.endOfDirectory(handle=int(sys.argv[1]))
Example #14
0
def getRecentEpisodes(tagname,limit):
    #if the addon is called with recentepisodes parameter, we return the recentepisodes list of the given tagname
    xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
    # First we get a list of all the TV shows - filtered by tag
    json_query_string = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": { "sort": { "order": "descending", "method": "dateadded" }, "properties": [ "title","sorttitle" ], "filter": {"operator": "contains", "field": "tag", "value": "%s"} }, "id": "libTvShows"}' %tagname)    
    json_result = json.loads(json_query_string)
    
    # If we found any, put all tv show id's in a list
    if json_result.has_key('result') and json_result['result'].has_key('tvshows'):
        alltvshowIds = list()
        for tvshow in json_result['result']['tvshows']:
            alltvshowIds.append(tvshow["tvshowid"])
        alltvshowIds = set(alltvshowIds)
        
        #get all recently added episodes
        json_query2 = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": { "sort": {"order": "descending", "method": "dateadded"}, "filter": {"field": "playcount", "operator": "lessthan", "value":"1"}, "properties": [ "title", "playcount", "season", "episode", "showtitle", "plot", "file", "rating", "resume", "tvshowid", "art", "streamdetails", "firstaired", "runtime", "cast", "writer", "dateadded", "lastplayed" ]}, "limits":{"end":%d}, "id": "1"}' %limit)
        count = 0
        if json_query2:
            json_query2 = json.loads(json_query2)
            if json_query2.has_key('result') and json_query2['result'].has_key('episodes'):
                for item in json_query2['result']['episodes']:
                    if item["tvshowid"] in alltvshowIds:
                        liz = createListItem(item)
                        xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=item['file'], listitem=liz)
                        count += 1
                    if count == limit:
                        break
    xbmcplugin.endOfDirectory(handle=int(sys.argv[1]))
def build_music_playlist():
    log( "Building Music Playlist", xbmc.LOGNOTICE )
    xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "AudioPlaylist.Clear", "id": 1}')
    music_playlist = xbmc.PlayList( xbmc.PLAYLIST_MUSIC )
    track_location = []
    # check to see if playlist or music file is selected
    if trivia_settings[ "trivia_music" ] == 1:
        if trivia_settings[ "trivia_music_file" ].endswith(".m3u"):
            log( "Music Playlist: %s" % trivia_settings[ "trivia_music_file" ] )
            playlist_file = xbmcvfs.File( trivia_settings[ "trivia_music_file" ], 'rb')
            saved_playlist = playlist_file.read().splitlines()
            playlist_file.close()
            log( "Finished Reading Music Playlist" )
            track_info, track_location = parse_playlist( saved_playlist, xbmc.getSupportedMedia('music') )
        elif os.path.splitext( trivia_settings[ "trivia_music_file" ] )[1] in xbmc.getSupportedMedia('music'):
            for track in range(100):
                track_location.append( trivia_settings[ "trivia_music_file" ] )
    # otherwise
    else:
        if trivia_settings[ "trivia_music_folder" ]:
            # search given folder and subfolders for files
            track_location = dirEntries( trivia_settings[ "trivia_music_folder" ], "music", "TRUE" )
    # shuffle playlist
    shuffle( track_location )
    for track in track_location:
        music_playlist.add( track,  )
Example #16
0
    def getLibraryMeta(self):
        try:
            if self.content == 'movie':
                meta = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": {"filter":{"or": [{"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}]}, "properties" : ["title", "originaltitle", "year", "genre", "studio", "country", "runtime", "rating", "votes", "mpaa", "director", "writer", "plot", "plotoutline", "tagline", "thumbnail", "file"]}, "id": 1}' % (self.year, str(int(self.year)+1), str(int(self.year)-1)))
                meta = unicode(meta, 'utf-8', errors='ignore')
                meta = json.loads(meta)['result']['movies']
                meta = [i for i in meta if i['file'].endswith(self.file)][0]

                self.DBID = meta['movieid'] ; poster = thumb = meta['thumbnail']

                meta = {'title': meta['title'], 'originaltitle': meta['originaltitle'], 'year': meta['year'], 'genre': str(' / '.join(meta['genre'])), 'studio' : str(' / '.join(meta['studio'])), 'country' : str(' / '.join(meta['country'])), 'duration' : meta['runtime'], 'rating': meta['rating'], 'votes': meta['votes'], 'mpaa': meta['mpaa'], 'director': str(' / '.join(meta['director'])), 'writer': str(' / '.join(meta['writer'])), 'plot': meta['plot'], 'plotoutline': meta['plotoutline'], 'tagline': meta['tagline']}


            elif self.content == 'episode':
                meta = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "season", "operator": "is", "value": "%s"}, {"field": "episode", "operator": "is", "value": "%s"}]}, "properties": ["title", "season", "episode", "showtitle", "firstaired", "runtime", "rating", "director", "writer", "plot", "thumbnail", "file"]}, "id": 1}' % (self.season, self.episode))
                meta = unicode(meta, 'utf-8', errors='ignore')
                meta = json.loads(meta)['result']['episodes']
                meta = [i for i in meta if i['file'].endswith(self.file)][0]

                self.DBID = meta['episodeid'] ; thumb = meta['thumbnail'] ; showtitle = meta['showtitle']

                meta = {'title': meta['title'], 'season' : meta['season'], 'episode': meta['episode'], 'tvshowtitle': meta['showtitle'], 'premiered' : meta['firstaired'], 'duration' : meta['runtime'], 'rating': meta['rating'], 'director': str(' / '.join(meta['director'])), 'writer': str(' / '.join(meta['writer'])), 'plot': meta['plot']}

                poster = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"filter": {"field": "title", "operator": "is", "value": "%s"}, "properties": ["thumbnail"]}, "id": 1}' % showtitle)
                poster = unicode(poster, 'utf-8', errors='ignore')
                poster = json.loads(poster)['result']['tvshows'][0]['thumbnail']


            return (poster, thumb, meta)
        except:
            poster, thumb, meta = '', '', {'title': self.name}
            return (poster, thumb, meta)
Example #17
0
def clear_slideshow():
    get_players = json.loads(xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 1}'))  # @UndefinedVariable
    for _player in get_players['result']:
        if _player['type'] == 'picture':
            stop_slideshow = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Player.Stop", "params": {"playerid":%i}, "id": 1}' % _player['playerid'])  # @UndefinedVariable
        else: continue
    clear_playlist = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Playlist.Clear", "params": {"playlistid":2}, "id": 1}')  # @UndefinedVariable
def build_music_playlist():
    utils.log( "Building Music Playlist", xbmc.LOGNOTICE )
    xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "AudioPlaylist.Clear", "id": 1}')
    music_playlist = xbmc.PlayList( xbmc.PLAYLIST_MUSIC )
    track_location = []
    # check to see if playlist or music file is selected
    if trivia_settings[ "trivia_music" ] == 1:
        if ( os.path.splitext( trivia_settings[ "trivia_music_file" ] )[ 1 ] ).lower() in ( "m3u", "pls", "asf", "ram" ):
            utils.log( "Music Playlist: %s" % trivia_settings[ "trivia_music_file" ] )
            if trivia_settings[ "trivia_music_file" ].endswith(".m3u"):
                track_location = parser.parse_m3u( trivia_settings[ "trivia_music_file" ], xbmc.getSupportedMedia('music') )
            elif trivia_settings[ "trivia_music_file" ].endswith(".pls"):
                track_location = parser.parse_pls( trivia_settings[ "trivia_music_file" ], xbmc.getSupportedMedia('music') )
            elif trivia_settings[ "trivia_music_file" ].endswith(".asf"):
                track_location = parser.parse_asf( trivia_settings[ "trivia_music_file" ], xbmc.getSupportedMedia('music') )
            elif trivia_settings[ "trivia_music_file" ].endswith(".ram"):
                track_location = parser.parse_ram( trivia_settings[ "trivia_music_file" ], xbmc.getSupportedMedia('music') )
        elif os.path.splitext( trivia_settings[ "trivia_music_file" ] )[1] in xbmc.getSupportedMedia('music'):
            for track in range(100):
                track_location.append( trivia_settings[ "trivia_music_file" ] )
    # otherwise
    else:
        if trivia_settings[ "trivia_music_folder" ]:
            # search given folder and subfolders for files
            track_location = absolute_listdir( trivia_settings[ "trivia_music_folder" ], media_type = "music", recursive = True )
    # shuffle playlist
    shuffle( track_location )
    for track in track_location:
        music_playlist.add( track,  )
Example #19
0
def getTvshowList():
    rpccmd = {'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': { 'properties': ['title', 'imdbnumber'] }, 'id': 'libTvShows'}
    rpccmd = json.dumps(rpccmd)
    result = xbmc.executeJSONRPC(rpccmd)
    tvshows = json.loads(result)
    log('tvshows=%s' % tvshows)  
    tvshowList = []
    if tvshows.has_key('result') and tvshows['result'] != None and tvshows['result'].has_key('tvshows'):
        tvshows = tvshows['result']['tvshows']
        for tvshow in tvshows:
            rpccmd = {'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': {'tvshowid': tvshow['tvshowid'], 'properties': ['season', 'episode', 'playcount']}, 'id': 1}
            rpccmd = json.dumps(rpccmd)
            result = xbmc.executeJSONRPC(rpccmd)
            episodes = json.loads(result)
            log('tvshow=%s [%s]' % (tvshow['title'], tvshow['imdbnumber'])) 
            log('episodes[%s]=%s' % (tvshow['imdbnumber'], episodes)) 
            if episodes.has_key('result') and episodes['result'] != None and episodes['result'].has_key('episodes'):
                episodes = episodes['result']['episodes']
                lastEpisode = None
                lastSeasonNr = 0
                lastEpisodeNr = 0
                firstEpisode = None
                firstSeasonNr = 2
                firstEpisodeNr = 2
                for episode in episodes:
                    if episode['playcount'] >= 1:
                        if (episode['season'] > lastSeasonNr):
                            lastSeasonNr = episode['season']
                            lastEpisodeNr = episode['episode']
                            lastEpisode = episode
                        elif (episode['season'] == lastSeasonNr and episode['episode'] > lastEpisodeNr):
                            lastEpisodeNr = episode['episode']
                            lastEpisode = episode
                    if (episode['season'] < firstSeasonNr):
                        firstSeasonNr = episode['season']
                        firstEpisodeNr = episode['episode']
                        firstEpisode = episode
                    elif (episode['season'] == firstSeasonNr and episode['episode'] < firstEpisodeNr):
                        firstEpisodeNr = episode['episode']
                        firstEpisode = episode
                if lastEpisode != None:
                    tvshowList.append({
                        'seen': 1,
                        'title': tvshow['title'],
                        'show_id': tvshow['imdbnumber'],
                        'season': lastEpisode['season'],
                        'episode': lastEpisode['episode']
                    })
                    log('dernier_vu=s%.2de%.2d' % (int(lastEpisode['season']), int(lastEpisode['episode'])))
                elif firstEpisode != None:
                    tvshowList.append({
                        'seen': 0,
                        'title': tvshow['title'],
                        'show_id': tvshow['imdbnumber'],
                        'season': firstEpisode['season'],
                        'episode': firstEpisode['episode']
                    })
                    log('premier_non_vu=s%.2de%.2d' % (int(firstEpisode['season']), int(firstEpisode['episode'])))
    log('list=%s' % tvshowList)
    return tvshowList
Example #20
0
def setTvshowProgress(show_id, last_season_seen, last_episode_seen):
    rpccmd = {'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShows', 'params': { 'properties': ['title', 'imdbnumber'] }, 'id': 'libTvShows'}
    rpccmd = json.dumps(rpccmd)
    result = xbmc.executeJSONRPC(rpccmd)
    tvshows = json.loads(result)
    log('tvshows=%s' % tvshows)
    if tvshows['result']['limits']['total'] == 0:
        return
    tvshows = tvshows['result']['tvshows']
    for tvshow in tvshows:
        if int(tvshow['imdbnumber']) == int(show_id):
            log('tvshow=%s' % tvshow)
            rpccmd = {'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodes', 'params': {'tvshowid': tvshow['tvshowid'], 'properties': ['title', 'season', 'episode']}, 'id': 1}
            rpccmd = json.dumps(rpccmd)
            result = xbmc.executeJSONRPC(rpccmd)
            episodes = json.loads(result)  
            log('episodes=%s' % episodes)  
            if episodes['result']['limits']['total'] > 0:
                episodes = episodes['result']['episodes']
                for episode in episodes:
                    log('episode=%s' % episode) 
                    if (episode['season'] <= last_season_seen and episode['episode'] <= last_episode_seen):               
                        command2 = '{"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetEpisodeDetails", "params": {"episodeid" : %s, "playcount": %s}}' % (episode['episodeid'], 1)
                        result2 = json.loads(xbmc.executeJSONRPC(command2))
                        log('watched=%s' % 1)
                    else:         
                        command2 = '{"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetEpisodeDetails", "params": {"episodeid" : %s, "playcount": %s}}' % (episode['episodeid'], 0)
                        result2 = json.loads(xbmc.executeJSONRPC(command2))
                        log('watched=%s' % 0)
 def alphabetletter(self):
     """used with the alphabet scrollbar to jump to a letter"""
     if KODI_VERSION > 16:
         xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=False, listitem=xbmcgui.ListItem())
     letter = self.params.get("letter", "").upper()
     jumpcmd = ""
     if letter in ["A", "B", "C", "2"]:
         jumpcmd = "2"
     elif letter in ["D", "E", "F", "3"]:
         jumpcmd = "3"
     elif letter in ["G", "H", "I", "4"]:
         jumpcmd = "4"
     elif letter in ["J", "K", "L", "5"]:
         jumpcmd = "5"
     elif letter in ["M", "N", "O", "6"]:
         jumpcmd = "6"
     elif letter in ["P", "Q", "R", "S", "7"]:
         jumpcmd = "7"
     elif letter in ["T", "U", "V", "8"]:
         jumpcmd = "8"
     elif letter in ["W", "X", "Y", "Z", "9"]:
         jumpcmd = "9"
     if jumpcmd:
         xbmc.executebuiltin("SetFocus(50)")
         for i in range(40):
             xbmc.executeJSONRPC(
                 '{ "jsonrpc": "2.0", "method": "Input.ExecuteAction",\
                 "params": { "action": "jumpsms%s" }, "id": 1 }'
                 % (jumpcmd)
             )
             xbmc.sleep(50)
             if xbmc.getInfoLabel("ListItem.Sortletter").upper() == letter:
                 break
def mirror_sub(id, filename, sub_file):
    try:
        playerid_query = '{"jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 1}'
        playerid = json.loads(xbmc.executeJSONRPC(playerid_query))['result'][0]['playerid']
        imdb_id_query = '{"jsonrpc": "2.0", "method": "Player.GetItem", "params": {"playerid": ' + str(playerid) + ', "properties": ["imdbnumber"]}, "id": 1}'
        imdb_id = json.loads(xbmc.executeJSONRPC (imdb_id_query))['result']['item']['imdbnumber']
    except:
        imdb_id = 0

    values = {}
    values['id'] = id
    values['versioname'] = filename
    values['source'] = 'ktuvit'
    values['year'] = xbmc.getInfoLabel("VideoPlayer.Year")
    values['season'] = str(xbmc.getInfoLabel("VideoPlayer.Season"))
    values['episode'] = str(xbmc.getInfoLabel("VideoPlayer.Episode"))
    values['imdb'] = str(imdb_id)
    values['tvshow'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.TVshowtitle"))
    values['title'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.OriginalTitle"))
    values['file_original_path'] = urllib.unquote(unicode(xbmc.Player().getPlayingFile(), 'utf-8'))
    url = 'http://api.wizdom.xyz/upload.php'
    try:
        post(url, files={'sub': open(sub_file, 'rb')}, data=values)
    except:
        pass
Example #23
0
    def getKodiMusicVideos(self,fullInfo = False):
        #returns all musicvideos in Kodi db inserted by MB
        xbmc.sleep(sleepVal)
        if fullInfo:
            json_response = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMusicVideos", "params": { "properties" : ["art", "thumbnail", "fanart", "resume", "runtime", "year", "genre", "studio", "artist", "album", "track", "lastplayed", "plot", "director", "playcount", "tag", "file"] }, "id": "libMusicVideos"}')
        else:
            json_response = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMusicVideos", "params": { "properties" : ["resume", "playcount", "lastplayed", "file", "track"] }, "id": "libMusicVideos"}')
        jsonobject = json.loads(json_response.decode('utf-8','replace'))  
        musicvideos = None
        if(jsonobject.has_key('result')):
            result = jsonobject['result']
            if(result.has_key('musicvideos')):
                musicvideos = result['musicvideos']

        kodiMusicVideoMap = None
        if(musicvideos != None and len(musicvideos) > 0):
            kodiMusicVideoMap = {}
            connection = utils.KodiSQL()
            cursor = connection.cursor()
            for kodivideo in musicvideos:
                cursor.execute("SELECT c23 as MBid FROM musicvideo WHERE idMVideo = ?",(kodivideo["musicvideoid"],))
                result = cursor.fetchone()
                if result != None:
                    key = result[0]
                    kodiMusicVideoMap[key] = kodivideo
            
            cursor.close()    
        return kodiMusicVideoMap
 def _fetch_albums(self, request):
     if not xbmc.abortRequested:
         json_string = '{"jsonrpc": "2.0", "id": 1, "method": "AudioLibrary.GetAlbums", "params": {"properties": ["title", "description", "albumlabel", "artist", "genre", "year", "thumbnail", "fanart", "rating", "playcount"], "limits": {"end": %d},' %self.LIMIT
         if request == 'RecommendedAlbum':
             json_query = xbmc.executeJSONRPC('%s "sort": {"order": "descending", "method": "playcount" }}}' %json_string)
         elif request == 'RecentAlbum':
             json_query = xbmc.executeJSONRPC('%s "sort": {"order": "descending", "method": "dateadded" }}}' %json_string)
         else:
             json_query = xbmc.executeJSONRPC('%s "sort": {"method": "random"}}}' %json_string)
         json_query = unicode(json_query, 'utf-8', errors='ignore')
         json_query = simplejson.loads(json_query)
         if json_query['result'].has_key('albums'):
             self._clear_properties(request)
             count = 0
             for item in json_query['result']['albums']:
                 count += 1
                 rating = str(item['rating'])
                 if rating == '48':
                     rating = ''
                 play = 'XBMC.RunScript(' + __addonid__ + ',albumid=' + str(item.get('albumid')) + ')'
                 self.WINDOW.setProperty("%s.%d.Title"       % (request, count), item['title'])
                 self.WINDOW.setProperty("%s.%d.Label"       % (request, count), item['title']) #needs to be removed
                 self.WINDOW.setProperty("%s.%d.Artist"      % (request, count), " / ".join(item['artist']))
                 self.WINDOW.setProperty("%s.%d.Genre"       % (request, count), " / ".join(item['genre']))
                 self.WINDOW.setProperty("%s.%d.Year"        % (request, count), str(item['year']))
                 self.WINDOW.setProperty("%s.%d.RecordLabel" % (request, count), item['albumlabel'])
                 self.WINDOW.setProperty("%s.%d.Description" % (request, count), item['description'])
                 self.WINDOW.setProperty("%s.%d.Rating"      % (request, count), rating)
                 self.WINDOW.setProperty("%s.%d.Thumb"       % (request, count), item['thumbnail']) #remove
                 self.WINDOW.setProperty("%s.%d.Fanart"      % (request, count), item['fanart']) #remove
                 self.WINDOW.setProperty("%s.%d.Art(thumb)"  % (request, count), item['thumbnail'])
                 self.WINDOW.setProperty("%s.%d.Art(fanart)" % (request, count), item['fanart'])
                 self.WINDOW.setProperty("%s.%d.Play"        % (request, count), play)
         del json_query
Example #25
0
def first_step():
    which_way = xbmcgui.Dialog().select(__language__(33901), ["TVShow Time > Kodi", "Kodi > TVShow Time"])
    if which_way < 0: return
    tvshows = []
    tvshowsid = []
    command = '{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"sort": { "order": "ascending", "method": "label" }}, "id": 1}'
    result = json.loads(xbmc.executeJSONRPC(command))                     
    for i in range(0, result['result']['limits']['total']):
        tvshows.append(result['result']['tvshows'][i]['label'])
        tvshowsid.append(result['result']['tvshows'][i]['tvshowid'])
    tvshows.insert(0, __language__(33902))
    tvshowsid.insert(0, "0")
    whattvshow = xbmcgui.Dialog().select(__language__(33903), tvshows)
    if whattvshow < 0: return
    elif whattvshow == 0:
        scan(which_way)
    else:
        seasons = []
        command = '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params":{"tvshowid": %s, "properties": ["season"], "sort": { "order": "ascending", "method": "season" }}, "id": 1}' % tvshowsid[whattvshow]
        result = json.loads(xbmc.executeJSONRPC(command))                     
        for i in range(0, result['result']['limits']['total']):
            seasons.append(str(result['result']['episodes'][i]['season']))
        seasons = remove_duplicates(seasons)
        seasons.insert(0, __language__(33904))
        whatseason = xbmcgui.Dialog().select(__language__(33905), seasons)
        if whatseason < 0: return
        elif whatseason == 0:
            scan(which_way, tvshowsid[whattvshow])
        else:
            scan(which_way, tvshowsid[whattvshow], whatseason)
Example #26
0
def setXBMCMoviePlaycount(movieid, playcount, imdb_id):
    if getXBMCMajorVersion() >= 12:
        time.sleep(0.2)
        xbmc.executeJSONRPC(
            json.dumps(
                {
                    "jsonrpc": "2.0",
                    "method": "VideoLibrary.SetMovieDetails",
                    "params": {"movieid": movieid, "playcount": playcount},
                    "id": 1,
                }
            )
        )
        time.sleep(0.2)
    else:
        match = raw_xbmc_database.RawXbmcDb.query(
            "SELECT movie.idFile FROM movie" + " WHERE movie.c09='%(imdb_id)s'" % {"imdb_id": xcp(imdb_id)}
        )

        if not match:
            # add error message here
            return

        try:
            match[0][0]
        except KeyError:
            return

        raw_xbmc_database.RawXbmcDb.execute(
            "UPDATE files"
            + " SET playcount=%(playcount)d" % {"playcount": int(playcount)}
            + " WHERE idFile=%(idFile)s" % {"idFile": xcp(match[0][0])}
        )
Example #27
0
def getEpisodeDetailsFromXbmc(libraryId, fields):
	rpccmd = json.dumps({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetEpisodeDetails', 'params':{'episodeid': libraryId, 'properties': fields}, 'id': 1})

	result = xbmc.executeJSONRPC(rpccmd)
	Debug('[VideoLibrary.GetEpisodeDetails] ' + result)
	result = json.loads(result)

	# check for error
	try:
		error = result['error']
		Debug("getEpisodeDetailsFromXbmc: " + str(error))
		return None
	except KeyError:
		pass # no error

	try:
		# get tvdb id
		rpccmd_show = json.dumps({'jsonrpc': '2.0', 'method': 'VideoLibrary.GetTVShowDetails', 'params':{'tvshowid': result['result']['episodedetails']['tvshowid'], 'properties': ['year', 'imdbnumber']}, 'id': 1})
		
		result_show = xbmc.executeJSONRPC(rpccmd_show)
		Debug('[VideoLibrary.GetTVShowDetails] ' + result_show)
		result_show = json.loads(result_show)
		
		# add to episode data
		result['result']['episodedetails']['tvdb_id'] = result_show['result']['tvshowdetails']['imdbnumber']
		result['result']['episodedetails']['year'] = result_show['result']['tvshowdetails']['year']
		
		return result['result']['episodedetails']
	except KeyError:
		Debug("getEpisodeDetailsFromXbmc: KeyError: result['result']['episodedetails']")
		return None
    def getDetails(self):
        details_query_string = '{"jsonrpc": "2.0", "method": "Player.GetProperties", "params":' \
            '{ "properties": ["currentaudiostream", "audiostreams", "subtitleenabled", "currentsubtitle", "subtitles" ], "playerid": 1 },' \
            '"id": 1}'
        json_query = xbmc.executeJSONRPC(details_query_string)
        json_query = unicode(json_query, 'utf-8', errors='ignore')
        json_response = simplejson.loads(json_query)
        
        if json_response.has_key('result') and json_response['result'] != None:
            self.selected_audio_stream = json_response['result']['currentaudiostream']
            self.selected_sub = json_response['result']['currentsubtitle']
            self.selected_sub_enabled = json_response['result']['subtitleenabled']
            self.audiostreams = json_response['result']['audiostreams']
            self.subtitles = json_response['result']['subtitles']
        log(LOG_DEBUG, json_response )

        genre_tags_query_string = '{"jsonrpc": "2.0", "method": "Player.GetItem", "params": { "properties": ["genre", "tag"], "playerid": 1 }, "id": 1}'
        json_query = xbmc.executeJSONRPC(genre_tags_query_string)
        json_query = unicode(json_query, 'utf-8', errors='ignore')
        json_response = simplejson.loads(json_query)
        if json_response.has_key('result') and json_response['result'] != None:
            gt = []
            if json_response['result']['item'].has_key('genre'):
                gt = json_response['result']['item']['genre']
            if json_response['result']['item'].has_key('tag'):
                gt.extend(json_response['result']['item']['tag'])
            self.genres_and_tags = set(map(lambda x:x.lower(), gt))
        log(LOG_DEBUG, 'Video tags/genres: {0}'.format(self.genres_and_tags))
        log(LOG_DEBUG, json_response )
Example #29
0
    def _get_info( self, episodeid, playcount, playstatus ):
        try:
            tvshow_query = '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodeDetails", "params": {"episodeid": ' + str(episodeid) + ', "properties": ["tvshowid", "showtitle", "season", "episode"]}, "id": 1}'
            tvshow = json.loads(xbmc.executeJSONRPC (tvshow_query))['result']['episodedetails']
            tvdbid_query = '{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShowDetails", "params": {"tvshowid": ' + str(tvshow['tvshowid']) + ', "properties": ["imdbnumber"]}, "id": 1}'
            tvdbid = json.loads(xbmc.executeJSONRPC (tvdbid_query))['result']['tvshowdetails']['imdbnumber']
            showtitle = tvshow['showtitle'].encode("utf-8")
            epname = str(tvshow['season']) + 'x' + str(tvshow['episode'])
        except:
            log("could not get tvshow/episode details", xbmc.LOGNOTICE)
        if not tvdbid:
            url = self.service[1] + '/shows/search'
            urldata = '?v=2.2&key=' + self.service[2] + '&title=' + showtitle
            try:
                tvdbid_query = get_urldata(url + urldata, '', "GET")
                tvdbid_query = json.loads(tvdbid_query)
                tvdbid = tvdbid_query['shows'][0]['thetvdb_id']
            except:
                log("could not fetch tvshow's thetvdb_id", xbmc.LOGNOTICE)
                return False
        url = self.service[1] + '/shows/episodes'
        urldata = '?v=2.2&key=' + self.service[2] + '&thetvdb_id=' + str(tvdbid) + '&season=' + str(tvshow['season']) + '&episode=' + str(tvshow['episode'])
        try:
            tvdbepid_query = get_urldata(url + urldata, '', "GET")
            tvdbepid_query = json.loads(tvdbepid_query)
            tvdbepid = tvdbepid_query['episodes'][0]['thetvdb_id']
        except:
            log("could not fetch episode's thetvdb_id", xbmc.LOGNOTICE)
            return False

        epinfo = [int(tvdbid), int(tvdbepid), int(playcount), bool(playstatus), showtitle, epname]
        return epinfo
Example #30
0
def RefreshPVR(m3uPath, epgPath, logoPath, forceUpdate=False, forceUpdateIPTV=False):
	if forceUpdateIPTV or common.getAutoIPTV():
		UpdateIPTVSimpleSettings(m3uPath, epgPath, logoPath)
	kodi16 = True if common.GetKodiVer() < 17 else False
	if Addon.getSetting("autoPVR") == "true":
		if (not json.loads(xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Addons.GetAddonDetails","params":{"addonid":"pvr.iptvsimple", "properties": ["enabled"]},"id":1}'))['result']['addon']['enabled'] or (kodi16 and not json.loads(xbmc.executeJSONRPC('{"jsonrpc":"2.0", "method":"Settings.GetSettingValue", "params":{"setting":"pvrmanager.enabled"},"id":1}'))['result']['value'])):
			tvOption = common.GetMenuSelected(localizedString(30317).encode('utf-8'), [localizedString(30318).encode('utf-8'), localizedString(30319).encode('utf-8')])
			if tvOption != 0:
				if tvOption == 1:
					Addon.setSetting("useIPTV", "False")
				return False
		isIPTVnotRestarted = not EnableIptvClient() and not kodi16
		isPVRnotRestarted = kodi16 and not EnablePVR()
		if isIPTVnotRestarted and forceUpdate:
			xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Addons.SetAddonEnabled","params":{"addonid":"pvr.iptvsimple","enabled":false},"id":1}')
			xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Addons.SetAddonEnabled","params":{"addonid":"pvr.iptvsimple","enabled":true},"id":1}')
			#iptvAddon = GetIptvAddon()
			#if iptvAddon is None:
			#	return False
			#iptvAddon.setSetting("m3uPathType", iptvAddon.getSetting("m3uPathType"))
		if isPVRnotRestarted:
			xbmc.executebuiltin('StopPVRManager')
			xbmc.executebuiltin('StartPVRManager')
		return True
	else:
		return False
Example #31
0
def migrate_profile(new_profile, add_on_id, kodi_add_on_dir, add_on_name):
    """ Migrates the old user profile.

    :param str|unicode new_profile:     The new profile folder.
    :param str|unicode add_on_id:       The new add-on id.
    :param str|unicode kodi_add_on_dir: The Kodi add-on dir.
    :param str|unicode add_on_name:     The name of the current add-on.

    """

    old_add_on_id = "net.rieter.xot"
    # This was a xbmc.LOGWARNING, but that is not allowed according to the Kodi add-on rules.
    log_level = xbmc.LOGDEBUG

    xbmc.log(
        "{}: Checking if migration of profile is required.".format(
            add_on_name), xbmc.LOGDEBUG)
    # If the profile already existed, just stop here.
    if os.path.isdir(new_profile):
        xbmc.log("{}: Profile already migrated.".format(add_on_name),
                 log_level)
        return

    import shutil
    d = xbmcgui.Dialog()

    # If an old add-on with the old ID was found, disable and rename it.
    old_add_on_path = os.path.abspath(
        os.path.join(kodi_add_on_dir, "..", old_add_on_id))
    if os.path.isdir(old_add_on_path):
        xbmc.log(
            "{}: Disabling add-on from {}".format(add_on_name,
                                                  old_add_on_path), log_level)

        # Disable it.
        data = {
            "jsonrpc": "2.0",
            "method": "Addons.SetAddonEnabled",
            "params": {
                "addonid": old_add_on_id,
                "enabled": False
            },
            "id": 1
        }
        result = xbmc.executeJSONRPC(json.dumps(data))
        xbmc.log(result, log_level)
        result = json.loads(result)
        if not result or "error" in result:
            # This was a xbmc.LOGWARNING, but that is not allowed according to the Kodi add-on rules.
            xbmc.log(
                "{}: Error disabling {}".format(add_on_name, old_add_on_id),
                xbmc.LOGDEBUG)

        # Rename it.
        old_add_on_xml = os.path.join(old_add_on_path, "addon.xml")
        if os.path.exists(old_add_on_xml):
            with io.open(old_add_on_xml, mode="r", encoding='utf-8') as fp:
                content = fp.read()

            if "<broken>" not in content:
                xbmc.log(
                    "{}: Marking add-on {} as broken.".format(
                        add_on_name, old_add_on_path), log_level)

                content = content.replace(
                    '</language>', '</language>\n        '
                    '<broken>New Add-on is used. Please install version 4.8 or higher.</broken>'
                )
                with io.open(old_add_on_xml, mode='w+',
                             encoding='utf-8') as fp:
                    fp.write(content)
            text = xbmcaddon.Addon().getLocalizedString(30603)
            d.ok(add_on_name, text)

        xbmc.log(
            "{}: Reloading all Kodi Add-ons information.".format(add_on_name),
            log_level)
        xbmc.executebuiltin("UpdateLocalAddons")

    # If there was an old profile, migrate it.
    old_profile = os.path.abspath(
        os.path.join(new_profile, "..", old_add_on_id))
    if not os.path.exists(old_profile):
        xbmc.log(
            "{}: No old profile data found at {}.".format(
                add_on_name, old_profile), log_level)
        return
    xbmc.log("{}: Old Profile located at {}".format(add_on_name, old_profile),
             log_level)

    d.notification(add_on_name,
                   "Migrating add-on data to new format.",
                   icon="info",
                   time=5)

    xbmc.log(
        "{}: Migrating addon_data {} to {}.".format(add_on_name, old_profile,
                                                    new_profile), log_level)
    shutil.copytree(old_profile,
                    new_profile,
                    ignore=shutil.ignore_patterns("textures"))

    # If there were local setttings, we need to migrate those too so the channel ID's are updated.
    local_settings_file = os.path.join(new_profile, "settings.json")
    if os.path.exists(local_settings_file):
        xbmc.log("{}: Migrating {}.".format(add_on_name, local_settings_file),
                 log_level)
        with io.open(local_settings_file, mode="rb") as fp:
            content = fp.read()
            settings = json.loads(content, encoding='utf-8')

        channel_ids = settings.get("channels", {})
        channel_settings = {}
        for channel_id in channel_ids:
            new_channel_id = channel_id.replace(old_add_on_id, add_on_id)
            xbmc.log(
                "{}: - Renaming {} -> {}.".format(add_on_name, channel_id,
                                                  new_channel_id), log_level)
            channel_settings[new_channel_id] = settings["channels"][channel_id]

        settings["channels"] = channel_settings
        with io.open(local_settings_file, mode='w+b') as fp:
            content = json.dumps(settings, indent=4, encoding='utf-8')
            fp.write(content)

    # fix the favourites
    favourites_path = os.path.join(new_profile, "favourites")
    if os.path.isdir(favourites_path):
        xbmc.log(
            "{}: Updating favourites at {}".format(add_on_name,
                                                   favourites_path), log_level)
        for fav in os.listdir(favourites_path):
            # plugin://net.rieter.xot/
            fav_path = os.path.join(favourites_path, fav)
            xbmc.log("{}: - Updating favourite: {}.".format(add_on_name, fav),
                     log_level)
            with io.open(fav_path, mode='r', encoding='utf-8') as fp:
                content = fp.read()

            content = content.replace("plugin://{}/".format(old_add_on_id),
                                      "plugin://{}/".format(add_on_id))
            with io.open(fav_path, mode='w+', encoding='utf-8') as fp:
                fp.write(content)

    xbmc.log("{}: Migration completed.".format(add_on_name), log_level)
    return
    def loop(self):
        twpath = os.path.join(xbmc.translatePath('special://home'), 'userdata',
                              'addon_data', 'service.maxxam.teamwatch',
                              'tw.ini')

        while not self.monitor.abortRequested():
            # after DISPLAY_TIME_SECS elapsed hide the message bar
            if self.monitor.waitForAbort(REFRESH_TIME_SECS):
                self.hide_message()
                self._log("stop")
                break

            if self.feed_is_shown and time.time(
            ) - self.feed_show_time > DISPLAY_TIME_SECS:
                self.hide_message()

                if self.show_disable_after:
                    self.hide_message()
                    self.show_enable = False
                    self.show_disable_after = False

            if (time.time() -
                    self.start_time) < REFRESH_TIME_SECS or self.feed_is_shown:
                continue

            self.start_time = time.time()

            try:
                file = open(twpath, "r")
                self.id_chat = int(file.read())
                file.close()
            except:
                self.id_chat = -1

            params = {
                'idt': self.id_twitter,
                'idc': self.id_chat,
                'twid': self.id_teamwatch,
                'pcid': self.id_playerctl,
                'nickname': self.nickname
            }
            if self.feed_name:
                params['q'] = ":".join(self.feed_name)
            else:
                params['q'] = "#teamwatch"

            if self.twitter_enabled:
                params['tqp'] = "&lang=%s&result_type=%s" % (
                    self.twitter_language, self.twitter_result_type)
                params['tl'] = self.twitter_language
            else:
                params['    notweet'] = 1

            url = 'http://www.teamwatch.it/get.php?%s' % urllib.urlencode(
                params)

            if DEBUG > 1:
                self._log("id_chat: " + str(self.id_chat))
                self._log(url)

            try:
                jresult = {}
                jresult = json.loads(urllib.urlopen(url).read())
            except:
                self._log("error opening %s" % url)
            finally:
                if 'id' in jresult:
                    if 'is_twitter' in jresult and jresult['is_twitter'] == 1:
                        self.id_twitter = jresult['id']
                    else:
                        self.id_chat = jresult['id']

                    file = open(twpath, "w+")
                    file.write(str(self.id_chat))
                    file.close()

            if jresult['status'] == 'ok' and self.show_enable:
                file = open(twpath, "w")
                file.write(str(self.id_chat))
                file.close()

                user = jresult['user'].encode('utf-8')
                text = jresult['text'].encode('utf-8')

                if self.show_allways or xbmcgui.getCurrentWindowId(
                ) == WINDOW_FULLSCREEN_VIDEO:
                    if DEBUG > 1:
                        self.show_message(user, text, [
                            ICON_CHAT, ICON_TWITTER
                        ][jresult['is_twitter']])  #, jresult['id'])
                    else:
                        self.show_message(user, text,
                                          [ICON_CHAT, ICON_TWITTER
                                           ][jresult['is_twitter']])
            elif jresult['status'] == 'settings':
                param = jresult['param'].encode('utf-8')
                if param.startswith("#tw:addfeed:"):
                    if not param[12:] in self.feed_name:
                        self.feed_name.append(param[12:])
                        self.__addon__.setSetting('feed',
                                                  ":".join(self.feed_name))
                        self.show_message('TeamWatch',
                                          localize(32000, param[12:]),
                                          ICON_SETTING)
                elif param.startswith("#tw:removefeed:"):
                    if param[15:] in self.feed_name:
                        self.feed_name.remove(param[15:])
                        self.__addon__.setSetting('feed',
                                                  ":".join(self.feed_name))
                        self.show_message('TeamWatch',
                                          localize(32001, param[15:]),
                                          ICON_SETTING)
                elif param == "#tw:off":
                    self.show_message('TeamWatch', localize(32002),
                                      ICON_SETTING)
                    self.show_disable_after = True
                elif param == "#tw:on":
                    self.show_enable = True
                    self.show_message('TeamWatch', localize(32003),
                                      ICON_SETTING)
                elif param == "#tw:bar:top":
                    self.bartop = 0
                    self.show_message('TeamWatch', "Bar position set to top",
                                      ICON_SETTING)
                elif param == "#tw:bar:bottom":
                    self.bartop = self.screen_height - 75
                    self.show_message('TeamWatch',
                                      "Bar position set to bottom",
                                      ICON_SETTING)
                elif param == "#tw:id":
                    self.id_chat = jresult['idc']
                    self.id_twitter = jresult['idt']

                    file = open(twpath, "w")
                    file.write(str(self.id_chat))
                    file.close()
                elif param == "#tw:playerctl:playpause":
                    self._log('esecuzione #tw:playerctl:playpause')
                    xbmc.executebuiltin("Action(PlayPause)")
                    self._log('playpause terminated id_chat: ' +
                              str(self.id_chat))
                elif param == "#tw:playerctl:sshot":
                    xbmc.executebuiltin("TakeScreenshot")
                elif param.startswith("#tw:playerctl:seek:"):
                    t = [
                        int("0" + filter(str.isdigit, x))
                        for x in param[19:].split(":")
                    ]
                    if len(t) == 4:
                        xbmc.executeJSONRPC(
                            '{ "jsonrpc": "2.0", "method": "Player.Seek", "params": {"playerid":1, "value": {"hours":%d, "minutes":%d, "seconds":%d, "milliseconds":%d}}, "id": 1 }'
                            % tuple(t))
                    elif DEBUG:
                        self._log('#tw:playerctl:seek invalid time')
                elif param.startswith("#tw:playstream:"):
                    self._log('*** playstream received ***')
                    self._log(param[15:])
                    player = xbmc.Player()
                    player.play(param[15:])
                elif param.startswith("#tw:invite:"):
                    # web_pdb.set_trace()
                    if DEBUG: self._log("#tw:invite")
                    invite = param[11:].split(":")

                    if invite[0] == "m":
                        self._log("#tw:invite:m: %s" % invite[1])
                        movie = xbmc_helpers.search_movie(invite[1])
                        self._log("after movie search")

                        if movie:
                            # dialog = xbmcgui.Dialog()
                            # res = dialog.yesno(localize(32004), localize(32005, (invite[1], movie["title"])))
                            if DEBUG:
                                self._log("invite received for movie: %s" %
                                          movie["title"])

                            player = xbmc.Player()
                            player.play(movie["file"])

                            if player.isPlaying():
                                self._log('playing...')
                            else:
                                self._log('not playing...')
                        else:
                            if DEBUG:
                                self._log(
                                    "invite received for non existent movie %s"
                                    % invite[1])

                    elif invite[0] == "e":
                        episode = xbmc_helpers.search_episode(
                            invite[1], invite[2], invite[3])

                        if episode:
                            dialog = xbmcgui.Dialog()
                            s_ep = "S[COLOR green][B]%02d[/B][/COLOR]E[COLOR green][B]%02d[/B][/COLOR]" % (
                                int(episode["season"]), int(
                                    episode["episode"]))
                            res = dialog.yesno(
                                localize(32004),
                                localize(
                                    32006,
                                    (invite[1], episode["showtitle"], s_ep)))
                            if DEBUG:
                                self._log(
                                    "invite received for episode id: %d" %
                                    episode["episodeid"])
                        else:
                            if DEBUG:
                                self._log(
                                    "invite received for non existent episode %s %s %s"
                                    % (invite[1], invite[2], invite[3]))
                    else:
                        pass
                else:
                    pass
            else:
                if DEBUG and jresult['status'] == "fail" and jresult[
                        'reason'] != "no feeds" and not jresult[
                            'reason'].startswith('waiting'):
                    self._log(jresult)

                if DEBUG and jresult['reason'].startswith('json parse error'):
                    self.id_twitter = -1
                    self.id_chat = -1
Example #33
0
 def _execute(self, request):
     request_string = json.dumps(request)
     response = xbmc.executeJSONRPC(request_string)
     if (response):
         response = json.loads(response)
     return response
Example #34
0
    def ShowNotification(title,
                         lines,
                         notificationType=Info,
                         displayTime=1500,
                         fallback=True,
                         logger=None):
        """ Shows an XBMC Notification

        Arguments:
        titel   : String - The title to show
        content : String - The content to show

        Keyword Arguments:
        notificationType  : String - The type of notification: info, error, warning
        displayTime       : int    - Time to display the notification. Defaults to 1500 ms.
        fallback          : bool   - Should we fallback on XbmcWrapper.ShowDialog on error?

        """

        # check for a title
        if title:
            notificationTitle = "%s - %s" % (Config.appName, title)
        else:
            notificationTitle = Config.appName

        # check for content and merge multiple lines. This is to stay compatible
        # with the LanguageHelper.GetLocalizedString that returns strings as arrays
        # if they are multiple lines (this is because XbmcWrapper.ShowDialog needs
        # this for multi-line dialog boxes.
        if not lines:
            notificationContent = ""
        else:
            if isinstance(lines, (tuple, list)):
                notificationContent = " ".join(lines)
            else:
                notificationContent = lines

        # determine the duration
        notificationType = notificationType.lower()
        if notificationType == XbmcWrapper.Warning and displayTime < 2500:
            displayTime = 2500
        elif notificationType == XbmcWrapper.Info and displayTime < 5000:
            displayTime = 5000
        elif displayTime < 1500:
            # cannot be smaller then 1500 (API limit)
            displayTime = 1500

        # Get an icon
        notificationIcon = os.path.join(Config.rootDir, "icon.png")
        if os.path.exists(notificationIcon):
            # change the separators
            notificationIcon = notificationIcon.replace("\\", "/")
        else:
            notificationIcon = notificationType

        if logger:
            logger.Debug("Showing notification: %s - %s", notificationTitle,
                         notificationContent)

        command = '{"id": 1,"jsonrpc":"2.0","method":"GUI.ShowNotification","params":{"title":"%s","message":"%s", "image":"%s", "displaytime": %s}}' % (
            notificationTitle, notificationContent, notificationIcon,
            displayTime)
        try:
            if logger:
                logger.Trace("Sending command: %s", command)
            response = xbmc.executeJSONRPC(command)
            if logger:
                logger.Trace("Response: %s", response)
            return response
        except:
            if fallback:
                XbmcWrapper.ShowDialog(title or "", lines or "")
            # no reason to worry if this does not work on older XBMC's
            return False
Example #35
0
def getTvshowList():
    rpccmd = {
        'jsonrpc': '2.0',
        'method': 'VideoLibrary.GetTVShows',
        'params': {
            'properties': ['title', 'imdbnumber']
        },
        'id': 'libTvShows'
    }
    rpccmd = json.dumps(rpccmd)
    result = xbmc.executeJSONRPC(rpccmd)
    tvshows = json.loads(result)
    log('tvshows=%s' % tvshows)
    tvshowList = []
    if tvshows.has_key('result') and tvshows['result'] != None and tvshows[
            'result'].has_key('tvshows'):
        tvshows = tvshows['result']['tvshows']
        for tvshow in tvshows:
            rpccmd = {
                'jsonrpc': '2.0',
                'method': 'VideoLibrary.GetEpisodes',
                'params': {
                    'tvshowid': tvshow['tvshowid'],
                    'properties': ['season', 'episode', 'playcount']
                },
                'id': 1
            }
            rpccmd = json.dumps(rpccmd)
            result = xbmc.executeJSONRPC(rpccmd)
            episodes = json.loads(result)
            log('tvshow=%s [%s]' % (tvshow['title'], tvshow['imdbnumber']))
            log('episodes[%s]=%s' % (tvshow['imdbnumber'], episodes))
            if episodes.has_key(
                    'result') and episodes['result'] != None and episodes[
                        'result'].has_key('episodes'):
                episodes = episodes['result']['episodes']
                lastEpisode = None
                lastSeasonNr = 0
                lastEpisodeNr = 0
                firstEpisode = None
                firstSeasonNr = 2
                firstEpisodeNr = 2
                for episode in episodes:
                    if episode['playcount'] >= 1:
                        if (episode['season'] > lastSeasonNr):
                            lastSeasonNr = episode['season']
                            lastEpisodeNr = episode['episode']
                            lastEpisode = episode
                        elif (episode['season'] == lastSeasonNr
                              and episode['episode'] > lastEpisodeNr):
                            lastEpisodeNr = episode['episode']
                            lastEpisode = episode
                    if (episode['season'] < firstSeasonNr):
                        firstSeasonNr = episode['season']
                        firstEpisodeNr = episode['episode']
                        firstEpisode = episode
                    elif (episode['season'] == firstSeasonNr
                          and episode['episode'] < firstEpisodeNr):
                        firstEpisodeNr = episode['episode']
                        firstEpisode = episode
                if lastEpisode != None:
                    tvshowList.append({
                        'seen': 1,
                        'title': tvshow['title'],
                        'show_id': tvshow['imdbnumber'],
                        'season': lastEpisode['season'],
                        'episode': lastEpisode['episode']
                    })
                    log('dernier_vu=s%.2de%.2d' % (int(
                        lastEpisode['season']), int(lastEpisode['episode'])))
                elif firstEpisode != None:
                    tvshowList.append({
                        'seen': 0,
                        'title': tvshow['title'],
                        'show_id': tvshow['imdbnumber'],
                        'season': firstEpisode['season'],
                        'episode': firstEpisode['episode']
                    })
                    log('premier_non_vu=s%.2de%.2d' % (int(
                        firstEpisode['season']), int(firstEpisode['episode'])))
    log('list=%s' % tvshowList)
    return tvshowList
#
#     Copyright (C) 2016 KenV99
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import xbmc
import sys

addonid = sys.argv[1]

xbmc.executeJSONRPC(
    '{"jsonrpc":"2.0","method":"Addons.SetAddonEnabled", "params":{"addonid":"%s","enabled":"toggle"},"id":1}'
    % addonid)
xbmc.log(msg='***** Toggling addon enabled 1: %s' % addonid)
xbmc.sleep(1000)
xbmc.executeJSONRPC(
    '{"jsonrpc":"2.0","method":"Addons.SetAddonEnabled", "params":{"addonid":"%s","enabled":"toggle"},"id":1}'
    % addonid)
xbmc.log(msg='***** Toggling addon enabled 2: %s' % addonid)
Example #37
0
def search_subtitles(search):
    subtitles = []
    log("entering search_subtitles()")
    if search['mode'] == "movie":
        log("movies not supported!")
        return False
    # get video file name
    dirsync = __addon__.getSetting('dirsync') == 'true'
    if dirsync:
        # get directory name as filename
        filename = os.path.basename(os.path.dirname(search['path'])).lower()
    else:
        # or use filename
        filename = os.path.basename(search['path']).lower()
        # and remove file extension
        filename = re.sub(r"\.[^.]+$", "", filename)
    filename = normalize_string(filename)
    log("after filename = %s" % (filename))
    # if file, check if valid tvshow
    if search['mode'] == "file" and not re.search(r"(?i)(s[0-9]+e[0-9]+|[0-9]+x?[0-9]{2,})", filename):
        log("not a tvshow or badly named!")
        return False
    # get subtitle team
    subteams = []
    subteams.append(filename.replace(".","-"))
    if len(subteams[0]) > 0:
        # get team name (everything after "-")
        subteams[0] = self_team_pattern.match("-" + subteams[0]).groups()[0].lower()
        # find equivalent teams, if any
        tmp = other_team(subteams[0],0,1)
        if len(tmp) > 0 and tmp != subteams[0]:
            subteams.append(tmp)
        # find other equivalent teams, if any
        tmp = other_team(subteams[0],1,0)
        if len(tmp) > 0 and tmp != subteams[0]:
            subteams.append(tmp)
    log("after subteams = %s" % (subteams))
    # configure socket
    socket.setdefaulttimeout(10)
    # define default url to get betaseries episode id from filename
    episodeurl = "%s/episodes/scraper?file=%s&key=%s&v=%s" % (self_host, urllib.quote(filename), self_apikey, self_apiver)
    # check video type
    if search['mode'] == "tvshow":
        # get playerid
        json_query = '{"jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 1}'
        playerid = json.loads(xbmc.executeJSONRPC(json_query))['result'][0]['playerid']
        # get tvshowid
        json_query = '{"jsonrpc": "2.0", "method": "Player.GetItem", "params": {"playerid": ' + str(playerid) + ', "properties": ["tvshowid"]}, "id": 1}'
        tvshowid = json.loads(xbmc.executeJSONRPC (json_query))['result']['item']['tvshowid']
        # check result
        if tvshowid > 0:
            # get tvdbid
            json_query = '{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShowDetails", "params": {"tvshowid": ' + str(tvshowid) + ', "properties": ["imdbnumber"]}, "id": 1}'
            tvdbid_result = json.loads(xbmc.executeJSONRPC(json_query))
            # if we have tvdbid, work with ids
            if 'result' in tvdbid_result:
                # get betaseries show id from tvdbid
                tvdbid = tvdbid_result['result']['tvshowdetails']['imdbnumber']
                showurl = "%s/shows/display?thetvdb_id=%s&key=%s&v=%s" % (self_host, tvdbid, self_apikey, self_apiver)
                showid = json.loads(get_url(showurl))["show"]["id"]
                log("after showid = %s" % (showid))
                # then get betaseries episode id
                episodeurl = "%s/episodes/search?show_id=%s&number=S%#02dE%#02d&key=%s&v=%s" % (self_host, showid, int(search['season']), int(search['episode']), self_apikey, self_apiver)
    try:
        episodeid = json.loads(get_url(episodeurl))["episode"]["id"]
        log("after episodeid = %s" % (episodeid))
    except:
        log("error or episode not found!")
        return False
    # then get subtitles list
    listurl = "%s/subtitles/episode?id=%s&key=%s&v=%s" % (self_host, episodeid, self_apikey, self_apiver)
    try:
        data = json.loads(get_url(listurl))["subtitles"]
    except:
        log("could not parse data or fetch url, cannot continue")
        return False
    # for each release version
    log("parsing data after urlopen")
    log("--------------------------")
    for subtitle in data:
        # get filename
        subfile = normalize_string(subtitle["file"])
        log("after subfile = %s" % (subfile))
        # get file extension
        ext = string.split(subfile,'.')[-1]
        # get season number from data
        season = int(subtitle["episode"]["season"])
        log("after season = %s" % (season))
        # get episode number from data
        episode = int(subtitle["episode"]["episode"])
        log("after episode = %s" % (episode))
        # get names of files contained in zip file, if any
        if len(subtitle["content"]) > 0:
            content = subtitle["content"]
        # or put filename in content
        else:
            content = [subtitle["file"]]
        log("after content = %s" % (content))
        # for each file in content
        for subversion in content:
            log("-------------")
            # subtitle file name
            subversion = normalize_string(subversion)
            log("after subversion = %s" % (subversion))
            # subtitle download url
            link = subtitle["url"]
            log("after link = %s" % (link))
            try:
                # normalize lang
                lang2 = {
                    "VO": "en",
                    "VF": "fr",
                    "VOVF": "xx",
                }[subtitle["language"]]
            except:
                log("unsupported language")
                continue 
            # get note
            if 0 <= int(subtitle["quality"]) <= 5:
                note = int(subtitle["quality"])
            else:
                note = 0
            log("after note = %s" % (note))
            # check if file is a subtitle
            if not len(re.findall(r"(?i)\.(srt|ssa|ass|sub)$", subversion)):
                log("not a subtitle : %s" % (subversion))
                continue
            # if from a zip file
            if len(content) > 1:
                # check if file is for correct season and episode
                search_string = r"(?i)(s%#02de%#02d|%d%#02d|%dx%#02d)" % (season, episode, season, episode, season, episode)
                if not re.search(search_string, subversion):
                    log("file not matching episode : %s" % (subversion))
                    continue
                # get subtitle file lang
                langs = re.search(r"(?i)[ _.-](english|french|eng|fre|en|fr|vo|vf)[ _.-]", subversion)
                # or get zip file lang
                if langs == None:
                    langs = lang2
                else:
                    langs = langs.group(1).lower()
                log("after zip langs = %s" % (lang2))
                try:
                    lang2 = {
                        "french": 'fr',
                        "english": 'en',
                        "fre": 'fr',
                        "eng": 'en',
                        "fr": 'fr',
                        "en": 'en',
                        "vf": 'fr',
                        "vo": 'en'
                    }[langs]
                except:
                    log("unsupported language")
                    continue
                log("after zip lang2 = %s" % (lang2))
            try:
                # get full language name
                lang = xbmc.convertLanguage(lang2, xbmc.ENGLISH_NAME)
            except:
                log("unsupported language")
                continue
            # if lang = user gui language
            if lang == search['uilang']:
                # put this file on top
                uilang = True
            else:
                uilang = False
            log("after lang = %s, lang2 = %s" % (lang, lang2))
            # check sync
            sync = False
            team = False
            for (key, subteam) in enumerate(subteams):
                # if team corresponds
                if len(subteam) > 0 and len(re.findall(r"(?i)[ _.-](" + subteam + ")[ _.-]", subversion)) > 0:
                    # set sync tag
                    sync = True
                    # if videofile team matches subfile team
                    if key == 0:
                        team = True
            log("after sync = %s" % (sync))
            # check if this is for hearing impaired
            if len(re.findall(r"(?i)[ _.-](CC|HI)[ _.-]", subversion)) > 0:
                cc = True
            else:
                cc = False
            log("after cc = %s" % (cc))
            # if language allowed by user
            if lang2 in search['langs']:
                # add subtitle to list
                subtitles.append({'uilang':uilang,'ext':ext,'filename':subversion,'link':link,'lang':lang,'lang2':lang2,"cc":cc,"sync":sync,"note":note,"team":team})
                log("subtitle added : %s" % (subversion))
        log("--------------------------")
    if subtitles:
        # get settings for sorting
        uifirst = __addon__.getSetting('uifirst') == 'true'
        ccfirst = __addon__.getSetting('ccfirst') == 'true'
        # sort accordingly
        log("sorting by filename asc")
        subtitles.sort(key=lambda x: [x['filename']])
        if not ccfirst:
            log("sorting by cc last")
            subtitles.sort(key=lambda x: [x['cc']])
        log("sorting by note best")
        subtitles.sort(key=lambda x: [x['note']], reverse=True)
        log("sorting by lang asc")
        subtitles.sort(key=lambda x: [x['lang']])
        if ccfirst:
            log("sorting by cc first")
            subtitles.sort(key=lambda x: [not x['cc']])
        if uifirst:
            log("sorting by uilang first")
            subtitles.sort(key=lambda x: [not x['uilang']])
        log("sorting by sync first")
        subtitles.sort(key=lambda x: [not x['sync']])
        log("sorting by team first")
        subtitles.sort(key=lambda x: [not x['team']])
        log("sorted subtitles = %s" % (subtitles))
        # for each subtitle
        for item in subtitles:
            # xbmc list item format
            listitem = xbmcgui.ListItem(label=item["lang"],
              label2=item["filename"],
              iconImage=str(item["note"]),
              thumbnailImage=item["lang2"])
            # setting sync / CC tag
            listitem.setProperty("sync", 'true' if item["sync"] else 'false')
            listitem.setProperty("hearing_imp", 'true' if item["cc"] else 'false')
            # adding item to GUI list
            url = "plugin://%s/?action=download&link=%s&ext=%s&filename=%s" % (__addonid__, item["link"], item["ext"], urllib.quote(item["filename"]))
            xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=listitem,isFolder=False)
    else:
        if self_notify:
            xbmc.executebuiltin((u'Notification(%s,%s,%s,%s)' % (__addonname__, __language__(30010), 750, __icon__)).encode('utf-8', 'ignore'))
        log("nothing found")
    log("end of search_subtitles()")
Example #38
0
	if not control.addon().getAddonInfo('id')=='program.apollo':
		with open(M3UFile, "rt") as fin:
			with open(M3UFile+"_tmp", "wt") as fout:
				for line in fin:
					fout.write(line.replace('program.apollo', control.addon().getAddonInfo('id')))
		fin.close
		fout.close
		os.remove(M3UFile)
		os.rename(M3UFile+"_tmp",M3UFile)
	
	xbmc.sleep(5)
	xbmc.executebuiltin('StopPVRManager')
	xbmc.executebuiltin('StartPVRManager')

try:
	if not json.loads(xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Addons.GetAddonDetails","params":{"addonid":"pvr.iptvsimple", "properties": ["enabled"]},"id":1}'))['result']['addon']['enabled']:
		xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Addons.SetAddonEnabled","params":{"addonid":"pvr.iptvsimple","enabled":true},"id":1}')
		xbmc.sleep(5)
		print "**** IPTV Simple: Enable"
except:	pass

try:
	if not json.loads(xbmc.executeJSONRPC('{"jsonrpc":"2.0", "method":"Settings.GetSettingValue", "params":{"setting":"pvrmanager.enabled"},"id":1}'))['result']['value']:
		xbmc.executeJSONRPC('{"jsonrpc":"2.0", "method":"Settings.SetSettingValue", "params":{"setting":"pvrmanager.enabled", "value":true},"id":1}')
		xbmc.sleep(2)
		xbmc.executebuiltin('StopPVRManager')
		xbmc.executebuiltin('StartPVRManager')
		print "**** PVR Manager: Enable"
		xbmc.Dialog().ok(control.addon().getAddonInfo('name'),"Please restart kodi for TV Guide to start")
except:	pass
Example #39
0
        if isItMovie:
            item['title'] = xbmc.getInfoLabel("ListItem.OriginalTitle")
        elif isItEpisode:
            item['title'] = xbmc.getInfoLabel("ListItem.TVShowTitle")
        else:
            item[
                'title'] = "SearchFor..."  # In order to show "No Subtitles Found" result.

    MyLog("item:%s" % item)
    imdb_id = 0
    try:
        if Player().isPlaying(
        ):  # Enable using subtitles search dialog when kodi is not playing
            playerid_query = '{"jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 1}'
            playerid = loads(
                executeJSONRPC(playerid_query))['result'][0]['playerid']
            imdb_id_query = '{"jsonrpc": "2.0", "method": "Player.GetItem", "params": {"playerid": ' + str(
                playerid) + ', "properties": ["imdbnumber"]}, "id": 1}'
            imdb_id = loads(
                executeJSONRPC(imdb_id_query))['result']['item']['imdbnumber']
            MyLog("imdb JSONPC:%s" % imdb_id)
        else:
            if labelIMDB:
                imdb_id = labelIMDB
            else:
                if isItMovie:
                    imdb_id = "ThisIsMovie"  #Search the movie by item['title'] for imdb_id
                elif isItEpisode:
                    imdb_id = "ThisIsEpisode"  #Search by item['title'] for tvdb_id
                else:
                    imdb_id = "tt0"  # In order to show "No Subtitles Found" result => Doesn't recognize movie/episode
Example #40
0
def execute_jsonrpc(command):
    if not isinstance(command, basestring):
        command = json.dumps(command)
    response = xbmc.executeJSONRPC(command)
    return json.loads(response)
Example #41
0
def Main():
    first_q = dialog.yesno('LazyTV', lang(32142), lang(32143), lang(32144))
    if first_q != 1:
        sys.exit()
    else:
        keyboard = xbmc.Keyboard(lang(32139))
        keyboard.doModal()
        if (keyboard.isConfirmed()):
            clone_name = keyboard.getText()
        else:
            sys.exit()

    # if the clone_name is blank then use default name of 'Clone'
    if not clone_name:
        clone_name = 'Clone'

    san_name = 'script.lazytv.' + sanitize_strings(clone_name)
    new_path = os.path.join(addon_path, san_name)

    log('clone_name = ' + str(clone_name))
    log('san_name = ' + str(san_name))
    log('new_path = ' + str(new_path))
    log('script path = ' + str(scriptPath))

    #check if folder exists, if it does then abort
    if os.path.isdir(new_path):

        log('That name is in use. Please try another')

        dialog.ok('LazyTV', lang(32145))
        __addon__.openSettings()
        sys.exit()

    try:

        # copy current addon to new location
        IGNORE_PATTERNS = ('.pyc', 'CVS', '.git', 'tmp', '.svn')
        shutil.copytree(scriptPath,
                        new_path,
                        ignore=shutil.ignore_patterns(*IGNORE_PATTERNS))

        # remove the unneeded files
        addon_file = os.path.join(new_path, 'addon.xml')

        os.remove(os.path.join(new_path, 'service.py'))
        os.remove(addon_file)
        #os.remove(os.path.join(new_path,'resources','selector.py'))
        os.remove(os.path.join(new_path, 'resources', 'settings.xml'))
        os.remove(os.path.join(new_path, 'resources', 'clone.py'))

        # replace the settings file and addon file with the truncated one
        shutil.move(os.path.join(new_path, 'resources', 'addon_clone.xml'),
                    addon_file)
        shutil.move(os.path.join(new_path, 'resources', 'settings_clone.xml'),
                    os.path.join(new_path, 'resources', 'settings.xml'))

    except Exception as e:
        ex_type, ex, tb = sys.exc_info()
        errorHandle(e, tb, new_path)

    # edit the addon.xml to point to the right folder
    tree = et.parse(addon_file)
    root = tree.getroot()
    root.set('id', san_name)
    root.set('name', clone_name)
    tree.find('.//summary').text = clone_name
    tree.write(addon_file)

    # replace the id on these files, avoids Access Violation
    py_files = [
        os.path.join(new_path, 'resources', 'selector.py'),
        os.path.join(new_path, 'resources', 'playlists.py'),
        os.path.join(new_path, 'resources', 'update_clone.py'),
        os.path.join(new_path, 'resources', 'episode_exporter.py')
    ]

    for py in py_files:
        for line in fileinput.input(
                py, inplace=1
        ):  # Does a list of files, and writes redirects STDOUT to the file in question
            print line.replace('script.lazytv', san_name),

    # stop and start the addon to have it show in the Video Addons window
    try:
        xbmc.executeJSONRPC(
            '{"jsonrpc":"2.0","method":"Addons.SetAddonEnabled","id":1,"params":{"addonid":"%s","enabled":false}}'
            % san_name)
        xbmc.sleep(1000)
        xbmc.executeJSONRPC(
            '{"jsonrpc":"2.0","method":"Addons.SetAddonEnabled","id":1,"params":{"addonid":"%s", "enabled":true}}'
            % san_name)
    except:
        pass

    dialog.ok('LazyTV', lang(32146), lang(32147))
Example #42
0
	def on_player_get():
		r_dict = json.loads(xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Player.GetActivePlayers","id":0}'))
		try: return r_dict["result"]
		except Exception: return None
Example #43
0
import lib.private.ydlfix
import lib.utils as utils
import xbmc
import xbmcaddon
from lib.utils import logger
from lib.youtube_dl import YoutubeDL

lib.private.ydlfix.patch_youtube_dl()

if utils.is_python_3():
    from urllib.parse import unquote
else:
    from urllib import unquote

have_adaptive_plugin = '"enabled":true' in xbmc.executeJSONRPC(
    '{"jsonrpc":"2.0","method":"Addons.GetAddonDetails","id":1,"params":{"addonid":"inputstream.adaptive", "properties": ["enabled"]}}'
)


def run(argument):
    if argument['type'] == 'magnet':
        handle_magnet(argument['data'])
    elif argument['type'] == 'unresolvedurl':
        if ('queue' not in argument) or (argument['queue'] == 'false'):
            action = 'play'
        else:
            action = 'queue'
        handle_unresolved_url(argument['data'], action)


def handle_magnet(data):
Example #44
0
def getBandwidthLimit():
    json_result = xbmc.executeJSONRPC(
        '{"jsonrpc":"2.0","method":"Settings.GetSettingValue","params":{"setting":"network.bandwidth"},"id":1}')
    data_object = json.loads(json_result)
    return data_object['result']['value']
Example #45
0
def listCat(cat):
    xbmcplugin.setContent(pluginhandle, "addons")
    xbmcplugin.addSortMethod(pluginhandle, xbmcplugin.SORT_METHOD_LABEL)
    addons = os.listdir(addonsFolder)
    json_result = xbmc.executeJSONRPC(
        '{"jsonrpc": "2.0", "method": "Addons.GetAddons", "params": {"content": "'
        + contentType + '"}, "id": 1}')
    if '"Method not found."' in json_result:
        if cat == "all":
            for a in addons:
                types = getTypes(a)
                if a != "script.categories" and contentType in types:
                    try:
                        currentAddon = xbmcaddon.Addon(id=a)
                        addonUrl = getAddonUrl(a, types)
                        title = currentAddon.getAddonInfo('name')
                        addAddonDir(title, addonUrl,
                                    currentAddon.getAddonInfo('icon'),
                                    currentAddon.getAddonInfo('description'),
                                    contentType, a,
                                    currentAddon.getAddonInfo('author'),
                                    currentAddon.getAddonInfo('version'))
                    except:
                        pass
        else:
            if os.path.exists(catsFile):
                fh = open(catsFile, 'r')
                content = fh.read()
                fh.close()
                for a in addons:
                    types = getTypes(a)
                    if a != "script.categories" and contentType in types and a + "#" + cat in content:
                        try:
                            currentAddon = xbmcaddon.Addon(id=a)
                            addonUrl = getAddonUrl(a, types)
                            title = currentAddon.getAddonInfo('name')
                            addAddonRDir(
                                title, addonUrl,
                                currentAddon.getAddonInfo('icon'), cat,
                                currentAddon.getAddonInfo('description'), a,
                                currentAddon.getAddonInfo('author'),
                                currentAddon.getAddonInfo('version'))
                        except:
                            pass

    else:
        match = re.compile('"addonid":"(.+?)","type":"(.+?)"',
                           re.DOTALL).findall(json_result)
        if cat == "all":
            for addonid, temp in match:
                try:
                    if addonid != "script.categories":
                        types = getTypes(addonid)
                        addonUrl = getAddonUrl(addonid, types)
                        currentAddon = xbmcaddon.Addon(id=addonid)
                        title = currentAddon.getAddonInfo('name')
                        addAddonDir(title, addonUrl,
                                    currentAddon.getAddonInfo('icon'),
                                    currentAddon.getAddonInfo('description'),
                                    contentType, addonid,
                                    currentAddon.getAddonInfo('author'),
                                    currentAddon.getAddonInfo('version'))
                except:
                    pass
        else:
            if os.path.exists(catsFile):
                fh = open(catsFile, 'r')
                content = fh.read()
                fh.close()
                for addonid, temp in match:
                    if addonid + "#" + cat in content:
                        try:
                            if addonid != "script.categories":
                                types = getTypes(addonid)
                                addonUrl = getAddonUrl(addonid, types)
                                currentAddon = xbmcaddon.Addon(id=addonid)
                                title = currentAddon.getAddonInfo('name')
                                addAddonRDir(
                                    title, addonUrl,
                                    currentAddon.getAddonInfo('icon'), cat,
                                    currentAddon.getAddonInfo('description'),
                                    addonid,
                                    currentAddon.getAddonInfo('author'),
                                    currentAddon.getAddonInfo('version'))
                        except:
                            pass
    xbmcplugin.endOfDirectory(pluginhandle)
    if forceViewMode:
        xbmc.executebuiltin('Container.SetViewMode(' + viewMode2 + ')')
Example #46
0
def getAllCount():
    json_result = xbmc.executeJSONRPC(
        '{"jsonrpc": "2.0", "method": "Addons.GetAddons", "params": {"content": "'
        + contentType + '"}, "id": 1}')
    match = re.compile('"addonid"', re.DOTALL).findall(json_result)
    return len(match) - 1
Example #47
0
        def _maybePlayNextProgramme(self):
            nextProgramme = _db_.getNextEpg()
            _db_.closeDB()

            if not nextProgramme:
                return

            timestampNow = int(time.time())
            if int(nextProgramme['end']) <= timestampNow:
                question = 'Do you want to play the next programme: '+nextProgramme["title"] + '?'
                response = xbmcgui.Dialog().yesno(_scriptname_, question, yeslabel='Yes', nolabel='No')

                if response:
                    command = 'RunPlugin(plugin://plugin.video.o2tvgo.iptv.simple?playfromepg=1&starttimestamp='
                    command += str(nextProgramme["start"])
                    command += '&channelname='
                    command += str(nextProgramme["channelName"])
                    command += ')'
                    self.logDbg('command: '+command)
                    xbmc.executebuiltin(command)

            else:
                position = timestampNow - int(nextProgramme['start'])
                length = int(nextProgramme['end']) - int(nextProgramme['start'])
                lengthMin = length / 60
                positionMinutes = position / 60
                positionPercent = 10000 * position / length * 0.01
                question = 'Do you want to switch to the currently playing programme on '+nextProgramme["channelName"]+': '+nextProgramme["title"] + ' (' + str(positionMinutes) + ' / ' + str(lengthMin) + ' min [' + str(positionPercent) + '%])?'
                response = xbmcgui.Dialog().yesno(_scriptname_, question, yeslabel='Yes', nolabel='No')

                if response:
                    payload = {
                      "jsonrpc": "2.0",
                      "id":"1",
                      "method": "PVR.GetChannels",
                      "params": {
                        "channelgroupid": "alltv"
                      }
                    }
                    payloadJson = json.dumps(payload)
                    jsonResponse = xbmc.executeJSONRPC(payloadJson)
                    if jsonResponse:
                        response = json.loads(jsonResponse)

                    channelID = None
                    if "result" in response and "channels" in response["result"]:
                        channels = response["result"]["channels"]
                        for channel in channels:
                            if channel["label"] == nextProgramme["channelName"]:
                                channelID = channel["channelid"]
                                break
                    if not channelID and channelID != 0:
                        self.logErr("Could not find the channel's ID")
                        self.logDbg('channelName: '+nextProgramme["channelName"])
                        self.logDbg('channels: '+jsonResponse)
                    else:
                        payload = {
                          "jsonrpc": "2.0",
                          "id":"1",
                          "method": "Player.Open",
                          "params": {
                            "item":{
                              "channelid": channelID
                            }
                          }
                        }
                        payloadJson = json.dumps(payload)
                        jsonResponse = xbmc.executeJSONRPC(payloadJson)
                        if jsonResponse:
                            responseDecoded = json.loads(jsonResponse)
                            if "error" in responseDecoded:
                                if "message" in responseDecoded["error"]:
                                    self.logErr("Could not play "+nextProgramme["channelKey"]+": "+responseDecoded["error"]["message"])
                                else:
                                    self.logErr("Could not play "+nextProgramme["channelKey"])
                                self.logDbg('payloadJson: '+payloadJson)
                                self.logDbg('jsonResponse: '+jsonResponse)
                        else:
                            self.logErr("Could not play "+nextProgramme["channelKey"]+": No response from JSONRPC")
                            self.logDbg('payloadJson: '+payloadJson)
                            self.logDbg('jsonResponse: '+jsonResponse)

            _db_.setIsNextProgrammeUsed()
            _db_.closeDB()
Example #48
0
def get_kodi_json(method, params):
    json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "%s", "params": %s, "id": 1}' % (method, params))
    json_query = unicode(json_query, 'utf-8', errors='ignore')
    return simplejson.loads(json_query)
Example #49
0
def getMovieLibrary():
    try:
        if common.getXBMCVersion() >= 12.0:
            properties = [
                'year', 'imdbnumber', 'thumbnail', 'plot', 'dateadded',
                'rating'
            ]
        else:
            properties = ['year', 'imdbnumber', 'thumbnail', 'plot', 'rating']
    except:
        properties = ['year', 'imdbnumber', 'thumbnail', 'plot', 'rating']
    rpccmd = json.dumps({
        'jsonrpc': '2.0',
        'method': 'VideoLibrary.GetMovies',
        'params': {
            'properties': properties,
            "sort": {
                "order": "ascending",
                "method": "label",
                "ignorearticle": True
            }
        },
        "id": "libMovies"
    })
    result = xbmc.executeJSONRPC(rpccmd)
    result = json.loads(result)
    if 'error' in result:
        dialog = xbmcgui.Dialog()
        ok = dialog.ok(plugin, settings.getLocalizedString(30018))
        build_main_directory()
        return
    if (result['result']['limits']['total'] == 0):
        dialog = xbmcgui.Dialog()
        ok = dialog.ok(plugin, settings.getLocalizedString(30016))
        build_main_directory()
        return
    totalItems = len(result['result']['movies'])
    for movie in result['result']['movies']:
        label = movie['label'].encode('ascii', 'ignore')
        plot = movie['plot'].encode('ascii', 'ignore')
        if 'dateadded' in movie:
            day = movie['dateadded'].split(' ')[0].split('-')
            date = day[2] + '.' + day[1] + '.' + day[0]
        else:
            date = '0000.00.00'
        thumbnail = movie['thumbnail']
        year = movie['thumbnail']
        url = movie['imdbnumber'].rsplit('tt')
        if len(url) == 2:
            url = url[1]
        else:
            url = '1'
        listitem = xbmcgui.ListItem(label=label,
                                    iconImage=thumbnail,
                                    thumbnailImage=thumbnail)
        u = {'mode': '8', 'name': label, 'url': url}
        cm = []
        run = sys.argv[0] + '?' + urllib.urlencode({
            'mode': '8',
            'name': label,
            'url': url,
            'download': 'True'
        })
        cm.append(
            (settings.getLocalizedString(30059), "XBMC.RunPlugin(%s)" % run))
        infoLabels = {
            "Title": label,
            "Plot": plot,
            "date": date,
            "Year": movie['year'],
            "Rating": movie['rating']
        }
        addListItem(label=label,
                    image=thumbnail,
                    url=u,
                    isFolder=False,
                    totalItems=totalItems,
                    infoLabels=infoLabels,
                    cm=cm)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_TITLE)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_DATE)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_VIDEO_YEAR)
    xbmcplugin.addSortMethod(handle=int(sys.argv[1]),
                             sortMethod=xbmcplugin.SORT_METHOD_VIDEO_RATING)
    setViewMode("500", "movies")
    xbmcplugin.endOfDirectory(int(sys.argv[1]))
def playVid(id,
            filename=None,
            season=None,
            episode=None,
            show=None,
            folder=None,
            type=''):
    import time
    import json

    #Check if its PseudoTV that's playing this file, if so, we shouldn't do anything else than play the video
    if xbmcgui.Window(10000).getProperty('PseudoTVRunning') == 'True':
        dev.log('PseudoTV is running, so just play the video')
        return playYoutubeVid(id)

    #Prepare the information
    loadingTime = time.time()
    totalTime = 0
    currentTime = 0
    folderPath = xbmc.getInfoLabel('Container.FolderPath')
    name = filename
    filename = filename + '.strm'
    filename = filename.translate(None, '\/:*?"<>|').strip('.')

    #Grab the metadata of this episode
    if type == 'movies':
        #meta = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": {"filter":{"field": "studio", "operator": "is", "value": "Youtube"}, "properties": ["title", "runtime", "rating", "director", "writer", "plot", "thumbnail", "file"]}, "id": 1}' % (filename))
        query = '{"jsonrpc": "2.0", "params": {"sort": {"order": "ascending", "method": "title"}, "filter": {"operator": "contains", "field": "path", "value": "%s"}, "properties": ["title", "art", "file", "thumbnail", "runtime", "rating", "plot"]}, "method": "VideoLibrary.GetMovies", "id": "libMovies"}' % (
            folder)
        dev.log('trying meta query now: ' + query)
        meta = xbmc.executeJSONRPC(query)

    else:
        meta = xbmc.executeJSONRPC(
            '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "season", "operator": "is", "value": "%s"}, {"field": "episode", "operator": "is", "value": "%s"}]}, "properties": ["title", "season", "episode", "showtitle", "firstaired", "runtime", "rating", "director", "writer", "plot", "thumbnail", "file"]}, "id": 1}'
            % (season, episode))
    meta = unicode(meta, 'utf-8', errors='ignore')
    dev.log('Meta: ' + meta)
    if 'episodes' in json.loads(meta)['result'] or 'movies' in json.loads(
            meta)['result']:
        if type == 'movies':
            meta = json.loads(meta)['result']['movies']
        else:
            meta = json.loads(meta)['result']['episodes']
        for i in meta:
            dev.log('Meta: ' + i['file'].encode('utf8'))
            dev.log('Looking for :' + filename)
            dev.log('File :' + i['file'])
            i['file'] = i['file'].encode('utf-8')
            if i['file'].endswith(filename):
                dev.log('Found the episode we are looking for')
                meta = i
                break

        if type == 'movies':
            DBID = meta['movieid']
            thumb = meta['thumbnail']

            meta = {
                'title': meta['title'].encode('utf-8'),
                'duration': meta['runtime'],
                'rating': meta['rating'],
                'plot': meta['plot'].encode('utf-8')
            }
            poster = 'Default.png'
            #poster = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"filter": {"field": "title", "operator": "is", "value": "%s"}, "properties": ["thumbnail"]}, "id": 1}' % showtitle.encode('utf-8'))
            #poster = unicode(poster, 'utf-8', errors='ignore')
            #poster = json.loads(poster)['result']['tvshows'][0]['thumbnail']
        else:
            DBID = meta['episodeid']
            thumb = meta['thumbnail']
            showtitle = meta['showtitle']

            meta = {
                'title': meta['title'].encode('utf-8'),
                'season': meta['season'],
                'episode': meta['episode'],
                'tvshowtitle': meta['showtitle'].encode('utf-8'),
                'premiered': meta['firstaired'].encode('utf-8'),
                'duration': meta['runtime'],
                'rating': meta['rating'],
                'director': str(' / '.join(meta['director']).encode('utf-8')),
                'writer': str(' / '.join(meta['writer']).encode('utf-8')),
                'plot': meta['plot'].encode('utf-8')
            }

            poster = xbmc.executeJSONRPC(
                '{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"filter": {"field": "title", "operator": "is", "value": "%s"}, "properties": ["thumbnail"]}, "id": 1}'
                % showtitle.encode('utf-8'))
            poster = unicode(poster, 'utf-8', errors='ignore')
            poster = json.loads(poster)['result']['tvshows'][0]['thumbnail']

        #If resume playback is set in the settings, display a resume menu
        try:
            if xbmcaddon.Addon().getSetting('resume_playback') == 'true':
                dev.log('Resume Playback is turned on. Grab resume point..')
                offset = bookmarks.getBookmark(name)
                dev.log('Offset is %s' % offset)
                if offset == '0': raise Exception()
                dev.log('Grabbing minutes and seconds')
                minutes, seconds = divmod(float(offset), 60)
                hours, minutes = divmod(minutes, 60)
                dev.log('Showing yesno. Minutes: %s, seconds: %s' %
                        (minutes, seconds))
                #yes = yesnoDialog('%s %02d:%02d:%02d' % ('Resume from ', hours, minutes, seconds), '', '', self.name, 'Resume', 'Start From Beginning')
                yes = xbmcgui.Dialog().yesno(
                    'Resume',
                    '%s %02d:%02d:%02d' %
                    ('Resume from ', hours, minutes, seconds),
                    nolabel='Resume',
                    yeslabel='Start From Beginning')
                dev.log('Chose option: %s' % yes)
                if yes: offset = '0'
        except:
            pass

        #Play the youtube video with the meta data just acquired
        playYoutubeVid(id, meta, poster)
    else:
        dev.log(
            'Error: Could not retrieve meta information from the database!',
            True)
        return playYoutubeVid(
            id
        )  #Just play the video, since we could not retrieve meta information

    #Check if the video is still playing and store the time it is currently playing
    for i in range(0, 300):
        if xbmc.Player().isPlayingVideo():
            #Set the offset of the video
            try:
                if offset == '0': raise Exception()
                xbmc.Player().seekTime(float(offset))
            except:
                pass
            break
        xbmc.sleep(100)
    while xbmc.Player().isPlayingVideo():
        try:
            totalTime = xbmc.Player().getTotalTime()
        except:
            pass
        try:
            currentTime = xbmc.Player().getTime()
        except:
            pass
        xbmc.sleep(1000)

    diff = currentTime / totalTime  #Calculate how much of the video has been watched
    #The video has stopped playing
    dev.log('Ended Video Playback (%s) @ %s (percentage: %s)' %
            (totalTime, currentTime, diff))

    #Delete the previous bookmark where we were and store the new one
    try:
        bookmarks.deleteBookmark(name)  #Delete the previous saved bookmark
        dev.log('Deleted the previous bookmark')
        ok = int(currentTime) > 120 and (
            currentTime / totalTime
        ) <= .9  #Has the video been playing long enough and is it viewed less then 90%?
        if ok:
            bookmarks.addBookmark(currentTime, name)  #Add the new bookmark
            dev.log('Added new bookmark @ %s' % currentTime)
    except:
        pass

    #Mark the episode as watched if enough was watched
    ok = diff >= .9  #Did the episode get watched for 90% or more?
    if int(currentTime) < 120:
        ok = diff >= .75  #Since the runtime is very short, we'll accept a view through as 75%
    if ok:
        dev.log('Episode has been watched for %s, mark as watched' % diff)
        bookmarks.mark_as_watched(DBID,
                                  folderPath)  #Mark the episode as watched
    else:
        dev.log('Episode has been watched for %s, dont mark as watched' % diff)
Example #51
0
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2011-present Alex@ELEC (http://alexelec.in.ua)

import os, json
import xbmc, xbmcgui

kodi_json = {}
params = {}
params["setting"] = "input.libinputkeyboardlayout"
kodi_json["jsonrpc"] = "2.0"
kodi_json["method"] = "Settings.GetSettingValue"
kodi_json["params"] = params
kodi_json["id"] = 1

request = xbmc.executeJSONRPC(json.dumps(kodi_json).encode("utf-8"))
response = json.loads(request.decode('utf-8', 'replace'))

if 'result' in response:
    kodi_json["method"] = "Settings.SetSettingValue"
    params["setting"] = "input.libinputkeyboardlayout"
    if response['result']['value'] == 'us':
        params["value"] = "ru"
        request = xbmc.executeJSONRPC(json.dumps(kodi_json).encode("utf-8"))
        response = json.loads(request.decode('utf-8', 'replace'))
        if response['result']:
            xbmc.executebuiltin(
                'Notification("Keybord", "set keyboard layout: Russian (RU)", 5000)'
            )
        else:
            xbmc.executebuiltin(
Example #52
0
# -*- coding: utf-8 -*-
import xbmc, xbmcaddon, xbmcplugin, xbmcgui
import sys, os, time, datetime, re, json
import urllib, urlparse

xbmcVer = xbmcaddon.Addon('xbmc.addon').getAddonInfo('version').split('.')
if int(xbmcVer[0]) > 16:
	
	res = json.loads(xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Addons.GetAddons","params":{"type":"kodi.inputstream","content":"unknown","enabled":false,"installed":true},"id":1}')).get('result', []).get('addons', [])
	for item in res:
		xbmc.executeJSONRPC('{{"jsonrpc": "2.0", "method":"Addons.SetAddonEnabled","params":{{"addonid":"{0}","enabled":true}}, "id": 1}}'.format(item['addonid']))

resolverID = 'script.module.israeliveresolver'
AddonID = "plugin.video.israelive"
Addon = xbmcaddon.Addon(AddonID)
if Addon.getSetting("unverifySSL") == "true":
	try:
		import ssl
		ssl._create_default_https_context = ssl._create_unverified_context
	except:
		pass
addonPath = xbmc.translatePath(Addon.getAddonInfo("path")).decode("utf-8")
libDir = os.path.join(addonPath, 'resources', 'lib')
sys.path.insert(0, libDir)
import common, myIPTV, checkUpdates, updateM3U

localizedString = Addon.getLocalizedString
AddonName = Addon.getAddonInfo("name")
icon = Addon.getAddonInfo('icon')
artDir = os.path.join(addonPath, 'resources', 'art')
__icon__ = os.path.join(artDir, "check2.png")
Example #53
0
#!/usr/bin/env python
import xbmc
import json
jsonSWAT_Sel_Vol = '{"jsonrpc": "2.0", "method": "Application.GetProperties", "params": {"properties": ["volume"]}, "id": 1}'
jsonSWAT_Notify = '{"jsonrpc":"2.0","method":"GUI.ShowNotification","params":{"title":"Volume Level","message":"%s","image":"info"},"id":1}'
result = json.loads(xbmc.executeJSONRPC(jsonSWAT_Sel_Vol))['result']['volume']
print result
xbmc.executeJSONRPC(jsonSWAT_Notify % result)


Example #54
0
def walk_Path(path, walked_files, progress):
    log("walk_Path(" + path + ")")

    if progress.iscanceled():
        return

    global dirCount
    global fileCount
    global filesFound

    count_text = language(30105).format(str(dirCount), str(fileCount))
    found_text = language(30107).format(str(filesFound))
    hacked_path = language(30108).format(
        unicode(path, 'utf-8', errors='replace'))
    progress.update(0, count_text, found_text, hacked_path)
    #time.sleep(5)

    # double slash the \ in the path
    path = path.replace("\\", "\\\\")
    rpcCall = "{\"jsonrpc\": \"2.0\", \"method\": \"Files.GetDirectory\", \"params\": {\"directory\": \"" + path + "\"}, \"id\": 1}"
    #log("rpcCall: " + rpcCall)
    jsonResult = xbmc.executeJSONRPC(rpcCall)
    #log("Files.GetDirectory results: " + jsonResult)

    # json.loads expects utf-8 but the conversion using unicode breaks stuff
    #jsonResult = unicode(jsonResult, 'utf-8', errors='ignore')
    #set_files = json.loads(jsonResult)

    set_files = []

    try:
        set_files = eval(jsonResult)
    except:
        log("Error Parsing GetDirectory() results : " + str(sys.exc_info()[0]))
        return

    if (len(set_files) == 0):
        return

    if (set_files.get('error') != None):
        xbmcgui.Dialog().ok(language(30109), language(30110),
                            str(set_files.get('error')))
        log("Error walking the source path: " + str(set_files.get('error')))
        return

    files = set_files['result']
    #['files']
    files = files.get('files')

    if (files == None):
        return

    dirCount += 1

    for file in files:
        if progress.iscanceled():
            return
        if file['filetype'] == "directory":
            walk_Path(file["file"], walked_files, progress)
        elif file['filetype'] == "file":
            fileCount += 1
            if file_has_extensions(file["file"],
                                   FILE_EXTENSIONS) and file_contains_forbiden(
                                       file["file"]) == False:
                filesFound += 1
                log("WALKER ADDING FILE : " + file["file"])
                file_name = file["file"]
                #XBMC urlencodes the filename if it's in a .rar
                if file_name.startswith('rar://'):
                    file_name = urllib.unquote(file_name)
                walked_files.append(file_name)
def getJSON(method, params):
    json_response = xbmc.executeJSONRPC(
        '{ "jsonrpc": "2.0", "method" : "%s", "params": %s, "id":1 }' %
        (method, try_encode(params)))
    jsonobject = json.loads(json_response.decode('utf-8', 'replace'))

    if (jsonobject.has_key('result')):
        jsonobject = jsonobject['result']
        if jsonobject.has_key('files'):
            return jsonobject['files']
        elif jsonobject.has_key('movies'):
            return jsonobject['movies']
        elif jsonobject.has_key('tvshows'):
            return jsonobject['tvshows']
        elif jsonobject.has_key('episodes'):
            return jsonobject['episodes']
        elif jsonobject.has_key('musicvideos'):
            return jsonobject['musicvideos']
        elif jsonobject.has_key('channels'):
            return jsonobject['channels']
        elif jsonobject.has_key('recordings'):
            return jsonobject['recordings']
        elif jsonobject.has_key('songs'):
            return jsonobject['songs']
        elif jsonobject.has_key('albums'):
            return jsonobject['albums']
        elif jsonobject.has_key('songdetails'):
            return jsonobject['songdetails']
        elif jsonobject.has_key('albumdetails'):
            return jsonobject['albumdetails']
        elif jsonobject.has_key('artistdetails'):
            return jsonobject['artistdetails']
        elif jsonobject.has_key('favourites'):
            if jsonobject['favourites']:
                return jsonobject['favourites']
            else:
                return {}
        elif jsonobject.has_key('tvshowdetails'):
            return jsonobject['tvshowdetails']
        elif jsonobject.has_key('episodedetails'):
            return jsonobject['episodedetails']
        elif jsonobject.has_key('moviedetails'):
            return jsonobject['moviedetails']
        elif jsonobject.has_key('setdetails'):
            return jsonobject['setdetails']
        elif jsonobject.has_key('sets'):
            return jsonobject['sets']
        elif jsonobject.has_key('video'):
            return jsonobject['video']
        elif jsonobject.has_key('artists'):
            return jsonobject['artists']
        elif jsonobject.has_key('sources'):
            if jsonobject['sources']:
                return jsonobject['sources']
            else:
                return {}
        elif jsonobject.has_key('addons'):
            return jsonobject['addons']
        else:
            logMsg(
                "getJson - invalid result for Method %s - params: %s - response: %s"
                % (method, params, str(jsonobject)))
            return {}
    else:
        logMsg(
            "getJson - empty result for Method %s - params: %s - response: %s"
            % (method, params, str(jsonobject)))
        return {}
Example #56
0
def get_library_files(type_of_scan):

    library_files = []
    media_files = []

    #Movies
    if type_of_scan == 1 or type_of_scan == 0:
        jsonResult = xbmc.executeJSONRPC(
            '{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": {"properties": ["file", "trailer"]}, "id": 1}'
        )
        log("VideoLibrary.GetMovies results: " + jsonResult)
        result = eval(jsonResult)  #json.loads(jsonResult)
        movies = result['result']

        movies = movies.get('movies')

        if (movies == None):
            if type_of_scan == 1:
                xbmcgui.Dialog().ok(language(30114), language(30115))
            movies = []

        for m in movies:
            media_files.append(m['file'])

            #try:
            #    trailer = m['trailer']
            #    if not trailer.startswith('http://'):
            #        media_files.append(clean_name(trailer))
            #except KeyError:
            #    pass

#TV Shows
    if type_of_scan == 2 or type_of_scan == 0:
        jsonResult = xbmc.executeJSONRPC(
            '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"properties": ["file"]}, "id": 1}'
        )
        log("VideoLibrary.GetEpisodes results: " + jsonResult)
        result = eval(jsonResult)  #json.loads(jsonResult)
        tvshows = result['result']
        tvshows = tvshows.get('episodes')

        if (tvshows == None):
            if type_of_scan == 2:
                xbmcgui.Dialog().ok(language(30116), language(30117))
            tvshows = []

        for t in tvshows:
            media_files.append(t['file'])

    # add files from trailers and sets
    for f in media_files:

        if f.startswith("videodb://"):
            rpcCall = "{\"jsonrpc\": \"2.0\", \"method\": \"Files.GetDirectory\", \"params\": {\"directory\": \"" + f + "\"}, \"id\": 1}"
            rpc_result = xbmc.executeJSONRPC(rpcCall)
            set_files = eval(rpc_result)  #json.loads(rpc_result)

            sub_files = []
            sub_trailers = []

            for item in set_files['result']['files']:
                sub_files.append(clean_name(item['file']))
                try:
                    trailer = item['trailer']
                    if not trailer.startswith('http://'):
                        library_files.append(clean_name(trailer))
                except KeyError:
                    pass

            library_files.extend(sub_files)
            library_files.extend(sub_trailers)
        elif f.startswith('stack://'):
            f = f.replace('stack://', '')
            f = f.replace(',,', '<ACTUALCOMMER>')
            parts = f.split(' , ')

            #parts = [ clean_name(f) for f in parts ]

            for b in parts:
                b = b.replace('<ACTUALCOMMER>', ',')
                b = clean_name(b)
                library_files.append(b)
        else:
            library_files.append(clean_name(f))

    # all paths to lower case
    #library_files = [ file_name.lower() for file_name in library_files ]

    # make a set from the paths
    library_files = set(library_files)

    return library_files
Example #57
0
 def doScan(self, movieDir):
     json_cmd = '{"jsonrpc":"2.0","method":"VideoLibrary.Scan", "params": {"directory":"%s/"},"id":1}' % movieDir.replace(
         '\\', '/')
     jsonRespond = xbmc.executeJSONRPC(json_cmd)
                xbmc_port) + "/jsonrpc"
            req = urllib2.Request(xbmc_json_rpc_url, data=jsontools.dump_json(payload), headers=headers)
            f = urllib2.urlopen(req)
            response = f.read()
            f.close()

            logger.info("get_data: response %s" % response)
            data = jsontools.load_json(response)
        except Exception, ex:
            template = "An exception of type {0} occured. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            logger.error("get_data: error en xbmc_json_rpc_url: %s" % message)
            data = ["error"]
    else:
        try:
            data = jsontools.load_json(xbmc.executeJSONRPC(jsontools.dump_json(payload)))
        except Exception, ex:
            template = "An exception of type {0} occured. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            logger.error("get_data:: error en xbmc.executeJSONRPC: {0}".
                        format(message))
            data = ["error"]

    logger.info("data: %s" % data)

    return data


def update(folder_content=config.get_setting("folder_tvshows"), folder=""):
    """
    Actualiza la libreria dependiendo del tipo de contenido y la ruta que se le pase.
    def addToMenu(self, path, label, icon, content, window, DATA):
        log(repr(window))
        log(repr(label))
        log(repr(path))
        log(repr(content))
        # Show a waiting dialog
        dialog = xbmcgui.DialogProgress()
        dialog.create(path, LANGUAGE(32063))

        # Work out if it's a single item, or a node
        isNode = False
        jsonPath = path.replace("\\", "\\\\")

        json_query = xbmc.executeJSONRPC(
            '{ "jsonrpc": "2.0", "id": 0, "method": "Files.GetDirectory", "params": { "properties": ["title", "file", "thumbnail"], "directory": "'
            + jsonPath + '", "media": "files" } }')
        json_query = unicode(json_query, 'utf-8', errors='ignore')
        json_response = simplejson.loads(json_query)

        labels = []
        paths = []
        nodePaths = []

        # Add all directories returned by the json query
        if 'result' in json_response and 'files' in json_response[
                'result'] and json_response['result']['files'] is not None:
            labels = [LANGUAGE(32058)]
            paths = ["ActivateWindow(%s,%s,return)" % (window, path)]
            for item in json_response['result']['files']:
                if item["filetype"] == "directory":
                    isNode = True
                    labels.append(item["label"])
                    nodePaths.append("ActivateWindow(%s,%s,return)" %
                                     (window, item["file"]))
        else:
            # Unable to add to get directory listings
            log("Invalid JSON response returned")
            log(repr(simplejson))
            # And tell the user it failed
            xbmcgui.Dialog().ok(ADDON.getAddonInfo("name"),
                                ADDON.getLocalizedString(32115))
            return

        # Add actions based on content
        if content == "albums":
            labels.append("Play")
            paths.append(
                "RunScript(script.skinshortcuts,type=launchalbum&album=%s)" %
                (self.extractID(path)))
        if window == 10002:
            labels.append("Slideshow")
            paths.append("SlideShow(%s,notrandom)" % (path))
            labels.append("Slideshow (random)")
            paths.append("SlideShow(%s,random)" % (path))
            labels.append("Slideshow (recursive)")
            paths.append("SlideShow(%s,recursive,notrandom)" % (path))
            labels.append("Slideshow (recursive, random)")
            paths.append("SlideShow(%s,recursive,random)" % (path))
        if path.endswith(".xsp"):
            labels.append("Play")
            paths.append("PlayMedia(%s)" % (path))

        allMenuItems = [xbmcgui.ListItem(label=LANGUAGE(32112))]  # Main menu
        allLabelIDs = ["mainmenu"]
        if isNode:
            allMenuItems.append(xbmcgui.ListItem(
                label=LANGUAGE(32113)))  # Main menu + autofill submenu
            allLabelIDs.append("mainmenu")

        # Get main menu items
        menuitems = DATA._get_shortcuts("mainmenu", processShortcuts=False)
        DATA._clear_labelID()
        for menuitem in menuitems.findall("shortcut"):
            # Get existing items labelID's
            allMenuItems.append(
                xbmcgui.ListItem(
                    label=DATA.local(menuitem.find("label").text)[2]))
            listitem.setArt({'icon': menuitem.find("icon").text})
            allLabelIDs.append(
                DATA._get_labelID(
                    DATA.local(menuitem.find("label").text)[3],
                    menuitem.find("action").text))

        # Close progress dialog
        dialog.close()

        # Show a select dialog so the user can pick where in the menu to add the item
        w = ShowDialog("DialogSelect.xml",
                       CWD,
                       listing=allMenuItems,
                       windowtitle=LANGUAGE(32114))
        w.doModal()
        selectedMenu = w.result
        del w

        if selectedMenu == -1 or selectedMenu is None:
            # User cancelled
            return

        action = paths[0]
        if isNode and selectedMenu == 1:
            # We're auto-filling submenu, so add all sub-nodes as possible default actions
            paths = paths + nodePaths

        if len(paths) > 1:
            # There are multiple actions to choose from
            selectedAction = xbmcgui.Dialog().select(LANGUAGE(32095), labels)

            if selectedAction == -1 or selectedAction is None:
                # User cancelled
                return True

            action = paths[selectedAction]

        # Add the shortcut to the menu the user has selected
        # Load existing main menu items
        menuitems = DATA._get_shortcuts(allLabelIDs[selectedMenu],
                                        processShortcuts=False)
        DATA._clear_labelID()

        # Generate a new labelID
        newLabelID = DATA._get_labelID(label, action)

        # Write the updated mainmenu.DATA.xml
        newelement = xmltree.SubElement(menuitems.getroot(), "shortcut")
        xmltree.SubElement(newelement, "label").text = label
        xmltree.SubElement(newelement,
                           "label2").text = "32024"  # Custom shortcut
        xmltree.SubElement(newelement, "icon").text = icon
        xmltree.SubElement(newelement, "thumb")
        xmltree.SubElement(newelement, "action").text = action

        DATA.indent(menuitems.getroot())
        path = xbmc.translatePath(
            os.path.join(
                "special://profile", "addon_data", ADDONID, "%s.DATA.xml" %
                (DATA.slugify(allLabelIDs[selectedMenu], True))))
        menuitems.write(path, encoding="UTF-8")

        if isNode and selectedMenu == 1:
            # We're also going to write a submenu
            menuitems = xmltree.ElementTree(xmltree.Element("shortcuts"))

            for item in json_response['result']['files']:
                if item["filetype"] == "directory":
                    newelement = xmltree.SubElement(menuitems.getroot(),
                                                    "shortcut")
                    xmltree.SubElement(newelement,
                                       "label").text = item["label"]
                    xmltree.SubElement(
                        newelement, "label2").text = "32024"  # Custom shortcut
                    xmltree.SubElement(newelement,
                                       "icon").text = item["thumbnail"]
                    xmltree.SubElement(newelement, "thumb")
                    xmltree.SubElement(
                        newelement,
                        "action").text = "ActivateWindow(%s,%s,return)" % (
                            window, item["file"])

            DATA.indent(menuitems.getroot())
            path = xbmc.translatePath(
                os.path.join("special://profile", "addon_data", ADDONID,
                             DATA.slugify(newLabelID, True) + ".DATA.xml"))
            menuitems.write(path, encoding="UTF-8")

        # Mark that the menu needs to be rebuilt
        xbmcgui.Window(10000).setProperty("skinshortcuts-reloadmainmenu",
                                          "True")

        # And tell the user it all worked
        xbmcgui.Dialog().ok(ADDON.getAddonInfo("name"), LANGUAGE(32090))
Example #60
0
def GetSimilarFromOwnLibrary(dbid):
    movies = []
    #    # if xbmcvfs.exists(filename) and time.time() - os.path.getmtime(filename) < 1:
    # return read_from_file(filename)
    if True:
        json_query = xbmc.executeJSONRPC(
            '{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovieDetails", "params": {"properties": ["genre","director","country","year","mpaa"], "movieid":%s }, "id": 1}'
            % dbid)
        json_query = unicode(json_query, 'utf-8', errors='ignore')
        json_response = simplejson.loads(json_query)
        if "moviedetails" in json_response['result']:
            id = json_response['result']['moviedetails']['movieid']
            genres = json_response['result']['moviedetails']['genre']
            year = int(json_response['result']['moviedetails']['year'])
            countries = json_response['result']['moviedetails']['country']
            directors = json_response['result']['moviedetails']['director']
            mpaa = json_response['result']['moviedetails']['mpaa']
            json_query = xbmc.executeJSONRPC(
                '{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": {"properties": ["genre","director","mpaa","country","year"], "sort": { "method": "random" } }, "id": 1}'
            )
            json_query = unicode(json_query, 'utf-8', errors='ignore')
            json_query = simplejson.loads(json_query)
            if "movies" in json_query['result']:
                quotalist = []
                for item in json_query['result']['movies']:
                    difference = int(item['year']) - year
                    hit = 0.0
                    miss = 0.0
                    quota = 0.0
                    for genre in genres:
                        if genre in item['genre']:
                            hit += 1.0
                        else:
                            miss += 1.0
                    miss += 0.00001
                    if hit > 0.0:
                        quota = float(hit) / float(hit + miss)
                    if genres[0] == item['genre'][0]:
                        quota += 0.3
                    if difference < 6 and difference > -6:
                        quota += 0.15
                    if difference < 3 and difference > -3:
                        quota += 0.15
                    if countries[0] == item['country'][0]:
                        quota += 0.4
                    if mpaa == item['mpaa']:
                        quota += 0.4
                    if directors[0] == item['director'][0]:
                        quota += 0.6
                    quotalist.append((quota, item["movieid"]))
                if True:
                    quotalist = sorted(quotalist,
                                       key=lambda quota: quota[0],
                                       reverse=True)
                    count = 1
                    for list_movie in quotalist:
                        if id <> list_movie[1]:
                            json_query = xbmc.executeJSONRPC(
                                '{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovieDetails", "params": {"properties": ["imdbnumber","genre","year", "art", "rating"], "movieid":%s }, "id": 1}'
                                % str(list_movie[1]))
                            json_query = unicode(json_query,
                                                 'utf-8',
                                                 errors='ignore')
                            json_response = simplejson.loads(json_query)
                            movie = json_response["result"]["moviedetails"]
                            newmovie = {
                                'Art(fanart)': movie["art"].get('fanart', ""),
                                'Art(poster)': movie["art"].get('poster', ""),
                                'Title': movie.get('label', ""),
                                'OriginalTitle':
                                movie.get('originaltitle', ""),
                                'ID': movie.get('imdbnumber', ""),
                                'Path': "",
                                'Play': "",
                                'DBID': "",
                                'Rating': str(round(float(movie['rating']),
                                                    1)),
                                'Premiered': movie.get('year', "")
                            }
                            movies.append(newmovie)
                            count += 1
                            if count > 20:
                                break

                return movies