当前位置: 首页>>代码示例>>Python>>正文


Python API.get方法代码示例

本文整理汇总了Python中API.API.get方法的典型用法代码示例。如果您正苦于以下问题:Python API.get方法的具体用法?Python API.get怎么用?Python API.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在API.API的用法示例。


在下文中一共展示了API.get方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: setListItemProps

# 需要导入模块: from API import API [as 别名]
# 或者: from API.API import get [as 别名]
    def setListItemProps(self, server, id, listItem, result):
        # set up item and item info
        thumbID = id
        eppNum = -1
        seasonNum = -1
        tvshowTitle = ""
        
        if(result.get("Type") == "Episode"):
            thumbID = result.get("SeriesId")
            seasonNum = result.get("ParentIndexNumber")
            eppNum = result.get("IndexNumber")
            tvshowTitle = result.get("SeriesName")
            
        self.setArt(listItem,'poster', API().getArtwork(result, "Primary"))
        self.setArt(listItem,'tvshow.poster', API().getArtwork(result, "SeriesPrimary"))
        self.setArt(listItem,'clearart', API().getArtwork(result, "Art"))
        self.setArt(listItem,'tvshow.clearart', API().getArtwork(result, "Art"))    
        self.setArt(listItem,'clearlogo', API().getArtwork(result, "Logo"))
        self.setArt(listItem,'tvshow.clearlogo', API().getArtwork(result, "Logo"))    
        self.setArt(listItem,'discart', API().getArtwork(result, "Disc"))  
        self.setArt(listItem,'fanart_image', API().getArtwork(result, "Backdrop"))
        self.setArt(listItem,'landscape', API().getArtwork(result, "Thumb"))   
        
        listItem.setProperty('IsPlayable', 'true')
        listItem.setProperty('IsFolder', 'false')
        
        # Process Studios
        studios = API().getStudios(result)
        if studios == []:
            studio = ""
        else:
            studio = studios[0]
        listItem.setInfo('video', {'studio' : studio})    
            
        details = {
                 'title'        : result.get("Name", "Missing Name"),
                 'plot'         : result.get("Overview")
                 }
                 
        if(eppNum > -1):
            details["episode"] = str(eppNum)
            
        if(seasonNum > -1):
            details["season"] = str(seasonNum)  

        if tvshowTitle != None:
            details["TVShowTitle"] = tvshowTitle    
        
        listItem.setInfo( "Video", infoLabels=details )

        people = API().getPeople(result)

        # Process Genres
        genre = API().getGenre(result)
        
        listItem.setInfo('video', {'director' : people.get('Director')})
        listItem.setInfo('video', {'writer' : people.get('Writer')})
        listItem.setInfo('video', {'mpaa': result.get("OfficialRating")})
        listItem.setInfo('video', {'genre': API().getGenre(result)})
开发者ID:fhriley,项目名称:Emby.Kodi,代码行数:61,代码来源:PlaybackUtils.py

示例2: updatePlayCount

# 需要导入模块: from API import API [as 别名]
# 或者: from API.API import get [as 别名]
    def updatePlayCount(self, itemID):
        #update playcount of the itemID from MB3 to Kodi library
        
        addon = xbmcaddon.Addon(id='plugin.video.emby')
        WINDOW = xbmcgui.Window( 10000 )
        
        embyItem = ReadEmbyDB().getItem(itemID)
        if(embyItem == None):
            return False
        
        type = embyItem.get("Type")
        
        #process movie
        if type == 'Movie':
            kodiItem = ReadKodiDB().getKodiMovie(itemID)     

            if(kodiItem == None):
                return False
                
            if(self.ShouldStop(None)):
                return False
 
            userData = API().getUserData(embyItem)
            timeInfo = API().getTimeInfo(embyItem)
                
            kodiresume = int(round(kodiItem['resume'].get("position")))
            resume = int(round(float(timeInfo.get("ResumeTime"))))*60
            total = int(round(float(timeInfo.get("TotalTime"))))*60
            if kodiresume != resume:
                WriteKodiDB().setKodiResumePoint(kodiItem['movieid'],resume,total,"movie")
            #write property forced will refresh the item in the list so playcount change is immediately visible
            WriteKodiDB().updateProperty(kodiItem,"playcount",int(userData.get("PlayCount")),"movie",True)
            WriteKodiDB().updateProperty(kodiItem,"lastplayed",userData.get("LastPlayedDate"), "movie")
                
            if(self.ShouldStop(None)):
                return False 
                    
        #process episode
        elif type == 'Episode':
            if(self.ShouldStop(None)):
                return False                   
                    
            kodiItem = ReadKodiDB().getKodiEpisodeByMbItem(embyItem["Id"], embyItem["SeriesId"])

            userData = API().getUserData(embyItem)
            timeInfo = API().getTimeInfo(embyItem)
            
            if kodiItem != None:
                kodiresume = int(round(kodiItem['resume'].get("position")))
                resume = int(round(float(timeInfo.get("ResumeTime"))))*60
                total = int(round(float(timeInfo.get("TotalTime"))))*60
                if kodiresume != resume:
                    WriteKodiDB().setKodiResumePoint(kodiItem['episodeid'],resume,total,"episode")
                #write property forced will refresh the item in the list so playcount change is immediately visible
                WriteKodiDB().updateProperty(kodiItem,"playcount",int(userData.get("PlayCount")),"episode",True)
                WriteKodiDB().updateProperty(kodiItem,"lastplayed",userData.get("LastPlayedDate"), "episode")       
        
        return True
开发者ID:freddy36,项目名称:Emby.Kodi,代码行数:60,代码来源:LibrarySync.py

