Example #1
0
                    uniqueSongs[key] = song
    for x in thumbsDownSongs:
        print x['artist'] + " - " + x['title']

    #WARN: will make thumbs down
    #TODO: uncomment this line------------------
    #api.rate_songs(thumbsDownSongs, '1')
    print "found " + str(len(thumbsDownSongs)) + " dupe songs"

    #tracks = playlist['tracks']
    #find_and_remove_dups(api, tracks)


# 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)
    #api.perform_oauth()
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. Finding duplicates in playlists"
    dedupeSongs()
        self.makePath(song)
        return os.path.join(song.path, clean(song.title) + ".mp3")

class Song(object):
    def __init__(self, tid, title, artist, album, length):
        self.tid = clean(tid)
        self.title = clean(title)
        self.artist = clean(artist)
        self.album = clean(album)
        self.length = length
    def __repr__(self):
        return "{} - {}".format(self.artist, self.title)

# Login
mc = Mobileclient()
mc.__init__(debug_logging=False, validate=True, verify_ssl=True)
mc.login(username, password, mc.FROM_MAC_ADDRESS)

# Pick a device_id for downloading later
device_id = None
for device in mc.get_registered_devices():
    if device['type'] == 'ANDROID':
        device_id = device['id'][2:] #.encode('ascii','ignore')
        break
    elif device['type'] == 'IOS':
        device_id = device['id']
        break

if not device_id:
    print("No Android or iOS device linked to account!")
    exit()
Example #3
0
import discogs_client
from gmusicapi import Musicmanager
from gmusicapi import Mobileclient

d = discogs_client.Client(
    'ExampleApplication/0.1',
    user_token='KPqrfKmxmnGoqyTHVjoVxcBYumJhRCDbmEsVPnqz')

api = Mobileclient()
mm = Musicmanager()
mm.login()
api.__init__(debug_logging=True, validate=True, verify_ssl=True)
# credentials below
api.oauth_login('000000000', "C:/users/file")


def trackdict(artist, track, year):
    #Puts track info into a dictionary
    dicx = {'artist': artist, 'track': track, 'year': year}
    return dicx


