def get_data(self):
		mobileapi = Mobileclient()
		mobileapi.login(setting.GUSER, setting.GPASS)
		library = mobileapi.get_all_songs()
		mobileapi.logout()
		
		return library
Esempio n. 2
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)
Esempio n. 3
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)
Esempio n. 4
0
class Client(object):
    def __init__(self):
        self.client = Mobileclient()
        self.client.login(config.gmusic['email'], config.gmusic['password'],
                          Mobileclient.FROM_MAC_ADDRESS)

    def search_songs(self, query_str):
        song_hits = self.client.search(unicode(query_str), 8)['song_hits']
        songs = []
        for song_hit in song_hits:
            songs.append({
                'title': song_hit['track']['title'],
                'artist': song_hit['track']['artist'],
                'album': song_hit['track']['album'],
                'nid': song_hit['track']['nid']
            })

        return songs

    def get_song_url(self, song_nid):
        song_id = self.__prepare_song_id(song_nid)
        return self.client.get_stream_url(song_id)

    def get_song_info(self, song_nid):
        song_id = self.__prepare_song_id(song_nid)
        return self.client.get_track_info(song_id)

    def __prepare_song_id(self, song_nid):
        return 'T{0}'.format(song_nid)
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])
Esempio n. 6
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()
Esempio n. 7
0
    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"
Esempio n. 8
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')
Esempio n. 9
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')
Esempio n. 10
0
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)
Esempio n. 11
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)
Esempio n. 12
0
class Music:
    def __init__(self):
        self.index = 0
        self.tracks = []
        self.api = Mobileclient()
        print("logged")
        self.api.login('*****@*****.**', 'romgroGMAIL95',
                       Mobileclient.FROM_MAC_ADDRESS)

    def load_random(self):
        stations = self.api.get_all_stations()
        station = random.choice(stations)
        self.tracks = self.api.get_station_tracks(station["id"])

    def play_random(self):
        url = self.api.get_stream_url(self.tracks[self.index]['nid'],
                                      device_id=None,
                                      quality=u'hi')
        self.player = vlc.MediaPlayer(url)
        self.player.play()

    def update(self):
        # todo update
        pass

    def next_song(self):
        self.index += 1
        self.play_random()
        pass
Esempio n. 13
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
Esempio n. 14
0
def connect_api():
    with open('secrets.json', 'r') as secrets:
        secrets_dict = json.load(secrets)
        user = secrets_dict['username']
        user_pass = secrets_dict['password']
    api = Mobileclient()
    api.login(user, user_pass, Mobileclient.FROM_MAC_ADDRESS)
    return api
class GoogleMusicHelper(object):
    def __init__(self, email=None, password=None):
        self.google_music_client = Mobileclient()
        if email and password:
            self.login(email, password)

    def login(self, email, password):
        if self.google_music_client.login(email, password,
                                          Mobileclient.FROM_MAC_ADDRESS):
            return "Logged in to Google"
        return "Error logging in"

    def add_song_by_name_to_google_library(self, song="", artist=""):
        results = self.google_music_client.search(query=song + " " + artist,
                                                  max_results=1)
        if results:
            track = results["song_hits"][0]["track"]
            return self.google_music_client.add_store_tracks(
                track.get("storeId") or track.get("nid"))

    def list_playlists(self):
        return self.google_music_client.get_all_user_playlist_contents()

    def sync_playlists_with_library(self, password=None, username=None):
        if self.google_music_client.login(username, password,
                                          Mobileclient.FROM_MAC_ADDRESS):
            all_tracks = []
            for playlist in self.google_music_client.get_all_user_playlist_contents(
            ):
                for track in playlist["tracks"]:
                    all_tracks.append(track["track"])

            playlist_store_ids = [track["storeId"] for track in all_tracks]
            all_songs = self.google_music_client.get_all_songs(
                incremental=False)

            print all_songs[0]

            added_store_ids = []
            for song in all_songs:
                store_id = None
                if song.get("nid"):
                    store_id = song["nid"]
                elif song.get("storeId"):
                    store_id = song["storeId"]
                added_store_ids.append(store_id)

            new_store_ids = set(playlist_store_ids) - set(added_store_ids)
            new_tracks = [
                track for track in all_tracks
                if track["storeId"] not in added_store_ids
            ]
            for storeId in new_store_ids:
                for track in new_tracks:
                    if track["storeId"] == storeId:
                        break
                print track['title'] + " by " + track["artist"]
                print self.google_music_client.add_store_tracks(storeId)
Esempio n. 16
0
    def __sync_song_ratings(self, apim, songs):
        apim = Mobileclient()
        apim.login(self.email, self.password)

        """
        Sync ratings to Google Music
        """

        apim.change_song_metadata(songs)
Esempio n. 17
0
def get_gmusic_api():
    global gmusic
    if gmusic is None:
        gmusic = Mobileclient(debug_logging=False)
        gmusic.login(email=USER_NAME,
                     password=APP_PASSWORD,
                     locale='en_US',
                     android_id=Mobileclient.FROM_MAC_ADDRESS)
    return gmusic