示例3: PLAY

# 需要导入模块: from API import API [as 别名]
# 或者: from API.API import get [as 别名]
    def PLAY(self, result, setup="service"):
        xbmc.log("PLAY Called")
        WINDOW = xbmcgui.Window(10000)

        username = WINDOW.getProperty('currUser')
        userid = WINDOW.getProperty('userId%s' % username)
        server = WINDOW.getProperty('server%s' % username)
        
        try:
            id = result["Id"]
        except:
            return

        userData = result['UserData']

        # BOOKMARK - RESUME POINT
        timeInfo = API().getTimeInfo(result)
        jumpBackSec = int(utils.settings("resumeJumpBack"))
        seekTime = round(float(timeInfo.get('ResumeTime')), 6)
        if seekTime > jumpBackSec:
            # To avoid negative bookmark
            seekTime = seekTime - jumpBackSec

        itemsToPlay = []
        # Check for intros
        if seekTime == 0:
            # if we have any play them when the movie/show is not being resumed
            # We can add the option right here
            url = "{server}/mediabrowser/Users/{UserId}/Items/%s/Intros?format=json&ImageTypeLimit=1&Fields=Etag" % id    
            intros = self.downloadUtils.downloadUrl(url)
            if intros[u'TotalRecordCount'] == 0:
                pass
            else:
                for intro in intros[u'Items']:
                    introId = intro[u'Id']
                    itemsToPlay.append(introId)

        # Add original item
        itemsToPlay.append(id)
        
        # For split movies
        if u'PartCount' in result:
            partcount = result[u'PartCount']
            # Get additional parts/playurl
            url = "{server}/mediabrowser/Videos/%s/AdditionalParts" % id
            parts = self.downloadUtils.downloadUrl(url)
            for part in parts[u'Items']:
                partId = part[u'Id']
                itemsToPlay.append(partId)

        if len(itemsToPlay) > 1:
            # Let's play the playlist
            return self.AddToPlaylist(itemsToPlay)

        playurl = PlayUtils().getPlayUrl(server, id, result)

        if playurl == False or WINDOW.getProperty('playurlFalse') == "true":
            WINDOW.clearProperty('playurlFalse')
            xbmc.log("Failed to retrieve the playback path/url.")
            return

        if WINDOW.getProperty("%splaymethod" % playurl) == "Transcode":
            # Transcoding, we pull every track to set before playback starts
            playurlprefs = self.audioSubsPref(playurl, result.get("MediaSources"))
            if playurlprefs:
                playurl = playurlprefs
            else: # User cancelled dialog
                return


        thumbPath = API().getArtwork(result, "Primary")
        
        #if the file is a virtual strm file, we need to override the path by reading it's contents
        if playurl.endswith(".strm"):
            xbmc.log("virtual strm file file detected, starting playback with 3th party addon...")
            StrmTemp = "special://temp/temp.strm"
            xbmcvfs.copy(playurl, StrmTemp)
            playurl = open(xbmc.translatePath(StrmTemp), 'r').readline()
                 
        listItem = xbmcgui.ListItem(path=playurl, iconImage=thumbPath, thumbnailImage=thumbPath)

        if WINDOW.getProperty("%splaymethod" % playurl) != "Transcode":
            # Only for direct play and direct stream
            # Append external subtitles to stream
            subtitleList = self.externalSubs(id, playurl, server, result.get('MediaSources'))
            listItem.setSubtitles(subtitleList)
            #pass

        # Can not play virtual items
        if (result.get("LocationType") == "Virtual"):
          xbmcgui.Dialog().ok(self.language(30128), self.language(30129))

        watchedurl = "%s/mediabrowser/Users/%s/PlayedItems/%s" % (server, userid, id)
        positionurl = "%s/mediabrowser/Users/%s/PlayingItems/%s" % (server, userid, id)
        deleteurl = "%s/mediabrowser/Items/%s" % (server, id)

        # set the current playing info
        WINDOW.setProperty(playurl+"watchedurl", watchedurl)
        WINDOW.setProperty(playurl+"positionurl", positionurl)
        WINDOW.setProperty(playurl+"deleteurl", "")
#.........这里部分代码省略.........
开发者ID:raven-au,项目名称:Emby.Kodi,代码行数:103,代码来源:PlaybackUtils.py

示例4: addOrUpdateSongToKodiLibrary

