def get_gm_api(): api = Mobileclient() if not api.oauth_login(config.get_gpm_device_id()): api.perform_oauth() if not api.oauth_login(config.get_gpm_device_id()): raise ValueError("Could not authenticate") return api
def authenticate(): try: Mobileclient.perform_oauth(pathToAuth, open_browser=True) except: print("An unknown Error has occurred, quitting setup") input("Press Enter to continue...") exit()
def machineautn(): mm = Mobileclient() mm.perform_oauth() mm2 = Musicmanager() mm2.perform_oauth()
class GMusicApp: def __init__(self): self.base_dir = os.path.dirname(os.path.realpath(__file__)) self.cred_filename = os.path.join(self.base_dir, 'credentials.json') self.api = Mobileclient() @staticmethod def get_device_id(): dev_id = os.getenv('DEVICE_ID') if not dev_id: raise Exception('Please fill the DEVICE_ID field in .env file') elif not re.match('^[a-f0-9]*$', dev_id): raise Exception('DEVICE_ID is incorrect') return dev_id def auth(self): try: device_id = self.get_device_id() except Exception as e: raise e if not os.path.exists(self.cred_filename): self.api.perform_oauth(self.cred_filename, False) return self.api.oauth_login(device_id, self.cred_filename) def run(self): playlists = self.api.get_all_playlists() print(playlists)
class GMusicClient: def __init__(self): """ This connects to the google music server by requesting credentials. """ self.api = Mobileclient() # username = input('Type your Google Play Music email below.\n--> ') self.username = os.getenv('GOOGLE_USERNAME') dir_path = os.path.dirname(os.path.realpath(__file__)) + '/.cache-gmusic-' + ''.join(filter(str.isalpha, self.username)) # Check if already authenticated if(not os.path.isfile(dir_path)): self.api.perform_oauth(open_browser=True, storage_filepath=dir_path) # Attempt to log in; if fail, get new token. try: self.api.oauth_login(Mobileclient.FROM_MAC_ADDRESS, oauth_credentials=dir_path) except: self.api.perform_oauth(open_browser=True, storage_filepath=dir_path) self.api.oauth_login(Mobileclient.FROM_MAC_ADDRESS, oauth_credentials=dir_path) print('Connected to GMusic') def get_playlists(self): """ Gets all the playlists in Google Play Music. Some may not actually have any music, but they will be processed anyways. """ playlists_cache_path = os.path.dirname(os.path.realpath(__file__)) + '/.cache-playlists_cache-' + ''.join(filter(str.isalpha, self.username)) if (os.path.isfile(playlists_cache_path)): with open(playlists_cache_path, 'rb') as playlists_cache_file: playlists = pickle.load(playlists_cache_file) else: print('Requesting Google playlists') playlistsG = self.api.get_all_user_playlist_contents() print('Received Google playlists, we have', len(playlistsG), 'playlists') playlists = Playlists(playlistsG) with open(playlists_cache_path, 'wb') as playlists_cache_file: pickle.dump(playlists, playlists_cache_file) return playlists def get_all_songs(self): """ Gets the entire Google library for adding to the """ lib_cache_path = os.path.dirname(os.path.realpath(__file__)) + '/.cache-lib_cache-' + ''.join(filter(str.isalpha, self.username)) if (os.path.isfile(lib_cache_path)): with open(lib_cache_path, 'rb') as lib_cache_file: library = pickle.load(lib_cache_file) else: print('Requesting Google library') librarySongs = self.api.get_all_songs() print('Received Google library, we have', len(librarySongs), 'songs') library = MusicLibrary(librarySongs) with open(lib_cache_path, 'wb') as lib_cache_file: pickle.dump(library, lib_cache_file) return library
def log_in(api: Mobileclient): print("You need to log in to continue:") api.perform_oauth() if not api.oauth_login(Mobileclient.FROM_MAC_ADDRESS): print("Something went wrong with authentication") return False print("Logged in successfully") return True
def __init__(self, device_id=device_id, first=False): api = Mobileclient() if first: api.perform_oauth() api.oauth_login(device_id) self.api = api self.play_list_dict = {} self.play_list_songs_dict = {} self.new_play_lists = set()
class GPM_client: def __init__(self): logging.info("Starting GPM client") self.gpm_client = Mobileclient() # login while not self.gpm_client.is_authenticated(): logging.info("Logging you in...") if not self.gpm_client.oauth_login(device_id=Mobileclient.FROM_MAC_ADDRESS, oauth_credentials='./.gpmtoken'): logging.debug("No previous credentials - performing Oauth") self.gpm_client.perform_oauth(open_browser=True, storage_filepath='./.gpmtoken')
def main() -> None: gpm_client = Mobileclient() if not gpm_client.oauth_login(gpm_client.FROM_MAC_ADDRESS): gpm_client.perform_oauth() if gpm_client: # Save thumbs up songs from GPM to local playlist file # top_songs = __get_top_songs(gpm_client) # if len(top_songs) > 0: # __save_playlist_locally('gpm_thumbs_up', top_songs) pass
def get_google_playlists(): print("Retreiving playlists from Google Music.") playlists_path = f"{state_dir}/playlists.json" if os.path.exists(playlists_path) and not force_fetch: with open(playlists_path, 'r') as infile: return json.load(infile) print("Could not find saved favorites playlist, or force_fetch is True") credentials_path = f"{state_dir}/gmusic_credentials.json" mm = Mobileclient() if not os.path.exists(credentials_path): mm.perform_oauth(credentials_path, open_browser=True) mm.oauth_login(google_device_id, oauth_credentials=credentials_path) if mm.is_authenticated(): print("Authenticated sucessfully!") else: print("Could not authenticate :(") raise SystemExit(1) playlists = mm.get_all_user_playlist_contents() playlist_names = [p['name'] for p in playlists] print(f'Found playlists: {playlist_names}') clean_playlists = [] for p in playlists: playlist = { 'name': p['name'], 'tracks': [], } for track in p['tracks']: t = extract_google_track(track) if t is not None: playlist['tracks'].append(t) if len(playlist['tracks']) == 0: print(f"No tracks found in {p['name']}") else: clean_playlists.append(playlist) pprint(clean_playlists) if len(clean_playlists) == 0: print(f"No playlists with tracks found") raise SystemExit(1) with open(playlists_path, 'w') as outfile: json.dump(clean_playlists, outfile) return clean_playlists
class GPM_client: def __init__(self): logging.info("Starting GPM client") self.gpm_client = Mobileclient() # login if self.gpm_client.is_authenticated(): logging.info("Logging you in...") self.gpm_client.oauth_login( device_id=Mobileclient.FROM_MAC_ADDRESS) else: logging.debug("No previous credentials - performing Oauth") self.gpm_client.perform_oauth(open_browser=True)
def login(): api = Mobileclient() logged_in = api.oauth_login(Mobileclient.FROM_MAC_ADDRESS) if not logged_in: print('Unable to login, attemping oauth') api.perform_oauth() logged_in = api.oauth_login(Mobileclient.FROM_MAC_ADDRESS) if not logged_in: print('Unable to auth') else: print('Logged in') update_edge_playlist(api)
def onetime_perform_oauth(path, open_browser=False): """ params: path to store oauth credentials, after a call to this you should only need to call gm_api.oauth_login() returns authenticated api """ gm_api = Mobileclient() try: gm_api.perform_oauth(path, open_browser) except oauth2client.client.FlowExchangeError: print('\nError obtaining OAuth credentials, aborting\n', file=sys.stderr) else: print('\n\nOK, OAuth credentials stored at: ', path, '\n\n') return gm_api # not authenticated yet!
def authorize_mobile(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): api.perform_oauth(authorize_file, True) api.oauth_login(Mobileclient.FROM_MAC_ADDRESS, authorize_file) if not api.is_authenticated(): return None return api
def main(argv=None): """ Parse arguments, set up debugging and cache metadata. """ api = Mobileclient() parser_args = get_parser_args(argv) logging_args = { 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s', 'datefmt': '%m-%d %H:%M' } if parser_args.debug_level: logging_args['level'] = DEBUG_LEVELS[parser_args.debug_level] logging.basicConfig(**logging_args) for item, value in list(vars(parser_args).items()): if item == "pwd": continue logging.info("Parser arg: %15s = %s", item, value) if not os.path.exists(api.OAUTH_FILEPATH): logging.info("performing oauth") perform_oauth_args = {'open_browser': parser_args.oauth_browser} if parser_args.oauth_creds_file: perform_oauth_args[ 'storage_filepath'] = parser_args.oauth_creds_file api.perform_oauth(**perform_oauth_args) logging.info("logging in to api") response = api.oauth_login(device_id=parser_args.device_id) try: assert api.is_authenticated() logging.debug("valid device IDs: %s", pformat(api.get_registered_devices())) assert response except AssertionError: logging.warning("\n\n!!! failed to authenticate\n%s.", traceback.format_exc()) raise BadLoginException("Bad login. Check creds and internet") logging.info("api response: %s", response) cache_playlist(api, parser_args)
def login(self, *args): res = api.oauth_login(Mobileclient.FROM_MAC_ADDRESS) if (not res): print ('\n====================================================' + '\nPlease log in. Credentials will be saved as' + '\n' + Mobileclient.OAUTH_FILEPATH + '.' + '\n----------------------------------------------------') Mobileclient.perform_oauth(storage_filepath=Mobileclient.OAUTH_FILEPATH, open_browser=True) res = api.oauth_login(Mobileclient.FROM_MAC_ADDRESS) print ('----------------------------------------------------') if (not res): print ('Login failed. Try again or press ctrl+c to cancel.') Credintials.login(self, *args) return else: print ('Login successful!\nnow performing selected or default option...') print ('====================================================')
def main(): global waiting waiting = False mc = Mobileclient() mc.perform_oauth(storage_filepath='./oauth.cred') mc.oauth_login(device_id=mc.FROM_MAC_ADDRESS, oauth_credentials='./oauth.cred') waiting = True thread = Thread(target=threaded_cursor, args=('Gathering Metadata', )) thread.start() library = mc.get_all_songs() years = {} for song in library: if 'year' in song: try: if not str(song['year']) in years: years[str(song['year'])] = [] if any(song['album'] in keys['album'] for keys in years[str(song['year'])]): continue else: if 'albumArtRef' in song: d = { 'album': song['album'], 'artwork': song['albumArtRef'][0]['url'] } years[str(song['year'])].append(d) else: if verbose: print("No album art for {}".format(song)) except KeyError: if verbose: print("Key error {}".format(song)) else: if verbose: print("No year for {}".format(song)) # clean up songs with unknown year if '0' in years: del years['0'] waiting = False thread.join() make_plot(years)
def gpm_login(): client = Mobileclient() oauth = client.perform_oauth(open_browser=True) client.oauth_login(Mobileclient.FROM_MAC_ADDRESS, oauth_credentials = oauth, locale = 'en_US') if client.is_authenticated(): print('👌') return client
def main(args): if args.mobileclient: from gmusicapi import Mobileclient api = Mobileclient(debug_logging=True) settings['google']['mobileclient'] = api.perform_oauth( open_browser=True).to_json() elif args.musicmanager: from gmusicapi import Musicmanager api = Musicmanager(debug_logging=True) settings['google']['musicmanager'] = api.perform_oauth( open_browser=True).to_json() elif args.youtube: from ytmusicapi import YTMusic api = YTMusic() settings['youtube']['headers'] = api.setup() if ( args.headers_raw is None) else api.setup( headers_raw=args.headers_raw) settings.save()
class Gmusic: """Gmusic class for api operations.""" def __init__(self, account): """Initialize class.""" self.account = account self.api = Mobileclient() self._oauth_credential = str('{}/oauth.cred'.format(os.getcwd())) self.connect_to_api() # Attributes self.podcasts = {} def connect_to_api(self): """Connect to the gmusic api.""" if os.path.isfile(self._oauth_credential): print("\nExisting oauth file found! Using that to login...\n") self.oauth_login() else: print( "\nNOTE: You must authenticate to the google music api, follow the directions." ) print( "The oauth credential file will be stored in this script directory as oauth.cred\n" ) self.perform_oauth() self.oauth_login() def oauth_login(self): """Login using oath token.""" try: self.api.oauth_login(oauth_credentials=self._oauth_credential, device_id=self.api.FROM_MAC_ADDRESS) except Exception as e: print("\nGoogle Music API login failed: {}".format(e)) quit() def perform_oauth(self): """Request oath token from user.""" try: self.api.perform_oauth(storage_filepath=self._oauth_credential) except Exception as e: print("\nGoogle Music API login failed: {}".format(e)) quit()
def export_song_data(name, data, dry_run): gmusic = Mobileclient() logged_in = gmusic.oauth_login(Mobileclient.FROM_MAC_ADDRESS) if not logged_in: print("Couldn't log in. Starting authentication...") gmusic.perform_oauth() logged_in = gmusic.oauth_login(Mobileclient.FROM_MAC_ADDRESS) if logged_in: print("Logged in!") else: print("Login failed.") sys.exit(1) song_ids = data_to_song_ids(gmusic, data) print("Found %d/%d tracks on Google Music." % (len(song_ids), len(data))) if song_ids and not dry_run: playlist_id = gmusic.create_playlist(name) gmusic.add_songs_to_playlist(playlist_id, song_ids) print("Created playlist \"%s\"." % name)
class GMusicClient: def __init__(self): """ This connects to the google music server by requesting credentials. """ self.api = Mobileclient() username = input('Type your Google Play Music email below.\n--> ') dir_path = os.path.dirname( os.path.realpath(__file__)) + '/.cache-gmusic-' + ''.join( filter(str.isalpha, username)) # Check if already authenticated if (not os.path.isfile(dir_path)): self.api.perform_oauth(open_browser=True, storage_filepath=dir_path) # Attempt to log in; if fail, get new token. try: self.api.oauth_login(Mobileclient.FROM_MAC_ADDRESS) except: self.api.perform_oauth(open_browser=True, storage_filepath=dir_path) self.api.oauth_login(Mobileclient.FROM_MAC_ADDRESS) print('Connected to GMusic') def get_playlists(self): """ Gets all the playlists in Google Play Music. Some may not actually have any music, but they will be processed anyways. """ return Playlists(self.api.get_all_user_playlist_contents()) def get_all(self): """ Gets the entire Google library for adding to the """ print('Requesting Google library') library = self.api.get_all_songs() print('Received Google library, we have', len(library), 'songs') return MusicLibrary(library)
def get_google(): global google_client if google_client is not None: return google_client credentials_path = f"{state_dir}/gmusic_credentials.json" google_client = Mobileclient() # mm.perform_oauth() if not os.path.exists(credentials_path): google_client.perform_oauth(credentials_path, open_browser=True) google_client.oauth_login(google_device_id, oauth_credentials=credentials_path) if google_client.is_authenticated(): print("Authenticated sucessfully!") else: print("Could not authenticate :(") raise SystemExit(1) return google_client
class GMusic: def __init__(self): self._client = Mobileclient() # auth information stored in client.OAUTH_FILEPATH path by default is_user_authenticated = os.path.exists(self._client.OAUTH_FILEPATH) if is_user_authenticated == False: self.authenticate_in_google() is_logged_in = self._client.oauth_login( device_id=Mobileclient.FROM_MAC_ADDRESS) if is_logged_in == False: raise 'Login to Google Play Music failed' def authenticate_in_google(): self._client.perform_oauth() def get_liked_tracks(self): liked_tracks = self._client.get_top_songs() return liked_tracks
def get_api(): global device_id api = Mobileclient() if device_id.strip() == '': creds = api.perform_oauth(None, True) api.oauth_login(Mobileclient.FROM_MAC_ADDRESS, creds) devices = api.get_registered_devices() device_id = devices[0]["id"] config.set(SECTION, 'device_id', device_id) else: api.oauth_login(device_id) return api
def load_client(): """ Loads the client for the Google Play Music API :return: client reference """ client = Mobileclient() if (not os.path.exists(client.OAUTH_FILEPATH)): credentials = client.perform_oauth() ## Yes this is bad. ## No, I don't feel bad. try: client.oauth_login("") except InvalidDeviceId as e: client.oauth_login(e.valid_device_ids[0]) return client
def open_api(): global api log('Logging into google music...') # Attempt to login api = Mobileclient() logged_in = api.oauth_login(Mobileclient.FROM_MAC_ADDRESS) if not logged_in: log('No oauth credentials found, please authenticate your account!') # Performs oauth and stores generated credentials to Appdirs # 'user_data_dir' by default. oauth only needs to be performed once per # machine if the credentials are stored, which is the default behavior. authenticated = api.perform_oauth(open_browser=True) else: log('Successfully logged in!') dlog(u'Available track details: ' + str(get_google_track_details())) return api
class Oath_Client(): def __init__(self): self.collection = Mobileclient() def register(self): return self.collection.perform_oauth() def login(self): if os.path.exists(credentials_path): try: self.collection.oauth_login(self.collection.FROM_MAC_ADDRESS) return True except Exception: return False else: return False def logout(self): os.remove(credentials_path)
def open_api(oauth_file_prefix): global api log('Logging into google music...') api = Mobileclient() oAuthFile = oauth_file_prefix + ".gMusic.oauth" if not os.path.isfile(oAuthFile): if not api.perform_oauth(oAuthFile, True): log('ERROR unable to perform authentication') exit() if not api.oauth_login(Mobileclient.FROM_MAC_ADDRESS, oAuthFile): log('ERROR unable to login using oauth token') exit() password = None log('Login Successful.') dlog(u'Available track details: ' + str(get_google_track_details())) return api
api = Mobileclient(debug_logging=False) if os.path.exists("config.json"): with open('config.json', 'r') as fp: ids = json.load(fp) i = 0 while True: try: api.oauth_login(ids[i]) break except: print("oops, this didn't work, trying again") i += 1 i %= len(ids) else: oa = api.perform_oauth() api.oauth_login(Mobileclient.FROM_MAC_ADDRESS, oauth_credentials=oa) devices = api.get_registered_devices() ids = [] for i in devices: ids.append(i['id'][2:]) with open('config.json', 'w') as fp: json.dump(ids, fp) songs = api.get_all_songs() for song in songs: dirName = normalizePath("%s - %s" % (song["artist"], song["album"])) dirPath = targetDir + "/" + dirName if not os.path.exists(dirPath): print("downloading to directory: " + dirPath) os.makedirs(dirPath)
print "USAGE:" print "./add_last_songs_to_top_of_playlist.py 'PLAYLIST NAME' NUMBER_SONGS" print print "example: ./add_last_songs_to_top_of_playlist.py 'Ultimate Everything' 5" print " will move the last 5 songs in 'Ultimate Everything' to the top of the playlist." exit(0) else: playlist_name = sys.argv[1] num_songs = sys.argv[2] # Setup the gmusicapi api = Mobileclient() api.__init__() # Check to see if OAuth credentials available, ask user to setup if not try: api.oauth_login(Mobileclient.FROM_MAC_ADDRESS) except: print "No OAuth credentials found! Please setup in the following screen!" api.perform_oauth() api.oauth_login(Mobileclient.FROM_MAC_ADDRESS) # If it fails here, it wasn't meant to be # Then, move on to doing all the work if api.is_authenticated(): print "Successfully logged in. Moving " + num_songs + " tracks to top of playlist" playlists = api.get_all_user_playlist_contents() tracks = get_playlist_tracks(playlist_name, playlists) move_songs_to_top(api, tracks, int(num_songs)) print "Script completed successfully!"