def download_album(username, password, artist_name, album_name):
    api = Mobileclient()
    api.login(username, password, Mobileclient.FROM_MAC_ADDRESS)

    library = api.get_all_songs()
    songs = [s for s in library if s['albumArtist'] == artist_name and s['album'] == album_name]

    if len(songs) == 0:
        print('Error: Album not found', file=sys.stderr)
        return

    device_id = api.get_registered_devices()[0]['id'].replace('0x', '')
    dname = slugify(unicode(album_name))
    os.mkdir(dname)
    
    # download songs
    for song in tqdm(songs, desc='Downloading'):
        fname = slugify(song['title'])
        mpg_name = os.path.join(dname, fname + '.mpg')
        mp3_name = os.path.join(dname, fname + '.mp3')

        url = api.get_stream_url(song['id'], device_id=device_id)
        response = requests.get(url)

        # first save as MPEG video
        with open(mpg_name, 'wb') as fout:
            for chunk in response.iter_content(chunk_size=128):
                fout.write(chunk)

        # call FFMPEG to convert to MP3
        os.system(' '.join([FFMPEG_CMD] + FFMPEG_ARGS).format(
            input=mpg_name,
            output=mp3_name,
            title=song['title'],
            artist=song['albumArtist'],
            album=song['album'],
            track=song['trackNumber']))

        os.remove(mpg_name)

    # download album art
    art_name = os.path.join(dname, dname + '.png')
    album_info = api.get_album_info(songs[0]['albumId'], include_tracks=False)
    response = requests.get(album_info['albumArtRef'])
    t = magic.from_buffer(response.content, mime=True)

    if t == 'image/jpeg':
        ext = '.jpg'
    elif t == 'image/png':
        ext = '.png'
    else:
        print('Unknown MIME type: {}'.format(t), file=sys.stderr)
        ext = '.wat'

    with open(os.path.join(dname, dname + ext), 'wb') as fout:
        fout.write(response.content)
Esempio n. 19
0
class Plugin:
    name = 'gmusic'

    def __init__(self, username, password):
        self.client = Mobileclient()
        self.client.login(username, password, Mobileclient.FROM_MAC_ADDRESS)
        # self.webclient = Webclient()
        # self.webclient.login(username, password)

    def get_tracks(self, artist=None, album=None):
        """
        Fetches tracks from api.

        If no filter is defined, it will get user tracks
        """
        return TrackList(self.client.get_all_songs())

    def get_playlists(self):
        """
        Get playlists and radios
        """
        playlists = []
        for playlist in self.client.get_all_user_playlist_contents():
            tracks = TrackList([
                self.client.get_track_info(x['trackId'])
                for x in playlist['tracks']
            ])
            playlists.append(PlayList(playlist['name'], tracks))
        return playlists

    def stream(self, track):
        def _stream(url):
            inp = requests.get(url, stream=True)
            chunk_size = 1024
            for chunk in inp.iter_content(chunk_size):
                if not chunk:
                    continue
                yield chunk

        song_id = track.uri.split(':')[-1]
        return _stream(self.client.get_stream_url(song_id))

    def search(self, keywords, matches):
        results = self.client.search(keywords)
        if matches == 'artist':
            return {'artists': results.get('artist_hits', [])}
        elif matches == 'album':
            return {'albums': results.get('album_hits', [])}
        elif matches == 'tracks':
            return {'tracks': results.get('song_hits', [])}
        elif matches == 'all':
            return {
                'artists': results.get('artist_hits', []),
                'albums': results.get('album_hits', []),
                'tracks': results.get('song_hits', [])
            }
Esempio n. 20
0
    def get_stream_client(self):
        device_id = self.get_device_id()
        client = Mobileclient(False, False, True)
        logger.info("Logging in '%s' with device id '%s'." % (self.username, device_id))
        client.login(self.username, self.password, device_id)

        if not client.is_authenticated():
            raise Exception("Client couldn't log in.")

        return client
Esempio n. 21
0
class GMusicWS:
    def __init__(self, user, password, playlistName):
        self.playlistName = playlistName
        self.api = Mobileclient()
        print("Logging into MobileClient API")
        self.api.login(user, password,
                       "android_id")  #insert unique android_id here

    def mapUnknownTracks(self, db):
        playlist = db.unmappedTracks()

        for track in playlist:
            searchstr = track.artist + " " + track.song
            print("Searching for %s" % (searchstr))
            try:
                result = self.api.search_all_access(searchstr, max_results=1)
                print("Found " + result['song_hits'][0]['track']['artist'] +
                      " - " + result['song_hits'][0]['track']['title'])
                nid = result['song_hits'][0]['track']['nid']
                db.storemapping(track.song, track.artist, nid)
            except:
                print("Error parsing result: " + str(result))

            time.sleep(1)

    def maintain(self, tracks):
        print("Searching for playlist %s" % (self.playlistName))

        found = False
        searchres = self.api.get_all_playlists()
        for list in searchres:
            if list['name'] == self.playlistName:
                found = True
                pid = list['id']

        if not found:
            print("Not found - creating")
            pid = self.api.create_playlist(self.playlistName)

        print("Playlist id is %s" % (pid))

        print("Getting current contents")
        playlists = self.api.get_all_user_playlist_contents()
        currentEntries = []
        for playlist in playlists:
            if playlist['name'] == self.playlistName:
                for entry in playlist['tracks']:
                    currentEntries.append(entry['id'])

        print("Removing songs")
        self.api.remove_entries_from_playlist(currentEntries)

        print("Adding songs")
        self.api.add_songs_to_playlist(pid, tracks)
