def _build_playlist( movie_titles ): for movie in movie_titles: xbmc.log( "[script.cinema.experience] - Movie Title: %s" % movie, level=xbmc.LOGNOTICE ) xbmc.executehttpapi( "SetResponseFormat()" ) xbmc.executehttpapi( "SetResponseFormat(OpenField,)" ) # select Movie path from movieview Limit 1 sql = "SELECT movieview.idMovie, movieview.c00, movieview.strPath, movieview.strFileName, movieview.c08, movieview.c14 FROM movieview WHERE c00 LIKE '%s' LIMIT 1" % ( movie.replace( "'", "''", ), ) xbmc.log( "[script.cinema.experience] - SQL: %s" % ( sql, ), level=xbmc.LOGDEBUG ) # query database for info dummy is needed as there are two </field> formatters try: movie_id, movie_title, movie_path, movie_filename, thumb, genre, dummy = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus( sql ), ).split( "</field>" ) movie_id = int( movie_id ) except: traceback.print_exc() xbmc.log( "[script.cinema.experience] - Unable to match movie", level=xbmc.LOGERROR ) movie_id = 0 movie_title = movie_path = movie_filename = thumb = genre = dummy = "" movie_full_path = os.path.join(movie_path, movie_filename).replace("\\\\" , "\\") xbmc.log( "[script.cinema.experience] - Movie Title: %s" % movie_title, level=xbmc.LOGNOTICE ) xbmc.log( "[script.cinema.experience] - Movie Path: %s" % movie_path, level=xbmc.LOGNOTICE ) xbmc.log( "[script.cinema.experience] - Movie Filename: %s" % movie_filename, level=xbmc.LOGNOTICE ) xbmc.log( "[script.cinema.experience] - Full Movie Path: %s" % movie_full_path, level=xbmc.LOGNOTICE ) if not movie_id == 0: json_command = '{"jsonrpc": "2.0", "method": "Playlist.Add", "params": {"playlistid": 1, "item": {"movieid": %d} }, "id": 1}' % movie_id json_response = xbmc.executeJSONRPC(json_command) xbmc.log( "[script.cinema.experience] - JSONRPC Response: \n%s" % movie_title, level=xbmc.LOGDEBUG ) xbmc.sleep( 50 )
def _finalize_download( self, tmp_path ): try: # copy the trailer msg1 = xbmc.getLocalizedString( 30603 ) % ( os.path.split( self.filepath )[ 1 ], ) msg2 = xbmc.getLocalizedString( 30602 ) % ( os.path.split( self.filepath )[ 0 ], ) pDialog.update( -1 )#, msg1, msg2 ) # necessary for dialog to update xbmc.sleep( 50 ) xbmc.executehttpapi( "FileCopy(%s,%s)" % ( tmp_path, self.filepath.encode( "utf-8" ), ) ) """ # create conf file for better MPlayer playback only when trailer saved on xbox and not progressive if ( not self.filepath.startswith( "smb://" ) and not 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 = xbmc.getLocalizedString( 30603 ) % ( os.path.split( thumbpath )[ 1 ], ) ##pDialog.update( -1, msg1, msg2 ) # necessary for dialog to update ##xbmc.sleep( 50 ) ##xbmc.executehttpapi( "FileCopy(%s,%s)" % ( self.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
def installer(file="Z:\\savegame.zip"): if xbmcgui.Dialog().yesno("Install","Install Save Game?"): xbmc.executebuiltin('XBMC.Extract('+file+',' +"e:\\" + ')') xbmc.executehttpapi('FileDelete(e:\\gameid.ini)') # get rid of this file xbmcgui.Dialog().ok("Game Saves","Game Save Installed") else: xbmcgui.Dialog().ok("Game Saves","Game Save Not Installed")
def _finalize_download(self, tmp_path): try: # copy the trailer pDialog.update(-1) # only copy if the trailer doesn't exist if not os.path.isfile(self.filepath): xbmc.executehttpapi("FileCopy(%s,%s)" % (tmp_path, urllib.quote_plus(self.filepath.encode("utf-8")))) # fetch the thumbnail thumbpath = os.path.splitext(self.filepath)[0] + ".tbn" # necessary for dialog to update if not os.path.isfile(thumbpath): xbmc.executehttpapi( "FileCopy(%s,%s)" % (self.g_thumbnail, urllib.quote_plus(thumbpath.encode("utf-8"))) ) self.g_thumbnail = thumbpath # 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
def _finalize_download( self, tmp_path ): try: # copy the trailer msg1 = xbmc.getLocalizedString( 30503 ) % ( os.path.split( self.filepath )[ 1 ], ) msg2 = xbmc.getLocalizedString( 30502 ) % ( os.path.split( self.filepath )[ 0 ], ) pDialog.update( -1, msg1, msg2 ) # necessary for dialog to update xbmc.sleep( 50 ) xbmc.executehttpapi( "FileCopy(%s,%s)" % ( tmp_path, self.filepath.encode( "utf-8" ), ) ) # create conf file for better MPlayer playback only when trailer saved on xbox and not progressive if ( not self.filepath.startswith( "smb://" ) and not g_movie_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 = xbmc.getLocalizedString( 30503 ) % ( os.path.split( thumbpath )[ 1 ], ) pDialog.update( -1, msg1, msg2 ) # necessary for dialog to update xbmc.sleep( 50 ) xbmc.executehttpapi( "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
def get_cached_thumb( self, fpath ): # fixe me: xbmc not change/reload/refresh image if path is same fpath = xbmc.translatePath( fpath ) filename = md5.new( open( fpath ).read( 250 ) ).hexdigest() temp = "special://temp/moviesets/%s.tbn" % filename if not os.path.exists( temp ): xbmc.executehttpapi( "FileCopy(%s,%s)" % ( fpath, temp ) ).replace( "<li>", "" ) return ( fpath, temp )[ os.path.exists( temp ) ]
def save_lyrics( self, song ): try: # format lyrics with song info header song.lyrics = "[ti:%s]\n[ar:%s]\n[al:%s]\n[re:%s]\n[ve:%s]\n[we:%s]\n[offset:0]\n\n%s" % ( song.title, song.artist, song.album, self.Addon.getAddonInfo( "Name" ), self.Addon.getAddonInfo( "Version" ), song.website, song.lyrics, ) # use httpapi for smb:// paths if xbox if ( song.lyrics_path.startswith( "smb://" ) and os.environ.get( "OS", "n/a" ) == "xbox" ): # no way to create dirs for smb:// paths on xbox xbmc.executehttpapi( "FileUpload(%s,%s)" % ( song.lyrics_path, base64.standard_b64encode( BOM_UTF8 + song.lyrics.encode( "UTF-8", "replace" ) ), ) ) else: # if the path to the source file does not exist create it self._makedirs( os.path.dirname( song.lyrics_path ) ) # save lyrics open( song.lyrics_path, "w" ).write( BOM_UTF8 + song.lyrics.encode( "UTF-8", "replace" ) ) except Exception, e: # log error xbmc.log( "Lyrics::save_lyrics (%s)" % ( e, ), xbmc.LOGERROR ) # set error message song.message = self.Addon.getLocalizedString( 30852 ) % ( e, ) song.status = False
def showInfo(self, timer): if self.hideShortItems: position = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition() + self.infoOffset if self.channels[self.currentChannel - 1].getItemDuration(xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition()) < self.shortItemLength: return self.getControl(102).setVisible(True) self.showingInfo = True self.setShowInfo() if self.infoTimer.isAlive(): self.infoTimer.cancel() self.infoTimer = threading.Timer(timer, self.hideInfo) self.infoTimer.name = "InfoTimer" if xbmc.getCondVisibility('Player.ShowInfo'): if USING_FRODO: json_query = '{"jsonrpc": "2.0", "method": "Input.Info", "id": 1}' self.ignoreInfoAction = True self.channelList.sendJSON(json_query); else: xbmc.executehttpapi("SendKey(0xF049)") self.ignoreInfoAction = True self.infoTimer.start()
def saving(self): listIdGenres = [] listStrGenres = [] for e in self.genres: listIdGenres.append(e[0]) listStrGenres.append(e[1]) if self.mode == "movie": sql_data = 'DELETE FROM genrelinkmovie WHERE idMovie=\"%s\"' % (self.idfilm) else: sql_data = 'DELETE FROM genrelinktvshow WHERE idShow=\"%s\"' % (self.idfilm) xml_data = xbmc.executehttpapi( "ExecVideoDatabase(%s)" % urllib.quote_plus( sql_data ), ) lg = [] for g in self.movieGenres: lg.append(listStrGenres[listIdGenres.index(g)]) if self.mode == "movie": sql_data = 'INSERT INTO genrelinkmovie ("idGenre","idMovie") VALUES (%s,%s)' % (g, self.idfilm) else: sql_data = 'INSERT INTO genrelinktvshow ("idGenre","idShow") VALUES (%s,%s)' % (g, self.idfilm) xml_data = xbmc.executehttpapi( "ExecVideoDatabase(%s)" % urllib.quote_plus( sql_data ), ) self.strgenre = " / ".join(lg) if self.mode == "movie": sql_data = 'UPDATE movie SET c14=\"%s\" WHERE idMovie=%s' % (self.strgenre, self.idfilm) else: sql_data = 'UPDATE tvshow SET c08=\"%s\" WHERE idShow=%s' % (self.strgenre, self.idfilm) xml_data = xbmc.executehttpapi( "ExecVideoDatabase(%s)" % urllib.quote_plus( sql_data ), ) self.ex = 1 self.close()
def update_item_and_file_id(self, old_idItem, new_idItem, old_idFile, new_idFile): sql_dict = {'newItemId': new_idItem, 'newFileId': new_idFile, 'oldItemId': old_idItem, 'oldFileId': old_idFile} if self.library == MOVIES: update_sql = ["update movie set idMovie=%(newItemId)d, idFile=%(newFileId)d where idMovie=%(oldItemId)d;", "update actorlinkmovie set idMovie=%(newItemId)d where idMovie=%(oldItemId)d;", "update countrylinkmovie set idMovie=%(newItemId)d where idMovie=%(oldItemId)d;", "update directorlinkmovie set idMovie=%(newItemId)d where idMovie=%(oldItemId)d;", "update genrelinkmovie set idMovie=%(newItemId)d where idMovie=%(oldItemId)d;", "update movielinktvshow set idMovie=%(newItemId)d where idMovie=%(oldItemId)d;", "update setlinkmovie set idMovie=%(newItemId)d where idMovie=%(oldItemId)d;", "update studiolinkmovie set idMovie=%(newItemId)d where idMovie=%(oldItemId)d;", "update writerlinkmovie set idMovie=%(newItemId)d where idMovie=%(oldItemId)d;"] elif self.library == TV_EPISODES: update_sql = ["update episode set idEpisode=%(newItemId)d, idFile=%(newFileId)d where idEpisode=%(oldItemId)d;", "update actorlinkepisode set idEpisode=%(newItemId)d where idEpisode=%(oldItemId)d;", "update directorlinkepisode set idEpisode=%(newItemId)d where idEpisode=%(oldItemId)d;", "update tvshowlinkepisode set idEpisode=%(newItemId)d where idEpisode=%(oldItemId)d;", "update writerlinkepisode set idEpisode=%(newItemId)d where idEpisode=%(oldItemId)d;"] elif self.library == MUSIC_VIDEOS: update_sql = ["update musicvideo set idMVideo=%(newItemId)d, idFile=%(newFileId)d where idMVideo=%(oldItemId)d;", "update actorlinkmusicvideo set idMVideo=%(newItemId)d where idMVideo=%(oldItemId)d;", "update directorlinkmusicvideo set idMVideo=%(newItemId)d where idMVideo=%(oldItemId)d;", "update genrelinkmusicvideo set idMVideo=%(newItemId)d where idMVideo=%(oldItemId)d;", "update studiolinkmusicvideo set idMVideo=%(newItemId)d where idMVideo=%(oldItemId)d;"] if self.library in (MOVIES, TV_EPISODES, MUSIC_VIDEOS): update_sql += ["update files set idFile=%(newFileId)d where idFile=%(oldFileId)d;", "update bookmark set idFile=%(newFileId)d where idFile=%(oldFileId)d;", "update stacktimes set idFile=%(newFileId)d where idFile=%(oldFileId)d;", "update streamdetails set idFile=%(newFileId)d where idFile=%(oldFileId)d;"] for q in update_sql: xbmc.executehttpapi( "ExecVideoDatabase(%s)" % quote_plus( q % sql_dict ), )
def showInfo(self, timer): if self.hideShortItems: position = xbmc.PlayList( xbmc.PLAYLIST_MUSIC).getposition() + self.infoOffset if self.channels[self.currentChannel - 1].getItemDuration( xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition() ) < self.shortItemLength: return self.getControl(102).setVisible(True) self.showingInfo = True self.setShowInfo() if self.infoTimer.isAlive(): self.infoTimer.cancel() self.infoTimer = threading.Timer(timer, self.hideInfo) self.infoTimer.name = "InfoTimer" if xbmc.getCondVisibility('Player.ShowInfo'): xbmc.executehttpapi("SendKey(0xF049)") self.ignoreInfoAction = True self.infoTimer.start()
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 _set_thumb(self, launcherName, romname, url): self.url = url # download thumb urllib.urlretrieve(url, None, self._report_hook) # copy it into thumbs path path = self.settings["thumbs_path"] filepath = os.path.join(path, os.path.basename(url)) pDialog.update(100, __language__(30032)) xbmc.sleep(50) print filepath xbmc.executehttpapi("FileCopy(%s,%s)" % ( url, filepath, )) launcher = self.launchers[launcherName] if (romname): rom = launcher["roms"][romname] rom["thumb"] = filepath else: launcher["thumb"] = filepath self._save_launchers() # returning back to the previous window if (romname): xbmc.executebuiltin("ReplaceWindow(Programs,%s?%s)" % (self._path, launcherName)) else: xbmc.executebuiltin("ReplaceWindow(Programs,%s)" % (self._path))
def _run_rom(self, launcherName, romName): if (self.launchers.has_key(launcherName)): launcher = self.launchers[launcherName] if (launcher["roms"].has_key(romName)): rom = self.launchers[launcherName]["roms"][romName] if (os.environ.get( "OS", "xbox" ) == "xbox"): f=open(SHORTCUT_FILE, "wb") f.write("<shortcut>\n") f.write(" <path>" + launcher["application"] + "</path>\n") f.write(" <custom>\n") f.write(" <game>" + rom["filename"] + "</game>\n") f.write(" </custom>\n") f.write("</shortcut>\n") f.close() xbmc.executebuiltin('XBMC.Runxbe(' + SHORTCUT_FILE + ')') else: if (sys.platform == 'win32'): if (launcher["wait"] == "true"): cmd = "System.ExecWait" else: cmd = "System.Exec" xbmc.executebuiltin("%s(\\\"%s\\\" %s \\\"%s\\\")" % (cmd, launcher["application"], launcher["args"], rom["filename"])) elif (sys.platform.startswith('linux')): #this minimizes xbmc some apps seems to need it xbmc.executehttpapi("Action(199)") os.system("\"%s\" %s \"%s\"" % (launcher["application"], launcher["args"], rom["filename"])) #this brings xbmc back xbmc.executehttpapi("Action(199)") elif (sys.platform.startswith('darwin')): os.system("\"%s\" %s \"%s\"" % (launcher["application"], launcher["args"], rom["filename"])) else: pass;
def _set_thumb(self, launcherName, romname, url): self.url = url # download thumb urllib.urlretrieve( url, None, self._report_hook ) # copy it into thumbs path path = self.settings[ "thumbs_path" ] filepath = os.path.join(path, os.path.basename(url)) pDialog.update( 100, __language__( 30032 )) xbmc.sleep( 50 ) xbmc.executehttpapi( "FileCopy(%s,%s)" % (url, filepath, ) ) launcher = self.launchers[launcherName] if (romname): rom = launcher["roms"][romname] rom["thumb"] = filepath else: launcher["thumb"] = filepath self.storage_backend._save_launchers(self.launchers) # returning back to the previous window if (romname): xbmc.executebuiltin("ReplaceWindow(Programs,%s?%s)" % (self._path, launcherName)) else: xbmc.executebuiltin("ReplaceWindow(Programs,%s)" % (self._path))
def _toogle_fullscreen(): try: # Dharma / Eden compatible xbmc.executehttpapi("Action(199)") except: # Frodo & + compatible xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Input.ExecuteAction","params":{"action":"togglefullscreen"},"id":"1"}')
def SetMusicBrainzID(xbmc_artist_id, musicbrainz_id): # OR song.idArtist='SELECT' <- total workaround to force execution of sql query # xbmc allows only queries with SELECT phrase update_query = "UPDATE song SET strMusicBrainzArtistID='%s' WHERE idArtist=%i OR strMusicBrainzArtistID='SELECT'" % ( musicbrainz_id, xbmc_artist_id) xbmc.executehttpapi("QueryMusicDatabase(%s)" % urllib.quote_plus(update_query))
def UnFullScreenXBMC(): #this minimizes xbmc some apps seems to need it try: xbmc.executehttpapi("Action(199)") except: xbmc.executeJSONRPC( '{"jsonrpc":"2.0","method":"Input.ExecuteAction","params":{"action":"togglefullscreen"},"id":"1"}' )
def showChannelLabel(self, channel): self.log('showChannelLabel ' + str(channel)) if self.channelLabelTimer.isAlive(): self.channelLabelTimer.cancel() self.channelLabelTimer = threading.Timer(5.0, self.hideChannelLabel) tmp = self.inputChannel self.hideChannelLabel() self.inputChannel = tmp curlabel = 0 if channel > 99: self.channelLabel[curlabel].setImage(IMAGES_LOC + 'label_' + str(channel // 100) + '.png') self.channelLabel[curlabel].setVisible(True) curlabel += 1 if channel > 9: self.channelLabel[curlabel].setImage(IMAGES_LOC + 'label_' + str((channel % 100) // 10) + '.png') self.channelLabel[curlabel].setVisible(True) curlabel += 1 self.channelLabel[curlabel].setImage(IMAGES_LOC + 'label_' + str(channel % 10) + '.png') self.channelLabel[curlabel].setVisible(True) ##ADDED BY SRANSHAFT: USED TO SHOW NEW INFO WINDOW WHEN CHANGING CHANNELS if self.inputChannel == -1 and self.infoOnChange == True: self.infoOffset = 0 self.showInfo(5.0) if self.showChannelBug == True: try: self.getControl(103).setImage( self.channelLogos + ascii(self.channels[self.currentChannel - 1].name) + '.png') except: pass else: try: self.getControl(103).setImage('') except: pass ## if xbmc.getCondVisibility('Player.ShowInfo'): xbmc.executehttpapi("SendKey(0xF049)") self.ignoreInfoAction = True self.channelLabelTimer.name = "ChannelLabel" self.channelLabelTimer.start() self.startNotificationTimer(10.0) self.log('showChannelLabel return')
def get_cached_thumb(self, fpath): # fixe me: xbmc not change/reload/refresh image if path is same fpath = translatePath(fpath) filename = md5.new(open(fpath).read(250)).hexdigest() temp = "special://temp/moviesets/%s.tbn" % filename if not os.path.exists(temp): executehttpapi("FileCopy(%s,%s)" % (fpath, temp)) #.replace( "<li>", "" ) return (fpath, temp)[os.path.exists(temp)]
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 fetch_similarTracks( self, currentlyPlayingTitle, currentlyPlayingArtist ): apiMethod = "&method=track.getsimilar&limit=" + str(self.limitlastfmresult) # The url in which to use Base_URL = self.apiPath + apiMethod + "&artist=" + urllib.quote_plus(currentlyPlayingArtist) + "&track=" + urllib.quote_plus(currentlyPlayingTitle) #print Base_URL WebSock = urllib.urlopen(Base_URL) # Opens a 'Socket' to URL WebHTML = WebSock.read() # Reads Contents of URL and saves to Variable WebSock.close() # Closes connection to url xbmc.executehttpapi("setresponseformat(openRecordSet;<recordset>;closeRecordSet;</recordset>;openRecord;<record>;closeRecord;</record>;openField;<field>;closeField;</field>)"); #print WebHTML similarTracks = re.findall("<track>.+?<name>(.+?)</name>.+?<match>(.+?)</match>.+?<artist>.+?<name>(.+?)</name>.+?</artist>.+?</track>", WebHTML, re.DOTALL ) random.shuffle(similarTracks) foundArtists = [] countTracks = len(similarTracks) print "Count: " + str(countTracks) for similarTrackName, matchValue, similarArtistName in similarTracks: #print "Looking for: " + similarTrackName + " - " + similarArtistName + " - " + matchValue similarTrackName = similarTrackName.replace("+"," ").replace("("," ").replace(")"," ").replace(""","'").replace("'","''").replace("&","and") similarArtistName = similarArtistName.replace("+"," ").replace("("," ").replace(")"," ").replace(""","'").replace("'","''").replace("&","and") sql_music = "select strTitle, strArtist, strAlbum, strPath, strFileName, strThumb, iDuration from songview where strTitle LIKE '%%" + similarTrackName + "%%' and strArtist LIKE '%%" + similarArtistName + "%%' order by random() limit 1" music_xml = xbmc.executehttpapi( "QueryMusicDatabase(%s)" % quote_plus( sql_music ), ) # separate the records records = re.findall( "<record>(.+?)</record>", music_xml, re.DOTALL ) for count, item in enumerate( records ): # separate individual fields fields = re.findall( "<field>(.*?)</field>", item, re.DOTALL ) artist = fields[1] trackTitle = fields[0] album = fields[2] trackPath = fields[3] + fields[4] thumb = fields[5] duration = int(fields[6]) print "Found: " + trackTitle + " by: " + artist if (self.allowtrackrepeat == "true" or (self.allowtrackrepeat == "false" and trackPath not in self.addedTracks)): if (self.preferdifferentartist == "false" or (self.preferdifferentartist == "true" and eval(matchValue) < 0.2 and similarArtistName not in foundArtists)): listitem = self.getListItem(trackTitle,artist,album,thumb,duration) xbmc.PlayList(0).add(url=trackPath, listitem=listitem) self.addedTracks += [trackPath] xbmc.executebuiltin("Container.Refresh") self.countFoundTracks += 1 if (similarArtistName not in foundArtists): foundArtists += [similarArtistName] if (self.countFoundTracks >= self.numberoftrackstoadd): break if (self.countFoundTracks == 0): time.sleep(3) #self.firstRun = 1 print "None found" xbmc.executebuiltin("Notification(" + self.SCRIPT_NAME+",No similar tracks were found)") return False xbmc.executebuiltin('SetCurrentPlaylist(0)')
def _get_queued_video_info( feature = 0 ): xbmc.log( "%s - _get_queued_video_info() Started" % log_message, level=xbmc.LOGDEBUG ) equivalent_mpaa = "NR" try: # get movie name movie_title = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )[ feature ].getdescription() # this is used to skip trailer for current movie selection movie = os.path.splitext( os.path.basename( xbmc.PlayList( xbmc.PLAYLIST_VIDEO )[ feature ].getfilename() ) )[ 0 ] # format our records start and end xbmc.executehttpapi( "SetResponseFormat()" ) xbmc.executehttpapi( "SetResponseFormat(OpenField,)" ) # TODO: verify the first is the best audio # setup the sql, we limit to 1 record as there can be multiple entries in streamdetails sql = "SELECT movie.c12, movie.c14, streamdetails.strAudioCodec FROM movie, streamdetails WHERE movie.idFile=streamdetails.idFile AND streamdetails.iStreamType=1 AND c00='%s' LIMIT 1" % ( movie_title.replace( "'", "''", ), ) xbmc.log( "%s - SQL: %s" % ( log_message, sql, ), level=xbmc.LOGDEBUG ) # query database for info dummy is needed as there are two </field> formatters mpaa, genre, audio, dummy = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus( sql ), ).split( "</field>" ) # TODO: add a check and new sql for videos queued from files mode, or try an nfo # calculate rating if mpaa == "": mpaa = "NR" elif mpaa.startswith("Rated"): mpaa = mpaa.split( " " )[ 1 - ( len( mpaa.split( " " ) ) == 1 ) ] mpaa = ( mpaa, "NR", )[ mpaa not in ( "G", "PG", "PG-13", "R", "NC-17", "Unrated", ) ] elif mpaa.startswith("UK"): mpaa = mpaa.split( ":" )[ 1 - ( len( mpaa.split( ":" ) ) == 1 ) ] mpaa = ( mpaa, "NR", )[ mpaa not in ( "12", "12A", "PG", "15", "18", "R18", "MA", "U", ) ] else: mpaa = ( mpaa, "NR", )[ mpaa not in ( "12", "12A", "PG", "15", "18", "R18", "MA", "U", ) ] if mpaa not in ( "G", "PG", "PG-13", "R", "NC-17", "Unrated", "NR" ): if mpaa in ("12", "12A",): equivalent_mpaa = "PG-13" elif mpaa == "15": equivalent_mpaa = "R" elif mpaa == "U": equivalent_mpaa = "G" elif mpaa in ("18", "R18", "MA",): equivalent_mpaa = "NC-17" else: equivalent_mpaa = mpaa except: traceback.print_exc() movie_title = mpaa = audio = genre = movie = equivalent_mpaa = "" # spew queued video info to log xbmc.log( "%s - Queued Movie Information" % log_message, level=xbmc.LOGDEBUG ) xbmc.log( "%s %s" % ( log_message,log_sep ), level=xbmc.LOGDEBUG ) xbmc.log( "%s - Title: %s" % ( log_message, movie_title, ), level=xbmc.LOGDEBUG ) xbmc.log( "%s - Path: %s" % ( log_message, movie, ), level=xbmc.LOGDEBUG ) xbmc.log( "%s - Genre: %s" % ( log_message, genre, ), level=xbmc.LOGDEBUG ) xbmc.log( "%s - MPAA: %s" % ( log_message, mpaa, ), level=xbmc.LOGDEBUG ) xbmc.log( "%s - Audio: %s" % ( log_message, audio, ), level=xbmc.LOGDEBUG ) if _S_( "audio_videos_folder" ): xbmc.log( "%s - Folder: %s" % ( log_message, ( xbmc.translatePath( _S_( "audio_videos_folder" ) ) + { "dca": "DTS", "ac3": "Dolby", "dtsma": "DTSHD-MA", "dtshd_ma": "DTSHD-MA", "a_truehd": "Dolby TrueHD", "truehd": "Dolby TrueHD" }.get( audio, "Other" ) + xbmc.translatePath( _S_( "audio_videos_folder" ) )[ -1 ], ) ), level=xbmc.LOGDEBUG ) xbmc.log( "%s %s" % ( log_message, log_sep ), level=xbmc.LOGDEBUG ) # return results return mpaa, audio, genre, movie, equivalent_mpaa
def GetMusicBrainzId(artist): xbmc.executehttpapi( "SetResponseFormat()" ) xbmc.executehttpapi( "SetResponseFormat(OpenRecord,%s)" % ( "<record>", ) ) xbmc.executehttpapi( "SetResponseFormat(CloseRecord,%s)" % ( "</record>", ) ) xbmc.executehttpapi('') sqlQuery = "SELECT DISTINCT artist.strArtist, song.idArtist, song.strMusicBrainzArtistID FROM song JOIN artist ON artist.idArtist=song.idArtist WHERE artist.strArtist='%s'" %artist results = xbmc.executehttpapi( "QueryMusicDatabase(%s)" % urllib.quote_plus( sqlQuery ) ) records = re.findall( "<record>(.+?)</record>", results, re.DOTALL ) if len(records) == 1: fields = re.findall( "<field>(.+?)</field>", records[0], re.DOTALL) if len(fields) == 3: if fields[2] == 'not_there': log('We searched MusicBrainz before and not found - let\'s try again') return GetMusicBrainzIdFromNet(artist, int(fields[1])) else: log('MusicBrainz id is already stored in XBMC database') return fields[2] else: log('We didn\'t search MusicBrainz for this artist yet - let\'s try') return GetMusicBrainzIdFromNet(artist, int(fields[1])) return None
def _get_queued_video_info(self): try: xbmc.log("_get_queued_video_info()", xbmc.LOGNOTICE) # clear then queue the currently selected video xbmc.executebuiltin("Playlist.Clear") xbmc.executebuiltin("Action(Queue,%d)" % (xbmcgui.getCurrentWindowId() - 10000,)) xbmc.log("Action(Queue,%d)" % (xbmcgui.getCurrentWindowId() - 10000,), xbmc.LOGNOTICE) # we need to sleep so the video gets queued properly xbmc.sleep(300) # create a video playlist self.playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) # get movie name movie_title = self.playlist[0].getdescription() # this is used to skip trailer for current movie selection movie = os.path.splitext(os.path.basename(self.playlist[0].getfilename()))[0] # format our records start and end xbmc.executehttpapi("SetResponseFormat()") xbmc.executehttpapi("SetResponseFormat(OpenField,)") # TODO: verify the first is the best audio # setup the sql, we limit to 1 record as there can be multiple entries in streamdetails sql = ( "SELECT movie.c12, movie.c14, streamdetails.strAudioCodec FROM movie, streamdetails WHERE movie.idFile=streamdetails.idFile AND streamdetails.iStreamType=1 AND c00='%s' LIMIT 1" % (movie_title.replace("'", "''"),) ) xbmc.log("SQL: %s" % (sql,), xbmc.LOGNOTICE) # query database for info dummy is needed as there are two </field> formatters mpaa, genre, audio, dummy = xbmc.executehttpapi("QueryVideoDatabase(%s)" % quote_plus(sql)).split( "</field>" ) # TODO: add a check and new sql for videos queued from files mode, or try an nfo # calculate rating mpaa = mpaa.split(" ")[1 - (len(mpaa.split(" ")) == 1)] mpaa = (mpaa, "NR")[mpaa not in ("G", "PG", "PG-13", "R", "NC-17", "Unrated")] except: movie_title = mpaa = audio = genre = movie = "" # spew queued video info to log xbmc.log("-" * 70, xbmc.LOGNOTICE) xbmc.log("Title: %s" % (movie_title,), xbmc.LOGNOTICE) xbmc.log("Path: %s" % (movie,), xbmc.LOGNOTICE) xbmc.log("Genre: %s" % (genre,), xbmc.LOGNOTICE) xbmc.log("MPAA: %s" % (mpaa,), xbmc.LOGNOTICE) xbmc.log("Audio: %s" % (audio,), xbmc.LOGNOTICE) if _S_("audio_videos_folder"): xbmc.log( "- Folder: %s" % ( xbmc.translatePath(_S_("audio_videos_folder")) + {"dca": "DTS", "ac3": "Dolby"}.get(audio, "Other") + xbmc.translatePath(_S_("audio_videos_folder"))[-1], ), xbmc.LOGNOTICE, ) xbmc.log("-" * 70, xbmc.LOGNOTICE) # return results return mpaa, audio, genre, movie
def GetMusicBrainzId(artist): xbmc.executehttpapi("SetResponseFormat()") xbmc.executehttpapi("SetResponseFormat(OpenRecord,%s)" % ("<record>", )) xbmc.executehttpapi("SetResponseFormat(CloseRecord,%s)" % ("</record>", )) xbmc.executehttpapi('') sqlQuery = "SELECT DISTINCT artist.strArtist, song.idArtist, song.strMusicBrainzArtistID FROM song JOIN artist ON artist.idArtist=song.idArtist WHERE artist.strArtist='%s'" % artist results = xbmc.executehttpapi("QueryMusicDatabase(%s)" % urllib.quote_plus(sqlQuery)) records = re.findall("<record>(.+?)</record>", results, re.DOTALL) if len(records) == 1: fields = re.findall("<field>(.+?)</field>", records[0], re.DOTALL) if len(fields) == 3: if fields[2] == 'not_there': log('We searched MusicBrainz before and not found - let\'s try again' ) return GetMusicBrainzIdFromNet(artist, int(fields[1])) else: log('MusicBrainz id is already stored in XBMC database') return fields[2] else: log('We didn\'t search MusicBrainz for this artist yet - let\'s try' ) return GetMusicBrainzIdFromNet(artist, int(fields[1])) return None
def showChannelLabel(self, channel): self.log('showChannelLabel ' + str(channel)) if self.channelLabelTimer.isAlive(): self.channelLabelTimer.cancel() self.channelLabelTimer = threading.Timer(5.0, self.hideChannelLabel) tmp = self.inputChannel self.hideChannelLabel() self.inputChannel = tmp curlabel = 0 if channel > 99: self.channelLabel[curlabel].setImage(IMAGES_LOC + 'label_' + str(channel // 100) + '.png') self.channelLabel[curlabel].setVisible(True) curlabel += 1 if channel > 9: self.channelLabel[curlabel].setImage(IMAGES_LOC + 'label_' + str((channel % 100) // 10) + '.png') self.channelLabel[curlabel].setVisible(True) curlabel += 1 self.channelLabel[curlabel].setImage(IMAGES_LOC + 'label_' + str(channel % 10) + '.png') self.channelLabel[curlabel].setVisible(True) ##ADDED BY SRANSHAFT: USED TO SHOW NEW INFO WINDOW WHEN CHANGING CHANNELS if self.inputChannel == -1 and self.infoOnChange == True: self.infoOffset = 0 self.showInfo(5.0) if self.showChannelBug == True: try: self.getControl(103).setImage(self.channelLogos + ascii(self.channels[self.currentChannel - 1].name) + '.png') except: pass else: try: self.getControl(103).setImage('') except: pass ## if xbmc.getCondVisibility('Player.ShowInfo'): if USING_FRODO: json_query = '{"jsonrpc": "2.0", "method": "Input.Info", "id": 1}' self.ignoreInfoAction = True self.channelList.sendJSON(json_query); else: xbmc.executehttpapi("SendKey(0xF049)") self.ignoreInfoAction = True self.channelLabelTimer.name = "ChannelLabel" self.channelLabelTimer.start() self.startNotificationTimer(10.0) self.log('showChannelLabel return')
def _play_video_playlist( self ): # set this to -1 as True and False are taken self.exiting = -1 # cancel timers self._cancel_timers() # turn screensaver back on xbmc.executehttpapi( "SetGUISetting(3,screensaver.mode,%s)" % self.screensaver ) # we play the video playlist here so the screen does not flash xbmc.Player().play( self.playlist ) # close trivia slide show self.close()
def __init__( self ): # parse argv for any preferences self._parse_argv() # clear properties self._clear_properties() # format our records start and end xbmc.executehttpapi( "SetResponseFormat(OpenRecord,%s)" % ( "<record>", ) ) xbmc.executehttpapi( "SetResponseFormat(CloseRecord,%s)" % ( "</record>", ) ) # fetch media info self._fetch_movie_info() self._fetch_tvshow_info()
def onAction(self,action): try: action = int(action) except: action = action.getId() if action == ACTION_SHOW_INFO: if xbmc.getCondVisibility('Player.ShowInfo'): xbmc.executehttpapi("SendKey(0xF049)") elif action != ACTION_MOVE_UP and action != ACTION_MOVE_DOWN: self.close()
def _get_movie_details( movie_title="", thumbnail="", movie_full_path="" ): xbmc.log( "[script.cinema.experience] - [ce_playlist.py] - _get_movie_details started", level=xbmc.LOGNOTICE ) # format our records start and end xbmc.executehttpapi( "SetResponseFormat()" ) xbmc.executehttpapi( "SetResponseFormat(OpenField,)" ) # retrive plot(c01), plotoutline(c02), runtime(c11), mpaa(c12), year(c07), studio(c18), genre(c14), writer(c06), director(c15), tagline(c03), votes(c04), imdbcode(c09), rating(c05), top250(c13) from database sql_query = "SELECT c01, c02, c11, c12, c07, c18, c14, c06, c15, c03, c04, c09, c05, c13 FROM movieview WHERE c00='%s' LIMIT 1" % ( movie_title.replace( "'", "''", ), ) # the dummy string is to catch the extra </field> plot, plotoutline, runtime, mpaa, year, studio, genre, writer, director, tagline, votes, imdbcode, rating, top250, dummy = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus( sql_query ), ).split( "</field>" ) return plot, plotoutline, runtime, mpaa, year, studio, genre, writer, director, tagline, votes, imdbcode, rating, votes, top250
def auto_refresh( before, mode ): xbmc.log( "[ script.cinema.experience ] - auto_refresh( %s, %s )" % ( before, mode ), level=xbmc.LOGNOTICE ) # turn off autorefresh if _S_( "autorefresh" ) == "true" and before == "True" and mode=="disable": xbmc.executehttpapi( "SetGUISetting(1; videoplayer.adjustrefreshrate; False)" ) # turn on autorefresh elif _S_( "autorefresh" ) == "true" and before == "True" and mode=="enable": xbmc.executehttpapi( "SetGUISetting(1; videoplayer.adjustrefreshrate; True)" ) status = True status = xbmc.executehttpapi( "GetGuiSetting(1; videoplayer.adjustrefreshrate)" ).strip("<li>") xbmc.log( "[ script.cinema.experience ] - Autorefresh Status: %s" % status, level=xbmc.LOGNOTICE )
def onAction(self, action): try: action = int(action) except: action = action.getId() if action == ACTION_SHOW_INFO: if xbmc.getCondVisibility('Player.ShowInfo'): xbmc.executehttpapi("SendKey(0xF049)") elif action != ACTION_MOVE_UP and action != ACTION_MOVE_DOWN: self.close()
def _fetch_music_info( self ): # Current Working Directory # sql statement if ( self.ALBUMS ): sql_music = "select * from albumview order by RANDOM() limit %d" % ( self.LIMIT, ) # query the database for recently added albums music_xml = xbmc.executehttpapi( "QueryMusicDatabase(%s)" % quote_plus( sql_music ), ) # separate the records items = re.findall( "<record>(.+?)</record>", music_xml, re.DOTALL ) # enumerate thru our records and set our properties for count, item in enumerate( items ): # separate individual fields fields = re.findall( "<field>(.*?)</field>", item, re.DOTALL ) # set properties self.WINDOW.setProperty( "RandomSong.%d.Title" % ( count + 1, ), fields[ 1 ] ) self.WINDOW.setProperty( "RandomSong.%d.Year" % ( count + 1, ), fields[ 8 ] ) self.WINDOW.setProperty( "RandomSong.%d.Artist" % ( count + 1, ), fields[ 6 ] ) self.WINDOW.setProperty( "RandomSong.%d.Rating" % ( count + 1, ), fields[ 18 ] ) # Album Path (ID) path = 'XBMC.RunScript(script.randomitems,albumid=' + fields[ 0 ] + ')' self.WINDOW.setProperty( "RandomSong.%d.Path" % ( count + 1, ), path ) # get cache name of path to use for fanart cache_name = xbmc.getCacheThumbName( fields[ 6 ] ) self.WINDOW.setProperty( "RandomSong.%d.Fanart" % ( count + 1, ), "special://profile/Thumbnails/Music/%s/%s" % ( "Fanart", cache_name, ) ) self.WINDOW.setProperty( "RandomSong.%d.Thumb" % ( count + 1, ), fields[ 9 ] ) else: # set our unplayed query unplayed = ( "", "where lastplayed is null ", )[ self.UNPLAYED ] # sql statement sql_music = "select * from songview %sorder by RANDOM() limit %d" % ( unplayed, self.LIMIT, ) # query the database music_xml = xbmc.executehttpapi( "QueryMusicDatabase(%s)" % quote_plus( sql_music ), ) # separate the records items = re.findall( "<record>(.+?)</record>", music_xml, re.DOTALL ) # enumerate thru our records and set our properties for count, item in enumerate( items ): # separate individual fields fields = re.findall( "<field>(.*?)</field>", item, re.DOTALL ) # set properties self.WINDOW.setProperty( "RandomSong.%d.Title" % ( count + 1, ), fields[ 3 ] ) self.WINDOW.setProperty( "RandomSong.%d.Year" % ( count + 1, ), fields[ 6 ] ) self.WINDOW.setProperty( "RandomSong.%d.Artist" % ( count + 1, ), fields[ 24 ] ) self.WINDOW.setProperty( "RandomSong.%d.Album" % ( count + 1, ), fields[ 21 ] ) self.WINDOW.setProperty( "RandomSong.%d.Rating" % ( count + 1, ), fields[ 18 ] ) path = fields[ 22 ] # don't add song for albums list TODO: figure out how toplay albums ##if ( not self.ALBUMS ): path += fields[ 8 ] self.WINDOW.setProperty( "RandomSong.%d.Path" % ( count + 1, ), path ) # get cache name of path to use for fanart cache_name = xbmc.getCacheThumbName( fields[ 24 ] ) self.WINDOW.setProperty( "RandomSong.%d.Fanart" % ( count + 1, ), "special://profile/Thumbnails/Music/%s/%s" % ( "Fanart", cache_name, ) ) self.WINDOW.setProperty( "RandomSong.%d.Thumb" % ( count + 1, ), fields[ 27 ] )
def downloader(url,dest="Z:\\savegame.zip"): xbmc.executehttpapi('FileDelete(' + dest +')') dp = xbmcgui.DialogProgress() dp.create("GSM","Downloading File",url) try: urllib.urlretrieve(url,dest,lambda nb, bs, fs, url=url: _pbhook(nb,bs,fs,url,dp)) dp.close() return 1 except: dp.close() xebi('XBMC.Notification(MC360,Download Cancelled)') return 0
def _get_thumbnail( self, path ): # check for a thumb based on trailername.tbn thumbnail = os.path.splitext( path )[ 0 ] + ".tbn" # if thumb does not exist try stripping -trailer if ( not xbmc.executehttpapi( "FileExists(%s)" % ( thumbnail, ) ) == "<li>True" ): thumbnail = "%s.tbn" % ( os.path.splitext( path )[ 0 ].replace( "-trailer", "" ), ) # if thumb does not exist return empty if ( not xbmc.executehttpapi( "FileExists(%s)" % ( thumbnail, ) ) == "<li>True" ): # set empty string thumbnail = None # return result return thumbnail
def _init_variables( self ): self.global_timer = None self.slide_timer = None self.exiting = False # get current screensaver self.screensaver = xbmc.executehttpapi( "GetGUISetting(3;screensaver.mode)" ).replace( "<li>", "" ) # get the current volume self.current_volume = int( xbmc.executehttpapi( "GetVolume" ).replace( "<li>", "" ) ) # our complete shuffled list of slides self.slide_playlist = [] self.tmp_slides = [] self.image_count = 0
def _play_video_playlist(self): # set this to -1 as True and False are taken self.exiting = -1 # cancel timers self._cancel_timers() # turn screensaver back on xbmc.executehttpapi("SetGUISetting(3,screensaver.mode,%s)" % self.screensaver) # we play the video playlist here so the screen does not flash xbmc.Player().play(self.playlist) # close trivia slide show self.close()
def _fetch_music_info(self): # sql statement if self.ALBUMS: sql_music = "select idAlbum from albumview order by idAlbum desc limit %d" % (self.LIMIT,) # query the database for recently added albums music_xml = xbmc.executehttpapi("QueryMusicDatabase(%s)" % quote_plus(sql_music)) # separate the records albums = re.findall("<record>(.+?)</record>", music_xml, re.DOTALL) # set our unplayed query unplayed = ("(idAlbum = %s)", "(idAlbum = %s and lastplayed is null)")[self.UNPLAYED] # sql statement sql_music = "select songview.* from songview where %s limit 1" % (unplayed,) # clear our xml data music_xml = "" # enumerate thru albums and fetch info for album in albums: # query the database and add result to our string music_xml += xbmc.executehttpapi( "QueryMusicDatabase(%s)" % quote_plus(sql_music % (album.replace("<field>", "").replace("</field>", ""),)) ) else: # set our unplayed query unplayed = ("", "where lastplayed is null ")[self.UNPLAYED] # sql statement sql_music = "select * from songview %sorder by idSong desc limit %d" % (unplayed, self.LIMIT) # query the database music_xml = xbmc.executehttpapi("QueryMusicDatabase(%s)" % quote_plus(sql_music)) # separate the records items = re.findall("<record>(.+?)</record>", music_xml, re.DOTALL) # enumerate thru our records and set our properties for count, item in enumerate(items): # separate individual fields fields = re.findall("<field>(.*?)</field>", item, re.DOTALL) # set properties self.WINDOW.setProperty("LatestSong.%d.Title" % (count + 1,), fields[3]) self.WINDOW.setProperty("LatestSong.%d.Year" % (count + 1,), fields[6]) self.WINDOW.setProperty("LatestSong.%d.Artist" % (count + 1,), fields[24]) self.WINDOW.setProperty("LatestSong.%d.Album" % (count + 1,), fields[21]) self.WINDOW.setProperty("LatestSong.%d.Rating" % (count + 1,), fields[18]) path = fields[22] # don't add song for albums list TODO: figure out how toplay albums ##if ( not self.ALBUMS ): path += fields[8] self.WINDOW.setProperty("LatestSong.%d.Path" % (count + 1,), path) # get cache name of path to use for fanart cache_name = xbmc.getCacheThumbName(fields[24]) self.WINDOW.setProperty( "LatestSong.%d.Fanart" % (count + 1,), "special://profile/Thumbnails/Music/%s/%s" % ("Fanart", cache_name), ) self.WINDOW.setProperty("LatestSong.%d.Thumb" % (count + 1,), fields[27])
def _get_slides_xml( self, path ): # if no slides.xml exists return false if ( not ( "True" in xbmc.executehttpapi( "FileExists(%s)" % ( os.path.join( path, "slides.xml" ), ) ) ) ): return False, "", "", "", "", "" # fetch data, with hack for change in xbmc so older revisions still work xml_data = binascii.a2b_base64( xbmc.executehttpapi( "FileDownload(%s,bare)" % ( os.path.join( path, "slides.xml" ), ) ).split("\r\n\r\n")[ -1 ] ) # read formats and rating mpaa, theme = re.findall( "<slide rating=\"([^\"]*) theme=\"([^\"]*)\">", xml_data )[ 0 ] question_format = re.findall( "<question format=\"([^\"]+)\" />", xml_data )[ 0 ] clue_format = re.findall( "<clue format=\"([^\"]+)\" />", xml_data )[ 0 ] answer_format = re.findall( "<answer format=\"([^\"]+)\" />", xml_data )[ 0 ] # return results return True, mpaa, theme, question_format, clue_format, answer_format
def scanSeasonLibrary(self, tbns_set): # # *All Seasons # sql_seasons = "select path.strPath" \ " from path" \ " join tvshowlinkpath on tvshowlinkpath.idPath = path.idPath" xml_seasons = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus(sql_seasons), ) # Thumbnails... beautifulSoup = BeautifulSoup(xml_seasons) fieldNodes = beautifulSoup.findAll("field") for fieldNode in fieldNodes: season_full_path = "season%s%s" % (fieldNode.contents[0], xbmc.getLocalizedString(20366)) season_thumbnail = xbmc.getCacheThumbName(season_full_path) tbns_set.add(season_thumbnail) # # Season (1..n) # sql_seasons = "select episodeview.c12, path.strPath" \ " from episodeview" \ " join tvshowlinkpath on tvshowlinkpath.idShow = episodeview.idShow " \ " join path on path.idPath = tvshowlinkpath.idPath " \ " group by path.strPath, episodeview.c12" xml_seasons = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus(sql_seasons), ) # Thumbnails... beautifulSoup = BeautifulSoup(xml_seasons) fieldNodes = beautifulSoup.findAll("field") fieldNodesTuples = zip(fieldNodes[::2], fieldNodes[1::2]) for fieldNodeSeason, fieldNodePath in fieldNodesTuples: season_full_path = "season%s%s %s" % ( fieldNodePath.contents[0], xbmc.getLocalizedString(20373), fieldNodeSeason.contents[0]) season_thumbnail = xbmc.getCacheThumbName(season_full_path) tbns_set.add(season_thumbnail) # Cleanup sql_seasons = None xml_seasons = None fieldNodes = None fieldNodesTuples = None beautifulSoup = None
def play_picture_slideshow(origurl, name): print "Starting play_picture_slideshow(): " + str(origurl) #user clicked on a picture if origurl[-4:].lower() == '.jpg' or origurl[-4:].lower( ) == '.gif' or origurl[-4:].lower() == '.png': print "Single picture mode" origurl = origurl.replace(' ', '%20') xbmc.log("adding to picture slideshow: " + str(origurl)) xbmc.executehttpapi("ClearSlideshow") xbmc.executehttpapi("AddToSlideshow(%s)" % origurl) xbmc.executebuiltin("SlideShow(,,notrandom)") return #user clicked on <start slideshow> items = getItemsFromUrl(origurl) xbmc.executehttpapi("ClearSlideshow") itemCount = 0 for item in items: itemCount = itemCount + 1 label, url, description, pubDate, guid, thumb, duration, rating, viewcount = getItemFields( item) if url is not None and url != '': xbmc.executehttpapi("AddToSlideshow(%s)" % url) print "# of pictures added to sideshow " + str(itemCount) xbmc.executebuiltin("SlideShow(,,notrandom)")
def play_picture_slideshow(origurl, name): print "Starting play_picture_slideshow(): " + str(origurl) #user clicked on a picture if origurl[-4:].lower()=='.jpg' or origurl[-4:].lower()=='.gif' or origurl[-4:].lower()=='.png': print "Single picture mode" origurl = origurl.replace( ' ', '%20' ) xbmc.log("adding to picture slideshow: " + str(origurl)) xbmc.executehttpapi("ClearSlideshow") xbmc.executehttpapi("AddToSlideshow(%s)" % origurl) xbmc.executebuiltin( "SlideShow(,,notrandom)" ) return #user clicked on <start slideshow> items = getItemsFromUrl(origurl) xbmc.executehttpapi("ClearSlideshow") itemCount=0 for item in items: itemCount=itemCount+1 label, url, description, pubDate, guid, thumb, duration, rating, viewcount = getItemFields(item) if url is not None and url != '': xbmc.executehttpapi("AddToSlideshow(%s)" % url) print "# of pictures added to sideshow " + str(itemCount) xbmc.executebuiltin( "SlideShow(,,notrandom)" )
def _init_variables(self): self.global_timer = None self.slide_timer = None self.exiting = False # get current screensaver self.screensaver = xbmc.executehttpapi( "GetGUISetting(3;screensaver.mode)").replace("<li>", "") # get the current volume self.current_volume = int( xbmc.executehttpapi("GetVolume").replace("<li>", "")) # our complete shuffled list of slides self.slide_playlist = [] self.tmp_slides = [] self.image_count = 0
def _stop(): __settings__.setSetting(id="clientrunningflag", value="false") __settings__.setSetting(id="activesrcnm", value="") __settings__.setSetting(id="activesrcip", value="") xbmc.executehttpapi("Stop()") xbmc.executebuiltin("playlist.clear()") xbmc.executebuiltin("Notification(Multiroom Audio,All Streaming Stopped,7000,"+DEFAULT_IMG+")") if (sys.platform == 'win32'): subprocess.Popen(r'C:\WINDOWS\system32\cmd.exe /c "taskkill /F /IM vlc.exe"',shell=True) ##os.system("taskkill /F /IM vlc.exe") else: if (sys.platform.startswith('linux')): os.system("killall vlc | killall screen") else: os.system("killall vlc | killall screen")
def _finalize_download( self, tmp_path ): #try: if ( tmp_path != self.filepath ): msg1 = '%s' % ( os.path.split( self.filepath )[ 1 ], ) msg2 = '%s' % ( os.path.split( self.filepath )[ 0 ], ) pDialog.update( -1, msg1, msg2 ) xbmc.sleep( 50 ) # necessary for dialog to update xbmc.executehttpapi( "FileCopy(%s,%s)" % ( tmp_path, self.filepath.encode( "utf-8" ), ) ) os.remove( tmp_path ) thumbpath = os.path.splitext( self.filepath )[ 0 ] + ".tbn" msg1 = '%s' % ( os.path.split( thumbpath )[ 1 ], ) pDialog.update( -1, msg1, msg2 ) xbmc.sleep( 50 ) # necessary for dialog to update #xbmc.executehttpapi( "FileCopy(%s,%s)" % ( g_thumbnail, thumbpath.encode( "utf-8" ), ) ) return True
def getShortTV(title): try: # search TVDB's id from tvshow's title query = "select c12 from tvshow where c00 = '" + unicode( title) + "' limit 1" res = xbmc.executehttpapi("queryvideodatabase(" + query + ")") # get the result tvdbid = re.search('field>(.*?)<\/field', res) tvdbid = tvdbid.group(1) # get tvshow's url from TVDB's id searchurl = 'http://' + apiurl + '/shows/display/' + tvdbid + '.xml?key=' + apikey log(__name__, " BetaSeries query : %s" % (searchurl)) dom = minidom.parse(urllib.urlopen(searchurl)) url = "" if len(dom.getElementsByTagName('url')): url = dom.getElementsByTagName('url')[0].childNodes[0] url = url.nodeValue return url log(__name__, "'%s %s %s %s'" % (user, password, searchurl, url)) except: log(__name__, "getShortTV() failed") return url
def getRandomMovie(filterWatched, filterGenre, genre): # set our unplayed query if filterWatched: unplayed = "where (playCount is null " else: unplayed = "" # filter by genre? (There must be a neater way of doing this) if filterGenre: # if we're already filtering unplayed films then we need to ADD an extra criteria if filterWatched: filter = "AND movieview.c14 like '%%" + genre + "%%') " # otherwise it's a new criteria else: filter = " where movieview.c14 like '%%" + genre + "%%' " else: if filterWatched: filter = ") " else: filter = "" # sql statement sql_movies = "select movieview.c00, movieview.c08, movieview.c14, movieview.strPath, movieview.strFilename from movieview %s%sorder by RANDOM() limit 1" % ( unplayed, filter) # query the database movies_xml = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus(sql_movies), ) # separate the records movies = re.findall("<record>(.+?)</record>", movies_xml, re.DOTALL) # enumerate thru our records and set our properties for count, movie in enumerate(movies): # # separate individual fields fields = re.findall("<field>(.*?)</field>", movie, re.DOTALL) thumb_cache, fanart_cache, play_path = get_media(fields[3], fields[4]) # return the filepath for the film return play_path
def searchGames(self): log('|==================================|') log('searchGames().start') listItems = [] self.getControl(191).setLabel('[B]Games[/B]') gamesSQL = 'SELECT xbeDescription, strFileName FROM files WHERE strFileName LIKE "F:\GAMES%" AND xbeDescription LIKE "%' + self.SEARCH_STRING + '%"' log('searchGames().sql = ' + gamesSQL) gamesXML = xbmc.executehttpapi( "QueryProgramDatabase(%s)" % quote_plus(gamesSQL), ) games = re.findall("<record>(.+?)</record>", gamesXML, re.DOTALL) results = len(games) log('searchGames().results: ' + str(results)) for count, game in enumerate(games): fields = re.findall("<field>(.*?)</field>", game, re.DOTALL) thumb_cache = xbmc.getCacheThumbName(fields[1]) thumb = "special://profile/Thumbnails/Programs/%s/%s" % ( thumb_cache[0], thumb_cache, ) listItem = xbmcgui.ListItem(fields[0], fields[0], thumb, thumb) listItem.setProperty('path', fields[1]) listItem.setProperty('content', 'game') listItems.append(listItem) if results > 0: log('searchGames().success') self.getControl(201).addItems(listItems) self.getControl(200).setLabel(str(results)) self.getControl(209).setVisible(True) self.CONTENT_FOUND = 'true' log('searchGames().end')
def _get_items(self, paths, media_type): # reset folders list folders = [] # enumerate thru paths and fetch videos/pictures recursively for path in paths: # get the directory listing entries = xbmc.executehttpapi("GetDirectory(%s)" % (path, )).split("\n") # enumerate through our entries list and check for valid media type for entry in entries: # remove <li> from item entry = entry.replace("<li>", "") # if folder add to our folder list to recursively fetch videos/pictures if (entry.endswith("/") or entry.endswith("\\")): folders += [entry] # is this a valid video/picture file elif (entry and ((media_type.startswith("video") and os.path.splitext(entry)[1] in xbmc.getSupportedMedia("video")) or (media_type.endswith("picture") and os.path.splitext(entry)[1] in xbmc.getSupportedMedia("picture")))): # add our entry self.tmp_paths += [entry] # if there are folders call again (we want recursive) if (folders): self._get_items(folders, media_type)
def onInit(self): print "MenuGui.onInit" #trivia = "htpc-tac" q = 4400 while q < 4403: sql = "SELECT movieview.strPath, movieview.strFileName FROM movieview WHERE movieview.c07 < 2010 ORDER BY RANDOM() LIMIT 1" try: path, filename, dummy = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus(sql), ).split("</field>") except: xbmc.log("[script.sneak] - SQL failed for guisetup: ", xbmc.LOGNOTICE) ja = 0 ja = path.find("<field>") if ja != -1: dummy, path = path.split("<field>") dummy, filename = filename.split("<field>") xbmc.log("[script.sneak] - Gui Poster Path: %s " % path, xbmc.LOGNOTICE) xbmc.log("[script.sneak] - Gui Poster filename: %s" % filename, xbmc.LOGNOTICE) poster = getCachedThumb(os.path.join(path, filename)) xbmc.log("[script.sneak] - Gui Poster combine: %s" % poster, xbmc.LOGNOTICE) self.getControl(q).setImage(poster) q = q + 1
def _sqlquery(self, sqlquery): movie_list = [] movies = [] xbmc.executehttpapi("SetResponseFormat()") xbmc.executehttpapi("SetResponseFormat(OpenField,)") sqlquery = "SELECT movieview.c00 FROM movieview JOIN genrelinkmovie ON genrelinkmovie.idMovie=movieview.idMovie JOIN genre ON genrelinkmovie.idGenre=genre.idGenre WHERE strGenre='Action' ORDER BY RANDOM() LIMIT 4" log("[ script.cinema.experience ] - SQL: %s" % sqlquery) try: sqlresult = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus(sqlquery), ) log("sqlresult: %s" % sqlresult) movies = sqlresult.split("</field>") movie_list = movies[0:len(movies) - 1] except: log("Error searching database", xbmc.LOGNOTICE) return movie_list
def TV_listing(self): # sql statement for tv shows sql_data = "select tvshow.c00 , tvshow.c12 , path.strPath from tvshow , path , tvshowlinkpath where path.idPath = tvshowlinkpath.idPath AND tvshow.idShow = tvshowlinkpath.idShow" xml_data = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % urllib.quote_plus(sql_data), ) if DEBUG: print "### xml data: %s" % xml_data match = re.findall( "<field>(.*?)</field><field>(.*?)</field><field>(.*?)</field>", xml_data, re.DOTALL) try: self.TVlist = [] for import_base in match: try: if DEBUG: print import_base TVshow = {} TVshow["name"] = repr(import_base[0]).strip("'u") TVshow["id"] = repr(import_base[1]).strip("'u") TVshow["path"] = import_base[2] self.TVlist.append(TVshow) except: print_exc() except: print_exc() print "### no tvshow found in db"
def scanMovieLibrary(self, tbns_set): # Get movie list... sql_movies = "select strPath, strFilename from movieview" xml_movies = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus(sql_movies), ) beautifulSoup = BeautifulSoup(xml_movies) fieldNodes = beautifulSoup.findAll("field") fieldNodesTuples = zip(fieldNodes[::2], fieldNodes[1::2]) for fieldNodePath, fieldNodeFile in fieldNodesTuples: movie_path = fieldNodePath.contents[0] movie_file = fieldNodeFile.contents[0] movie_file_path = os.path.join(movie_path, movie_file) tbn_movie_path = xbmc.getCacheThumbName(movie_path) tbn_movie_file_path = xbmc.getCacheThumbName(movie_file_path) tbns_set.add(tbn_movie_path) tbns_set.add(tbn_movie_file_path) # Cleanup sql_movies = None xml_movies = None fieldNodesTuples = None beautifulSoup = None
def traversedir(path): print path # os.listdir also does not work with samba shares, using xbmc httpapi as a workaround #folderContents = os.listdir(path) response = xbmc.executehttpapi("GetDirectory(" + path + ")") # remove <li> tags response = response.replace("<li>", "") # we only want the directories and files, so remove the absolute network path response = response.replace(path, "") # also "dir/" has to be just "dir" response = response.replace("/", "") # first token is a newline, we do not want that response = response.replace("\n", "", 1) # we split at each newline, so that we have a list of dirs & files folderContents = response.split('\n') for entries in folderContents: url = os.path.join(path, entries) #url = path + entries isDir = os.path.isdir(url) liz = xbmcgui.ListItem(entries, '') if isDir: url = sys.argv[0] + "?mode=traverse&identifier=" + url + "/" xbmcplugin.addDirectoryItem(int(sys.argv[1]), url, liz, isFolder=True) else: xbmcplugin.addDirectoryItem(int(sys.argv[1]), url, liz, isFolder=False)
def TakeScreenShot(filename="", flash=False, rotation=0, width=720, height=576, quality=90): """ http://xbmc.org/wiki/?title=WebServerHTTP-API#Action_commands Captures the current contents of the XBMC screen. If no parameters then the action is the same as initiating a regular screenshot command with the image being saved in the screenshot directory. If filename is provided then the image is saved to filename. If flash=True the screen will flash as the command executes. If resolution, width, height and quality are given then those values are used to define the rotation (in degrees), resolution and jpeg quality of the saved image. The command must conform to one of: Filename, flash, rotation, width, height, quality """ if not filename: filename = str(time.time()) + ".jpg" filename = os.path.join(SCREENSHOT_DATA, filename) command = "%s;%s;%i;%i;%i;%i" % ( filename, repr(flash).lower(), rotation, width, height, quality, ) return xbmc.executehttpapi("TakeScreenShot(%s)" % (command, )).replace( "<li>", "")
def _fetch_actors_info( self ): print "### MOST REPRESENTED ACTOR" # sql statement for actors #sql_actors ="SELECT COUNT(actorlinkmovie.idActor), actorlinkmovie.idActor, actors.strActor, actors.strThumb FROM actorlinkmovie INNER JOIN actors ON actorlinkmovie.idActor=actors.idActor GROUP BY actorlinkmovie.idActor order by RANDOM() DESC LIMIT %s" % ( self.ACTOR_LIMIT, ) #order by COUNT(actorlinkmovie.idActor) sql_actors ="SELECT COUNT(actorlinkmovie.idActor), actorlinkmovie.idActor, actors.strActor, actors.strThumb FROM actorlinkmovie INNER JOIN actors ON actorlinkmovie.idActor=actors.idActor GROUP BY actorlinkmovie.idActor order by COUNT(actorlinkmovie.idActor) DESC LIMIT %s" % ( self.ACTOR_LIMIT, ) # # query the database actors_xml = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus( sql_actors ), ) # separate the records actors = re.findall( "<record>(.+?)</record>", actors_xml, re.DOTALL ) # enumerate thru our records and set our properties all_actors = [] for actor in actors : # separate individual fields fields = re.findall( "<field>(.*?)</field>", actor, re.DOTALL ) # set properties print "### %s %s - %s" % (fields [ 1 ], fields[ 2 ] ,fields[ 0 ] ) actor_data = self._get_actor_page( fields[ 2 ], fields[ 1 ] ) all_actors.append(actor_data) for gencount , i in enumerate(all_actors): self.WINDOW.setProperty( "ActorStuff.%d.name" % ( gencount + 1, ), i.get("name", "" ) ) self.WINDOW.setProperty( "ActorStuff.%d.ID" % ( gencount + 1, ), i.get("actorID", "" ) ) print "### DJP!! %s" % i.get("actorID", "" ) if len(i.get("images", "" )) >> 1: for count, image in enumerate( i.get("images", "" ) ): self.WINDOW.setProperty( "ActorStuff.%d.images%d" % ( gencount + 1, count + 1 ), image ) elif len(i.get("images", "" )) == 1: self.WINDOW.setProperty( "ActorStuff.%d.images1" % ( gencount + 1, ), i.get("images", "" )[0] ) else: self.WINDOW.setProperty( "ActorStuff.%d.images1" % ( gencount + 1, ), "" ) self.WINDOW.setProperty( "ActorStuff.%d.bio" % ( gencount + 1, ), i.get("bio", "" ) ) if i.get("bloc", False): for count , info in enumerate( i["bloc"].keys()): print "%s/%s : %s" % ( count , info , i["bloc"][info] ) self.WINDOW.setProperty( "ActorStuff.%d.info%d" % ( gencount + 1, count + 1 ), info + ":" + i["bloc"][info] ) print "######################"
def _fetch_tvshow_info( self ): # set our unplayed query unplayed = ( "", "where playCount isnull ", )[ self.UNPLAYED ] # sql statement if ( self.RECENT ): # recently added sql_episodes = "select * from episodeview %sorder by idepisode desc limit %d" % ( unplayed, self.LIMIT, ) else: # tv shows not finished sql_episodes = "select episodeview.*, bookmark.timeInSeconds from episodeview join bookmark on (episodeview.idFile = bookmark.idFile) %sorder by episodeview.strTitle limit %d" % ( unplayed, self.LIMIT, ) # query the database episodes_xml = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus( sql_episodes ), ) # separate the records episodes = re.findall( "<record>(.+?)</record>", episodes_xml, re.DOTALL ) # enumerate thru our records and set our properties for count, episode in enumerate( episodes ): # separate individual fields fields = re.findall( "<field>(.*?)</field>", episode, re.DOTALL ) # set properties self.WINDOW.setProperty( "LatestEpisode.%d.ShowTitle" % ( count + 1, ), fields[ 27 ] ) self.WINDOW.setProperty( "LatestEpisode.%d.EpisodeTitle" % ( count + 1, ), fields[ 1 ] ) self.WINDOW.setProperty( "LatestEpisode.%d.EpisodeNo" % ( count + 1, ), "s%02de%02d" % ( int( fields[ 13 ] ), int( fields[ 14 ] ), ) ) self.WINDOW.setProperty( "LatestEpisode.%d.Rating" % ( count + 1, ), fields[ 4 ] ) # get cache names of path to use for thumbnail/fanart and play path thumb_cache, fanart_cache, play_path = self._get_media( fields[ 24 ], fields[ 23 ] ) self.WINDOW.setProperty( "LatestEpisode.%d.Path" % ( count + 1, ), play_path ) self.WINDOW.setProperty( "LatestEpisode.%d.Fanart" % ( count + 1, ), "special://profile/Thumbnails/Video/%s/%s" % ( "Fanart", fanart_cache, ) ) # initial thumb path thumb = "special://profile/Thumbnails/Video/%s/%s" % ( thumb_cache[ 0 ], thumb_cache, ) # if thumb does not exist use an auto generated thumb path if ( not os.path.isfile( xbmc.translatePath( thumb ) ) ): thumb = "special://profile/Thumbnails/Video/%s/auto-%s" % ( thumb_cache[ 0 ], thumb_cache, ) self.WINDOW.setProperty( "LatestEpisode.%d.Thumb" % ( count + 1, ), thumb )