# 需要导入模块: from API import API [as 别名]
# 或者: from API.API import get [as 别名]
    def addOrUpdateSongToKodiLibrary(self, MBitem, connection, cursor):

        kodiVersion = self.kodiversion
        
        embyId = MBitem["Id"]
        
        # If the item already exist in the local Kodi DB we'll perform a full item update
        # If the item doesn't exist, we'll add it to the database
        
        cursor.execute("SELECT kodi_id FROM emby WHERE emby_id = ?", (embyId,))
        try:
            songid = cursor.fetchone()[0]
        except:
            songid = None
        
        timeInfo = API().getTimeInfo(MBitem)
        userData = API().getUserData(MBitem)
        genres = MBitem.get('Genres')

        ##### The song details #####
        playcount = userData.get('PlayCount')
        lastplayed = userData.get('LastPlayedDate')
        dateadded = API().getDateCreated(MBitem)
        checksum = API().getChecksum(MBitem)
        
        name = MBitem['Name']
        musicBrainzId = API().getProvider(MBitem, "musicBrainzTrackId")
        genre = " / ".join(genres)
        artists = " / ".join(MBitem.get('Artists'))
        tracknumber = MBitem.get('IndexNumber', 0)
        disc = MBitem.get('ParentIndexNumber', 1)
        track = disc*2**16 + tracknumber
        year = MBitem.get('ProductionYear')
        bio = API().getOverview(MBitem)
        duration = timeInfo.get('TotalTime')


        if utils.settings('directstreammusic') == "true":
            WINDOW = xbmcgui.Window(10000)
            username = WINDOW.getProperty('currUser')
            server = WINDOW.getProperty('server%s' % username)

            playurl = PlayUtils().directStream(MBitem, server, embyId, "Audio")
            filename = "stream.mp3"
            path = playurl.replace(filename, "")
        else:
            # Get the path and filename
            playurl = PlayUtils().directPlay(MBitem)
            path, filename = ntsplit(playurl)
            if "/" in playurl:
                path = "%s/" % path
            elif "\\" in playurl:
                path = "%s\\" % path


        # Validate the path in database
        cursor.execute("SELECT idPath as pathid FROM path WHERE strPath = ?", (path,))
        try:
            pathid = cursor.fetchone()[0]
        except:
            cursor.execute("select coalesce(max(idPath),0) as pathid from path")
            pathid = cursor.fetchone()[0] + 1
            query = "INSERT INTO path(idPath, strPath) values(?, ?)"
            cursor.execute(query, (pathid, path))

        # Get the album
        cursor.execute("SELECT kodi_id FROM emby WHERE emby_id = ?", (MBitem.get("AlbumId"),))
        try:
            albumid = cursor.fetchone()[0]
        except:
            # No album found, create a single's album
            cursor.execute("select coalesce(max(idAlbum),0) as albumid from album")
            albumid = cursor.fetchone()[0] + 1
            if kodiVersion == 15:
                # Kodi Isengard
                query = "INSERT INTO album(idAlbum, strGenres, iYear, dateAdded, strReleaseType) values(?, ?, ?, ?, ?)"
                cursor.execute(query, (albumid, genre, year, dateadded, "single"))
            elif kodiVersion == 16:
                query = "INSERT INTO album(idAlbum, strGenres, iYear, strReleaseType) values(?, ?, ?, ?)"
                cursor.execute(query, (albumid, genre, year, "single"))
            else:
                # Kodi Gotham and Helix
                query = "INSERT INTO album(idAlbum, strGenres, iYear, dateAdded) values(?, ?, ?, ?)"
                cursor.execute(query, (albumid, genre, year, dateadded))
        finally:
            cursor.execute("SELECT strArtists FROM album WHERE idAlbum = ?", (albumid,))
            result = cursor.fetchone()
            if result and result[0] == "":
                # Link album to artists
                if MBitem['AlbumArtists']:
                    album_artists = MBitem['AlbumArtists']
                else:
                    album_artists = MBitem['ArtistItems']

                MBartists = []
                for artist in album_artists:
                    MBartists.append(artist['Name'])
                    cursor.execute("SELECT kodi_id FROM emby WHERE emby_id = ?", (artist['Id'],))
                    try:
                        artistid = cursor.fetchone()[0]
#.........这里部分代码省略.........
开发者ID:Misty27,项目名称:Emby.Kodi,代码行数:103,代码来源:WriteKodiMusicDB.py

示例5: addOrUpdateAlbumToKodiLibrary