Esempio n. 22
0
def get_authenitcated_client():
    email = input("Email: ")
    password = getpass.getpass("Password: "******"Failied to authenticate, try again.")
        return get_authenitcated_client()
    return client
Esempio n. 23
0
def logintest():
	if verifyServer(request.args.get('h','')):
		api = Mobileclient()
		try:
			api.login(request.args.get('u', ''),request.args.get('p', ''))
		except:
			return "False"
		api.logout()
		return "True"
	else:
		return 'You are not the server!'
Esempio n. 24
0
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()
Esempio n. 25
0
    def login(self):
        if self.api is not None:
            return self.api
        
        debug("logging in as {}", self.config["email"])
        
        api = Mobileclient(debug_logging=DEBUG)
        api.login(self.config["email"], self.config["password"], Mobileclient.FROM_MAC_ADDRESS)

        self.api = api
        
        return api
Esempio n. 26
0
def main():
    log.setLevel(logging.DEBUG)
    logging.getLogger('gmusicapi').setLevel(logging.DEBUG)
    
    cred_path = os.path.join(os.path.expanduser('~'), '.gmusic-sync')

    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)

    src_user = config.get('src','username')
    src_pass = config.get('src','password')
    src_device = config.get('src','deviceid')

    dst_user = config.get('dst','username')
    dst_pass = config.get('dst','password')
    dst_device = config.get('dst','deviceid')

    if not src_user or not src_pass or not dst_user or not dst_pass:
        raise NoCredentialException(
                    'No username/password could be read from config file'
                    ': %s' % cred_path)
    if not src_device or not dst_device:
         raise NoCredentialException(
                    'No deviceId could be read from config file'
                    ': %s' % cred_path)
    
    parser = argparse.ArgumentParser(description='gmusic-sync', add_help=False)

    parser.add_argument('-d', '--dst',help='Use dst credentials instead of src', action='store_true',dest='dst')
    parser.add_argument('-t', '--trackid', help='Store ID for the Track', dest='trackid')

    args = parser.parse_args()

    # do some arg parsing here later

    api = Mobileclient()
    if args.dst:
        api.login(dst_user, dst_pass, dst_device)
    else:
        api.login(src_user, src_pass, src_device)
    
    print api.get_track_info(args.trackid)
Esempio n. 27
0
class GMusicWS:
	def __init__(self, user, password, playlistName):
		self.playlistName = playlistName
		self.api = Mobileclient()
		print ("Logging into MobileClient API")
		self.api.login(user, password,"android_id") #insert unique android_id here

	def mapUnknownTracks(self, db):
		playlist = db.unmappedTracks()
		
		for track in playlist:
			searchstr = track.artist + " " + track.song
			print ("Searching for %s" % (searchstr))
			try:
				result = self.api.search_all_access(searchstr, max_results=1)
				print ("Found " + result['song_hits'][0]['track']['artist'] + " - " + result['song_hits'][0]['track']['title'])
				nid = result['song_hits'][0]['track']['nid']
				db.storemapping(track.song, track.artist, nid)
			except:
				print ("Error parsing result: " + str(result))
				
			time.sleep(1)
	
	def maintain(self, tracks):
		print ("Searching for playlist %s" % (self.playlistName))
				
		found = False
		searchres = self.api.get_all_playlists()
		for list in searchres:
			if list['name'] == self.playlistName:
				found = True
				pid = list['id']
				
		if not found:
			print ("Not found - creating")
			pid = self.api.create_playlist(self.playlistName)
		
		print ("Playlist id is %s" % (pid))
		
		print ("Getting current contents")
		playlists = self.api.get_all_user_playlist_contents()
		currentEntries = []
		for playlist in playlists:
			if playlist['name'] == self.playlistName:
				for entry in playlist['tracks']:
					currentEntries.append(entry['id'])

		print ("Removing songs")		
		self.api.remove_entries_from_playlist(currentEntries)
		
		print ("Adding songs")
		self.api.add_songs_to_playlist(pid, tracks)
