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:"******"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."
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
class GMusicSession(object): def __init__(self): super(GMusicSession, self).__init__() logger.info('Mopidy uses Google Music') self.api = Webclient() def login(self, username, password): if self.api.is_authenticated(): self.api.logout() try: self.api.login(username, password) except CallFailure as error: logger.error(u'Failed to login as "%s": %s', username, error) return self.api.is_authenticated() def logout(self): if self.api.is_authenticated(): return self.api.logout() else: return True def get_all_songs(self): if self.api.is_authenticated(): return self.api.get_all_songs() else: return {} def get_stream_url(self, song_id): if self.api.is_authenticated(): try: return self.api.get_stream_urls(song_id)[0] except CallFailure as error: logger.error(u'Failed to lookup "%s": %s', song_id, error) def get_all_playlist_ids(self): if self.api.is_authenticated(): return self.api.get_all_playlist_ids() else: return {} def get_playlist_songs(self, playlist_id): if self.api.is_authenticated(): return self.api.get_playlist_songs(playlist_id) else: return {}
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
def main(): parser = argparse.ArgumentParser( description='List all devices registered for Google Play Music') parser.add_argument('username', help='Your Google Play Music username') parser.add_argument('password', help='Your very secret password') args = parser.parse_args() api = Webclient(validate=False) if not api.login(args.username, args.password): print "Could not login to Google Play Music. Incorrect username or password." return for device in api.get_registered_devices(): print '%s | %s | %s | %s' % (device['name'], device.get('manufacturer'), device['model'], device['id']) api.logout()
def main(): parser = argparse.ArgumentParser(description = 'List all devices registered for Google Play Music') parser.add_argument('username', help = 'Your Google Play Music username') parser.add_argument('password', help = 'Your very secret password') args = parser.parse_args() api = Webclient(validate = False) if not api.login(args.username, args.password): print "Could not login to Google Play Music. Incorrect username or password." return for device in api.get_registered_devices(): print '%s | %s | %s | %s' % (device['name'], device.get('manufacturer'), device['model'], device['id']) api.logout()
def main(): api = Webclient() login(api) playlists = api.get_all_playlist_ids().pop('user') indexed_playlist_names = index_playlists(playlists) curlist = choose_playlist(api, indexed_playlist_names, playlists)[0] songs = api.get_playlist_songs(curlist) print songs curpos = 0 cursongid = songs[curpos]['id'] cursongurl = api.get_stream_url(cursongid) print cursongurl #cursong = play(cursongurl) while 1: if cursong.poll() is not None: curpos += 1 cursongid = songs[curpos]['id'] cursong = play(get_stream_url(cursongid)) c = getch() if (c == 'q'): api.logout() break
def main(): api = Webclient() login(api) playlists = api.get_all_playlist_ids().pop('user') indexed_playlist_names = index_playlists(playlists) curlist = choose_playlist(api, indexed_playlist_names, playlists)[0] songs = api.get_playlist_songs(curlist) print songs curpos = 0; cursongid = songs[curpos]['id'] cursongurl = api.get_stream_url(cursongid) print cursongurl #cursong = play(cursongurl) while 1: if cursong.poll() is not None: curpos += 1 cursongid = songs[curpos]['id'] cursong = play(get_stream_url(cursongid)) c = getch() if (c == 'q'): api.logout() break
class MusicSync(object): def __init__(self, email=None, password=None): self.mm = Musicmanager() self.wc = Webclient() self.mc = Mobileclient() 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.mc.get_all_user_playlist_contents() #self.playlists = self.mc.get_all_playlists() #self.playlists = self.wc.get_all_playlist_ids(auto=False) self.all_songs = self.mc.get_all_songs() #print "Got %d playlists." % len(self.playlists['user']) print "Got %d playlists containing %d songs." % (len( self.playlists), len(self.all_songs)) print "" def auth(self): self.logged_in = self.mc.login(self.email, self.password) #self.logged_in = self.wc.login(self.email, self.password) if not self.logged_in: print "Login failed..." exit() print "" print "Logged in as %s" % self.email print "" 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" print "" def sync_playlist(self, filename, remove_missing): #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 not in self.playlists['user']: #print " didn't exist... creating..." #self.playlists['user'][title] = [self.wc.create_playlist(title)] print "" plid = "" for pl in self.playlists: if pl['name'] == title: plid = pl['id'] goog_songs = pl['tracks'] if plid == "": print " didn't exist... creating..." plid = self.mc.create_playlist(self, title) #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) print "" # 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 for fn in pc_songs: if self.file_already_in_list(fn, goog_songs, self.all_songs): existing_files += 1 continue print "" print "Adding: %s" % os.path.basename(fn).encode('cp1252') #print "Adding: %s" % os.path.basename(fn) #online = False online = self.find_song(fn, goog_songs, self.all_songs) #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 "" print "Too many disconnections - quitting. Please try running the script again." print "" exit() print "Connection Error -- Reattempting login" fatal_count += 1 self.wc.logout() self.mc.logout() self.mm.logout() result = [] time.sleep(STANDARD_SLEEP) except: result = [] time.sleep(STANDARD_SLEEP) try: if result[0]: song_id = result[0].itervalues().next() else: song_id = result[1].itervalues().next() print " upload complete [%s]" % song_id except: print " upload failed - skipping" tag = self.get_id3_tag(fn) print " failed song:\t%s\t%s\t%s" % ( tag['title'].encode('cp1252'), tag['artist'].encode('cp1252'), tag['album'].encode('cp1252')) if not song_id: failed_files += 1 continue added = self.mc.add_songs_to_playlist(plid, song_id) time.sleep(.3) # Don't spam the server too fast... print " done adding to playlist" added_files += 1 if remove_missing: for g in goog_songs: for s in self.all_songs: if g['trackId'] == s['id']: print "" print "Removing: %s" % s['title'].encode('cp1252') self.mc.remove_entries_from_playlist(g['id']) #self.wc.remove_songs_from_playlist(plid, s.id) time.sleep(.3) # Don't spam the server too fast... removed_files += 1 print "" print "---" print "%d songs unmodified" % existing_files print "%d songs added" % added_files print "%d songs failed" % failed_files print "%d songs removed" % removed_files def get_files_from_playlist(self, filename): files = [] f = codecs.open(filename, encoding='cp1252') #f = codecs.open(filename, encoding='utf-8') for line in f: line = line.rstrip().replace(u'\ufeff', u'') if line == "" or line[0] == "#": continue path = os.path.abspath(self.get_platform_path(line)) if not os.path.exists(path): print "File not found: %s" % line continue files.append(path) f.close() return files def file_already_in_list(self, filename, goog_songs, all_songs): tag = self.get_id3_tag(filename) print "Searching for\t%s\t%s\t%s" % (tag['title'].encode('cp1252'), tag['artist'].encode('cp1252'), tag['album'].encode('cp1252')) i = 0 while i < len(goog_songs): for s in all_songs: if goog_songs[i]['trackId'] == s['id']: if self.tag_compare(s, tag): print "Found match\t%s\t%s\t%s" % ( s['title'].encode('cp1252'), s['artist'].encode('cp1252'), s['album'].encode('cp1252')) goog_songs.pop(i) return True i += 1 return False def get_id3_tag(self, filename): data = mutagen.File(filename, easy=True) r = {} if 'title' not in data: title = os.path.splitext(os.path.basename(filename))[0] print 'Found song with no ID3 title, setting using filename:' print ' %s' % title print ' (please note - the id3 format used (v2.4) is invisible to windows)' data['title'] = [title] data.save() r['title'] = data['title'][0] r['track'] = int(data['tracknumber'][0].split('/') [0]) if 'tracknumber' in data else 0 # If there is no track, try and get a track number off the front of the file... since thats # what google seems to do... # Not sure how google expects it to be formatted, for now this is a best guess if r['track'] == 0: m = re.match("(\d+) ", os.path.basename(filename)) if m: r['track'] = int(m.group(0)) r['artist'] = data['artist'][0] if 'artist' in data else '' r['album'] = data['album'][0] if 'album' in data else '' return r def find_song(self, filename, goog_songs, all_songs): tag = self.get_id3_tag(filename) print "Searching for\t%s\t%s\t%s" % (tag['title'].encode('cp1252'), tag['artist'].encode('cp1252'), tag['album'].encode('cp1252')) #results = self.wc.search(tag['title']) # NOTE - diagnostic print here to check results if you're creating duplicates #print results['song_hits'] #for r in goog_songs: #for r in results['song_hits']: for s in all_songs: #if r['trackId'] == s['id']: if self.tag_compare(s, tag): # TODO: add rough time check to make sure its "close" print "Found match\t%s\t%s\t%s" % ( s['title'].encode('cp1252'), s['artist'].encode('cp1252'), s['album'].encode('cp1252')) return s return None def tag_compare(self, g_song, tag): # If a google result has no track, google doesn't return a field for it if 'title' not in g_song: g_song['title'] = "" if 'artist' not in g_song: g_song['artist'] = "" if 'album' not in g_song: g_song['album'] = "" if 'track' not in g_song: g_song['track'] = 0 if (g_song['title'].lower() == tag['title'].lower() and g_song['artist'].lower() == tag['artist'].lower()) or\ (g_song['album'].lower() == tag['album'].lower() and g_song['title'].lower() == tag['title'].lower()) or\ (g_song['artist'].lower() == tag['artist'].lower() and g_song['album'].lower() == tag['album'].lower() and g_song['track'] == tag['track']): print "Partial match\t%s\t%s\t%s" % ( g_song['title'].encode('cp1252'), g_song['artist'].encode('cp1252'), g_song['album'].encode('cp1252')) return g_song['title'].lower() == tag['title'].lower() and\ g_song['artist'].lower() == tag['artist'].lower() and\ g_song['album'].lower() == tag['album'].lower() #and\ #g_song['track'] == tag['track'] def delete_song(self, sid): self.mc.delete_songs(sid) print "Deleted song by id [%s]" % sid def get_platform_path(self, full_path): # Try to avoid messing with the path if possible if os.sep == '/' and '\\' not in full_path: return full_path if os.sep == '\\' and '\\' in full_path: return full_path if '\\' not in full_path: return full_path return os.path.normpath(full_path.replace('\\', '/'))
class MusicSync(object): def __init__(self, email=None, password=None): self.mm = Musicmanager() self.wc = Webclient() self.mc = Mobileclient() 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.mc.get_all_user_playlist_contents() #self.playlists = self.mc.get_all_playlists() #self.playlists = self.wc.get_all_playlist_ids(auto=False) self.all_songs = self.mc.get_all_songs() #print "Got %d playlists." % len(self.playlists['user']) print "Got %d playlists containing %d songs." % (len(self.playlists), len(self.all_songs)) print "" def auth(self): self.logged_in = self.mc.login(self.email, self.password) #self.logged_in = self.wc.login(self.email, self.password) if not self.logged_in: print "Login failed..." exit() print "" print "Logged in as %s" % self.email print "" 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" print "" def sync_playlist(self, filename, remove_missing): #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 not in self.playlists['user']: #print " didn't exist... creating..." #self.playlists['user'][title] = [self.wc.create_playlist(title)] print "" plid = "" for pl in self.playlists: if pl['name'] == title: plid = pl['id'] goog_songs = pl['tracks'] if plid == "": print " didn't exist... creating..." plid = self.mc.create_playlist(self, title) #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) print "" # 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 for fn in pc_songs: if self.file_already_in_list(fn, goog_songs, self.all_songs): existing_files += 1 continue print "" print "Adding: %s" % os.path.basename(fn).encode('cp1252') #print "Adding: %s" % os.path.basename(fn) #online = False online = self.find_song(fn, goog_songs, self.all_songs) #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 "" print "Too many disconnections - quitting. Please try running the script again." print "" exit() print "Connection Error -- Reattempting login" fatal_count += 1 self.wc.logout() self.mc.logout() self.mm.logout() result = [] time.sleep(STANDARD_SLEEP) except: result = [] time.sleep(STANDARD_SLEEP) try: if result[0]: song_id = result[0].itervalues().next() else: song_id = result[1].itervalues().next() print " upload complete [%s]" % song_id except: print " upload failed - skipping" tag = self.get_id3_tag(fn) print " failed song:\t%s\t%s\t%s" % (tag['title'].encode('cp1252'), tag['artist'].encode('cp1252'), tag['album'].encode('cp1252')) if not song_id: failed_files += 1 continue added = self.mc.add_songs_to_playlist(plid, song_id) time.sleep(.3) # Don't spam the server too fast... print " done adding to playlist" added_files += 1 if remove_missing: for g in goog_songs: for s in self.all_songs: if g['trackId'] == s['id']: print "" print "Removing: %s" % s['title'].encode('cp1252') self.mc.remove_entries_from_playlist(g['id']) #self.wc.remove_songs_from_playlist(plid, s.id) time.sleep(.3) # Don't spam the server too fast... removed_files += 1 print "" print "---" print "%d songs unmodified" % existing_files print "%d songs added" % added_files print "%d songs failed" % failed_files print "%d songs removed" % removed_files def get_files_from_playlist(self, filename): files = [] f = codecs.open(filename, encoding='cp1252') #f = codecs.open(filename, encoding='utf-8') for line in f: line = line.rstrip().replace(u'\ufeff',u'') if line == "" or line[0] == "#": continue path = os.path.abspath(self.get_platform_path(line)) if not os.path.exists(path): print "File not found: %s" % line continue files.append(path) f.close() return files def file_already_in_list(self, filename, goog_songs, all_songs): tag = self.get_id3_tag(filename) print "Searching for\t%s\t%s\t%s" % (tag['title'].encode('cp1252'), tag['artist'].encode('cp1252'), tag['album'].encode('cp1252')) i = 0 while i < len(goog_songs): for s in all_songs: if goog_songs[i]['trackId'] == s['id']: if self.tag_compare(s, tag): print "Found match\t%s\t%s\t%s" % (s['title'].encode('cp1252'), s['artist'].encode('cp1252'), s['album'].encode('cp1252')) goog_songs.pop(i) return True i += 1 return False def get_id3_tag(self, filename): data = mutagen.File(filename, easy=True) r = {} if 'title' not in data: title = os.path.splitext(os.path.basename(filename))[0] print 'Found song with no ID3 title, setting using filename:' print ' %s' % title print ' (please note - the id3 format used (v2.4) is invisible to windows)' data['title'] = [title] data.save() r['title'] = data['title'][0] r['track'] = int(data['tracknumber'][0].split('/')[0]) if 'tracknumber' in data else 0 # If there is no track, try and get a track number off the front of the file... since thats # what google seems to do... # Not sure how google expects it to be formatted, for now this is a best guess if r['track'] == 0: m = re.match("(\d+) ", os.path.basename(filename)) if m: r['track'] = int(m.group(0)) r['artist'] = data['artist'][0] if 'artist' in data else '' r['album'] = data['album'][0] if 'album' in data else '' return r def find_song(self, filename, goog_songs, all_songs): tag = self.get_id3_tag(filename) print "Searching for\t%s\t%s\t%s" % (tag['title'].encode('cp1252'), tag['artist'].encode('cp1252'), tag['album'].encode('cp1252')) #results = self.wc.search(tag['title']) # NOTE - diagnostic print here to check results if you're creating duplicates #print results['song_hits'] #for r in goog_songs: #for r in results['song_hits']: for s in all_songs: #if r['trackId'] == s['id']: if self.tag_compare(s, tag): # TODO: add rough time check to make sure its "close" print "Found match\t%s\t%s\t%s" % (s['title'].encode('cp1252'), s['artist'].encode('cp1252'), s['album'].encode('cp1252')) return s return None def tag_compare(self, g_song, tag): # If a google result has no track, google doesn't return a field for it if 'title' not in g_song: g_song['title'] = "" if 'artist' not in g_song: g_song['artist'] = "" if 'album' not in g_song: g_song['album'] = "" if 'track' not in g_song: g_song['track'] = 0 if (g_song['title'].lower() == tag['title'].lower() and g_song['artist'].lower() == tag['artist'].lower()) or\ (g_song['album'].lower() == tag['album'].lower() and g_song['title'].lower() == tag['title'].lower()) or\ (g_song['artist'].lower() == tag['artist'].lower() and g_song['album'].lower() == tag['album'].lower() and g_song['track'] == tag['track']): print "Partial match\t%s\t%s\t%s" % (g_song['title'].encode('cp1252'), g_song['artist'].encode('cp1252'), g_song['album'].encode('cp1252')) return g_song['title'].lower() == tag['title'].lower() and\ g_song['artist'].lower() == tag['artist'].lower() and\ g_song['album'].lower() == tag['album'].lower() #and\ #g_song['track'] == tag['track'] def delete_song(self, sid): self.mc.delete_songs(sid) print "Deleted song by id [%s]" % sid def get_platform_path(self, full_path): # Try to avoid messing with the path if possible if os.sep == '/' and '\\' not in full_path: return full_path if os.sep == '\\' and '\\' in full_path: return full_path if '\\' not in full_path: return full_path return os.path.normpath(full_path.replace('\\', '/'))
while True: chosen_number = int(raw_input('Choose a playlist to export (enter the number): ')) if chosen_number < i and chosen_number >= 0: break else: print 'Error, try again' i = 1 for playlist in api.get_all_playlist_ids()['user']: if i == chosen_number: chosen_id = api.get_all_playlist_ids()['user'][playlist][0] chosen_name = playlist break else: i += 1 songs = [] for song in api.get_playlist_songs(chosen_id): songs.append(song['artist'] + ' - ' + song['album'] + ' - ' + song['name']) songs.sort(key=lambda s: s.lower()) f = open(os.path.join(os.path.dirname(__file__), playlist + '.txt'), "w") for song in songs: f.write(song.encode("utf-8") + "\n") api.logout() raw_input('Success! Press enter to exit.')
class GoogleMusicLogin(): 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) def checkCookie(self): # Remove cookie data if it is older then 7 days if self.settings.getSetting('cookie-date') != None and len( self.settings.getSetting('cookie-date')) > 0: if (datetime.now() - datetime( *time.strptime(self.settings.getSetting('cookie-date'), '%Y-%m-%d %H:%M:%S.%f')[0:6])).days >= 7: self.clearCookie() def checkCredentials(self): if not self.settings.getSetting('username'): self.settings.openSettings() def getApi(self): return self.gmusicapi def getDevice(self): return self.settings.getSetting('device_id') 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() self.main.log(repr(devices)) for device in devices: if device["type"] in ("PHONE", "IOS"): device_id = str(device["id"]) break if device_id: if device_id.lower().startswith('0x'): device_id = device_id[2:] self.settings.setSetting('device_id', device_id) self.main.log('Found device_id: ' + device_id) def clearCookie(self): self.settings.setSetting('logged_in', "") self.settings.setSetting('authtoken', "") self.settings.setSetting('cookie-xt', "") self.settings.setSetting('cookie-sjsaid', "") self.settings.setSetting('device_id', "") def logout(self): self.gmusicapi.logout() def login(self, nocache=False): if nocache or not self.settings.getSetting('logged_in'): self.main.log('Logging in') username = self.settings.getSetting('username') password = self.settings.getSetting('password') try: self.gmusicapi.login(username, password) except Exception as e: self.main.log(repr(e)) if not self.gmusicapi.is_authenticated(): self.main.log("Login failed") self.settings.setSetting('logged_in', "") self.language = self.settings.getLocalizedString dialog = self.xbmcgui.Dialog() dialog.ok(self.language(30101), self.language(30102)) self.settings.openSettings() else: self.main.log("Login succeeded") if not nocache: self.settings.setSetting('logged_in', "1") self.settings.setSetting('authtoken', self.gmusicapi.session._authtoken) self.settings.setSetting( 'cookie-xt', self.gmusicapi.session._rsession.cookies['xt']) self.settings.setSetting( 'cookie-sjsaid', self.gmusicapi.session._rsession.cookies['sjsaid']) self.settings.setSetting('cookie-date', str(datetime.now())) else: self.main.log("Loading auth from cache") self.gmusicapi.session._authtoken = self.settings.getSetting( 'authtoken') self.gmusicapi.session._rsession.cookies[ 'xt'] = self.settings.getSetting('cookie-xt') self.gmusicapi.session._rsession.cookies[ 'sjsaid'] = self.settings.getSetting('cookie-sjsaid') self.gmusicapi.session.is_authenticated = True
class GoogleMusicLogin(): 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) def checkCookie(self): # Remove cookie data if it is older then 7 days if self.settings.getSetting('cookie-date') != None and len(self.settings.getSetting('cookie-date')) > 0: if (datetime.now() - datetime(*time.strptime(self.settings.getSetting('cookie-date'), '%Y-%m-%d %H:%M:%S.%f')[0:6])).days >= 7: self.clearCookie() def checkCredentials(self): if not self.settings.getSetting('username'): self.settings.openSettings() def getApi(self): return self.gmusicapi def getDevice(self): return self.settings.getSetting('device_id') 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() self.main.log(repr(devices)) for device in devices: if device["type"] in ("PHONE","IOS"): device_id = str(device["id"]) break if device_id: if device_id.lower().startswith('0x'): device_id = device_id[2:] self.settings.setSetting('device_id',device_id) self.main.log('Found device_id: '+device_id) def clearCookie(self): self.settings.setSetting('logged_in', "") self.settings.setSetting('authtoken', "") self.settings.setSetting('cookie-xt', "") self.settings.setSetting('cookie-sjsaid', "") self.settings.setSetting('device_id', "") def logout(self): self.gmusicapi.logout() def login(self,nocache=False): if nocache or not self.settings.getSetting('logged_in'): self.main.log('Logging in') username = self.settings.getSetting('username') password = self.settings.getSetting('password') try: self.gmusicapi.login(username, password) except Exception as e: self.main.log(repr(e)) if not self.gmusicapi.is_authenticated(): self.main.log("Login failed") self.settings.setSetting('logged_in', "") self.language = self.settings.getLocalizedString dialog = self.xbmcgui.Dialog() dialog.ok(self.language(30101), self.language(30102)) self.settings.openSettings() else: self.main.log("Login succeeded") if not nocache: self.settings.setSetting('logged_in', "1") self.settings.setSetting('authtoken', self.gmusicapi.session._authtoken) self.settings.setSetting('cookie-xt', self.gmusicapi.session._rsession.cookies['xt']) self.settings.setSetting('cookie-sjsaid', self.gmusicapi.session._rsession.cookies['sjsaid']) self.settings.setSetting('cookie-date', str(datetime.now())) else: self.main.log("Loading auth from cache") self.gmusicapi.session._authtoken = self.settings.getSetting('authtoken') self.gmusicapi.session._rsession.cookies['xt'] = self.settings.getSetting('cookie-xt') self.gmusicapi.session._rsession.cookies['sjsaid'] = self.settings.getSetting('cookie-sjsaid') self.gmusicapi.session.is_authenticated = True
reporting_json = reporting_json + str(error_playlist) + ',' if (len(reporting_playlists_error) > 0): reporting_json = reporting_json[:-1] #Removes last "," reporting_json = reporting_json + u']}}' logger.debug('REPORTING JSON: ' + str(reporting_json)) reporting_json_filename = 'reports/report_' + now.strftime("%Y-%m-%d") + '.json' with open(reporting_json_filename, 'w') as output_file: output_file.write(reporting_json) ### UPDATE favorites_uploaded JSON updated_favorites = u'{"favorites_uploaded": {"tracks": [' for track in uploaded_tracks: updated_favorites = updated_favorites + '{"id": ' + str(track) + '},' if (len(uploaded_tracks) > 0): updated_favorites = updated_favorites[:-1] #Removes last "," updated_favorites = updated_favorites + u'], "playlists": [' for playlist in uploaded_playlists: updated_favorites = updated_favorites + '{"id": ' + str(playlist) + '},' if (len(uploaded_playlists) > 0): updated_favorites = updated_favorites[:-1] #Removes last "," updated_favorites = updated_favorites + u']}}' logger.debug('UPDATED UPLOADED FAVORITES: ' + str(updated_favorites)) with open('favorites_uploaded.json', 'w') as outfile: outfile.write(updated_favorites) ### LOG OUT webclient.logout() logger.info('Done! Edgar out!')