class GoogleClient(): def __init__(self, username=None, password=None): self._username = username self._password = password # Initiates the oAuth def Authenticate(self): self.MusicManager = Musicmanager(debug_logging=False) attempts = 0 # Attempt to login. Perform oauth only when necessary. while attempts < 3: if self.MusicManager.login(): break self.MusicManager.perform_oauth() attempts += 1 if not self.MusicManager.is_authenticated(): print("Sorry, login failed.") return False print("OAuth successfull\n") username = self._username password = self._password if not username or not password: cred_path = os.path.join(os.path.expanduser('~'), '.gmusicfs') if not os.path.isfile(cred_path): raise Exception( '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 Exception( '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 Exception( 'No username/password could be read from config file' ': %s' % cred_path) self.Api = Mobileclient(debug_logging = False) if not self.Api.login(username, password, Mobileclient.FROM_MAC_ADDRESS): raise Exception('login failed for %s' % username) return True
def authorize_manager(parameters): # api = Webclient() # api = Mobileclient() api = Musicmanager() # after running api.perform_oauth() once: # api.oauth_login('<a previously-registered device id>') # api.login(email=parameters.username, password=parameters.password) # => True if not os.path.exists(authorize_file + '_manager'): api.perform_oauth(authorize_file + '_manager', True) api.login(authorize_file + '_manager') if not api.is_authenticated(): return None return api
def main(): path = sys.argv[1] if not os.path.exists(path): print("Invalid file path. %s" % path) return api = Musicmanager() api.login() if not api.is_authenticated(): print("Login Error\n") return print("start upload...\n") upload_info = api.upload(path) print(upload_info) print("upload is completed.\n") api.logout()
class GoogleClient(): # Initiates the oAuth def Authenticate(self): self.MusicManager = Musicmanager(debug_logging=False) attempts = 0 # Attempt to login. Perform oauth only when necessary. while attempts < 3: if self.MusicManager.login(): break self.MusicManager.perform_oauth() attempts += 1 if not self.MusicManager.is_authenticated(): print "Sorry, login failed." return False print "Successfully logged in.\n" return True
def play_song_by_artist(song, artist): if Mobileclient.is_authenticated(gpm): mm = Musicmanager() mm.login('/home/pi/oauth.cred') if Musicmanager.is_authenticated(mm): song_dict = mm.get_purchased_songs() song_pattern = re.compile( r'(?:.)*\s?(' + re.escape(song) + r')\s?(?:.)*', re.IGNORECASE) artist_pattern = re.compile( r'(?:.)*\s?(' + re.escape(artist) + r')\s?(?:.)*', re.IGNORECASE) btn = OnButtonPress() btn.start() for song in song_dict: m = re.match(artist_pattern, song['artist']) print(m) if (re.match(song_pattern, song['title']) is not None and re.match(artist_pattern, song['artist']) is not None): print('Song found!') song_id = song['id'] (filename, audio) = mm.download_song(song_id) # get rid of non-ascii characters in file name filename = filename.encode('ascii', errors='ignore') # check if song is already downloaded # path will look something like: # /home/pi/Music/02 - Raindrop Prelude.mp3 # forces filename to be a string filename = filename.decode('ascii') path = song_location + filename try: if os.path.isfile(path): print('Song is already downloaded...') print(path) print('Playing song.') vlc_instance = vlc.Instance() p = vlc_instance.media_player_new() media = vlc_instance.media_new(path) p.set_media(media) events = p.event_manager() events.event_attach( vlc.EventType.MediaPlayerEndReached, SongFinished) p.play() p.audio_set_volume(58) while finish == 0: duration = p.get_time() / 1000 (m, s) = divmod(duration, 60) print('Current song is: ', path) print('Length:', '%02d:%02d' % (m, s)) time.sleep(5) p.stop() break else: with open(path, 'wb') as f: f.write(audio) print('Song has been added to: ' + path) print('Playing song.') vlc_instance = vlc.Instance() p = vlc_instance.media_player_new() media = vlc_instance.media_new(path) p.set_media(media) events = p.event_manager() events.event_attach( vlc.EventType.MediaPlayerEndReached, SongFinished) p.play() p.audio_set_volume(58) while finish == 0: duration = p.get_time() / 1000 m, s = divmod(duration, 60) print('Current song is: ', path) print('Length:', '%02d:%02d' % (m, s)) time.sleep(5) p.stop() break except (OSError, IOError): print('An error has occurred.') break else: print('Song not found yet.') else: print('Looks like you need to authenticate.') mm.perform_oauth('/home/pi/oauth.cred') print('Logging out.') Mobileclient.logout(gpm) mm.logout() else: print('Mobile client is not authenticated.') Mobileclient.logout(gpm)
class Gmusic(BeetsPlugin): def __init__(self): super().__init__() self.m = Musicmanager() # OAUTH_FILEPATH was moved in gmusicapi 12.0.0. if hasattr(Musicmanager, 'OAUTH_FILEPATH'): oauth_file = Musicmanager.OAUTH_FILEPATH else: oauth_file = gmusicapi.clients.OAUTH_FILEPATH self.config.add({ 'auto': False, 'uploader_id': '', 'uploader_name': '', 'device_id': '', 'oauth_file': oauth_file, }) if self.config['auto']: self.import_stages = [self.autoupload] def commands(self): gupload = Subcommand('gmusic-upload', help='upload your tracks to Google Play Music') gupload.func = self.upload search = Subcommand('gmusic-songs', help='list of songs in Google Play Music library') search.parser.add_option('-t', '--track', dest='track', action='store_true', help='Search by track name') search.parser.add_option('-a', '--artist', dest='artist', action='store_true', help='Search by artist') search.func = self.search return [gupload, search] def authenticate(self): if self.m.is_authenticated(): return # Checks for OAuth2 credentials, # if they don't exist - performs authorization oauth_file = self.config['oauth_file'].as_filename() if os.path.isfile(oauth_file): uploader_id = self.config['uploader_id'] uploader_name = self.config['uploader_name'] self.m.login(oauth_credentials=oauth_file, uploader_id=uploader_id.as_str().upper() or None, uploader_name=uploader_name.as_str() or None) else: self.m.perform_oauth(oauth_file) def upload(self, lib, opts, args): items = lib.items(ui.decargs(args)) files = self.getpaths(items) self.authenticate() ui.print_('Uploading your files...') self.m.upload(filepaths=files) ui.print_('Your files were successfully added to library') def autoupload(self, session, task): items = task.imported_items() files = self.getpaths(items) self.authenticate() self._log.info('Uploading files to Google Play Music...', files) self.m.upload(filepaths=files) self._log.info('Your files were successfully added to your ' + 'Google Play Music library') def getpaths(self, items): return [x.path for x in items] def search(self, lib, opts, args): password = config['gmusic']['password'] email = config['gmusic']['email'] uploader_id = config['gmusic']['uploader_id'] device_id = config['gmusic']['device_id'] password.redact = True email.redact = True # Since Musicmanager doesn't support library management # we need to use mobileclient interface mobile = Mobileclient() try: new_device_id = (device_id.as_str() or uploader_id.as_str().replace(':', '') or Mobileclient.FROM_MAC_ADDRESS).upper() mobile.login(email.as_str(), password.as_str(), new_device_id) files = mobile.get_all_songs() except NotLoggedIn: ui.print_( 'Authentication error. Please check your email and password.') return if not args: for i, file in enumerate(files, start=1): print(i, ui.colorize('blue', file['artist']), file['title'], ui.colorize('red', file['album'])) else: if opts.track: self.match(files, args, 'title') else: self.match(files, args, 'artist') @staticmethod def match(files, args, search_by): for file in files: if ' '.join(ui.decargs(args)) in file[search_by]: print(file['artist'], file['title'], file['album'])
class Gmusic(BeetsPlugin): def __init__(self): super(Gmusic, self).__init__() self.m = Musicmanager() self.config.add({ u'auto': False, u'uploader_id': '', u'uploader_name': '', u'device_id': '', u'oauth_file': gmusicapi.clients.OAUTH_FILEPATH, }) if self.config['auto']: self.import_stages = [self.autoupload] def commands(self): gupload = Subcommand('gmusic-upload', help=u'upload your tracks to Google Play Music') gupload.func = self.upload search = Subcommand('gmusic-songs', help=u'list of songs in Google Play Music library') search.parser.add_option('-t', '--track', dest='track', action='store_true', help='Search by track name') search.parser.add_option('-a', '--artist', dest='artist', action='store_true', help='Search by artist') search.func = self.search return [gupload, search] def authenticate(self): if self.m.is_authenticated(): return # Checks for OAuth2 credentials, # if they don't exist - performs authorization oauth_file = self.config['oauth_file'].as_str() if os.path.isfile(oauth_file): uploader_id = self.config['uploader_id'] uploader_name = self.config['uploader_name'] self.m.login(oauth_credentials=oauth_file, uploader_id=uploader_id.as_str().upper() or None, uploader_name=uploader_name.as_str() or None) else: self.m.perform_oauth(oauth_file) def upload(self, lib, opts, args): items = lib.items(ui.decargs(args)) files = self.getpaths(items) self.authenticate() ui.print_(u'Uploading your files...') self.m.upload(filepaths=files) ui.print_(u'Your files were successfully added to library') def autoupload(self, session, task): items = task.imported_items() files = self.getpaths(items) self.authenticate() self._log.info(u'Uploading files to Google Play Music...', files) self.m.upload(filepaths=files) self._log.info(u'Your files were successfully added to your ' + 'Google Play Music library') def getpaths(self, items): return [x.path for x in items] def search(self, lib, opts, args): password = config['gmusic']['password'] email = config['gmusic']['email'] uploader_id = config['gmusic']['uploader_id'] device_id = config['gmusic']['device_id'] password.redact = True email.redact = True # Since Musicmanager doesn't support library management # we need to use mobileclient interface mobile = Mobileclient() try: new_device_id = (device_id.as_str() or uploader_id.as_str().replace(':', '') or Mobileclient.FROM_MAC_ADDRESS).upper() mobile.login(email.as_str(), password.as_str(), new_device_id) files = mobile.get_all_songs() except NotLoggedIn: ui.print_( u'Authentication error. Please check your email and password.' ) return if not args: for i, file in enumerate(files, start=1): print(i, ui.colorize('blue', file['artist']), file['title'], ui.colorize('red', file['album'])) else: if opts.track: self.match(files, args, 'title') else: self.match(files, args, 'artist') @staticmethod def match(files, args, search_by): for file in files: if ' '.join(ui.decargs(args)) in file[search_by]: print(file['artist'], file['title'], file['album'])
class Gmusic(object): def __init__(self, playlists_to_sync, credentials_storage_location, debug): self.playlists_to_sync = playlists_to_sync self.credentials_storage_location = credentials_storage_location self._client = Mobileclient(debug_logging=debug) self._manager = Musicmanager(debug_logging=debug) def client_login(self): credentials = self.credentials_storage_location if not os.path.isfile(credentials): credentials = self._client.perform_oauth( storage_filepath=self.credentials_storage_location, open_browser=True) if not self._client.oauth_login( device_id=Mobileclient.FROM_MAC_ADDRESS, oauth_credentials=credentials, ): logger.error("Gmusic mobile client authentication failed") return False logger.info("Gmusic mobile client authentication succeeded.") return True def manager_login(self): credentials = self.credentials_storage_location if not os.path.isfile(credentials): credentials = self._manager.perform_oauth( storage_filepath=self.credentials_storage_location, open_browser=True) if not self._manager.login(oauth_credentials=credentials, ): logger.error("Gmusic music manager authentication failed") return False logger.info("Gmusic music manager authentication succeeded.") return True @property def client(self): if not self._client.is_authenticated(): self.client_login() return self._client @property def manager(self): if not self._manager.is_authenticated(): self.manager_login() return self._manager @cached_property def uploaded_songs(self): return {song['id']: song for song in self.manager.get_uploaded_songs()} @property def _playlists(self): playlists = self.client.get_all_user_playlist_contents() logger.debug("Loaded {} playlists".format(len(playlists))) return playlists @cached_property def playlists(self): playlists_to_sync = [] for playlist in self._playlists: if playlist['name'] in self.playlists_to_sync: playlists_to_sync.append(playlist) return playlists_to_sync def get_latest_addition_date(self, playlist): lastModified = playlist.get('lastModifiedTimestamp') if lastModified: return datetime.fromtimestamp(int(lastModified) / 10**6).replace(tzinfo=pytz.utc) return None