Repository navigation
Expand file tree
/
Copy pathmain.user.js
More file actions
253 lines (252 loc) · 8.08 KB
/
Copy pathmain.user.js
File metadata and controls
253 lines (252 loc) · 8.08 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
// ==UserScript==
// @name 萌娘百科缓存部分Api请求
// @namespace https://github.com/gui-ying233/mwApiCache
// @version 3.10.3
// @description 缓存部分Api请求结果以提升速度减少WAF几率
// @author 鬼影233
// @license MIT
// @match zh.moegirl.org.cn/*
// @match mzh.moegirl.org.cn/*
// @match mobile.moegirl.org.cn/*
// @match commons.moegirl.org.cn/*
// @match library.moegirl.org.cn/*
// @match en.moegirl.org.cn/*
// @match ja.moegirl.org.cn/*
// @icon http://moegirl.org.cn/favicon.ico
// @supportURL https://github.com/gui-ying233/mwApiCache/issues
// @run-at document-start
// @grant none
// ==/UserScript==
(() => {
"use strict";
if (new URLSearchParams(window.location.search).get("safemode")) return;
const ver = 2;
const log = (type, ...args) => {
console.debug(
`%cmwApiCache-${type}\n${args.join("\n")}`,
"border-left:1em solid #4E3DA4;background-color:#3C2D73;color:#D9D9D9;padding:1em",
);
};
log("Beg", new Date().toISOString());
log("Ver", ver);
log("Svd", +window.localStorage.getItem("mwApiCache-Svd"));
const id = setInterval(async () => {
if (!window.mediaWiki?.Api?.prototype) return;
clearInterval(id);
const originalMediaWikiApiGet = window.mediaWiki.Api.prototype.get;
const originalMediaWikiApiPost = window.mediaWiki.Api.prototype.post;
await window.$.ready;
const cfg = window.mediaWiki.config;
const userName = cfg.get("wgUserName");
const pending = new Map();
window.addEventListener(
"storage",
e => {
if (!e.key.startsWith("mwApiCache-")) return;
if (e.newValue) {
if (
e.key === "mwApiCache-Svd" &&
+e.newValue <= +e.oldValue
)
return;
e.storageArea.setItem(e.key, e.newValue);
log("Set", e.key, e.newValue);
} else {
e.storageArea.removeItem(e.key);
log("Del", e.key);
}
},
{ passive: true },
);
const timestamp = Date.now();
for (const key in window.localStorage) {
if (!key.startsWith("mwApiCache-") || key === "mwApiCache-Svd")
continue;
const cache = JSON.parse(window.localStorage.getItem(key));
if (cache.timestamp < timestamp || cache.ver !== ver) {
log("Del", key);
window.localStorage.removeItem(key);
}
}
const bc = new BroadcastChannel("mwApiCache");
bc.addEventListener("message", e => {
if (e.data === "init")
Object.keys(sessionStorage).forEach(
key =>
key.startsWith("mwApiCache-") &&
bc.postMessage({
key: key.replace("mwApiCache-", ""),
value: JSON.parse(sessionStorage.getItem(key)),
}),
);
else {
const { key, value } = e.data;
window.sessionStorage.setItem(
`mwApiCache-${key}`,
JSON.stringify(value),
);
log("Set", key, JSON.stringify(value));
}
});
bc.postMessage("init");
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;
const getCache = (t, method, arg, ms = day * 7) => {
const timestamp = Date.now();
const _arg = JSON.stringify(arg);
const key = `mwApiCache-${_arg}`;
const storage = ms ? window.localStorage : window.sessionStorage;
const cache = JSON.parse(storage.getItem(key));
if (cache?.ver !== ver || (ms && cache?.timestamp < timestamp)) {
if (cache) {
log("Del", key);
storage.removeItem(key);
}
const res = method.call(
t,
Object.assign(
{
maxage: Math.round(ms / second),
smaxage: Math.round(ms / second),
},
arg,
),
);
res.then(_res => {
log("Set", _arg, JSON.stringify(_res));
const value = {
ver,
timestamp: timestamp + ms,
res: _res,
};
storage.setItem(key, JSON.stringify(value));
if (!ms) bc.postMessage({ key: _arg, value });
return _res;
});
return res;
}
storage.setItem(
"mwApiCache-Svd",
+storage.getItem("mwApiCache-Svd") + 1,
);
log("Get", _arg);
const promise = $()
.promise()
.then(() => cache.res);
promise.abort = () => {};
return promise;
};
const apiFilter = (t, method, [payload, ...args]) => {
const arg = JSON.stringify(payload);
if (pending.has(arg)) {
log("Dup", arg);
return pending.get(arg);
}
let result;
switch (arg) {
case `{"action":"query","ususers":"${userName}","meta":["userinfo","siteinfo"],"list":["users"],"uiprop":["rights"],"siprop":["specialpagealiases"],"usprop":["blockinfo"]}`:
case '{"action":"query","meta":"siteinfo","siprop":"specialpagealiases","formatversion":2,"uselang":"content","maxage":3600}':
case '{"action":"query","meta":"userinfo","uiprop":["groups","rights"]}':
case `{"action":"query","prop":"revisions","titles":"User:${userName}/codemirror-mediawiki.json","rvprop":"content","rvlimit":1}`:
case '{"action":"paraminfo","modules":"main","helpformat":"html","uselang":"zh"}':
case '{"action":"paraminfo","modules":"json","helpformat":"html","uselang":"zh"}':
case '{"action":"query","meta":"siteinfo","siprop":["general","namespaces"]}':
result = getCache(t, method, payload);
break;
case `{"action":"query","meta":"allmessages","ammessages":["Editnotice-${cfg.get(
"wgNamespaceNumber",
)}","Editnotice-${cfg.get("wgNamespaceNumber")}-${cfg
.get("wgPageName")
.replaceAll("_", " ")
.replace(
`${
cfg.get("wgFormattedNamespaces")[
cfg.get("wgNamespaceNumber")
]
}:`,
"",
)}"],"amenableparser":1}`:
result = getCache(t, method, payload, 3 * day);
break;
case `{"action":"query","prop":"revisions|info","inprop":"protection|watched","format":"json","pageids":${cfg.get(
"wgArticleId",
)}}`:
result = getCache(t, method, payload, 0);
break;
case '{"action":"query","meta":"notifications","formatversion":2,"notfilter":"!read","notprop":"list","notformat":"model","notlimit":"max"}':
result = getCache(t, method, payload, 5 * minute - 1);
break;
default:
if (
/^{"action":"query","meta":"allmessages","ammessages":\[".*?"\],"amlang":"zh","formatversion":2}$/.test(
arg,
) ||
/^{"action":"parse","text":"<span id=\\"mw_editnotice_test_var\\".+?","preview":true,"disablelimitreport":true,"disableeditsection":true,"disabletoc":true}$/.test(
arg,
)
) {
result = getCache(t, method, payload);
break;
}
if (
/^{"action":"query","meta":"allmessages","ammessages":\["Editnotice-\d+","Editnotice-\d+-.+"],"amenableparser":1}$/.test(
arg,
)
) {
result = getCache(t, method, payload, 3 * day);
break;
}
if (
payload?.action === "compare" ||
/^{"action":"query","prop":"revisions\|info","inprop":"protection\|watched","format":"json","pageids":\d+}$/.test(
arg,
)
) {
result = getCache(t, method, payload, 0);
break;
}
if (
payload?.action === "paraminfo" ||
payload?.action === "help"
) {
result = getCache(t, method, payload, 30 * day);
break;
}
if (payload?.maxage ?? payload?.smaxage) {
result = getCache(
t,
method,
payload,
(payload?.maxage ?? payload?.smaxage) * second,
);
break;
}
if (
payload?.action === "edit" &&
payload?.title ===
`User:${userName}/codemirror-mediawiki.json`
)
(localStorage.removeItem(
`mwApiCache-{"action":"query","prop":"revisions","titles":"User:${userName}/codemirror-mediawiki.json","rvprop":"content","rvlimit":1}`,
),
log(
"Del",
`mwApiCache-{"action":"query","prop":"revisions","titles":"User:${userName}/codemirror-mediawiki.json","rvprop":"content","rvlimit":1}`,
));
log("Ign", arg);
result = method.apply(t, [payload, ...args]);
}
pending.set(arg, result);
result.always(() => pending.delete(arg));
return result;
};
window.mediaWiki.Api.prototype.get = function (...args) {
return apiFilter(this, originalMediaWikiApiPost, args);
};
window.mediaWiki.Api.prototype.post = function (...args) {
return apiFilter(this, originalMediaWikiApiPost, args);
};
}, 5);
})();