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


Python Webclient.get_all_songs方法代码示例

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


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

示例1: GMusic

# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import get_all_songs [as 别名]
class GMusic(object):
    def __init__(self):
        self.webclient = Webclient(debug_logging=False)
        self.email = None
        self.password = None
        self.authenticated = False
        self.all_songs = list()
        self.playlists = list()

    def authenticate(self, email=None, password=None):
        if email:
            self.email = email
        if password:
            self.password = password

        try:
            Log("AUTHENTICATING!!!!111")
            self.authenticated = self.webclient.login(self.email, self.password)
        except AlreadyLoggedIn:
            self.authenticated = True


        return self.authenticated

    def get_all_songs(self):
        try:
            self.all_songs = self.webclient.get_all_songs()
        except NotLoggedIn:
            if self.authenticate():
                self.all_songs = self.webclient.get_all_songs()
            else:
                Log("LOGIN FAILURE")
                return

        return self.all_songs

    def get_all_playlists(self):
        try:
            self.playlists = self.webclient.get_all_playlist_ids()
        except NotLoggedIn:
            if self.authenticate():
                self.playlists = self.webclient.get_all_playlist_ids()
            else:
                Log("LOGIN FAILURE")
                return

        return self.playlists

    def get_stream_url(self, song_id):
        try:
            stream_url = self.webclient.get_stream_url(song_id)
        except NotLoggedIn:
            if self.authenticate():
                stream_url = self.webclient.get_stream_url(song_id)
            else:
                Log("LOGIN FAILURE")
                return

        return stream_url
开发者ID:ceekee,项目名称:GoogleMusic.bundle,代码行数:61,代码来源:__init__.py

示例2: main

# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import get_all_songs [as 别名]
def main():
	api = Webclient()
	loggedIn = connect(api, raw_input('Username: '), getpass.getpass('Password: '))

	if not loggedIn:
		print "Authorization unsuccessful"
		sys.exit(0)
	else:
		print "Authorization successful!"

	print api.get_all_songs()[0]
开发者ID:Widdershin,项目名称:Playball,代码行数:13,代码来源:playball.py

示例3: gMusicClient

# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import get_all_songs [as 别名]
class gMusicClient(object):
	logged_in = False
	api = None
	playlists = dict()
	library = dict()

	def __init__(self, email, password):
		self.api = Webclient()
		logged_in = False
		attempts = 0
		if len(password) is 0:
			password = getpass("Google password:")
		while not self.logged_in and attempts < 3:
			self.logged_in = self.api.login(email, password)
			attempts += 1

	def __del__(self):
		self.api.logout()

	def updateLocalLib(self):
		songs = list()
		self.library = dict()
		self.playlists = dict()
		songs = self.api.get_all_songs()
		for song in songs:
			song_title = song["title"]
			if song["artist"] == "":
				song_artist = "Unknown Artist"
			else:
				song_artist = song["artist"]
			if song["album"] == "":
				song_album = "Unknown Album"
			else:
				song_album = song["album"]
			if not (song_artist in self.library):
				albums_dict = dict()
				self.library[song_artist] = albums_dict
			if not (song_album in self.library[song_artist]):
				song_list = list()
				self.library[song_artist][song_album] = song_list
			self.library[song_artist][song_album].append(song)
		plists = self.api.get_all_playlist_ids(auto=True, user=True)
		for u_playlist, u_playlist_id in plists["user"].iteritems():
			self.playlists[u_playlist] = self.api.get_playlist_songs(u_playlist_id[0])
		self.playlists["Thumbs Up"] = [song for song in songs if song['rating'] == 5]

	def getSongStream(self, song):
		return self.api.get_stream_urls(song["id"])

	def getStreamAudio(self, song):
		return self.api.get_stream_audio(song["id"])

	def thumbsUp(self, song):
		try:
			song["rating"] = 5
			song_list = [song]
			self.api.change_song_metadata(song_list)
			print "Gave a Thumbs Up to {0} by {1} on Google Play.".format(song["title"].encode("utf-8"), song["artist"].encode("utf-8"))
		except:
			print "Error giving a Thumbs Up on Google Play."
开发者ID:vulcanfk,项目名称:PlayMusicCL,代码行数:62,代码来源:PlayMusicCL.py

示例4: download_song

# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import get_all_songs [as 别名]
def download_song():
	print "Request : Download url"
	mm = Webclient()
	token = request.form['token']
	songid = request.form['songid']
	mm.setToken(token)
	songs = mm.get_all_songs(incremental=False)
	url = mm.get_stream_url(songid)
	return url
开发者ID:scleriot,项目名称:syncgmusic,代码行数:11,代码来源:server.py

示例5: __init__

# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import get_all_songs [as 别名]
class User:
	def __init__(self, cshUsername, cshHomeDirectory):
		self.cshlibrary = []
		self.cshUsername = cshUsername
		self.cshHomeDirectory = cshHomeDirectory

	def playLogin(self, username, password):
		self.api = Webclient()
		self.api.login(username, password)
		self.playlibrary = self.api.get_all_songs()
开发者ID:gambogi,项目名称:PlaySoap,代码行数:12,代码来源:user.py

示例6: list

# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import get_all_songs [as 别名]
def list():
	mm = Webclient()
	token = request.form['token']
	mm.setToken(token)
	playlists = mm.get_all_playlist_ids()
	output = "["

	songs = mm.get_all_songs(incremental=False)
	output += "{'title': 'Full library', 'songs' : "
	output += json.dumps(songs)
	output += "},"

	for (key,values) in playlists['user'].items():
		for playlistid in values:
			output += "{ 'title':'"+key+"', 'songs' :"
			songs=mm.get_playlist_songs(playlistid)
			output += json.dumps(songs)
			output += "},"

	output += "]"

	return output
开发者ID:scleriot,项目名称:syncgmusic,代码行数:24,代码来源:server.py

示例7: MusicLibrary

# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import get_all_songs [as 别名]
class MusicLibrary(object):
    'Read information about your Google Music library'
    
    def __init__(self, username=None, password=None,
                 true_file_size=False, scan=True, verbose=0):
        self.verbose = False
        if verbose > 1:
            self.verbose = True

        self.__login_and_setup(username, password)
        if scan:
            self.rescan()
        self.true_file_size = true_file_size

    def rescan(self):
        self.__artists = {} # 'artist name' -> {'album name' : Album(), ...}
        self.__albums = [] # [Album(), ...]
        self.__aggregate_albums()

    def __login_and_setup(self, username=None, password=None):
        # If credentials are not specified, get them from $HOME/.gmusicfs
        if not username or not password:
            cred_path = os.path.join(os.path.expanduser('~'), '.gmusicfs')
            if not os.path.isfile(cred_path):
                raise NoCredentialException(
                    'No username/password was specified. No config file could '
                    'be found either. Try creating %s and specifying your '
                    'username/password there. Make sure to chmod 600.'
                    % cred_path)
            if not oct(os.stat(cred_path)[os.path.stat.ST_MODE]).endswith('00'):
                raise NoCredentialException(
                    'Config file is not protected. Please run: '
                    'chmod 600 %s' % cred_path)
            self.config = ConfigParser.ConfigParser()
            self.config.read(cred_path)
            username = self.config.get('credentials','username')
            password = self.config.get('credentials','password')
            if not username or not password:
                raise NoCredentialException(
                    'No username/password could be read from config file'
                    ': %s' % cred_path)
                
        self.api = GoogleMusicAPI(debug_logging=self.verbose)
        log.info('Logging in...')
        self.api.login(username, password)
        log.info('Login successful.')
        
    def __aggregate_albums(self):
        'Get all the tracks in the library, parse into artist and album dicts'
        all_artist_albums = {} # 'Artist|||Album' -> Album()
        log.info('Gathering track information...')
        tracks = self.api.get_all_songs()
        for track in tracks:
            # Prefer the album artist over the track artist if there is one:
            artist = track['albumArtistNorm']
            if artist.strip() == '':
                artist = track['artistNorm']
            # Get the Album object if it already exists:
            key = '%s|||%s' % (formatNames(artist), formatNames(track['albumNorm']))
            album = all_artist_albums.get(key, None)
            if not album:
                # New Album
                if artist == '':
                    artist = 'unknown'
                album = all_artist_albums[key] = Album(
                    self, formatNames(track['albumNorm']))
                self.__albums.append(album)
                artist_albums = self.__artists.get(artist, None)
                if artist_albums:
                    artist_albums[formatNames(album.normtitle)] = album
                else:
                    self.__artists[artist] = {album.normtitle: album}
                    artist_albums = self.__artists[artist]
            album.add_track(track)
        log.debug('%d tracks loaded.' % len(tracks))
        log.debug('%d artists loaded.' % len(self.__artists))
        log.debug('%d albums loaded.' % len(self.__albums))

    def get_artists(self):
        return self.__artists

    def get_albums(self):
        return self.__albums

    def get_artist_albums(self, artist):
        log.debug(artist)
        return self.__artists[artist]

    def cleanup(self):
        pass
