check.mjs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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.06.30";
  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-armv8",
  25. };
  26. /* ======= clash meta ======= */
  27. const META_URL_PREFIX = `https://github.com/MetaCubeX/Clash.Meta/releases/download/`;
  28. const META_VERSION = "v1.15.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. if (zipFile.endsWith(".zip")) {
  108. const zip = new AdmZip(tempZip);
  109. zip.getEntries().forEach((entry) => {
  110. console.log(`[DEBUG]: "${name}" entry name`, entry.entryName);
  111. });
  112. zip.extractAllTo(tempDir, true);
  113. await fs.rename(tempExe, sidecarPath);
  114. console.log(`[INFO]: "${name}" unzip finished`);
  115. } else {
  116. // gz
  117. const readStream = fs.createReadStream(tempZip);
  118. const writeStream = fs.createWriteStream(sidecarPath);
  119. await new Promise((resolve, reject) => {
  120. const onError = (error) => {
  121. console.error(`[ERROR]: "${name}" gz failed`, error.message);
  122. reject(error);
  123. };
  124. readStream
  125. .pipe(zlib.createGunzip().on("error", onError))
  126. .pipe(writeStream)
  127. .on("finish", () => {
  128. console.log(`[INFO]: "${name}" gunzip finished`);
  129. execSync(`chmod 755 ${sidecarPath}`);
  130. console.log(`[INFO]: "${name}" chmod binary finished`);
  131. resolve();
  132. })
  133. .on("error", onError);
  134. });
  135. }
  136. } catch (err) {
  137. throw err;
  138. } finally {
  139. // delete temp dir
  140. await fs.remove(tempDir);
  141. }
  142. }
  143. /**
  144. * prepare clash core
  145. * if the core version is not updated in time, use S3 storage as a backup.
  146. */
  147. async function resolveClash() {
  148. try {
  149. return await resolveSidecar(clash());
  150. } catch {
  151. console.log(`[WARN]: clash core needs to be updated`);
  152. return await resolveSidecar(clashS3());
  153. }
  154. }
  155. /**
  156. * only Windows
  157. * get the wintun.dll (not required)
  158. */
  159. async function resolveWintun() {
  160. const { platform } = process;
  161. if (platform !== "win32") return;
  162. const url = "https://www.wintun.net/builds/wintun-0.14.1.zip";
  163. const tempDir = path.join(TEMP_DIR, "wintun");
  164. const tempZip = path.join(tempDir, "wintun.zip");
  165. const wintunPath = path.join(tempDir, "wintun/bin/amd64/wintun.dll");
  166. const targetPath = path.join(cwd, "src-tauri/resources", "wintun.dll");
  167. if (!FORCE && (await fs.pathExists(targetPath))) return;
  168. await fs.mkdirp(tempDir);
  169. if (!(await fs.pathExists(tempZip))) {
  170. await downloadFile(url, tempZip);
  171. }
  172. // unzip
  173. const zip = new AdmZip(tempZip);
  174. zip.extractAllTo(tempDir, true);
  175. if (!(await fs.pathExists(wintunPath))) {
  176. throw new Error(`path not found "${wintunPath}"`);
  177. }
  178. await fs.rename(wintunPath, targetPath);
  179. await fs.remove(tempDir);
  180. console.log(`[INFO]: resolve wintun.dll finished`);
  181. }
  182. /**
  183. * download the file to the resources dir
  184. */
  185. async function resolveResource(binInfo) {
  186. const { file, downloadURL } = binInfo;
  187. const resDir = path.join(cwd, "src-tauri/resources");
  188. const targetPath = path.join(resDir, file);
  189. if (!FORCE && (await fs.pathExists(targetPath))) return;
  190. await fs.mkdirp(resDir);
  191. await downloadFile(downloadURL, targetPath);
  192. console.log(`[INFO]: ${file} finished`);
  193. }
  194. /**
  195. * download file and save to `path`
  196. */
  197. async function downloadFile(url, path) {
  198. const options = {};
  199. const httpProxy =
  200. process.env.HTTP_PROXY ||
  201. process.env.http_proxy ||
  202. process.env.HTTPS_PROXY ||
  203. process.env.https_proxy;
  204. if (httpProxy) {
  205. options.agent = proxyAgent(httpProxy);
  206. }
  207. const response = await fetch(url, {
  208. ...options,
  209. method: "GET",
  210. headers: { "Content-Type": "application/octet-stream" },
  211. });
  212. const buffer = await response.arrayBuffer();
  213. await fs.writeFile(path, new Uint8Array(buffer));
  214. console.log(`[INFO]: download finished "${url}"`);
  215. }
  216. /**
  217. * main
  218. */
  219. const SERVICE_URL =
  220. "https://github.com/zzzgydi/clash-verge-service/releases/download/latest";
  221. const resolveService = () =>
  222. resolveResource({
  223. file: "clash-verge-service.exe",
  224. downloadURL: `${SERVICE_URL}/clash-verge-service.exe`,
  225. });
  226. const resolveInstall = () =>
  227. resolveResource({
  228. file: "install-service.exe",
  229. downloadURL: `${SERVICE_URL}/install-service.exe`,
  230. });
  231. const resolveUninstall = () =>
  232. resolveResource({
  233. file: "uninstall-service.exe",
  234. downloadURL: `${SERVICE_URL}/uninstall-service.exe`,
  235. });
  236. const resolveMmdb = () =>
  237. resolveResource({
  238. file: "Country.mmdb",
  239. downloadURL: `https://github.com/Dreamacro/maxmind-geoip/releases/download/20221112/Country.mmdb`,
  240. });
  241. const resolveGeosite = () =>
  242. resolveResource({
  243. file: "geosite.dat",
  244. downloadURL: `https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat`,
  245. });
  246. const resolveGeoIP = () =>
  247. resolveResource({
  248. file: "geoip.dat",
  249. downloadURL: `https://github.com/Loyalsoldier/geoip/releases/latest/download/geoip.dat`,
  250. });
  251. const tasks = [
  252. { name: "clash", func: resolveClash, retry: 5 },
  253. { name: "clash-meta", func: () => resolveSidecar(clashMeta()), retry: 5 },
  254. { name: "wintun", func: resolveWintun, retry: 5, winOnly: true },
  255. { name: "service", func: resolveService, retry: 5, winOnly: true },
  256. { name: "install", func: resolveInstall, retry: 5, winOnly: true },
  257. { name: "uninstall", func: resolveUninstall, retry: 5, winOnly: true },
  258. { name: "mmdb", func: resolveMmdb, retry: 5 },
  259. { name: "geosite", func: resolveGeosite, retry: 5 },
  260. { name: "geoip", func: resolveGeoIP, retry: 5 },
  261. ];
  262. async function runTask() {
  263. const task = tasks.shift();
  264. if (!task) return;
  265. if (task.winOnly && process.platform !== "win32") return runTask();
  266. for (let i = 0; i < task.retry; i++) {
  267. try {
  268. await task.func();
  269. break;
  270. } catch (err) {
  271. console.error(`[ERROR]: task::${task.name} try ${i} == `, err.message);
  272. }
  273. }
  274. return runTask();
  275. }
  276. runTask();
  277. runTask();