Esempio n. 28
0
class AudioStream:
    __username = configuration.get('google_username')
    __password = configuration.get('google_password')
    __track_prefetch = 15
    __client = None
    __playlist = []

    def __init__(self, station_id = 'IFL'):
        self.__client = Mobileclient()
        self.__client.login(self.__username, self.__password, Mobileclient.FROM_MAC_ADDRESS)
        self.__playlist = self.__fetchTrackIDs(station_id)

    def __del__(self):
        if self.__client:
            self.__client.logout()

    def __fetchTrackIDs(self, station_id):
        if not self.__client or not self.__client.is_authenticated():
            logger.error("Client is not authenticated!")
            return []

        tracklist = self.__client.get_station_tracks(station_id, num_tracks=self.__track_prefetch)
        logger.info("Received tracks: %r" % json.dumps(tracklist))

        # Filter out explicit tracks, where non-explicit is explicitType=2
        tracklist = [track for track in tracklist if not 'explicitType' in track or track['explicitType'] == "2"]
        logger.info("Non-explicit tracks: %r" % json.dumps(tracklist))

        # Fetch both song IDs and Nautilus (old) IDs
        songids = [track['id'] for track in tracklist if 'id' in track]
        nautids = [track['nid'] for track in tracklist if 'nid' in track]

        return songids + nautids

    def pop(self):
        while self.__playlist:
            track_id = self.__playlist.pop()

            try:
                stream_url = self.__client.get_stream_url(track_id, quality='low')
                return stream_url
            except(exceptions.CallFailure):
                logger.warning("Failed to fetch Stream URL for ID %s" % track_id)

            raise IndexError("pop from empty list")

    def reverse(self):
        # Reverse just returns itself, since the playlist is already chaos
        return self

    def __len__(self):
        return len(self.__playlist)
Esempio n. 29
0
class Plugin:
    name = 'gmusic'

    def __init__(self, username, password):
        self.client = Mobileclient()
        self.client.login(username, password, Mobileclient.FROM_MAC_ADDRESS)
        # self.webclient = Webclient()
        # self.webclient.login(username, password)

    def get_tracks(self, artist=None, album=None):
        """
        Fetches tracks from api.

        If no filter is defined, it will get user tracks
        """
        return TrackList(self.client.get_all_songs())

    def get_playlists(self):
        """
        Get playlists and radios
        """
        playlists = []
        for playlist in self.client.get_all_user_playlist_contents():
            tracks = TrackList([self.client.get_track_info(x['trackId']) for x in playlist['tracks']])
            playlists.append(PlayList(playlist['name'], tracks))
        return playlists

    def stream(self, track):
        def _stream(url):
            inp = requests.get(url, stream=True)
            chunk_size = 1024
            for chunk in inp.iter_content(chunk_size):
                if not chunk:
                    continue
                yield chunk
        song_id = track.uri.split(':')[-1]
        return _stream(self.client.get_stream_url(song_id))

    def search(self, keywords, matches):
        results = self.client.search(keywords)
        if matches == 'artist':
            return {'artists': results.get('artist_hits', [])}
        elif matches == 'album':
            return {'albums': results.get('album_hits', [])}
        elif matches == 'tracks':
            return {'tracks': results.get('song_hits', [])}
        elif matches == 'all':
            return {'artists': results.get('artist_hits', []),
                    'albums': results.get('album_hits', []),
                    'tracks': results.get('song_hits', [])}
Esempio n. 30
0
def login_to_gmusic(username, password):
    """
    DEPRECATED, use login_to_gmusic_with_oauth() instead
    params: username & password for your gmusic account
    returns the authenticated gmusic api object
    """
    gm_api = Mobileclient()
    gm_api.login(email=username, password=password, \
              android_id=gm_api.FROM_MAC_ADDRESS, locale=u'es_ES')
    if gm_api.is_authenticated():
        print('Logged in to Google Music')
        return gm_api
    else:
        sys.stderr.write('error logging in, exiting program')
        sys.exit()
def lastfm_to_google_music(lastfm_user, lastfm_apikey, gmusic_email, gmusic_password):
    lastfm_client = LastFMClient()
    gmusic_client = Mobileclient()
    gmusic_client.login(gmusic_email, gmusic_password)
   

    tracks= defaultdict(list)

    # get gmusic all songs
    gmusic_load =  gmusic_client.get_all_songs()
    for element in gmusic_load :
        rp_artist = element["artist"].encode('utf8').lower()
        rp_title = element["title"].encode('utf8').lower()
        tracks["gmusic"].append((rp_artist,rp_title))


    # get lastfm loves
    lastfm_likes = lastfm_client.liked_tracks(lastfm_user, lastfm_apikey)
    json_string = json.loads(lastfm_likes)
    for element in json_string["lovedtracks"]["track"]:
        rp_artist = element["artist"]["name"].encode('utf8').lower()
        rp_title = element["name"].encode('utf8').lower()
        tracks["lastfm"].append((rp_artist,rp_title))


    match = set(tracks["lastfm"]) & set(tracks["gmusic"])

    print "gmusic total"
    print sum(len(x) for x in tracks["gmusic"])

    print "Lastfm likes total"
    lastfm_like_count = sum(len(x) for x in tracks["lastfm"])
    print lastfm_like_count

    print "matched with gmusic"
    print sum(len(x) for x in match)

    print "not matched"
    print list(set(tracks["lastfm"]) - set(match))

    for element in gmusic_load:
        rp_artist = element["artist"].encode('utf8').lower()
        rp_title = element["title"].encode('utf8').lower()

        for element2 in match:
            if element2 == (rp_artist,rp_title):
                element['rating'] = '5'
                gmusic_client.change_song_metadata(element)
