| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- import { Logs } from "./logs.js";
- import { getData, setData } from "./cache.js";
- const accountOptionCacheFile = 'data/accountOptionCache.json';
- const ACCOUNT_OPTIONS = {
- currentIndex: 0,
- nextChangeTime: 0,
- };
- const IS_DEV = process.env.NODE_ENV == 'development';
- /**
- * 随机一个毫秒数
- * 范围:4小时 ~ 7小时
- * 测试环境范围:4分钟 ~ 7分钟
- * 加上当前时间戳
- * 计算下次切换时间
- */
- const getRandomTime = () => {
- const nowTime = Date.now();
- const min = 1000 * 60 * (IS_DEV ? 1 : 60) * 4;
- const max = 1000 * 60 * (IS_DEV ? 1 : 60) * 7;
- const randomTime = Math.floor(Math.random() * (max - min + 1)) + min;
- return nowTime + randomTime;
- }
- /**
- * 缓存GLOBAL_DATA数据到文件
- * @returns {Promise<void>}
- */
- const saveGlobalDataToCache = async () => {
- return setData(accountOptionCacheFile, ACCOUNT_OPTIONS);
- }
- /**
- * 从文件中加载GLOBAL_DATA数据
- * @returns {Promise<void>}
- */
- const loadGlobalDataFromCache = async () => {
- return getData(accountOptionCacheFile)
- .then(data => {
- if (!data) {
- return;
- }
- Object.keys(ACCOUNT_OPTIONS).forEach(key => {
- if (key in data) {
- ACCOUNT_OPTIONS[key] = data[key];
- }
- });
- });
- }
- /**
- * 获取当前账号信息
- * @returns
- */
- export const getAccountInfo = () => {
- const nowTime = Date.now();
- const accounts = process.env.PINNACLE_ACCOUNTS?.split(',').map(item => {
- const [username, password, localAddress, platform] = item.split(':');
- return { username, password, localAddress, platform };
- }) ?? [];
- if (accounts.length == 0) {
- return null;
- }
- let isAccountChanged = false;
- if (ACCOUNT_OPTIONS.nextChangeTime == 0) {
- ACCOUNT_OPTIONS.currentIndex = 0;
- ACCOUNT_OPTIONS.nextChangeTime = getRandomTime();
- }
- else if (nowTime > ACCOUNT_OPTIONS.nextChangeTime) {
- ACCOUNT_OPTIONS.currentIndex++;
- if (ACCOUNT_OPTIONS.currentIndex >= accounts.length) {
- ACCOUNT_OPTIONS.currentIndex = 0;
- }
- ACCOUNT_OPTIONS.nextChangeTime = getRandomTime();
- isAccountChanged = true;
- saveGlobalDataToCache();
- }
- const accountInfo = accounts[ACCOUNT_OPTIONS.currentIndex];
- if (isAccountChanged) {
- const { password, ...accountInfoRest } = accountInfo;
- Logs.out('account changed', ACCOUNT_OPTIONS, accountInfoRest);
- }
- return accountInfo;
- }
- /**
- * 监听进程退出事件
- * 保存GLOBAL_DATA数据
- */
- const saveExit = (code) => {
- saveGlobalDataToCache()
- .then(() => {
- Logs.out('account options saved');
- })
- .catch(err => {
- Logs.err('failed to save account options', err.message);
- })
- .finally(() => {
- process.exit(code);
- });
- }
- process.on('SIGINT', () => {
- saveExit(0);
- });
- process.on('SIGTERM', () => {
- saveExit(0);
- });
- process.on('SIGUSR2', () => {
- saveExit(0);
- });
- loadGlobalDataFromCache();
|