|
| 1 | +import { logger } from "./logger" |
| 2 | +import {join} from 'node:path' |
| 3 | +import fs from 'node:fs' |
| 4 | +import * as unzipper from 'unzipper' |
| 5 | +import http from 'node:http' |
| 6 | +import currentVer from './workers/update.json' |
| 7 | +import { inspect } from "node:util" |
| 8 | +// 定义 update.json 的数据结构 |
| 9 | +interface UpdateInfo { |
| 10 | + ver: string |
| 11 | + filename: string |
| 12 | +} |
| 13 | +const MAX_REDIRECTS = 5 // 防止无限重定向 |
| 14 | +/** |
| 15 | + * 辅助函数:下载文件并流式解压到指定路径 |
| 16 | + * @param downloadUrl 文件的URL |
| 17 | + * @param extractPath 解压的目标路径 |
| 18 | + * @param redirectCount 当前重定向次数 |
| 19 | + */ |
| 20 | +const downloadAndUnzip = (downloadUrl: string, extractPath: string, redirectCount = 0): Promise<void> => { |
| 21 | + return new Promise((resolve, reject) => { |
| 22 | + if (redirectCount > MAX_REDIRECTS) { |
| 23 | + return reject(new Error('超过最大重定向次数')) |
| 24 | + } |
| 25 | + const options = { agent: httpAgent } |
| 26 | + http.get(downloadUrl, options, (response) => { |
| 27 | + // 处理重定向 |
| 28 | + if (response.statusCode && response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) { |
| 29 | + logger(`下载被重定向到: ${response.headers.location}`) |
| 30 | + return downloadAndUnzip(response.headers.location, extractPath, redirectCount + 1).then(resolve).catch(reject) |
| 31 | + } |
| 32 | + |
| 33 | + if (response.statusCode !== 200) { |
| 34 | + return reject(new Error(`下载失败,状态码: ${response.statusCode}`)) |
| 35 | + } |
| 36 | + |
| 37 | + // 将下载流直接导入解压器 |
| 38 | + response.pipe(unzipper.Extract({ path: extractPath })) |
| 39 | + .on('finish', resolve) |
| 40 | + .on('error', reject) |
| 41 | + }).on('error', (err) => { |
| 42 | + logger(`downloadAndUnzip Error`, err.message) |
| 43 | + }) |
| 44 | + }) |
| 45 | +} |
| 46 | +const httpAgent = new http.Agent({ keepAlive: false }) |
| 47 | + |
| 48 | +/** |
| 49 | + * 辅助函数:发起 GET 请求,处理重定向,并以文本形式返回响应体。 |
| 50 | + * @param requestUrl 请求的 URL |
| 51 | + * @param redirectCount 当前重定向次数 |
| 52 | + * @returns Promise,解析为响应体字符串 |
| 53 | + */ |
| 54 | +const fetchText = (requestUrl: string, redirectCount = 0): Promise<string> => { |
| 55 | + return new Promise((resolve, reject) => { |
| 56 | + if (redirectCount > MAX_REDIRECTS) { |
| 57 | + return reject(new Error('超过最大重定向次数')) |
| 58 | + } |
| 59 | + logger(`fetchText access ${requestUrl}`) |
| 60 | + const options = { agent: httpAgent } |
| 61 | + http.get(requestUrl, options, (response) => { |
| 62 | + // 处理重定向 |
| 63 | + if (response.statusCode && response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) { |
| 64 | + logger(`被重定向到: ${response.headers.location}`) |
| 65 | + return fetchText(response.headers.location, redirectCount + 1).then(resolve).catch(reject) |
| 66 | + } |
| 67 | + |
| 68 | + // 处理请求错误 |
| 69 | + if (response.statusCode && response.statusCode >= 400) { |
| 70 | + return reject(new Error(`请求失败,状态码: ${response.statusCode}`)) |
| 71 | + } |
| 72 | + logger(`fetchText success!`) |
| 73 | + let body = '' |
| 74 | + response.setEncoding('utf8') |
| 75 | + response.on('data', (chunk) => { body += chunk; }) |
| 76 | + response.on('end', () => { |
| 77 | + logger(`response.on('end') ${body}`) |
| 78 | + resolve(body) |
| 79 | + }) |
| 80 | + }).on('error', (err) => { |
| 81 | + logger(`fetchText Error`, err.message) |
| 82 | + }) |
| 83 | + }) |
| 84 | +} |
| 85 | + |
| 86 | +/** |
| 87 | + * 从节点列表中随机选择一个节点 |
| 88 | + * @param nodes 节点信息数组 |
| 89 | + * @returns 随机选中的一个节点信息对象 |
| 90 | + */ |
| 91 | + |
| 92 | +const getRandomNode = (nodes: nodes_info[]): nodes_info => { |
| 93 | + if (!nodes || nodes.length === 0) { |
| 94 | + throw new Error('节点列表为空,无法选择节点。') |
| 95 | + } |
| 96 | + const randomIndex = Math.floor(Math.random() * nodes.length) |
| 97 | + return nodes[randomIndex] |
| 98 | +} |
| 99 | + |
| 100 | +/** |
| 101 | + * 主更新函数 |
| 102 | + */ |
| 103 | +export const runUpdater = async (nodes: nodes_info[] ) => { |
| 104 | + |
| 105 | + |
| 106 | + logger('🚀 开始执行动态节点更新程序...') |
| 107 | + |
| 108 | + try { |
| 109 | + |
| 110 | + |
| 111 | + const selectedNode = getRandomNode(nodes) |
| 112 | + logger(`✅ 节点列表获取成功!已随机选择节点: ${selectedNode.ip_addr} (位于 ${selectedNode.region})`); |
| 113 | + |
| 114 | + // --- 步骤 2: 使用选定节点的 IP 获取更新信息 --- |
| 115 | + // 使用节点的 IP 地址构建 API 的基础 URL |
| 116 | + const baseApiUrl = `http://${selectedNode.ip_addr}/silentpass-rpc/` |
| 117 | + const updateJsonUrl = `${baseApiUrl}update.json` |
| 118 | + |
| 119 | + // --- 步骤 2: 使用选定节点的 IP 获取更新信息 --- |
| 120 | + |
| 121 | + const updateInfoText = await fetchText(updateJsonUrl) |
| 122 | + logger(`正在从选定节点 ${updateJsonUrl} 获取更新信息... updateInfoText = ${updateInfoText}`) |
| 123 | + const updateInfo: UpdateInfo = JSON.parse(updateInfoText) |
| 124 | + |
| 125 | + |
| 126 | + if (!updateInfo.filename) { |
| 127 | + throw new Error('无法从 JSON 响应中获取文件名。') |
| 128 | + } |
| 129 | + |
| 130 | + logger(`✅ 获取信息成功!最新版本: ${updateInfo.ver}, 文件名: ${updateInfo.filename}`) |
| 131 | + |
| 132 | + const updateVer = isNewerVersion(currentVer.ver, updateInfo.ver) |
| 133 | + if (!updateVer) { |
| 134 | + return logger(`runUpdater [No update]!`) |
| 135 | + } |
| 136 | + // --- 步骤 3: 从选定节点下载并解压文件 --- |
| 137 | + const downloadUrl = `${baseApiUrl}${updateInfo.filename}` |
| 138 | + const extractPath = join(__dirname, 'workers') |
| 139 | + |
| 140 | + logger(`⏳ 正在从 ${downloadUrl} 下载并解压...`) |
| 141 | + logger(`将解压到目录: ${extractPath}`) |
| 142 | + |
| 143 | + // 确保目标目录存在 |
| 144 | + if (!fs.existsSync(extractPath)) { |
| 145 | + fs.mkdirSync(extractPath, { recursive: true }) |
| 146 | + } |
| 147 | + await downloadAndUnzip(downloadUrl, extractPath) |
| 148 | + logger(`🎉 成功下载并解压文件到 ${extractPath}`) |
| 149 | + |
| 150 | + } catch (error) { |
| 151 | + console.error('❌ 更新过程中发生错误:', error instanceof Error ? error.message : error) |
| 152 | + } |
| 153 | +} |
| 154 | +// 执行更新程序 |
| 155 | + |
| 156 | +/** |
| 157 | + * 比较两个语义化版本号。 |
| 158 | + * @param oldVer 旧版本号,如 "0.18.0" |
| 159 | + * @param newVer 新版本号,如 "0.18.1" |
| 160 | + * @returns 如果 newVer 比 oldVer 新,则返回 true;否则返回 false。 |
| 161 | + */ |
| 162 | +function isNewerVersion(oldVer: string, newVer: string): boolean { |
| 163 | + const oldParts = oldVer.split('.').map(Number); |
| 164 | + const newParts = newVer.split('.').map(Number); |
| 165 | + |
| 166 | + for (let i = 0; i < oldParts.length; i++) { |
| 167 | + if (newParts[i] > oldParts[i]) { |
| 168 | + return true; |
| 169 | + } |
| 170 | + if (newParts[i] < oldParts[i]) { |
| 171 | + return false; |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + return false; // 如果版本号完全相同,则不是更新的版本 |
| 176 | +} |
| 177 | + |
0 commit comments