Files
ql-scripts/xiequ/scrip_switch.js
zhuhjay 960e2ecc0e fix(api): 修复API使用数量获取异常问题
- 添加数据有效性检查,防止空数据导致的错误
- 增加日志输出显示API剩余数量状态
- 当数据为空时返回默认值0避免程序崩溃
- 确保API数量计算逻辑的稳定性
2026-01-05 18:54:19 +08:00

87 lines
3.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* cron: 38 2,8,14,20 * * *
*
* 携趣白名单切换(多个携趣多个IP多个IP选中一个合适的携趣进行切换)
*/
const { Env } = require('../common');
const $ = new Env('携趣小助手-白名单切换');
const fetch = require('node-fetch');
/** 环境变量
* XQ_ACCOUNTS: uid1;ukey1@备注 -》 多个则使用 & 分隔
* XQ_WHITELIST: ip1 -》 多个则使用 & 分隔
*/
const accounts = process.env['XQ_ACCOUNTS'];
const whitelist = process.env['XQ_WHITELIST'];
const apiTpl = {
// 查看当前哪些 IP 在白名单中
get: info => `http://op.xiequ.cn/IpWhiteList.aspx?uid=${info.uid}&ukey=${info.ukey}&act=get`,
add: (info, ip) => `http://op.xiequ.cn/IpWhiteList.aspx?uid=${info.uid}&ukey=${info.ukey}&act=add&ip=${ip}`,
delOne: (info, ip) => `http://op.xiequ.cn/IpWhiteList.aspx?uid=${info.uid}&ukey=${info.ukey}&act=del&ip=${ip}`,
delAll: info => `http://op.xiequ.cn/IpWhiteList.aspx?uid=${info.uid}&ukey=${info.ukey}&act=del&ip=all`,
// 获取 API 使用情况
apiUse: info => `http://op.xiequ.cn/ApiUser.aspx?act=suitdt&uid=${info.uid}&ukey=${info.ukey}`
}
!(async () => {
if (!accounts || !whitelist) {
$.log('请填写环境变量 XQ_ACCOUNTS & XQ_WHITELIST');
return;
}
let tmp = [];
let accs = accounts.split('&');
let ips = whitelist.split('&');
// 解析参数 & 获取信息
for (let content of accs) {
let [acc, comment] = content.split('@');
let [uid, ukey] = acc.split(';');
if (!uid || !ukey) {
$.log('请填写正确的环境变量 XQ_ACCOUNTS');
return;
}
let info = { uid: uid.trim(), ukey: ukey.trim(), comment: comment || `[uid:${uid}]` };
let item = {
info: info,
res: await (await fetch(apiTpl.get(info))).text(),
count: await (async function () {
let { data } = await (await fetch(apiTpl.apiUse(info))).json();
if (!data || !data[0]) {
$.log(`该api剩余数量可能为0: ${data}`);
return 0;
}
return +data[0].num - +data[0].use;
}())
};
tmp.push(item)
$.log(`[INFO] ${item.info.comment} 剩余数: ${item.count}`);
}
// 删除所有白名单
$.log('\n--- 删除白名单 --- \n');
for (let tmpElement of tmp) {
if (tmpElement?.res) {
await fetch(apiTpl.delAll(tmpElement.info));
$.log(`删除 name: ${tmpElement.info.comment} 下的所有白名单 -> `, tmpElement.res);
}
}
await $.wait(520);
// 选中一个数量最多的 API
let change = tmp.sort((a, b) => b.count - a.count)[0];
$.log('\n--- 切换白名单 --- \n');
if (change) {
for (const ip of ips) {
await fetch(apiTpl.add(change.info, ip));
$.log(`添加 name: ${change.info.comment} 白名单`);
}
}
})()
.catch((e) => {
$.logErr(e);
})
.finally(() => {
$.done();
});