Skip to content

Commit

Permalink
feat: Adding download-progress event to AutoUpdater (#1042)
Browse files Browse the repository at this point in the history
Closes #958
  • Loading branch information
badams authored and develar committed Dec 28, 2016
1 parent 96895cf commit b3a0be0
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 4 deletions.
9 changes: 8 additions & 1 deletion nsis-auto-updater/src/NsisUpdater.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,13 @@ export class NsisUpdater extends EventEmitter {
async downloadUpdate() {
const versionInfo = this.versionInfo
const fileInfo = this.fileInfo
const downloadOptions: any = {
onProgress: (progress: any) => this.emit("download-progress", {}, progress)
}

if (fileInfo && fileInfo.sha2) {
downloadOptions["sha2"] = fileInfo.sha2
}

if (versionInfo == null || fileInfo == null) {
const message = "Please check update first"
Expand All @@ -157,7 +164,7 @@ export class NsisUpdater extends EventEmitter {
}

return mkdtemp(`${path.join(tmpdir(), "up")}-`)
.then(it => download(fileInfo.url, path.join(it, fileInfo.name), fileInfo.sha2 == null ? null : {sha2: fileInfo.sha2}))
.then(it => download(fileInfo.url, path.join(it, fileInfo.name), downloadOptions))
.then(it => {
this.setupPath = it
this.addQuitHandler()
Expand Down
14 changes: 12 additions & 2 deletions nsis-auto-updater/src/electronHttpExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { net } from "electron"
import { createWriteStream, ensureDir } from "fs-extra-p"
import BluebirdPromise from "bluebird-lst-c"
import * as path from "path"
import { HttpExecutor, DownloadOptions, HttpError, DigestTransform, checkSha2 } from "../../src/util/httpExecutor"
import { HttpExecutor, DownloadOptions, HttpError, DigestTransform, checkSha2, calculateDownloadProgress } from "../../src/util/httpExecutor"
import { Url } from "url"
import { safeLoad } from "js-yaml"
import _debug from "debug"
Expand Down Expand Up @@ -69,7 +69,7 @@ export class ElectronHttpExecutor implements HttpExecutor {
// user-agent must be specified, otherwise some host can return 401 unauthorised

//FIXME hack, the electron typings specifies Protocol with capital but the code actually uses with small case
const requestOpts = {
const requestOpts = {
protocol: parsedUrl.protocol,
hostname: parsedUrl.hostname,
path: parsedUrl.path,
Expand Down Expand Up @@ -99,6 +99,16 @@ export class ElectronHttpExecutor implements HttpExecutor {
return
}

if (options.onProgress != null) {
const total = parseInt(String(safeGetHeader(response, "content-length")), 10)
const start = Date.now()
let transferred = 0

response.on("data", (chunk: any) => {
transferred = calculateDownloadProgress(total, start, transferred, chunk, options.onProgress)
})
}

ensureDirPromise
.then(() => {
const fileOut = createWriteStream(destination)
Expand Down
12 changes: 12 additions & 0 deletions src/util/httpExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Transform } from "stream"
export interface DownloadOptions {
skipDirCreation?: boolean
sha2?: string
onProgress?(progress: any): void
}

export class HttpExecutorHolder {
Expand Down Expand Up @@ -75,4 +76,15 @@ export function checkSha2(sha2Header: string | null | undefined, sha2: string |
}
}
return true
}

export function calculateDownloadProgress(total: number, start: number, transferred: number, chunk: any, callback: any): number {
transferred += chunk.length
callback({
total: total,
transferred: transferred,
percent: ((transferred / total) * 100).toFixed(2),
bytesPerSecond: Math.round(transferred / ((Date.now() - start) / 1000))
})
return transferred
}
14 changes: 13 additions & 1 deletion src/util/nodeHttpExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import BluebirdPromise from "bluebird-lst-c"
import * as path from "path"
import { homedir } from "os"
import { parse as parseIni } from "ini"
import { HttpExecutor, DownloadOptions, HttpError, DigestTransform, checkSha2 } from "./httpExecutor"
import { HttpExecutor, DownloadOptions, HttpError, DigestTransform, checkSha2, calculateDownloadProgress} from "./httpExecutor"
import { Url } from "url"
import { RequestOptions } from "https"
import { safeLoad } from "js-yaml"
Expand Down Expand Up @@ -95,6 +95,18 @@ export class NodeHttpExecutor implements HttpExecutor {
return
}

if (options.onProgress != null) {
const total = parseInt(response.headers["content-length"], 10)
const start = Date.now()
let transferred = 0

response.on("data", (chunk: any) => {
transferred = calculateDownloadProgress(total, start, transferred, chunk, options.onProgress)
})

response.pause()
}

ensureDirPromise
.then(() => {
const fileOut = createWriteStream(destination)
Expand Down
29 changes: 29 additions & 0 deletions test/src/nsisUpdaterTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,35 @@ test("test error", async () => {
expect(actualEvents).toMatchSnapshot()
})

test("test download progress", async () => {
const tmpDir = new TmpDir()
const testResourcesPath = await tmpDir.getTempFile("update-config")
await outputFile(path.join(testResourcesPath, "app-update.yml"), safeDump(<GenericServerOptions>{
provider: "generic",
url: "https://develar.s3.amazonaws.com/test",
}))
g.__test_resourcesPath = testResourcesPath
const updater: NsisUpdater = new NsisUpdaterClass()
updater.autoDownload = false

const progressEvents: Array<any> = []

updater.addListener("download-progress", (e: any, progress: any) => {
progressEvents.push(progress)
})

await updater.checkForUpdates()
await updater.downloadUpdate()

expect(progressEvents.length).toBeGreaterThanOrEqual(1)

const lastEvent = progressEvents.pop()

expect(parseInt(lastEvent.percent, 10)).toBe(100)
expect(lastEvent.bytesPerSecond).toBeGreaterThan(1)
expect(lastEvent.transferred).toBe(lastEvent.total)
})

function trackEvents(updater: NsisUpdater) {
const actualEvents: Array<string> = []
for (const eventName of ["checking-for-update", "update-available", "update-downloaded", "error"]) {
Expand Down

0 comments on commit b3a0be0

Please sign in to comment.