本文整理汇总了Python中gmusicapi.Webclient.login方法的典型用法代码示例。如果您正苦于以下问题:Python Webclient.login方法的具体用法?Python Webclient.login怎么用?Python Webclient.login使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类gmusicapi.Webclient
的用法示例。
在下文中一共展示了Webclient.login方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: authenticate
# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import login [as 别名]
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()
示例2: getDeviceId
# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import login [as 别名]
def getDeviceId(verbose=False):
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)
config = ConfigParser.ConfigParser()
config.read(cred_path)
username = config.get('credentials','username')
password = config.get('credentials','password')
if not username or not password:
raise NoCredentialException(
'No username/password could be read from config file'
': %s' % cred_path)
api = GoogleMusicWebAPI(debug_logging=verbose)
log.info('Logging in...')
api.login(username, password)
log.info('Login successful.')
for device in api.get_registered_devices():
if not device['name']:
device['name']='NoName'
if device['id'][1]=='x':
print '%s : %s' % (device['name'], device['id'])
示例3: __init__
# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import login [as 别名]
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)
示例4: start
# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import login [as 别名]
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"
示例5: initthread
# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import login [as 别名]
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")
示例6: __init__
# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import login [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()
示例7: GoogleMusic
# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import login [as 别名]
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()
示例8: __init__
# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import login [as 别名]
class UrlGetter:
def __init__(self, sck_path, user, passwd):
pygame.init()
pygame.mixer.init()
self.sck_path = sck_path
self.webapi = Webclient()
self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# Look if socket has been created
try:
os.remove(self.sck_path)
except OSError:
pass
# GMusic login
try:
self.webapi.login(user, passwd)
except:
sys.stderr.write('Problem with authentication on Google server\n')
self.init_socket()
def init_socket(self):
self.socket.bind(self.sck_path)
self.socket.listen(3)
while 1:
conn, addr = self.socket.accept()
self.manage_connection(conn)
def manage_connection(self, conn):
data = conn.recv(50)
if data:
try:
stream_url = self.webapi.get_stream_urls(data)
except exceptions.CallFailure:
conn.close()
return
conn.send(stream_url[0])
print('url_getter.py: Ottenuta URL -> ' + stream_url[0])
conn.close()
示例9: __init__
# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import login [as 别名]
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
示例10: login_to_google_music
# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import login [as 别名]
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)
示例11: gMusicClient
# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import login [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."
示例12: GMusic
# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import login [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
示例13: setup_web_api
# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import login [as 别名]
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)
示例14: get_deviceid
# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import login [as 别名]
def get_deviceid(self, username, password):
logger.warning(u'No mobile device ID configured. '
u'Trying to detect one.')
webapi = Webclient(validate=False)
webapi.login(username, password)
devices = webapi.get_registered_devices()
deviceid = None
for device in devices:
if device['type'] == 'PHONE' and device['id'][0:2] == u'0x':
# Omit the '0x' prefix
deviceid = device['id'][2:]
break
webapi.logout()
if deviceid is None:
logger.error(u'No valid mobile device ID found. '
u'Playing songs will not work.')
else:
logger.info(u'Using mobile device ID %s', deviceid)
return deviceid
示例15: initDevice
# 需要导入模块: from gmusicapi import Webclient [as 别名]
# 或者: from gmusicapi.Webclient import login [as 别名]
def initDevice(self):
device_id = self.settings.getSetting('device_id')
if not device_id:
self.main.log('Trying to fetch the device_id')
webclient = Webclient(debug_logging=False,validate=False)
self.checkCredentials()
username = self.settings.getSetting('username')
password = self.settings.getSetting('password')
webclient.login(username, password)
if webclient.is_authenticated():
devices = webclient.get_registered_devices()
for device in devices:
if device["type"] == "PHONE":
device_id = str(device["id"])
break
if device_id.lower().startswith('0x'): device_id = device_id[2:]
self.settings.setSetting('device_id',device_id)
self.main.log('device_id: '+device_id)