# 需要导入模块: from API import API [as 别名]
# 或者: from API.API import get [as 别名]
    def addOrUpdateAlbumToKodiLibrary(self, MBitem, connection, cursor):
        
        kodiVersion = self.kodiversion
        
        embyId = MBitem["Id"]
        
        # If the item already exist in the local Kodi DB we'll perform a full item update
        # If the item doesn't exist, we'll add it to the database
        
        cursor.execute("SELECT kodi_id FROM emby WHERE emby_id = ?", (embyId,))
        try:
            albumid = cursor.fetchone()[0]
        except:
            albumid = None

        genres = MBitem.get('Genres')

        ##### The album details #####
        lastScraped = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        dateadded = API().getDateCreated(MBitem)
        checksum = API().getChecksum(MBitem)

        name = MBitem['Name']
        musicBrainzId = API().getProvider(MBitem, "musicBrainzAlbum")
        year = MBitem.get('ProductionYear')
        genre = " / ".join(genres)
        bio = API().getOverview(MBitem)
        
        MBartists = []
        for item in MBitem['AlbumArtists']:
            MBartists.append(item['Name'])
        artists = " / ".join(MBartists)

        # Associate the artwork
        artworks = API().getAllArtwork(MBitem, parentInfo=True)
        thumb = artworks['Primary']
        if thumb:
            thumb = "<thumb>%s</thumb>" % thumb

        
        ##### UPDATE THE ALBUM #####
        if albumid:
            self.logMsg("UPDATE album to Kodi library, Id: %s - Title: %s" % (embyId, name), 1)

            if kodiVersion == 15:
                # Kodi Isengard
                query = "UPDATE album SET strAlbum = ?, strMusicBrainzAlbumID = ?, strArtists = ?, iYear = ?, strGenres = ?, strReview = ?, strImage = ?, lastScraped = ?, dateAdded = ?, strReleaseType = ? WHERE idAlbum = ?"
                cursor.execute(query, (name, musicBrainzId, artists, year, genre, bio, thumb, lastScraped, dateadded, "album", albumid))
            elif kodiVersion == 16:
                query = "UPDATE album SET strAlbum = ?, strMusicBrainzAlbumID = ?, strArtists = ?, iYear = ?, strGenres = ?, strReview = ?, strImage = ?, lastScraped = ?, strReleaseType = ? WHERE idAlbum = ?"
                cursor.execute(query, (name, musicBrainzId, artists, year, genre, bio, thumb, lastScraped, "album", albumid))
            else:
                # Kodi Gotham and Helix
                query = "UPDATE album SET strAlbum = ?, strMusicBrainzAlbumID = ?, strArtists = ?, iYear = ?, strGenres = ?, strReview = ?, strImage = ?, lastScraped = ?, dateAdded = ? WHERE idAlbum = ?"
                cursor.execute(query, (name, musicBrainzId, artists, year, genre, bio, thumb, lastScraped, dateadded, albumid))

            # Update the checksum in emby table
            query = "UPDATE emby SET checksum = ? WHERE emby_id = ?"
            cursor.execute(query, (checksum, embyId))

        ##### OR ADD THE ALBUM #####
        else:
            self.logMsg("ADD album to Kodi library, Id: %s - Title: %s" % (embyId, name), 1)
            
            # Safety check: does the strMusicBrainzAlbumID already exist?
            cursor.execute("SELECT idAlbum FROM album WHERE strMusicBrainzAlbumID = ?", (musicBrainzId,))
            try:
                albumid = cursor.fetchone()[0]
            except:
                # Create the album
                cursor.execute("select coalesce(max(idAlbum),0) as albumid from album")
                albumid = cursor.fetchone()[0] + 1
                if kodiVersion == 15:
                    # Kodi Isengard
                    query = "INSERT INTO album(idAlbum, strAlbum, strMusicBrainzAlbumID, strArtists, iYear, strGenres, strReview, strImage, lastScraped, dateAdded, strReleaseType) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
                    cursor.execute(query, (albumid, name, musicBrainzId, artists, year, genre, bio, thumb, lastScraped, dateadded, "album"))
                elif kodiVersion == 16:
                    query = "INSERT INTO album(idAlbum, strAlbum, strMusicBrainzAlbumID, strArtists, iYear, strGenres, strReview, strImage, lastScraped, strReleaseType) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
                    cursor.execute(query, (albumid, name, musicBrainzId, artists, year, genre, bio, thumb, lastScraped, "album"))
                else:
                    # Kodi Gotham and Helix
                    query = "INSERT INTO album(idAlbum, strAlbum, strMusicBrainzAlbumID, strArtists, iYear, strGenres, strReview, strImage, lastScraped, dateAdded) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
                    cursor.execute(query, (albumid, name, musicBrainzId, artists, year, genre, bio, thumb, lastScraped, dateadded))

            # Create the reference in emby table
            query = "INSERT INTO emby(emby_id, kodi_id, media_type, checksum) values(?, ?, ?, ?)"
            cursor.execute(query, (embyId, albumid, "album", checksum))


        # Add genres
        self.AddGenresToMedia(albumid, genres, "album", cursor)

        # Update artwork
        if artworks['Primary']:
            self.textureCache.addOrUpdateArt(artworks['Primary'], albumid, "album", "thumb", cursor)
            artworks['Primary'] = ""

        if artworks.get('BoxRear'):
            self.textureCache.addOrUpdateArt(artworks['BoxRear'], albumid, "album", "poster", cursor)
            artworks['BoxRear'] = ""
#.........这里部分代码省略.........
开发者ID:Misty27,项目名称:Emby.Kodi,代码行数:103,代码来源:WriteKodiMusicDB.py

示例6: setListItemProps

# 需要导入模块: from API import API [as 别名]
# 或者: from API.API import get [as 别名]
    def setListItemProps(self, server, id, listItem, result):
        # set up item and item info
        userid = self.downloadUtils.getUserId()
        thumbID = id
        eppNum = -1
        seasonNum = -1
        tvshowTitle = ""
        
        if(result.get("Type") == "Episode"):
            thumbID = result.get("SeriesId")
            seasonNum = result.get("ParentIndexNumber")
            eppNum = result.get("IndexNumber")
            tvshowTitle = result.get("SeriesName")
            
        self.setArt(listItem,'poster', self.downloadUtils.getArtwork(result, "Primary"))
        self.setArt(listItem,'tvshow.poster', self.downloadUtils.getArtwork(result, "SeriesPrimary"))
        self.setArt(listItem,'clearart', self.downloadUtils.getArtwork(result, "Art"))
        self.setArt(listItem,'tvshow.clearart', self.downloadUtils.getArtwork(result, "Art"))    
        self.setArt(listItem,'clearlogo', self.downloadUtils.getArtwork(result, "Logo"))
        self.setArt(listItem,'tvshow.clearlogo', self.downloadUtils.getArtwork(result, "Logo"))    
        self.setArt(listItem,'discart', self.downloadUtils.getArtwork(result, "Disc"))  
        self.setArt(listItem,'fanart_image', self.downloadUtils.getArtwork(result, "Backdrop"))
        self.setArt(listItem,'landscape', self.downloadUtils.getArtwork(result, "Thumb"))   
        
        listItem.setProperty('IsPlayable', 'true')
        listItem.setProperty('IsFolder', 'false')
        
        # Process Studios
        studio = API().getStudio(result) 
        listItem.setInfo('video', {'studio' : studio})    

        # play info
        playinformation = ''
        if PlayUtils().isDirectPlay(result) == True:
            if self.settings.getSetting('playFromStream') == "true":
                playinformation = self.language(30164)
            else:
                playinformation = self.language(30165)
        else:
            playinformation = self.language(30166)
            
        details = {
                 'title'        : result.get("Name", "Missing Name") + ' - ' + playinformation,
                 'plot'         : result.get("Overview")
                 }
                 
        if(eppNum > -1):
            details["episode"] = str(eppNum)
            
        if(seasonNum > -1):
            details["season"] = str(seasonNum)  

        if tvshowTitle != None:
            details["TVShowTitle"] = tvshowTitle	
        
        listItem.setInfo( "Video", infoLabels=details )

        people = API().getPeople(result)

        # Process Genres
        genre = API().getGenre(result)
        
        listItem.setInfo('video', {'director' : people.get('Director')})
        listItem.setInfo('video', {'writer' : people.get('Writer')})
        listItem.setInfo('video', {'mpaa': self.db.get(thumbID + ".OfficialRating")})
        listItem.setInfo('video', {'genre': genre})