Esempio n. 32
0
class PlayPiApp(AppConfig):
    name = 'play_pi'
    label = 'play_pi'
    verbose_name = 'Play Pi'

    def ready(self):
        from play_pi.models import RadioStation
        from play_pi.utils import mpd_client
        super(PlayPiApp, self).ready()
        Track = self.get_model('Track')
        try:
            with mpd_client() as client:
                playlist = client.playlistinfo()
                mpd_ids = tuple(int(song['id']) for song in playlist)
            q = Q(mpd_id__gt=0) & ~Q(mpd_id__in=mpd_ids)
            Track.objects.filter(q).update(mpd_id=0)
            RadioStation.objects.filter(q).update(mpd_id=0)
        except Exception:
            # Will happen if migrations have not ran yet
            # Or mpd is not running
            pass

    def get_credentials(self):
        from play_pi.models import GoogleCredentials
        return GoogleCredentials.objects.enabled().get()

    def get_api(self):
        if not hasattr(self, 'api'):
            from gmusicapi import Mobileclient
            self.api = Mobileclient()
            credentials = self.get_credentials()
            login = self.api.login(credentials.username, credentials.password, credentials.device_id)
            if not login:
                raise Exception('Login error')
        return self.api
Esempio n. 33
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
def login_to_google_music(user):
    api = Mobileclient()

    # Try to read the username and password from a file
    # This is useful for 2-step authentication
    # Don't store your regular password in plain text!
    try:
        creds_file = open(CREDS_FILE)
        creds = json.load(creds_file)
    except IOError:
        creds = {}

    try:
        user = creds["username"]
    except KeyError:
        if not user:
            user = raw_input("Google username/email: ")

    try:
        password = creds["password"]
    except KeyError:
        password = getpass()

    print "\nLogging in..."
    if api.login(user, password, Mobileclient.FROM_MAC_ADDRESS):
        return api
    else:
        print "Login failed. Giving up."
        exit(1)
Esempio n. 35
0
 def __init__(self, hass, config):
     """Initialize the books authors."""
     global G_GM_MOBILE_CLIENT_API
     self.hass = hass
     self.all_gm_tracks = []
     self.selected_books = []
     from gmusicapi import Mobileclient
     G_GM_MOBILE_CLIENT_API = Mobileclient()
     G_GM_MOBILE_CLIENT_API.login(GM_USER, GM_PASS, GM_DEV_KEY)
     if not G_GM_MOBILE_CLIENT_API.is_authenticated():
         _LOGGER.error("Failed to log in, check gmusicapi")
         return False
     else:
         _LOGGER.info("OK - we are in Gmusic")
         _LOGGER.info("devices: " +
                      str(G_GM_MOBILE_CLIENT_API.get_registered_devices()))
Esempio n. 36
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
Esempio n. 37
0
class gmusicConfig:

    def __init__(self, account):
        self.account = account
        self.open_config()
        self.api = Mobileclient()

    def open_config(self):
        config = configparser.ConfigParser()

        cf = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            "api.cfg"
            )
        if not config.read([cf]):
            print("No login configuration file found!")

        self.email = config.get(self.account, 'email')
        self.password = config.get(self.account, 'password') 

    def login(self):
        try:
            logged_in = self.api.login(self.email, self.password, self.api.FROM_MAC_ADDRESS)
            if logged_in == False:
                print("Google Music API login failed")
                sys.exit()
            if logged_in == True:
                return logged_in
        except:
            print("Google Music API login failed")
Esempio n. 38
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})
Esempio n. 39
0
	def download_songs(self):
		api = Musicmanager()
		ip = urllib2.urlopen('http://ip.42.pl/raw').read() #Obtain your public IP address
		mac_binary = str(get_mac()) #Obtain binary MAC address
		temp = mac_binary.replace(':', '').replace('-', '').replace('.', '').upper()
		mac_h3x = temp[:2] + ":" + ":".join([temp[i] + temp[i+1] for i in range(2,12,2)]) #Convert MAC from 48bit int to hexadecimal string
		user = pwd.getpwuid(os.getuid())[0] #Get your system's username
		hostname = '<' + ip + '>' + '' + '(gmusicapi-{2.0.0})'
		Musicmanager.perform_oauth(storage_filepath='/home/' + user + '/.config/gmusicapi/oauth.cred', open_browser=False)
		api.login(oauth_credentials='/home/' + user + '/.config/gmusicapi/oauth.cred', uploader_id=mac_h3x, uploader_name=hostname)
		gmusicapi.clients.Musicmanager(debug_logging=True, validate=True)		
		playlist_id = raw_input("insert id: ")
		
		api_ = Mobileclient()
		api_.login(self.email, self.password)
		playlist_method = api_.get_all_playlists()
