package eu.friedcutlet.yokan.services.extensions.js import eu.friedcutlet.yokan.database.DbSource import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject /** * Mangayomi-compatible globals (`Client`, `SharedPreferences`, `MProvider`, DOM, crypto, ...) * evaluated before the extension source; every host call goes through `sendMessage`. */ internal fun javaScriptBootstrap(source: DbSource): String = """ function sendMessage(channel, payload) { return __bridge.sendMessage(String(channel), String(payload)); } function Client(reqcopyWith) { this.reqcopyWith = reqcopyWith || null; } // The bootstrap intentionally stays ES5 so loading it is cheap. User extensions run directly // on QuickJS and can use modern ECMAScript syntax without a transpilation pass. Client.prototype.head = function(url, headers) { return JSON.parse(sendMessage("http_head", JSON.stringify([null, this.reqcopyWith, url, headers || {}]))); }; Client.prototype.get = function(url, headers) { return JSON.parse(sendMessage("http_get", JSON.stringify([null, this.reqcopyWith, url, headers || {}]))); }; Client.prototype.post = function(url, headers, body) { return JSON.parse(sendMessage("http_post", JSON.stringify([null, this.reqcopyWith, url, headers || {}, body]))); }; Client.prototype.put = function(url, headers, body) { return JSON.parse(sendMessage("http_put", JSON.stringify([null, this.reqcopyWith, url, headers || {}, body]))); }; Client.prototype.delete = function(url, headers, body) { return JSON.parse(sendMessage("http_delete", JSON.stringify([null, this.reqcopyWith, url, headers || {}, body]))); }; Client.prototype.patch = function(url, headers, body) { return JSON.parse(sendMessage("http_patch", JSON.stringify([null, this.reqcopyWith, url, headers || {}, body]))); }; function SharedPreferences() {} SharedPreferences.prototype.get = function(key) { return sendMessage("get", JSON.stringify([key])); }; SharedPreferences.prototype.getString = function(key, defaultValue) { return sendMessage("getString", JSON.stringify([key, defaultValue == null ? "" : defaultValue])); }; SharedPreferences.prototype.setString = function(key, value) { return sendMessage("setString", JSON.stringify([key, value == null ? "" : String(value)])); }; SharedPreferences.prototype.getBoolean = function(key, defaultValue) { var raw = sendMessage("getString", JSON.stringify([key, ""])); if (raw === "true") return true; if (raw === "false") return false; return !!defaultValue; }; SharedPreferences.prototype.getInt = function(key, defaultValue) { var raw = sendMessage("getString", JSON.stringify([key, ""])); var n = parseInt(raw, 10); return isNaN(n) ? (defaultValue | 0) : n; }; SharedPreferences.prototype.getLong = function(key, defaultValue) { var raw = sendMessage("getString", JSON.stringify([key, ""])); var n = Number(raw); return isFinite(n) && raw !== "" ? n : (defaultValue || 0); }; SharedPreferences.prototype.getFloat = function(key, defaultValue) { var raw = sendMessage("getString", JSON.stringify([key, ""])); var n = parseFloat(raw); return isNaN(n) ? (defaultValue || 0) : n; }; SharedPreferences.prototype.getStringSet = function(key, defaultValue) { var raw = sendMessage("getString", JSON.stringify([key, ""])); if (!raw) return defaultValue || []; try { var parsed = JSON.parse(raw); if (Array.isArray(parsed)) return parsed; } catch (e) {} return String(raw).split(",").map(function(s) { return s.trim(); }).filter(Boolean); }; SharedPreferences.prototype.setBoolean = function(key, value) { return sendMessage("setString", JSON.stringify([key, value ? "true" : "false"])); }; SharedPreferences.prototype.setInt = function(key, value) { return sendMessage("setString", JSON.stringify([key, String(value | 0)])); }; SharedPreferences.prototype.setLong = function(key, value) { return sendMessage("setString", JSON.stringify([key, String(value)])); }; SharedPreferences.prototype.setFloat = function(key, value) { return sendMessage("setString", JSON.stringify([key, String(value)])); }; SharedPreferences.prototype.setStringSet = function(key, value) { return sendMessage("setString", JSON.stringify([key, JSON.stringify(value || [])])); }; // QuickJS lacks a few newer builtins the extensions rely on; polyfill defensively. if (typeof Array.prototype.at !== "function") { Array.prototype.at = function(index) { index = Math.trunc(index) || 0; if (index < 0) index += this.length; return (index < 0 || index >= this.length) ? undefined : this[index]; }; } if (typeof String.prototype.at !== "function") { String.prototype.at = function(index) { index = Math.trunc(index) || 0; if (index < 0) index += this.length; return (index < 0 || index >= this.length) ? undefined : this.charAt(index); }; } if (typeof Array.prototype.findLast !== "function") { Array.prototype.findLast = function(predicate, thisArg) { for (var i = this.length - 1; i >= 0; i--) { if (predicate.call(thisArg, this[i], i, this)) return this[i]; } return undefined; }; } if (typeof Array.prototype.findLastIndex !== "function") { Array.prototype.findLastIndex = function(predicate, thisArg) { for (var i = this.length - 1; i >= 0; i--) { if (predicate.call(thisArg, this[i], i, this)) return i; } return -1; }; } var console = typeof console === "undefined" ? {} : console; console.log = console.warn = console.error = function(message) { if (typeof message === "object") message = JSON.stringify(message); sendMessage("log", JSON.stringify([String(message)])); }; String.prototype.substringAfter = function(pattern) { const index = this.indexOf(pattern); return index === -1 ? this.substring(0) : this.substring(index + pattern.length); }; String.prototype.substringAfterLast = function(pattern) { return this.split(pattern).pop(); }; String.prototype.substringBefore = function(pattern) { const index = this.indexOf(pattern); return index === -1 ? this.substring(0) : this.substring(0, index); }; String.prototype.substringBeforeLast = function(pattern) { const index = this.lastIndexOf(pattern); return index === -1 ? this.substring(0) : this.substring(0, index); }; String.prototype.substringBetween = function(left, right) { const start = this.indexOf(left); if (start === -1) return ""; const contentStart = start + left.length; const end = this.indexOf(right, contentStart); return end === -1 ? "" : this.substring(contentStart, end); }; function parseDates(value, dateFormat, dateFormatLocale) { return JSON.parse(sendMessage("parseDates", JSON.stringify([Array.isArray(value) ? value : [value], dateFormat || "", dateFormatLocale || ""]))); } $HTML_DOM_JS function xpathFirst(html, expression) { return JSON.parse(sendMessage("xpathFirst", JSON.stringify([String(html || ""), String(expression || "")]))); } function xpathAll(html, expression) { return JSON.parse(sendMessage("xpathAll", JSON.stringify([String(html || ""), String(expression || "")]))); } function parseEpub(path) { return JSON.parse(sendMessage("parseEpub", JSON.stringify([String(path || "")]))); } function parseEpubChapter(path, index) { return sendMessage("parseEpubChapter", JSON.stringify([String(path || ""), index | 0])); } function cryptoBytesToHex(value) { if (typeof value === "string") return value; if (!Array.isArray(value)) return ""; var out = ""; for (var i = 0; i < value.length; i++) { var part = (Number(value[i]) & 255).toString(16); out += part.length < 2 ? "0" + part : part; } return out; } var Crypto = { aesEncrypt: function(keyHexOrBase64, ivHexOrBase64, plaintext) { return JSON.parse(sendMessage("cryptoAes", JSON.stringify(["encrypt", keyHexOrBase64, ivHexOrBase64, plaintext]))); }, aesDecrypt: function(keyHexOrBase64, ivHexOrBase64, ciphertext) { return JSON.parse(sendMessage("cryptoAes", JSON.stringify(["decrypt", keyHexOrBase64, ivHexOrBase64, ciphertext]))); }, aesGcmEncrypt: function(keyHexOrBase64, ivHexOrBase64, plaintextHexOrBase64, additionalDataHexOrBase64) { return JSON.parse(sendMessage("cryptoAesGcm", JSON.stringify(["encrypt", keyHexOrBase64, ivHexOrBase64, plaintextHexOrBase64, additionalDataHexOrBase64 || ""]))); }, aesGcmDecrypt: function(options, ivHexOrBase64, ciphertextHexOrBase64) { var key = options; var iv = ivHexOrBase64; var data = ciphertextHexOrBase64; var returnText = false; if (options && typeof options === "object") { key = options.key || (options.keyFromSha256 ? this.sha256Hex(options.keyFromSha256) : ""); iv = cryptoBytesToHex(options.iv); data = cryptoBytesToHex(options.data); returnText = true; } var result = JSON.parse(sendMessage("cryptoAesGcm", JSON.stringify(["decrypt", key, iv, data, options && options.additionalData ? options.additionalData : ""]))); return returnText ? (result ? result.utf8 : null) : result; }, sha256: function(data) { return JSON.parse(sendMessage("cryptoDigest", JSON.stringify(["sha-256", data]))); }, sha1: function(data) { return JSON.parse(sendMessage("cryptoDigest", JSON.stringify(["sha-1", data]))); }, md5: function(data) { var r = JSON.parse(sendMessage("cryptoDigest", JSON.stringify(["md5", String(data == null ? "" : data)]))); return r ? r.hex : ""; }, sha256Hex: function(data) { var r = JSON.parse(sendMessage("cryptoDigest", JSON.stringify(["sha-256", String(data == null ? "" : data)]))); return r ? r.hex : ""; }, sha1Hex: function(data) { var r = JSON.parse(sendMessage("cryptoDigest", JSON.stringify(["sha-1", String(data == null ? "" : data)]))); return r ? r.hex : ""; }, sha256Bytes: function(data) { var r = JSON.parse(sendMessage("cryptoDigest", JSON.stringify(["sha-256", String(data == null ? "" : data)]))); return r ? r.hex : ""; }, hmac: function(algorithm, key, message) { var r = JSON.parse(sendMessage("cryptoHmac", JSON.stringify([String(algorithm || "sha-256"), String(key == null ? "" : key), String(message == null ? "" : message)]))); return r ? r.hex : ""; }, hmacSHA256: function(key, message) { return this.hmac("sha-256", key, message); }, hmacSha256: function(key, message) { return this.hmac("sha-256", key, message); }, hmacSha256Truncated: function(key, message, bytes) { return this.hmac("sha-256", key, message).substring(0, (bytes | 0) * 2); }, hmacSHA1: function(key, message) { return this.hmac("sha-1", key, message); }, base64Encode: function(text) { return JSON.parse(sendMessage("cryptoBase64", JSON.stringify(["encode", String(text || "")]))); }, base64Decode: function(text) { return JSON.parse(sendMessage("cryptoBase64", JSON.stringify(["decode", String(text || "")]))); }, fromBase64: function(text) { return JSON.parse(sendMessage("cryptoBase64", JSON.stringify(["decode", String(text || "")]))); }, base64ToHex: function(b64) { var s = atob(String(b64 || "")); var out = ""; for (var i = 0; i < s.length; i++) { var h = s.charCodeAt(i).toString(16); out += h.length < 2 ? "0" + h : h; } return out; }, tripleDESEncrypt: function(dataBase64, keyBase64, ivBase64) { var r = JSON.parse(sendMessage("cryptoDes", JSON.stringify(["encrypt", String(keyBase64 || ""), String(ivBase64 || ""), String(dataBase64 || "")]))); return r ? r.base64 : ""; }, encrypt3DESCBC: function(dataBase64, keyBase64, ivBase64) { return this.tripleDESEncrypt(dataBase64, keyBase64, ivBase64); } }; var Extractors = { extract: function(host, url, headers) { return JSON.parse(sendMessage("extractVideo", JSON.stringify([String(host || ""), String(url || ""), headers || {}]))); } }; // Promise-aware JSON.stringify helper. Extensions can pass either synchronous or asynchronous // producer functions; QuickJS drains the resulting promise jobs before evaluation returns. function jsonStringify(fn) { var result = fn(); if (result && typeof result.then === "function") { return result.then(function(v) { return JSON.stringify(v); }); } return JSON.stringify(result); } function MProvider() {} Object.defineProperty(MProvider.prototype, "source", { get: function() { return ${source.toMSourceJson()}; }, configurable: true }); Object.defineProperty(MProvider.prototype, "supportsLatest", { get: function() { throw new Error("supportsLatest not implemented"); }, configurable: true }); // Default methods stay synchronous; subclasses may freely override them with async methods. MProvider.prototype.getHeaders = function(url) { throw new Error("getHeaders not implemented"); }; MProvider.prototype.getPopular = function(page) { throw new Error("getPopular not implemented"); }; MProvider.prototype.getLatestUpdates = function(page) { throw new Error("getLatestUpdates not implemented"); }; MProvider.prototype.search = function(query, page, filters) { throw new Error("search not implemented"); }; MProvider.prototype.getDetail = function(url) { throw new Error("getDetail not implemented"); }; MProvider.prototype.getPageList = function(url) { throw new Error("getPageList not implemented"); }; MProvider.prototype.getVideoList = function(url) { throw new Error("getVideoList not implemented"); }; MProvider.prototype.getHtmlContent = function(name, url) { throw new Error("getHtmlContent not implemented"); }; MProvider.prototype.cleanHtmlContent = function(html) { throw new Error("cleanHtmlContent not implemented"); }; MProvider.prototype.getFilterList = function() { return []; }; MProvider.prototype.getSourcePreferences = function() { return []; }; """.trimIndent() private fun DbSource.toMSourceJson(): JsonObject = buildJsonObject { put("apiUrl", JsonPrimitive(apiUrl)) put("baseUrl", JsonPrimitive(baseUrl)) put("dateFormat", JsonPrimitive(dateFormat)) put("dateFormatLocale", JsonPrimitive(dateFormatLocale)) put("hasCloudflare", JsonPrimitive(hasCloudflare)) put("id", JsonPrimitive(id)) put("isFullData", JsonPrimitive(isFullData)) put("lang", JsonPrimitive(lang)) put("name", JsonPrimitive(name)) put("additionalParams", JsonPrimitive(additionalParams)) put("notes", JsonPrimitive(notes)) }