开发者ID:MediaBrowser,项目名称:MediaBrowser.Kodi,代码行数:68,代码来源:PlaybackUtils.py

示例7: updatePlayCounts

# 需要导入模块: from API import API [as 别名]
# 或者: from API.API import get [as 别名]
    def updatePlayCounts(self):
        #update all playcounts from MB3 to Kodi library
        
        addon = xbmcaddon.Addon(id='plugin.video.emby')
        WINDOW = xbmcgui.Window( 10000 )
        pDialog = None
        startedSync = datetime.today()
        processMovies = True
        processTvShows = True
        
        if(WINDOW.getProperty("SyncDatabaseShouldStop") ==  "true"):
            utils.logMsg("Sync PlayCount", "Can not start SyncDatabaseShouldStop=True", 0)
            return True        
        
        if(WINDOW.getProperty("updatePlayCounts_Running") == "true"):
            utils.logMsg("Sync PlayCount", "updatePlayCounts Already Running", 0)
            return False
            
        WINDOW.setProperty("updatePlayCounts_Running", "true")
            
        try:
            playCountSyncIndication = addon.getSetting("playCountSyncIndication")
            playCountSyncFirstRun = addon.getSetting("SyncFirstCountsRunDone")
                
            if(playCountSyncFirstRun != "true" or playCountSyncIndication == "Dialog Progress"):
                pDialog = xbmcgui.DialogProgress()
            elif(playCountSyncIndication == "BG Progress"):
                pDialog = xbmcgui.DialogProgressBG()
                
            if(pDialog != None):
                pDialog.create('Sync PlayCounts', 'Sync PlayCounts')        
        
            totalCountsUpdated = 0
            totalPositionsUpdated = 0
            
            #process movies
            if processMovies:
                if(pDialog != None):
                    pDialog.update(0, "Processing Movies", "")
                    
                views = ReadEmbyDB().getCollections("movies")
                viewCount = len(views)
                viewCurrent = 1
                for view in views:
                    allMB3Movies = ReadEmbyDB().getMovies(view.get('id'), fullinfo = False, fullSync = True)
                    allKodiMovies = ReadKodiDB().getKodiMovies(False)
                    
                    if(self.ShouldStop(pDialog)):
                        return False
                            
                    if(allMB3Movies != None and allKodiMovies != None):
                        
                        if(pDialog != None):
                            progressTitle = "Sync PlayCounts: Processing " + view.get('title') + " " + str(viewCurrent) + " of " + str(viewCount)
                            pDialog.update(0, progressTitle)
                            totalCount = len(allMB3Movies) + 1
                            count = 1
                    
                        for item in allMB3Movies:
                            
                            if not item.get('IsFolder'):                           
                                kodiItem = allKodiMovies.get(item["Id"], None)
                                
                                userData = API().getUserData(item)
                                timeInfo = API().getTimeInfo(item)
                                
                                if kodiItem != None:
                                    kodiresume = int(round(kodiItem['resume'].get("position")))
                                    resume = int(round(float(timeInfo.get("ResumeTime"))))*60
                                    total = int(round(float(timeInfo.get("TotalTime"))))*60
                                    if kodiresume != resume:
                                        WriteKodiDB().setKodiResumePoint(kodiItem['movieid'],resume,total,"movie")
                                        totalPositionsUpdated += 1
                                    updated = WriteKodiDB().updateProperty(kodiItem,"playcount",int(userData.get("PlayCount")), "movie")
                                    updated |= WriteKodiDB().updateProperty(kodiItem,"lastplayed",userData.get("LastPlayedDate"), "movie")
                                    if(updated):
                                        totalCountsUpdated += 1
                                        
                                if(self.ShouldStop(pDialog)):
                                    return False
                                
                                # update progress bar
                                if(pDialog != None):
                                    percentage = int(((float(count) / float(totalCount)) * 100))
                                    pDialog.update(percentage, progressTitle, "Updating Movie: " + str(count))
                                    count += 1   
                                
                    viewCurrent += 1
                    
            #process Tv shows
            if processTvShows:
                if(pDialog != None):
                    pDialog.update(0, "Processing TV Episodes", "")
                views = ReadEmbyDB().getCollections("tvshows")
                viewCount = len(views)
                viewCurrent = 1
                progressTitle = ""
                for view in views:            
            
                    tvshowData = ReadEmbyDB().getTVShows(id = view.get('id'), fullinfo = False, fullSync = True)
#.........这里部分代码省略.........
开发者ID:freddy36,项目名称:Emby.Kodi,代码行数:103,代码来源:LibrarySync.py

示例8: print

# 需要导入模块: from API import API [as 别名]
# 或者: from API.API import get [as 别名]
        'offset': '0',
        'subscription-key': 'f7cc29509a8443c5b3a5e56b0e38b5a6',
    })

    try:
        conn = http.client.HTTPSConnection('oxfordhk.azure-api.net')
        conn.request("GET", "/academic/v1.0/evaluate?%s" % params)
        response = conn.getresponse()
        data = response.read()
        data = json.loads(data.decode('UTF-8'))
        conn.close()
        return data
    except Exception as e:
        print(e)

