-
Notifications
You must be signed in to change notification settings - Fork 14
/
eBooksAssistantServer.py
executable file
·454 lines (396 loc) · 13.4 KB
/
eBooksAssistantServer.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from crawler import c_dangdang, c_duokan, c_jd, c_weread, c_weread_vbookid, c_ximalaya, c_douban_info
from utilities import *
app = Bottle()
@app.hook('before_request')
def setup_request():
request_id = uuid4().hex
# 设置 response headers
headers_to_set = {
'Content-Type': 'application/json; charset=UTF-8',
'Cache-Control': 'no-cache, no-store, must-revalidate, private, max-age=0',
'Pragma': 'no-cache',
'Expires': '0',
'X-Request-ID': request_id
}
for key, value in headers_to_set.items():
response.set_header(key, value)
@app.route('/favicon.ico')
def favicon():
return static_file('favicon.ico', root='static')
@app.route('/')
def home():
response.status = 302
response.set_header('Location', 'https://github.com/caspartse/eBooksAssistant?utm_source=api.youdianzishu.com&utm_medium=redirect')
@app.route('/v2/dangdang', method='GET')
def dangdang() -> str:
'''
当当云阅读
:return: JSON 字符串
'''
vendor = 'dangdang'
request_id = response.get_header('X-Request-ID', uuid4().hex)
result = {
'data': {},
'errmsg': '',
'path': vendor,
'request_id': request_id
}
try:
isbn = request.query.isbn.strip() if request.query.isbn else ''
title = request.query.title or ''
subtitle = request.query.subtitle or ''
author = request.query.author or ''
translator = request.query.translator or ''
publisher = request.query.publisher or ''
# 没有ISBN或标题,返回错误
if not all([isbn, title]):
result['errmsg'] = 'No ISBN or title has been provided.'
resp = json.dumps(result)
return resp
# 使用缓存或重新爬取
cached_key = f'data_{vendor}_{isbn}'
if cached_json := rd.get(cached_key):
data = json.loads(cached_json)
else:
data = c_dangdang(
{
'isbn': isbn,
'title': title,
'subtitle': subtitle,
'author': author,
'translator': translator,
'publisher': publisher
}
)
if data:
result['data'] = data
else:
result['errmsg'] = 'No results found.'
except Exception as e:
traceback.print_exc()
result['errmsg'] = 'Unknow error.'
resp = json.dumps(result)
return resp
@app.route('/v2/duokan', method='GET')
def duokan() -> str:
'''
多看阅读
:return: JSON 字符串
'''
vendor = 'duokan'
request_id = response.get_header('X-Request-ID', uuid4().hex)
result = {
'data': {},
'errmsg': '',
'path': vendor,
'request_id': request_id
}
try:
isbn = request.query.isbn.strip() if request.query.isbn else ''
title = request.query.title or ''
subtitle = request.query.subtitle or ''
author = request.query.author or ''
translator = request.query.translator or ''
publisher = request.query.publisher or ''
# 没有ISBN或标题,返回错误
if not all([isbn, title]):
result['errmsg'] = 'No ISBN or title has been provided.'
resp = json.dumps(result)
return resp
# 使用缓存或重新爬取
cached_key = f'data_{vendor}_{isbn}'
if cached_json := rd.get(cached_key):
data = json.loads(cached_json)
else:
data = c_duokan(
{
'isbn': isbn,
'title': title,
'subtitle': subtitle,
'author': author,
'translator': translator,
'publisher': publisher
}
)
if data:
result['data'] = data
else:
result['errmsg'] = 'No results found.'
except Exception as e:
traceback.print_exc()
result['errmsg'] = 'Unknow error.'
resp = json.dumps(result)
return resp
@app.route('/v2/jd', method='GET')
def jd() -> str:
'''
京东读书
:return: JSON 字符串
'''
vendor = 'jd'
request_id = response.get_header('X-Request-ID', uuid4().hex)
result = {
'data': {},
'errmsg': '',
'path': vendor,
'request_id': request_id
}
try:
isbn = request.query.isbn.strip() if request.query.isbn else ''
title = request.query.title or ''
subtitle = request.query.subtitle or ''
author = request.query.author or ''
translator = request.query.translator or ''
publisher = request.query.publisher or ''
# 没有ISBN或标题,返回错误
if not all([isbn, title]):
result['errmsg'] = 'No ISBN or title has been provided.'
resp = json.dumps(result)
return resp
# 使用缓存或重新爬取
cached_key = f'data_{vendor}_{isbn}'
if cached_json := rd.get(cached_key):
data = json.loads(cached_json)
else:
data = c_jd(
{
'isbn': isbn,
'title': title,
'subtitle': subtitle,
'author': author,
'translator': translator,
'publisher': publisher
}
)
if data:
result['data'] = data
else:
result['errmsg'] = 'No results found.'
except Exception as e:
traceback.print_exc()
result['errmsg'] = 'Unknow error.'
resp = json.dumps(result)
return resp
@app.route('/v2/weread', method='GET')
def weread() -> str:
'''
微信读书
:return: JSON 字符串
'''
vendor = 'weread'
request_id = response.get_header('X-Request-ID', uuid4().hex)
result = {
'data': {},
'errmsg': '',
'path': vendor,
'request_id': request_id
}
try:
isbn = request.query.isbn.strip() if request.query.isbn else ''
title = request.query.title or ''
subtitle = request.query.subtitle or ''
author = request.query.author or ''
translator = request.query.translator or ''
publisher = request.query.publisher or ''
# 没有ISBN或标题,返回错误
if not all([isbn, title]):
result['errmsg'] = 'No ISBN or title has been provided.'
resp = json.dumps(result)
return resp
data = {}
cached_key = f'data_{vendor}_{isbn}'
if cached_json := rd.get(cached_key):
# 避免返回未上架/已下架的图书,所以需要再次查询
if v := c_weread_vbookid(json.loads(cached_json)['vbookid']):
data = v
else:
data = c_weread(
{
'isbn': isbn,
'title': title,
'subtitle': subtitle,
'author': author,
'translator': translator,
'publisher': publisher
}
)
if data:
result['data'] = data
else:
result['errmsg'] = 'No results found.'
except Exception as e:
traceback.print_exc()
result['errmsg'] = 'Unknow error.'
resp = json.dumps(result)
return resp
@app.route('/v2/ximalaya', method='GET')
def ximalaya() -> str:
'''
喜马拉雅
:return: JSON 字符串
'''
vendor = 'ximalaya'
request_id = response.get_header('X-Request-ID', uuid4().hex)
result = {
'data': {},
'errmsg': '',
'path': vendor,
'request_id': request_id
}
try:
isbn = request.query.isbn.strip() if request.query.isbn else ''
title = request.query.title or ''
subtitle = request.query.subtitle or ''
author = request.query.author or ''
translator = request.query.translator or ''
publisher = request.query.publisher or ''
# 没有标题或作者,返回错误
if not all([author, title]):
result['errmsg'] = 'No title or author has been provided.'
resp = json.dumps(result)
return resp
cached_key = f'data_{vendor}_{isbn}'
cached_data = None
if cached_json := rd.get(cached_key):
cached_data = json.loads(cached_json)
update_time = arrow.get(cached_data['update_time'])
# 更新时间超过 30 天,重新查询
if (update_time.shift(days=30) < arrow.now()):
cached_data = None
if not cached_data:
data = c_ximalaya(
{
'isbn': isbn,
'title': title,
'subtitle': subtitle,
'author': author,
'translator': translator,
'publisher': publisher
}
)
else:
data = cached_data
if data:
result['data'] = data
else:
result['errmsg'] = 'No results found.'
except Exception as e:
traceback.print_exc()
result['errmsg'] = 'Unknow error.'
resp = json.dumps(result)
return resp
@app.route('/sync_metadata', method='POST')
@app.route('/v2/sync_metadata', method='POST')
def sync_metadata() -> str:
'''
接收来自客户端同步的图书元数据
:return: JSON 字符串
'''
request_id = response.get_header('X-Request-ID', uuid4().hex)
result = {
'data': {},
'errmsg': '',
'path': 'sync_metadata',
'request_id': request_id
}
metadata = request.json or {}
if not metadata:
resp = json.dumps(result)
return resp
try:
metadata['douban_rating_score'] = metadata['rating_score']
metadata['douban_url'] = metadata['url']
metadata['douban_sid'] = re.search(r'/subject/(\d+)/', metadata['url']).group(1)
save_metadata(metadata)
except Exception as e:
traceback.print_exc()
resp = json.dumps(result)
return resp
@app.route('/weread/douban_info', method='GET')
@app.route('/v2/weread/douban_info', method='GET')
def weread_douban_info() -> str:
'''
微信图书页面,查询豆瓣图书信息
:return: JSON 字符串
'''
request_id = response.get_header('X-Request-ID', uuid4().hex)
result = {
'data': {},
'errmsg': '',
'path': 'weread/douban_info',
'request_id': request_id
}
try:
vbookid = request.query.vbookid
# 没有 vbookid,返回错误
if not vbookid:
result['errmsg'] = 'No vbookid has been provided.'
resp = json.dumps(result)
return resp
try:
conn = db_pool.getconn()
conn.autocommit = False
cur = conn.cursor()
q = f'''
SELECT
(CASE
WHEN douban_url = '' THEN 'https://book.douban.com/isbn/' || isbn || '/'
ELSE douban_url
END) AS url,
(CASE
WHEN douban_rating_score = '' THEN '0.0'
ELSE douban_rating_score
END) AS score
FROM metadata md
WHERE EXISTS (
SELECT 1
FROM market mk
WHERE vendor = 'weread'
AND vbookid = '{vbookid}'
AND mk.isbn = md.isbn
);
'''
cur.execute(q)
row = cur.fetchone()
except Exception as e:
traceback.print_exc()
finally:
cur.close()
db_pool.putconn(conn)
if row:
douban_url, douban_rating_score = row
douban_rating_star = f'douban_rating_star_{round(float(douban_rating_score) + 0.0001)}'
update_time = arrow.now().format('YYYY-MM-DD HH:mm:ss')
data = {
'url': douban_url,
'douban_rating_score': douban_rating_score,
'douban_rating_star': douban_rating_star,
'update_time': update_time
}
result['data'] = data
else:
# 先获得 isbn,再查询豆瓣图书信息
if isbn := (c_weread_vbookid(vbookid).get('isbn', '')):
metadata = c_douban_info(isbn)
douban_url = metadata.get('douban_url', f'https://book.douban.com/isbn/{isbn}/')
douban_rating_score = metadata.get('douban_rating_score', '0.0')
douban_rating_star = metadata.get('douban_rating_star', 'douban_rating_star_0')
update_time = arrow.now().format('YYYY-MM-DD HH:mm:ss')
data = {
'url': douban_url,
'douban_rating_score': douban_rating_score,
'douban_rating_star': douban_rating_star,
'update_time': update_time
}
result['data'] = data
else:
result['errmsg'] = 'No results found.'
except Exception as e:
traceback.print_exc()
result['errmsg'] = 'Unknow error.'
resp = json.dumps(result)
return resp
if __name__ == '__main__':
run(app, server='paste', host='0.0.0.0', port=8081, debug=True, reloader=True)