Example #1
0
    def __init__(self, username, password, logger=None):
        mobile_client = Mobileclient()
        mobile_client.login(username, password, mobile_client.FROM_MAC_ADDRESS)

        device_id = None
        for device in reversed(mobile_client.get_registered_devices()):
            type = str(device['type'])
            if type == 'ANDROID' or type == 'IOS':
                device_id = device['id'][2:]
                break

        if device_id == None:
            raise Exception("No mobile device id found!")

        self._api = Mobileclient()
        success = self._api.login(username, password, device_id)

        self.logger = logger

        if not success:
            raise Exception("Unsuccessful login. Aborting!")

        # Populate our library
        self.library = {}
        self.indexing_thread = threading.Thread(target=self.index_library)
        self.indexing_thread.start()
Example #2
0
def process():
    body = request.json
    if 'api' in body:
        endpoint = body['api']
        if endpoint == 'login':
            api = Mobileclient()
            flow = oauth2client.client.OAuth2WebServerFlow(
                **api._session_class.oauth._asdict())
            url = flow.step1_get_authorize_url()
            return {'url': url}
        elif endpoint == 'new_releases':
            api = Mobileclient(validate=False)
            credentials = oauth2client.client.OAuth2Credentials.from_json(
                body['creds'])
            api._authtype = 'oauth'
            api.session.login(credentials)
            albums = get_albums(api)
            return {'albums': albums}
    elif 'auth' in body:
        code = body['auth']
        api = Mobileclient()
        flow = oauth2client.client.OAuth2WebServerFlow(
            **api._session_class.oauth._asdict())
        credentials = flow.step2_exchange(code)
        string_creds = credentials.to_json()
        return {'creds': string_creds}
    return ''
Example #3
0
    def __init__(self, action=None):
        print "Initialising GOPMA."
        config = ConfigParser.ConfigParser()
        config.read('config.ini')

        email = config.get('login', 'email')
        password = config.get('login', 'password')
        try:
            auth_token = config.get('login', 'auth_token')
        except:
            auth_token = False
            print "No auth token could be found"

        print "Logging into Google Play Music as", email
        logged_in = False
        bad_auth = False
        while not logged_in:
            if not auth_token or bad_auth:
                self.api = Mobileclient()
                login = self.api.login(email, password,
                                       Mobileclient.FROM_MAC_ADDRESS)
                if not login:
                    print "Login failed, check your credentials."
                    sys.exit()

                # Save the auth token for later
                with open('config.ini', 'w+') as f:
                    config.set('login', 'auth_token',
                               self.api.session._authtoken)
                    config.write(f)
                    f.close()
                    print "Saved auth token for later."

                logged_in = True
            else:
                print "Found an auth token, trying it."
                self.api = Mobileclient()
                self.api.session._authtoken = auth_token
                self.api.session.is_authenticated = True
                try:
                    # Test the auth token
                    self.api.get_registered_devices()
                    logged_in = True
                except:
                    # Failed
                    print "Bad auth token, manually signing in."
                    bad_auth = True
        print "Successfully logged in as", email

        if action != 'reset_genres':
            print "Loading data."
            self.playlists = self.api.get_all_playlists()
            self.content = self.api.get_all_user_playlist_contents()
            self.root_genres, self.child_genres = self.load_genres()
            print "Data successfully loaded."