Esempio n. 40
0
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
Esempio n. 41
0
class GoogleMusic(Source):
    def __init__(self, library, username, password):
        Source.__init__(self, library, SourceType.GOOGLE)
        self.GOOGLE_DEVICE_ID = None

        print username
        print password

        self.client = Mobileclient()
        logged_in = self.client.login(username, password, Mobileclient.FROM_MAC_ADDRESS)
        print "Google logged in:", logged_in

        DList = self.client.get_registered_devices()
        self.GOOGLE_DEVICE_ID = DList[0]["id"]
        if self.GOOGLE_DEVICE_ID[:2] == '0x':
            self.GOOGLE_DEVICE_ID = self.GOOGLE_DEVICE_ID[2:]

        print self.GOOGLE_DEVICE_ID

        #>testing
        # self.get_stream_URL("47b9d52c-9d66-3ff2-94d4-3ae55c0d2acc")

    def get_stream_URL(self, song_id):
        return self.client.get_stream_url(song_id, self.GOOGLE_DEVICE_ID)

    def sync(self):
        gmusic_tracks = self.client.get_all_songs()
        for track in gmusic_tracks:
            art = ''
            try:
                art = track['albumArtRef'][0]['url']
            except KeyError:
                art = ''
            self.library.insert_track(track['title'], track['album'], track['artist'], self._source, str(track['id']), track['trackNumber'], art)
def login_to_google_music(user):
    api = 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 api.login(user, password):
            return api
        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)
Esempio n. 43
0
def login(username,password):
	api = Mobileclient()
	try:
		loggedin = api.login(username, password)
		return api
	except:
		return False
def ask_for_credentials():
    """Make an instance of the api and attempts to login with it.
    Returns the authenticated api.
    """

    # We're not going to upload anything, so the Mobileclient is what we want.
    api = Mobileclient(debug_logging=False)

    logged_in = False
    attempts = 0

    #try:
    #    logged_in = api.login("mail", "pass", Mobileclient.FROM_MAC_ADDRESS)
    #except:
    #    print(Fore.YELLOW + "Error logging you in!")

    while not logged_in and attempts < 3:
        print("Please log in into your Google Play account.")
        email = input('Email: ')
        password = getpass()

        logged_in = api.login(email, password, Mobileclient.FROM_MAC_ADDRESS)
        attempts += 1

    return api
Esempio n. 45
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():
    logger.info('Scanning the Billboard Charts......')
    chart_df_dict = {}
    global gmusic
    if not gmusic:
        gmusic = Mobileclient(debug_logging=False)
        gmusic.login(email=USER_NAME,
                     password=APP_PASSWORD,
                     locale='en_US',
                     android_id=Mobileclient.FROM_MAC_ADDRESS)
    for chart, chart_name in charts_to_playlist:
        logger.info('Getting {}......'.format(chart_name))
        chart_scraped = billboard.ChartData(config['BILLBOARD'][chart])
        chart_df = get_song_df(chart_scraped)
        #Delete Playlist if present.
        logger.info('Updating {} Playlist......'.format(chart_name))
        delete_playlist_if_exists(chart_name)
        #Create Playlist
        playlist_id = gmusic.create_playlist(
            name=chart_name,
            description=chart_name + ' from Billboard on week {}'.format(
                current_week(dt.datetime.today())),
            public=True)
        gmusic.add_songs_to_playlist(
            playlist_id=playlist_id,
            song_ids=chart_df.song_id.dropna().tolist())
        chart_df_dict[chart] = chart_df
        #Top Rising from Hot 100
        if chart_df_dict.has_key('HOT_100'):
            logger.info('Updating {} Playlist......'.format('Top 25 Risers'))
            top_100 = chart_df_dict['HOT_100']
            top_100.loc[top_100.change == 'Hot Shot Debut', 'change'] = 100
            top_100.change = pd.to_numeric(top_100.change,
                                           errors='coerce').fillna(0)
            hot25_risers = top_100.sort_values(
                by=['change'],
                ascending=False).head(25).sort_values(by=['rank'],
                                                      ascending=True)
            delete_playlist_if_exists('Top 25 Risers')
            playlist_id = gmusic.create_playlist(
                'Top 25 Risers',
                'Top 25 Risers from Hot 100 Billboard on week {}'.format(
                    current_week(dt.datetime.today())))
            gmusic.add_songs_to_playlist(
                playlist_id=playlist_id,
                song_ids=hot25_risers.song_id.dropna().tolist())
            logger.info('Finished Updating......'.format('Top 25 Risers'))
Esempio n. 47
0
class GoogleMusicClient(object):

    def __init__(self, email, password, device_id):
        self.api = Mobileclient()
        self.api.login(email, password)
        self.device_id = device_id

        self.playlists = []
        self.songs = {}

        self.player = Player()

    def update_library(self):
        self.songs = {song.get('nid'): song for song in self.api.get_all_songs()}

        self.playlists = [
            Playlist(name=playlist['name'].encode('utf-8'),
                     tracks=[track['trackId'] for track in playlist['tracks']])
            for playlist in self.api.get_all_user_playlist_contents()
        ]

    def play(self, item_type, item_index):
        if item_type == 'playlist':
            click.echo('playing {} {}'.format(item_type, self.playlists[int(item_index)].name))

    def queue(self, item_type, item_index):
        if item_type == 'playlist':
            for song in self.playlists[int(item_index)]:
                self.player.enqueue(song)

    def show(self, item_type, item_index):
        if item_type == 'playlist':
            playlist = self.playlists[int(item_index)]
            click.echo('showing {} {}'.format(item_type, playlist.name))
            for song in playlist.tracks:
                click.echo(self.songs[song])
        elif item_type == 'queue':
            for song in self.player.queue:
                click.echo(song)

    def list(self, item_type):
        if item_type == 'playlist':
            for i, playlist in enumerate(self.playlists):
                click.echo("[{}]\t{} ({})".format(i, playlist.name, len(playlist.tracks)))
        elif item_type == 'songs':
            click.echo(self.songs)