########################################
#         PROGRAM INPUTS               #
########################################
label_name = 'Altered reality records'
playlist_name = 'AutoARR'
how_many_releases = 0  #Leave at 0 for all release - Limit this for labels with lots of releases!
how_many_tracks = 20
descending = True  #True means reverse chronological order, eg. recent first
#======================================#
Example #4
0
def reverseplaylist(playlist_name='', repeat=False, quick=False):
    mc = Mobileclient()
    mc.__init__()

    # Find location of this script
    dir_path = os.path.dirname(os.path.realpath(__file__))

    # Check whether this is the first time the program has been run by searching the directory for the log file
    file_list = os.listdir(dir_path)

    # No log file means not run
    if '.gmusiclog.txt' not in file_list:
        print(
            '\n' +
            'This is the first time this program has been run in this folder.'
            + '\n' + 'performing initial authentication.' + '\n')

        # Autorepeat cannot be true without logfile, override if true
        repeat = False

        # Start with a bogus device ID to determine real id from error message
        devID = 'ffffffff'
        mc.perform_oauth()
        try:
            mc.oauth_login(devID)
        except Exception as e:
            error = str(e)
            IDpos = error.find('*')
            nextIDpos = error.find('\n', IDpos + 1, len(error))
            devID = error[IDpos + 2:nextIDpos]
            # Perform login
            mc.oauth_login(devID)

        # Write authentication stuff to logfile
        with open(dir_path + '/.gmusiclog.txt', 'w') as log:
            log.write(devID + '\n')
            x = datetime.datetime.now()
            timeString = (str(x.day) + '/' + str(x.month) + '/' + str(x.year) +
                          '  ' + str(x.hour) + ':' + str(x.minute) + ':' +
                          str(x.second) + '.' + str(x.microsecond))
            log.write('Initial authentication performed at ' + timeString +
                      '\n')

    # Log file exists, we will check whether the user has requested autorepeat
    else:
        print(
            '\n' +
            'This is not the first time this program has been run in this folder'
            + '\n' + 'performing login.' + '\n')

        # Open the logfile to read device id and previous playlists
        with open(dir_path + '/.gmusiclog.txt', 'r') as log:
            # Get device ID
            devID = log.readline().strip()
            # Look for the playlist name from the bottom of the list
            contents = log.read()

        # Perform login
        mc.oauth_login(devID)
        playlistLocation = contents.rfind('PLAYLIST')
        if playlistLocation != -1:
            # Define end of playlist to make defining desired playlist a little cleaner
            endOfPlaylist = contents.find('\n', playlistLocation,
                                          len(contents))
            desired_playlist = contents[playlistLocation + 10:endOfPlaylist]

        with open(dir_path + '/.gmusiclog.txt', 'a+') as log:

            # Write authentication stuff to logfile
            x = datetime.datetime.now()
            timeString = (str(x.day) + '/' + str(x.month) + '/' + str(x.year) +
                          '  ' + str(x.hour) + ':' + str(x.minute) + ':' +
                          str(x.second) + '.' + str(x.microsecond))
            log.write('Login performed at ' + timeString + '\n')

    # Get user input for desired playlist if autorepeat is not enabled
    if repeat == False and playlist_name == '':
        desired_playlist = input(
            'Name of the playlist being reversed (case sensetive): ')
    elif playlist_name != '':
        # If a name is given this overrides all else
        desired_playlist = playlist_name
    else:
        print('Autorepeat enabled, reversing playlist: ' + desired_playlist +
              '\n')

    # Establish the name of the reversed playlist
    reversed_playlist = desired_playlist + 'REVERSED'

    # Check to see whether the desired and reversed playlists exist yet
    allPlaylists = mc.get_all_playlists()
    desired_playlist_index = -1
    reversed_playlist_index = -1
    for n in allPlaylists:
        if n['name'] == reversed_playlist:
            reversed_playlist_index = n
            reversedID = n['id']
        elif n['name'] == desired_playlist:
            desired_playlist_index = n
            desiredID = n['id']

    # Desired playlist exists, so we check to see if it has also been reversed
    if desired_playlist_index != -1:
        # We cache the playlist name so that it can be automatically re-reversed next time
        with open(dir_path + '/.gmusiclog.txt', 'a+') as log:
            log.write('PLAYLIST: ' + desired_playlist + '\n')

        # Desired playlist has been reversed, we can either delete the old one before proceeding
        # or perform a quick update
        if reversed_playlist_index != -1:
            print('The ' + desired_playlist + ' playlist has been reversed.')

            # Determine whether to do a quick update or not
            if quick == True:
                print('performing quick update')
                quick_update(mc, desiredID, reversedID)
                return
            else:
                print('Performing full update\n' +
                      'Deleting the old playlist...\n')
                mc.delete_playlist(reversedID)

        # Desired playlist has not been reversed, create the reverse
        else:
            print('The ' + desired_playlist +
                  ' playlist has not been reversed, creating the reverse now.')

        # If we have got this far, the reversed playlist doesn't exist
        print('Generating reversed song list...')
        reversedID, id_list = create_new(mc, desired_playlist)
        print('Adding songs to the playlist...')
        mc.add_songs_to_playlist(reversedID, id_list)
        print('Done!')

    # No such playlist exists
    else:
        print(
            'No playlist by the name of ' + desired_playlist +
            ' found. Did you spell it correctly? A reminder here that the playlist name is case sensetive.'
        )
### Main

if len(sys.argv) != 3:
    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)
import os
import random
import sys

from functools import reduce
from itertools import takewhile

from gmusicapi import Mobileclient
from gmusicapi.exceptions import InvalidDeviceId
from gmusicapi.appdirs import my_appdirs

playlistName = 'Album shuffle'

# Initialise the Google Play Music API
mc = Mobileclient()
mc.__init__()

print('Logging in')
if os.path.isfile(mc.OAUTH_FILEPATH):
    # We have credentials - do a normal login.
    # Need to get a valid device ID from the exception text when using an invalid ID.
    deviceId = 'deviceId'
    while True:
        try:
            mc.oauth_login(deviceId)
            break
        except InvalidDeviceId as exc:
            deviceId = str(exc).split('\n')[1].replace('* ', '')
else:
    # First time login - do OAuth in browser
    mc.perform_oauth(open_browser=True)