2018-12-18 16:58:06 +00:00
|
|
|
import * as plugins from './webdetector.plugins';
|
|
|
|
|
2018-12-19 16:17:25 +00:00
|
|
|
import {throttleTime } from 'rxjs/operators';
|
|
|
|
|
|
|
|
export interface IWebDetectorOptions {
|
|
|
|
checkOnlineUrl: string;
|
|
|
|
}
|
|
|
|
|
2018-12-18 16:58:06 +00:00
|
|
|
export class WebDetector {
|
2018-12-19 16:17:25 +00:00
|
|
|
options: IWebDetectorOptions;
|
|
|
|
private onlineObservableIntake = new plugins.smartrx.ObservableIntake();
|
|
|
|
onlineObservable = this.onlineObservableIntake.observable.pipe(throttleTime(10000));
|
|
|
|
latestState: 'online' | 'offline' = 'online';
|
|
|
|
|
|
|
|
constructor(optionsArg: IWebDetectorOptions) {
|
|
|
|
this.options = optionsArg;
|
|
|
|
}
|
|
|
|
|
2018-12-18 16:58:06 +00:00
|
|
|
/**
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
async isOnline() {
|
2018-12-19 16:17:25 +00:00
|
|
|
let reachesInternet: boolean = false;
|
|
|
|
const controller = new AbortController();
|
|
|
|
const fetchPromise = fetch(this.options.checkOnlineUrl, { signal: controller.signal });
|
|
|
|
const timeout = setTimeout(() => {
|
|
|
|
controller.abort();
|
|
|
|
}, 1000);
|
|
|
|
|
|
|
|
await fetchPromise.then(async response => {
|
|
|
|
reachesInternet = true
|
|
|
|
}).catch(err => {
|
|
|
|
// console.log(`request to ${this.options.checkOnlineUrl} failed}`)
|
|
|
|
});
|
|
|
|
const latestLocalState = (() => {
|
|
|
|
if(reachesInternet) {
|
|
|
|
return 'online'
|
|
|
|
} else {
|
|
|
|
return 'offline'
|
|
|
|
}
|
|
|
|
})();
|
|
|
|
if(latestLocalState !== this.latestState) {
|
|
|
|
|
|
|
|
this.onlineObservableIntake.push(this.latestState);
|
|
|
|
}
|
|
|
|
this.latestState = latestLocalState;
|
|
|
|
return reachesInternet;
|
|
|
|
}
|
2018-12-18 16:58:06 +00:00
|
|
|
|
2018-12-19 16:17:25 +00:00
|
|
|
async startPeriodicChecks() {
|
|
|
|
while (true) {
|
|
|
|
await this.isOnline();
|
|
|
|
await plugins.smartdelay.delayFor(3000);
|
2018-12-18 16:58:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|