-
Notifications
You must be signed in to change notification settings - Fork 0
/
gplaydownload.py
executable file
·78 lines (69 loc) · 2.34 KB
/
gplaydownload.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import sys
import getopt
import os
import os.path
import time
import requests
from gmusicapi import Musicmanager
def usage():
print "usage: gplaydownload.py [-d|--download-dir=dir]"
def parse_args():
download_dir = '.'
notify_plex = False
try :
opts, extraparams = getopt.getopt(sys.argv[1:], 'nd:h', ['notify-plex', 'download-dir=', 'help'])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ['-h', '--help']:
usage()
sys.exit(2)
elif opt in ['-d', '--download-dir']:
download_dir = arg
elif opt in ['-n', '--notify-plex']:
notify_plex = True
if not download_dir.endswith('/'):
download_dir += '/'
return download_dir, notify_plex
def log(msg):
print time.asctime(time.localtime(time.time())) + ": " + msg
def get_songs():
log("Checking for updates")
songs = mm.get_all_songs()
downloaded_songs = False
for song in songs:
path = song['artist'][0] + '/' + song['artist'] + '/' + song['album']
path = path.lower().replace(' ', '_')
path = download_dir + path
track_number = str(song['track_number'])
if len(track_number) < 2:
track_number = '0' + track_number
filename = track_number + ' ' + song['title'] + '.mp3'
filename = filename.lower().replace(' ', '_')
full_path = path + '/' + filename
if not os.path.isfile(full_path):
if not os.path.isdir(path):
log("Creating directory " + path)
os.makedirs(path)
log("Downloading " + full_path)
suggested_filename, audio = mm.download_song(song['id'])
with open(full_path, 'wb') as f:
f.write(audio)
downloaded_songs = True
if downloaded_songs and notify_plex:
log("Notifying local Plex Media Server to refresh")
r = requests.get('http://localhost:32400/library/sections/3/refresh?force=1')
r.raise_for_status()
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()
if __name__ == "__main__":
run()