t1 = time()
data = callAPI('Id=2112090702',attr='Id,Ti,AA.AuId,AA.AfId,F.FId,J.JN,J.JId,C.CId,RId',count = 1000000)
t2 = time()
print(data)
print('Elapsed time of official API:',t2-t1)

#国伟的API
from API import API
from searchPath import genURL
api = API()
url = genURL(expr='Id=2112090702' , attr='Id,Ti,AA.AuId,AA.AfId,F.FId,J.JN,J.JId,C.CId,RId',count=1000000)
t1 = time()
data = api.get(url).getvalue().decode('UTF-8')
t2 = time()
print(data)
print('Elapsed time of guowei\' API:',t2-t1)
开发者ID:bop2016,项目名称:bop2016,代码行数:33,代码来源:compareAPI.py

示例9: updateDB

# 需要导入模块: from API import API [as 别名]
# 或者: from API.API import get [as 别名]
    def updateDB(self, item):
        id=item.get("Id")
        userid = downloadUtils.getUserId()
        mb3Host = __settings__.getSetting('ipaddress')
        mb3Port = __settings__.getSetting('port')    
        Name=API().getName(item)
        db.set(id+".Name",Name)
        timeInfo = API().getTimeInfo(item)
        mediaStreams=API().getMediaStreams(item)
        userData=API().getUserData(item)
        people = API().getPeople(item)
        db.set(id+".Overview",API().getOverview(item))
        db.set(id+".OfficialRating",item.get("OfficialRating"))
        CommunityRating=item.get("CommunityRating")
        if CommunityRating != None:
            db.set(id+".CommunityRating",       str(CommunityRating))
        db.set(id+".CriticRating",              str(item.get("CriticRating")))
        db.set(id+".ProductionYear",            str(item.get("ProductionYear")))
        db.set(id+".LocationType",              item.get("LocationType"))
        db.set(id+".IsFolder",                  str(item.get("IsFolder")))
        db.set(id+".Primary",                   downloadUtils.getArtwork(item, "Primary")) 
        db.set(id+".Backdrop",                  downloadUtils.getArtwork(item, "Backdrop"))
        db.set(id+".poster",                    downloadUtils.getArtwork(item, "poster")) 
        db.set(id+".tvshow.poster",             downloadUtils.getArtwork(item, "tvshow.poster")) 
        db.set(id+".Banner",                    downloadUtils.getArtwork(item, "Banner")) 
        db.set(id+".Logo",                      downloadUtils.getArtwork(item, "Logo")) 
        db.set(id+".Disc",                      downloadUtils.getArtwork(item, "Disc")) 
        db.set(id+".Art",                       downloadUtils.getArtwork(item, "Art")) 
        db.set(id+".Thumb",                     downloadUtils.getArtwork(item, "Thumb")) 
        db.set(id+".Thumb3",                    downloadUtils.getArtwork(item, "Thumb3")) 
        db.set(id+".Primary2",                  downloadUtils.getArtwork(item, "Primary2")) 
        db.set(id+".Primary4",                  downloadUtils.getArtwork(item, "Primary4")) 
        db.set(id+".Primary3",                  downloadUtils.getArtwork(item, "Primary3")) 
        db.set(id+".Backdrop2",                 downloadUtils.getArtwork(item, "Backdrop2")) 
        db.set(id+".Backdrop3",                 downloadUtils.getArtwork(item, "Backdrop3")) 
        db.set(id+".BackdropNoIndicators",      downloadUtils.getArtwork(item, "BackdropNoIndicators"))         
        db.set(id+".Duration",                  timeInfo.get('Duration'))
        db.set(id+".CompletePercentage",        timeInfo.get('Percent'))
        db.set(id+".ResumeTime",                timeInfo.get('ResumeTime'))
        db.set(id+".Channels",                  mediaStreams.get('channels'))
        db.set(id+".VideoCodec",                mediaStreams.get('videocodec'))
        db.set(id+".AspectRatio",               mediaStreams.get('aspectratio'))
        db.set(id+".AudioCodec",                mediaStreams.get('audiocodec'))
        db.set(id+".Height",                    mediaStreams.get('height'))
        db.set(id+".Width",                     mediaStreams.get('width'))       
        db.set(id+".Director",                  people.get('Director'))
        db.set(id+".Writer",                    people.get('Writer'))
        db.set(id+".ItemType",                  item.get("Type"))
        db.set(id+".Watched",                   userData.get('Watched'))
        db.set(id+".Favorite",                  userData.get('Favorite'))
        db.set(id+".PlayCount",                 userData.get('PlayCount'))
        db.set(id+".Studio",                    API().getStudio(item))
        db.set(id+".Genre",                     API().getGenre(item))
        db.set(id+".WatchedURL",                'http://' + mb3Host + ':' + mb3Port + '/mediabrowser/Users/' + userid + '/PlayedItems/' + id)
        db.set(id+".FavoriteURL",               'http://' + mb3Host + ':' + mb3Port + '/mediabrowser/Users/'+ userid + '/FavoriteItems/' + id)
        db.set(id+".DeleteURL",                 'http://' + mb3Host + ':' + mb3Port + '/mediabrowser/Items/' + id)
        
        
        if(item.get("PremiereDate") != None):
            premieredatelist = (item.get("PremiereDate")).split("T")
            db.set(id+".PremiereDate",              premieredatelist[0])
        else:
            premieredate = ""

        # add resume percentage text to titles
        if (__settings__.getSetting('addResumePercent') == 'true' and Name != '' and timeInfo.get('Percent') != 'None'):
            db.set(id+".Name", Name + " (" + timeInfo.get('Percent') + "%)")