Example #4
0
    def __init__(self, email, password, device_id):
        self.__gmusic = Mobileclient()
        self.__email = email
        self.__device_id = device_id
        self.logged_in = False
        self.queue = list()
        self.queue_index = -1
        self.play_queue_order = list()
        self.play_modes = TizEnumeration(["NORMAL", "SHUFFLE"])
        self.current_play_mode = self.play_modes.NORMAL
        self.now_playing_song = None

        userdir = os.path.expanduser('~')
        tizconfig = os.path.join(userdir,
                                 ".config/tizonia/." + email + ".auth_token")
        auth_token = ""
        if os.path.isfile(tizconfig):
            with open(tizconfig, "r") as f:
                auth_token = pickle.load(f)
                if auth_token:
                    # 'Keep track of the auth token' workaround. See:
                    # https://github.com/diraimondo/gmusicproxy/issues/34#issuecomment-147359198
                    print_msg("[Google Play Music] [Authenticating] : " \
                              "'with cached auth token'")
                    self.__gmusic.android_id = device_id
                    self.__gmusic.session._authtoken = auth_token
                    self.__gmusic.session.is_authenticated = True
                    try:
                        self.__gmusic.get_registered_devices()
                    except CallFailure:
                        # The token has expired. Reset the client object
                        print_wrn("[Google Play Music] [Authenticating] : " \
                                  "'auth token expired'")
                        self.__gmusic = Mobileclient()
                        auth_token = ""

        if not auth_token:
            attempts = 0
            print_nfo("[Google Play Music] [Authenticating] : " \
                      "'with user credentials'")
            while not self.logged_in and attempts < 3:
                self.logged_in = self.__gmusic.login(email, password,
                                                     device_id)
                attempts += 1

            with open(tizconfig, "a+") as f:
                f.truncate()
                pickle.dump(self.__gmusic.session._authtoken, f)

        self.library = CaseInsensitiveDict()
        self.song_map = CaseInsensitiveDict()
        self.playlists = CaseInsensitiveDict()
        self.stations = CaseInsensitiveDict()
Example #5
0
def get_gmusic_playlists(username, password):
    api = Mobileclient()
    print(username + ":" + password)
    logged_in = api.login(username, password, Mobileclient.FROM_MAC_ADDRESS)

    if not logged_in:
        print("Login failed.")

    if api.is_authenticated():
        playlists = api.get_all_user_playlist_contents()

        output_dict = {}
        for playlist in playlists:
            name = playlist["name"]
            tracks = playlist["tracks"]

            for track in tracks:
                track = track["track"]
                artist = track["artist"]
                title = track["title"]

                if name in output_dict:
                    output_dict[name].append((artist, title))
                else:
                    output_dict[name] = [(artist, title)]

        return output_dict

    return None
Example #6
0
 def __init__(self, google_username, google_password):
     self.client = Mobileclient(validate=False)
     # generate a stable, unique android id
     h = hashlib.sha256()
     h.update(google_username)
     android_id = h.hexdigest()[:16]
     self.client.login(google_username, google_password, android_id)
Example #7
0
 def __init__(self):
     self.api = Mobileclient(debug_logging=False)
     with open(path + "oauth.cred", 'w+') as tmp:
         tmp.write(settings['google']['mobileclient'])
         tmp.close()
         self.api.oauth_login(Mobileclient.FROM_MAC_ADDRESS, tmp.name)
         os.remove(tmp.name)
Example #8
0
def google_music(gmail, psswd,last_sync = 0):

    from gmusicapi import Mobileclient
    api = Mobileclient()
    songs =[]

    if api.login(gmail, psswd, ):
        library = api.get_all_songs()

        for track in  library:
            song = {}
            song['name'] = track.get('title','')
            song['artist'] = track.get('artist','')
            song['year'] = track.get('year',0)
            song['genre'] = track.get('genre','')
            song['plays'] = track.get('playCount',0)
            tup = youtubeVidSearch(song['name'],song['artist'])
            song['url'] = tup[0]
            song['art'] = tup[1]
            stamp = int(track.get('creationTimestamp',0))/1000.0
            if stamp > last_sync and song.get('url') :
                songs.append(song)
                print track

    return songs
