def login(): print "Request : Login" token = request.form['token'] mm = Webclient() ok, token2 = mm.login_token(token) if ok : return token2
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)
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']))
def authenticate(self, USER_DATA_FILENAME): self.G_username = raw_input("Google Play Account Email: ") self.G_password = getpass.getpass("Google Play Account Pass: "******"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: "******"Soundcloud Account Password: "******"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()
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'])
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"
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)
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
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")
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
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)
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()
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 writeAlbumArt(): #TODO: https://github.com/simon-weber/gmusicapi/issues/352 # see branch: https://github.com/simon-weber/gmusicapi/issues/242 wc = Webclient() wc.__init__() #wc.oauth_login(Mobileclient.FROM_MAC_ADDRESS) if wc.login(uname, password): print "webclient login successful" else: print "LOGIN FAILED for Webclient"
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 __init__(self): self.webclient = Webclient(debug_logging=False) self.mobileclient = Mobileclient(debug_logging=False) self.email = None self.password = None self.mc_authenticated = False self.wc_authenticated = False self.authenticated = False self.device = None self.all_songs = list() self.playlists = list()
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()
def main(): api = Webclient() loggedIn = connect(api, raw_input('Username: '******'Password: ')) if not loggedIn: print "Authorization unsuccessful" sys.exit(0) else: print "Authorization successful!" print api.get_all_songs()[0]
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
def __init__(self): self.authenticated = False self.all_access = False self._device = None self._webclient = Webclient(debug_logging=False) self._mobileclient = Mobileclient(debug_logging=False) self._playlists = [] self._playlist_contents = [] self._all_songs = [] self._all_artists = {} self._all_albums = {} self._all_genres = {} self._stations = []
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()
def __login(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) 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) self.api = GoogleMusicAPI() log.info('Logging in...') self.api.login(username, password) log.info('Login successful.')
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 __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 __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 ""
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 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")
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
def ask_for_credentials(): """Make an instance of the api and attempts to login with it. Return the authenticated api. """ # We're not going to upload anything, so the webclient is what we want. api = Webclient() logged_in = False attempts = 0 while not logged_in and attempts < 3: email = raw_input("Email: ") password = getpass() logged_in = api.login(email, password) attempts += 1 return api
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 __init__(self): self.authenticated = False self.all_access = False self.library_loaded = False self.all_songs = [] self.letters = {} self.artists = {} self.albums = {} self.genres = {} self.tracks_by_letter = {} self.tracks_by_artist = {} self.tracks_by_album = {} self.tracks_by_genre = {} self._device = None self._webclient = Webclient(debug_logging=False) self._mobileclient = Mobileclient(debug_logging=False) self._playlists = [] self._playlist_contents = [] self._stations = []
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)
def __init__(self): self.playlist = [] # Array of all tracks self.playlist_id = 0 # Id of playlist self.current_track_index = 0 # Index of current song self.player = Player() # MPlayer instance self.webclient = Webclient() # Client for WebInterface self.mobileclient = Mobileclient() # Client for MobileInterface self.timer = None # Timer to start next track self.deviceid = 0 # DeviceId to use self.playtype = PlayType.LINEAR # LINEAR or SHUFFLE
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 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 __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 __init__(self): self.mob_client = Mobileclient() self.web_client = Webclient() self.logfile = None self.logfile_open = False # logged_in is True if login was successful logged_in = self.mob_client.login(MY_GMAIL, MY_PASSWORD, Mobileclient.FROM_MAC_ADDRESS) if logged_in: print("GoogleMusic MobileClient Logged In") else: raise Exception("Couldn't log in, exiting...") logged_in = self.web_client.login(MY_GMAIL, MY_PASSWORD) if logged_in: print("GoogleMusic WebClient Logged In") else: raise Exception("Couldn't log in, exiting...")
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 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)
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(): 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()
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 #self.gmusicapi = gmusicapi self.initDevice() if self.getDevice(): self.gmusicapi = Mobileclient(debug_logging=True, validate=False) else: self.gmusicapi = Webclient(debug_logging=True, validate=False) def checkCookie(self): # Remove cookie data if it is older then 14 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 >= 14: 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() 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) 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 login(self, nocache=False): # Continue with normal procedure if nocache or not self.settings.getSetting('logged_in'): #if not self.gmusicapi.session.is_authenticated: 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)) 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 GMusic(object): def __init__(self): self.webclient = Webclient(debug_logging=False) self.mobileclient = Mobileclient(debug_logging=False) self.email = None self.password = None self.mc_authenticated = False self.wc_authenticated = False self.authenticated = False self.device = None self.all_songs = list() self.playlists = list() ########################################################################### # Name: authenticate() # # Description: Attempts to authenticate class Mobileclient and Webclient # # instances. # # Inputs: login credentials: email, password # # Outputs: returns True if both Mobileclient and Webclient auth is True # ########################################################################### def authenticate(self, email=None, password=None): if email: self.email = email if password: self.password = password try: Log("Authenticating mobileclient...") self.mc_authenticated = self.mobileclient.login( self.email, self.password) except AlreadyLoggedIn: self.mc_authenticated = True try: Log("Authenticating webclient...") self.wc_authenticated = self.webclient.login( self.email, self.password) except AlreadyLoggedIn: self.wc_authenticated = True self.authenticated = self.mc_authenticated and self.wc_authenticated return self.authenticated ########################################################################### # Name: get_all_songs() # # Description: Returns a list of all songs # # Inputs: None # # Outputs: A list of all the songs a user owns. # ########################################################################### def get_all_songs(self): try: self.all_songs = self.mobileclient.get_all_songs() except NotLoggedIn: if self.authenticate(): self.all_songs = self.mobileclient.get_all_songs() else: Log("LOGIN FAILURE") return return self.all_songs def get_all_playlists(self): try: self.playlists = self.mobileclient.get_all_playlist_ids() except NotLoggedIn: if self.authenticate(): self.playlists = self.mobileclient.get_all_playlist_ids() else: Log("LOGIN FAILURE") return return self.playlists def get_stream_url(self, song_id): try: stream_url = self.mobileclient.get_stream_url(song_id) except NotLoggedIn: if self.authenticate(): stream_url = self.mobileclient.get_stream_url(song_id) else: Log("LOGIN FAILURE") return return stream_url
class Gmusic: artists = [] playlists = [] api = Webclient() player = Player(api) def telnetCmd(self, cmd): tn = telnetlib.Telnet('localhost', '6600') tn.read_until('OK MPD 0.16.0') tn.write(cmd + "\n") result = tn.read_until('OK', 10) tn.close() return result def playSong(self, songId): url = self.api.get_stream_urls(songId)[0] self.telnetCmd('clear') self.telnetCmd('add ' + str(url)) self.telnetCmd('play') def playList(self, playlistId): self.player.setPlaylist(self.playlists[playlistId]) self.player.playSong() def login(self): usuario = '*****@*****.**' senha = 'vd001989' loggedin = Gmusic.api.login(usuario, senha) return loggedin def loadSongs(self): songsApi = Gmusic.api.get_all_songs() for s in songsApi: artistC = Artist() artistC.name = s["artist"] artistC.url = s.get('artistImageBaseUrl', '') artistIndex = -1 if not (artistC in self.artists): artistC.id = len(Gmusic.artists) artistIndex = artistC.id self.artists.append(artistC) else: artistIndex = self.artists.index(artistC) albumC = Album() albumC.name = s["album"] albumC.url = s.get('albumArtUrl', '') albumC.artistId = self.artists[artistIndex].id if not (albumC in self.artists[artistIndex].albums): albumC.id = len(self.artists[artistIndex].albums) self.artists[artistIndex].albums.append(albumC) albumIndex = albumC.id else: albumIndex = self.artists[artistIndex].albums.index(albumC) song = Song() song.id = s["id"] song.title = s["title"] self.artists[artistIndex].albums[albumIndex].songs.append(song) def loadPlaylists(self): plApi = Gmusic.api.get_all_playlist_ids() for name,pids in plApi['user'].iteritems(): for pid in pids: playlist = Playlist() playlist.name = name playlist.id = pid playlist.index = len(self.playlists) tracks = self.api.get_playlist_songs(pid) for s in tracks: song = Song() song.id = s["id"] song.title = s["title"] song.album = s["album"] song.artist = s["artist"] playlist.songs.append(song) self.playlists.append(playlist) def __init__(self): a = ""
BASE_DIR = os.getcwd() USERNAME = raw_input("Google Username:\n") PASSWORD = getpass("Google Password:\n") ANDROID_ID = raw_input( "Android ID (this is optional, leaving it blank will attempt to use MAC address as ID):\n" ) ALBUM = raw_input("Name of Album to fix in GPM:\n") ALBUM_DIR = raw_input( "Folder path containing the songs with the correct artwork embedded:\n") BACKED_UP_FOLDER_ALBUM = False BACKED_UP_FOLDER = False VERBOSE = True api = Mobileclient() webapi = Webclient() clear = lambda: os.system('cls') if VERBOSE: print "Logging in...\n" api_logged_in = api.login( USERNAME, PASSWORD, ANDROID_ID) if ANDROID_ID else api.login( USERNAME, PASSWORD, Mobileclient.FROM_MAC_ADDRESS) web_logged_in = webapi.login(USERNAME, PASSWORD) if not api_logged_in and not web_logged_in: raise ('Both Mobile and Web logins failed!') elif api_logged_in and not web_logged_in: raise ('Web login failed!') elif web_logged_in and not api_logged_in: raise ('Mobile login failed!') elif api_logged_in and web_logged_in:
def __init__(self, speaker): self.speaker = speaker self.api = Webclient()
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 "" def auth(self): 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, artist_title_array, playlist_title=-99): if playlist_title == -99: title = "GMusicSync Playlist %3d" % time.time() else: title = str(playlist_title) print "Synching playlist: %s" % title if title not in self.playlists['user']: print " didn't exist... creating..." self.playlists['user'][title] = [self.wc.create_playlist(title)] print "" 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 = artist_title_array 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 for fn in pc_songs: if self.file_already_in_list(fn, goog_songs): existing_files += 1 continue print "" try: print "Adding: %s - %s" % (fn[0], fn[1]) except: print "Incorrect format for %r, expecting ('artist','title')" % fn continue online = self.find_song(fn) song_id = None if online: song_id = online['id'] print " already uploaded [%s]" % song_id else: print " Sorry, can't find song." if not song_id: failed_files += 1 continue added = self.wc.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 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='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, artist_title, goog_songs): i = 0 while i < len(goog_songs): if self.song_compare(goog_songs[i], artist_title): goog_songs.pop(i) return True i += 1 return False def find_song(self, artist_title): try: artist = artist_title[0] title = artist_title[1] except: return None results = self.wc.search(title) print "\t", results[:2] for r in results['song_hits']: if self.song_compare(r, artist_title): return r return None def song_compare(self, g_song, artist_title): try: artist = artist_title[0] title = artist_title[1] except: return False # TODO: add fuzzy matching return g_song['title'].lower() == title.lower() and\ g_song['artist'].lower() == artist.lower() 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('\\', '/'))
import urllib # Use Google account credintials. If two factor is enabled, use application specific password. email = '*****@*****.**' password = '******' # Device ID for API queries. Leave blank if unknown. device_id = '' if email == '': email = raw_input("Email: ") if password == '': password = raw_input("Password: "******"Logging in..." logged_in = web_client.login(email, password) logged_in = mobile_client.login(email, password) # logged_in is True if login was successful if logged_in == True: print "Successfully logged in" if device_id == '': devices = web_client.get_registered_devices()
class GoogleMusic(object): def __init__(self): self.webclient = Webclient() self.mobileclient = Mobileclient() def is_authenticated(self): if 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) self.webclient.login(username, password) except: raise Exception('Couldn\'t log into Google Music') def search(self, query, kind): if self.is_authenticated(): results = self.mobileclient.search_all_access(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: urls = self.webclient.get_stream_urls(track.get('storeId')) if len(urls) == 1: stream_file.write( self.webclient.session._rsession.get(urls[0]).content) range_pairs = [[int(s) for s in val.split('-')] for url in urls for key, val in parse_qsl(urlparse(url)[4]) if key == 'range'] for url, (start, end) in zip(urls, range_pairs): stream_file.truncate(start) 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()
def __init__(self): self.webclient = Webclient() self.mobileclient = Mobileclient()
def playLogin(self, username, password): self.api = Webclient() self.api.login(username, password) self.playlibrary = self.api.get_all_songs()
class GMusic(object): def __init__(self): self.authenticated = False self.all_access = False self.library_loaded = False self.all_songs = [] self.letters = {} self.artists = {} self.albums = {} self.genres = {} self.tracks_by_letter = {} self.tracks_by_artist = {} self.tracks_by_album = {} self.tracks_by_genre = {} self._device = None self._webclient = Webclient(debug_logging=False) self._mobileclient = Mobileclient(debug_logging=False) self._playlists = [] self._playlist_contents = [] self._stations = [] def _get_device_id(self): if self.authenticated: devices = self._webclient.get_registered_devices() for dev in devices: if dev['type'] == 'PHONE': self._device = dev['id'][2:] break elif dev['type'] == 'IOS': self._device = dev['id'] break def _set_all_access(self): settings = self._webclient._make_call(webclient.GetSettings, '') self.all_access = True if 'isSubscription' in settings[ 'settings'] and settings['settings'][ 'isSubscription'] == True else False def _set_all_songs(self): if len(self.all_songs) == 0: try: self.all_songs = self._mobileclient.get_all_songs() except NotLoggedIn: if self.authenticate(): self.all_songs = self._mobileclient.get_all_songs() else: return [] else: return self.all_songs def authenticate(self, email, password): try: mcauthenticated = self._mobileclient.login(email, password) except AlreadyLoggedIn: mcauthenticated = True try: wcauthenticated = self._webclient.login(email, password) except AlreadyLoggedIn: wcauthenticated = True self.authenticated = mcauthenticated and wcauthenticated self._set_all_access() self._get_device_id() return self.authenticated def load_data(self): self._set_all_songs() for song in self.all_songs: thumb = None letter = song['title'][0] artist = song['artist'] album = song['album'] genre = song['genre'] if 'genre' in song else '(None)' if letter not in self.tracks_by_letter: self.tracks_by_letter[letter] = [] self.letters[letter] = None if artist not in self.tracks_by_artist: self.tracks_by_artist[artist] = [] self.artists[artist] = None if album not in self.tracks_by_album: self.tracks_by_album[album] = [] self.albums[album] = None if genre not in self.tracks_by_genre: self.tracks_by_genre[genre] = [] self.genres[genre] = None track = {'artist': artist, 'album': album} if 'title' in song: track['title'] = song['title'] if 'album' in song: track['album'] = song['album'] if 'artist' in song: track['artist'] = song['artist'] if 'durationMillis' in song: track['durationMillis'] = song['durationMillis'] if 'id' in song: track['id'] = song['id'] if 'trackNumber' in song: track['trackType'] = song['trackNumber'] if 'storeId' in song: track['storeId'] = song['storeId'] if 'albumArtRef' in song: track['albumArtRef'] = song['albumArtRef'] thumb = song['albumArtRef'][0]['url'] self.letters[letter] = thumb self.artists[artist] = thumb self.albums[album] = thumb self.genres[genre] = thumb self.tracks_by_letter[letter].append({ 'track': track, 'thumb': thumb, 'id': song['id'] }) self.tracks_by_artist[artist].append({ 'track': track, 'thumb': thumb, 'id': song['id'] }) self.tracks_by_album[album].append({ 'track': track, 'thumb': thumb, 'id': song['id'] }) self.tracks_by_genre[genre].append({ 'track': track, 'thumb': thumb, 'id': song['id'] }) self.library_loaded = True def get_tracks_for_type(self, type, name): type = type.lower() if type == 'artists': return self.tracks_by_artist[name] elif type == 'albums': return self.tracks_by_album[name] elif type == 'genres': return self.tracks_by_genre[name] elif type == 'songs by letter': return self.tracks_by_letter[name] else: return {} def get_song(self, id): return [x for x in self.all_songs if x['id'] == id][0] def get_all_playlists(self): if len(self._playlists) == 0: try: self._playlists = self._mobileclient.get_all_playlists() except NotLoggedIn: if self.authenticate(): self._playlists = self._mobileclient.get_all_playlists() else: return [] return self._playlists def get_all_user_playlist_contents(self, id): tracks = [] if len(self._playlist_contents) == 0: try: self._playlist_contents = self._mobileclient.get_all_user_playlist_contents( ) except NotLoggedIn: if self.authenticate(): self._playlist_contents = self._mobileclient.get_all_user_playlist_contents( ) else: return [] for playlist in self._playlist_contents: if id == playlist['id']: tracks = playlist['tracks'] break return tracks def get_shared_playlist_contents(self, token): playlist = [] try: playlist = self._mobileclient.get_shared_playlist_contents(token) except NotLoggedIn: if self.authenticate(): playlist = self._mobileclient.get_shared_playlist_contents( token) else: return [] return playlist def get_all_stations(self): if len(self._stations) == 0: try: self._stations = self._mobileclient.get_all_stations() except NotLoggedIn: if self.authenticate(): self._stations = self._mobileclient.get_all_stations() else: return [] return self._stations def get_station_tracks(self, id, num_tracks=200): tracks = [] try: tracks = self._mobileclient.get_station_tracks(id, num_tracks) except NotLoggedIn: if self.authenticate(): tracks = self._mobileclient.get_station_tracks(id, num_tracks) else: return [] return tracks def get_genres(self): genres = [] try: genres = self._mobileclient.get_genres() except NotLoggedIn: if self.authenticate(): genres = self._mobileclient.get_genres() else: return [] return genres def create_station(self, name, id): station = None try: station = self._mobileclient.create_station(name=name, genre_id=id) except NotLoggedIn: if self.authenticate(): station = self._mobileclient.create_station(name=name, genre_id=id) else: return [] return station def search_all_access(self, query, max_results=50): results = None try: results = self._mobileclient.search_all_access(query, max_results) except NotLoggedIn: if self.authenticate(): results = self._mobileclient.search_all_access( query, max_results) else: return [] return results def get_artist_info(self, id, include_albums=True, max_top_tracks=5, max_rel_artist=5): results = None try: results = self._mobileclient.get_artist_info( id, include_albums=include_albums, max_top_tracks=max_top_tracks, max_rel_artist=max_rel_artist) except NotLoggedIn: if self.authenticate(): results = self._mobileclient.get_artist_info( id, include_albums=include_albums, max_top_tracks=max_top_tracks, max_rel_artist=max_rel_artist) else: return [] return results def get_album_info(self, id, include_tracks=True): results = None try: results = self._mobileclient.get_album_info( id, include_tracks=include_tracks) except NotLoggedIn: if self.authenticate(): results = self._mobileclient.get_album_info( id, include_tracks=include_tracks) else: return [] return results def add_aa_track(self, id): track = None try: track = self._mobileclient.add_aa_track(id) except NotLoggedIn: if self.authenticate(): track = self._mobileclient.add_aa_track(id) else: return None return track def add_songs_to_playlist(self, playlist_id, song_ids): tracks = None try: tracks = self._mobileclient.add_songs_to_playlist( playlist_id, song_ids) except NotLoggedIn: if self.authenticate(): tracks = self._mobileclient.add_songs_to_playlist( playlist_id, song_ids) else: return None return tracks def get_stream_url(self, id): try: stream_url = self._mobileclient.get_stream_url(id, self._device) except NotLoggedIn: if self.authenticate(): stream_url = self._mobileclient.get_stream_url( id, self._device) else: return '' except CallFailure: raise CallFailure('Could not play song with id: ' + id, 'get_stream_url') return stream_url
from gmusicapi import Webclient import json api = Webclient() api.login('*****@*****.**', 'biffyclyro') # => True library = api.get_all_songs() print json.dumps(library)
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('\\', '/'))
import sys from gmusicapi import Webclient if __name__ == "__main__": if sys.argv[1] == "1": wc = Webclient() success = wc.login(sys.argv[2], sys.argv[3]) if success == True: devices = wc.get_registered_devices() valid = [ device['id'][2:] + " (" + device['model'] + ")" for device in devices if device['type'] == 'PHONE' ] deviceid = valid[0].split(' ', 1)[0] print(deviceid) if sys.argv[1] == "2": print("Spotify is not yet supported.")