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


Python gmusicapi.Webclient类代码示例

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


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

示例1: gMusicClient

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,代码行数:60,代码来源:PlayMusicCL.py

示例2: login

def login():
	print "Request : Login"
	token = request.form['token']
	mm = Webclient()
	ok, token2 = mm.login_token(token)
	if ok :
		return token2
开发者ID:scleriot,项目名称:syncgmusic,代码行数:7,代码来源:server.py

示例3: login_to_google_music

def login_to_google_music(user):
    api = Webclient()
    apiMobile = Mobileclient()
    attempts = 0

    while attempts < 3:
        if user == None:
            user = raw_input("Google username or email: ")

        # Try to read the password from a file
        # If file doesn't exist, ask for password
        # This is useful for 2-step authentication only
        # Don't store your regular password in plain text!
        try:
            pw_file = open("pass.txt")
            password = pw_file.readline()
            print "Reading password from pass.txt."
        except IOError:
            password = getpass()

        print "\nLogging in..."
        if apiMobile.login(user,password) and api.login(user, password):
            return api, apiMobile
        else:
            print "Login failed."
            # Set the username to none so it is prompted to be re-entered on the next loop iteration
            user = None
            attempts += 1

    print str(attempts) + " failed login attempts. Giving up."
    exit(0)
开发者ID:nimai,项目名称:Google-Music-Playlist-Sync,代码行数:31,代码来源:google-music-playlist-sync.py

示例4: __init__

class Player:

	def __init__(self, library_manager):
		pygame.init()
		pygame.mixer.init()

		self.library_manager = library_manager
		self.webapi = Webclient()

		try:
			self.webapi.login(setting.GUSER, setting.GPASS)
		except:
			sys.stderr.write('Problem with authentication on Google server\n')


	def play(self, songId):
		f = open('tostream.mp3', 'w')
		song = self.webapi.get_stream_audio(songId)
		f.write(song)
		f.close()
		#songFile = StringIO.StringIO(song)
		
		pygame.mixer.music.load('tostream.mp3')
		pygame.mixer.music.play()

		print('streaming audio: ' + songId)

		while pygame.mixer.music.get_busy():
			pygame.time.Clock().tick(10)
开发者ID:PaoloCifariello,项目名称:RaspGMusic,代码行数:29,代码来源:player.py

示例5: start

    def start(self):
        """
        Start the sync
        """

        api = Webclient()
        apim = Mobileclient()
        apim.login(self.email, self.password)

        try:
            api.login(self.email, self.password)
            xml_file = open('self.xml_file', 'r').read()

            print "Parsing songs from iTunes XML file..."
            itunes_song_list = self.__get_itunes_song_list(xml_file)
            print "iTunes XML file parsing complete"

            print "Retrieving songs from Google Music..."
            gmusic_song_list = self.__get_gmusic_song_list(apim)
            print "Google Music song retrieval complete"

            print "Computing the intersection of the song lists..."
            song_list = self.__get_intersection(gmusic_songs=gmusic_song_list, itunes_songs=itunes_song_list,
                                                only_no_rating=self.only_no_rating)
            print "Song list intersection computed"

            print "Syncing song ratings..."
            self.__sync_song_ratings(api, song_list)
            print "Song ratings sync complete!"

        except CallFailure:
            print "Error: Couldn't log in to Google Music!"
        except IOError:
            print "Error: iTunes XML file not found"
开发者ID:drgould,项目名称:gmusic-ratings-sync,代码行数:34,代码来源:ratingssync.py

示例6: __init__

class gmObject:
    
    def __init__(self):
        self.mc = Mobileclient()
        self.wc = Webclient()
        self.mm = Musicmanager()
    
    def login(self, username, password):
        error.e = 0
        
        if not self.mc.login(username, password):
            gmtPrintV("gmObject.login: Wrong username or password (or no internet connection)")
            error.e = error.LOGIN_FAILED
            return
        
        if not self.wc.login(username, password):
            gmtPrintV("gmObject.login: Wrong username or password (or no internet connection)")
            error.e = error.LOGIN_FAILED
            return
        
        if not self.mm.login(config.cred_path):
            gmtPrintV("gmObject.login: Wrong credentials (or no internet connection)")
            error.e = error.LOGIN_FAILED
            return
        
    def logout(self):
        error.e = 0
        
        try:
            self.mc.logout()
            self.wc.logout()
            self.mm.logout()
        except:
            gmtPrintV("gmObject.logout: Logout failed")
            error.e = error.LOGOUT_FAILED
