Skip to content

Commit

Permalink
Правки по ProgressHelper и MirrorManager
Browse files Browse the repository at this point in the history
  • Loading branch information
JoCat committed Aug 3, 2020
1 parent fcba600 commit f592a63
Show file tree
Hide file tree
Showing 5 changed files with 118 additions and 127 deletions.
84 changes: 25 additions & 59 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,19 @@
"start": "node dist/LauncherServer.js"
},
"devDependencies": {
"@types/cli-progress": "^3.7.0",
"@types/decompress": "^4.2.3",
"@types/node": "^12.12.21",
"@types/progress-stream": "^2.0.0",
"@types/rimraf": "^3.0.0",
"@types/semver": "^7.3.1",
"@types/ws": "^7.2.6",
"cli-progress": "^3.8.2",
"colors": "^1.4.0",
"cross-env": "^7.0.2",
"decompress": "^4.2.1",
"import-sort-style-module": "^6.0.0",
"prettier": "^2.0.5",
"prettier-plugin-import-sort": "0.0.4",
"progress-stream": "^2.0.0",
"rimraf": "^3.0.2",
"semver": "^7.3.2",
"source-map-support": "^0.5.19",
Expand Down
48 changes: 0 additions & 48 deletions src/main/helpers/ProgressBarHelper.ts

This file was deleted.

79 changes: 79 additions & 0 deletions src/main/helpers/ProgressHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import * as progress from "progress-stream"

export class ProgressHelper {
static barCompleteChar: string = "\u2588"
static barIncompleteChar: string = "\u2591"
static barsize: number = 20

static getLoadingProgressBar(options: progress.Options) {
return this.getProgress(options, ProgressType.LOADING)
}

static getDownloadProgressBar(options: progress.Options) {
return this.getProgress(options, ProgressType.DOWNLOAD)
}

private static getProgress(options: progress.Options, type: ProgressType) {
let info = progress(options)
process.stdout.write('\x1B[?25l') // Hide cursor
info.on('progress', progress => {
process.stdout.clearLine(0)
process.stdout.cursorTo(0)
switch (type) {
case ProgressType.LOADING:
process.stdout.write(this.getLoadingProgressTemplate(progress))
break;
case ProgressType.DOWNLOAD:
process.stdout.write(this.getDownloadProgressTemplate(progress))
break;
}
})
info.on('end', () => {
process.stdout.clearLine(0)
process.stdout.cursorTo(0)
process.stdout.write('\x1B[?25h') // Show cursor
})
return info
}

private static getLoadingProgressTemplate(progress: progress.Progress) {
const string = "{bar} {percent}%" // Для выноса потом в lang файлы
return string
.replace("{bar}", this.getBar(progress.percentage))
.replace("{percent}", progress.percentage.toFixed(2))
}

private static getDownloadProgressTemplate(progress: progress.Progress) {
const string = "{bar} {percent}% Осталось: {eta}s | Скорость: {speed}/s {transferred}/{total}" // Аналогично
return string
.replace("{bar}", this.getBar(progress.percentage))
.replace("{percent}", progress.percentage.toFixed(2))
.replace("{eta}", progress.eta.toString())
.replace("{speed}", this.bytesToSize(progress.speed))
.replace("{transferred}", this.bytesToSize(progress.transferred))
.replace("{total}", this.bytesToSize(progress.length))
}

private static getBar(percentage: number): string {
// calculate barsize
const completeSize = Math.round(percentage / 100 * this.barsize)
const incompleteSize = this.barsize - completeSize

// generate bar string by stripping the pre-rendered strings
return this.barCompleteChar.repeat(completeSize)
+ this.barIncompleteChar.repeat(incompleteSize)
}

private static bytesToSize(bytes: number): string {
const sizes = ["Bytes", "KB", "MB"]
if (bytes === 0) return "n/a"
const i = Math.floor(Math.log(bytes) / Math.log(1024))
if (i === 0) return `${bytes} ${sizes[i]})`
return `${(bytes / 1024 ** i).toFixed(2)} ${sizes[i]}`
}
}

export enum ProgressType {
DOWNLOAD,
LOADING
}
30 changes: 12 additions & 18 deletions src/main/mirror/MirrorManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import * as decompress from "decompress"
import * as rimraf from "rimraf"

import { LogHelper } from "../helpers/LogHelper"
import { ProgressBarHelper } from "../helpers/ProgressBarHelper"
import { ProgressHelper } from "../helpers/ProgressHelper"
import { StorageHelper } from "../helpers/StorageHelper"
import { App } from "../LauncherServer"

Expand Down Expand Up @@ -47,7 +47,7 @@ export class MirrorManager {

try {
LogHelper.info("Клиент найден, загрузка...")
profile = await this.downloadFile(new URL(`/clients/${clientName}.json`, mirror), false)
profile = await this.downloadFile(new URL(`/clients/${clientName}.json`, mirror))
client = await this.downloadFile(new URL(`/clients/${clientName}.zip`, mirror))
} catch (error) {
LogHelper.error("Ошибка при загрузке клиента!")
Expand Down Expand Up @@ -124,27 +124,21 @@ export class MirrorManager {
App.CommandsManager.console.resume()
}

downloadFile(url: URL, showProgress: boolean = true): Promise<string> {
downloadFile(url: URL): Promise<string> {
const handler = url.protocol === "https:" ? https : http
const tempFilename = path.resolve(StorageHelper.tempDir, randomBytes(16).toString("hex"))
const tempFile = fs.createWriteStream(tempFilename)

return new Promise((resolve, reject) => {
handler
.get(url, (res) => {
res.pipe(tempFile)
if (showProgress) {
let downloaded = 0
const progressBar = ProgressBarHelper.getDownloadProgressBar()
progressBar.start(parseInt(res.headers["content-length"], 10), 0)
res.on("data", (chunk) => {
downloaded += chunk.length
progressBar.update(downloaded)
})
res.on("end", () => {
progressBar.stop()
})
}
.get(url, res => {
res
.pipe(
ProgressHelper.getDownloadProgressBar({
length: parseInt(res.headers["content-length"], 10)
})
)
.pipe(tempFile)
res.on("end", () => {
resolve(tempFilename)
})
Expand All @@ -160,7 +154,7 @@ export class MirrorManager {
const handler = url.protocol === "https:" ? https : http
return new Promise((resolve) => {
handler
.request(url, { method: "HEAD" }, (res) => {
.request(url, { method: "HEAD" }, res => {
return new RegExp(/2[\d]{2}/).test(res.statusCode.toString()) ? resolve(true) : resolve(false)
})
.on("error", (err) => {
Expand Down

0 comments on commit f592a63

Please sign in to comment.