开发者ID:jaduncan,项目名称:GMusicFS,代码行数:92,代码来源:gmusicfs.py

示例8: Music

# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import get_all_songs [as 别名]
class Music(Command):
    def __init__(self, credentials):
        self.keywords = ['music']
        self.gmusic = Webclient()
        self.gmusic.login(credentials['u'], credentials['pass'])
        self.currentPlaylist = list()
        self.currentSong = dict()
        self.isPlaying = False
        self.playlistIndex = 0
        self.updateSongs()
        self.player = PCM()

    def updateSongs(self):
        self.playlists = self.gmusic.get_all_playlist_ids()["user"]
        if len(self.currentPlaylist) == 0:
            self.currentPlaylist= self.gmusic.get_playlist_songs(self.playlists['Megalist'][0])
            random.shuffle(self.currentPlaylist)

        if not self.currentSong:
            self.currentSong = self.currentPlaylist[self.playlistIndex]

        self.library = self.gmusic.get_all_songs()
            
    def play(self, cs = None):
        if cs == None:
            cs = self.currentPlaylist[self.playlistIndex]
        self.currentSong = cs
        self.isPlaying = True
#       self.player.write(self.gmusic.get_stream_audio(self.currentSong[u'id']))
        print 'play' + self.currentSong['title']

    def pause(self):
        self.isPlaying = False
        print 'pausing'

    def nextSong(self):
        self.playlistIndex += 1
        if self.playlistIndex >= len(self.currentPlaylist):
            self.playlistIndex = 0
            self.pause()
        else:
            self.play()

    def previousSong(self):
        self.playlistIndex -= 1
        if self.playlistIndex < 0:
            self.playlistIndex = 0
        self.play()

    def rickRoll(self):
        self.playlist = list()
        for song in self.library:
            if song['titleNorm'] == 'never gonna give you up':
                self.currentPlaylist = [song]
                self.playlistIndex = 0
                self.play()

    def playSong(self, songname):
        for song in self.library:
            if songname in song['titleNorm']:
                self.play(cs = song)
                self.currentPlaylist = [song]
#               tempplaylist = self.gmusic.get_playlist_songs(self.playlists['Megalist'][0])
#               random.shuffle(tempplaylist)
#               self.currentPlaylist += tempplaylist
                break
    def playAlbum(self, albumname):
        tempplaylist = list()
        for song in self.library:
            if albumname in song["albumNorm"] or albumname in song["album"]:
                tempplaylist += [song]
        if len(tempplaylist) > 0:
            self.currentPlaylist = sorted(tempplaylist, key=lambda k: k['track'])
            self.play()

    def playArtist(self, artistname):
        tempplaylist = list()
        for song in self.library:
            if artistname in song["artistNorm"] or artistname in song["artist"]:
                tempplaylist += [song]    
        if len(templaylist) > 0:
            self.currentPlaylist = tempplaylist
            random.shuffle(self.currentPlaylist)
            self.playlistIndex = 0
            self.play()

    def playPlaylist(self, playlistname):
        self.currentPlaylist = self.gmusic.get_playlist_songs(self.playlists[playlistname][0])
        random.shuffle(self.currentPlaylist)
        self.playlistIndex = 0
        self.play()

    def run(self, commandlist):
        if len(commandlist) == 0:
            if self.isPlaying == True:
                self.pause()
            else:
                self.play()
            print "music toggle"

#.........这里部分代码省略.........
开发者ID:rshipp,项目名称:Pixel-Interpreter-Framework,代码行数:103,代码来源:music.py

示例9: handle

# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import get_all_songs [as 别名]
    def handle(self, *args, **options):
        if GPLAY_PASS == "" or GPLAY_USER == "":
            self.stdout.write('Credentials not set up. Please edit settings.py')
            return

        api = Webclient()
        if not api.login(GPLAY_USER,GPLAY_PASS):
            self.stdout.write('Incorrect credentials, login failed')
            return

        self.stdout.write('Connected to Google Music, downloading data...')
        library = api.get_all_songs()
        self.stdout.write('Data downloaded!')
        self.stdout.write('Clearing DB...')
        cursor = connection.cursor()
        # This can take a long time using ORM commands on the Pi, so lets Truncate
        cursor.execute('DELETE FROM ' + Track._meta.db_table)
        cursor.execute('DELETE FROM ' + Album._meta.db_table)
        cursor.execute('DELETE FROM ' + Artist._meta.db_table)
        cursor.execute('DELETE FROM ' + Playlist._meta.db_table)
        cursor.execute('DELETE FROM ' + PlaylistConnection._meta.db_table)
        self.stdout.write('Parsing new data...')

        # Easier to keep track of who we've seen like this...
        artists = []
        albums = []

        for song in library:
            track = Track()

            if song['albumArtist'] == "":
                if song['artist'] == "":
                    a = "Unknown Artist"
                else:
                    a = song['artist']
            else:
                a = song['albumArtist']

            if a not in artists:
                artist = Artist()
                artist.name = a
                try:
                    artist.art_url = song['artistImageBaseUrl']
                except:
                    artist.art_url = ""
                artist.save()
                artists.append(a)
                self.stdout.write('Added artist: '+ a)
            else:
                artist = Artist.objects.get(name=a)
            track.artist = artist

            if song['album'] not in albums:
                album = Album()
                album.name = song['album']
                album.artist = artist
                try:
                    album.art_url = song['albumArtUrl']
                except:
                    album.art_url = ""
                album.save()
                albums.append(song['album'])
            else:
                album = Album.objects.get(name=song['album'])
            track.album = album

            track.name = song['title']
            track.stream_id = song['id']
            try:
                track.track_no = song['track']
            except:
                track.track_no = 0
            track.save()

        self.stdout.write('All tracks saved!')
        self.stdout.write('Getting Playlists...')
        playlists = api.get_all_playlist_ids(auto=False, user=True)
        self.stdout.write('Saving playlists...')
        for name in playlists['user']:
            for pid in playlists['user'][name]:
                p = Playlist()
                p.pid = pid
                p.name = name
                p.save()

        for playlist in Playlist.objects.all():
            self.stdout.write('Getting playlist contents for ' + playlist.name)
            songs = api.get_playlist_songs(playlist.pid)
            for song in songs:
                track = Track.objects.get(stream_id=song['id'])
                pc = PlaylistConnection()
                pc.playlist = playlist
                pc.track = track
                pc.save()

        self.stdout.write('Library saved!')
开发者ID:kambiz,项目名称:play-pi,代码行数:98,代码来源:init_gplay.py

示例10: Pygmy

# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import get_all_songs [as 别名]

