|
| 1 | +import axios from 'axios'; |
| 2 | + |
| 3 | +/** |
| 4 | + * GitHub Release 控制器 |
| 5 | + * 用于获取 GitHub 仓库的最新 Release 下载链接 |
| 6 | + */ |
| 7 | +export default (fastify, options, done) => { |
| 8 | + |
| 9 | + /** |
| 10 | + * 获取最新 Release 下载链接 |
| 11 | + * 路径: /gh/release |
| 12 | + * 参数: repo (可选,默认 hjdhnx/drpy-node) |
| 13 | + */ |
| 14 | + fastify.get('/gh/release', async (request, reply) => { |
| 15 | + const repo = request.query.repo || 'hjdhnx/drpy-node'; |
| 16 | + const proxyPrefix = 'https://github.catvod.com/'; |
| 17 | + const apiUrl = `https://api.github.com/repos/${repo}/releases/latest`; |
| 18 | + |
| 19 | + try { |
| 20 | + fastify.log.info(`Fetching release info for ${repo}`); |
| 21 | + |
| 22 | + const response = await axios.get(apiUrl, { |
| 23 | + headers: { |
| 24 | + 'User-Agent': 'drpy-node-client', |
| 25 | + 'Accept': 'application/vnd.github.v3+json' |
| 26 | + } |
| 27 | + }); |
| 28 | + |
| 29 | + const data = response.data; |
| 30 | + |
| 31 | + if (!data.assets || data.assets.length === 0) { |
| 32 | + return reply.status(404).send({ error: 'No assets found in the latest release' }); |
| 33 | + } |
| 34 | + |
| 35 | + // 打印全部文件列表的链接 |
| 36 | + fastify.log.info(`Assets for ${repo} ${data.tag_name}:`); |
| 37 | + const fileList = data.assets.map(asset => { |
| 38 | + fastify.log.info(`- ${asset.name}: ${asset.browser_download_url}`); |
| 39 | + return { |
| 40 | + name: asset.name, |
| 41 | + url: asset.browser_download_url, |
| 42 | + proxy_url: proxyPrefix + asset.browser_download_url |
| 43 | + }; |
| 44 | + }); |
| 45 | + |
| 46 | + // 优先选择后缀为 .7z 且文件名不包含 green 的文件 |
| 47 | + let targetAsset = data.assets.find(asset => asset.name.toLowerCase().endsWith('.7z') && !asset.name.toLowerCase().includes('green')); |
| 48 | + |
| 49 | + if (!targetAsset) { |
| 50 | + fastify.log.warn(`No asset found matching criteria (.7z, no 'green'), falling back to the first asset.`); |
| 51 | + targetAsset = data.assets[0]; |
| 52 | + } |
| 53 | + |
| 54 | + const originalUrl = targetAsset.browser_download_url; |
| 55 | + const finalUrl = proxyPrefix + originalUrl; |
| 56 | + |
| 57 | + // 返回这个完整链接 |
| 58 | + // 用户要求"返回这个完整链接",这里直接返回字符串 |
| 59 | + return reply.send(finalUrl); |
| 60 | + |
| 61 | + } catch (error) { |
| 62 | + fastify.log.error(`Error fetching release for ${repo}: ${error.message}`); |
| 63 | + if (error.response) { |
| 64 | + fastify.log.error(`GitHub API Status: ${error.response.status}`); |
| 65 | + return reply.status(error.response.status).send({ |
| 66 | + error: 'GitHub API Error', |
| 67 | + message: error.response.data.message |
| 68 | + }); |
| 69 | + } |
| 70 | + return reply.status(500).send({ error: 'Internal Server Error', message: error.message }); |
| 71 | + } |
| 72 | + }); |
| 73 | + |
| 74 | + done(); |
| 75 | +}; |
0 commit comments