-
Notifications
You must be signed in to change notification settings - Fork 5
/
PlayListParser.py
96 lines (77 loc) · 2.43 KB
/
PlayListParser.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
#!/usr/bin/env python
#coding=utf-8
import json
import sys
import os
from MP3Crawler import *
from Constants import *
class PlayListParser(object):
"""This class is used to parser json result """
@classmethod
def init(cls):
#change the default coding
reload(sys)
sys.setdefaultencoding('utf-8')
if not os.path.isdir(playListInfoDir):
os.mkdir(playListInfoDir)
if not os.path.isdir(musicInfoDir):
os.mkdir(musicInfoDir)
if not os.path.isdir(mp3Dir):
os.mkdir(mp3Dir)
@classmethod
def parser(cls,jsonText):
jsonData=json.loads(jsonText,encoding='utf-8')
return jsonData
@classmethod
def savePlayListInfo(cls,josnData):
'''save a playlist info as file
##TODO save into database
'''
playListInfo= josnData['result'].copy()
del playListInfo['tracks']
id = playListInfo['id'] ##TODO raise some exception
if id :
playListInfoFie = open(playListInfoDir+str(id)+'.txt', 'w')
playListInfoFie.write(json.dumps(playListInfo,encoding="UTF-8",ensure_ascii=False))
playListInfoFie.close( )
return True
else:
print 'save playListInfo fail'
return False
@classmethod
def downloadMusics(cls,jsonData,mp3Crawler):
''''download mp3 music and save music info '''
tracks = jsonData['result']['tracks']
for track in tracks:
PlayListParser.__saveMusic(track,mp3Crawler)
@classmethod
def __saveMusic(cls,track,mp3Crawler):
'''save a mp3 music info as file
##TODO save into database
and save mp3 file
'''
id = track['id'] ##TODO raise some exception
if id :
musicInfoFie = open(musicInfoDir+str(id)+'.txt', 'w')
#text=
musicInfoFie.write(json.dumps(track,encoding="UTF-8",ensure_ascii=False))
musicInfoFie.close( )
else:
print 'save music info fail'
return False
task={'savePath':mp3Dir + str(id)+'.mp3','url':track['mp3Url'],'type':'mp3'}
mp3Crawler.addTask(task)
return True
if __name__ == '__main__':
fileObject = open('result.json')
try:
jsonText = fileObject.read( )
finally:
fileObject.close( )
crawler = MP3Crawler("MP3Crawler",10)
crawler.start()
PlayListParser.init()
jsonData = PlayListParser.parser(jsonText)
if PlayListParser.savePlayListInfo(jsonData):
PlayListParser.downloadMusics(jsonData,crawler)
crawler.waitUtilComplete()