import ProgressBar from 'electron-progressbar' ; import { ProgressInfo } from 'electron-builder' ; import { app , BrowserWindow } from 'electron' ; import log from 'electron-log' ; export class UpdateProgressBar { private progressBar : ProgressBar ; private get innerProgressBarWindow ( ) : BrowserWindow { return this . progressBar . _window ; } private showingProgress = false ; public showIndeterminateState ( ) { this . progressBar ?. close ( ) ; this . progressBar = progressBarFactory . createWithIndeterminateState ( ) ; } public showProgress ( progress ) { const percentage = getUpdatePercent ( progress ) ; this . showPercentage ( percentage ) ; } public showPercentage ( percentage ) { if ( ! this . showingProgress ) { this . progressBar ?. close ( ) ; this . showingProgress = true ; this . progressBar = progressBarFactory . createWithPercentile ( percentage ) ; } else { this . progressBar . value = percentage ; } } public showError ( e ) { const reportUpdateError = ( ) => { this . progressBar . detail = 'An error occurred while fetching updates.' + `\n${ e && e . message ? e . message : e }` ; this . innerProgressBarWindow . setClosable ( true ) ; } ; if ( this . progressBar . innerProgressBarWindow ) { reportUpdateError ( ) ; } else { this . progressBar . on ( 'ready' , ( ) => reportUpdateError ( ) ) ; } } public close ( ) { if ( ! this . progressBar . isCompleted ( ) ) { this . progressBar . close ( ) ; } } } function getUpdatePercent ( progress ) { let { percent } = progress ; if ( percent ) { percent = Math . round ( percent * 100 ) / 100 ; } return percent ; } const progressBarFactory = { createWithIndeterminateState : ( ) => { return new ProgressBar ( { title : `${ app . name } Update` , text : `Downloading ${ app . name } update...` , } ) ; } , createWithPercentile : ( initialPercentage ) => { const progressBar = new ProgressBar ( { indeterminate : false , title : `${ app . name } Update` , text : `Downloading ${ app . name } update...` , detail : `${ initialPercentage }% ...` , initialValue : initialPercentage , } ) ; progressBar . on ( 'completed' , ( ) => { progressBar . detail = 'Download completed.' ; } ) . on ( 'aborted' , ( value ) => { log . info ( `progress aborted... ${ value }` ) ; } ) . on ( 'progress' , ( value ) => { progressBar . detail = `${ value }% ...` ; } ) . on ( 'ready' , ( ) => { progressBar . value = initialPercentage ; } ) ; return progressBar ; } , } ;