installEditor.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. import http from "https"
  2. import { chmodSync, createWriteStream, existsSync, fstat, mkdirSync, readFileSync, unlink } from "fs"
  3. import { homedir } from "os"
  4. import path, { dirname } from "path"
  5. import AdmZip from "adm-zip"
  6. import { fileURLToPath } from "url"
  7. function download(url, dest) {
  8. console.log(`Fetching ${url}`)
  9. return new Promise((resolve, reject) => {
  10. var file = createWriteStream(dest);
  11. try {
  12. http.get(url, function (response) {
  13. const { statusCode } = response
  14. if (statusCode !== 200) {
  15. throw new Error("Network error downloading " + url)
  16. }
  17. response
  18. .pipe(file)
  19. .on("error", () => {
  20. unlink(file)
  21. throw new Error("Cannot write to file")
  22. })
  23. file.on("finish", function () {
  24. resolve()
  25. }).on("error", () => {
  26. unlink(file)
  27. throw new Error("Cannot write to file")
  28. })
  29. });
  30. } catch (e) {
  31. reject(e)
  32. }
  33. })
  34. }
  35. export async function installEditor() {
  36. const __filename = fileURLToPath(import.meta.url)
  37. const __dirname = dirname(__filename)
  38. const config = JSON.parse(readFileSync(path.join(__dirname, "package.json")))
  39. const ver = config.version
  40. // compute metadata
  41. let platform = {
  42. "darwin": "macos",
  43. "linux": "linux",
  44. "win32": "windows"
  45. }[process.platform]
  46. if (process.arch === "arm64") {
  47. platform += "_arm";
  48. }
  49. const distName = `PhaserEditor2D-core-${ver}-${platform}`
  50. const fileName = `${distName}.zip`
  51. // create install dir
  52. const home = homedir()
  53. const installsDir = path.join(home, ".phasereditor2d", "installs")
  54. const distInstallDir = path.join(installsDir, distName)
  55. const execFile = path.join(distInstallDir, "PhaserEditor2D",
  56. `PhaserEditor2D${platform === "windows" ? ".exe" : ""}`)
  57. if (existsSync(execFile)) {
  58. return execFile
  59. }
  60. mkdirSync(installsDir, { recursive: true })
  61. // download
  62. const outputFile = path.join(installsDir, fileName)
  63. if (!existsSync(outputFile)) {
  64. const updatesUrl = "https://updates.phasereditor2d.com"
  65. const fileUrl = `${updatesUrl}/v${ver}/PhaserEditor2D-core-${ver}-${platform}.zip`
  66. await download(fileUrl, outputFile)
  67. }
  68. // unzip
  69. console.log(`Unzipping ${outputFile}`)
  70. mkdirSync(distInstallDir, { recursive: true })
  71. const zip = new AdmZip(outputFile)
  72. zip.extractAllTo(distInstallDir, true)
  73. if (platform !== "windows") {
  74. chmodSync(execFile, "777");
  75. }
  76. // TODO check md5sum
  77. return execFile
  78. }