"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// ../../packages/utils-pure/index.ts function randomHex(length, pad = "-") { return Array.isArray(length) ? length.map((l) => randomHex(l, pad)).join(pad) : Array.from({ length }).map(() => Math.floor(Math.random() * 16).toString(16)).join(""); } // ../../core/alipan/api.ts function createApi(http) { let memberUrl = "https://member.aliyundrive.com", aliyundriveUrl = "https://api.aliyundrive.com", authUrl = "https://auth.aliyundrive.com", apiUrl = "https://api.alipan.com"; return { refreshToken(refreshToken2) { return http.post(`${aliyundriveUrl}/token/refresh`, { refresh_token: refreshToken2 }); }, getAccessToken(refreshToken2) { return http.post(`${authUrl}/v2/account/token`, { refresh_token: refreshToken2, grant_type: "refresh_token" }); }, signInList() { return http.post( `${memberUrl}/v2/activity/sign_in_list?_rx-s=mobile`, { "_rx-s": "mobile" } ); }, signIn() { return http.post( `${memberUrl}/v2/activity/sign_in_info?_rx-s=mobile`, {} ); }, signInReward(signInDay) { return http.post( `${memberUrl}/v1/activity/sign_in_reward?_rx-s=mobile`, { signInDay } ); }, signInTaskReward(signInDay) { return http.post(`${memberUrl}/v2/activity/sign_in_task_reward`, { signInDay }); }, updateDeviceExtras() { return http.post( `${apiUrl}/users/v1/users/update_device_extras`, { albumAccessAuthority: !0, albumBackupLeftFileTotal: 0, albumBackupLeftFileTotalSize: 0, albumFile: 0, autoBackupStatus: !0, // totalSize: 0, // useSize: 0, brand: "xiaomi", systemVersion: "Android 13" } ); }, createSession(deviceId, refreshToken2, pubKey, deviceName, modelName) { return http.post( "https://api.alipan.com/users/v1/users/device/create_session", { deviceName, modelName, nonce: "0", pubKey, refreshToken: refreshToken2 }, { headers: { "x-device-id": deviceId } } ); }, getDeviceAppletList() { return http.post( `${apiUrl}/adrive/v2/backup/device_applet_list_summary`, {} ); }, getDeviceList() { return http.post(`${apiUrl}/users/v2/users/device_list`, {}); }, getAlbumsInfo() { return http.post( `${aliyundriveUrl}/adrive/v1/user/albums_info`, {} ); }, getDeviceRoomList() { return http.post( "https://user.aliyundrive.com/v1/deviceRoom/listDevice", {} ); }, getDeviceRoomRewardInfoToday() { return http.post( `${memberUrl}/v1/deviceRoom/rewardInfoToday`, {} ); }, getDeviceRoomRewardEnergy(deviceId) { return http.post( `${memberUrl}/v1/deviceRoom/rewardEnergy`, { deviceId } ); }, createFile(deviceId, driveId) { let size = Math.floor(Math.random() * 3e4); return http.post( `${aliyundriveUrl}/adrive/v2/biz/albums/file/create`, { drive_id: driveId, part_info_list: [ { part_number: 1, part_size: size } ], parent_file_id: "root", name: Math.floor(Math.random() * 1e8) + ".jpg", type: "file", check_name_mode: "auto_rename", size, create_scene: "album_autobackup", hidden: !1, content_type: "image/jpeg" }, { headers: { "x-device-id": deviceId } } ); }, completeUpload(deviceId, driveId, fileId, uploadId) { return http.post( `${aliyundriveUrl}/v2/file/complete`, { drive_id: driveId, upload_id: uploadId, file_id: fileId }, { headers: { "x-device-id": deviceId } } ); }, completeAlbumsUpload(deviceId, driveId, fileId, contentHash) { return http.post( `${aliyundriveUrl}/adrive/v2/biz/albums/file/complete`, { drive_id: driveId, file_id: fileId, content_hash: contentHash, content_hash_name: "sha1" }, { headers: { "x-device-id": deviceId } } ); }, deleteFile(deviceId, driveId, fileId) { return http.post( `${apiUrl}/adrive/v4/batch`, { requests: [ { body: { drive_id: driveId, file_id: fileId }, id: fileId, method: "POST", url: "/file/delete" } ], resource: "file" }, { headers: { "x-device-id": deviceId } } ); }, home() { return http.post(`${aliyundriveUrl}/apps/v2/users/home/widgets`, {}); } }; } // ../../core/alipan/index.ts async function request($, api, name, ...args) { try { let { success, message, result } = await api(...args); if (!success) $.logger.error(`${name}失败`, message); else return result; } catch (error) { $.logger.error(`${name}异常`, error); } return {}; } async function refreshToken($, token) { try { let data = await $.api.getAccessToken(token); if (!data.access_token) { $.logger.error("获取 access_token 失败", JSON.stringify(data)); return; } return data; } catch (error) { $.logger.error("获取 access_token 异常", error); } } async function createDeviceApi($, refreshToken2, deviceId) { try { let { success } = await $.api.createSession( deviceId, refreshToken2, randomHex(32), "XiaoMi 14Pro", "xiaomi" ); return success ? ($.logger.info("创建虚拟设备成功"), !0) : ($.logger.error(`创建虚拟设备${deviceId}失败`), !1); } catch (error) { $.logger.error(`创建虚拟设备${deviceId}异常`, error); } return !1; } async function getDeviceRoomListApi($) { try { let { items } = await $.api.getDeviceRoomList(); if (!items) { $.logger.error("获取设备间列表失败"); return; } return items; } catch (error) { $.logger.error("获取设备间列表异常", error); } } async function getDeviceRoomRewardInfo($) { return request($, $.api.getDeviceRoomRewardInfoToday, "获取设备间领取信息"); } async function getAlbumsDriveId($) { try { let { code, message, data } = await $.api.getAlbumsInfo(); if (code !== "200") { $.logger.error("获取相册文件夹失败", message); return; } return data.driveId; } catch (error) { $.logger.error("获取相册文件夹异常", error); } } async function createDevice($) { let needNum = 5 - (await getDeviceRoomListApi($)).length; if (!(needNum <= 0)) { $.logger.info(`需要创建${needNum}个虚拟设备`); for (let i = 0; i < needNum; i++) await createDeviceApi($, $.DATA.refreshToken, randomHex(64)); } } async function uploadFile($, deviceId, driveId) { try { let { file_id, upload_id } = await $.api.createFile(deviceId, driveId); if (file_id) return await $.sleep(1e3), await $.api.completeUpload(deviceId, driveId, file_id, upload_id), await $.api.completeAlbumsUpload( deviceId, driveId, file_id, "DA39A3EE5E6B4B0D3255BFEF95601890AFD80709" ), { file_id, upload_id }; $.logger.error(`${deviceId}上传文件失败`); } catch (error) { $.logger.error("上传文件异常", error); } return {}; } async function deviceRoomListHandle(deviceRooms) { let nofinishDevices = /* @__PURE__ */ new Set(), rewardEnergys = /* @__PURE__ */ new Set(), okNum = 0; for (let { canCollectEnergy, id, gmtCollectEnergy } of deviceRooms) !canCollectEnergy && new Date(gmtCollectEnergy).getUTCDate() !== (/* @__PURE__ */ new Date()).getUTCDate() ? nofinishDevices.add(id) : canCollectEnergy ? rewardEnergys.add(id) : okNum++; return { nofinishDevices: Array.from(nofinishDevices), rewardEnergys: Array.from(rewardEnergys), okNum }; } async function deleteFileApi($, deviceId, driveId, fileId) { try { await $.api.deleteFile(deviceId, driveId, fileId); } catch (error) { $.logger.error(`删除文件${fileId}异常`, error); } } async function deleteFiles($, needDeleteFiles, driveId) { for (let [fileId, deviceId] of needDeleteFiles) await deleteFileApi($, deviceId, driveId, fileId), await $.sleep(1e3); } async function deviceRoomTask($) { let { rewardCountToday, rewardTotalSize } = await getDeviceRoomRewardInfo($); if (rewardCountToday >= 5) { $.logger.info( `今日已领取${rewardCountToday}次设备间空间,历史总共${rewardTotalSize}M` ); return; } let driveId = await getAlbumsDriveId($); if (!driveId) { $.logger.error("未获取到文件夹故跳过执行"); return; } let needDeleteFiles = /* @__PURE__ */ new Map(); await createDevice($), await _deviceRoomTask(), await $.sleep(2e3), await deleteFiles($, needDeleteFiles, driveId); async function _deviceRoomTask() { let items = await getDeviceRoomListApi($); if (!items) return $.logger.error("无法获取虚拟设备,跳过执行"), !1; if (items.length === 0) return $.logger.error("无法创建虚拟设备,跳过执行"), !1; let { nofinishDevices, rewardEnergys, okNum } = await deviceRoomListHandle(items); if (okNum >= 5) return !1; $.logger.info("跳过领取设备间奖励"); for (let deviceId of rewardEnergys) $.logger.info(`${deviceId} 可领取`); for (let deviceId of nofinishDevices) { let { file_id } = await uploadFile($, deviceId, driveId) || {}; file_id && needDeleteFiles.set(file_id, deviceId), await $.sleep(1e3); } return !0; } } async function getDeviceList($) { try { let data = await $.api.getDeviceAppletList(); if (!data.deviceItems) { $.logger.error("获取设备信息失败", JSON.stringify(data)); return; } if (data.deviceItems.length === 0) { $.logger.error("获取到的设备列表未空"); return; } return data.deviceItems; } catch (error) { $.logger.error("获取设备信息异常", error); } } async function getDevice($) { let devices = await getDeviceList($); return devices ? devices.find(({ deviceId }) => deviceId) : void 0; } async function signInTask($) { let { rewards } = await request($, $.api.signIn, "签到"); if (rewards.find( ({ type, status }) => type === "dailyTask" && (status === "verification" || status === "finished") )) return; let { deviceId, backupViews } = await getDevice($) || {}; if (!deviceId) { $.logger.error("未获取到设备 id,跳过每日任务执行"); return; } $.DATA.deviceId = deviceId; let backupView = backupViews.find(({ view }) => view === "album"); if (!backupView) { $.logger.error("未获取到文件夹 id,跳过每日任务执行"); return; } await request($, $.api.updateDeviceExtras, "上报备份"), $.logger.info("不再完成备份任务"); } async function printSignInInfo($) { let { rewards } = await request($, $.api.signIn, "签到"); if (!rewards) return; let statusMap = { unfinished: "未完成", finished: "未领取奖励", verification: "已领取奖励", notStart: "未开始" }; rewards.forEach(({ remind, name, status }) => { $.logger.info(`${remind}/${name}/${statusMap[status]}`); }); } async function run($) { let taskList = [signInTask, printSignInInfo]; $.config.skipUpload !== !0 && taskList.unshift(deviceRoomTask); for (let task of taskList) await task($), await $.sleep(1e3); for (let task of $.DATA.afterTask) await task(), await $.sleep(1e3); } // index.ts var _conf = require('@asunajs/conf'); var _http = require('@asunajs/http'); var _push = require('@asunajs/push'); // ../../packages/utils/index.ts var _crypto = require('crypto'); var _crypto2 = _interopRequireDefault(_crypto); function sleep(time) { return new Promise((res) => setTimeout(() => res(time), time)); } async function createLogger(options) { let { createConsola, consola } = await Promise.resolve().then(() => _interopRequireWildcard(require("./dist-WNKMRARM.cjs"))); return consola.options.level = 5, createConsola({ level: 5, reporters: [ { log: ({ type, args, level, date }) => { if (options && options.pushData) { let msg = args.reduce((str, cur) => `${str} ${cur}`, "").substring(1); options.pushData.push({ msg, type, level, date }); } consola[type].apply(consola, args); } } ] }); } function _hash(algorithm, input) { return _crypto2.default.createHash(algorithm).update(input).digest("hex"); } function sha256(input) { return _hash("sha256", input); } async function pushMessage({ pushData, message, sendNotify: sendNotify2, createRequest: createRequest2 }) { if (pushData.length && message) { if (message.onlyError && !pushData.some((el) => el.type === "error")) return; let msg = pushData.filter((el) => el.level < 4).map((m) => `[${m.type} ${m.date.toLocaleTimeString()}]${m.msg}`).join(` `); msg && await sendNotify2( { logger: await createLogger(), http: { fetch: (op) => createRequest2().request(op) } }, message, message.title || "asign 运行推送", msg ); } } // utils.ts var _secp256k1 = require('secp256k1'); var _secp256k12 = _interopRequireDefault(_secp256k1); var { publicKeyCreate, ecdsaSign } = _secp256k12.default; function getSignature(nonce, user_id, deviceId) { let toHex = (bytes) => Buffer.from(bytes).toString("hex"), toU8 = (str) => new Uint8Array(Buffer.from(str, "hex")), privateKey = toU8(sha256(user_id)), publicKey = "04" + toHex(publicKeyCreate(privateKey)); return { signature: toHex( ecdsaSign( toU8(sha256(`5dde4e1bdf9e4966b387ba58f4b3fdc3:${deviceId}:${user_id}:${nonce}`)), privateKey ).signature ) + "01", publicKey }; } // index.ts function getXSignature(DATA, userId) { if (DATA["x-signature"]) return DATA["x-signature"]; let t = DATA.deviceId ? getSignature(0, userId, DATA.deviceId).signature : ""; return DATA["x-signature"] = t, t || randomHex(128) + "01"; } async function main(config, option) { let token = config.token; if (!token) return; let logger = await createLogger({ pushData: option == null ? void 0 : option.pushData }), DATA = { deviceId: "", afterTask: [] }, accessToken, userId, $ = { api: createApi( _http.createRequest.call(void 0, { hooks: { beforeRequest: [ (options) => { options.headers = { "x-device-id": DATA.deviceId, authorization: accessToken ? `Bearer ${accessToken}` : "", "x-signature": getXSignature(DATA, userId), ...options.headers }; } ] }, headers: { "content-type": "application/json;charset=UTF-8", referer: "https://alipan.com/", origin: "https://alipan.com/", "x-canary": "client=Android,app=adrive,version=v5.8.0", "user-agent": "AliApp(AYSD/5.8.0) com.alicloud.databox/37029260 Channel/36176727979800@rimet_android_5.8.0 language/zh-CN /Android Mobile/Mi 6X" } }) ), logger, DATA, sleep, config }, rtData = await refreshToken($, token.trim()); if (rtData) return DATA.refreshToken = rtData.refresh_token, accessToken = rtData.access_token, userId = rtData.user_id, DATA.deviceId = rtData.device_id, $.logger.info("-------------"), $.logger.info(`你好${rtData.nick_name || rtData.user_name}`), await run($), rtData.refresh_token; } async function run2(inputPath) { let { config, path } = await _conf.loadConfig.call(void 0, inputPath), logger = await createLogger(), alipan = config.alipan; if (!alipan || !alipan.length || !alipan[0].token) return logger.error("未找到配置文件/变量"); let pushData = []; for (let index = 0; index < alipan.length; index++) { let c = alipan[index]; if (c.token) try { let token = await main(c, { pushData }); token && _conf.rewriteConfigSync.call(void 0, path, ["alipan", index, "token"], token); } catch (error) { logger.error(error); } } await pushMessage({ pushData, message: config.message, sendNotify: _push.sendNotify, createRequest: _http.createRequest }); } exports.main = main; exports.run = run2;