check.mjs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. import fs from "fs-extra";
  2. import zlib from "zlib";
  3. import path from "path";
  4. import AdmZip from "adm-zip";
  5. import fetch from "node-fetch";
  6. import proxyAgent from "https-proxy-agent";
  7. import { execSync } from "child_process";
  8. const cwd = process.cwd();
  9. const TEMP_DIR = path.join(cwd, "node_modules/.verge");
  10. const FORCE = process.argv.includes("--force");
  11. const SIDECAR_HOST = execSync("rustc -vV")
  12. .toString()
  13. .match(/(?<=host: ).+(?=\s*)/g)[0];
  14. /* ======= clash ======= */
  15. const CLASH_STORAGE_PREFIX = "https://release.dreamacro.workers.dev/";
  16. const CLASH_URL_PREFIX =
  17. "https://github.com/Dreamacro/clash/releases/download/premium/";
  18. const CLASH_LATEST_DATE = "2023.08.17";
  19. const CLASH_MAP = {
  20. "win32-x64": "clash-windows-amd64",
  21. "darwin-x64": "clash-darwin-amd64",
  22. "darwin-arm64": "clash-darwin-arm64",
  23. "linux-x64": "clash-linux-amd64",
  24. "linux-arm64": "clash-linux-arm64",
  25. };
  26. /* ======= clash meta ======= */
  27. const META_URL_PREFIX = `https://github.com/MetaCubeX/Clash.Meta/releases/download/`;
  28. const META_VERSION = "v1.16.0";
  29. const META_MAP = {
  30. "win32-x64": "clash.meta-windows-amd64-compatible",
  31. "darwin-x64": "clash.meta-darwin-amd64",
  32. "darwin-arm64": "clash.meta-darwin-arm64",
  33. "linux-x64": "clash.meta-linux-amd64-compatible",
  34. "linux-arm64": "clash.meta-linux-arm64",
  35. };
  36. /**
  37. * check available
  38. */
  39. const { platform, arch } = process;
  40. if (!CLASH_MAP[`${platform}-${arch}`]) {
  41. throw new Error(`clash unsupported platform "${platform}-${arch}"`);
  42. }
  43. if (!META_MAP[`${platform}-${arch}`]) {
  44. throw new Error(`clash meta unsupported platform "${platform}-${arch}"`);
  45. }
  46. function clash() {
  47. const name = CLASH_MAP[`${platform}-${arch}`];
  48. const isWin = platform === "win32";
  49. const urlExt = isWin ? "zip" : "gz";
  50. const downloadURL = `${CLASH_URL_PREFIX}${name}-${CLASH_LATEST_DATE}.${urlExt}`;
  51. const exeFile = `${name}${isWin ? ".exe" : ""}`;
  52. const zipFile = `${name}.${urlExt}`;
  53. return {
  54. name: "clash",
  55. targetFile: `clash-${SIDECAR_HOST}${isWin ? ".exe" : ""}`,
  56. exeFile,
  57. zipFile,
  58. downloadURL,
  59. };
  60. }
  61. function clashS3() {
  62. const name = CLASH_MAP[`${platform}-${arch}`];
  63. const isWin = platform === "win32";
  64. const urlExt = isWin ? "zip" : "gz";
  65. const downloadURL = `${CLASH_STORAGE_PREFIX}${CLASH_LATEST_DATE}/${name}-${CLASH_LATEST_DATE}.${urlExt}`;
  66. const exeFile = `${name}${isWin ? ".exe" : ""}`;
  67. const zipFile = `${name}.${urlExt}`;
  68. return {
  69. name: "clash",
  70. targetFile: `clash-${SIDECAR_HOST}${isWin ? ".exe" : ""}`,
  71. exeFile,
  72. zipFile,
  73. downloadURL,
  74. };
  75. }
  76. function clashMeta() {
  77. const name = META_MAP[`${platform}-${arch}`];
  78. const isWin = platform === "win32";
  79. const urlExt = isWin ? "zip" : "gz";
  80. const downloadURL = `${META_URL_PREFIX}${META_VERSION}/${name}-${META_VERSION}.${urlExt}`;
  81. const exeFile = `${name}${isWin ? ".exe" : ""}`;
  82. const zipFile = `${name}-${META_VERSION}.${urlExt}`;
  83. return {
  84. name: "clash-meta",
  85. targetFile: `clash-meta-${SIDECAR_HOST}${isWin ? ".exe" : ""}`,
  86. exeFile,
  87. zipFile,
  88. downloadURL,
  89. };
  90. }
  91. /**
  92. * download sidecar and rename
  93. */
  94. async function resolveSidecar(binInfo) {
  95. const { name, targetFile, zipFile, exeFile, downloadURL } = binInfo;
  96. const sidecarDir = path.join(cwd, "src-tauri", "sidecar");
  97. const sidecarPath = path.join(sidecarDir, targetFile);
  98. await fs.mkdirp(sidecarDir);
  99. if (!FORCE && (await fs.pathExists(sidecarPath))) return;
  100. const tempDir = path.join(TEMP_DIR, name);
  101. const tempZip = path.join(tempDir, zipFile);
  102. const tempExe = path.join(tempDir, exeFile);
  103. await fs.mkdirp(tempDir);
  104. try {
  105. if (!(await fs.pathExists(tempZip))) {
  106. await downloadFile(downloadURL, tempZip);
  107. }
  108. if (zipFile.endsWith(".zip")) {
  109. const zip = new AdmZip(tempZip);
  110. zip.getEntries().forEach((entry) => {
  111. console.log(`[DEBUG]: "${name}" entry name`, entry.entryName);
  112. });
  113. zip.extractAllTo(tempDir, true);
  114. await fs.rename(tempExe, sidecarPath);
  115. console.log(`[INFO]: "${name}" unzip finished`);
  116. } else {
  117. // gz
  118. const readStream = fs.createReadStream(tempZip);
  119. const writeStream = fs.createWriteStream(sidecarPath);
  120. await new Promise((resolve, reject) => {
  121. const onError = (error) => {
  122. console.error(`[ERROR]: "${name}" gz failed:`, error.message);
  123. reject(error);
  124. };
  125. readStream
  126. .pipe(zlib.createGunzip().on("error", onError))
  127. .pipe(writeStream)
  128. .on("finish", () => {
  129. console.log(`[INFO]: "${name}" gunzip finished`);
  130. execSync(`chmod 755 ${sidecarPath}`);
  131. console.log(`[INFO]: "${name}" chmod binary finished`);
  132. resolve();
  133. })
  134. .on("error", onError);
  135. });
  136. }
  137. } catch (err) {
  138. // 需要删除文件
  139. await fs.remove(sidecarPath);
  140. throw err;
  141. } finally {
  142. // delete temp dir
  143. await fs.remove(tempDir);
  144. }
  145. }
  146. /**
  147. * prepare clash core
  148. * if the core version is not updated in time, use S3 storage as a backup.
  149. */
  150. async function resolveClash() {
  151. try {
  152. return await resolveSidecar(clash());
  153. } catch {
  154. console.log(`[WARN]: clash core needs to be updated`);
  155. return await resolveSidecar(clashS3());
  156. }
  157. }
  158. /**
  159. * only Windows
  160. * get the wintun.dll (not required)
  161. */
  162. async function resolveWintun() {
  163. const { platform } = process;
  164. if (platform !== "win32") return;
  165. const url = "https://www.wintun.net/builds/wintun-0.14.1.zip";
  166. const tempDir = path.join(TEMP_DIR, "wintun");
  167. const tempZip = path.join(tempDir, "wintun.zip");
  168. const wintunPath = path.join(tempDir, "wintun/bin/amd64/wintun.dll");
  169. const targetPath = path.join(cwd, "src-tauri/resources", "wintun.dll");
  170. if (!FORCE && (await fs.pathExists(targetPath))) return;
  171. await fs.mkdirp(tempDir);
  172. if (!(await fs.pathExists(tempZip))) {
  173. await downloadFile(url, tempZip);
  174. }
  175. // unzip
  176. const zip = new AdmZip(tempZip);
  177. zip.extractAllTo(tempDir, true);
  178. if (!(await fs.pathExists(wintunPath))) {
  179. throw new Error(`path not found "${wintunPath}"`);
  180. }
  181. await fs.rename(wintunPath, targetPath);
  182. await fs.remove(tempDir);
  183. console.log(`[INFO]: resolve wintun.dll finished`);
  184. }
  185. /**
  186. * download the file to the resources dir
  187. */
  188. async function resolveResource(binInfo) {
  189. const { file, downloadURL } = binInfo;
  190. const resDir = path.join(cwd, "src-tauri/resources");
  191. const targetPath = path.join(resDir, file);
  192. if (!FORCE && (await fs.pathExists(targetPath))) return;
  193. await fs.mkdirp(resDir);
  194. await downloadFile(downloadURL, targetPath);
  195. console.log(`[INFO]: ${file} finished`);
  196. }
  197. /**
  198. * download file and save to `path`
  199. */
  200. async function downloadFile(url, path) {
  201. const options = {};
  202. const httpProxy =
  203. process.env.HTTP_PROXY ||
  204. process.env.http_proxy ||
  205. process.env.HTTPS_PROXY ||
  206. process.env.https_proxy;
  207. if (httpProxy) {
  208. options.agent = proxyAgent(httpProxy);
  209. }
  210. const response = await fetch(url, {
  211. ...options,
  212. method: "GET",
  213. headers: { "Content-Type": "application/octet-stream" },
  214. });
  215. const buffer = await response.arrayBuffer();
  216. await fs.writeFile(path, new Uint8Array(buffer));
  217. console.log(`[INFO]: download finished "${url}"`);
  218. }
  219. /**
  220. * main
  221. */
  222. const SERVICE_URL =
  223. "https://github.com/zzzgydi/clash-verge-service/releases/download/latest";
  224. const resolveService = () =>
  225. resolveResource({
  226. file: "clash-verge-service.exe",
  227. downloadURL: `${SERVICE_URL}/clash-verge-service.exe`,
  228. });
  229. const resolveInstall = () =>
  230. resolveResource({
  231. file: "install-service.exe",
  232. downloadURL: `${SERVICE_URL}/install-service.exe`,
  233. });
  234. const resolveUninstall = () =>
  235. resolveResource({
  236. file: "uninstall-service.exe",
  237. downloadURL: `${SERVICE_URL}/uninstall-service.exe`,
  238. });
  239. const resolveMmdb = () =>
  240. resolveResource({
  241. file: "Country.mmdb",
  242. downloadURL: `https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/country.mmdb`,
  243. });
  244. const resolveGeosite = () =>
  245. resolveResource({
  246. file: "geosite.dat",
  247. downloadURL: `https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geosite.dat`,
  248. });
  249. const resolveGeoIP = () =>
  250. resolveResource({
  251. file: "geoip.dat",
  252. downloadURL: `https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geoip.dat`,
  253. });
  254. const tasks = [
  255. { name: "clash", func: resolveClash, retry: 5 },
  256. { name: "clash-meta", func: () => resolveSidecar(clashMeta()), retry: 5 },
  257. { name: "wintun", func: resolveWintun, retry: 5, winOnly: true },
  258. { name: "service", func: resolveService, retry: 5, winOnly: true },
  259. { name: "install", func: resolveInstall, retry: 5, winOnly: true },
  260. { name: "uninstall", func: resolveUninstall, retry: 5, winOnly: true },
  261. { name: "mmdb", func: resolveMmdb, retry: 5 },
  262. { name: "geosite", func: resolveGeosite, retry: 5 },
  263. { name: "geoip", func: resolveGeoIP, retry: 5 },
  264. ];
  265. async function runTask() {
  266. const task = tasks.shift();
  267. if (!task) return;
  268. if (task.winOnly && process.platform !== "win32") return runTask();
  269. for (let i = 0; i < task.retry; i++) {
  270. try {
  271. await task.func();
  272. break;
  273. } catch (err) {
  274. console.error(`[ERROR]: task::${task.name} try ${i} ==`, err.message);
  275. if (i === task.retry - 1) throw err;
  276. }
  277. }
  278. return runTask();
  279. }
  280. runTask();
  281. runTask();