#.........这里部分代码省略.........
            return 0
        else:
            return 1

    def on_song_activate( self, widget, path, col ):
        # set the player state to null
        self.player.set_state( Gst.State.NULL )
        # set the player uri to the activated song url
        # HEYYYYYY
        self.player.set_property( "uri", self.api.get_stream_urls( self.song_store[ path ][ 1 ] )[ 0 ] )
        # set the player state to playing
        self.player.set_state( Gst.State.PLAYING )

    def add_artist_to_store( self, artist ):
        if not artist in self.artist_dictionary:
            self.artist_dictionary[ artist ] = 0
            
        self.artist_dictionary[ artist ] += 1

    def add_song_to_store( self, track ):
        this_artist = track[ "artist" ] if not track[ "artist" ] == "" else "Unknown"

        self.add_artist_to_store( this_artist )

        # format the time to minutes:seconds and remove the leading 0
        time_string = re.sub(
            "^0", "",
            time.strftime( "%H:%M:%S", time.gmtime( int( track[ "durationMillis" ] ) / 1000 ) )
        )

        self.song_store.append([
            "",
            track["id"],
            track["track"],
            track["title"] if not track[ "title" ] == "" else "Unknown",
            this_artist,
            track["album"] if not track[ "album" ] == "" else "Unknown",
            str( track[ "year" ] if not track[ "year" ] == 0 else "" ),
            str( time_string )
        ])

    def find_songs( self ):
        if not self.api.is_authenticated() == True:
            return

        self.library = self.api.get_all_songs()

        for track in self.library:
            self.add_song_to_store( track )

        for artist in self.artist_dictionary:
            self.artist_store.append([
                artist + " (" + str( self.artist_dictionary[ artist ] ) + ")"
            ])

        self.artist_store.append([
            "All " + str( len( self.artist_dictionary ) ) + " artists (" + str( len( self.song_store ) ) + ")"
        ])

        self.show_all()

        # parse through every directory listed in the library
        #for directory in self.directories:
            # parse through all sub-folders looking for audio audio files
            #for r,d,f in os.walk( directory ):
                #for filename in f:
                    # mime = mimetypes.guess_type( filename )
                    #mime = magic.from_file( os.path.join( r, filename ), mime = True )
                    #print(mime)
                    # make sure mime-type is not None, otherwise the match will throw an error on some files
                    #if not mime == None:
                        #match = re.match( "^audio", mime )
                        #if match:
                            # it's an audio file, add it to the library even though we're not sure gstreamer can play it
                            #self.add_song_to_store( r, filename )

    def get_image( self, icon ):
        image = Gtk.Image()
        image.set_from_stock( icon, Gtk.IconSize.BUTTON )
        return image

    def play_pause( self, widget ):
        if self.playing == False:
            #filepath = self.entry.get_text()
            #if os.path.isfile(filepath):
            self.playing = True
            self.button_stop.set_sensitive( True )
            image = self.get_image( Gtk.STOCK_MEDIA_PAUSE )
            #self.player.set_property("uri", "file://" + filepath)
            #self.player.set_state(gst.STATE_PLAYING)
        else:
            self.playing = False
            image = self.get_image( Gtk.STOCK_MEDIA_PLAY )
        self.button_play.set_image( image )

    def do_stop( self, w ):
        self.button_play.set_image( self.get_image( Gtk.STOCK_MEDIA_PLAY ) )
        #self.player.set_state(gst.STATE_NULL)
        self.playing = False
        self.button_stop.set_sensitive( False )
开发者ID:kvonflotow,项目名称:pygmy,代码行数:104,代码来源:pygmy.py

示例11: GoogleMusic

# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import get_all_songs [as 别名]
class GoogleMusic(RadiopieModule):
	def run(self):
		log.info("Google Music started")
		self._lcd.setFirst(" Google")
		self.__player = None
		self.__api = None
		self.__library = None
		self.loadConfiguration()
		self.googleMusicConnection()
		while not self._terminate.isSet():
			if(self._ok.isSet()):
				self._ok.clear()
				self.playCurrentSong()
			if(self._left.isSet()):
				self._left.clear()
				self._terminate.set()
			time.sleep(1)
		self.setdown()

	def googleMusicConnection(self):
		log.info("Login as user " + self.__user + " ...")
		self._lcd.setLast(" Login..")
		self.__api = Webclient()
		self.__api.login(self.__user, self.__password)
		log.info("Loading Library")
		self._lcd.setLast(" Loading")
		self.__library = self.__api.get_all_songs()
		self._lcd.setLast(" Ready")

	def playCurrentSong(self):
		log.info("Playing a song")
		if(self.__player == None):
			self.setup()
		else:
			self.__player.set_state(gst.STATE_NULL)
		self.__currentsong = self.__library[random.randint(0,len(self.__library))]
		self._lcd.setLast(self.__currentsong["title"].encode("utf-8"))
		url = self.__api.get_stream_urls(self.__currentsong["id"])
		self.__player.set_property("uri", url[0])
		self.__player.set_state(gst.STATE_PLAYING)
		log.info("Playing song " + self.__currentsong["title"] + " ... ")
	

	def setup(self):
		self.__player = gst.element_factory_make("playbin2", "player")
		bus = self.__player.get_bus()
		bus.add_signal_watch()
		bus.connect("message", self.on_status)

	def loadConfiguration(self):
		log.info("Loading settings from json ...")
		json_data = open('defaults.json')
		data = json.load(json_data)
		self.__user = data["google-music-user"]
		self.__password = data["google-music-password"]

	def setdown(self):
		self.__player.set_state(gst.STATE_NULL)

	def on_status(self, bus, message):
		t = message.type
		if(t == gst.MESSAGE_EOS):
			log.info("Song end")
			self.playCurrentSong()
		if(t == pygst.MESSAGE_ERROR):
			err, debug = message.parse_error()
			log.error(err)
			log.debug(debug)
			self.__player.set_state(gst.STATE_NONE)
	
	@staticmethod
	def getName():
		return "Google Music"