def main():
    args, config = init()

    if not os.path.isdir(config['PROG']['DownloadPath']):
        os.mkdir(config['PROG']['DownloadPath'])

    sc_download(
        config['SOUNDCLOUD']['PlaylistUrl'],
        config['PROG']['DownloadPath']
    )

    mc = Mobileclient()
    mc.login(config['GMUSIC']['User'], config['GMUSIC']['Password'], Mobileclient.FROM_MAC_ADDRESS)

    mm = Musicmanager()
    if not (os.path.exists(gmclients.OAUTH_FILEPATH) and mm.login(gmclients.OAUTH_FILEPATH)):
        mm.perform_oauth(gmclients.OAUTH_FILEPATH, open_browser=True)
        if not mm.login(gmclients.OAUTH_FILEPATH):
            sys.stderr.write('Musicmanager could not authenticate')

    if config['GMUSIC']['TargetPlaylist'] not in set([item['name'] for item in mc.get_all_playlists() if not item['deleted']]):
        mc.create_playlist(name=config['GMUSIC']['TargetPlaylist'], description='Tracks synchronized using {}'.format(__prog__), public=False)

    playlist_id, current_members = gm_get_current_pl_member(mc, config['GMUSIC']['TargetPlaylist'])

    for track in os.listdir(config['PROG']['DownloadPath']):
        print('Uploading {}'.format(track))
        uploaded_id = gm_extract_id(mm.upload('{}{}'.format(config['PROG']['DownloadPath'], track)))
        mc.add_songs_to_playlist(playlist_id, uploaded_id)
Example #10
0
def update_stats(user_id):
    gm = Mobileclient()
    user = UserSettings.objects.get(pk=user_id)
    try:
        user_credential_base64 = user.credential
        user_credential = codecs.decode(user_credential_base64.encode(),
                                        "base64")
        credential = pickle.loads(user_credential)

        # TODO think about google apis problem
        gm.oauth_login(user.current_device, credential)

        try:
            library = gm.get_all_songs()
            gm.logout()
        except Exception as e:
            print("Exception: " + str(e))
            return

        new_library = prepare_library(library)

        new_stats = PlayMusicStats()
        new_stats.user = user.user
        new_stats.stats = new_library
        new_stats.total_time = get_total_time_in_sec(new_library)
        new_stats.save()

        print('Stats for ' + str(user.user) + ' saved')
    except Exception as e:
        user.credential_is_valid = False
        user.save()
        print('Credential for ' + str(user.user) + ' is invalid: ' + str(e))
Example #11
0
def get_gpm_client():
    """ Fetch the Google Play Music Client"""
    gpm_client = Mobileclient()
    # Make sure that login works
    device_id = settings.GOOGLE_DEVICE_ID or get_mac_address().replace(":", "").upper()
    assert gpm_client.oauth_login(device_id, oauth_credentials=GPM_TOKEN)
    return gpm_client
Example #12
0
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 get_all_podcasts_from_google_music():
    '''Returns sorted list of all podcast episodes from Google as a list
  '''

    here = os.path.dirname(os.path.realpath(__file__))
    oauth_path = os.path.join(here, config['DEFAULT']['OAUTH_FILEPATH'])
    device_id = config['DEFAULT']['DEVICE_ID']
    mc = Mobileclient()
    series_title = "Fourth Official Soccer Podcast"
    google_music_url = "https://play.google.com/music/m/"

    # mc.perform_oauth() only needed once (can be avoided by providing an oauth file)
    mc.oauth_login(device_id, oauth_path)

    episodes_list = mc.get_all_podcast_episodes(device_id)
    episodes_list = [
        episode for episode in episodes_list
        if episode['seriesTitle'] == series_title
    ]
    episodes_list = sorted(episodes_list,
                           key=itemgetter('publicationTimestampMillis'))
    url_list = [
        f"{google_music_url}{episode['episodeId']}?t={episode['title']}-{episode['seriesTitle']}"
        for episode in episodes_list
    ]
    url_list = [url.replace(" ", "_") for url in url_list]
    episodes_list = [{'name': episode['title'], 'description': episode['description'], \
      'publication_timestamp_millis': episode['publicationTimestampMillis'], \
      'url': url} for episode, url in zip(episodes_list, url_list)]

    return episodes_list
