forked from Acode-Foundation/Acode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.js
More file actions
501 lines (453 loc) · 12.3 KB
/
plugin.js
File metadata and controls
501 lines (453 loc) · 12.3 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
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
import "./plugin.scss";
import fsOperation from "fileSystem";
import ajax from "@deadlyjack/ajax";
import Page from "components/page";
import alert from "dialogs/alert";
import loader from "dialogs/loader";
import purchaseListener from "handlers/purchase";
import actionStack from "lib/actionStack";
import constants from "lib/constants";
import installPlugin from "lib/installPlugin";
import InstallState from "lib/installState";
import settings from "lib/settings";
import { hideAd } from "lib/startAd";
import markdownIt from "markdown-it";
import anchor from "markdown-it-anchor";
import markdownItFootnote from "markdown-it-footnote";
import MarkdownItGitHubAlerts from "markdown-it-github-alerts";
import markdownItTaskLists from "markdown-it-task-lists";
import { highlightCodeBlock, initHighlighting } from "utils/codeHighlight";
import helpers from "utils/helpers";
import Url from "utils/Url";
import view from "./plugin.view.js";
let $lastPluginPage;
/**
* Plugin page
* @param {string} id
* @param {boolean} installed
* @param {() => void} [onInstall]
* @param {() => void} [onUninstall]
* @param {boolean} [installOnRender]
*/
export default async function PluginInclude(
id,
installed,
onInstall,
onUninstall,
installOnRender,
) {
if ($lastPluginPage) {
$lastPluginPage.hide();
}
installed = typeof installed !== "boolean" ? installed === "true" : installed;
const $page = Page(strings["plugin"]);
let plugin = {};
let currentVersion = "";
let purchased = false;
let cancelled = false;
let update = false;
let isPaid = false;
let price;
let product;
let purchaseToken;
let $settingsIcon;
let minVersionCode = -1;
actionStack.push({
id: "plugin",
action: $page.hide,
});
$page.onhide = function () {
hideAd();
actionStack.remove("plugin");
loader.removeTitleLoader();
cancelled = true;
$lastPluginPage = null;
};
$lastPluginPage = $page;
app.append($page);
helpers.showAd();
try {
if (installed) {
const manifest = Url.join(PLUGIN_DIR, id, "plugin.json");
const installedPlugin = await fsOperation(manifest)
.readFile("json")
.catch((err) => {
alert(`Failed to load plugin metadata: ${manifest}`);
console.error(err);
});
const { author } = installedPlugin;
const readme = Url.join(
PLUGIN_DIR,
id,
installedPlugin.readme || "readme.md",
);
const description = await fsOperation(readme)
.readFile("utf8")
.catch((err) => {
alert(`Failed to load plugin readme: ${readme}`);
console.error(err);
});
let changelogs = "";
if (installedPlugin.changelogs) {
const changelogPath = Url.join(
PLUGIN_DIR,
id,
installedPlugin.changelogs,
);
const changelogExists = await fsOperation(changelogPath).exists();
if (changelogExists) {
changelogs = await fsOperation(changelogPath).readFile("utf8");
}
}
const iconUrl = await helpers.toInternalUri(
Url.join(PLUGIN_DIR, id, installedPlugin.icon),
);
const iconData = await fsOperation(iconUrl).readFile();
const icon = URL.createObjectURL(
new Blob([iconData], { type: "image/png" }),
);
plugin = {
id,
icon,
name: installedPlugin.name,
version: installedPlugin.version,
author: author.name,
author_github: author.github,
source: installedPlugin.source,
license: installedPlugin.license,
keywords: installedPlugin.keywords,
contributors: installedPlugin.contributors,
repository: installedPlugin.repository,
description,
changelogs,
};
isPaid = installedPlugin.price > 0;
$page.settitle(plugin.name);
render();
}
await (async () => {
try {
loader.showTitleLoader();
if ((await helpers.checkAPIStatus()) && isValidSource(plugin.source)) {
const remotePlugin = await fsOperation(
constants.API_BASE,
`plugin/${id}`,
)
.readFile("json")
.catch(() => null);
if (cancelled || !remotePlugin) return;
if (installed && remotePlugin?.version !== plugin.version) {
currentVersion = plugin.version;
update = true;
}
if (remotePlugin.min_version_code) {
minVersionCode = remotePlugin.min_version_code;
}
plugin = Object.assign({}, remotePlugin);
if (!Number.parseFloat(remotePlugin.price)) return;
isPaid = remotePlugin.price > 0;
try {
[product] = await helpers.promisify(iap.getProducts, [
remotePlugin.sku,
]);
if (product) {
const purchase = await getPurchase(product.productId);
purchased = !!purchase;
price = product.price;
purchaseToken = purchase?.purchaseToken;
}
} catch (error) {
helpers.error(error);
}
}
} catch (error) {
console.error(error);
} finally {
loader.removeTitleLoader();
}
})();
$page.settitle(plugin.name);
render();
if (installOnRender && !installed) {
const $button = $page.get('[data-type="install"], [data-type="buy"]');
$button?.click();
}
} catch (err) {
console.error(err);
helpers.error(err);
} finally {
loader.removeTitleLoader();
}
async function install() {
try {
await Promise.all([
loadAd(this),
installPlugin(plugin.source || id, plugin.name, purchaseToken),
]);
if (onInstall) onInstall(plugin);
installed = true;
update = false;
if (!plugin.price) {
await helpers.showInterstitialIfReady();
}
render();
} catch (err) {
window.log("error", err);
helpers.error(err);
}
}
async function uninstall() {
try {
const pluginDir = Url.join(PLUGIN_DIR, plugin.id);
const state = await InstallState.new(plugin.id);
await Promise.all([
loadAd(this),
fsOperation(pluginDir).delete(),
state.delete(state.storeUrl),
]);
acode.unmountPlugin(plugin.id);
if (onUninstall) onUninstall(plugin.id);
installed = false;
update = false;
if (!plugin.price) {
await helpers.showInterstitialIfReady();
}
render();
} catch (err) {
window.log("error", err);
helpers.error(err);
}
}
async function buy(e) {
const $button = e.target;
const oldText = $button.textContent;
try {
if (!product) throw new Error("Product not found");
const apiStatus = await helpers.checkAPIStatus();
if (!apiStatus) {
alert(strings.error, strings.api_error);
return;
}
iap.setPurchaseUpdatedListener(...purchaseListener(onpurchase, onerror));
$button.textContent = strings["loading..."];
await helpers.promisify(iap.purchase, product.productId);
async function onpurchase(e) {
const purchase = await getPurchase(product.productId);
await ajax.post(Url.join(constants.API_BASE, "plugin/order"), {
data: {
id: plugin.id,
token: purchase?.purchaseToken,
package: BuildInfo.packageName,
},
});
purchaseToken = purchase?.purchaseToken;
purchased = !!purchase;
$button.textContent = oldText;
install();
}
async function onerror(error) {
helpers.error(error);
$button.textContent = oldText;
}
} catch (error) {
window.log("error", "Failed to buy:");
window.log("error", error);
helpers.error(error);
$button.textContent = oldText;
}
}
async function refund(e) {
const $button = e.target;
const oldText = $button.textContent;
try {
if (!product) throw new Error("Product not found");
$button.textContent = strings["loading..."];
const { refer, refunded, error } = await ajax.post(
Url.join(constants.API_BASE, "plugin/refund"),
{
data: {
id: plugin.id,
package: BuildInfo.packageName,
token: purchaseToken,
},
},
);
if (refer) {
system.openInBrowser(refer);
return;
}
if (refunded) {
toast(strings.success);
if (installed) uninstall();
else render();
return;
}
toast(error || strings.error);
} catch (error) {
window.log("error", error);
helpers.error(error);
} finally {
$button.textContent = oldText;
}
}
async function render() {
const pluginSettings = settings.uiSettings[`plugin-${plugin.id}`];
$page.body = view({
...plugin,
body: markdownIt({
html: true,
xhtmlOut: true,
})
.use(MarkdownItGitHubAlerts)
.use(anchor, {
slugify: (s) =>
s
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-"),
})
.use(markdownItTaskLists)
.use(markdownItFootnote)
.render(plugin.description),
changelogs: plugin.changelogs
? markdownIt({ html: true, xhtmlOut: true })
.use(MarkdownItGitHubAlerts)
.use(anchor, {
slugify: (s) =>
s
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-"),
})
.use(markdownItTaskLists)
.use(markdownItFootnote)
.render(plugin.changelogs)
: null,
purchased,
installed,
update,
isPaid,
price,
buy,
refund,
install,
uninstall,
currentVersion,
minVersionCode,
});
// Handle anchor links
$page.body.querySelectorAll("a[href^='#']").forEach((link) => {
const originalHref = link.getAttribute("href");
link.setAttribute("data-href", originalHref);
link.style.cursor = "pointer";
// Remove default click behavior
link.removeAttribute("href");
// Add custom click handler
link.addEventListener(
"click",
(e) => {
e.preventDefault();
e.stopPropagation();
const hash = link.getAttribute("data-href") || link.textContent;
const targetId = hash.startsWith("#") ? hash.slice(1) : hash;
// Look for either the anchor link or a heading with matching id
const targetElement =
$page.body.querySelector(`[name="${targetId}"]`) ||
$page.body.querySelector(`#${targetId}`);
if (targetElement) {
const headerOffset =
document.querySelector("header")?.offsetHeight || 0;
const elementPosition = targetElement.getBoundingClientRect().top;
const offsetPosition = elementPosition - headerOffset;
$page.body.scrollBy({
top: offsetPosition,
behavior: "smooth",
});
}
return false;
},
{ capture: true },
);
});
// Initialize theme-aware highlight styles
initHighlighting();
// Add copy button and syntax highlighting to code blocks
const codeBlocks = $page.body.querySelectorAll("pre");
codeBlocks.forEach((pre) => {
pre.style.position = "relative";
const copyButton = document.createElement("button");
copyButton.className = "copy-button";
copyButton.textContent = "Copy";
const codeElement = pre.querySelector("code");
if (codeElement) {
const langMatch = codeElement.className.match(/language-(\w+)/);
if (langMatch) {
const lang = langMatch[1];
const originalCode = codeElement.textContent || "";
codeElement.classList.add("cm-highlighted");
highlightCodeBlock(originalCode, lang).then((highlighted) => {
if (highlighted && highlighted !== originalCode) {
codeElement.innerHTML = highlighted;
}
});
}
}
copyButton.addEventListener("click", async () => {
const code = pre.querySelector("code")?.textContent || pre.textContent;
try {
cordova.plugins.clipboard.copy(code);
copyButton.textContent = "Copied!";
setTimeout(() => {
copyButton.textContent = "Copy";
}, 2000);
} catch (err) {
copyButton.textContent = "Failed to copy";
setTimeout(() => {
copyButton.textContent = "Copy";
}, 2000);
}
});
pre.appendChild(copyButton);
});
if ($settingsIcon) {
$settingsIcon.remove();
$settingsIcon = null;
}
if (pluginSettings) {
pluginSettings.setTitle(plugin.name);
$settingsIcon = (
<span
attr-action="settings"
className="icon settings"
onclick={() => pluginSettings.show()}
></span>
);
if (!$page.header.contains($settingsIcon)) {
$page.header.append($settingsIcon);
}
}
}
async function loadAd(el) {
if (!helpers.canShowAds()) return;
try {
if (!(await window.iad?.isLoaded())) {
const oldText = el.textContent;
el.textContent = strings["loading..."];
await window.iad.load();
el.textContent = oldText;
}
} catch (error) {
console.warn("Failed to load plugin page ad.", error);
}
}
async function getPurchase(sku) {
const purchases = await helpers.promisify(iap.getPurchases);
const purchase = purchases.find((p) => p.productIds.includes(sku));
return purchase;
}
}
function isValidSource(source) {
return source
? source.startsWith(Url.join(constants.API_BASE, "plugin"))
: true;
}