Esempio n. 48
0
def main():

    api = Mobileclient()
    if not api.login(credentials.email, credentials.password):
        print "Couldn't log in :("
        return

    check_playlists(api)
Esempio n. 49
0
def pandora_to_google_music(pandora_email, pandora_password, gmusic_email,
                            gmusic_password):
    """ Sync Pandora likes with Google Music playlists """

    gmusic_client = Mobileclient()
    gmusic_client.login(gmusic_email, gmusic_password)

    pandora_client = PandoraClient(pandora_email, pandora_password)

    # Get liked Pandora tracks
    pandora_likes = pandora_client.liked_tracks()
    pandora_like_count = sum(len(x) for x in pandora_likes.values())

    # Get Pandora stations
    pandora_stations = set(pandora_client.stations())

    pandora_playlists = defaultdict(list)

    # Copy all songs to main playlist
    # Add Pandora prefix to playlist names
    # Remove deleted stations (songs will be in main playlist)
    for station_name, songs in pandora_likes.items():
        # Copy songs to main playlist
        pandora_playlists["Pandora"].extend(songs)

        # Check station hasn't been deleted
        if station_name in pandora_stations:
            pandora_playlists["Pandora - %s" % station_name] = songs

    # Match Pandora likes with Google Music
    playlists = match_playlists_with_gmusic(gmusic_client, pandora_playlists)
    gmusic_match_count = len(playlists.get("Pandora", []))

    # Sync Google Music playlists
    songs_added, songs_removed = sync_gmusic_playlists(gmusic_client,
                                                       playlists)

    print_section_heading("Summary")
    print "%d/%d songs matched" % (gmusic_match_count, pandora_like_count)
    print "{added}/{removed} changes to playlists".format(
        added=colored("+%d" % songs_added, "green"),
        removed=colored("-%d" % songs_removed, "red"),
    )

    return pandora_like_count, gmusic_match_count, songs_added, songs_removed
def get_albums_from_playlist(config):
    login, password, playlist_name, android_id = map(config.get, ('login', 'password', 'playlist', 'android_id'))
    api = Mobileclient()
    if not android_id:
        android_id = Mobileclient.FROM_MAC_ADDRESS 
    try:
        api.login(login, password, android_id)
        all_playlists = api.get_all_user_playlist_contents()
        matched_playlist = next(playlist for playlist in all_playlists if playlist['name'].lower() == playlist_name.lower())
        album_list = {(entry['track']['albumArtist'], entry['track']['album'])
              for entry in matched_playlist['tracks'] if 'track' in entry}
        return album_list
    except StopIteration:
        sys.exit('playlist not found.')
    except NotLoggedIn:
        sys.exit('wrong username or password.')
    finally:
        api.logout()
def setup_mobile_api():
    global mobile_api
    mobile_api = Mobileclient()

    mobile_logged_in = mobile_api.login(username, password)

    if not mobile_logged_in:
        print "Failed to log in to the mobile API, ensure your details are correct and try again."
        sys.exit(0)
Esempio n. 52
0
def main():

    api = Mobileclient()
    if not api.login(credentials.email, credentials.password):
        print "Couldn't log in :("
        return

    regen_playlist(api, 'All')
    regen_playlist(api, 'Programming')
Esempio n. 53
0
class Playlist():
    '''
    Parent class for specific types of playlists, like:
        Live Setlist Playlist
            setlist based on the set of songs played at a live concert
        Upcoming Concert Playlist
            setlist generated from a list of bands that have upcoming concerts in an area
    '''
    def __init__(self, make=False):
        self.setup_logging()
        self.api = Mobileclient()
        self.logged_in = self.api.login(
            EMAIL,
            TOKEN,
            # Mobileclient.FROM_MAC_ADDRESS)
            DEVICE_ID)
        if self.logged_in:
            self.info("Logged into GPMAA successfully")

    def setup_logging(self):
        logger_name = '.'.join([__name__, __class__.__name__])
        self.logger = logging.getLogger(logger_name)
        logging.getLogger('gmusicapi.protocol.shared').setLevel(logging.INFO)
        logging.getLogger('urllib3.connectionpool').setLevel(logging.WARNING)

    def error(self, msg):
        self.logger.error(msg)

    def info(self, msg):
        self.logger.info(msg)

    def debug(self, msg):
        self.logger.debug(msg)

    def search(self, query):
        '''
        This function got pulled to the parent class because we'll always be searching
        for things and wanting the song results. They're always going to have to be
        processed this way because of how the search result is formatted.

        The result is a list of song dictionaries with keys such as storeId, artist, etc.
        '''
        res = self.api.search(query)['song_hits']
        res = [song['track'] for song in res]
        return res

    def create_playlist(self, song_ids, name, description='', public=False):
        self.info("Creating {}".format(name))
        self.id = self.api.create_playlist(name, description, public)
        self.api.add_songs_to_playlist(self.id, song_ids)

    def delete_playlist(self):
        if hasattr(self, 'id') and self.id is not None:
            self.info("Deleting playlist id: %s".format(self.id))
            self.api.delete_playlist(self.id)
        else:
            self.info("Can't delete a playlist without its id")