Example #14
0
def setup(username, password):
    global api
    api = Mobileclient()
    logged_in = api.login(username, password, Mobileclient.FROM_MAC_ADDRESS)
    while (not logged_in):
        logged_in = api.login(username, password,
                              Mobileclient.FROM_MAC_ADDRESS)
Example #15
0
def machineautn():

    mm = Mobileclient()
    mm.perform_oauth()

    mm2 = Musicmanager()
    mm2.perform_oauth()
Example #16
0
 def __init__(self, fileName):
     '''
     Initializes the API with user credentials
     :param: fileName Reference to the file with authentication information
     :return: Reference to the API
     '''
     api = Mobileclient()
     # read in the auth file
     cntr = 0
     for line in open(fileName):
         if (cntr == 0):
             user = line.strip()
         if (cntr == 1):
             app_pwd = line.strip()
         cntr += 1
     # bail before potential exception
     if (cntr != 2):
         print("ERROR: Improperly formatted auth file.", file=sys.stderr)
         exit(1)
     # TODO improve MAC id
     logged_in = api.login(user, app_pwd, Mobileclient.FROM_MAC_ADDRESS)
     # error handling for auth
     if not(logged_in):
         print("ERROR: Unable to log in.", file=sys.stderr)
         exit(1)
     return api
Example #17
0
def gpm_login(request):
    if request.method == 'POST':
        form = GPMLoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']

            # attempt a GPM login with the given form credentials
            global gpm
            gpm = Mobileclient()
            gpm_loggedIn = gpm.login(email, password,
                                     Mobileclient.FROM_MAC_ADDRESS)
            if gpm_loggedIn:  # if login successful, create a new user in the database
                if not GPMUser.objects.filter(
                        spotify_user=request.user).exists():
                    new_gpm_user = GPMUser(spotify_user=request.user,
                                           email=email,
                                           password=password)
                    new_gpm_user.save()
                return render(request, 'spotify_to_gpm_app/homepage.html')
            else:  # if login not successful, tell the user to fill out the form again
                form = GPMLoginForm()
                return render(request, 'spotify_to_gpm_app/login_page.html', {
                    'failed': 'GPM Login Failed. Try again.',
                    'form': form
                })
    else:  # if form is invalid, send it back to the template
        form = GPMLoginForm()
    return render(request, 'spotify_to_gpm_app/login_page.html',
                  {'form': form})
Example #18
0
 def setUp(self):
     with open(os.path.join(TEST_DATA_DIR, 'library.json')) as library_json:
         data = json.load(library_json)
         with patch.object(Mobileclient,
                           'get_all_user_playlist_contents',
                           return_value=data):
             self.library = Library(Mobileclient())
Example #19
0
    def __init__(self, hass, config):
        """Initialize the books authors."""
        global GM_DEV_KEY
        global G_GM_MOBILE_CLIENT_API
        self.hass = hass
        self.all_gm_tracks = []
        self.selected_books = []
        _LOGGER.info("GM_USER: "******" GM_PASS: *******" +
                     " GM_DEV_KEY: " + str(GM_DEV_KEY))
        from gmusicapi import Mobileclient

        G_GM_MOBILE_CLIENT_API = Mobileclient()

        # if GM_DEV_KEY is None:
        #     G_GM_MOBILE_CLIENT_API.login(GM_USER, GM_PASS, Mobileclient.FROM_MAC_ADDRESS)
        # else:
        #     G_GM_MOBILE_CLIENT_API.login(GM_USER, GM_PASS, GM_DEV_KEY)
        #
        G_GM_MOBILE_CLIENT_API.oauth_login("3cf7d4cc166ab0ee")
        if not G_GM_MOBILE_CLIENT_API.is_authenticated():
            _LOGGER.error("Failed to log in, check Google Music api")
            return False
        else:
            _LOGGER.info("OK - we are in Google Music")
            registered_devices = G_GM_MOBILE_CLIENT_API.get_registered_devices(
            )
    def __init__(self,
                 account,
                 password,
                 shuffle=False,
                 loop=0,
                 volume=50,
                 muted=False,
                 library_update=False,
                 debug=False):
        self._api = Mobileclient(debug_logging=False)
        self._vlc = Instance()

        self._library_songs = None
        self._library_playlists = None

        self._queue_trackDict = []
        self._queue_index = -99  # -1 = finished playing queue, -99 = empty queue, -2 = fresh start
        self._queue_history_backward = []
        self._queue_history_forward = []
        self._queue_shuffle_on = shuffle
        self._queue_loop_mode = loop  # 0 = loop off, 1 = loop all, 2 = repeat one

        self._player = None
        self._player_state = 'stopped'  # stopped, playing, or paused
        self._player_volume = volume
        self._player_volume_muted = muted

        self._command_dict = available_commands
        self._id_text = '[GooglePlayMusicPlayer] '
        self._is_playing_before_pausing_for_command = False
        self._last_executed_command = 'stop'
        self._debug = debug

        self._api.login(account, password, Mobileclient.FROM_MAC_ADDRESS)
        self._library_load_data(library_update)
