import { Injectable , EventEmitter } from '@angular/core' ; import { ElectronService } from './electron.service' ; import { NewDownload , DownloadProgress } from '../../../electron/shared/interfaces/download.interface' ; @ Injectable ( { providedIn : 'root' } ) export class DownloadService { private downloadUpdatedEmitter = new EventEmitter < DownloadProgress > ( ) ; private downloads : DownloadProgress [ ] = [ ] ; constructor ( private electronService ) { this . electronService . receiveIPC ( 'download-updated' , result => { const thisDownloadIndex = this . downloads . findIndex ( download => download . versionID == result . versionID ) ; if ( result . type == 'cancel' ) { this . downloads = this . downloads . filter ( download => download . versionID != result . versionID ) ; } else if ( thisDownloadIndex == - 1 ) { this . downloads . push ( result ) ; } else { this . downloads [ thisDownloadIndex ] = result ; } this . downloadUpdatedEmitter . emit ( result ) ; } ) ; } get downloadCount ( ) { return this . downloads . length ; } get completedCount ( ) { return this . downloads . filter ( download => download . type == 'done' ) . length ; } get totalDownloadingPercent ( ) { let total = 0 ; let count = 0 ; for ( const download of this . downloads ) { if ( ! download . stale ) { total += download . percent ; count ++ ; } } return total / count ; } get anyErrorsExist ( ) { return this . downloads . find ( download => download . type == 'error' ) ? true : false ; } addDownload ( versionID , newDownload ) { if ( ! this . downloads . find ( download => download . versionID == versionID ) ) { if ( this . downloads . every ( download => download . type == 'done' ) ) { this . downloads . forEach ( download => download . stale = true ) ; } this . electronService . sendIPC ( 'download' , { action : 'add' , versionID , data : newDownload } ) ; } } onDownloadUpdated ( callback ) { this . downloadUpdatedEmitter . subscribe ( callback ) ; } cancelDownload ( versionID ) { const removedDownload = this . downloads . find ( download => download . versionID == versionID ) ; if ( [ 'error' , 'done' ] . includes ( removedDownload . type ) ) { this . downloads = this . downloads . filter ( download => download . versionID != versionID ) ; removedDownload . type = 'cancel' ; this . downloadUpdatedEmitter . emit ( removedDownload ) ; } else { this . electronService . sendIPC ( 'download' , { action : 'cancel' , versionID } ) ; } } cancelCompleted ( ) { for ( const download of this . downloads ) { if ( download . type == 'done' ) { this . cancelDownload ( download . versionID ) ; } } } retryDownload ( versionID ) { this . electronService . sendIPC ( 'download' , { action : 'retry' , versionID } ) ; } }