本文整理汇总了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."
示例2: login
def login():
print "Request : Login"
token = request.form['token']
mm = Webclient()
ok, token2 = mm.login_token(token)
if ok :
return token2
示例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)
示例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)
示例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"
示例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
示例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()
示例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")
示例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)
示例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
示例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)
示例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()
示例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]
示例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()
示例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