Example #21
0
 def __init__(self, device_id: str, cred_mc: oauth2client.client.OAuth2Credentials, cred_mm: oauth2client.client.OAuth2Credentials):
     self._mc = Mobileclient()
     if not self._mc.oauth_login(device_id, cred_mc):
         raise RuntimeError('Mobileclient login failed')
     self._mm = Musicmanager()
     if not self._mm.login(cred_mm, _UPLOADER_ID, _UPLOADER_NAME):
         raise RuntimeError('Musicmanager login failed')
Example #22
0
 def __init__(self):
     self.index = 0
     self.tracks = []
     self.api = Mobileclient()
     print("logged")
     self.api.login('*****@*****.**', 'romgroGMAIL95',
                    Mobileclient.FROM_MAC_ADDRESS)
Example #23
0
    def put(self, request):

        user_settings = self.get_object(request.user)
        serializer = UserSettingsSerializer(user_settings, data=request.data)

        if serializer.is_valid():
            try:
                code = serializer.validated_data['code']
            except:
                return Response('Code is empty',
                                status=status.HTTP_400_BAD_REQUEST)
            try:
                flow = OAuth2WebServerFlow(
                    **Mobileclient._session_class.oauth._asdict())
                credential = flow.step2_exchange(code)
                credential_picked = codecs.encode(pickle.dumps(credential),
                                                  "base64").decode()

                gm = Mobileclient()
                current_device = gm.get_device_ids(credential)[0]
            except:
                # TODO change response and connect it to frontend
                return Response(
                    'Please enter the correct code or try again later',
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR)

            user_settings.credential = credential_picked
            user_settings.current_device = current_device
            user_settings.credential_is_valid = True
            serializer.save()

            update_stats(request.user.pk)

            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #24
0
def google_playlists(x):
    api = Mobileclient()
    api.login('*****@*****.**', 'rtqjkpidxwxddpur',
              Mobileclient.FROM_MAC_ADDRESS)
    all_playlists = api.get_all_playlists(incremental=False,
                                          include_deleted=False)
    dj_list = list(set(x['host']))
    for k, dj in enumerate(dj_list):
        # pull out subset of a given Dj
        subset = x.loc[x['host'] == (dj)]
        print("\n   Analyzing " + dj + " Playlists...\n")
        # pull out subset of dj subset for a given month
        for i in np.arange(1, 12, 1):
            print('Now loading Month: ' + str(i))
            artists = np.load(dj + '/' + '2015-' + str(i) + '-artists.npy')
            if len(artists) == 0:
                break
            titles = np.load(dj + '/' + '2015-' + str(i) + '-titles.npy')
            # playlist_exists = False
            # playlist_name = 'KCRW DJ '+host+', Tracks of 2015-'+str(i)
            # print("Searching for playlist named: " + playlist_name)
            # for playlist in all_playlists:
            # 	if playlist['name'] == playlist_name:
            # 		playlist_exists = True
            # 		playlist_id = playlist['id']
            # 		print("Playlist exists, adding new songs to playlist: "+playlist_name)
            # if not playlist_exists:
            # 	playlist_id = api.create_playlist(playlist_name, description=None, public=False)
            # 	print("Playlist is new, creating playlist and adding new songs to: "+playlist_name)
            search_google(api, artists, titles)
