Skip to content

Commit

Permalink
Fixed bug while node-fetch library is missing inside builded binaries
Browse files Browse the repository at this point in the history
  • Loading branch information
opengs committed Sep 11, 2023
1 parent 1da3f57 commit b4836fb
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 35 deletions.
51 changes: 16 additions & 35 deletions lib/module/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import { ChildProcessWithoutNullStreams, spawn } from 'child_process'
import { EventEmitter } from 'stream'
import path from 'path'
import { app } from 'electron'
import fs from 'fs'
import fetch from 'electron-fetch'
import decompress from 'decompress'

export type ModuleName = 'DB1000N' | 'DISTRESS' | 'MHDDOS_PROXY'

Expand Down Expand Up @@ -113,23 +116,18 @@ export abstract class Module<ConfigType extends BaseConfig> {
abstract getAllVersions(): Promise<Version[]>
abstract installVersion(versionTag: string): AsyncGenerator<InstallProgress, void, void>
public async uninstallVersion (versionTag: string): Promise<void> {
// Import here to make file compatible with frontend
const fs = (await import('fs')).promises
await fs.rmdir(path.join(this.installationDirectory, versionTag), { recursive: true })
await fs.promises.rmdir(path.join(this.installationDirectory, versionTag), { recursive: true })
}

protected async *installVersionFromGithub (owner: string, repo: string, tag: string, assetMapping: Array<{ name: string, arch: 'x64' | 'arm64' | 'ia32', platform: 'linux' | 'win32' | 'darwin' }>): AsyncGenerator<InstallProgress, void, void> {
// Import here to make file compatible with frontend
const fetch = await import('node-fetch')

interface GithubRelease {
assets: Array<{ name: string, browser_download_url: string }>
}

let release: GithubRelease
try {
console.log(`Fetching github release: https://api.github.com/repos/${owner}/${repo}/releases/tags/${tag}`)
const releaseResponse = await fetch.default(`https://api.github.com/repos/${owner}/${repo}/releases/tags/${tag}`)
const releaseResponse = await fetch(`https://api.github.com/repos/${owner}/${repo}/releases/tags/${tag}`)
if (releaseResponse.status !== 200) {
yield { stage: 'FAILED', progress: 0, errorCode: InstallationErrorCodes.UNKNOWN, errorMessage: `Cant fetch github release: ${await releaseResponse.text()}` }
return
Expand Down Expand Up @@ -180,21 +178,18 @@ export abstract class Module<ConfigType extends BaseConfig> {
private githubReleaseCache = [] as { tag_name: string, name: string, body: string }[]
private githubReleaseCacheTime?: Date
protected async loadVersionsFromGithub (owner: string, repo: string): Promise<Version[]> {
// Import here to make file compatible with frontend
const fetch = await import('node-fetch')
const fs = (await import('fs')).promises

const isVersionInstalled = async (tagName: string) => {
return await new Promise<boolean>((resolve) => {
fs.access(path.join(this.installationDirectory, tagName))
fs.promises.access(path.join(this.installationDirectory, tagName))
.then(() => resolve(true))
.catch(() => resolve(false))
})
}

//Cache github releases for 5 minutes in order to ommit Gihub API rate limit
if (this.githubReleaseCacheTime === undefined || this.githubReleaseCacheTime.getTime() + 5 * 60 * 1000 > new Date().getTime()) {
const response = await fetch.default(`https://api.github.com/repos/${owner}/${repo}/releases`)
const response = await fetch(`https://api.github.com/repos/${owner}/${repo}/releases`)
if (response.status !== 200) {
throw new Error(`Cant fetch github releases: ${await response.text()}`)
}
Expand All @@ -213,11 +208,7 @@ export abstract class Module<ConfigType extends BaseConfig> {
}

protected async *downloadFile (url: string, outPath: string): AsyncGenerator<{progress: number}, void, void> {
// Import here to make file compatible with frontend
const fetch = await import('node-fetch')
const fs = await import('fs')

const response = await fetch.default(url)
const response = await fetch(url)
const fileStream = fs.createWriteStream(outPath)
const contentLengthHeader = response.headers.get('content-length')
if (contentLengthHeader == null) {
Expand Down Expand Up @@ -268,31 +259,27 @@ export abstract class Module<ConfigType extends BaseConfig> {
}

protected async extractArchive (archivePath: string, outPath: string, deleteSource = true): Promise<void> {
// Import here to make file compatible with frontend
const fs = (await import('fs')).promises
const decompress = (await import('decompress')).default

try {
const directoryExist = await new Promise<boolean>((resolve) => {
fs.access(outPath)
fs.promises.access(outPath)
.then(() => resolve(true))
.catch(() => resolve(false))
})
if (!directoryExist) {
await fs.mkdir(outPath, { recursive: true })
await fs.promises.mkdir(outPath, { recursive: true })
}

if (archivePath.endsWith('.zip') || archivePath.endsWith('.tar.gz')) {
await decompress(archivePath, outPath)
} else {
await fs.copyFile(archivePath, path.join(outPath, path.basename(archivePath)))
await fs.promises.copyFile(archivePath, path.join(outPath, path.basename(archivePath)))
if (process.platform !== 'win32') {
await fs.chmod(path.join(outPath, path.basename(archivePath)), "775") // Make executable
await fs.promises.chmod(path.join(outPath, path.basename(archivePath)), "775") // Make executable
}
}
} finally {
if (deleteSource) {
await fs.unlink(archivePath)
await fs.promises.unlink(archivePath)
}
}
}
Expand Down Expand Up @@ -373,25 +360,19 @@ export abstract class Module<ConfigType extends BaseConfig> {
}

protected async loadConfig (): Promise<void> {
// Import here to make file compatible with frontend
const fs = (await import('fs')).promises

const configFilePath = path.join(this.installationDirectory, 'config.json')
try {
const configDump = await fs.readFile(configFilePath, { encoding: 'utf-8' })
const configDump = await fs.promises.readFile(configFilePath, { encoding: 'utf-8' })
const config = JSON.parse(configDump) as ConfigType
this._config = config
} catch (err) {}
}

protected async saveConfig(config: ConfigType): Promise<void> {
// Import here to make file compatible with frontend
const fs = (await import('fs')).promises

const configDump = JSON.stringify(config)
const configFilePath = path.join(this.installationDirectory, 'config.json')

await fs.mkdir(this.installationDirectory, { recursive: true })
await fs.writeFile(configFilePath, configDump, { encoding: 'utf-8' })
await fs.promises.mkdir(this.installationDirectory, { recursive: true })
await fs.promises.writeFile(configFilePath, configDump, { encoding: 'utf-8' })
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"dependencies": {
"@quasar/extras": "^1.16.4",
"decompress": "^4.2.1",
"electron-fetch": "^1.9.1",
"node-fetch": "^3.3.2",
"pinia": "^2.0.11",
"quasar": "^2.6.0",
Expand Down
14 changes: 14 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1793,6 +1793,13 @@ electron-builder@^24.3.0:
simple-update-notifier "2.0.0"
yargs "^17.6.2"

electron-fetch@^1.9.1:
version "1.9.1"
resolved "https://registry.yarnpkg.com/electron-fetch/-/electron-fetch-1.9.1.tgz#e28bfe78d467de3f2dec884b1d72b8b05322f30f"
integrity sha512-M9qw6oUILGVrcENMSRRefE1MbHPIz0h79EKIeJWK9v563aT9Qkh8aEHPO1H5vi970wPirNY+jO9OpFoLiMsMGA==
dependencies:
encoding "^0.1.13"

electron-packager@^17.1.1:
version "17.1.2"
resolved "https://registry.yarnpkg.com/electron-packager/-/electron-packager-17.1.2.tgz#18030b28024d242b706d0a8a67ed4cd1a57311aa"
Expand Down Expand Up @@ -1862,6 +1869,13 @@ encodeurl@~1.0.2:
resolved "https://registry.yarnpkg.com/encodeurl/-/encodeurl-1.0.2.tgz#ad3ff4c86ec2d029322f5a02c3a9a606c95b3f59"
integrity sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==

encoding@^0.1.13:
version "0.1.13"
resolved "https://registry.yarnpkg.com/encoding/-/encoding-0.1.13.tgz#56574afdd791f54a8e9b2785c0582a2d26210fa9"
integrity sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==
dependencies:
iconv-lite "^0.6.2"

end-of-stream@^1.0.0, end-of-stream@^1.1.0, end-of-stream@^1.4.1:
version "1.4.4"
resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.4.tgz#5ae64a5f45057baf3626ec14da0ca5e4b2431eb0"
Expand Down

0 comments on commit b4836fb

Please sign in to comment.