Esempio n. 54
0
def login():
    print("Login to Google Play Music")
    user = raw_input("Username: "******"Password: "******" ")

    if user:
        if password:
            apiMobileClient = Mobileclient(False)
            apiMobileClient.login(user, password, Mobileclient.FROM_MAC_ADDRESS)

            return apiMobileClient
        else:
            print("Password not set")
            sys.exit(1)
    else:
        print("User not set")
        sys.exit(1)
Esempio n. 55
0
def init_gmusic_api():
    t0 = time.time()
    print('init_gmusic_api')
    global api
    api = Mobileclient()
    logged_in = api.login(gmusic_secrets.USERNAME, gmusic_secrets.PW,
                          Mobileclient.FROM_MAC_ADDRESS)
    assert (logged_in)
    print('init_gmusic_api finished: %0.2f' % (time.time() - t0))
Esempio n. 56
0
class PlayMusic:
    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)

    def is_authenticated(self):
        return self.client.is_authenticated()

    @staticmethod
    def track_url(play_track):
        return "https://play.google.com/music/m/%s" % play_track["nid"]

    @staticmethod
    def playlist_url(playlist_id):
        return "https://play.google.com/music/playlist/%s" % playlist_id

    def search_tracks(self, query):
        if len(query) >= MAX_QUERY_LENGTH:
            # long queries don't work for some reason
            # for example "The Moderately Talented Yet Attractive Young Woman vs. The Exceptionally Talented Yet Not
            # So Attractive Middle Aged Man / Sun Kil Moon / Among The Leaves"
            parts = query.split(" ")
            query = parts.pop(0)
            for part in parts:
                if len(query) + 1 + len(part) > MAX_QUERY_LENGTH:
                    break
                query += " " + part

        retries = RETRIES
        response = None
        while retries and not response:
            retries -= 1
            try:
                response = self.client.search_all_access(query)
            except Exception, e:
                if not retries:
                    raise e
                # sleep for two seconds before retrying
                time.sleep(2)
        return [PlayTrack(song["track"]) for song in response["song_hits"]]
def pandora_to_google_music(pandora_email, pandora_password, gmusic_email, gmusic_password):
    """ Sync Pandora likes with Google Music playlists """

    gmusic_client = Mobileclient()
    gmusic_client.login(gmusic_email, gmusic_password, Mobileclient.FROM_MAC_ADDRESS)

    pandora_client = PandoraClient(pandora_email, pandora_password)

    # Get liked Pandora tracks
    pandora_likes = pandora_client.liked_tracks()
    pandora_like_count = sum(len(x) for x in pandora_likes.values())

    # Get Pandora stations
    pandora_stations = set(pandora_client.stations())

    pandora_playlists = defaultdict(list)

    # Copy all songs to main playlist
    # Add Pandora prefix to playlist names
    # Remove deleted stations (songs will be in main playlist)
    for station_name, songs in pandora_likes.items():
        # Copy songs to main playlist
        pandora_playlists["Pandora"].extend(songs)

        # Check station hasn't been deleted
        if station_name in pandora_stations:
            pandora_playlists["Pandora - %s" % station_name] = songs

    # Match Pandora likes with Google Music
    playlists = match_playlists_with_gmusic(gmusic_client, pandora_playlists)
    gmusic_match_count = len(playlists.get("Pandora", []))

    # Sync Google Music playlists
    songs_added, songs_removed = sync_gmusic_playlists(gmusic_client, playlists)

    print_section_heading("Summary")
    print "%d/%d songs matched" % (gmusic_match_count, pandora_like_count)
    print "{added}/{removed} changes to playlists".format(
        added=colored("+%d" % songs_added, "green"),
        removed=colored("-%d" % songs_removed, "red"),
    )

    return pandora_like_count, gmusic_match_count, songs_added, songs_removed
    def __init__(self, login=True, dry_run=False):
        if login:
            try:
                google_username = os.environ.get('USERNAME')
                google_password = os.environ.get('PASSWORD')

                api = Mobileclient()
                api.login(google_username, google_password,
                          Mobileclient.FROM_MAC_ADDRESS)
                if api.is_authenticated():
                    self.api = api
            except:
                print "ERROR: Unable to login with the credentials provided!"
                sys.exit(1)
        if dry_run:
            print "Dry-run mode enabled. Logging only. No changes will be made."
            self.dry_run = True
        else:
            self.dry_run = False