postUpdate.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. /**
  2. * 更新发布工具
  3. *
  4. * Copyright © 2025 imengyu.top imengyu-update-server
  5. */
  6. import { confirm , input } from '@inquirer/prompts';
  7. import { writeFile, readFile, access, unlink, readdir, stat, constants } from 'node:fs/promises';
  8. import { exec } from 'node:child_process';
  9. import fs from 'fs';
  10. import archiver from 'archiver';
  11. import path from 'node:path';
  12. import OSS from 'ali-oss';
  13. import cliProgress from 'cli-progress';
  14. import { selectVersion } from './index.mjs';
  15. import { config } from './postConfig.mjs';
  16. import { dirname } from 'node:path';
  17. import { fileURLToPath } from 'node:url';
  18. //基础配置
  19. //========================================
  20. const __filename = fileURLToPath(import.meta.url);
  21. const __dirname = dirname(__filename);
  22. function readFileRange(file, start, length) {
  23. return new Promise((resolve, reject) => {
  24. fs.open(file, 'r', (err, fd) => {
  25. if (err) {
  26. reject('Error opening file:', er);
  27. return;
  28. }
  29. const buffer = Buffer.alloc(length);
  30. fs.read(fd, buffer, 0, length, start, (err, bytesRead, buffer) => {
  31. if (err) {
  32. reject('Error reading file:', err)
  33. return;
  34. }
  35. fs.close(fd, (err) => {
  36. if (err) {
  37. reject('Error closing file:', err)
  38. return ;
  39. }
  40. resolve(buffer);
  41. });
  42. });
  43. });
  44. })
  45. }
  46. export function pad(num, n) {
  47. var strNum = num.toString();
  48. var len = strNum.length;
  49. while (len < n) {
  50. strNum = "0" + strNum;
  51. len++;
  52. }
  53. return strNum;
  54. }
  55. async function getConfig() {
  56. let postConfig = {
  57. lastVersion: '',
  58. lastUpdateInfo: '',
  59. lastSubmitDay: '',
  60. lastTodaySubVersion: 0,
  61. };
  62. try {
  63. postConfig = JSON.parse(await readFile(path.resolve(__dirname, './_config.json')));
  64. } catch {
  65. //
  66. }
  67. if (postConfig.lastSubmitDay != new Date().getDate())
  68. postConfig.lastTodaySubVersion = 0;
  69. return postConfig;
  70. }
  71. async function saveConfig(postConfig) {
  72. postConfig.lastSubmitDay = new Date().getDate();
  73. await writeFile(path.resolve(__dirname, './_config.json'), JSON.stringify(postConfig));
  74. }
  75. //App更新与提交
  76. //========================================
  77. export async function postAppUpdate(axiosInstance, param) {
  78. const postConfig = await getConfig();
  79. const versionId = await selectVersion(false, postConfig.lastVersion);
  80. const updateInfo = await input({ message: '输入更新信息', default: postConfig.lastUpdateInfo });
  81. await axiosInstance.post('/update-post', { config: { type: 2, test: true, versionId, uploadWebConfig: config.uploadWebConfig, submitKey: config.submitKey } });
  82. postConfig.lastVersion = versionId;
  83. postConfig.lastUpdateInfo = updateInfo;
  84. postConfig.lastTodaySubVersion++;
  85. const updateSource = (await select({
  86. choices: [
  87. {
  88. name: '重新构建',
  89. value: 'rebuild',
  90. },
  91. {
  92. name: '已上传的阿里OSS文件路径',
  93. value: 'uploaded-alioss',
  94. },
  95. ],
  96. message: '选择上传来源',
  97. default: 'rebuild',
  98. }));
  99. const force = await confirm({ message: '强制更新?', default: false });
  100. const updateNext = hotfix ? false : await confirm({ message: '作为下个版本?', default: false });
  101. const versionCode = config.buildAppGetVersion();
  102. await saveConfig(postConfig);
  103. if (updateSource === 'rebuild')
  104. await config.buildAppCallback(param, versionCode, postConfig.lastTodaySubVersion);
  105. else if (updateSource === 'uploaded-alioss') {
  106. const fileName = await input({ message: '输入已上传的阿里OSS文件路径' });
  107. try {
  108. const result = (await axiosInstance.post('/update-post', {
  109. type: 2,
  110. ossConfig: {
  111. ossPath: fileName,
  112. ossPublic: '',
  113. },
  114. uploadAppConfig: {
  115. updateAsNext: updateNext,
  116. },
  117. versionId,
  118. updateInfo,
  119. versionCode: versionCode
  120. })).data;
  121. console.log('上传成功');
  122. console.log('新更新ID: ' + result.updateId);
  123. } catch (e) {
  124. console.error('上传失败', e);
  125. }
  126. return;
  127. }
  128. else {
  129. console.error('错误的选择');
  130. return;
  131. }
  132. const uploadFile = await config.buildAppGetUploadFile(param);
  133. try {
  134. await access(uploadFile, constants.R_OK)
  135. } catch {
  136. console.error(`Failed to access ${uploadFile}, did you created it?`);
  137. return;
  138. }
  139. console.log('开始上传');
  140. //小于8mb则小文件上传,否则使用阿里OSS上传
  141. const fileInfo = await stat(uploadFile);
  142. if (fileInfo.size < 8 * 1024 * 1024) {
  143. const appData = (await readFile(uploadFile));
  144. const formData = new FormData();
  145. formData.append("file", new Blob([ appData ], { type : 'application/zip' }));
  146. formData.append("type", 2);
  147. formData.append("versionId", versionId);
  148. formData.append("updateInfo", updateInfo);
  149. formData.append("uploadAppConfig", { updateAsNext: updateNext });
  150. formData.append("force", force);
  151. formData.append("versionCode", versionCode);
  152. try {
  153. const result = (await axiosInstance.post('/update-post', formData, {
  154. headers: { 'Content-Type': 'multipart/form-data' }
  155. })).data;
  156. console.log('上传成功');
  157. console.log('新更新ID: ' + result.updateId);
  158. console.log('删除构建文件');
  159. await unlink(uploadFile);
  160. } catch (e) {
  161. console.error('上传失败', e);
  162. }
  163. } else {
  164. //阿里OSS上传
  165. //请求STS进行临时授权
  166. const stsToken = (await axiosInstance.post('/update-ali-oss-sts')).data;
  167. const client = new OSS({
  168. region: stsToken.Region,
  169. accessKeyId: stsToken.AccessKeyId,
  170. accessKeySecret: stsToken.AccessKeySecret,
  171. stsToken: stsToken.SecurityToken,
  172. bucket: stsToken.Bucket,
  173. refreshSTSToken: async () => {
  174. const refreshToken = (await axiosInstance.get("/update-ali-oss-sts")).data;
  175. return {
  176. accessKeyId: refreshToken.AccessKeyId,
  177. accessKeySecret: refreshToken.AccessKeySecret,
  178. stsToken: refreshToken.SecurityToken,
  179. };
  180. },
  181. });
  182. //小于96mb则直接上传,否则分片上传
  183. const fileName = `/${await config.buildAppGetOSSFileName(param)}`;
  184. console.log('Start upload to ali oss');
  185. let returnUrl = '';
  186. if (fileInfo.size < 96 * 1024 * 1024) {
  187. const result = await client.put(fileName, uploadFile);
  188. returnUrl = result.url;
  189. } else {
  190. const bar1 = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);
  191. bar1.start(100, 0);
  192. await aliOSSMultipartUpload(client, fileName, uploadFile, (p) => {
  193. bar1.update(p * 100);
  194. });
  195. bar1.stop();
  196. }
  197. console.log('Upload to ali oss done');
  198. try {
  199. const result = (await axiosInstance.post('/update-post', {
  200. type: 2,
  201. ossConfig: {
  202. ossPath: fileName,
  203. ossPublic: returnUrl,
  204. },
  205. uploadAppConfig: {
  206. updateAsNext: updateNext,
  207. },
  208. versionId,
  209. updateInfo,
  210. versionCode: versionCode
  211. })).data;
  212. console.log('上传成功');
  213. console.log('新更新ID: ' + result.updateId);
  214. } catch (e) {
  215. console.error('上传失败', e);
  216. }
  217. }
  218. }
  219. //Web更新与提交
  220. //========================================
  221. export async function postWebUpdate(axiosInstance, param) {
  222. const skipBuild = param.skip
  223. const noDelete = param.ndelete;
  224. const postConfig = await getConfig();
  225. const versionId = await selectVersion(false, postConfig.lastVersion);
  226. const updateInfo = await input({ message: '输入更新信息', default: postConfig.lastUpdateInfo });
  227. postConfig.lastVersion = versionId;
  228. postConfig.lastUpdateInfo = updateInfo;
  229. postConfig.lastTodaySubVersion++;
  230. await axiosInstance.post('/update-post', { config: { type: 1, test: true, versionId, uploadWebConfig: config.uploadWebConfig, submitKey: config.submitKey } });
  231. const now = new Date();
  232. const versionCode = await config.buildWebVersionGenerateCommand(now, postConfig.lastTodaySubVersion);
  233. if (config.buildWebOutVersionPath)
  234. await writeFile(path.resolve(__dirname, config.buildWebOutVersionPath), versionCode);
  235. await saveConfig(postConfig);
  236. if (!skipBuild && config.buildWebCommand) {
  237. console.log('正在执行构建...');
  238. await new Promise((resolve, reject) => {
  239. exec(config.buildWebCommand, function(err, stdout) {
  240. if (err)
  241. reject(err);
  242. else
  243. resolve();
  244. });
  245. });
  246. console.log('构建完成');
  247. }
  248. const distDir = path.resolve(__dirname, config.buildWebOutDir);
  249. try {
  250. await access(distDir, constants.R_OK)
  251. } catch {
  252. console.error(`Failed to access ${distDir}`);
  253. return;
  254. }
  255. const outputPath = __dirname + '/upload.zip';
  256. if (!skipBuild) {
  257. console.log('开始压缩zip...');
  258. const output = fs.createWriteStream(outputPath);
  259. const archive = archiver('zip', {
  260. zlib: { level: 9 } // Sets the compression level.
  261. });
  262. archive.pipe(output);
  263. const files = await readdir(distDir);
  264. for (const file of files) {
  265. const filestat = await stat(distDir + '/' + file);
  266. if (filestat.isDirectory()) {
  267. archive.directory(distDir + '/' + file, file);
  268. } else {
  269. archive.file(distDir + '/' + file, { name: file });
  270. }
  271. }
  272. console.log('等待压缩zip...');
  273. const waitArchive = new Promise((resolve, reject) => {
  274. output.on('close', function() {
  275. console.log(archive.pointer() + ' total bytes');
  276. console.log('archiver has been finalized and the output file descriptor has closed.');
  277. resolve();
  278. });
  279. archive.on('error', function(err) {
  280. reject(err);
  281. });
  282. })
  283. await archive.finalize();
  284. await waitArchive;
  285. }
  286. console.log('开始上传zip');
  287. let success = false;
  288. //小于8mb则小文件上传,否则分片上传
  289. const fileInfo = await stat(outputPath);
  290. const formData = new FormData();
  291. const submitConfig = {
  292. type: 1,
  293. versionId,
  294. updateInfo,
  295. versionCode,
  296. uploadWebConfig: config.uploadWebConfig,
  297. }
  298. if (fileInfo.size < 8 * 1024 * 1024) {
  299. const uploadZipContent = await readFile(outputPath);
  300. formData.append("file", new Blob([ uploadZipContent ], { type : 'application/zip' }), 'upload.zip');
  301. } else {
  302. const multuploadInfo = (await axiosInstance.post('/update-large-token', {
  303. fileSize: fileInfo.size,
  304. fileName: path.basename(outputPath)
  305. })).data;
  306. const chunkSize = multuploadInfo.splitPartSize;
  307. const bar1 = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);
  308. bar1.start(100, 0);
  309. for (let i = 0; i < multuploadInfo.allChunks; i++) {
  310. const start = i * chunkSize;
  311. const len = Math.min(start + chunkSize, fileInfo.size) - start;
  312. const uploadZipContent = await readFileRange(outputPath, start, len);
  313. const subFormData = new FormData();
  314. subFormData.append("file", new Blob([ uploadZipContent ], { type : 'application/zip' }), 'upload.zip');
  315. subFormData.append("key", multuploadInfo.key);
  316. subFormData.append("info", JSON.stringify({}));
  317. (await axiosInstance.post('/update-large', subFormData, {
  318. headers: { 'Content-Type': 'multipart/form-data' }
  319. })).data;
  320. bar1.update(Math.floor(i / multuploadInfo.allChunks * 100));
  321. }
  322. bar1.stop();
  323. submitConfig.multuploadedKey = multuploadInfo.key;
  324. }
  325. try {
  326. formData.append("config", JSON.stringify(submitConfig));
  327. const result = (await axiosInstance.post('/update-post', formData, {
  328. headers: { 'Content-Type': 'multipart/form-data' }
  329. })).data;
  330. console.log('上传成功');
  331. console.log('新更新ID: ' + result.updateId);
  332. success = true;
  333. } catch (e) {
  334. console.error('上传失败', e);
  335. }
  336. if (!success || noDelete)
  337. return;
  338. console.log('删除zip');
  339. await unlink(outputPath);
  340. }