本文整理汇总了Python中gmusicapi.Musicmanager类的典型用法代码示例。如果您正苦于以下问题:Python Musicmanager类的具体用法?Python Musicmanager怎么用?Python Musicmanager使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Musicmanager类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
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
示例2: run
def run():
global download_dir, notify_plex, mm
download_dir, notify_plex = parse_args()
log("Creating music manager")
mm = Musicmanager()
log("Attempting login")
if not mm.login():
print "OAuth required:"
mm.perform_oauth()
get_songs()
示例3: GMusicPodcastSyncDestination
class GMusicPodcastSyncDestination(PodcastSyncDestination):
def __init__(self):
super(GMusicPodcastSyncDestination, self).__init__()
self.serviceIdentifier = "GOO"
self.serviceName = "Google Music"
self.musicManager = Musicmanager()
self.mobileClient = Mobileclient()
oAuthFile = "gMusic.oauth"
if not os.path.isfile(oAuthFile):
if not self.musicManager.perform_oauth(oAuthFile, True):
print "Failed to authenticate Music Manager."
raise PodcastSyncDestinationException("Authentication Failure.")
else:
try:
self.musicManagerauthenticated = self.musicManager.login(oAuthFile)
except gmusicapi.exceptions.AlreadyLoggedIn:
pass
username = raw_input("Enter Google Username: ")
password = getpass.getpass("Enter Google Password: ")
if not self.mobileClient.login(username, password, Mobileclient.FROM_MAC_ADDRESS):
raise PodcastSyncDestinationException("Authentication Failure.")
# perform a push task. should return a PodFastPodcastPushedEpisode instance
def pushEpisode(self, podcastSyncTaskEpisodePush):
(uploaded, matched, not_uploaded) = self.musicManager.upload([podcastSyncTaskEpisodePush.localFilename])
songGoogleMusicID = ""
if not_uploaded: # If the track was not uploaded, it may have been uploaded in the past.
p = re.compile("ALREADY_EXISTS\\((.*)\\)")
m = p.findall(not_uploaded[podcastSyncTaskEpisodePush.localFilename])
songGoogleMusicID = m[0]
else:
songGoogleMusicID = uploaded[podcastSyncTaskEpisodePush.localFilename]
print "Track uploaded Successfully. ID:" + songGoogleMusicID
gmusicPlayLists = self.mobileClient.get_all_playlists()
playListExists = False
gmusicPlaylistID = ""
for gmusicPlayList in gmusicPlayLists:
if gmusicPlayList["name"] == podcastSyncTaskEpisodePush.playlistName:
playListExists = True
gmusicPlaylistID = gmusicPlayList["id"]
break
if not playListExists:
print "Creating playlist..."
gmusicPlaylistID = self.mobileClient.create_playlist(podcastSyncTaskEpisodePush.playlistName)
addedEntries = self.mobileClient.add_songs_to_playlist(gmusicPlaylistID, [songGoogleMusicID])
print "Moved track to playlist."
return songGoogleMusicID
# Pull (deletes) an episode from the destination returns true on success, False on faiilure
def pullEpisode(self, podcastSyncTaskEpisodePull):
self.mobileClient.delete_songs([podcastSyncTaskEpisodePull.syncDestinationID])
# TODO: Error check here.
return True
示例4: GoogleClient
class GoogleClient():
def __init__(self, username=None, password=None):
self._username = username
self._password = password
# Initiates the oAuth
def Authenticate(self):
self.MusicManager = Musicmanager(debug_logging=False)
attempts = 0
# Attempt to login. Perform oauth only when necessary.
while attempts < 3:
if self.MusicManager.login():
break
self.MusicManager.perform_oauth()
attempts += 1
if not self.MusicManager.is_authenticated():
print("Sorry, login failed.")
return False
print("OAuth successfull\n")
username = self._username
password = self._password
if not username or not password:
cred_path = os.path.join(os.path.expanduser('~'), '.gmusicfs')
if not os.path.isfile(cred_path):
raise Exception(
'No username/password was specified. No config file could '
'be found either. Try creating %s and specifying your '
'username/password there. Make sure to chmod 600.'
% cred_path)
if not oct(os.stat(cred_path)[os.path.stat.ST_MODE]).endswith('00'):
raise Exception(
'Config file is not protected. Please run: '
'chmod 600 %s' % cred_path)
self.config = ConfigParser.ConfigParser()
self.config.read(cred_path)
username = self.config.get('credentials','username')
password = self.config.get('credentials','password')
if not username or not password:
raise Exception(
'No username/password could be read from config file'
': %s' % cred_path)
self.Api = Mobileclient(debug_logging = False)
if not self.Api.login(username, password, Mobileclient.FROM_MAC_ADDRESS):
raise Exception('login failed for %s' % username)
return True
示例5: download_songs
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()
示例6: api_init
def api_init():
mm = Musicmanager()
e = settings['email']
creds = os.path.expanduser("~/.local/share/gmusicapi/oauth.cred") # default oauth store location
if OTHERACCOUNT:
e = settings['email2']
creds = os.path.expanduser("~/.local/share/gmusicapi/oauth2.cred")
if e is not None:
if settings['first'] == '1' or OTHERACCOUNT and settings['first2'] == '1':
print "Performing OAUTH for %s" % e
mm.perform_oauth(storage_filepath=creds)
update_first(e)
log("Logging in as %s" % e)
if mm.login(oauth_credentials=creds):
return mm
log("Login failed for second user")
return False
示例7: __init__
def __init__(self):
super(Gmusic, self).__init__()
# Checks for OAuth2 credentials,
# if they don't exist - performs authorization
self.m = Musicmanager()
if os.path.isfile(gmusicapi.clients.OAUTH_FILEPATH):
self.m.login()
else:
self.m.perform_oauth()
示例8: GoogleManager
class GoogleManager():
def __init__(self, directory):
self.music_dir = directory
self.Google = Musicmanager()
self.Google.login()
def upload(self):
files = []
for dirpath, dirnames, filenames in walk(self.music_dir):
for name in filenames:
if name.endswith('.mp3'):
files += [join(dirpath, name)]
for f in files:
ret = self.Google.upload(f)
print(ret)
示例9: GoogleClient
class GoogleClient():
# Initiates the oAuth
def Authenticate(self):
self.MusicManager = Musicmanager(debug_logging=False)
attempts = 0
# Attempt to login. Perform oauth only when necessary.
while attempts < 3:
if self.MusicManager.login():
break
self.MusicManager.perform_oauth()
attempts += 1
if not self.MusicManager.is_authenticated():
print "Sorry, login failed."
return False
print "Successfully logged in.\n"
return True
示例10: setup_music_manager_api
def setup_music_manager_api():
global music_manager_api
music_manager_api = Musicmanager()
if not config.get_is_authenticated():
print "Follow the instructions to authenticate with Google..."
credentials = music_manager_api.perform_oauth()
if credentials is not None:
config.set_is_authenticated(True)
else:
print "Failed to authenticate, try again."
sys.exit(0)
music_manager_logged_in = music_manager_api.login()
if not music_manager_logged_in:
print "Failed to log in to the music manager API, you will be asked to authenticate again next run."
sys.exit(0)
示例11: download_user_track
def download_user_track(mgr: gmusicapi.Musicmanager, full_path, track):
dirname = os.path.dirname(full_path)
fp, temp_path = tempfile.mkstemp(dir=dirname)
try:
fname, audio = mgr.download_song(track['id'])
fp.write(audio)
os.rename(temp_path, full_path)
finally:
if os.path.exists(temp_path):
os.unlink(temp_path)
示例12: __init__
def __init__(self):
super(Gmusic, self).__init__()
self.m = Musicmanager()
self.config.add({
u'auto': False,
u'uploader_id': '',
u'uploader_name': '',
u'device_id': '',
u'oauth_file': gmusicapi.clients.OAUTH_FILEPATH,
})
if self.config['auto']:
self.import_stages = [self.autoupload]
示例13: __init__
def __init__(self):
"""
Log into Musicmanager and get the library, either by loading an
existing library file, or by generating a new one.
"""
self.kind = 'free'
self.mm = Musicmanager()
self.mm.login()
self.songs = []
self.load_library()
if not self.songs:
self.gen_library()
示例14: __init__
def __init__(self, email=None, password=None):
self.mm = Musicmanager()
self.wc = Webclient()
if not email:
email = raw_input("Email: ")
if not password:
password = getpass()
self.email = email
self.password = password
self.logged_in = self.auth()
print "Fetching playlists from Google..."
self.playlists = self.wc.get_all_playlist_ids(auto=False)
print "Got %d playlists." % len(self.playlists['user'])
print ""
示例15: init
def init(self, oauth_credentials):
# Initialize the database
logger.info("%s: Initializing database" % self.email)
self._data_init()
# Create the Musicmanager
logger.info("%s: Logging in to Google music" % self.email)
self.mm = Musicmanager()
if not self.mm.login(oauth_credentials):
logger.info("%s: Error logging in to Google music" % self.email)
return False
# Check if we already have any watch paths configured
config = self._read_config()
watched_paths = config["watched_paths"] if "watched_paths" in config else []
logger.info("%s: Found previously watched paths %s" % (self.email, watched_paths))
# Create the FileWatcher
logger.info("%s: Creating the FileWatcher" % (self.email))
self.fw = FileWatcher(self.email, self._finished_writing_callback, watched_paths)
return True