forked from zhendi/DoubanFM-CLI
-
Notifications
You must be signed in to change notification settings - Fork 2
/
douban.py
296 lines (253 loc) · 10.1 KB
/
douban.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# this file should rename to douban_fm_lib.py and should only have net functions
import sys, os
import time
import thread
import pickle
import webbrowser
import json, urllib, httplib, contextlib, random, binascii, calendar
from Cookie import SimpleCookie
from contextlib import closing
from ConfigParser import SafeConfigParser
class PrivateFM(object):
def __init__ (self, channel, is_show = True, use_cache = True, use_webbrowser = False):
self.is_show = is_show
self.use_cache = use_cache
self.use_webbrowser = use_webbrowser
if use_cache:
self.cache = Cache()
self.channel = channel
# todo remove this var
self.dbcl2 = None
self.init_cookie()
self.login()
def init_cookie(self):
self.cookie = {}
if self.use_cache:
cookie = self.cache.get('cookie', {})
self.merge_cookie(cookie)
def login(self):
if self.remember_cookie():
self.login_from_cookie()
else:
self.get_user_input_name_pass()
self.login_from_net(self.username, self.password)
def get_user_input_name_pass(self):
config = SafeConfigParser()
config.read("doubanfm.config")
if config.has_option("DEFAULT","email"):
self.username = config.get("DEFAULT","email").strip()
else:
self.username = raw_input("请输入豆瓣登录账户:")
config.set("DEFAULT","email",self.username)
if config.has_option("DEFAULT","passwd"):
self.password = config.get("DEFAULT","passwd").strip()
else:
import getpass
self.password = getpass.getpass("请输入豆瓣登录密码:")
config.set("DEFAULT","passwd",self.password)
def remember_cookie(self):
return 'dbcl2' in self.cookie and 'bid' in self.cookie
# todo remove this method
def login_from_cookie(self):
dbcl2 = self.cookie['dbcl2'].value
if dbcl2 and len(dbcl2) > 0:
self.dbcl2 = dbcl2
self.uid = self.dbcl2.split(':')[0]
self.bid = self.cookie['bid'].value
def login_from_net(self, username, password):
print '正在登录...'
data = {
'source': 'radio',
'alias': username,
'form_password': password,
'remember': 'on',
'task': 'sync_channel_list'
}
# the flow of geting captcha should be invisibe to user
# so, we should only show one message of geting captha image
captcha_id = self.get_captcha_id()
captcha = self.get_captcha_solution(captcha_id)
data['captcha_id'] = captcha_id
data['captcha_solution'] = captcha
data = urllib.urlencode(data)
print 'Login ...\r',
sys.stdout.flush()
with closing(self.get_fm_conn()) as conn:
headers = self.get_headers_for_request({
'Origin': 'http://douban.fm',
'Content-Type': 'application/x-www-form-urlencoded',
})
conn.request("POST", "/j/login", data, headers)
response = conn.getresponse()
set_cookie = response.getheader('Set-Cookie')
if not set_cookie is None:
cookie = SimpleCookie(set_cookie)
self.save_cookie(cookie)
body = response.read()
body = json.loads(body)
if body['r'] != 0:
print 'login failed'
print body['err_msg']
thread.exit()
return
user_info = body['user_info']
play_record = user_info['play_record']
print user_info['name'],
print '累计收听'+str(play_record['played'])+'首',
print '加红心'+str(play_record['liked'])+'首',
print '收藏兆赫'+str(play_record['fav_chls_count'])+'个'
self.liked = play_record['liked']
self.login_from_cookie()
def get_captcha_solution(self, captcha_id):
self.show_captcha_image(captcha_id)
c = raw_input('验证码: ')
return c
def get_fm_conn(self):
return httplib.HTTPConnection("douban.fm")
def show_captcha_image(self, captcha_id):
with closing(self.get_fm_conn()) as conn:
path = "/misc/captcha?size=m&id=" + captcha_id
print 'http://douban.fm'+path
if self.use_webbrowser:
webbrowser.open('http://douban.fm'+path)
else:
import cStringIO
headers = self.get_headers_for_request()
conn.request("GET", path, None, headers)
response = conn.getresponse()
set_cookie = response.getheader('Set-Cookie')
if not set_cookie is None:
cookie = SimpleCookie(set_cookie)
self.save_cookie(cookie)
if response.status == 200:
body = response.read()
from PIL import Image
f = cStringIO.StringIO(body)
img = Image.open(f)
img.show();
def get_headers_for_request(self, extra = {}):
headers = {
'Connection': 'keep-alive',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'X-Requested-With': 'XMLHttpRequest',
'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/28.0.1500.71 Chrome/28.0.1500.71 Safari/537.36',
'Referer': 'http://douban.fm/',
'Accept-Language': 'zh-CN,zh;q=0.8'
}
if self.cookie:
cookie_str = self.get_cookie_for_request()
headers['Cookie'] = cookie_str
for key in extra:
headers[key] = extra[key]
return headers
def get_captcha_id(self, path = "/j/new_captcha"):
with closing(self.get_fm_conn()) as conn:
headers = self.get_headers_for_request()
conn.request("GET", path, None, headers)
response = conn.getresponse()
set_cookie = response.getheader('Set-Cookie')
if not set_cookie is None:
cookie = SimpleCookie(set_cookie)
self.save_cookie(cookie)
if response.status == 302:
print '...'
redirect_url = response.getheader('location')
return self.get_captcha_id(redirect_url)
if response.status == 200:
body = response.read()
return body.strip('"')
def save_cookie(self, cookie):
self.merge_cookie(cookie)
if self.use_cache:
self.cache.set('cookie', self.cookie)
# maybe we should extract a class XcCookie(SimpleCookie)
# merge(SimpleCookie)
def merge_cookie(self, cookie):
for key in cookie:
expires = cookie[key]['expires']
if expires:
print expires
ts = time.strptime('Tue, 01-Nov-2016 07:17:35 GMT', '%a, %d-%b-%Y %H:%M:%S %Z')
expires = time.mktime(ts)
now = time.time()
if expires > now:
self.cookie[key] = cookie[key]
else:
if key in self.cookie:
del self.cookie[key]
else:
self.cookie[key] = cookie[key]
# todo XcCookie.get_request_string()
def get_cookie_for_request(self):
cookie_segments = []
for key in self.cookie:
cookie_segment = key + '="' + self.cookie[key].value + '"'
cookie_segments.append(cookie_segment)
return '; '.join(cookie_segments)
def get_params(self, typename=None):
params = {}
params['r'] = ''.join(random.sample('0123456789abcdefghijklmnopqrstuvwxyz0123456789', 10))
params['uid'] = self.uid
params['channel'] = self.channel
params['from'] = 'mainsite'
if typename is not None:
params['type'] = typename
return params
def communicate(self, params):
data = urllib.urlencode(params)
with closing(httplib.HTTPConnection("douban.fm")) as conn:
conn.request('GET', "/j/mine/playlist?"+data, None, self.get_headers_for_request())
result = conn.getresponse().read()
return result
def playlist(self):
print 'Fetching playlist ...\r',
sys.stdout.flush()
params = self.get_params('n')
result = self.communicate(params)
result = json.loads(result)
if result.has_key('logout') and result['logout'] == 1:
print 'need relogin'
self.get_user_input_name_pass()
self.login_from_net(self.username, self.password)
return self.playlist()
else:
return result['song']
def del_song(self, sid, aid):
params = self.get_params('b')
params['sid'] = sid
params['aid'] = aid
result = self.communicate(params)
return json.loads(result)['song']
def fav_song(self, sid, aid):
params = self.get_params('r')
params['sid'] = sid
params['aid'] = aid
self.communicate(params)
def unfav_song(self, sid, aid):
params = self.get_params('u')
params['sid'] = sid
params['aid'] = aid
self.communicate(params)
class Cache:
"""docstring for cache"""
def has(self, name):
file_name = self.get_cache_file_name(name)
return os.path.exists(file_name)
def get(self, name, default = None):
file_name = self.get_cache_file_name(name)
if not os.path.exists(file_name):
return default
cache_file = open(file_name, 'rb')
content = pickle.load(cache_file)
cache_file.close()
return content
def set(self, name, content):
file_name = self.get_cache_file_name(name)
cache_file = open(file_name, 'wb')
pickle.dump(content, cache_file)
cache_file.close()
def get_cache_file_name(self, name):
# file should put into a `cache` dir
return name + '.cache'