diff --git a/.gitmodules b/.gitmodules index a8c520e..868a2ec 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ -[submodule "src/ENV"] - path = src/ENV - url = https://github.com/NanoCat-Me/ENV.git +[submodule "src/utils"] + path = src/utils + url = https://github.com/NanoCat-Me/utils.git diff --git a/js/AddOn.Microsoft.Translate.beta.js b/js/AddOn.Microsoft.Translate.beta.js index 28ebb29..85ddaaa 100644 --- a/js/AddOn.Microsoft.Translate.beta.js +++ b/js/AddOn.Microsoft.Translate.beta.js @@ -1,4 +1,19 @@ /* README: https://github.com/DualSubs */ +console.log('🍿️ DualSubs: ➕ AddOn Microsoft Translate β Response') +console.log('2024/10/12 15:15:44') +const $platform = platform(); +function platform() { + if ("undefined" !== typeof $environment && $environment["surge-version"]) + return "Surge" + if ("undefined" !== typeof $environment && $environment["stash-version"]) + return "Stash" + if ("undefined" !== typeof module && !!module.exports) return "Node.js" + if ("undefined" !== typeof $task) return "Quantumult X" + if ("undefined" !== typeof $loon) return "Loon" + if ("undefined" !== typeof $rocket) return "Shadowrocket" + if ("undefined" !== typeof Egern) return "Egern" +} + /* https://www.lodashjs.com */ class Lodash { static name = "Lodash"; @@ -71,48 +86,36 @@ class Lodash { } /* https://developer.mozilla.org/zh-CN/docs/Web/API/Storage/setItem */ -class $Storage { - static name = "$Storage"; - static version = "1.0.9"; - static about() { return console.log(`\n🟧 ${this.name} v${this.version}\n`) }; - static data = null - static dataFile = 'box.dat' +class Storage { + static name = "Storage"; + static version = "1.1.0"; + static about () { return log("", `🟧 ${this.name} v${this.version}`, "") }; + static data = null; + static dataFile = 'box.dat'; static #nameRegex = /^@(?[^.]+)(?:\.(?.*))?$/; - static #platform() { - if ('undefined' !== typeof $environment && $environment['surge-version']) - return 'Surge' - if ('undefined' !== typeof $environment && $environment['stash-version']) - return 'Stash' - if ('undefined' !== typeof module && !!module.exports) return 'Node.js' - if ('undefined' !== typeof $task) return 'Quantumult X' - if ('undefined' !== typeof $loon) return 'Loon' - if ('undefined' !== typeof $rocket) return 'Shadowrocket' - if ('undefined' !== typeof Egern) return 'Egern' - } - static getItem(keyName = new String, defaultValue = null) { let keyValue = defaultValue; // 如果以 @ switch (keyName.startsWith('@')) { case true: const { key, path } = keyName.match(this.#nameRegex)?.groups; - //console.log(`1: ${key}, ${path}`); + //log(`1: ${key}, ${path}`); keyName = key; let value = this.getItem(keyName, {}); - //console.log(`2: ${JSON.stringify(value)}`) + //log(`2: ${JSON.stringify(value)}`) if (typeof value !== "object") value = {}; - //console.log(`3: ${JSON.stringify(value)}`) + //log(`3: ${JSON.stringify(value)}`) keyValue = Lodash.get(value, path); - //console.log(`4: ${JSON.stringify(keyValue)}`) + //log(`4: ${JSON.stringify(keyValue)}`) try { keyValue = JSON.parse(keyValue); } catch (e) { // do nothing - } //console.log(`5: ${JSON.stringify(keyValue)}`) + } //log(`5: ${JSON.stringify(keyValue)}`) break; default: - switch (this.#platform()) { + switch ($platform) { case 'Surge': case 'Loon': case 'Stash': @@ -140,7 +143,7 @@ class $Storage { static setItem(keyName = new String, keyValue = new String) { let result = false; - //console.log(`0: ${typeof keyValue}`); + //log(`0: ${typeof keyValue}`); switch (typeof keyValue) { case "object": keyValue = JSON.stringify(keyValue); @@ -151,19 +154,19 @@ class $Storage { } switch (keyName.startsWith('@')) { case true: const { key, path } = keyName.match(this.#nameRegex)?.groups; - //console.log(`1: ${key}, ${path}`); + //log(`1: ${key}, ${path}`); keyName = key; let value = this.getItem(keyName, {}); - //console.log(`2: ${JSON.stringify(value)}`) + //log(`2: ${JSON.stringify(value)}`) if (typeof value !== "object") value = {}; - //console.log(`3: ${JSON.stringify(value)}`) + //log(`3: ${JSON.stringify(value)}`) Lodash.set(value, path, keyValue); - //console.log(`4: ${JSON.stringify(value)}`) + //log(`4: ${JSON.stringify(value)}`) result = this.setItem(keyName, value); - //console.log(`5: ${result}`) + //log(`5: ${result}`) break; default: - switch (this.#platform()) { + switch ($platform) { case 'Surge': case 'Loon': case 'Stash': @@ -199,7 +202,7 @@ class $Storage { result = this.setItem(keyName, value); break; default: - switch (this.#platform()) { + switch ($platform) { case 'Surge': case 'Loon': case 'Stash': @@ -222,7 +225,7 @@ class $Storage { static clear() { let result = false; - switch (this.#platform()) { + switch ($platform) { case 'Surge': case 'Loon': case 'Stash': @@ -292,466 +295,249 @@ class $Storage { } -class ENV { - static name = "ENV" - static version = '1.7.4' - static about() { return console.log(`\n🟧 ${this.name} v${this.version}\n`) } - - constructor(name, opts) { - console.log(`\n🟧 ${ENV.name} v${ENV.version}\n`); - this.name = name; - this.logs = []; - this.isMute = false; - this.isMuteLog = false; - this.logSeparator = '\n'; - this.encoding = 'utf-8'; - this.startTime = new Date().getTime(); - Object.assign(this, opts); - this.log(`\n🚩 开始!\n${name}\n`); - } - - platform() { - if ('undefined' !== typeof $environment && $environment['surge-version']) - return 'Surge' - if ('undefined' !== typeof $environment && $environment['stash-version']) - return 'Stash' - if ('undefined' !== typeof module && !!module.exports) return 'Node.js' - if ('undefined' !== typeof $task) return 'Quantumult X' - if ('undefined' !== typeof $loon) return 'Loon' - if ('undefined' !== typeof $rocket) return 'Shadowrocket' - if ('undefined' !== typeof Egern) return 'Egern' - } - - isNode() { - return 'Node.js' === this.platform() - } - - isQuanX() { - return 'Quantumult X' === this.platform() - } - - isSurge() { - return 'Surge' === this.platform() - } - - isLoon() { - return 'Loon' === this.platform() - } - - isShadowrocket() { - return 'Shadowrocket' === this.platform() - } - - isStash() { - return 'Stash' === this.platform() - } - - isEgern() { - return 'Egern' === this.platform() - } - - async getScript(url) { - return await this.fetch(url).then(response => response.body); - } - - async runScript(script, runOpts) { - let httpapi = $Storage.getItem('@chavy_boxjs_userCfgs.httpapi'); - httpapi = httpapi?.replace?.(/\n/g, '')?.trim(); - let httpapi_timeout = $Storage.getItem('@chavy_boxjs_userCfgs.httpapi_timeout'); - httpapi_timeout = (httpapi_timeout * 1) ?? 20; - httpapi_timeout = runOpts?.timeout ?? httpapi_timeout; - const [password, address] = httpapi.split('@'); - const request = { - url: `http://${address}/v1/scripting/evaluate`, - body: { - script_text: script, - mock_type: 'cron', - timeout: httpapi_timeout - }, - headers: { 'X-Key': password, 'Accept': '*/*' }, - timeout: httpapi_timeout - }; - await this.fetch(request).then(response => response.body, error => this.logErr(error)); - } - - initGotEnv(opts) { - this.got = this.got ? this.got : require('got'); - this.cktough = this.cktough ? this.cktough : require('tough-cookie'); - this.ckjar = this.ckjar ? this.ckjar : new this.cktough.CookieJar(); - if (opts) { - opts.headers = opts.headers ? opts.headers : {}; - if (undefined === opts.headers.Cookie && undefined === opts.cookieJar) { - opts.cookieJar = this.ckjar; - } - } - } - - async fetch(request = {} || "", option = {}) { - // 初始化参数 - switch (request.constructor) { - case Object: - request = { ...request, ...option }; - break; - case String: - request = { "url": request, ...option }; - break; - } // 自动判断请求方法 - if (!request.method) { - request.method = "GET"; - if (request.body ?? request.bodyBytes) request.method = "POST"; - } // 移除请求头中的部分参数, 让其自动生成 - delete request.headers?.Host; - delete request.headers?.[":authority"]; - delete request.headers?.['Content-Length']; - delete request.headers?.['content-length']; - // 定义请求方法(小写) - const method = request.method.toLocaleLowerCase(); - // 判断平台 - switch (this.platform()) { - case 'Loon': - case 'Surge': - case 'Stash': - case 'Egern': - case 'Shadowrocket': - default: - // 转换请求参数 - if (request.policy) { - if (this.isLoon()) request.node = request.policy; - if (this.isStash()) Lodash.set(request, "headers.X-Stash-Selected-Proxy", encodeURI(request.policy)); - } if (typeof request.redirection === "boolean") request["auto-redirect"] = request.redirection; - // 转换请求体 - if (request.bodyBytes && !request.body) { - request.body = request.bodyBytes; - delete request.bodyBytes; - } // 发送请求 - return await new Promise((resolve, reject) => { - $httpClient[method](request, (error, response, body) => { - if (error) reject(error); - else { - response.ok = /^2\d\d$/.test(response.status); - response.statusCode = response.status; - if (body) { - response.body = body; - if (request["binary-mode"] == true) response.bodyBytes = body; - } resolve(response); - } - }); - }); - case 'Quantumult X': - // 转换请求参数 - if (request.policy) Lodash.set(request, "opts.policy", request.policy); - if (typeof request["auto-redirect"] === "boolean") Lodash.set(request, "opts.redirection", request["auto-redirect"]); - // 转换请求体 - if (request.body instanceof ArrayBuffer) { - request.bodyBytes = request.body; - delete request.body; - } else if (ArrayBuffer.isView(request.body)) { - request.bodyBytes = request.body.buffer.slice(request.body.byteOffset, request.body.byteLength + request.body.byteOffset); - delete object.body; - } else if (request.body) delete request.bodyBytes; - // 发送请求 - return await $task.fetch(request).then( - response => { - response.ok = /^2\d\d$/.test(response.statusCode); - response.status = response.statusCode; - return response; - }, - reason => Promise.reject(reason.error)); - case 'Node.js': - let iconv = require('iconv-lite'); - this.initGotEnv(request); - const { url, ...option } = request; - return await this.got[method](url, option) - .on('redirect', (response, nextOpts) => { - try { - if (response.headers['set-cookie']) { - const ck = response.headers['set-cookie'] - .map(this.cktough.Cookie.parse) - .toString(); - if (ck) { - this.ckjar.setCookieSync(ck, null); - } - nextOpts.cookieJar = this.ckjar; - } - } catch (e) { - this.logErr(e); - } - // this.ckjar.setCookieSync(response.headers['set-cookie'].map(Cookie.parse).toString()) - }) - .then( - response => { - response.statusCode = response.status; - response.body = iconv.decode(response.rawBody, this.encoding); - response.bodyBytes = response.rawBody; - return response; - }, - error => Promise.reject(error.message)); - } }; - - /** - * - * 示例:$.time('yyyy-MM-dd qq HH:mm:ss.S') - * :$.time('yyyyMMddHHmmssS') - * y:年 M:月 d:日 q:季 H:时 m:分 s:秒 S:毫秒 - * 其中y可选0-4位占位符、S可选0-1位占位符,其余可选0-2位占位符 - * @param {string} format 格式化参数 - * @param {number} ts 可选: 根据指定时间戳返回格式化日期 - * - */ - time(format, ts = null) { - const date = ts ? new Date(ts) : new Date(); - let o = { - 'M+': date.getMonth() + 1, - 'd+': date.getDate(), - 'H+': date.getHours(), - 'm+': date.getMinutes(), - 's+': date.getSeconds(), - 'q+': Math.floor((date.getMonth() + 3) / 3), - 'S': date.getMilliseconds() - }; - if (/(y+)/.test(format)) - format = format.replace( - RegExp.$1, - (date.getFullYear() + '').substr(4 - RegExp.$1.length) - ); - for (let k in o) - if (new RegExp('(' + k + ')').test(format)) - format = format.replace( - RegExp.$1, - RegExp.$1.length == 1 - ? o[k] - : ('00' + o[k]).substr(('' + o[k]).length) - ); - return format - } - - /** - * 系统通知 - * - * > 通知参数: 同时支持 QuanX 和 Loon 两种格式, EnvJs根据运行环境自动转换, Surge 环境不支持多媒体通知 - * - * 示例: - * $.msg(title, subt, desc, 'twitter://') - * $.msg(title, subt, desc, { 'open-url': 'twitter://', 'media-url': 'https://github.githubassets.com/images/modules/open_graph/github-mark.png' }) - * $.msg(title, subt, desc, { 'open-url': 'https://bing.com', 'media-url': 'https://github.githubassets.com/images/modules/open_graph/github-mark.png' }) - * - * @param {*} title 标题 - * @param {*} subt 副标题 - * @param {*} desc 通知详情 - * @param {*} opts 通知参数 - * - */ - msg(title = name, subt = '', desc = '', opts) { - const toEnvOpts = (rawopts) => { - switch (typeof rawopts) { - case undefined: - return rawopts - case 'string': - switch (this.platform()) { - case 'Surge': - case 'Stash': - case 'Egern': - default: - return { url: rawopts } - case 'Loon': - case 'Shadowrocket': - return rawopts - case 'Quantumult X': - return { 'open-url': rawopts } - case 'Node.js': - return undefined - } - case 'object': - switch (this.platform()) { - case 'Surge': - case 'Stash': - case 'Egern': - case 'Shadowrocket': - default: { - let openUrl = - rawopts.url || rawopts.openUrl || rawopts['open-url']; - return { url: openUrl } - } - case 'Loon': { - let openUrl = - rawopts.openUrl || rawopts.url || rawopts['open-url']; - let mediaUrl = rawopts.mediaUrl || rawopts['media-url']; - return { openUrl, mediaUrl } - } - case 'Quantumult X': { - let openUrl = - rawopts['open-url'] || rawopts.url || rawopts.openUrl; - let mediaUrl = rawopts['media-url'] || rawopts.mediaUrl; - let updatePasteboard = - rawopts['update-pasteboard'] || rawopts.updatePasteboard; - return { - 'open-url': openUrl, - 'media-url': mediaUrl, - 'update-pasteboard': updatePasteboard - } - } - case 'Node.js': - return undefined - } - default: - return undefined - } - }; - if (!this.isMute) { - switch (this.platform()) { - case 'Surge': - case 'Loon': - case 'Stash': - case 'Egern': - case 'Shadowrocket': - default: - $notification.post(title, subt, desc, toEnvOpts(opts)); - break - case 'Quantumult X': - $notify(title, subt, desc, toEnvOpts(opts)); - break - case 'Node.js': - break - } - } - if (!this.isMuteLog) { - let logs = ['', '==============📣系统通知📣==============']; - logs.push(title); - subt ? logs.push(subt) : ''; - desc ? logs.push(desc) : ''; - console.log(logs.join('\n')); - this.logs = this.logs.concat(logs); - } - } - - log(...logs) { - if (logs.length > 0) { - this.logs = [...this.logs, ...logs]; - } - console.log(logs.join(this.logSeparator)); - } - - logErr(error) { - switch (this.platform()) { - case 'Surge': - case 'Loon': - case 'Stash': - case 'Egern': - case 'Shadowrocket': - case 'Quantumult X': - default: - this.log('', `❗️ ${this.name}, 错误!`, error); - break - case 'Node.js': - this.log('', `❗️${this.name}, 错误!`, error.stack); - break - } - } - - wait(time) { - return new Promise((resolve) => setTimeout(resolve, time)) - } - - done(object = {}) { - const endTime = new Date().getTime(); - const costTime = (endTime - this.startTime) / 1000; - this.log("", `🚩 ${this.name}, 结束! 🕛 ${costTime} 秒`, ""); - switch (this.platform()) { - case 'Surge': - if (object.policy) Lodash.set(object, "headers.X-Surge-Policy", object.policy); - $done(object); - break; - case 'Loon': - if (object.policy) object.node = object.policy; - $done(object); - break; - case 'Stash': - if (object.policy) Lodash.set(object, "headers.X-Stash-Selected-Proxy", encodeURI(object.policy)); - $done(object); - break; - case 'Egern': - $done(object); - break; - case 'Shadowrocket': - default: - $done(object); - break; - case 'Quantumult X': - if (object.policy) Lodash.set(object, "opts.policy", object.policy); - // 移除不可写字段 - delete object["auto-redirect"]; - delete object["auto-cookie"]; - delete object["binary-mode"]; - delete object.charset; - delete object.host; - delete object.insecure; - delete object.method; // 1.4.x 不可写 - delete object.opt; // $task.fetch() 参数, 不可写 - delete object.path; // 可写, 但会与 url 冲突 - delete object.policy; - delete object["policy-descriptor"]; - delete object.scheme; - delete object.sessionIndex; - delete object.statusCode; - delete object.timeout; - if (object.body instanceof ArrayBuffer) { - object.bodyBytes = object.body; - delete object.body; - } else if (ArrayBuffer.isView(object.body)) { - object.bodyBytes = object.body.buffer.slice(object.body.byteOffset, object.body.byteLength + object.body.byteOffset); - delete object.body; - } else if (object.body) delete object.bodyBytes; - $done(object); - break; - case 'Node.js': - process.exit(1); - break; - } - } +function initGotEnv(opts) { + this.got = this.got ? this.got : require("got"); + this.cktough = this.cktough ? this.cktough : require("tough-cookie"); + this.ckjar = this.ckjar ? this.ckjar : new this.cktough.CookieJar(); + if (opts) { + opts.headers = opts.headers ? opts.headers : {}; + if (undefined === opts.headers.Cookie && undefined === opts.cookieJar) { + opts.cookieJar = this.ckjar; + } + }} + +async function fetch(request = {} || "", option = {}) { + // 初始化参数 + switch (request.constructor) { + case Object: + request = { ...option, ...request }; + break; + case String: + request = { ...option, "url": request }; + break; + } // 自动判断请求方法 + if (!request.method) { + request.method = "GET"; + if (request.body ?? request.bodyBytes) request.method = "POST"; + } // 移除请求头中的部分参数, 让其自动生成 + delete request.headers?.Host; + delete request.headers?.[":authority"]; + delete request.headers?.["Content-Length"]; + delete request.headers?.["content-length"]; + // 定义请求方法(小写) + const method = request.method.toLocaleLowerCase(); + // 判断平台 + switch ($platform) { + case "Loon": + case "Surge": + case "Stash": + case "Egern": + case "Shadowrocket": + default: + // 转换请求参数 + if (request.timeout) { + request.timeout = parseInt(request.timeout, 10); + switch ($platform) { + case "Loon": + case "Shadowrocket": + case "Stash": + case "Egern": + default: + request.timeout = request.timeout / 1000; + break; + case "Surge": + break; + } } if (request.policy) { + switch ($platform) { + case "Loon": + request.node = request.policy; + break; + case "Stash": + Lodash.set(request, "headers.X-Stash-Selected-Proxy", encodeURI(request.policy)); + break; + case "Shadowrocket": + Lodash.set(request, "headers.X-Surge-Proxy", request.policy); + break; + } } if (typeof request.redirection === "boolean") request["auto-redirect"] = request.redirection; + // 转换请求体 + if (request.bodyBytes && !request.body) { + request.body = request.bodyBytes; + delete request.bodyBytes; + } // 发送请求 + return await new Promise((resolve, reject) => { + $httpClient[method](request, (error, response, body) => { + if (error) reject(error); + else { + response.ok = /^2\d\d$/.test(response.status); + response.statusCode = response.status; + if (body) { + response.body = body; + if (request["binary-mode"] == true) response.bodyBytes = body; + } resolve(response); + } + }); + }); + case "Quantumult X": + // 转换请求参数 + if (request.policy) Lodash.set(request, "opts.policy", request.policy); + if (typeof request["auto-redirect"] === "boolean") Lodash.set(request, "opts.redirection", request["auto-redirect"]); + // 转换请求体 + if (request.body instanceof ArrayBuffer) { + request.bodyBytes = request.body; + delete request.body; + } else if (ArrayBuffer.isView(request.body)) { + request.bodyBytes = request.body.buffer.slice(request.body.byteOffset, request.body.byteLength + request.body.byteOffset); + delete object.body; + } else if (request.body) delete request.bodyBytes; + // 发送请求 + return await $task.fetch(request).then( + response => { + response.ok = /^2\d\d$/.test(response.statusCode); + response.status = response.statusCode; + return response; + }, + reason => Promise.reject(reason.error)); + case "Node.js": + let iconv = require("iconv-lite"); + initGotEnv(request); + const { url, ...option } = request; + return await this.got[method](url, option) + .on("redirect", (response, nextOpts) => { + try { + if (response.headers["set-cookie"]) { + const ck = response.headers["set-cookie"] + .map(this.cktough.Cookie.parse) + .toString(); + if (ck) { + this.ckjar.setCookieSync(ck, null); + } + nextOpts.cookieJar = this.ckjar; + } + } catch (e) { + this.logErr(e); + } + // this.ckjar.setCookieSync(response.headers["set-cookie"].map(Cookie.parse).toString()) + }) + .then( + response => { + response.statusCode = response.status; + response.body = iconv.decode(response.rawBody, "utf-8"); + response.bodyBytes = response.rawBody; + return response; + }, + error => Promise.reject(error.message)); + }} + +function logError(error) { + switch ($platform) { + case "Surge": + case "Loon": + case "Stash": + case "Egern": + case "Shadowrocket": + case "Quantumult X": + default: + log("", `❗️执行错误!`, error, ""); + break + case "Node.js": + log("", `❗️执行错误!`, error.stack, ""); + break + }} + +function done(object = {}) { + switch ($platform) { + case "Surge": + if (object.policy) Lodash.set(object, "headers.X-Surge-Policy", object.policy); + log("", `🚩 执行结束! 🕛 ${(new Date().getTime() / 1000 - $script.startTime)} 秒`, ""); + $done(object); + break; + case "Loon": + if (object.policy) object.node = object.policy; + log("", `🚩 执行结束! 🕛 ${(new Date() - $script.startTime) / 1000} 秒`, ""); + $done(object); + break; + case "Stash": + if (object.policy) Lodash.set(object, "headers.X-Stash-Selected-Proxy", encodeURI(object.policy)); + log("", `🚩 执行结束! 🕛 ${(new Date() - $script.startTime) / 1000} 秒`, ""); + $done(object); + break; + case "Egern": + log("", `🚩 执行结束!`, ""); + $done(object); + break; + case "Shadowrocket": + default: + log("", `🚩 执行结束!`, ""); + $done(object); + break; + case "Quantumult X": + if (object.policy) Lodash.set(object, "opts.policy", object.policy); + // 移除不可写字段 + delete object["auto-redirect"]; + delete object["auto-cookie"]; + delete object["binary-mode"]; + delete object.charset; + delete object.host; + delete object.insecure; + delete object.method; // 1.4.x 不可写 + delete object.opt; // $task.fetch() 参数, 不可写 + delete object.path; // 可写, 但会与 url 冲突 + delete object.policy; + delete object["policy-descriptor"]; + delete object.scheme; + delete object.sessionIndex; + delete object.statusCode; + delete object.timeout; + if (object.body instanceof ArrayBuffer) { + object.bodyBytes = object.body; + delete object.body; + } else if (ArrayBuffer.isView(object.body)) { + object.bodyBytes = object.body.buffer.slice(object.body.byteOffset, object.body.byteLength + object.body.byteOffset); + delete object.body; + } else if (object.body) delete object.bodyBytes; + log("", `🚩 执行结束!`, ""); + $done(object); + break; + case "Node.js": + log("", `🚩 执行结束!`, ""); + process.exit(1); + break; + } } -var Settings = { - Switch: true, - Type: "Translate", - Types: [ - "Official", - "Translate" - ], - Languages: [ - "EN", - "ZH" - ], - CacheSize: 50 -}; -var Configs = { - breakLine: { - "text/xml": " ", - "application/xml": " ", - "text/vtt": "\n", - "application/vtt": "\n", - "text/json": "\n", - "application/json": "\n" - } -}; -var Default = { - Settings: Settings, - Configs: Configs -}; - -var Default$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - Configs: Configs, - Settings: Settings, - default: Default -}); - -var Database$1 = Database = { - "Default": Default$1, +const log = (...logs) => console.log(logs.join("\n")); + +var database = { + "Default": { + "Settings": { + "Switch": true, + "Type": "Translate", + "Types": [ + "Official", + "Translate" + ], + "Languages": [ + "EN", + "ZH" + ], + "CacheSize": 50 + }, + "Configs":{ + "breakLine":{ + "text/xml":" ", + "application/xml":" ", + "text/vtt":"\n", + "application/vtt":"\n", + "text/json":"\n", + "application/json":"\n" + } + } + } }; /** * Get Storage Variables - * @link https://github.com/NanoCat-Me/ENV/blob/main/getStorage.mjs + * @link https://github.com/NanoCat-Me/utils/blob/main/getStorage.mjs * @author VirgilClyne * @param {String} key - Persistent Store Key * @param {Array} names - Platform Names @@ -759,43 +545,43 @@ var Database$1 = Database = { * @return {Object} { Settings, Caches, Configs } */ function getStorage(key, names, database) { - //console.log(`☑️ ${this.name}, Get Environment Variables`, ""); + //log(`☑️ getStorage, Get Environment Variables`, ""); /***************** BoxJs *****************/ // 包装为局部变量,用完释放内存 // BoxJs的清空操作返回假值空字符串, 逻辑或操作符会在左侧操作数为假值时返回右侧操作数。 - let BoxJs = $Storage.getItem(key, database); - //console.log(`🚧 ${this.name}, Get Environment Variables`, `BoxJs类型: ${typeof BoxJs}`, `BoxJs内容: ${JSON.stringify(BoxJs)}`, ""); + let BoxJs = Storage.getItem(key, database); + //log(`🚧 getStorage, Get Environment Variables`, `BoxJs类型: ${typeof BoxJs}`, `BoxJs内容: ${JSON.stringify(BoxJs)}`, ""); /***************** Argument *****************/ let Argument = {}; - if (typeof $argument !== "undefined") { - if (Boolean($argument)) { - //console.log(`🎉 ${this.name}, $Argument`); + switch (typeof $argument) { + case "string": let arg = Object.fromEntries($argument.split("&").map((item) => item.split("=").map(i => i.replace(/\"/g, '')))); - //console.log(JSON.stringify(arg)); for (let item in arg) Lodash.set(Argument, item, arg[item]); - //console.log(JSON.stringify(Argument)); - } //console.log(`✅ ${this.name}, Get Environment Variables`, `Argument类型: ${typeof Argument}`, `Argument内容: ${JSON.stringify(Argument)}`, ""); - } /***************** Store *****************/ + break; + case "object": + for (let item in $argument) Lodash.set(Argument, item, $argument[item]); + break; + } //log(`✅ getStorage, Get Environment Variables`, `Argument类型: ${typeof Argument}`, `Argument内容: ${JSON.stringify(Argument)}`, ""); + /***************** Store *****************/ const Store = { Settings: database?.Default?.Settings || {}, Configs: database?.Default?.Configs || {}, Caches: {} }; if (!Array.isArray(names)) names = [names]; - //console.log(`🚧 ${this.name}, Get Environment Variables`, `names类型: ${typeof names}`, `names内容: ${JSON.stringify(names)}`, ""); + //log(`🚧 getStorage, Get Environment Variables`, `names类型: ${typeof names}`, `names内容: ${JSON.stringify(names)}`, ""); for (let name of names) { Store.Settings = { ...Store.Settings, ...database?.[name]?.Settings, ...Argument, ...BoxJs?.[name]?.Settings }; Store.Configs = { ...Store.Configs, ...database?.[name]?.Configs }; if (BoxJs?.[name]?.Caches && typeof BoxJs?.[name]?.Caches === "string") BoxJs[name].Caches = JSON.parse(BoxJs?.[name]?.Caches); Store.Caches = { ...Store.Caches, ...BoxJs?.[name]?.Caches }; - } //console.log(`🚧 ${this.name}, Get Environment Variables`, `Store.Settings类型: ${typeof Store.Settings}`, `Store.Settings: ${JSON.stringify(Store.Settings)}`, ""); + } //log(`🚧 getStorage, Get Environment Variables`, `Store.Settings类型: ${typeof Store.Settings}`, `Store.Settings: ${JSON.stringify(Store.Settings)}`, ""); traverseObject(Store.Settings, (key, value) => { - //console.log(`🚧 ${this.name}, traverseObject`, `${key}: ${typeof value}`, `${key}: ${JSON.stringify(value)}`, ""); + //log(`🚧 getStorage, traverseObject`, `${key}: ${typeof value}`, `${key}: ${JSON.stringify(value)}`, ""); if (value === "true" || value === "false") value = JSON.parse(value); // 字符串转Boolean else if (typeof value === "string") { if (value.includes(",")) value = value.split(",").map(item => string2number(item)); // 字符串转数组转数字 else value = string2number(value); // 字符串转数字 } return value; }); - //console.log(`✅ ${this.name}, Get Environment Variables`, `Store: ${typeof Store.Caches}`, `Store内容: ${JSON.stringify(Store)}`, ""); + //log(`✅ getStorage, Get Environment Variables`, `Store: ${typeof Store.Caches}`, `Store内容: ${JSON.stringify(Store)}`, ""); return Store; - /***************** function *****************/ function traverseObject(o, c) { for (var t in o) { var n = o[t]; o[t] = "object" == typeof n && null !== n ? traverseObject(n, c) : c(t, n); } return o } function string2number(string) { if (string && !isNaN(string)) string = parseInt(string, 10); return string } @@ -810,23 +596,21 @@ function getStorage(key, names, database) { * @return {Object} { Settings, Caches, Configs } */ function setENV(name, platforms, database) { - console.log(`☑️ Set Environment Variables`, ""); + log(`☑️ Set Environment Variables`, ""); let { Settings, Caches, Configs } = getStorage(name, platforms, database); /***************** Settings *****************/ if (!Array.isArray(Settings?.Types)) Settings.Types = (Settings.Types) ? [Settings.Types] : []; // 只有一个选项时,无逗号分隔 - console.log(`✅ Set Environment Variables, Settings: ${typeof Settings}, Settings内容: ${JSON.stringify(Settings)}`, ""); + log(`✅ Set Environment Variables, Settings: ${typeof Settings}, Settings内容: ${JSON.stringify(Settings)}`, ""); /***************** Caches *****************/ if (typeof Caches?.Playlists !== "object" || Array.isArray(Caches?.Playlists)) Caches.Playlists = {}; // 创建Playlists缓存 Caches.Playlists.Master = new Map(JSON.parse(Caches?.Playlists?.Master || "[]")); // Strings转Array转Map Caches.Playlists.Subtitle = new Map(JSON.parse(Caches?.Playlists?.Subtitle || "[]")); // Strings转Array转Map if (typeof Caches?.Subtitles !== "object") Caches.Subtitles = new Map(JSON.parse(Caches?.Subtitles || "[]")); // Strings转Array转Map - //console.log(`✅ Set Environment Variables, Caches: ${typeof Caches}, Caches内容: ${JSON.stringify(Caches)}`, ""); + //log(`✅ Set Environment Variables, Caches: ${typeof Caches}, Caches内容: ${JSON.stringify(Caches)}`, ""); /***************** Configs *****************/ return { Settings, Caches, Configs }; } -const $ = new ENV("🍿️ DualSubs: ➕ AddOn v1.0.1(4) Microsoft.Translate.beta"); - const $request = { "url": "https://edge.microsoft.com/translate/auth", "headers": { @@ -834,29 +618,28 @@ const $request = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" } }; - /***************** Processing *****************/ (async () => { // 读取设置 - const { Settings, Caches, Configs } = setENV("DualSubs", ["Translate", "API"], Database$1); - $.log(`⚠ Settings.Switch: ${Settings?.Switch}`, ""); + const { Settings, Caches, Configs } = setENV("DualSubs", ["Translate", "API"], database); + log(`⚠ Settings.Switch: ${Settings?.Switch}`, ""); switch (Settings.Switch) { case true: default: - const $response = await $.fetch($request); + const $response = await fetch($request); Lodash.set(Settings, "Vendor", "Microsoft"); Lodash.set(Settings, "Microsoft.Version", "Azure"); Lodash.set(Settings, "Microsoft.Mode", "Token"); Lodash.set(Settings, "Microsoft.Token", $response?.body); - $.log(`⚠ Settings: ${JSON.stringify(Settings)}`, ""); + log(`⚠ Settings: ${JSON.stringify(Settings)}`, ""); // 写入缓存 - $Storage.setItem(`@DualSubs.Translate.Settings.Vendor`, Settings.Vendor); - $Storage.setItem(`@DualSubs.API.Settings.Microsoft.Version`, Settings.Microsoft.Version); - $Storage.setItem(`@DualSubs.API.Settings.Microsoft.Mode`, Settings.Microsoft.Mode); - $Storage.setItem(`@DualSubs.API.Settings.Microsoft.Token`, Settings.Microsoft.Token); + Storage.setItem(`@DualSubs.Translate.Settings.Vendor`, Settings.Vendor); + Storage.setItem(`@DualSubs.API.Settings.Microsoft.Version`, Settings.Microsoft.Version); + Storage.setItem(`@DualSubs.API.Settings.Microsoft.Mode`, Settings.Microsoft.Mode); + Storage.setItem(`@DualSubs.API.Settings.Microsoft.Token`, Settings.Microsoft.Token); break; case false: break; }})() - .catch((e) => $.logErr(e)) - .finally(() => $.done()); + .catch((e) => logError(e)) + .finally(() => done()); diff --git a/js/AddOn.Microsoft.Translate.js b/js/AddOn.Microsoft.Translate.js index 4fda794..0ea9478 100644 --- a/js/AddOn.Microsoft.Translate.js +++ b/js/AddOn.Microsoft.Translate.js @@ -1 +1 @@ -class e{static name="Lodash";static version="1.2.2";static about(){return console.log(`\n🟧 ${this.name} v${this.version}\n`)}static get(e={},t="",s=void 0){Array.isArray(t)||(t=this.toPath(t));const o=t.reduce(((e,t)=>Object(e)[t]),e);return void 0===o?s:o}static set(e={},t="",s){return Array.isArray(t)||(t=this.toPath(t)),t.slice(0,-1).reduce(((e,s,o)=>Object(e[s])===e[s]?e[s]:e[s]=/^\d+$/.test(t[o+1])?[]:{}),e)[t[t.length-1]]=s,e}static unset(e={},t=""){return Array.isArray(t)||(t=this.toPath(t)),t.reduce(((e,s,o)=>o===t.length-1?(delete e[s],!0):Object(e)[s]),e)}static toPath(e){return e.replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean)}static escape(e){const t={"&":"&","<":"<",">":">",'"':""","'":"'"};return e.replace(/[&<>"']/g,(e=>t[e]))}static unescape(e){const t={"&":"&","<":"<",">":">",""":'"',"'":"'"};return e.replace(/&|<|>|"|'/g,(e=>t[e]))}}class t{static name="$Storage";static version="1.0.9";static about(){return console.log(`\n🟧 ${this.name} v${this.version}\n`)}static data=null;static dataFile="box.dat";static#e=/^@(?[^.]+)(?:\.(?.*))?$/;static#t(){return"undefined"!=typeof $environment&&$environment["surge-version"]?"Surge":"undefined"!=typeof $environment&&$environment["stash-version"]?"Stash":"undefined"!=typeof module&&module.exports?"Node.js":"undefined"!=typeof $task?"Quantumult X":"undefined"!=typeof $loon?"Loon":"undefined"!=typeof $rocket?"Shadowrocket":"undefined"!=typeof Egern?"Egern":void 0}static getItem(t=new String,s=null){let o=s;if(!0===t.startsWith("@")){const{key:s,path:a}=t.match(this.#e)?.groups;t=s;let r=this.getItem(t,{});"object"!=typeof r&&(r={}),o=e.get(r,a);try{o=JSON.parse(o)}catch(e){}}else{switch(this.#t()){case"Surge":case"Loon":case"Stash":case"Egern":case"Shadowrocket":o=$persistentStore.read(t);break;case"Quantumult X":o=$prefs.valueForKey(t);break;case"Node.js":this.data=this.#s(this.dataFile),o=this.data?.[t];break;default:o=this.data?.[t]||null}try{o=JSON.parse(o)}catch(e){}}return o??s}static setItem(t=new String,s=new String){let o=!1;if("object"==typeof s)s=JSON.stringify(s);else s=String(s);if(!0===t.startsWith("@")){const{key:a,path:r}=t.match(this.#e)?.groups;t=a;let i=this.getItem(t,{});"object"!=typeof i&&(i={}),e.set(i,r,s),o=this.setItem(t,i)}else switch(this.#t()){case"Surge":case"Loon":case"Stash":case"Egern":case"Shadowrocket":o=$persistentStore.write(s,t);break;case"Quantumult X":o=$prefs.setValueForKey(s,t);break;case"Node.js":this.data=this.#s(this.dataFile),this.data[t]=s,this.#o(this.dataFile),o=!0;break;default:o=this.data?.[t]||null}return o}static removeItem(t){let s=!1;if(!0===t.startsWith("@")){const{key:o,path:a}=t.match(this.#e)?.groups;t=o;let r=this.getItem(t);"object"!=typeof r&&(r={}),keyValue=e.unset(r,a),s=this.setItem(t,r)}else switch(this.#t()){case"Surge":case"Loon":case"Stash":case"Egern":case"Shadowrocket":case"Node.js":default:s=!1;break;case"Quantumult X":s=$prefs.removeValueForKey(t)}return s}static clear(){let e=!1;switch(this.#t()){case"Surge":case"Loon":case"Stash":case"Egern":case"Shadowrocket":case"Node.js":default:e=!1;break;case"Quantumult X":e=$prefs.removeAllValues()}return e}static#s(e){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(e),s=this.path.resolve(process.cwd(),e),o=this.fs.existsSync(t),a=!o&&this.fs.existsSync(s);if(!o&&!a)return{};{const e=o?t:s;try{return JSON.parse(this.fs.readFileSync(e))}catch(e){return{}}}}}static#o(e=this.dataFile){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(e),s=this.path.resolve(process.cwd(),e),o=this.fs.existsSync(t),a=!o&&this.fs.existsSync(s),r=JSON.stringify(this.data);o?this.fs.writeFileSync(t,r):a?this.fs.writeFileSync(s,r):this.fs.writeFileSync(t,r)}}}class s{static name="ENV";static version="1.7.4";static about(){return console.log(`\n🟧 ${this.name} v${this.version}\n`)}constructor(e,t){console.log(`\n🟧 ${s.name} v${s.version}\n`),this.name=e,this.logs=[],this.isMute=!1,this.isMuteLog=!1,this.logSeparator="\n",this.encoding="utf-8",this.startTime=(new Date).getTime(),Object.assign(this,t),this.log(`\n🚩 开始!\n${e}\n`)}platform(){return"undefined"!=typeof $environment&&$environment["surge-version"]?"Surge":"undefined"!=typeof $environment&&$environment["stash-version"]?"Stash":"undefined"!=typeof module&&module.exports?"Node.js":"undefined"!=typeof $task?"Quantumult X":"undefined"!=typeof $loon?"Loon":"undefined"!=typeof $rocket?"Shadowrocket":"undefined"!=typeof Egern?"Egern":void 0}isNode(){return"Node.js"===this.platform()}isQuanX(){return"Quantumult X"===this.platform()}isSurge(){return"Surge"===this.platform()}isLoon(){return"Loon"===this.platform()}isShadowrocket(){return"Shadowrocket"===this.platform()}isStash(){return"Stash"===this.platform()}isEgern(){return"Egern"===this.platform()}async getScript(e){return await this.fetch(e).then((e=>e.body))}async runScript(e,s){let o=t.getItem("@chavy_boxjs_userCfgs.httpapi");o=o?.replace?.(/\n/g,"")?.trim();let a=t.getItem("@chavy_boxjs_userCfgs.httpapi_timeout");a=1*a??20,a=s?.timeout??a;const[r,i]=o.split("@"),n={url:`http://${i}/v1/scripting/evaluate`,body:{script_text:e,mock_type:"cron",timeout:a},headers:{"X-Key":r,Accept:"*/*"},timeout:a};await this.fetch(n).then((e=>e.body),(e=>this.logErr(e)))}initGotEnv(e){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,e&&(e.headers=e.headers?e.headers:{},void 0===e.headers.Cookie&&void 0===e.cookieJar&&(e.cookieJar=this.ckjar))}async fetch(t={}||"",s={}){switch(t.constructor){case Object:t={...t,...s};break;case String:t={url:t,...s}}t.method||(t.method="GET",(t.body??t.bodyBytes)&&(t.method="POST")),delete t.headers?.Host,delete t.headers?.[":authority"],delete t.headers?.["Content-Length"],delete t.headers?.["content-length"];const o=t.method.toLocaleLowerCase();switch(this.platform()){case"Loon":case"Surge":case"Stash":case"Egern":case"Shadowrocket":default:return t.policy&&(this.isLoon()&&(t.node=t.policy),this.isStash()&&e.set(t,"headers.X-Stash-Selected-Proxy",encodeURI(t.policy))),"boolean"==typeof t.redirection&&(t["auto-redirect"]=t.redirection),t.bodyBytes&&!t.body&&(t.body=t.bodyBytes,delete t.bodyBytes),await new Promise(((e,s)=>{$httpClient[o](t,((o,a,r)=>{o?s(o):(a.ok=/^2\d\d$/.test(a.status),a.statusCode=a.status,r&&(a.body=r,1==t["binary-mode"]&&(a.bodyBytes=r)),e(a))}))}));case"Quantumult X":return t.policy&&e.set(t,"opts.policy",t.policy),"boolean"==typeof t["auto-redirect"]&&e.set(t,"opts.redirection",t["auto-redirect"]),t.body instanceof ArrayBuffer?(t.bodyBytes=t.body,delete t.body):ArrayBuffer.isView(t.body)?(t.bodyBytes=t.body.buffer.slice(t.body.byteOffset,t.body.byteLength+t.body.byteOffset),delete object.body):t.body&&delete t.bodyBytes,await $task.fetch(t).then((e=>(e.ok=/^2\d\d$/.test(e.statusCode),e.status=e.statusCode,e)),(e=>Promise.reject(e.error)));case"Node.js":let s=require("iconv-lite");this.initGotEnv(t);const{url:a,...r}=t;return await this.got[o](a,r).on("redirect",((e,t)=>{try{if(e.headers["set-cookie"]){const s=e.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();s&&this.ckjar.setCookieSync(s,null),t.cookieJar=this.ckjar}}catch(e){this.logErr(e)}})).then((e=>(e.statusCode=e.status,e.body=s.decode(e.rawBody,this.encoding),e.bodyBytes=e.rawBody,e)),(e=>Promise.reject(e.message)))}}time(e,t=null){const s=t?new Date(t):new Date;let o={"M+":s.getMonth()+1,"d+":s.getDate(),"H+":s.getHours(),"m+":s.getMinutes(),"s+":s.getSeconds(),"q+":Math.floor((s.getMonth()+3)/3),S:s.getMilliseconds()};/(y+)/.test(e)&&(e=e.replace(RegExp.$1,(s.getFullYear()+"").substr(4-RegExp.$1.length)));for(let t in o)new RegExp("("+t+")").test(e)&&(e=e.replace(RegExp.$1,1==RegExp.$1.length?o[t]:("00"+o[t]).substr((""+o[t]).length)));return e}msg(e=name,t="",s="",o){const a=e=>{switch(typeof e){case void 0:return e;case"string":switch(this.platform()){case"Surge":case"Stash":case"Egern":default:return{url:e};case"Loon":case"Shadowrocket":return e;case"Quantumult X":return{"open-url":e};case"Node.js":return}case"object":switch(this.platform()){case"Surge":case"Stash":case"Egern":case"Shadowrocket":default:return{url:e.url||e.openUrl||e["open-url"]};case"Loon":return{openUrl:e.openUrl||e.url||e["open-url"],mediaUrl:e.mediaUrl||e["media-url"]};case"Quantumult X":return{"open-url":e["open-url"]||e.url||e.openUrl,"media-url":e["media-url"]||e.mediaUrl,"update-pasteboard":e["update-pasteboard"]||e.updatePasteboard};case"Node.js":return}default:return}};if(!this.isMute)switch(this.platform()){case"Surge":case"Loon":case"Stash":case"Egern":case"Shadowrocket":default:$notification.post(e,t,s,a(o));break;case"Quantumult X":$notify(e,t,s,a(o));case"Node.js":}if(!this.isMuteLog){let o=["","==============📣系统通知📣=============="];o.push(e),t&&o.push(t),s&&o.push(s),console.log(o.join("\n")),this.logs=this.logs.concat(o)}}log(...e){e.length>0&&(this.logs=[...this.logs,...e]),console.log(e.join(this.logSeparator))}logErr(e){switch(this.platform()){case"Surge":case"Loon":case"Stash":case"Egern":case"Shadowrocket":case"Quantumult X":default:this.log("",`❗️ ${this.name}, 错误!`,e);break;case"Node.js":this.log("",`❗️${this.name}, 错误!`,e.stack)}}wait(e){return new Promise((t=>setTimeout(t,e)))}done(t={}){const s=((new Date).getTime()-this.startTime)/1e3;switch(this.log("",`🚩 ${this.name}, 结束! 🕛 ${s} 秒`,""),this.platform()){case"Surge":t.policy&&e.set(t,"headers.X-Surge-Policy",t.policy),$done(t);break;case"Loon":t.policy&&(t.node=t.policy),$done(t);break;case"Stash":t.policy&&e.set(t,"headers.X-Stash-Selected-Proxy",encodeURI(t.policy)),$done(t);break;case"Egern":case"Shadowrocket":default:$done(t);break;case"Quantumult X":t.policy&&e.set(t,"opts.policy",t.policy),delete t["auto-redirect"],delete t["auto-cookie"],delete t["binary-mode"],delete t.charset,delete t.host,delete t.insecure,delete t.method,delete t.opt,delete t.path,delete t.policy,delete t["policy-descriptor"],delete t.scheme,delete t.sessionIndex,delete t.statusCode,delete t.timeout,t.body instanceof ArrayBuffer?(t.bodyBytes=t.body,delete t.body):ArrayBuffer.isView(t.body)?(t.bodyBytes=t.body.buffer.slice(t.body.byteOffset,t.body.byteLength+t.body.byteOffset),delete t.body):t.body&&delete t.bodyBytes,$done(t);break;case"Node.js":process.exit(1)}}}var o={Switch:!0,Type:"Translate",Types:["Official","Translate"],Languages:["EN","ZH"],CacheSize:50},a={breakLine:{"text/xml":" ","application/xml":" ","text/vtt":"\n","application/vtt":"\n","text/json":"\n","application/json":"\n"}},r={Settings:o,Configs:a},i=Database={Default:Object.freeze({__proto__:null,Configs:a,Settings:o,default:r})};function n(s,o,a){console.log("☑️ Set Environment Variables","");let{Settings:r,Caches:i,Configs:n}=function(s,o,a){let r=t.getItem(s,a),i={};if("undefined"!=typeof $argument&&Boolean($argument)){let t=Object.fromEntries($argument.split("&").map((e=>e.split("=").map((e=>e.replace(/\"/g,""))))));for(let s in t)e.set(i,s,t[s])}const n={Settings:a?.Default?.Settings||{},Configs:a?.Default?.Configs||{},Caches:{}};Array.isArray(o)||(o=[o]);for(let e of o)n.Settings={...n.Settings,...a?.[e]?.Settings,...i,...r?.[e]?.Settings},n.Configs={...n.Configs,...a?.[e]?.Configs},r?.[e]?.Caches&&"string"==typeof r?.[e]?.Caches&&(r[e].Caches=JSON.parse(r?.[e]?.Caches)),n.Caches={...n.Caches,...r?.[e]?.Caches};return function e(t,s){for(var o in t){var a=t[o];t[o]="object"==typeof a&&null!==a?e(a,s):s(o,a)}return t}(n.Settings,((e,t)=>("true"===t||"false"===t?t=JSON.parse(t):"string"==typeof t&&(t=t.includes(",")?t.split(",").map((e=>c(e))):c(t)),t))),n;function c(e){return e&&!isNaN(e)&&(e=parseInt(e,10)),e}}(s,o,a);return Array.isArray(r?.Types)||(r.Types=r.Types?[r.Types]:[]),console.log(`✅ Set Environment Variables, Settings: ${typeof r}, Settings内容: ${JSON.stringify(r)}`,""),("object"!=typeof i?.Playlists||Array.isArray(i?.Playlists))&&(i.Playlists={}),i.Playlists.Master=new Map(JSON.parse(i?.Playlists?.Master||"[]")),i.Playlists.Subtitle=new Map(JSON.parse(i?.Playlists?.Subtitle||"[]")),"object"!=typeof i?.Subtitles&&(i.Subtitles=new Map(JSON.parse(i?.Subtitles||"[]"))),{Settings:r,Caches:i,Configs:n}}const c=new s("🍿️ DualSubs: ➕ AddOn v1.0.1(4) Microsoft.Translate"),l={url:"https://edge.microsoft.com/translate/auth",headers:{"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Safari/605.1.15",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}};(async()=>{const{Settings:s,Caches:o,Configs:a}=n("DualSubs",["Translate","API"],i);switch(c.log(`⚠ Settings.Switch: ${s?.Switch}`,""),s.Switch){case!0:default:const o=await c.fetch(l);e.set(s,"Vendor","Microsoft"),e.set(s,"Microsoft.Version","Azure"),e.set(s,"Microsoft.Mode","Token"),e.set(s,"Microsoft.Token",o?.body),c.log(`⚠ Settings: ${JSON.stringify(s)}`,""),t.setItem("@DualSubs.Translate.Settings.Vendor",s.Vendor),t.setItem("@DualSubs.API.Settings.Microsoft.Version",s.Microsoft.Version),t.setItem("@DualSubs.API.Settings.Microsoft.Mode",s.Microsoft.Mode),t.setItem("@DualSubs.API.Settings.Microsoft.Token",s.Microsoft.Token);case!1:}})().catch((e=>c.logErr(e))).finally((()=>c.done())); +console.log("🍿️ DualSubs: ➕ AddOn Microsoft Translate Response"),console.log("2024/10/12 15:15:48");const e=function(){if("undefined"!=typeof $environment&&$environment["surge-version"])return"Surge";if("undefined"!=typeof $environment&&$environment["stash-version"])return"Stash";if("undefined"!=typeof module&&module.exports)return"Node.js";if("undefined"!=typeof $task)return"Quantumult X";if("undefined"!=typeof $loon)return"Loon";if("undefined"!=typeof $rocket)return"Shadowrocket";if("undefined"!=typeof Egern)return"Egern"}();class t{static name="Lodash";static version="1.2.2";static about(){return console.log(`\n🟧 ${this.name} v${this.version}\n`)}static get(e={},t="",s=void 0){Array.isArray(t)||(t=this.toPath(t));const a=t.reduce(((e,t)=>Object(e)[t]),e);return void 0===a?s:a}static set(e={},t="",s){return Array.isArray(t)||(t=this.toPath(t)),t.slice(0,-1).reduce(((e,s,a)=>Object(e[s])===e[s]?e[s]:e[s]=/^\d+$/.test(t[a+1])?[]:{}),e)[t[t.length-1]]=s,e}static unset(e={},t=""){return Array.isArray(t)||(t=this.toPath(t)),t.reduce(((e,s,a)=>a===t.length-1?(delete e[s],!0):Object(e)[s]),e)}static toPath(e){return e.replace(/\[(\d+)\]/g,".$1").split(".").filter(Boolean)}static escape(e){const t={"&":"&","<":"<",">":">",'"':""","'":"'"};return e.replace(/[&<>"']/g,(e=>t[e]))}static unescape(e){const t={"&":"&","<":"<",">":">",""":'"',"'":"'"};return e.replace(/&|<|>|"|'/g,(e=>t[e]))}}class s{static name="Storage";static version="1.1.0";static about(){return o("",`🟧 ${this.name} v${this.version}`,"")}static data=null;static dataFile="box.dat";static#e=/^@(?[^.]+)(?:\.(?.*))?$/;static getItem(s=new String,a=null){let o=a;if(!0===s.startsWith("@")){const{key:e,path:a}=s.match(this.#e)?.groups;s=e;let i=this.getItem(s,{});"object"!=typeof i&&(i={}),o=t.get(i,a);try{o=JSON.parse(o)}catch(e){}}else{switch(e){case"Surge":case"Loon":case"Stash":case"Egern":case"Shadowrocket":o=$persistentStore.read(s);break;case"Quantumult X":o=$prefs.valueForKey(s);break;case"Node.js":this.data=this.#t(this.dataFile),o=this.data?.[s];break;default:o=this.data?.[s]||null}try{o=JSON.parse(o)}catch(e){}}return o??a}static setItem(s=new String,a=new String){let o=!1;if("object"==typeof a)a=JSON.stringify(a);else a=String(a);if(!0===s.startsWith("@")){const{key:e,path:i}=s.match(this.#e)?.groups;s=e;let r=this.getItem(s,{});"object"!=typeof r&&(r={}),t.set(r,i,a),o=this.setItem(s,r)}else switch(e){case"Surge":case"Loon":case"Stash":case"Egern":case"Shadowrocket":o=$persistentStore.write(a,s);break;case"Quantumult X":o=$prefs.setValueForKey(a,s);break;case"Node.js":this.data=this.#t(this.dataFile),this.data[s]=a,this.#s(this.dataFile),o=!0;break;default:o=this.data?.[s]||null}return o}static removeItem(s){let a=!1;if(!0===s.startsWith("@")){const{key:e,path:o}=s.match(this.#e)?.groups;s=e;let i=this.getItem(s);"object"!=typeof i&&(i={}),keyValue=t.unset(i,o),a=this.setItem(s,i)}else switch(e){case"Surge":case"Loon":case"Stash":case"Egern":case"Shadowrocket":case"Node.js":default:a=!1;break;case"Quantumult X":a=$prefs.removeValueForKey(s)}return a}static clear(){let t=!1;switch(e){case"Surge":case"Loon":case"Stash":case"Egern":case"Shadowrocket":case"Node.js":default:t=!1;break;case"Quantumult X":t=$prefs.removeAllValues()}return t}static#t(e){if(!this.isNode())return{};{this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(e),s=this.path.resolve(process.cwd(),e),a=this.fs.existsSync(t),o=!a&&this.fs.existsSync(s);if(!a&&!o)return{};{const e=a?t:s;try{return JSON.parse(this.fs.readFileSync(e))}catch(e){return{}}}}}static#s(e=this.dataFile){if(this.isNode()){this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const t=this.path.resolve(e),s=this.path.resolve(process.cwd(),e),a=this.fs.existsSync(t),o=!a&&this.fs.existsSync(s),i=JSON.stringify(this.data);a?this.fs.writeFileSync(t,i):o?this.fs.writeFileSync(s,i):this.fs.writeFileSync(t,i)}}}async function a(s={}||"",a={}){switch(s.constructor){case Object:s={...a,...s};break;case String:s={...a,url:s}}s.method||(s.method="GET",(s.body??s.bodyBytes)&&(s.method="POST")),delete s.headers?.Host,delete s.headers?.[":authority"],delete s.headers?.["Content-Length"],delete s.headers?.["content-length"];const o=s.method.toLocaleLowerCase();switch(e){case"Loon":case"Surge":case"Stash":case"Egern":case"Shadowrocket":default:if(s.timeout)switch(s.timeout=parseInt(s.timeout,10),e){case"Loon":case"Shadowrocket":case"Stash":case"Egern":default:s.timeout=s.timeout/1e3;case"Surge":}if(s.policy)switch(e){case"Loon":s.node=s.policy;break;case"Stash":t.set(s,"headers.X-Stash-Selected-Proxy",encodeURI(s.policy));break;case"Shadowrocket":t.set(s,"headers.X-Surge-Proxy",s.policy)}return"boolean"==typeof s.redirection&&(s["auto-redirect"]=s.redirection),s.bodyBytes&&!s.body&&(s.body=s.bodyBytes,delete s.bodyBytes),await new Promise(((e,t)=>{$httpClient[o](s,((a,o,i)=>{a?t(a):(o.ok=/^2\d\d$/.test(o.status),o.statusCode=o.status,i&&(o.body=i,1==s["binary-mode"]&&(o.bodyBytes=i)),e(o))}))}));case"Quantumult X":return s.policy&&t.set(s,"opts.policy",s.policy),"boolean"==typeof s["auto-redirect"]&&t.set(s,"opts.redirection",s["auto-redirect"]),s.body instanceof ArrayBuffer?(s.bodyBytes=s.body,delete s.body):ArrayBuffer.isView(s.body)?(s.bodyBytes=s.body.buffer.slice(s.body.byteOffset,s.body.byteLength+s.body.byteOffset),delete object.body):s.body&&delete s.bodyBytes,await $task.fetch(s).then((e=>(e.ok=/^2\d\d$/.test(e.statusCode),e.status=e.statusCode,e)),(e=>Promise.reject(e.error)));case"Node.js":let a=require("iconv-lite");!function(e){this.got=this.got?this.got:require("got"),this.cktough=this.cktough?this.cktough:require("tough-cookie"),this.ckjar=this.ckjar?this.ckjar:new this.cktough.CookieJar,e&&(e.headers=e.headers?e.headers:{},void 0===e.headers.Cookie&&void 0===e.cookieJar&&(e.cookieJar=this.ckjar))}(s);const{url:i,...r}=s;return await this.got[o](i,r).on("redirect",((e,t)=>{try{if(e.headers["set-cookie"]){const s=e.headers["set-cookie"].map(this.cktough.Cookie.parse).toString();s&&this.ckjar.setCookieSync(s,null),t.cookieJar=this.ckjar}}catch(e){this.logErr(e)}})).then((e=>(e.statusCode=e.status,e.body=a.decode(e.rawBody,"utf-8"),e.bodyBytes=e.rawBody,e)),(e=>Promise.reject(e.message)))}}const o=(...e)=>console.log(e.join("\n"));var i={Default:{Settings:{Switch:!0,Type:"Translate",Types:["Official","Translate"],Languages:["EN","ZH"],CacheSize:50},Configs:{breakLine:{"text/xml":" ","application/xml":" ","text/vtt":"\n","application/vtt":"\n","text/json":"\n","application/json":"\n"}}}};function r(e,a,i){o("☑️ Set Environment Variables","");let{Settings:r,Caches:n,Configs:c}=function(e,a,o){let i=s.getItem(e,o),r={};switch(typeof $argument){case"string":let e=Object.fromEntries($argument.split("&").map((e=>e.split("=").map((e=>e.replace(/\"/g,""))))));for(let s in e)t.set(r,s,e[s]);break;case"object":for(let e in $argument)t.set(r,e,$argument[e])}const n={Settings:o?.Default?.Settings||{},Configs:o?.Default?.Configs||{},Caches:{}};Array.isArray(a)||(a=[a]);for(let e of a)n.Settings={...n.Settings,...o?.[e]?.Settings,...r,...i?.[e]?.Settings},n.Configs={...n.Configs,...o?.[e]?.Configs},i?.[e]?.Caches&&"string"==typeof i?.[e]?.Caches&&(i[e].Caches=JSON.parse(i?.[e]?.Caches)),n.Caches={...n.Caches,...i?.[e]?.Caches};return function e(t,s){for(var a in t){var o=t[a];t[a]="object"==typeof o&&null!==o?e(o,s):s(a,o)}return t}(n.Settings,((e,t)=>("true"===t||"false"===t?t=JSON.parse(t):"string"==typeof t&&(t=t.includes(",")?t.split(",").map((e=>c(e))):c(t)),t))),n;function c(e){return e&&!isNaN(e)&&(e=parseInt(e,10)),e}}(e,a,i);return Array.isArray(r?.Types)||(r.Types=r.Types?[r.Types]:[]),o(`✅ Set Environment Variables, Settings: ${typeof r}, Settings内容: ${JSON.stringify(r)}`,""),("object"!=typeof n?.Playlists||Array.isArray(n?.Playlists))&&(n.Playlists={}),n.Playlists.Master=new Map(JSON.parse(n?.Playlists?.Master||"[]")),n.Playlists.Subtitle=new Map(JSON.parse(n?.Playlists?.Subtitle||"[]")),"object"!=typeof n?.Subtitles&&(n.Subtitles=new Map(JSON.parse(n?.Subtitles||"[]"))),{Settings:r,Caches:n,Configs:c}}const n={url:"https://edge.microsoft.com/translate/auth",headers:{"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Safari/605.1.15",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}};(async()=>{const{Settings:e,Caches:c,Configs:l}=r("DualSubs",["Translate","API"],i);switch(o(`⚠ Settings.Switch: ${e?.Switch}`,""),e.Switch){case!0:default:const i=await a(n);t.set(e,"Vendor","Microsoft"),t.set(e,"Microsoft.Version","Azure"),t.set(e,"Microsoft.Mode","Token"),t.set(e,"Microsoft.Token",i?.body),o(`⚠ Settings: ${JSON.stringify(e)}`,""),s.setItem("@DualSubs.Translate.Settings.Vendor",e.Vendor),s.setItem("@DualSubs.API.Settings.Microsoft.Version",e.Microsoft.Version),s.setItem("@DualSubs.API.Settings.Microsoft.Mode",e.Microsoft.Mode),s.setItem("@DualSubs.API.Settings.Microsoft.Token",e.Microsoft.Token);case!1:}})().catch((t=>function(t){switch(e){case"Surge":case"Loon":case"Stash":case"Egern":case"Shadowrocket":case"Quantumult X":default:o("","❗️执行错误!",t,"");break;case"Node.js":o("","❗️执行错误!",t.stack,"")}}(t))).finally((()=>function(s={}){switch(e){case"Surge":s.policy&&t.set(s,"headers.X-Surge-Policy",s.policy),o("",`🚩 执行结束! 🕛 ${(new Date).getTime()/1e3-$script.startTime} 秒`,""),$done(s);break;case"Loon":s.policy&&(s.node=s.policy),o("",`🚩 执行结束! 🕛 ${(new Date-$script.startTime)/1e3} 秒`,""),$done(s);break;case"Stash":s.policy&&t.set(s,"headers.X-Stash-Selected-Proxy",encodeURI(s.policy)),o("",`🚩 执行结束! 🕛 ${(new Date-$script.startTime)/1e3} 秒`,""),$done(s);break;case"Egern":case"Shadowrocket":default:o("","🚩 执行结束!",""),$done(s);break;case"Quantumult X":s.policy&&t.set(s,"opts.policy",s.policy),delete s["auto-redirect"],delete s["auto-cookie"],delete s["binary-mode"],delete s.charset,delete s.host,delete s.insecure,delete s.method,delete s.opt,delete s.path,delete s.policy,delete s["policy-descriptor"],delete s.scheme,delete s.sessionIndex,delete s.statusCode,delete s.timeout,s.body instanceof ArrayBuffer?(s.bodyBytes=s.body,delete s.body):ArrayBuffer.isView(s.body)?(s.bodyBytes=s.body.buffer.slice(s.body.byteOffset,s.body.byteLength+s.body.byteOffset),delete s.body):s.body&&delete s.bodyBytes,o("","🚩 执行结束!",""),$done(s);break;case"Node.js":o("","🚩 执行结束!",""),process.exit(1)}}())); diff --git a/package-lock.json b/package-lock.json index f211901..7304554 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,9 @@ "name": "dualsubs-addon", "version": "1.0.0", "license": "Apache-2.0", + "dependencies": { + "@rollup/plugin-node-resolve": "^15.3.0" + }, "devDependencies": { "@rollup/plugin-commonjs": "^25.0.7", "@rollup/plugin-json": "^6.1.0", @@ -118,6 +121,30 @@ } } }, + "node_modules/@rollup/plugin-node-resolve": { + "version": "15.3.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-15.3.0.tgz", + "integrity": "sha512-9eO5McEICxMzJpDW9OnMYSv4Sta3hmt7VtBFz5zR9273suNOydOyq/FrGeGy+KsTRFm8w0SLVhzig2ILFT63Ag==", + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.0.1", + "@types/resolve": "1.20.2", + "deepmerge": "^4.2.2", + "is-module": "^1.0.0", + "resolve": "^1.22.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^2.78.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, "node_modules/@rollup/plugin-terser": { "version": "0.4.4", "resolved": "https://registry.npmjs.org/@rollup/plugin-terser/-/plugin-terser-0.4.4.tgz", @@ -144,7 +171,6 @@ "version": "5.1.0", "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.1.0.tgz", "integrity": "sha512-XTIWOPPcpvyKI6L1NHo0lFlCyznUEyPmPY1mc3KpPVDYulHSTvyeLNVW00QTLIAFNhR3kYnJTQHeGqU4M3n09g==", - "dev": true, "dependencies": { "@types/estree": "^1.0.0", "estree-walker": "^2.0.2", @@ -163,179 +189,240 @@ } }, "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.12.0.tgz", - "integrity": "sha512-+ac02NL/2TCKRrJu2wffk1kZ+RyqxVUlbjSagNgPm94frxtr+XDL12E5Ll1enWskLrtrZ2r8L3wED1orIibV/w==", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.24.0.tgz", + "integrity": "sha512-Q6HJd7Y6xdB48x8ZNVDOqsbh2uByBhgK8PiQgPhwkIw/HC/YX5Ghq2mQY5sRMZWHb3VsFkWooUVOZHKr7DmDIA==", "cpu": [ "arm" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "android" ] }, "node_modules/@rollup/rollup-android-arm64": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.12.0.tgz", - "integrity": "sha512-OBqcX2BMe6nvjQ0Nyp7cC90cnumt8PXmO7Dp3gfAju/6YwG0Tj74z1vKrfRz7qAv23nBcYM8BCbhrsWqO7PzQQ==", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.24.0.tgz", + "integrity": "sha512-ijLnS1qFId8xhKjT81uBHuuJp2lU4x2yxa4ctFPtG+MqEE6+C5f/+X/bStmxapgmwLwiL3ih122xv8kVARNAZA==", "cpu": [ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "android" ] }, "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.12.0.tgz", - "integrity": "sha512-X64tZd8dRE/QTrBIEs63kaOBG0b5GVEd3ccoLtyf6IdXtHdh8h+I56C2yC3PtC9Ucnv0CpNFJLqKFVgCYe0lOQ==", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.24.0.tgz", + "integrity": "sha512-bIv+X9xeSs1XCk6DVvkO+S/z8/2AMt/2lMqdQbMrmVpgFvXlmde9mLcbQpztXm1tajC3raFDqegsH18HQPMYtA==", "cpu": [ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "darwin" ] }, "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.12.0.tgz", - "integrity": "sha512-cc71KUZoVbUJmGP2cOuiZ9HSOP14AzBAThn3OU+9LcA1+IUqswJyR1cAJj3Mg55HbjZP6OLAIscbQsQLrpgTOg==", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.24.0.tgz", + "integrity": "sha512-X6/nOwoFN7RT2svEQWUsW/5C/fYMBe4fnLK9DQk4SX4mgVBiTA9h64kjUYPvGQ0F/9xwJ5U5UfTbl6BEjaQdBQ==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "darwin" ] }, "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.12.0.tgz", - "integrity": "sha512-a6w/Y3hyyO6GlpKL2xJ4IOh/7d+APaqLYdMf86xnczU3nurFTaVN9s9jOXQg97BE4nYm/7Ga51rjec5nfRdrvA==", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.24.0.tgz", + "integrity": "sha512-0KXvIJQMOImLCVCz9uvvdPgfyWo93aHHp8ui3FrtOP57svqrF/roSSR5pjqL2hcMp0ljeGlU4q9o/rQaAQ3AYA==", "cpu": [ "arm" ], "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.24.0.tgz", + "integrity": "sha512-it2BW6kKFVh8xk/BnHfakEeoLPv8STIISekpoF+nBgWM4d55CZKc7T4Dx1pEbTnYm/xEKMgy1MNtYuoA8RFIWw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.12.0.tgz", - "integrity": "sha512-0fZBq27b+D7Ar5CQMofVN8sggOVhEtzFUwOwPppQt0k+VR+7UHMZZY4y+64WJ06XOhBTKXtQB/Sv0NwQMXyNAA==", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.24.0.tgz", + "integrity": "sha512-i0xTLXjqap2eRfulFVlSnM5dEbTVque/3Pi4g2y7cxrs7+a9De42z4XxKLYJ7+OhE3IgxvfQM7vQc43bwTgPwA==", "cpu": [ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.12.0.tgz", - "integrity": "sha512-eTvzUS3hhhlgeAv6bfigekzWZjaEX9xP9HhxB0Dvrdbkk5w/b+1Sxct2ZuDxNJKzsRStSq1EaEkVSEe7A7ipgQ==", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.24.0.tgz", + "integrity": "sha512-9E6MKUJhDuDh604Qco5yP/3qn3y7SLXYuiC0Rpr89aMScS2UAmK1wHP2b7KAa1nSjWJc/f/Lc0Wl1L47qjiyQw==", "cpu": [ "arm64" ], "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-powerpc64le-gnu": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.24.0.tgz", + "integrity": "sha512-2XFFPJ2XMEiF5Zi2EBf4h73oR1V/lycirxZxHZNc93SqDN/IWhYYSYj8I9381ikUFXZrz2v7r2tOVk2NBwxrWw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.12.0.tgz", - "integrity": "sha512-ix+qAB9qmrCRiaO71VFfY8rkiAZJL8zQRXveS27HS+pKdjwUfEhqo2+YF2oI+H/22Xsiski+qqwIBxVewLK7sw==", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.24.0.tgz", + "integrity": "sha512-M3Dg4hlwuntUCdzU7KjYqbbd+BLq3JMAOhCKdBE3TcMGMZbKkDdJ5ivNdehOssMCIokNHFOsv7DO4rlEOfyKpg==", "cpu": [ "riscv64" ], "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.24.0.tgz", + "integrity": "sha512-mjBaoo4ocxJppTorZVKWFpy1bfFj9FeCMJqzlMQGjpNPY9JwQi7OuS1axzNIk0nMX6jSgy6ZURDZ2w0QW6D56g==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.12.0.tgz", - "integrity": "sha512-TenQhZVOtw/3qKOPa7d+QgkeM6xY0LtwzR8OplmyL5LrgTWIXpTQg2Q2ycBf8jm+SFW2Wt/DTn1gf7nFp3ssVA==", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.24.0.tgz", + "integrity": "sha512-ZXFk7M72R0YYFN5q13niV0B7G8/5dcQ9JDp8keJSfr3GoZeXEoMHP/HlvqROA3OMbMdfr19IjCeNAnPUG93b6A==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.12.0.tgz", - "integrity": "sha512-LfFdRhNnW0zdMvdCb5FNuWlls2WbbSridJvxOvYWgSBOYZtgBfW9UGNJG//rwMqTX1xQE9BAodvMH9tAusKDUw==", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.24.0.tgz", + "integrity": "sha512-w1i+L7kAXZNdYl+vFvzSZy8Y1arS7vMgIy8wusXJzRrPyof5LAb02KGr1PD2EkRcl73kHulIID0M501lN+vobQ==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.12.0.tgz", - "integrity": "sha512-JPDxovheWNp6d7AHCgsUlkuCKvtu3RB55iNEkaQcf0ttsDU/JZF+iQnYcQJSk/7PtT4mjjVG8N1kpwnI9SLYaw==", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.24.0.tgz", + "integrity": "sha512-VXBrnPWgBpVDCVY6XF3LEW0pOU51KbaHhccHw6AS6vBWIC60eqsH19DAeeObl+g8nKAz04QFdl/Cefta0xQtUQ==", "cpu": [ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "win32" ] }, "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.12.0.tgz", - "integrity": "sha512-fjtuvMWRGJn1oZacG8IPnzIV6GF2/XG+h71FKn76OYFqySXInJtseAqdprVTDTyqPxQOG9Exak5/E9Z3+EJ8ZA==", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.24.0.tgz", + "integrity": "sha512-xrNcGDU0OxVcPTH/8n/ShH4UevZxKIO6HJFK0e15XItZP2UcaiLFd5kiX7hJnqCbSztUF8Qot+JWBC/QXRPYWQ==", "cpu": [ "ia32" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "win32" ] }, "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.12.0.tgz", - "integrity": "sha512-ZYmr5mS2wd4Dew/JjT0Fqi2NPB/ZhZ2VvPp7SmvPZb4Y1CG/LRcS6tcRo2cYU7zLK5A7cdbhWnnWmUjoI4qapg==", + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.24.0.tgz", + "integrity": "sha512-fbMkAF7fufku0N2dE5TBXcNlg0pt0cJue4xBRE2Qc5Vqikxr4VCgKj/ht6SMdFcOacVA9rqF70APJ8RN/4vMJw==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "win32" ] }, "node_modules/@types/estree": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.5.tgz", - "integrity": "sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==", - "dev": true + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", + "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==", + "license": "MIT" + }, + "node_modules/@types/resolve": { + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz", + "integrity": "sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==", + "license": "MIT" }, "node_modules/acorn": { "version": "8.11.3", @@ -382,11 +469,19 @@ "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", "dev": true }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/estree-walker": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", - "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", - "dev": true + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==" }, "node_modules/fs.realpath": { "version": "1.0.0", @@ -408,6 +503,15 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/glob": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/glob/-/glob-8.1.0.tgz", @@ -427,6 +531,18 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", @@ -443,6 +559,27 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "dev": true }, + "node_modules/is-core-module": { + "version": "2.15.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.15.1.tgz", + "integrity": "sha512-z0vtXSwucUJtANQWldhbtbt7BnL0vxiFjIdDLAatwhDYty2bad6s+rijD6Ri4YuYJubLzIJLUidCh09e1djEVQ==", + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", + "integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==", + "license": "MIT" + }, "node_modules/is-reference": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz", @@ -485,11 +622,16 @@ "wrappy": "1" } }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "license": "MIT" + }, "node_modules/picomatch": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "dev": true, "engines": { "node": ">=8.6" }, @@ -506,13 +648,31 @@ "safe-buffer": "^5.1.0" } }, + "node_modules/resolve": { + "version": "1.22.8", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", + "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", + "license": "MIT", + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/rollup": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.12.0.tgz", - "integrity": "sha512-wz66wn4t1OHIJw3+XU7mJJQV/2NAfw5OAk6G6Hoo3zcvz/XOfQ52Vgi+AN4Uxoxi0KBBwk2g8zPrTDA4btSB/Q==", - "dev": true, + "version": "4.24.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.24.0.tgz", + "integrity": "sha512-DOmrlGSXNk1DM0ljiQA+i+o0rSLhtii1je5wgk60j49d1jHT5YYttBv1iWOnYSTG+fZZESUOSNiAl89SIet+Cg==", + "devOptional": true, + "license": "MIT", "dependencies": { - "@types/estree": "1.0.5" + "@types/estree": "1.0.6" }, "bin": { "rollup": "dist/bin/rollup" @@ -522,19 +682,22 @@ "npm": ">=8.0.0" }, "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.12.0", - "@rollup/rollup-android-arm64": "4.12.0", - "@rollup/rollup-darwin-arm64": "4.12.0", - "@rollup/rollup-darwin-x64": "4.12.0", - "@rollup/rollup-linux-arm-gnueabihf": "4.12.0", - "@rollup/rollup-linux-arm64-gnu": "4.12.0", - "@rollup/rollup-linux-arm64-musl": "4.12.0", - "@rollup/rollup-linux-riscv64-gnu": "4.12.0", - "@rollup/rollup-linux-x64-gnu": "4.12.0", - "@rollup/rollup-linux-x64-musl": "4.12.0", - "@rollup/rollup-win32-arm64-msvc": "4.12.0", - "@rollup/rollup-win32-ia32-msvc": "4.12.0", - "@rollup/rollup-win32-x64-msvc": "4.12.0", + "@rollup/rollup-android-arm-eabi": "4.24.0", + "@rollup/rollup-android-arm64": "4.24.0", + "@rollup/rollup-darwin-arm64": "4.24.0", + "@rollup/rollup-darwin-x64": "4.24.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.24.0", + "@rollup/rollup-linux-arm-musleabihf": "4.24.0", + "@rollup/rollup-linux-arm64-gnu": "4.24.0", + "@rollup/rollup-linux-arm64-musl": "4.24.0", + "@rollup/rollup-linux-powerpc64le-gnu": "4.24.0", + "@rollup/rollup-linux-riscv64-gnu": "4.24.0", + "@rollup/rollup-linux-s390x-gnu": "4.24.0", + "@rollup/rollup-linux-x64-gnu": "4.24.0", + "@rollup/rollup-linux-x64-musl": "4.24.0", + "@rollup/rollup-win32-arm64-msvc": "4.24.0", + "@rollup/rollup-win32-ia32-msvc": "4.24.0", + "@rollup/rollup-win32-x64-msvc": "4.24.0", "fsevents": "~2.3.2" } }, @@ -592,6 +755,18 @@ "source-map": "^0.6.0" } }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/terser": { "version": "5.28.1", "resolved": "https://registry.npmjs.org/terser/-/terser-5.28.1.tgz", diff --git a/package.json b/package.json index 5453f5f..f3ca85b 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ }, "scripts": { "build": "rollup -c", - "test": "rollup --config --configDebug" + "build:debug": "rollup --config --configDebug" }, "browserslist": [ "iOS >= 15" @@ -25,5 +25,8 @@ "@rollup/plugin-json": "^6.1.0", "@rollup/plugin-terser": "^0.4.4", "rollup": "^4.9.6" + }, + "dependencies": { + "@rollup/plugin-node-resolve": "^15.3.0" } } diff --git a/rollup.debug.config.js b/rollup.debug.config.js index d04b4e5..def78a7 100644 --- a/rollup.debug.config.js +++ b/rollup.debug.config.js @@ -1,15 +1,16 @@ -import json from '@rollup/plugin-json'; +import json from "@rollup/plugin-json"; import commonjs from "@rollup/plugin-commonjs"; +import { nodeResolve } from '@rollup/plugin-node-resolve'; export default [ { - input: 'src/AddOn.Microsoft.Translate.beta.js', + input: "src/AddOn.Microsoft.Translate.beta.js", output: { - file: 'js/AddOn.Microsoft.Translate.beta.js', - banner: '/* README: https://github.com/DualSubs */', - format: 'es' + file: "js/AddOn.Microsoft.Translate.beta.js", + banner: `/* README: https://github.com/DualSubs */\nconsole.log('🍿️ DualSubs: ➕ AddOn Microsoft Translate β Response')\nconsole.log('${new Date().toLocaleString('zh-CN', {timeZone: 'PRC'})}')`, + format: "es" }, - plugins: [json(), commonjs()], + plugins: [json(), commonjs(), nodeResolve()], }, ]; diff --git a/rollup.default.config.js b/rollup.default.config.js index cc5676f..68812af 100644 --- a/rollup.default.config.js +++ b/rollup.default.config.js @@ -1,15 +1,16 @@ -import json from '@rollup/plugin-json'; +import json from "@rollup/plugin-json"; import commonjs from "@rollup/plugin-commonjs"; -import terser from '@rollup/plugin-terser'; +import terser from "@rollup/plugin-terser"; +import { nodeResolve } from '@rollup/plugin-node-resolve'; export default [ { - input: 'src/AddOn.Microsoft.Translate.js', + input: "src/AddOn.Microsoft.Translate.js", output: { - file: 'js/AddOn.Microsoft.Translate.js', - banner: '/* README: https://github.com/DualSubs */', - format: 'es' + file: "js/AddOn.Microsoft.Translate.js", + banner: `/* README: https://github.com/DualSubs */\nconsole.log('🍿️ DualSubs: ➕ AddOn Microsoft Translate Response')\nconsole.log('${new Date().toLocaleString('zh-CN', {timeZone: 'PRC'})}')`, + format: "es" }, - plugins: [json(), commonjs(), terser()] + plugins: [json(), commonjs(), nodeResolve(), terser()] }, ]; diff --git a/src/AddOn.Microsoft.Translate.beta.js b/src/AddOn.Microsoft.Translate.beta.js index b9a421d..ca20640 100644 --- a/src/AddOn.Microsoft.Translate.beta.js +++ b/src/AddOn.Microsoft.Translate.beta.js @@ -1,12 +1,6 @@ -import _ from './ENV/Lodash.mjs' -import $Storage from './ENV/$Storage.mjs' -import ENV from "./ENV/ENV.mjs"; - -import Database from "./database/index.mjs"; +import { $platform, _, Storage, fetch, notification, log, logError, wait, done, getScript, runScript } from "./utils/utils.mjs"; +import database from "./function/database.mjs"; import setENV from "./function/setENV.mjs"; - -const $ = new ENV("🍿️ DualSubs: ➕ AddOn v1.0.1(4) Microsoft.Translate.beta"); - const $request = { "url": "https://edge.microsoft.com/translate/auth", "headers": { @@ -14,30 +8,29 @@ const $request = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" } }; - /***************** Processing *****************/ (async () => { // 读取设置 - const { Settings, Caches, Configs } = setENV("DualSubs", ["Translate", "API"], Database); - $.log(`⚠ Settings.Switch: ${Settings?.Switch}`, ""); + const { Settings, Caches, Configs } = setENV("DualSubs", ["Translate", "API"], database); + log(`⚠ Settings.Switch: ${Settings?.Switch}`, ""); switch (Settings.Switch) { case true: default: - const $response = await $.fetch($request); + const $response = await fetch($request); _.set(Settings, "Vendor", "Microsoft"); _.set(Settings, "Microsoft.Version", "Azure"); _.set(Settings, "Microsoft.Mode", "Token"); _.set(Settings, "Microsoft.Token", $response?.body); - $.log(`⚠ Settings: ${JSON.stringify(Settings)}`, ""); + log(`⚠ Settings: ${JSON.stringify(Settings)}`, ""); // 写入缓存 - $Storage.setItem(`@DualSubs.Translate.Settings.Vendor`, Settings.Vendor); - $Storage.setItem(`@DualSubs.API.Settings.Microsoft.Version`, Settings.Microsoft.Version); - $Storage.setItem(`@DualSubs.API.Settings.Microsoft.Mode`, Settings.Microsoft.Mode); - $Storage.setItem(`@DualSubs.API.Settings.Microsoft.Token`, Settings.Microsoft.Token); + Storage.setItem(`@DualSubs.Translate.Settings.Vendor`, Settings.Vendor); + Storage.setItem(`@DualSubs.API.Settings.Microsoft.Version`, Settings.Microsoft.Version); + Storage.setItem(`@DualSubs.API.Settings.Microsoft.Mode`, Settings.Microsoft.Mode); + Storage.setItem(`@DualSubs.API.Settings.Microsoft.Token`, Settings.Microsoft.Token); break; case false: break; }; })() - .catch((e) => $.logErr(e)) - .finally(() => $.done()) + .catch((e) => logError(e)) + .finally(() => done()) diff --git a/src/AddOn.Microsoft.Translate.js b/src/AddOn.Microsoft.Translate.js index 106ae85..ca20640 100644 --- a/src/AddOn.Microsoft.Translate.js +++ b/src/AddOn.Microsoft.Translate.js @@ -1,12 +1,6 @@ -import _ from './ENV/Lodash.mjs' -import $Storage from './ENV/$Storage.mjs' -import ENV from "./ENV/ENV.mjs"; - -import Database from "./database/index.mjs"; +import { $platform, _, Storage, fetch, notification, log, logError, wait, done, getScript, runScript } from "./utils/utils.mjs"; +import database from "./function/database.mjs"; import setENV from "./function/setENV.mjs"; - -const $ = new ENV("🍿️ DualSubs: ➕ AddOn v1.0.1(4) Microsoft.Translate"); - const $request = { "url": "https://edge.microsoft.com/translate/auth", "headers": { @@ -14,30 +8,29 @@ const $request = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" } }; - /***************** Processing *****************/ (async () => { // 读取设置 - const { Settings, Caches, Configs } = setENV("DualSubs", ["Translate", "API"], Database); - $.log(`⚠ Settings.Switch: ${Settings?.Switch}`, ""); + const { Settings, Caches, Configs } = setENV("DualSubs", ["Translate", "API"], database); + log(`⚠ Settings.Switch: ${Settings?.Switch}`, ""); switch (Settings.Switch) { case true: default: - const $response = await $.fetch($request); + const $response = await fetch($request); _.set(Settings, "Vendor", "Microsoft"); _.set(Settings, "Microsoft.Version", "Azure"); _.set(Settings, "Microsoft.Mode", "Token"); _.set(Settings, "Microsoft.Token", $response?.body); - $.log(`⚠ Settings: ${JSON.stringify(Settings)}`, ""); + log(`⚠ Settings: ${JSON.stringify(Settings)}`, ""); // 写入缓存 - $Storage.setItem(`@DualSubs.Translate.Settings.Vendor`, Settings.Vendor); - $Storage.setItem(`@DualSubs.API.Settings.Microsoft.Version`, Settings.Microsoft.Version); - $Storage.setItem(`@DualSubs.API.Settings.Microsoft.Mode`, Settings.Microsoft.Mode); - $Storage.setItem(`@DualSubs.API.Settings.Microsoft.Token`, Settings.Microsoft.Token); + Storage.setItem(`@DualSubs.Translate.Settings.Vendor`, Settings.Vendor); + Storage.setItem(`@DualSubs.API.Settings.Microsoft.Version`, Settings.Microsoft.Version); + Storage.setItem(`@DualSubs.API.Settings.Microsoft.Mode`, Settings.Microsoft.Mode); + Storage.setItem(`@DualSubs.API.Settings.Microsoft.Token`, Settings.Microsoft.Token); break; case false: break; }; })() - .catch((e) => $.logErr(e)) - .finally(() => $.done()) + .catch((e) => logError(e)) + .finally(() => done()) diff --git a/src/ENV b/src/ENV deleted file mode 160000 index c650c23..0000000 --- a/src/ENV +++ /dev/null @@ -1 +0,0 @@ -Subproject commit c650c235f779516af18dd519d5a735a1be4793c1 diff --git a/src/database/Default.json b/src/database/Default.json deleted file mode 100644 index eb1f3b6..0000000 --- a/src/database/Default.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "Settings": { - "Switch": true, - "Type": "Translate", - "Types": [ - "Official", - "Translate" - ], - "Languages": [ - "EN", - "ZH" - ], - "CacheSize": 50 - }, - "Configs":{ - "breakLine":{ - "text/xml":" ", - "application/xml":" ", - "text/vtt":"\n", - "application/vtt":"\n", - "text/json":"\n", - "application/json":"\n" - } - } -} diff --git a/src/database/index.mjs b/src/database/index.mjs deleted file mode 100644 index ec723bc..0000000 --- a/src/database/index.mjs +++ /dev/null @@ -1,5 +0,0 @@ -import * as Default from "./Default.json"; - -export default Database = { - "Default": Default, -}; diff --git a/src/function/database.mjs b/src/function/database.mjs new file mode 100644 index 0000000..8c01761 --- /dev/null +++ b/src/function/database.mjs @@ -0,0 +1,27 @@ +export default { + "Default": { + "Settings": { + "Switch": true, + "Type": "Translate", + "Types": [ + "Official", + "Translate" + ], + "Languages": [ + "EN", + "ZH" + ], + "CacheSize": 50 + }, + "Configs":{ + "breakLine":{ + "text/xml":" ", + "application/xml":" ", + "text/vtt":"\n", + "application/vtt":"\n", + "text/json":"\n", + "application/json":"\n" + } + } + } +} diff --git a/src/function/setENV.mjs b/src/function/setENV.mjs index fe296bd..a0e154c 100644 --- a/src/function/setENV.mjs +++ b/src/function/setENV.mjs @@ -1,5 +1,5 @@ -import getStorage from '../ENV/getStorage.mjs' -import _ from '../ENV/Lodash.mjs' +import getStorage from '../utils/getStorage.mjs' +import { _, log } from "../utils/utils.mjs"; /** * Set Environment Variables @@ -10,17 +10,17 @@ import _ from '../ENV/Lodash.mjs' * @return {Object} { Settings, Caches, Configs } */ export default function setENV(name, platforms, database) { - console.log(`☑️ Set Environment Variables`, ""); + log(`☑️ Set Environment Variables`, ""); let { Settings, Caches, Configs } = getStorage(name, platforms, database); /***************** Settings *****************/ if (!Array.isArray(Settings?.Types)) Settings.Types = (Settings.Types) ? [Settings.Types] : []; // 只有一个选项时,无逗号分隔 - console.log(`✅ Set Environment Variables, Settings: ${typeof Settings}, Settings内容: ${JSON.stringify(Settings)}`, ""); + log(`✅ Set Environment Variables, Settings: ${typeof Settings}, Settings内容: ${JSON.stringify(Settings)}`, ""); /***************** Caches *****************/ if (typeof Caches?.Playlists !== "object" || Array.isArray(Caches?.Playlists)) Caches.Playlists = {}; // 创建Playlists缓存 Caches.Playlists.Master = new Map(JSON.parse(Caches?.Playlists?.Master || "[]")); // Strings转Array转Map Caches.Playlists.Subtitle = new Map(JSON.parse(Caches?.Playlists?.Subtitle || "[]")); // Strings转Array转Map if (typeof Caches?.Subtitles !== "object") Caches.Subtitles = new Map(JSON.parse(Caches?.Subtitles || "[]")); // Strings转Array转Map - //console.log(`✅ Set Environment Variables, Caches: ${typeof Caches}, Caches内容: ${JSON.stringify(Caches)}`, ""); + //log(`✅ Set Environment Variables, Caches: ${typeof Caches}, Caches内容: ${JSON.stringify(Caches)}`, ""); /***************** Configs *****************/ return { Settings, Caches, Configs }; }; diff --git a/src/utils b/src/utils new file mode 160000 index 0000000..40e91e8 --- /dev/null +++ b/src/utils @@ -0,0 +1 @@ +Subproject commit 40e91e80011968370ba7ef400ff768dabf5cf583