generated from KyuubiRan/EzXHepler-template
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathLocalScripts.kt
293 lines (269 loc) · 9.1 KB
/
LocalScripts.kt
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
package org.matrix.chromext.script
import java.io.File
import java.io.FileReader
import org.matrix.chromext.Chrome
import org.matrix.chromext.utils.Log
const val GM_addStyle =
"""
function GM_addStyle(css) {
const style = document.createElement("style");
style.setAttribute("type", "text/css");
style.textContent = css;
try {
(document.head || document.documentElement).appendChild(style);
} catch {
setTimeout(() => {document.head.appendChild(style);}, 0);
}
}
"""
const val GM_addElement =
"""
function GM_addElement() {
// parent_node, tag_name, attributes
if (arguments.length == 2) {
arguments = [document.head, arguments[0], arguments[1]];
};
if (arguments.length != 3) { return };
const element = document.createElement(arguments[1]);
for (const [key, value] of Object.entries(arguments[2])) {
if (key != "textContent") {
element.setAttribute(key, value);
} else {
element.textContent = value;
}
}
try {
arguments[0].appendChild(element);
} catch {
setTimeout(() => {document.head.appendChild(element);}, 0);
}
}
"""
const val GM_xmlhttpRequest =
"""
function GM_xmlhttpRequest(details) {
details.method = details.method ? details.method.toUpperCase() : "GET";
if (!details.url) {
throw new Error("GM_xmlhttpRequest requires a URL.");
}
const xmlhr = new XMLHttpRequest();
for (const [key, value] of Object.entries(details)) {
if (key.startsWith("on")) {
xmlhr.addEventListener(key.substring(2), value);
} else {
xmlhr[key] = value;
}
}
xmlhr.open(details.method, details.url, !details.synchronous || true, details.user || null, details.password || null);
if ("headers" in details) {
for (const header in details.headers) {
xmlhr.setRequestHeader(header, details.headers[header]);
}
}
if ("data" in details) {
if ("binary" in details) {
const blob = new Blob([details.data.toString()], "text/plain");
xmlhr.send(blob);
} else {
xmlhr.send(details.data);
}
} else {
xmlhr.send();
}
return xmlhr;
}
"""
const val GM_download =
"""
function GM_download(details) {
if (arguments.length == 2) {
details = {url: arguments[0], name: arguments[1]}
}
return GM_xmlhttpRequest({
url: details.url, responseType: 'blob',
onloadend: (event) => {
const xhr = event.target;
if (xhr.status !== 200) return console.error('Error loading: ', details.url, xhr);
const link = document.createElement('a');
link.href = URL.createObjectURL(xhr.response);
link.download = details.name;
link.dispatchEvent(new MouseEvent('click'));
setTimeout(URL.revokeObjectURL(link.href), 1000);
}
});
}
"""
const val GM_openInTab =
"""
function GM_openInTab(url, options) {
const gm_window = window.open(url, "_blank");
if ("active" in options && options.active ) {
gm_window.focus();
}
return gm_window;
}
"""
const val GM_registerMenuCommand =
"""
function GM_registerMenuCommand(title, listener, accessKey="Dummy") {
if (typeof ChromeXt.MenuCommand == "undefined") {
ChromeXt.MenuCommand = [];
}
ChromeXt.MenuCommand.push({title, listener});
return ChromeXt.MenuCommand.length - 1;
}
"""
const val GM_addValueChangeListener =
"""
function GM_addValueChangeListener(key, listener) {
if (typeof ChromeXt.ValueChangeListener == "undefined") {
ChromeXt.ValueChangeListener = [];
}
ChromeXt.ValueChangeListener.push({key, listener});
return ChromeXt.ValueChangeListener.length - 1;
}
"""
const val GM_setValue =
"""
function GM_setValue(key, value) {
if (typeof ChromeXt.ValueChangeListener != undefined) {
const old_value = localStorage.getItem(key + '_ChromeXt_Value');
if (old_value != null) {
ChromeXt.ValueChangeListener.forEach(e => {if (e.key == key) {e.listener(JSON.parse(old_value), value, false)}});
}
}
localStorage.setItem(key + '_ChromeXt_Value', JSON.stringify(value));
}
"""
const val GM_bootstrap =
"""
function GM_bootstrap() {
const row = /\/\/\s+@(\S+)\s+(.+)/g;
const meta = GM_info.script;
let match;
while ((match = row.exec(GM_info.scriptMetaStr)) !== null) {
if (meta[match[1]]) {
if (typeof meta[match[1]] == "string") meta[match[1]] = [meta[match[1]]];
meta[match[1]].push(match[2]);
} else meta[match[1]] = match[2];
}
meta.includes = meta.include;
meta.matches = meta.match;
meta.excludes = meta.exclude;
delete meta.include;
delete meta.match;
delete meta.exclude;
}
"""
fun encodeScript(script: Script): String? {
var code = script.code
if (!script.meta.startsWith("// ==UserScript==")) {
code = script.meta + code
}
if (script.require.size > 0) {
code =
GM_addElement +
"(async ()=> {" +
script.require
.map {
"try{await import('${it}')}catch{GM_addElement('script',{textContent: await (await fetch('${it}')).text()})};"
}
.joinToString("") +
code +
"})();"
}
code =
GM_bootstrap +
"const GM_info = {scriptMetaStr:`${script.meta}`,script:{antifeatures:{},options:{override:{}}}};GM_bootstrap();" +
code
script.grant.forEach granting@{
val function = it
when (function) {
"GM_addStyle" -> code = GM_addStyle + code
"GM_addElement" -> if (script.require.size == 0) code = GM_addElement + code
"GM_openInTab" -> code = GM_openInTab + code
"GM_info" -> return@granting
"GM_download" -> code = GM_xmlhttpRequest + GM_download + code
"GM_xmlhttpRequest" ->
if (!script.grant.contains("GM_download")) code = GM_xmlhttpRequest + code
"unsafeWindow" -> code = "const unsafeWindow = window;" + code
"GM_log" -> code = "const GM_log = console.log.bind(console);" + code
"GM_deleteValue" ->
code =
"function GM_deleteValue(key) {localStorage.removeItem(key + '_ChromeXt_Value')};" +
code
"GM_setValue" -> code = GM_setValue + code
"GM_getValue" ->
code =
"function GM_getValue(key, default_value) {let value = localStorage.getItem(key + '_ChromeXt_Value') || default_value;try {value = JSON.parse(value)} finally {return value}};" +
code
"GM_addValueChangeListener" -> code = GM_addValueChangeListener + code
"GM_removeValueChangeListener" ->
code =
"function GM_removeValueChangeListener(index) {ChromeXt.ValueChangeListener.splice(index, 1)};" +
code
"GM_registerMenuCommand" -> code = GM_registerMenuCommand + code
"GM_unregisterMenuCommand" ->
code =
"function GM_unregisterMenuCommand(index) {ChromeXt.MenuCommand.splice(index, 1)};" +
code
"GM_getResourceURL" -> {
var GM_ResourceURL = "GM_ResourceURL={"
script.resource.forEach {
val content = it.split(" ")
if (content.size != 2) return@granting
val name = content.first()
val url = content.last()
GM_ResourceURL += name + ":'" + url + "',"
}
GM_ResourceURL += "};"
code = GM_ResourceURL + "const GM_getResourceURL = (name) => GM_ResourceURL[name];" + code
}
"GM_getResourceText" -> {
var GM_ResourceText = "GM_ResourceText={"
runCatching {
script.resource.forEach {
val name = it.split(" ").first()
if (name == "") return@granting
val file =
File(
Chrome.getContext().getExternalFilesDir(null),
resourcePath(script.id, name))
if (file.exists()) {
val text = FileReader(file).use { it.readText() }
GM_ResourceText +=
name +
":'" +
text
.replace("\n", "ChromeXt_ResourceText_NEWLINE")
.replace("'", "ChromeXt_ResourceText_QUOTE") +
"',"
}
}
}
.onFailure { Log.ex(it) }
GM_ResourceText += "};"
code =
GM_ResourceText +
"""const GM_getResourceText = (name) => (name in GM_ResourceText) ? GM_ResourceText[name].replaceAll("ChromeXt_ResourceText_NEWLINE", "\n").replaceAll("ChromeXt_ResourceText_QUOTE", "'") : "ChromeXt failed to get resource";""" +
code
}
"GM_listValues" ->
code =
"const GM_listValues = ()=> [...Array(localStorage.length).keys()].map(x=>localStorage.key(x));" +
code
else ->
code =
"function ${function}(...args) {console.error('${function} is not implemented in ChromeXt yet, called with', args)}" +
code
}
}
when (script.runAt) {
RunAt.START -> code = "(()=>{${code}})();"
RunAt.END -> code = "window.addEventListener('DOMContentLoaded',()=>{${code}});"
RunAt.IDLE -> code = "window.addEventListener('load',()=>{${code}});"
}
return code
}
const val openEruda =
"try{ if (eruda._isInit) { eruda.hide(); eruda.destroy(); } else { eruda.init(); eruda._localConfig(); eruda.show(); } } catch (e) { globalThis.ChromeXt(JSON.stringify({ action: 'loadEruda', payload: ''})) }"