forked from wlp2s0/GMusic-Downloader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgmusic-dl.py
138 lines (115 loc) · 3.78 KB
/
gmusic-dl.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#!/usr/bin/env python
import os
import sys
from argparse import ArgumentParser
import eyed3
from gmusicapi import Mobileclient
from gmusicapi.exceptions import InvalidDeviceId
from goldfinch import validFileName as vfn
from tqdm import tqdm
from shutil import move
try:
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve
def npath(path):
return vfn(path, space='keep', initCap=False).decode('utf-8').rstrip('.')
parser = ArgumentParser()
parser.add_argument(dest='mail',
help='Your google mail for login.')
parser.add_argument('-o', '--output', dest='output',
default=os.path.join(os.getcwd(), 'Music'),
help='Destination to download files to. Default is ./Music/ (same folder)')
#parser.add_argument('-p', '--password', dest='passwd')
parser.add_argument('-i', '--device-id', dest='device_id', default=0,
help='Device ID to use - run without argument first to see available device IDs and then use one.')
parser.add_argument('-l', '--log', dest='log', action='store_true',
help='Enable to have log printed to "log.txt".')
args, unknown = parser.parse_known_args()
login = args.mail
targetDir = args.output
#log_path = os.path.join(os.getcwd(), 'log.txt') if args.log else None
device_id = args.device_id
eyed3.log.setLevel('ERROR')
api = Mobileclient(debug_logging=True)
if not os.path.exists(api.OAUTH_FILEPATH):
api.perform_oauth(
storage_filepath=api.OAUTH_FILEPATH,
open_browser=True
)
try:
logged_in = api.oauth_login(
args.device_id
)
except InvalidDeviceId as e:
print(str(e))
sys.exit()
print('\nSuccessful login:', logged_in)
if not logged_in:
exit()
pbar = tqdm(api.get_all_songs())
skipped = []
downloaded = []
failed = []
for song in pbar: # album['tracks']:
dirName = os.path.join(
npath(song['artist']),
npath(song['album'])
)
dirPath = os.path.join(
targetDir,
dirName
)
fileName = npath('{:02d}. {}{}'.format(
song['trackNumber'],
song['title'],
'.mp3' if not song['title'].endswith('.mp3') else ''
))
pbar.set_description('{}'.format(fileName).ljust(25)[:25])
filePath = os.path.join(dirPath, fileName)
if os.path.exists(filePath):
skipped.append(fileName)
continue
#print('downloading: ' + fileName)
try:
url = api.get_stream_url(song_id=song['id'], quality='hi')
urlretrieve(url, fileName)
if not os.path.exists(dirPath):
os.makedirs(dirPath)
move(fileName, filePath)
downloaded.append(fileName)
except Exception as e:
print('\n', str(e), '\n')
failed.append(fileName)
continue
audio = eyed3.load(filePath)
if audio.tag is None:
audio.tag = eyed3.id3.Tag()
audio.tag.file_info = eyed3.id3.FileInfo(filePath)
audio.tag.artist = song['artist']
audio.tag.album = song['album']
audio.tag.title = song['title']
audio.tag.track_num = song['trackNumber']
audio.tag.save()
if args.log:
try:
with open('log.txt', 'w') as f:
f.write(
(
'D: {} F: {} S: {}\n'
'Downloaded:\n'
'\t{}\n'
'Failed:\n'
'\t{}\n'
'Skipped:\n'
'\t{}\n'
).format(
len(downloaded), len(failed), len(skipped),
'\n\t'.join(downloaded),
'\n\t'.join(failed),
'\n\t'.join(skipped),
)
)
except Exception as e:
print(str(e))
print('done!')