开发者ID:stetro,项目名称:radiopie,代码行数:75,代码来源:GoogleMusic.py

示例12: MusicSync

# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import get_all_songs [as 别名]
class MusicSync(object):
    def __init__(self, email=None, password=None):
        self.mm = Musicmanager()
        self.wc = Webclient()
        if not email:
            email = raw_input("Email: ")
        if not password:
            password = getpass()

        self.email = email
        self.password = password

        self.logged_in = self.auth()

        print "Fetching playlists from Google..."
        self.playlists = self.wc.get_all_playlist_ids(auto=False)
        print "Got %d playlists." % len(self.playlists['user'])
        print "Fetching songs from Google..."
        self.songs = self.wc.get_all_songs()
        print "Got %d songs." % len(self.songs)        

    def auth(self):
        self.logged_in = self.wc.login(self.email, self.password)
        if not self.logged_in:
            print "Login failed..."
            exit()

        print "Logged in as %s" % self.email
        
        if not os.path.isfile(OAUTH_FILEPATH):
            print "First time login. Please follow the instructions below:"
            self.mm.perform_oauth()
        self.logged_in = self.mm.login()
        if not self.logged_in:
            print "OAuth failed... try deleting your %s file and trying again." % OAUTH_FILEPATH
            exit()

        print "Authenticated"
        
    def sync_playlist(self, filename, remove_missing=False):
        filename = self.get_platform_path(filename)
        os.chdir(os.path.dirname(filename))
        title = os.path.splitext(os.path.basename(filename))[0]
        print "Syncing playlist: %s" % filename
        if title in self.playlists['user']:
            plid = self.playlists['user'][title][0]        
            goog_songs = self.wc.get_playlist_songs(plid)
            print "  %d songs already in Google Music playlist" % len(goog_songs)
            pc_songs = self.get_files_from_playlist(filename)
            print "  %d songs in local playlist" % len(pc_songs)
            
            # Sanity check max 1000 songs per playlist
            if len(pc_songs) > MAX_SONGS_IN_PLAYLIST:
                print "    Google music doesn't allow more than %d songs in a playlist..." % MAX_SONGS_IN_PLAYLIST
                print "    Will only attempt to sync the first %d songs." % MAX_SONGS_IN_PLAYLIST
                del pc_songs[MAX_SONGS_IN_PLAYLIST:]
    
            existing_files = 0
            added_files = 0
            failed_files = 0
            removed_files = 0
            fatal_count = 0
            # print "Google songs: %s" % goog_songs
            for fn in pc_songs:
                if self.file_already_in_list(fn, goog_songs):
                    existing_files += 1
                    continue
                print "  adding: %s" % os.path.basename(fn)
                online = self.find_song(fn)
                song_id = None
                if online:
                    song_id = online['id']
                    print "  already uploaded [%s]" % song_id
                else:
                    attempts = 0
                    result = []
                    while not result and attempts < MAX_UPLOAD_ATTEMPTS_PER_FILE:
                        print "  uploading... (may take a while)"
                        attempts += 1
                        try:
                            result = self.mm.upload(fn)
                        except (BadStatusLine, CannotSendRequest):
                            # Bail out if we're getting too many disconnects
                            if fatal_count >= MAX_CONNECTION_ERRORS_BEFORE_QUIT:
                               print "Too many disconnections - quitting. Please try running the script again."
                               exit()
    
                            print "Connection Error -- Reattempting login"
                            fatal_count += 1
                            self.wc.logout()
                            self.mm.logout()
                            result = []
                            time.sleep(STANDARD_SLEEP)
    
                        except:
                            result = []
                            time.sleep(STANDARD_SLEEP)
    
                    try:
                        if result[0]:
#.........这里部分代码省略.........
开发者ID:bmjsmith,项目名称:m3uGoogleMusicSync,代码行数:103,代码来源:musicsync.py


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