开发者ID:Hellnation13,项目名称:MediaBrowser.Kodi,代码行数:69,代码来源:BackgroundData.py

示例10: Queue

# 需要导入模块: from API import API [as 别名]
# 或者: from API.API import get [as 别名]
from queue import Queue
from API import API
import grequests

if __name__ == '__main__':
    params = urllib.parse.urlencode({
        # Request parameters
        'expr': 'Composite(AA.AuN==\'jaime teevan\')',
        'model': 'latest',
        'attributes': 'Ti,Y,CC,AA.AuN,AA.AuId',
        'count': '2',
        'offset': '0',
        'subscription-key': 'f7cc29509a8443c5b3a5e56b0e38b5a6',
    })

    urls = ['http://oxfordhk.azure-api.net/academic/v1.0/evaluate?%s' % params] * 100
    q = Queue()
    api = API()
    # run 3 times to observe the effect of Curl_pool and obtain average time
    for i in range(10):
        start_time = time()
        api.multi_get_async(urls, lambda x: q.put_nowait(x))
        result = q.get()
        print(result[0][1].getvalue()[:10])
        print('Elapsed time of multi_get: %f' % (time() - start_time))
        start_time = time()
        api.multi_get_grequests(urls)
        print('Elapsed time of grequests: %f' % (time() - start_time))

    print(api.get('http://oxfordhk.azure-api.net/academic/v1.0/evaluate?%s' % params).getvalue()[:10])
开发者ID:bop2016,项目名称:bop2016,代码行数:32,代码来源:Test_API.py

示例11: addOrUpdateSongToKodiLibrary

# 需要导入模块: from API import API [as 别名]
# 或者: from API.API import get [as 别名]
    def addOrUpdateSongToKodiLibrary( self, embyId ,connection, cursor):
        
        addon = xbmcaddon.Addon(id='plugin.video.emby')
        WINDOW = xbmcgui.Window(10000)
        username = WINDOW.getProperty('currUser')
        userid = WINDOW.getProperty('userId%s' % username)
        server = WINDOW.getProperty('server%s' % username)
        downloadUtils = DownloadUtils()
        
        MBitem = ReadEmbyDB().getFullItem(embyId)
        
        timeInfo = API().getTimeInfo(MBitem)
        userData=API().getUserData(MBitem)
        
        kodiVersion = 14
        if xbmc.getInfoLabel("System.BuildVersion").startswith("15"):
            kodiVersion = 15
        
        # If the item already exist in the local Kodi DB we'll perform a full item update
        # If the item doesn't exist, we'll add it to the database
        
        cursor.execute("SELECT kodi_id FROM emby WHERE emby_id = ?",(MBitem["Id"],))
        result = cursor.fetchone()
        if result != None:
            songid = result[0]
        else:
            songid = None
        

        #### The song details #########
        name = utils.convertEncoding(MBitem["Name"])
        musicBrainzId = None
        if MBitem.get("ProviderIds"):
            if MBitem.get("ProviderIds").get("MusicBrainzTrackId"):
                musicBrainzId = MBitem.get("ProviderIds").get("MusicBrainzTrackId")
                
        genres = " / ".join(MBitem.get("Genres"))
        artists = " / ".join(MBitem.get("Artists"))
        track = MBitem.get("IndexNumber")
        duration = MBitem.get("RunTimeTicks", 0) / 10000000
        year = MBitem.get("ProductionYear")
        bio = utils.convertEncoding(API().getOverview(MBitem))
        
        dateadded = None
        if MBitem.get("DateCreated"):
            dateadded = MBitem["DateCreated"].split('.')[0].replace('T', " ")
        
        if userData.get("LastPlayedDate") != None:
            lastplayed = userData.get("LastPlayedDate")
        else:
            lastplayed = None
        
        playcount = None
        if userData.get("PlayCount"):
            playcount = int(userData.get("PlayCount"))
            
        #get the album
        albumid = None
        if MBitem.get("AlbumId"):
            cursor.execute("SELECT kodi_id FROM emby WHERE emby_id = ?",(MBitem.get("AlbumId"),))
            result = cursor.fetchone()
            if result:
                albumid = result[0]
        if albumid == None:
            #no album = single in kodi, we need to create a single album for that
            cursor.execute("select coalesce(max(idAlbum),0) as albumid from album")
            albumid = cursor.fetchone()[0]
            albumid = albumid + 1
            if kodiVersion == 15:
                pathsql="insert into album(idAlbum, strArtists, strGenres, iYear, dateAdded, strReleaseType) values(?, ?, ?, ?, ?, ?)"
                cursor.execute(pathsql, (albumid, artists, genres, year, dateadded, "single"))
            else:
                pathsql="insert into album(idAlbum, strArtists, strGenres, iYear, dateAdded) values(?, ?, ?, ?, ?)"
                cursor.execute(pathsql, (albumid, artists, genres, year, dateadded))
            #some stuff here to get the album linked to artists
            for artist in MBitem.get("ArtistItems"):
                cursor.execute("SELECT kodi_id FROM emby WHERE emby_id = ?",(artist["Id"],))
                result = cursor.fetchone()
                if result:
                    artistid = result[0]
                    sql="INSERT OR REPLACE into album_artist(idArtist, idAlbum, strArtist) values(?, ?, ?)"
                    cursor.execute(sql, (artistid, albumid, artist["Name"]))

        if PlayUtils().isDirectPlay(MBitem):
            playurl = PlayUtils().directPlay(MBitem)
            #use the direct file path
            if "\\" in playurl:
                filename = playurl.rsplit("\\",1)[-1]
                path = playurl.replace(filename,"")
            elif "/" in playurl:
                filename = playurl.rsplit("/",1)[-1]
                path = playurl.replace(filename,"")
        else:
            #for transcoding we just use the server's streaming path because I couldn't figure out how to set the plugin path in the music DB
            path = server + "/Audio/%s/" %MBitem["Id"]
            filename = "stream.mp3"

        #get the path
        cursor.execute("SELECT idPath as pathid FROM path WHERE strPath = ?",(path,))
        result = cursor.fetchone()
