UNPKG

@asunajs/caiyun

Version:

移动云盘签到

1,203 lines (1,177 loc) 42.6 kB
#!/usr/bin/env node import{createRequire}from'module';if(!globalThis.require)globalThis.require=createRequire(import.meta.url); import { CAIYUN_APP_VERSION, CAIYUN_BASE_UA, CAIYUN_CLIENT, CAIYUN_NET_TYPE, checkExchange, createApi, createGardenApi, createLogger, createTime, exchangeApi, formatTime, getAuthInfo, getCloudDayList, getExchangeList, getJwtToken, getNewAuth, getReceivePrizeDetails, getSmsVerCode, hidePhone, isString, isUndefined, isWps, md5, once, randomHex, randomNumber, receiveCloudDayGift, setStoreArray, sleep, uploadFileRequest, verifyCloudDay, waitToNextHour } from "./chunk-XDPOMWMM.js"; import { init_esm_shims } from "./chunk-ZWSCLKPB.js"; // cli2.ts init_esm_shims(); import { rewriteConfigSync as rewriteConfigSync2 } from "@asunajs/conf"; import { defineCommand, runMain } from "citty"; import { dirname as dirname2, resolve as resolve3 } from "node:path"; import { fileURLToPath } from "node:url"; // index.ts init_esm_shims(); import { rewriteConfigSync } from "@asunajs/conf"; // service/utils.ts init_esm_shims(); // ../../core/caiyun/options.ts init_esm_shims(); var defuConfig = { shake: { enable: !0, num: 15, delay: 2 }, garden: { enable: !1, inviteCodes: [], 开启果园助力: !1 }, aiRedPack: { enable: !0 }, backupWaitTime: 20, tasks: { skipTasks: [], 每月上传任务单日数量: 5 }, catalog: "00019700101000000001", cloudPhoneRedpack: { enable: !1 }, 是否打印今日云朵: !0, 剩余多少天刷新token: 10, 微信抽奖: { 次数: 1, 间隔: 500 }, 云朵大作战: { 目标排名: 500, 开启兑换: !1, 邀请用户: [], 游戏时间: 300 }, 文件获取方式: 1 }; // ../../packages/unstorage/index.ts init_esm_shims(); import { unlinkSync, writeFileSync } from "node:fs"; // ../../node_modules/.pnpm/unstorage@1.15.0_db0@0.3.1_ioredis@5.6.0/node_modules/unstorage/dist/index.mjs init_esm_shims(); // ../../node_modules/.pnpm/destr@2.0.5/node_modules/destr/dist/index.mjs init_esm_shims(); var suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/, suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/, JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/; function jsonParseTransform(key, value) { if (key === "__proto__" || key === "constructor" && value && typeof value == "object" && "prototype" in value) { warnKeyDropped(key); return; } return value; } function warnKeyDropped(key) { console.warn(`[destr] Dropping "${key}" key to prevent prototype pollution.`); } function destr(value, options = {}) { if (typeof value != "string") return value; if (value[0] === '"' && value[value.length - 1] === '"' && value.indexOf("\\") === -1) return value.slice(1, -1); let _value = value.trim(); if (_value.length <= 9) switch (_value.toLowerCase()) { case "true": return !0; case "false": return !1; case "undefined": return; case "null": return null; case "nan": return Number.NaN; case "infinity": return Number.POSITIVE_INFINITY; case "-infinity": return Number.NEGATIVE_INFINITY; } if (!JsonSigRx.test(value)) { if (options.strict) throw new SyntaxError("[destr] Invalid JSON"); return value; } try { if (suspectProtoRx.test(value) || suspectConstructorRx.test(value)) { if (options.strict) throw new Error("[destr] Possible prototype pollution"); return JSON.parse(value, jsonParseTransform); } return JSON.parse(value); } catch (error) { if (options.strict) throw error; return value; } } // ../../node_modules/.pnpm/unstorage@1.15.0_db0@0.3.1_ioredis@5.6.0/node_modules/unstorage/dist/shared/unstorage.mNKHTF5Y.mjs init_esm_shims(); function wrapToPromise(value) { return !value || typeof value.then != "function" ? Promise.resolve(value) : value; } function asyncCall(function_, ...arguments_) { try { return wrapToPromise(function_(...arguments_)); } catch (error) { return Promise.reject(error); } } function isPrimitive(value) { let type = typeof value; return value === null || type !== "object" && type !== "function"; } function isPureObject(value) { let proto = Object.getPrototypeOf(value); return !proto || proto.isPrototypeOf(Object); } function stringify(value) { if (isPrimitive(value)) return String(value); if (isPureObject(value) || Array.isArray(value)) return JSON.stringify(value); if (typeof value.toJSON == "function") return stringify(value.toJSON()); throw new Error("[unstorage] Cannot stringify value!"); } var BASE64_PREFIX = "base64:"; function serializeRaw(value) { return typeof value == "string" ? value : BASE64_PREFIX + base64Encode(value); } function deserializeRaw(value) { return typeof value != "string" || !value.startsWith(BASE64_PREFIX) ? value : base64Decode(value.slice(BASE64_PREFIX.length)); } function base64Decode(input) { return globalThis.Buffer ? Buffer.from(input, "base64") : Uint8Array.from( globalThis.atob(input), (c) => c.codePointAt(0) ); } function base64Encode(input) { return globalThis.Buffer ? Buffer.from(input).toString("base64") : globalThis.btoa(String.fromCodePoint(...input)); } var storageKeyProperties = [ "has", "hasItem", "get", "getItem", "getItemRaw", "set", "setItem", "setItemRaw", "del", "remove", "removeItem", "getMeta", "setMeta", "removeMeta", "getKeys", "clear", "mount", "unmount" ]; function prefixStorage(storage2, base) { if (base = normalizeBaseKey(base), !base) return storage2; let nsStorage = { ...storage2 }; for (let property of storageKeyProperties) nsStorage[property] = (key = "", ...args) => ( // @ts-ignore storage2[property](base + key, ...args) ); return nsStorage.getKeys = (key = "", ...arguments_) => storage2.getKeys(base + key, ...arguments_).then((keys) => keys.map((key2) => key2.slice(base.length))), nsStorage; } function normalizeKey(key) { return key && key.split("?")[0]?.replace(/[/\\]/g, ":").replace(/:+/g, ":").replace(/^:|:$/g, "") || ""; } function joinKeys(...keys) { return normalizeKey(keys.join(":")); } function normalizeBaseKey(base) { return base = normalizeKey(base), base ? base + ":" : ""; } function filterKeyByDepth(key, depth) { if (depth === void 0) return !0; let substrCount = 0, index = key.indexOf(":"); for (; index > -1; ) substrCount++, index = key.indexOf(":", index + 1); return substrCount <= depth; } function filterKeyByBase(key, base) { return base ? key.startsWith(base) && key[key.length - 1] !== "$" : key[key.length - 1] !== "$"; } // ../../node_modules/.pnpm/unstorage@1.15.0_db0@0.3.1_ioredis@5.6.0/node_modules/unstorage/dist/index.mjs var DRIVER_NAME = "memory", memory = () => { let data = /* @__PURE__ */ new Map(); return { name: DRIVER_NAME, getInstance: () => data, hasItem(key) { return data.has(key); }, getItem(key) { return data.get(key) ?? null; }, getItemRaw(key) { return data.get(key) ?? null; }, setItem(key, value) { data.set(key, value); }, setItemRaw(key, value) { data.set(key, value); }, removeItem(key) { data.delete(key); }, getKeys() { return [...data.keys()]; }, clear() { data.clear(); }, dispose() { data.clear(); } }; }; function createStorage(options = {}) { let context = { mounts: { "": options.driver || memory() }, mountpoints: [""], watching: !1, watchListeners: [], unwatch: {} }, getMount = (key) => { for (let base of context.mountpoints) if (key.startsWith(base)) return { base, relativeKey: key.slice(base.length), driver: context.mounts[base] }; return { base: "", relativeKey: key, driver: context.mounts[""] }; }, getMounts = (base, includeParent) => context.mountpoints.filter( (mountpoint) => mountpoint.startsWith(base) || includeParent && base.startsWith(mountpoint) ).map((mountpoint) => ({ relativeBase: base.length > mountpoint.length ? base.slice(mountpoint.length) : void 0, mountpoint, driver: context.mounts[mountpoint] })), onChange = (event, key) => { if (context.watching) { key = normalizeKey(key); for (let listener of context.watchListeners) listener(event, key); } }, startWatch = async () => { if (!context.watching) { context.watching = !0; for (let mountpoint in context.mounts) context.unwatch[mountpoint] = await watch( context.mounts[mountpoint], onChange, mountpoint ); } }, stopWatch = async () => { if (context.watching) { for (let mountpoint in context.unwatch) await context.unwatch[mountpoint](); context.unwatch = {}, context.watching = !1; } }, runBatch = (items, commonOptions, cb) => { let batches = /* @__PURE__ */ new Map(), getBatch = (mount) => { let batch = batches.get(mount.base); return batch || (batch = { driver: mount.driver, base: mount.base, items: [] }, batches.set(mount.base, batch)), batch; }; for (let item of items) { let isStringItem = typeof item == "string", key = normalizeKey(isStringItem ? item : item.key), value = isStringItem ? void 0 : item.value, options2 = isStringItem || !item.options ? commonOptions : { ...commonOptions, ...item.options }, mount = getMount(key); getBatch(mount).items.push({ key, value, relativeKey: mount.relativeKey, options: options2 }); } return Promise.all([...batches.values()].map((batch) => cb(batch))).then( (r) => r.flat() ); }, storage2 = { // Item hasItem(key, opts = {}) { key = normalizeKey(key); let { relativeKey, driver } = getMount(key); return asyncCall(driver.hasItem, relativeKey, opts); }, getItem(key, opts = {}) { key = normalizeKey(key); let { relativeKey, driver } = getMount(key); return asyncCall(driver.getItem, relativeKey, opts).then( (value) => destr(value) ); }, getItems(items, commonOptions = {}) { return runBatch(items, commonOptions, (batch) => batch.driver.getItems ? asyncCall( batch.driver.getItems, batch.items.map((item) => ({ key: item.relativeKey, options: item.options })), commonOptions ).then( (r) => r.map((item) => ({ key: joinKeys(batch.base, item.key), value: destr(item.value) })) ) : Promise.all( batch.items.map((item) => asyncCall( batch.driver.getItem, item.relativeKey, item.options ).then((value) => ({ key: item.key, value: destr(value) }))) )); }, getItemRaw(key, opts = {}) { key = normalizeKey(key); let { relativeKey, driver } = getMount(key); return driver.getItemRaw ? asyncCall(driver.getItemRaw, relativeKey, opts) : asyncCall(driver.getItem, relativeKey, opts).then( (value) => deserializeRaw(value) ); }, async setItem(key, value, opts = {}) { if (value === void 0) return storage2.removeItem(key); key = normalizeKey(key); let { relativeKey, driver } = getMount(key); driver.setItem && (await asyncCall(driver.setItem, relativeKey, stringify(value), opts), driver.watch || onChange("update", key)); }, async setItems(items, commonOptions) { await runBatch(items, commonOptions, async (batch) => { if (batch.driver.setItems) return asyncCall( batch.driver.setItems, batch.items.map((item) => ({ key: item.relativeKey, value: stringify(item.value), options: item.options })), commonOptions ); batch.driver.setItem && await Promise.all( batch.items.map((item) => asyncCall( batch.driver.setItem, item.relativeKey, stringify(item.value), item.options )) ); }); }, async setItemRaw(key, value, opts = {}) { if (value === void 0) return storage2.removeItem(key, opts); key = normalizeKey(key); let { relativeKey, driver } = getMount(key); if (driver.setItemRaw) await asyncCall(driver.setItemRaw, relativeKey, value, opts); else if (driver.setItem) await asyncCall(driver.setItem, relativeKey, serializeRaw(value), opts); else return; driver.watch || onChange("update", key); }, async removeItem(key, opts = {}) { typeof opts == "boolean" && (opts = { removeMeta: opts }), key = normalizeKey(key); let { relativeKey, driver } = getMount(key); driver.removeItem && (await asyncCall(driver.removeItem, relativeKey, opts), (opts.removeMeta || opts.removeMata) && await asyncCall(driver.removeItem, relativeKey + "$", opts), driver.watch || onChange("remove", key)); }, // Meta async getMeta(key, opts = {}) { typeof opts == "boolean" && (opts = { nativeOnly: opts }), key = normalizeKey(key); let { relativeKey, driver } = getMount(key), meta = /* @__PURE__ */ Object.create(null); if (driver.getMeta && Object.assign(meta, await asyncCall(driver.getMeta, relativeKey, opts)), !opts.nativeOnly) { let value = await asyncCall( driver.getItem, relativeKey + "$", opts ).then((value_) => destr(value_)); value && typeof value == "object" && (typeof value.atime == "string" && (value.atime = new Date(value.atime)), typeof value.mtime == "string" && (value.mtime = new Date(value.mtime)), Object.assign(meta, value)); } return meta; }, setMeta(key, value, opts = {}) { return this.setItem(key + "$", value, opts); }, removeMeta(key, opts = {}) { return this.removeItem(key + "$", opts); }, // Keys async getKeys(base, opts = {}) { base = normalizeBaseKey(base); let mounts = getMounts(base, !0), maskedMounts = [], allKeys = [], allMountsSupportMaxDepth = !0; for (let mount of mounts) { mount.driver.flags?.maxDepth || (allMountsSupportMaxDepth = !1); let rawKeys = await asyncCall( mount.driver.getKeys, mount.relativeBase, opts ); for (let key of rawKeys) { let fullKey = mount.mountpoint + normalizeKey(key); maskedMounts.some((p) => fullKey.startsWith(p)) || allKeys.push(fullKey); } maskedMounts = [ mount.mountpoint, ...maskedMounts.filter((p) => !p.startsWith(mount.mountpoint)) ]; } let shouldFilterByDepth = opts.maxDepth !== void 0 && !allMountsSupportMaxDepth; return allKeys.filter( (key) => (!shouldFilterByDepth || filterKeyByDepth(key, opts.maxDepth)) && filterKeyByBase(key, base) ); }, // Utils async clear(base, opts = {}) { base = normalizeBaseKey(base), await Promise.all( getMounts(base, !1).map(async (m) => { if (m.driver.clear) return asyncCall(m.driver.clear, m.relativeBase, opts); if (m.driver.removeItem) { let keys = await m.driver.getKeys(m.relativeBase || "", opts); return Promise.all( keys.map((key) => m.driver.removeItem(key, opts)) ); } }) ); }, async dispose() { await Promise.all( Object.values(context.mounts).map((driver) => dispose(driver)) ); }, async watch(callback) { return await startWatch(), context.watchListeners.push(callback), async () => { context.watchListeners = context.watchListeners.filter( (listener) => listener !== callback ), context.watchListeners.length === 0 && await stopWatch(); }; }, async unwatch() { context.watchListeners = [], await stopWatch(); }, // Mount mount(base, driver) { if (base = normalizeBaseKey(base), base && context.mounts[base]) throw new Error(`already mounted at ${base}`); return base && (context.mountpoints.push(base), context.mountpoints.sort((a, b) => b.length - a.length)), context.mounts[base] = driver, context.watching && Promise.resolve(watch(driver, onChange, base)).then((unwatcher) => { context.unwatch[base] = unwatcher; }).catch(console.error), storage2; }, async unmount(base, _dispose = !0) { base = normalizeBaseKey(base), !(!base || !context.mounts[base]) && (context.watching && base in context.unwatch && (context.unwatch[base]?.(), delete context.unwatch[base]), _dispose && await dispose(context.mounts[base]), context.mountpoints = context.mountpoints.filter((key) => key !== base), delete context.mounts[base]); }, getMount(key = "") { key = normalizeKey(key) + ":"; let m = getMount(key); return { driver: m.driver, base: m.base }; }, getMounts(base = "", opts = {}) { return base = normalizeKey(base), getMounts(base, opts.parents).map((m) => ({ driver: m.driver, base: m.mountpoint })); }, // Aliases keys: (base, opts = {}) => storage2.getKeys(base, opts), get: (key, opts = {}) => storage2.getItem(key, opts), set: (key, value, opts = {}) => storage2.setItem(key, value, opts), has: (key, opts = {}) => storage2.hasItem(key, opts), del: (key, opts = {}) => storage2.removeItem(key, opts), remove: (key, opts = {}) => storage2.removeItem(key, opts) }; return storage2; } function watch(driver, onChange, base) { return driver.watch ? driver.watch((event, key) => onChange(event, base + key)) : () => { }; } async function dispose(driver) { typeof driver.dispose == "function" && await asyncCall(driver.dispose); } // ../../node_modules/.pnpm/unstorage@1.15.0_db0@0.3.1_ioredis@5.6.0/node_modules/unstorage/drivers/fs-lite.mjs init_esm_shims(); import { existsSync as existsSync2, promises as fsp } from "node:fs"; import { resolve as resolve2, join } from "node:path"; // ../../node_modules/.pnpm/unstorage@1.15.0_db0@0.3.1_ioredis@5.6.0/node_modules/unstorage/drivers/utils/index.mjs init_esm_shims(); function createError(driver, message, opts) { let err = new Error(`[unstorage] [${driver}] ${message}`, opts); return Error.captureStackTrace && Error.captureStackTrace(err, createError), err; } function createRequiredError(driver, name) { return Array.isArray(name) ? createError( driver, `Missing some of the required options ${name.map((n) => "`" + n + "`").join(", ")}` ) : createError(driver, `Missing required option \`${name}\`.`); } // ../../node_modules/.pnpm/unstorage@1.15.0_db0@0.3.1_ioredis@5.6.0/node_modules/unstorage/drivers/utils/node-fs.mjs init_esm_shims(); import { existsSync, promises as fsPromises } from "node:fs"; import { resolve, dirname } from "node:path"; function ignoreNotfound(err) { return err.code === "ENOENT" || err.code === "EISDIR" ? null : err; } function ignoreExists(err) { return err.code === "EEXIST" ? null : err; } async function writeFile(path, data, encoding) { return await ensuredir(dirname(path)), fsPromises.writeFile(path, data, encoding); } function readFile(path, encoding) { return fsPromises.readFile(path, encoding).catch(ignoreNotfound); } function unlink(path) { return fsPromises.unlink(path).catch(ignoreNotfound); } function readdir(dir) { return fsPromises.readdir(dir, { withFileTypes: !0 }).catch(ignoreNotfound).then((r) => r || []); } async function ensuredir(dir) { existsSync(dir) || (await ensuredir(dirname(dir)).catch(ignoreExists), await fsPromises.mkdir(dir).catch(ignoreExists)); } async function readdirRecursive(dir, ignore, maxDepth) { if (ignore && ignore(dir)) return []; let entries = await readdir(dir), files = []; return await Promise.all( entries.map(async (entry) => { let entryPath = resolve(dir, entry.name); if (entry.isDirectory()) { if (maxDepth === void 0 || maxDepth > 0) { let dirFiles = await readdirRecursive( entryPath, ignore, maxDepth === void 0 ? void 0 : maxDepth - 1 ); files.push(...dirFiles.map((f) => entry.name + "/" + f)); } } else ignore && ignore(entry.name) || files.push(entry.name); }) ), files; } async function rmRecursive(dir) { let entries = await readdir(dir); await Promise.all( entries.map((entry) => { let entryPath = resolve(dir, entry.name); return entry.isDirectory() ? rmRecursive(entryPath).then(() => fsPromises.rmdir(entryPath)) : fsPromises.unlink(entryPath); }) ); } // ../../node_modules/.pnpm/unstorage@1.15.0_db0@0.3.1_ioredis@5.6.0/node_modules/unstorage/drivers/fs-lite.mjs var PATH_TRAVERSE_RE = /\.\.:|\.\.$/, DRIVER_NAME2 = "fs-lite", fs_lite_default = (opts = {}) => { if (!opts.base) throw createRequiredError(DRIVER_NAME2, "base"); opts.base = resolve2(opts.base); let r = (key) => { if (PATH_TRAVERSE_RE.test(key)) throw createError( DRIVER_NAME2, `Invalid key: ${JSON.stringify(key)}. It should not contain .. segments` ); return join(opts.base, key.replace(/:/g, "/")); }; return { name: DRIVER_NAME2, options: opts, flags: { maxDepth: !0 }, hasItem(key) { return existsSync2(r(key)); }, getItem(key) { return readFile(r(key), "utf8"); }, getItemRaw(key) { return readFile(r(key)); }, async getMeta(key) { let { atime, mtime, size, birthtime, ctime } = await fsp.stat(r(key)).catch(() => ({})); return { atime, mtime, size, birthtime, ctime }; }, setItem(key, value) { if (!opts.readOnly) return writeFile(r(key), value, "utf8"); }, setItemRaw(key, value) { if (!opts.readOnly) return writeFile(r(key), value); }, removeItem(key) { if (!opts.readOnly) return unlink(r(key)); }, getKeys(_base, topts) { return readdirRecursive(r("."), opts.ignore, topts?.maxDepth); }, async clear() { opts.readOnly || opts.noClear || await rmRecursive(r(".")); } }; }; // ../../node_modules/.pnpm/unstorage@1.15.0_db0@0.3.1_ioredis@5.6.0/node_modules/unstorage/drivers/memory.mjs init_esm_shims(); var DRIVER_NAME3 = "memory", memory_default = () => { let data = /* @__PURE__ */ new Map(); return { name: DRIVER_NAME3, getInstance: () => data, hasItem(key) { return data.has(key); }, getItem(key) { return data.get(key) ?? null; }, getItemRaw(key) { return data.get(key) ?? null; }, setItem(key, value) { data.set(key, value); }, setItemRaw(key, value) { data.set(key, value); }, removeItem(key) { data.delete(key); }, getKeys() { return [...data.keys()]; }, clear() { data.clear(); }, dispose() { data.clear(); } }; }; // ../../packages/unstorage/index.ts function getStorage(prefix) { let storage2 = createStorage({ driver: canWrite() ? fs_lite_default({ base: "./.temp/asign" }) : memory_default() }); return prefixStorage(storage2, prefix); } function canWrite() { try { let file = "asign_file_write.txt"; return writeFileSync(file, file), unlinkSync(file), !0; } catch { return !1; } } // service/utils.ts import { loadConfig as _lc } from "@asunajs/conf"; import { createRequest } from "@asunajs/http"; import { sendNotify } from "@asunajs/push"; import { defu } from "defu"; // service/upload-task.ts init_esm_shims(); import { got } from "@asunajs/http"; import { Buffer as Buffer2 } from "node:buffer"; import { randomBytes } from "node:crypto"; function getRandomFile($) { let randomBuffer = randomBytes(16); return { randomBuffer, fileMd5: $.node.myMD5(randomBuffer.toString("hex")), fileSize: 209715216 }; } async function _upload($) { let file = getRandomFile($), uploadInfo = { digest: file.fileMd5, contentSize: file.fileSize, manualRename: 2, ext: ".mp4", createTime: createTime() }; $.logger.debug((/* @__PURE__ */ new Date()).toLocaleString(), JSON.stringify(uploadInfo)), await uploadFile($, $.config.catalog, uploadInfo, file.randomBuffer) && $.logger.debug("上传成功"); } async function uploadTask($, progressNum) { if (isWps()) { $.logger.debug("当前环境为WPS,不支持上传文件"); return; } $.logger.debug("已经上传", progressNum, "字节"); let needM = 1025 - Math.floor(progressNum / 1024 / 1024); $.logger.debug("需要上传", needM, "MB"); for (let i = 0; i < needM; i += 200) await _upload($), needM - 200 > 0 && await $.sleep(3e3); } async function uploadFile($, parentCatalogID, { ext = ".png", digest = randomHex(32).toUpperCase(), contentSize = randomNumber(1, 1e3), manualRename = 2, contentName = "asign-" + randomHex(4) + ext, createTime: createTime2 = createTime() } = {}, randomBuffer) { try { $.logger.debug("开始上传文件", digest); let { redirectionUrl, uploadTaskID, contentID } = await uploadFileRequest($, parentCatalogID, { ext, digest, contentSize, manualRename, contentName, createTime: createTime2 }, !0); if (!redirectionUrl || !randomBuffer) return !!contentID; $.logger.debug("别着急,文件上传中。。。", contentID); let ok = await uploadFileApi(redirectionUrl.replace(/&amp;/g, "&"), uploadTaskID, randomBuffer); return ok && contentID && setStoreArray($.store, "files", [contentID]), ok; } catch (error) { $.logger.error("上传文件异常", error); } return !1; } async function uploadFileApi(url, id, randomBuffer) { let stream = got.stream.post(url, { headers: { UploadtaskID: id + "-", "x-huawei-uploadSrc": "1", "Content-Type": "application/octet-stream", "x-huawei-channelSrc": "10000023", "User-Agent": "okhttp/4.12.0", contentSize: "209715216", Range: "bytes=0-209715215" }, body: randomFile(randomBuffer) }); return stream.resume(), new Promise((resolve4, reject) => { stream.on("error", reject), stream.on("response", async (res) => { resolve4(res.ok); }); }); } function* randomFile(randomBuffer) { for (let i = 0; i < 209715200; i += 65536) yield Buffer2.alloc(65536); yield randomBuffer; } // utils/ai-userid-aes.ts init_esm_shims(); import { Buffer as Buffer3 } from "node:buffer"; import { createCipheriv, randomBytes as randomBytes2 } from "node:crypto"; function aesEecrypt(textUtf8, iv) { let decipher = createCipheriv("aes-128-cbc", Buffer3.from("xuL97!x7GGxG%8V4", "utf-8"), iv); return Buffer3.concat([decipher.update(textUtf8, "utf-8"), decipher.final()]); } function encryptAiUserId(userId) { let iv = randomBytes2(16); return Buffer3.from(Buffer3.concat([iv, aesEecrypt(userId, iv)]).toString("base64"), "utf-8").toString("base64"); } // utils/md5.ts init_esm_shims(); import { Buffer as Buffer4 } from "node:buffer"; function safeAdd(x, y) { var lsw = (x & 65535) + (y & 65535), msw = (x >> 16) + (y >> 16) + (lsw >> 16); return msw << 16 | lsw & 65535; } function bitRotateLeft(num, cnt) { return num << cnt | num >>> 32 - cnt; } function md5cmn(q, a, b, x, s, t) { return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); } function md5ff(a, b, c, d, x, s, t) { return md5cmn(b & c | ~b & d, a, b, x, s, t); } function md5gg(a, b, c, d, x, s, t) { return md5cmn(b & d | c & ~d, a, b, x, s, t); } function md5hh(a, b, c, d, x, s, t) { return md5cmn(b ^ c ^ d, a, b, x, s, t); } function md5ii(a, b, c, d, x, s, t) { return md5cmn(c ^ (b | ~d), a, b, x, s, t); } function _binlMD5_for(x, a, b, c, d) { let olda, oldb, oldc, oldd, i; for (i = 0; i < x.length; i += 16) olda = a, oldb = b, oldc = c, oldd = d, a = md5ff(a, b, c, d, x[i], 7, -680876936), d = md5ff(d, a, b, c, x[i + 1], 12, -389564586), c = md5ff(c, d, a, b, x[i + 2], 17, 606105819), b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330), a = md5ff(a, b, c, d, x[i + 4], 7, -176418897), d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426), c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341), b = md5ff(b, c, d, a, x[i + 7], 22, -45705983), a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416), d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417), c = md5ff(c, d, a, b, x[i + 10], 17, -42063), b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162), a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682), d = md5ff(d, a, b, c, x[i + 13], 12, -40341101), c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290), b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329), a = md5gg(a, b, c, d, x[i + 1], 5, -165796510), d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632), c = md5gg(c, d, a, b, x[i + 11], 14, 643717713), b = md5gg(b, c, d, a, x[i], 20, -373897302), a = md5gg(a, b, c, d, x[i + 5], 5, -701558691), d = md5gg(d, a, b, c, x[i + 10], 9, 38016083), c = md5gg(c, d, a, b, x[i + 15], 14, -660478335), b = md5gg(b, c, d, a, x[i + 4], 20, -405537848), a = md5gg(a, b, c, d, x[i + 9], 5, 568446438), d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690), c = md5gg(c, d, a, b, x[i + 3], 14, -187363961), b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501), a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467), d = md5gg(d, a, b, c, x[i + 2], 9, -51403784), c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473), b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734), a = md5hh(a, b, c, d, x[i + 5], 4, -378558), d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463), c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562), b = md5hh(b, c, d, a, x[i + 14], 23, -35309556), a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060), d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353), c = md5hh(c, d, a, b, x[i + 7], 16, -155497632), b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640), a = md5hh(a, b, c, d, x[i + 13], 4, 681279174), d = md5hh(d, a, b, c, x[i], 11, -358537222), c = md5hh(c, d, a, b, x[i + 3], 16, -722521979), b = md5hh(b, c, d, a, x[i + 6], 23, 76029189), a = md5hh(a, b, c, d, x[i + 9], 4, -640364487), d = md5hh(d, a, b, c, x[i + 12], 11, -421815835), c = md5hh(c, d, a, b, x[i + 15], 16, 530742520), b = md5hh(b, c, d, a, x[i + 2], 23, -995338651), a = md5ii(a, b, c, d, x[i], 6, -198630844), d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415), c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905), b = md5ii(b, c, d, a, x[i + 5], 21, -57434055), a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571), d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606), c = md5ii(c, d, a, b, x[i + 10], 15, -1051523), b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799), a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359), d = md5ii(d, a, b, c, x[i + 15], 10, -30611744), c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380), b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649), a = md5ii(a, b, c, d, x[i + 4], 6, -145523070), d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379), c = md5ii(c, d, a, b, x[i + 2], 15, 718787259), b = md5ii(b, c, d, a, x[i + 9], 21, -343485551), a = safeAdd(a, olda), b = safeAdd(b, oldb), c = safeAdd(c, oldc), d = safeAdd(d, oldd); return [a, b, c, d]; } function binlMD5(x, len, padding = !0, initialState = { a: 1732584193, b: -271733879, c: -1732584194, d: 271733878 }, fixLen = 0) { return padding && (x[len >> 5] |= 128 << len % 32, x[(len + 64 >>> 9 << 4) + 14] = len + fixLen), _binlMD5_for(x, initialState.a, initialState.b, initialState.c, initialState.d); } function incrementallyComputeMD5(s, fixLen = 0, initialState = { a: 1732584193, b: -271733879, c: -1732584194, d: 271733878 }) { return rstr2hex(binl2rstr(binlMD5(rstr2binl(decodeURIComponent(s)), s.length * 8, !0, initialState, fixLen))); } function binl2rstr(input) { let output = "", length32 = input.length * 32; for (let i = 0; i < length32; i += 8) output += String.fromCharCode(input[i >> 5] >>> i % 32 & 255); return output; } function rstr2hex(input) { var hexTab = "0123456789abcdef", output = "", x, i; for (i = 0; i < input.length; i += 1) x = input.charCodeAt(i), output += hexTab.charAt(x >>> 4 & 15) + hexTab.charAt(x & 15); return output; } function rstr2binl(input) { let buffer = Buffer4.from(input, "binary"), outputLength = Math.ceil(buffer.length / 4), output = new Uint32Array(outputLength), outputView = new Uint8Array(output.buffer); return buffer.copy(outputView, 0, 0, buffer.length), Array.from(output); } function myMD5(s) { return incrementallyComputeMD5(s, 3355443200, { a: -1235010310, b: -1633014442, c: 1919210400, d: -1138002915 }); } // service/utils.ts async function init(userConfig, { logger: logger2, localStorage, jwtToken }) { let config = initConfig(userConfig); if (!config.phone) return logger2.error("auth 格式解析错误,请查看是否填写正确的 auth"), {}; if (config.phone.length !== 11 || !config.phone.startsWith("1")) return logger2.info("auth 格式解析错误,请查看是否填写正确的 auth"), {}; let DATA = { baseUA: CAIYUN_BASE_UA, mailUaEnd: `(139PE_WebView_Android_${CAIYUN_APP_VERSION}_mcloud139)`, mailRequested: "cn.cj.pe", mcloudRequested: "com.chinamobile.mcloud" }, http = createRequest({ hooks: { beforeRequest: [ (options) => { ["caiyun.feixin.10086.cn", "mrp.mcloud.139.com"].includes(options.url.hostname) ? (jwtToken && (options.headers.jwttoken = jwtToken), options.headers.authorization = "Basic " + config.auth) : options.headers.authorization = config.auth; } ] }, headers: { "user-agent": DATA.baseUA, "x-requested-with": DATA.mcloudRequested, charset: "utf-8", "content-type": "application/json;charset=UTF-8", "x-yun-client-info": CAIYUN_CLIENT, "x-DeviceInfo": CAIYUN_CLIENT, "x-NetType": CAIYUN_NET_TYPE }, retry: { limit: 3, methods: ["POST", "GET", "PATCH", "DELETE", "OPTIONS", "TRACE"] } }), $ = { api: createApi(http), config, gardenApi: createGardenApi(http), logger: logger2, DATA, sleep, node: { uploadTask, myMD5, encryptAiUserId }, md5, store: {}, localStorage: localStorage || getStorage("caiyun-" + config.phone), http }; return logger2.info("=============="), printNickName($), printExpireTime($, $.config.expire), jwtToken ||= await getJwtToken($), { $, logger: logger2, jwtToken }; } function initConfig(userConfig) { let config = defu(userConfig, defuConfig); return { ...config, ...getAuthInfo(config.auth) }; } async function loadConfig(inputPath) { let r = await _lc(inputPath); if (!r.config) throw new Error("配置文件为空"); return { config: r.config.caiyun, message: r.config.message, path: r.path }; } function printNickName({ config, logger: logger2 }) { logger2.info(`登录账号【${config.nickname || hidePhone(config.phone)}】`); } function printExpireTime({ logger: logger2 }, expire) { logger2.info("登录过期时间", formatTime(expire)); } // service/index.ts init_esm_shims(); // service/exchange.ts init_esm_shims(); import { createRequest as createRequest2 } from "@asunajs/http"; import { sendNotify as sendNotify2 } from "@asunajs/push"; // service/hc1t.ts init_esm_shims(); var storage = getStorage("caiyun-hc1t"); // index.ts async function getConfig(inputPath) { return isUndefined(inputPath) || isString(inputPath) ? await loadConfig(inputPath) : inputPath; } // cli2.ts var logger = await createLogger(), login = async (inputPath, index) => { let { config, path } = await getAuth(inputPath, index), { $, jwtToken } = await init(config, { logger }); if (!jwtToken) throw new Error("获取 jwtToken 失败"); return { $, path }; }, refreshAuth = async ($, path, index) => { if (!await logger.prompt("是否确认刷新 auth?(Y/n)", { type: "confirm" })) return; let auth = await getNewAuth($); auth && (rewriteConfigSync2(path, ["caiyun", +index, "auth"], auth), logger.success("刷新 auth 成功", auth), logger.success("成功写入文件", path, "文件")); }, setup = once(async (args) => { let { $, path } = await login(args.config, args.index); return args["refresh-auth"] && await refreshAuth($, path, args.index), { $, path }; }), onceInit = once(init), operationArgs = { config: { type: "string", alias: "c", description: "配置文件路径" }, index: { type: "string", alias: "i", description: "指定要操作的账号", default: "0", valueHint: "默认 0,即第一个账号" }, "refresh-auth": { type: "boolean", alias: "r", description: "是否刷新 auth" } }, vipDay = defineCommand({ args: { ...operationArgs }, async run({ args }) { logger.debug("vipDay", args); } }), main = defineCommand({ meta: { name: "caiyun", version: "1.0.0", description: "caiyun 命令行工具" }, args: { ...operationArgs, check: { type: "boolean", description: "检查 auth 有效性" } }, subCommands: { vipDay }, async run({ args, rawArgs }) { if (rawArgs.length === 0) { await interactive(); return; } args.check && logger.fail("暂不支持检测"), await setup(args); } }); runMain(main); async function getAuth(inputPath, index) { let { config, path } = await getConfig(inputPath && resolve3(dirname2(fileURLToPath(import.meta.url)), inputPath)), _config = config[Number(index)]; if (!_config) throw new Error("账号不存在 请确认账号索引是否正确"); return { config: { ..._config, ...getAuthInfo(_config.auth) }, path }; } async function interactive() { let { config, path } = await getConfig(); logger.info("查看", path), logger.success("成功找到", config.length, "个配置,请选择需要操作的内容"); let configMap = config.map((c) => { try { return { ...c, ...getAuthInfo(c.auth) }; } catch { } }), index = +await logger.prompt("请选择要操作的账号", { type: "select", options: configMap.map((conf, i) => !conf || !conf.phone ? { label: `无效账号 ${i}`, value: String(i) } : { label: hidePhone(conf.phone) + ` (${formatTime(conf.expire)}) ` + (conf.nickname ? `【${conf.nickname}】` : ""), value: String(i), hint: String(i) }) }), ACTION = { CHECK: "check", REFRESH: "refresh", LOGIN: "login", CLOUD_DAY: "cloudday", EXCHANGE: "exchange" }; switch (await logger.prompt("请选择你的操作", { type: "select", options: [ { label: "检查账号登录是否失效", value: ACTION.CHECK }, { label: "刷新 authorization token", value: ACTION.REFRESH }, { label: "移动云盘会员日宠爱礼", value: ACTION.CLOUD_DAY }, { label: "云朵兑换奖励", value: ACTION.EXCHANGE } ] })) { case ACTION.CHECK: { let { jwtToken } = await onceInit(configMap[index], { logger }); jwtToken ? logger.success("账号有效") : logger.fail("账号无效"); return; } case ACTION.REFRESH: { let { $ } = await onceInit(configMap[index], { logger }); await refreshAuth($, path, index); return; } case ACTION.LOGIN: { logger.fail("暂不支持登录"); return; } case ACTION.CLOUD_DAY: { await cloudDay(configMap[index]); return; } case ACTION.EXCHANGE: { await exchange(configMap[index]); return; } default: return; } } async function cloudDay(config) { let { $ } = await onceInit(config, { logger }), list = await getCloudDayList($), prizeId = await logger.prompt("请选择需要领取的礼物", { type: "select", options: list.map((gift) => ({ label: gift.prizeName + (gift.prizeType === 1 ? "(钻石专享)" : ""), value: String(gift.prizeId) })) }); if (!await verifyCloudDay($, prizeId)) return; if (!await logger.prompt("是否发送短信验证码", { type: "confirm" })) { logger.info("不发送验证码"); return; } if (!await getSmsVerCode($, prizeId)) { logger.fatal("获取验证码失败"); return; } let smsCode = await logger.prompt("请输入短信验证码", { type: "text" }); await logger.prompt("是否等待", { type: "confirm" }) && (logger.info("等待到下一个小时"), await waitToNextHour()), await receiveCloudDayGift($, prizeId, smsCode); } async function exchange(config) { let { $ } = await onceInit(config, { logger }), list = await getExchangeList($), prizeId = +await logger.prompt("请选择需要兑换的商品", { type: "select", options: list.map((gift) => ({ label: gift.prizeId + `【${gift.prizeName}(${gift.pOrder})】(${gift.dailyRemainderCount})(${gift.count})`, value: String(gift.prizeId) })) }), prize = list.find((g) => g.prizeId === prizeId); logger.info("选择了", prize.prizeId, prize.prizeName), logger.info("今日剩余:", prize.dailyRemainderCount, "/", prize.dailyCount), logger.info("本年度剩余:", prize.count, "/", prize.totalCount); let details = await getReceivePrizeDetails($, prize.prizeId), smsCode; if (details.verifycode === 0) { if ($.logger.info("需要短信验证"), !checkExchange($, prize)) return; if (!await logger.prompt("是否发送短信验证码", { type: "confirm" })) { logger.info("不发送验证码"); return; } if (!await getSmsVerCode($, prizeId)) { logger.fatal("获取验证码失败"); return; } smsCode = await logger.prompt("请输入短信验证码", { type: "text" }); } await logger.prompt("是否等待", { type: "confirm" }) && (logger.info("等待到下一个小时"), await waitToNextHour()), await exchangeApi($, prizeId, prize.prizeName, smsCode); } export { login };