开发者ID:Shadowigor,项目名称:gmusic-tools,代码行数:35,代码来源:gmobject.py

示例7: authenticate

    def authenticate(self, USER_DATA_FILENAME):
        self.G_username = raw_input("Google Play Account Email: ")
        self.G_password = getpass.getpass("Google Play Account Pass: ")

        Deviceclient = Webclient()
        Deviceclient.login(self.G_username, self.G_password)

        DList = Deviceclient.get_registered_devices()

        for device in DList:
            if device['type'] == "PHONE":
                self.GOOGLE_DEVICE_ID = device["id"]
                if self.GOOGLE_DEVICE_ID[:2] == '0x':
                    self.GOOGLE_DEVICE_ID = self.GOOGLE_DEVICE_ID[2:]
                break

        self.S_username = raw_input("Soundcloud Account Username: ")
        self.S_password = getpass.getpass("Soundcloud Account Password: ")
        self.SOUNDCLOUD_CLIENT_ID = raw_input("Soundcloud Client ID: ")
        self.SOUNDCLOUD_CLIENT_SECRET_ID = raw_input("Soundcloud Secret Client ID: ")

        File = open(USER_DATA_FILENAME, 'w+')
        File.write(self.encode(self.enc_key, self.G_username) + '\n')
        File.write(self.encode(self.enc_key, self.G_password) + '\n')
        File.write(self.encode(self.enc_key, self.S_username) + '\n')
        File.write(self.encode(self.enc_key, self.S_password) + '\n')
        File.write(self.GOOGLE_DEVICE_ID + '\n')
        File.write(self.SOUNDCLOUD_CLIENT_ID + '\n')
        File.write(self.SOUNDCLOUD_CLIENT_SECRET_ID + '\n')
        File.close()
开发者ID:nightfire8199,项目名称:project-hermes,代码行数:30,代码来源:User.py

示例8: initthread

def initthread(mwc, mc):
    library = mwc.library
    mwc.status_msg("Initializing..")
    wc = Webclient()
    wc.login(config.user, config.password)
    devices = wc.get_registered_devices()

    mwc.status_msg("Retrieving usable device ID..")
    for dev in devices:
        if dev["type"] == "PHONE":
            # strip 0x if present
            config.devid = dev["id"][2:] if dev["id"].startswith("0x") else dev["id"]
            print("Found a usable device id: " + config.devid)
            break
    else:
        md = Gtk.MessageDialog(parent=mwc.ui, buttons=Gtk.ButtonsType.OK, message_type=Gtk.MessageType.ERROR, message_format="Could not find a usable device id. Please run the Google Play Music app at least once on your phone.")
        GLib.idle_add(modal_dialog_func, md)

    mc.login(config.user, config.password)
    player = Player(mc, config.devid)
    mwc.setplayer(player)

    def getalbumart(structure):
        if "albumArtRef" in structure:
            a = structure["albumArtRef"]
            for entry in a:
                if "url" in entry:
                    return entry["url"]
        return None

    mwc.status_msg("Retrieving library..")
    songs = mc.get_all_songs()
    for song in songs:
        track = Track(song["id"], song["title"], song["artist"], song["album"],
                      song["trackNumber"] if "trackNumber" in song else 0)
        track.albumarturl = getalbumart(song)
        library.add_track(track)

    mwc.status_msg("Retrieving playlists..")
    playlists = mc.get_all_user_playlist_contents()


    for x in playlists:
        tracks = []
        for t in x["tracks"]:
            if t["trackId"].startswith("T"): # all access track
                trackEntry = t["track"]
                track = Track(t["trackId"], trackEntry["title"], trackEntry["artist"], trackEntry["album"], trackEntry["trackNumber"])
                track.albumarturl = getalbumart(trackEntry)
                tracks.append(track)

            else:
                libtrack = library.find_track(t["trackId"])
                if libtrack is not None:
                    tracks.append(libtrack)
        library.add_list(Playlist(x["name"], tracks))

    mwc.status_msg("Idle")
