-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweread-price.user.js
More file actions
349 lines (290 loc) · 10.6 KB
/
weread-price.user.js
File metadata and controls
349 lines (290 loc) · 10.6 KB
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
// ==UserScript==
// @name WeReadPrice
// @namespace https://greasyfork.org/zh-CN/scripts/572301-wereadprice
// @homepage https://github.com/gaelthas/WeReadPrice
// @version 1.0.4
// @description 在微信读书书架页面显示书籍价格
// @author Galois
// @match https://weread.qq.com/*
// @grant GM_xmlhttpRequest
// @connect weread.qq.com
// @run-at document-idle
// @license MIT
// @updateURL https://update.greasyfork.org/scripts/572301/WeReadPrice.user.js
// @downloadURL https://update.greasyfork.org/scripts/572301/WeReadPrice.user.js
// ==/UserScript==
'use strict';
// ─── 配置 ────────────────────────────────────────────────────────────────────
const PRICE_CLASS = 'viberead-price';
const CACHE_TTL_MS = 1000 * 60 * 60 * 24; // 24h
const BATCH_SIZE = 5;
const BATCH_DELAY_MS = 200;
const CARD_SELECTORS = ['.shelfBook'];
const BOOKID_FROM_HREF_RE = /\/(?:reader|book)\/([^/?#]+)/;
// ─── 内存缓存 ─────────────────────────────────────────────────────────────────
const _cache = new Map();
function getCached(bookId) {
const entry = _cache.get(bookId);
if (!entry) return null;
if (Date.now() - entry.timestamp > CACHE_TTL_MS) {
_cache.delete(bookId);
return null;
}
return entry.data;
}
function setCached(bookId, data) {
_cache.set(bookId, { data, timestamp: Date.now() });
}
// ─── API ──────────────────────────────────────────────────────────────────────
function fetchPayInfo(bookId) {
return new Promise((resolve) => {
GM_xmlhttpRequest({
method: 'GET',
url: `https://weread.qq.com/web/book/info?bookId=${bookId}`,
withCredentials: true,
onload(resp) {
try {
const data = JSON.parse(resp.responseText);
resolve({
bookId: data.bookId,
title: data.title,
bookType: data.type,
centPrice: data.bookInfo?.centPrice ?? data.centPrice ?? null,
payingStatus: data.payingStatus,
paid: data.paid,
newRating: data.newRating,
deepVRating: data.deepVRating,
category: data.category,
free: data.free === 1,
});
} catch {
resolve(null);
}
},
onerror() { resolve(null); },
ontimeout() { resolve(null); },
});
});
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function fetchPrices(bookIds) {
const result = {};
const toFetch = [];
for (const bookId of bookIds) {
const cached = getCached(bookId);
if (cached) {
result[bookId] = cached;
} else {
toFetch.push(bookId);
}
}
for (let i = 0; i < toFetch.length; i += BATCH_SIZE) {
const batch = toFetch.slice(i, i + BATCH_SIZE);
await Promise.all(batch.map(async bookId => {
const data = await fetchPayInfo(bookId);
if (data) {
result[bookId] = data;
setCached(bookId, data);
}
}));
if (i + BATCH_SIZE < toFetch.length) {
await sleep(BATCH_DELAY_MS);
}
}
return result;
}
// ─── DOM 工具 ─────────────────────────────────────────────────────────────────
function queryBookCards() {
for (const sel of CARD_SELECTORS) {
const nodes = Array.from(document.querySelectorAll(sel));
if (nodes.length > 0) return nodes;
}
return [];
}
function extractBookId(card) {
const fromAttr = card.dataset && card.dataset.bookid;
if (fromAttr) return fromAttr;
if (card.href) {
const m = card.href.match(BOOKID_FROM_HREF_RE);
if (m) return m[1];
}
const link = card.querySelector('a[href]');
if (link) {
const m = link.href.match(BOOKID_FROM_HREF_RE);
if (m) return m[1];
}
return null;
}
function parseId(infoId) {
const type = infoId[3];
const dataSection = infoId.slice(7, infoId.length - 3);
const segments = dataSection.split('g');
const chunks = [];
for (const seg of segments) {
const len = parseInt(seg.slice(0, 2), 16);
chunks.push(seg.slice(2, 2 + len));
}
if (type === '3') {
return chunks.map(c => parseInt(c, 16).toString(10)).join('');
} else if (type === '4') {
const hex = chunks[0];
let result = '';
for (let i = 0; i < hex.length; i += 2) {
result += String.fromCharCode(parseInt(hex.slice(i, i + 2), 16));
}
return result;
}
throw new Error(`Unknown type flag: ${type}`);
}
function scanNewCards() {
const cards = queryBookCards();
const result = [];
for (const card of cards) {
if (card.querySelector('.' + PRICE_CLASS)) continue;
const rawId = extractBookId(card);
if (!rawId) continue;
try {
result.push({ element: card, bookId: parseId(rawId) });
} catch {
// 无法解析的 bookId 跳过
}
}
return result;
}
// ─── 价格注入 ─────────────────────────────────────────────────────────────────
function formatRatingValue(rating) {
if (rating == null || rating === '') return null;
const num = Number(rating);
if (!Number.isFinite(num)) return String(rating);
const score = num > 10 ? num / 10 : num;
return score % 1 === 0 ? String(score) : score.toFixed(1);
}
function formatCategory(category) {
if (!category) return '分类未知';
if (typeof category === 'string') {
return category;
}
if (Array.isArray(category)) {
const parts = category.map(item => {
if (typeof item === 'string') return item;
if (!item || typeof item !== 'object') return '';
return item.title || item.name || item.categoryName || item.label || '';
}).filter(Boolean);
return parts.length > 0 ? parts.join(' / ') : '分类未知';
}
if (typeof category === 'object') {
return category.title || category.name || category.categoryName || category.label || '分类未知';
}
return '分类未知';
}
function getPriceDisplay(priceData) {
if (!priceData) {
return { text: '暂无价格', color: '#888' };
}
if (priceData.bookType == 3) {
return { text: '公众号', color: '#888' };
}
if (priceData.paid == 1) {
return { text: '已购买', color: '#07c160' };
}
if (priceData.payingStatus == 0) {
return { text: '导入', color: '#888' };
}
if (priceData.free) {
return { text: '免费', color: '#07c160' };
}
if (priceData.centPrice != null) {
const fen = priceData.centPrice;
const yuan = fen % 100 === 0 ? String(fen / 100) : (fen / 100).toFixed(2);
return { text: '¥' + yuan, color: '#e64340' };
}
return { text: '暂无价格', color: '#888' };
}
function injectPriceLabel(card, priceData) {
if (card.querySelector('.' + PRICE_CLASS)) return;
const label = document.createElement('div');
label.className = PRICE_CLASS;
label.style.cssText = 'font-size:12px;margin-top:4px;line-height:1.6;pointer-events:none';
const priceDisplay = getPriceDisplay(priceData);
const newRating = formatRatingValue(priceData && priceData.newRating);
const deepVRating = formatRatingValue(priceData && priceData.deepVRating);
const category = formatCategory(priceData && priceData.category);
const rowStyle = 'display:flex;justify-content:space-between;align-items:center';
const leftStyle = 'white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1;min-width:0';
const rightStyle = 'white-space:nowrap;flex-shrink:0;text-align:right';
// Row 1: 评分1 / 评分2 | 价格
const row1 = document.createElement('div');
row1.style.cssText = rowStyle;
const ratingSpan = document.createElement('span');
const ratings = [newRating, deepVRating].filter(Boolean);
ratingSpan.textContent = ratings.length > 0 ? ratings.join(' / ') : '--';
ratingSpan.style.cssText = `color:#faad14;${leftStyle}`;
const priceSpan = document.createElement('span');
priceSpan.textContent = priceDisplay.text;
priceSpan.style.cssText = `color:${priceDisplay.color};${rightStyle}`;
row1.appendChild(ratingSpan);
row1.appendChild(priceSpan);
// Row 2: 分类
const row2 = document.createElement('div');
row2.style.cssText = rowStyle;
const catSpan = document.createElement('span');
catSpan.textContent = category;
catSpan.style.cssText = `color:#888;${leftStyle}`;
row2.appendChild(catSpan);
label.appendChild(row1);
label.appendChild(row2);
card.appendChild(label);
}
// ─── 核心流程 ─────────────────────────────────────────────────────────────────
async function scanAndInject() {
const newCards = scanNewCards();
if (newCards.length === 0) return;
const bookIds = newCards.map(c => c.bookId);
const prices = await fetchPrices(bookIds);
for (const { element, bookId } of newCards) {
injectPriceLabel(element, prices[bookId] || null);
}
}
// ─── MutationObserver ─────────────────────────────────────────────────────────
let _observer = null;
let _running = false;
let _pending = false;
async function _safeScanAndInject() {
_pending = false;
if (_running) {
_pending = true;
return;
}
_running = true;
try {
await scanAndInject();
} finally {
_running = false;
}
if (_pending) _safeScanAndInject();
}
function startObserver() {
if (_observer) _observer.disconnect();
_observer = new MutationObserver(() => {
_safeScanAndInject();
});
_observer.observe(document.body, { childList: true, subtree: true });
}
function stopObserver() {
if (_observer) {
_observer.disconnect();
_observer = null;
}
_pending = false;
}
// ─── 入口 ─────────────────────────────────────────────────────────────────────
async function init() {
stopObserver();
await scanAndInject();
startObserver();
}
init();
window.addEventListener('popstate', init);
window.addEventListener('hashchange', init);