#.........这里部分代码省略.........
开发者ID:SupDor,项目名称:Emby.Kodi,代码行数:103,代码来源:WriteKodiMusicDB.py

示例12: addOrUpdateSongToKodiLibrary

# 需要导入模块: from API import API [as 别名]
# 或者: from API.API import get [as 别名]
    def addOrUpdateSongToKodiLibrary(self, MBitem, connection, cursor):

        kodiVersion = self.kodiversion
        
        embyId = MBitem["Id"]
        
        # If the item already exist in the local Kodi DB we'll perform a full item update
        # If the item doesn't exist, we'll add it to the database
        
        cursor.execute("SELECT kodi_id FROM emby WHERE emby_id = ?", (embyId,))
        try:
            songid = cursor.fetchone()[0]
        except:
            songid = None
        
        timeInfo = API().getTimeInfo(MBitem)
        userData = API().getUserData(MBitem)
        genres = MBitem.get('Genres')

        ##### The song details #####
        playcount = userData.get('PlayCount')
        lastplayed = userData.get('LastPlayedDate')
        dateadded = API().getDateCreated(MBitem)
        checksum = API().getChecksum(MBitem)
        
        name = MBitem['Name']
        musicBrainzId = API().getProvider(MBitem, "musicBrainzTrackId")
        genre = " / ".join(genres)
        artists = " / ".join(MBitem.get('Artists'))
        track = MBitem.get('IndexNumber')
        year = MBitem.get('ProductionYear')
        bio = API().getOverview(MBitem)
        duration = timeInfo.get('TotalTime')

        # Get the path and filename
        playurl = PlayUtils().directPlay(MBitem)

        try:
            path, filename = ntsplit(playurl)
            if "/" in playurl:
                path = "%s/" % path
            elif "\\" in playurl:
                path = "%s\\" % path
        except: # playurl returned false - using server streaming path, because could not figure out plugin paths for music DB
            playurl = PlayUtils().directstream(MBitem, self.server, embyId, "Audio")
            filename = "stream.mp3"
            path = playurl.replace(filename, "")


        # Validate the path in database
        cursor.execute("SELECT idPath as pathid FROM path WHERE strPath = ?", (path,))
        try:
            pathid = cursor.fetchone()[0]
        except:
            cursor.execute("select coalesce(max(idPath),0) as pathid from path")
            pathid = cursor.fetchone()[0] + 1
            query = "INSERT INTO path(idPath, strPath) values(?, ?)"
            cursor.execute(query, (pathid, path))

        # Get the album
        cursor.execute("SELECT kodi_id FROM emby WHERE emby_id = ?", (MBitem.get("AlbumId"),))
        try:
            albumid = cursor.fetchone()[0]
        except:
            # No album found, create a single's album
            cursor.execute("select coalesce(max(idAlbum),0) as albumid from album")
            albumid = cursor.fetchone()[0] + 1
            if kodiVersion == 15 or kodiVersion == 16:
                # Kodi Isengard
                query = "INSERT INTO album(idAlbum, strArtists, strGenres, iYear, dateAdded, strReleaseType) values(?, ?, ?, ?, ?, ?)"
                cursor.execute(query, (albumid, artists, genre, year, dateadded, "single"))
            else:
                # Kodi Gotham and Helix
                query = "INSERT INTO album(idAlbum, strArtists, strGenres, iYear, dateAdded) values(?, ?, ?, ?, ?)"
                cursor.execute(query, (albumid, artists, genre, year, dateadded))

            # Link album to artists
            for artist in MBitem['ArtistItems']:
                cursor.execute("SELECT kodi_id FROM emby WHERE emby_id = ?", (artist['Id'],))
                try:
                    artistid = cursor.fetchone()[0]
                except: pass
                else:
                    query = "INSERT OR REPLACE INTO album_artist(idArtist, idAlbum, strArtist) values(?, ?, ?)"
                    cursor.execute(query, (artistid, albumid, artist['Name']))


        ##### UPDATE THE SONG #####
        if songid:
            self.logMsg("UPDATE song to Kodi library, Id: %s - Title: %s" % (embyId, name), 1)

            query = "UPDATE song SET idAlbum = ?, strArtists = ?, strGenres = ?, strTitle = ?, iTrack = ?, iDuration = ?, iYear = ?, strFilename = ?, strMusicBrainzTrackID = ?, iTimesPlayed = ?, lastplayed = ? WHERE idSong = ?"
            cursor.execute(query, (albumid, artists, genre, name, track, duration, year, filename, musicBrainzId, playcount, lastplayed, songid))

            # Update the checksum in emby table
            query = "UPDATE emby SET checksum = ? WHERE emby_id = ?"
            cursor.execute(query, (checksum, embyId))

        ##### OR ADD THE SONG #####
        else:
#.........这里部分代码省略.........
开发者ID:jurmb84,项目名称:Emby.Kodi,代码行数:103,代码来源:WriteKodiMusicDB.py


注:本文中的API.API.get方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。