forked from ipcjs/bilibili-helper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s1_show_all_post.user.js
349 lines (318 loc) · 10.6 KB
/
s1_show_all_post.user.js
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 列出S1一条帖子的所有内容
// @namespace https://github.com/ipcjs
// @version 1.3.2
// @description 在帖子的导航栏添加[显示全部]按钮, 列出帖子的所有内容
// @author ipcjs
// @include *://bbs.saraba1st.com/2b/thread-*-*-*.html
// @include *://bbs.saraba1st.com/2b/forum.php*
// @grant GM_xmlhttpRequest
// @grant GM.xmlHttpRequest
// @grant GM.setClipboard
// @grant GM_setClipboard
// @grant GM_addStyle
// @grant GM.addStyle
// @grant unsafeWindow
// @connect bbs.saraba1st.com
// @require https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js
// @run-at document-start
// ==/UserScript==
// type, props, children
// type, props, innerHTML
// 'text', text
const util_ui_element_creator = (type, props, children) => {
let elem = null;
if (type === "text") {
return document.createTextNode(props);
} else {
elem = document.createElement(type);
}
for (let n in props) {
if (n === "style") {
for (let x in props.style) {
elem.style[x] = props.style[x];
}
} else if (n === "className") {
elem.className = props[n];
} else if (n === "event") {
for (let x in props.event) {
elem.addEventListener(x, props.event[x]);
}
} else {
elem.setAttribute(n, props[n]);
}
}
if (children) {
if (typeof children === 'string') {
elem.innerHTML = children;
} else {
for (let i = 0; i < children.length; i++) {
if (children[i] != null)
elem.appendChild(children[i]);
}
}
}
return elem;
}
const _ = util_ui_element_creator
function log(...args) {
console.log(...args);
}
class AjaxException extends Error {
constructor(resp, message = "") {
super(message)
this.resp = resp
}
toString() {
return `AjaxException: message=${this.message}, status=${this.resp.status}, statusText=${this.resp.statusText}`
}
}
function ajaxPromise(options) {
return new Promise((resolve, reject) => {
options.method = options.method || 'GET';
options.onload = function (resp) {
resolve(resp);
}
options.onerror = function (resp) {
reject(new AjaxException(resp));
};
options.ontimeout = function (resp) {
reject(new AjaxException(resp, 'timeout'));
}
GM.xmlHttpRequest(options);
});
}
class Table {
constructor() {
const $postList = document.getElementById('postlist')
$postList.innerHTML = ''
this.listSize = 0
this.title = ''
document.getElementById('ct').insertBefore(_('div', {}, [
this.$title = _('h1', {}, this.title),
this.$table = _('table', { id: 'ssap-table' }),
this.$msg = _('div', { id: 'ssap-msg' })
]), $postList)
}
appendPostList(list) {
this.append(list, [
{ name: 'number', func: item => `<a target="_blank" href='forum.php?mod=redirect&goto=findpost&ptid=${item.ptid}&pid=${item.pid}'>${item.number}</a>` },
'username',
'dateline',
'message'
])
}
// append([{ name: 'ipcjs', age: 17 }, { name: 'fuck', age: 1 }], ['name', 'age']);
append(list, colNames) {
this.setListSize(this.listSize + list.length)
list.forEach(item => {
let $tr = _('tr')
colNames.forEach(it => {
let name = typeof it === 'string' ? it : it.name
let func = typeof it === 'string' ? item => item[name] : it.func
$tr.appendChild(_('td', { className: `ssap-${name}` }, func(item)))
})
this.$table.appendChild($tr)
})
}
setListSize(listSize) {
this.listSize = listSize
this._refreshTitle()
}
setTitle(title) {
this.title = title
this._refreshTitle()
}
showMsg(msg) {
this.$msg.innerText = msg
}
_refreshTitle() {
this.$title.innerHTML = `${this.title || 'Title'} ${this.listSize}`
}
_clearTable() {
this.listSize = 0
this.$table.innerHTML = ''
}
}
////////////////////// main ///////////////////////////////
let group, filter;
if (!(group = /thread-(\d+)-(\d+)-(\d+)/.exec(location.pathname))
&& !(group = /tid=(\d+)/.exec(location.search))) {
return; // 不匹配则返回
}
const POST_PAGE_MAX_COUNT = 1000; // 一次最多拉取多少条
const CONCURRENT_COUNT_MAX = 10; // 一次最多拉取多少页
const TID = group[1];
let table;
switch (TID) {
case '1494926': filter = f_1494926; break;
default: filter = f_all; break;
}
GM.addStyle(`
#ssap-table tr {
border-top: 1px solid #888;
}
#ssap-msg {
text-align: center;
}
#load-all-post {
margin: 0px 10px;
}
#ssap-table {
width: 100%;
table-layout: fixed;
}
#ssap-table .ssap-number {
width: 2%;
}
#ssap-table .ssap-username {
width: 5%;
}
#ssap-table .ssap-dateline {
width: 5%;
}
#ssap-table .ssap-message {
width: 88%;
}
#ssap-table img {
max-width: 88%;
}
`)
function loadAllPost() {
if (loadAllPost.loading) {
return
}
loadAllPost.loading = true
if (!table) {
table = new Table()
}
const load = async function () {
let page = 1;
let concurrentCount = 1;
while (true) {
table.showMsg(`加载第${page}->${page + concurrentCount - 1}页中...`)
const results = await Promise.all(Array.from({ length: concurrentCount }, (v, index) => retry(async (i) => {
const resp = await ajaxPromise({
url: `https://bbs.saraba1st.com/2b/api/mobile/index.php?module=viewthread&ppp=${POST_PAGE_MAX_COUNT}&tid=${TID}&page=${page + index}&version=1`,
timeout: 1000 * 15 * (i + 1),
})
return [index, resp]
}, 3)))
let json
for (const [index, resp] of results) {
const currentPage = page + index
json = JSON.parse(resp.responseText)
if (currentPage === 1) {
table.setTitle(json.Variables.thread.subject)
}
table.appendPostList(json.Variables.postlist.filter(filter))
log('>>', currentPage, table.listSize, json.Variables.thread);
}
// 总post条数为replies + 1
const postCount = +json.Variables.thread.replies + 1
if (table.listSize < postCount) {
page += concurrentCount;
concurrentCount = Math.min(concurrentCount + 3, Math.ceil((postCount - table.listSize) / POST_PAGE_MAX_COUNT), CONCURRENT_COUNT_MAX)
} else {
break;
}
}
}
load()
.then(r => {
table.showMsg('')
})
.catch((e) => {
table.showMsg(e.toString())
console.error(e)
})
.finally(() => {
loadAllPost.loading = false
})
}
async function retry(block, count = 3, timeMs = 1000) {
let error
for (let i = 0; i < count; i++) {
try {
return await block(i)
} catch (e) {
error = e
await delay(timeMs)
log(`retry: i=${i}, e=${e.toString()}`)
}
}
throw error
}
function delay(timeMs) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("continue")
}, timeMs);
})
}
function f_1494926(item) {
if (item.username === 'ipcjs') {
return true;
} else if (['SUNSUN', '蒹葭公子', '木水风铃'].includes(item.username) && item.message.includes('ipcjs 发表于')) {
return true;
}
return false;
}
function f_all() {
return true;
}
function feature_show_all() {
document.querySelector('#pt > div.z').appendChild(_('a', { id: 'load-all-post', href: 'javascript:;', event: { click: () => loadAllPost() } }, '[显示全部]'));
}
function feature_voters() {
const SEPARATOR = '\t'
async function copyVoters() {
const $button = this
const $content = document.getElementById('fwin_content_viewvote')
/** @type {HTMLSelectElement} */
const $select = $content.querySelector('select.ps')
let result = '# 投票结果'
for (const [index, option] of Array.from($select.options).entries()) {
$button.textContent = `[复制中(${index}/${$select.options.length})...]`
result += `\n\n## ${option.text}`
log(option.value, option.text)
let page = 0
let $next
do {
page++
const resp = await ajaxPromise({ url: `https://bbs.saraba1st.com/2b/forum.php?mod=misc&action=viewvote&tid=${TID}&polloptionid=${option.value}&infloat=yes&handlekey=viewvote&page=${page}&inajax=1&ajaxtarget=fwin_content_viewvote` })
const $xml = new DOMParser().parseFromString(resp.responseXML.documentElement.firstChild.textContent, 'text/html')
const $voters = Array.from($xml.querySelectorAll('li > p > a'))
result += page > 1 ? SEPARATOR : '\n\n'
result += $voters.map(it => it.textContent).join(SEPARATOR)
$next = $xml.querySelector('.pg > .nxt')
} while ($next)
}
log(result)
GM.setClipboard(result)
$button.textContent = '[复制完成!]'
}
new MutationObserver((mutations, observer) => {
for (let m of mutations) {
for (let node of m.addedNodes) {
if (node.nodeType === Node.ELEMENT_NODE) {
/** @type {HTMLDivElement} */
const $title = node.id === 'fctrl_viewvote' ? node : node.querySelector('#fctrl_viewvote')
let $button = node.querySelector('#ssap_copy_voters')
if ($title && !$button) {
log($title)
$button = _('a', { id: 'ssap_copy_voters', href: 'javascript:;', event: { click: copyVoters } }, '[复制结果]')
$title.insertBefore($button, $title.lastChild)
}
}
}
}
}).observe(document.getElementById('append_parent'), {
childList: true,
subtree: true,
})
}
unsafeWindow.addEventListener('DOMContentLoaded', (event) => {
feature_show_all()
feature_voters()
})