2017-09-28 19:18:12 -04:00
|
|
|
/**
|
|
|
|
* @license
|
|
|
|
* Copyright Google Inc. All Rights Reserved.
|
|
|
|
*
|
|
|
|
* Use of this source code is governed by an MIT-style license that can be
|
|
|
|
* found in the LICENSE file at https://angular.io/license
|
|
|
|
*/
|
|
|
|
|
|
|
|
import {Injectable} from '@angular/core';
|
2018-02-27 17:06:06 -05:00
|
|
|
import {NEVER, Observable} from 'rxjs';
|
2017-09-28 19:18:12 -04:00
|
|
|
|
2017-11-30 11:22:41 -05:00
|
|
|
import {ERR_SW_NOT_SUPPORTED, NgswCommChannel, UpdateActivatedEvent, UpdateAvailableEvent} from './low_level';
|
2017-09-28 19:18:12 -04:00
|
|
|
|
|
|
|
|
2018-02-27 17:06:06 -05:00
|
|
|
|
2017-09-28 19:18:12 -04:00
|
|
|
/**
|
|
|
|
* Subscribe to update notifications from the Service Worker, trigger update
|
|
|
|
* checks, and forcibly activate updates.
|
|
|
|
*
|
|
|
|
* @experimental
|
|
|
|
*/
|
|
|
|
@Injectable()
|
|
|
|
export class SwUpdate {
|
|
|
|
readonly available: Observable<UpdateAvailableEvent>;
|
|
|
|
readonly activated: Observable<UpdateActivatedEvent>;
|
|
|
|
|
|
|
|
constructor(private sw: NgswCommChannel) {
|
2017-11-30 11:22:41 -05:00
|
|
|
if (!sw.isEnabled) {
|
2018-02-27 17:06:06 -05:00
|
|
|
this.available = NEVER;
|
|
|
|
this.activated = NEVER;
|
2017-11-30 11:22:41 -05:00
|
|
|
return;
|
|
|
|
}
|
2018-02-27 17:06:06 -05:00
|
|
|
this.available = this.sw.eventsOfType<UpdateAvailableEvent>('UPDATE_AVAILABLE');
|
|
|
|
this.activated = this.sw.eventsOfType<UpdateActivatedEvent>('UPDATE_ACTIVATED');
|
2017-09-28 19:18:12 -04:00
|
|
|
}
|
|
|
|
|
2017-11-30 11:22:41 -05:00
|
|
|
/**
|
|
|
|
* Returns true if the Service Worker is enabled (supported by the browser and enabled via
|
|
|
|
* ServiceWorkerModule).
|
|
|
|
*/
|
|
|
|
get isEnabled(): boolean { return this.sw.isEnabled; }
|
|
|
|
|
2017-09-28 19:18:12 -04:00
|
|
|
checkForUpdate(): Promise<void> {
|
2017-11-30 11:22:41 -05:00
|
|
|
if (!this.sw.isEnabled) {
|
|
|
|
return Promise.reject(new Error(ERR_SW_NOT_SUPPORTED));
|
|
|
|
}
|
2017-09-28 19:18:12 -04:00
|
|
|
const statusNonce = this.sw.generateNonce();
|
|
|
|
return this.sw.postMessageWithStatus('CHECK_FOR_UPDATES', {statusNonce}, statusNonce);
|
|
|
|
}
|
|
|
|
|
|
|
|
activateUpdate(): Promise<void> {
|
2017-11-30 11:22:41 -05:00
|
|
|
if (!this.sw.isEnabled) {
|
|
|
|
return Promise.reject(new Error(ERR_SW_NOT_SUPPORTED));
|
|
|
|
}
|
2017-09-28 19:18:12 -04:00
|
|
|
const statusNonce = this.sw.generateNonce();
|
|
|
|
return this.sw.postMessageWithStatus('ACTIVATE_UPDATE', {statusNonce}, statusNonce);
|
|
|
|
}
|
|
|
|
}
|