开发者ID:hrkfdn,项目名称:gomusic,代码行数:58,代码来源:main.py

示例9: setup_web_api

def setup_web_api():
    global web_api
    web_api = Webclient()

    web_logged_in = web_api.login(username, password)

    if not web_logged_in:
        print "Failed to log in to the web API, ensure your details are correct and try again."
        sys.exit(0)
开发者ID:MorrisonCole,项目名称:google-music-helper,代码行数:9,代码来源:authentication.py

示例10: download_song

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,代码行数:9,代码来源:server.py

示例11: __init__

    def __init__(self):
        self.main      = sys.modules["__main__"]
        self.xbmcgui   = self.main.xbmcgui
        self.xbmc      = self.main.xbmc
        self.settings  = self.main.settings

        if self.getDevice():
            self.gmusicapi = Mobileclient(debug_logging=False,validate=False)
        else:
            self.gmusicapi = Webclient(debug_logging=False,validate=False)
开发者ID:Mondego,项目名称:pyreco,代码行数:10,代码来源:allPythonContent.py

示例12: __init__

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,代码行数:10,代码来源:user.py

示例13: main

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,代码行数:11,代码来源:playball.py

示例14: GoogleMusic

class GoogleMusic(object):
    def __init__(self):
        self.webclient = Webclient()
        self.mobileclient = Mobileclient()

    def is_authenticated(self):
        if not self.webclient.is_authenticated():
            if self.mobileclient.is_authenticated():
                return True

        return False

    def login(self, username, password):
        if not self.is_authenticated():
            try:
                self.mobileclient.login(username, password, Mobileclient.FROM_MAC_ADDRESS)
                self.webclient.login(username, password)
            except Exception as e:
                raise Exception('Couldn\'t log into Google Music: ' + e.message)

    def search(self, query, kind):
        if self.is_authenticated():
            results = self.mobileclient.search(query)[kind + '_hits']

            return results

    def get_track(self, store_id):
        return self.mobileclient.get_track_info(store_id)

    def save_stream(self, track, destination):
        if self.is_authenticated():
            with open(destination, 'w+b') as stream_file:
                url = self.mobileclient.get_stream_url(track.get('storeId'))

                stream_file.truncate(0)
                stream_file.seek(0, 2)
                audio = self.webclient.session._rsession.get(url).content
                stream_file.write(audio)

            tag = easyid3.EasyID3()
            tag['title'] = track.get('title').__str__()
            tag['artist'] = track.get('artist').__str__()
            tag['album'] = track.get('album').__str__()
            tag['date'] = track.get('year').__str__()
            tag['discnumber'] = track.get('discNumber').__str__()
            tag['tracknumber'] = track.get('trackNumber').__str__()
            tag['performer'] = track.get('albumArtist').__str__()
            tag.save(destination)

            tag = mp3.MP3(destination)
            tag.tags.add(
                id3.APIC(3, 'image/jpeg', 3, 'Front cover', urllib.urlopen(track.get('albumArtRef')[0].get('url')).read())
            )
            tag.save()
开发者ID:jonjomckay,项目名称:jenna,代码行数:54,代码来源:googlemusic.py

示例15: _get_client

def _get_client(clienttype, user):
    global CLIENTS
    try:
        return CLIENTS[clienttype][user]
    except KeyError:
        client = Webclient() if clienttype == 'webclient' else Mobileclient()
        LOGGER.debug("Logging in %s for %s", clienttype, user.name)
        success = client.login(user.username, user.password)
        if not success:
            raise Exception("Failed to log in as {} to webclient".format(user))
        CLIENTS[clienttype][user] = client
        return client
开发者ID:EliRibble,项目名称:urania,代码行数:12,代码来源:connection.py


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