Example #25
0
def login(username,password):
	api = Mobileclient()
	try:
		loggedin = api.login(username, password)
		return api
	except:
		return False
def main():
    parser = argparse.ArgumentParser(
        description='Convert a playlist'
    )
    parser.add_argument(
        'playlist_file',
        type=str,
        help='json file with the playlist info'
    )

    username = os.environ["GUSER"]
    password = getpass(
        "Google Password (if 2-factor app specific password) (sorry... no official gmusic api so no oauth):"
    )
    gmusic_client = Mobileclient()
    gmusic_client.login(username, password, Mobileclient.FROM_MAC_ADDRESS)

    args = parser.parse_args()
    with open(args.playlist_file) as infile:
        playlist = Playlist.from_dict(
            json.loads(infile.read())
        )

    track_ids = [get_relevant_track_id(track, results) for track, results in get_query_results(gmusic_client, playlist)]
    upload_playlist(gmusic_client, playlist.name, playlist.description, [x for x in track_ids if x])
Example #27
0
 def __init__(self, bot):
     self.bot = bot
     self.voice_states = {}
     self.api = Mobileclient()
     self.logged_in = self.api.login('email', 'password',
                                     '1234567890abcdef')
     self.VOLUME_LEVEL = .1
Example #28
0
class Player:
	def __init__(self,creds,logging=False,val=False,ssl=True):
		# verify that creds is a dict or raise TypeError
		if not (creds instanceof dict):
			raise TypeError('Credentials passed are not a dictionary')

		# verify that the fields for the dict are filled or raise Error
		if not (creds["email"] or creds["password"] or creds["mac"]):
			raise Error('Missing parameters for login')
		
		# create Mobileclient and set local variables
		self.email = creds["email"]
		self.password = creds["pass"]
		self.mac = creds["mac"]
		self.mc = Mobileclient(debug_logging=logging,validate=val,verify_ssl=ssl)

		# verify Mobileclient logged in or raise ConnectionError
		if not self.mc.login(self.email,self.password,self.mac):
			raise ConnectionError('Could not connect using those credentials'
)
		self.qd = { #query dictionary
			"song":["song_hits","nid"],
			"artist":["artist_hits","artistId"],
			"album":["album_hits","albumId"],
			}
		self.sd = { #search dictionary
			"song_hits":"nid",
			"artist_hits":"artistId",
			"album_hits":"albumId",
			"track","trackId"
			}
Example #29
0
 def search(self, lib, opts, args):
     password = config['gmusic']['password']
     email = config['gmusic']['email']
     password.redact = True
     email.redact = True
     # Since Musicmanager doesn't support library management
     # we need to use mobileclient interface
     mobile = Mobileclient()
     try:
         mobile.login(email.as_str(), password.as_str(),
                      Mobileclient.FROM_MAC_ADDRESS)
         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')
Example #30
0
def get_songs(sync=False):
    if os.path.isfile('songs.json') and not sync:
        f = open('songs.json', 'r')
        songs = f.read()
        songs = json.loads(songs)
    else:
        api = Mobileclient()
        api.login(GOOGLE_EMAIL, GOOGLE_MUSIC_PASS,
                  Mobileclient.FROM_MAC_ADDRESS)

        songs_gen = api.get_all_songs(True)

        print("Loading library songs:")

        songs = []
        for part in songs_gen:
            songs = songs + part
            print("%s songs loaded" % len(songs))

            str(len(songs)) + " songs loaded."

        songs = list(reversed(resort_by_added(songs)))

        f = open('songs.json', 'w')
        f.write(json.dumps(songs, indent=4, separators=(',', ': ')))
        f.close()

    return songs