-
Notifications
You must be signed in to change notification settings - Fork 0
/
parsed.py
211 lines (185 loc) · 5.63 KB
/
parsed.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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#coding:utf-8
"""
VK.com playlist downloader
Downloads entire user audio playlist to the local folder
Authorization required, you must have vkontante login/pass
usage:
python parsed.py -e <your_login> -p <your_pass> -u <user_id with playlist>
"""
import os
import argparse
import requests
import json
import threading
import Queue
#number of threads
THREADS_NUM = 5
VK_audio_url = 'http://vk.com/audio'
queue = Queue.Queue()
class ThreadGrabAudio(threading.Thread):
"""Worker class
For every download there is a thread instance which is
represented by this class
"""
music_folder = 'music'
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
#queue has tasks?
while not queue.empty():
#grab file url from queue
file = self.queue.get()
self.download(file)
self.queue.task_done()
def download(self, file):
"""Download files asynchronously
and save them to local directory 'music'
"""
request = requests.get(file.get('link'), stream=True)
file_name = self.make_filename(file)
with open(file_name, 'wb') as f:
for chunk in request.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
f.flush()
f.close()
def make_filename(self, file):
"""Create normalized file name
consist of author and track name
"""
author = self.normalize_name(file.get('author'))
name = self.normalize_name(file.get('name'))
return self.music_folder + '/' + author + ' - ' + name + '.mp3'
def normalize_name(self, name, separator=' '):
"""remove bullshit from the name and replace with separtor"""
bs = ['&', '#', "'", ';', '?', ':']
rep = ['\\\\', '\\', '//', '/']
for b in bs:
name = name.replace(b, '')
for n in rep:
name = name.replace(n, separator)
return name
class Parsed():
"""Parser class
Creates threading pool to download playlist files
in parallel
"""
SID = None
def __init__(self, user_id='', login='', passwd=''):
self.user_id = str(user_id)
self.login = login
self.passwd = passwd
self.SID = self.auth()
def run(self):
pass
def auth(self):
s = requests.Session()
s.post(
'https://login.vk.com',
data={
"act": "login",
"email": self.login,
"pass": self.passwd
}
)
sid = s.cookies.get('remixsid')
if not sid:
print 'Authorization problem'
return sid
def process_playlist(self):
audios = self.getAudioJSON()
self.ensure_dir('music')
try:
all = json.loads(audios)
for track in all.get('all'):
file = self.trackToFile(track)
#populate queue with files for download
queue.put(file)
#spawn a thread pool
for i in range(THREADS_NUM):
t = ThreadGrabAudio(queue)
t.daemon = True
t.setDaemon(True)
t.start()
except Exception, e:
print e
def ensure_dir(self, dir):
if not os.path.exists(dir):
os.makedirs(dir)
def trackToFile(self, track):
"""Converting track (which is array) to file dict
picking only interesting track info
"""
return {
'link': track[2],
'author': track[5],
'name': track[6]
}
def getAudioJSON(self):
"""Make request for vk.com audio
session id must be provided for remixsid cookie param
"""
res = requests.post(
url=VK_audio_url,
headers={
'Cookie': '; '.join([
'remixdt=0',
'remixtst=8537d36c',
'remixlang=0',
'remixsid=' + self.SID,
'remixflash=11.9.900',
'remixseenads=1'
])
},
data={
'act': 'load_audios_silent',
'al': '1',
'gid': '0',
'id': self.user_id,
'please_dont_ddos': '2'
}
)
#cut some garbage at the beginning
#and decode cyrilic symbols in response
print res
res = res.content[48:].decode('1251')
res = self.fix_json(res)
return res
def fix_json(self, json):
"""remove slashes since they can break download process"""
json = json.replace('\'', '"')
sep_index = json.find('<!>')
json = json[:sep_index]
return json
def main():
parser = argparse.ArgumentParser(description='process params')
parser.add_argument(
'-u', '--user',
help='vk.com user id',
required=True)
parser.add_argument(
'-e', '--email',
help='vk.com user email',
required=True)
parser.add_argument(
'-p',
'--password',
help='vk.com user pass',
required=True)
args = parser.parse_args()
#request audio playlist of the user with given id
if args.user is not None:
p = Parsed(
user_id=args.user,
login=args.email,
passwd=args.password
)
try:
p.process_playlist()
queue.join()
print 'Playlist successfully downloaded!'
except:
print 'Cannot download playlist'
if __name__ == '__main__':
main()