63 lines
1.6 KiB
TypeScript
63 lines
1.6 KiB
TypeScript
import * as plugins from './webdetector.plugins.js';
|
|
|
|
import { Platform } from './webdetector.classes.platform.js';
|
|
|
|
export interface IWebDetectorOptions {
|
|
checkOnlineUrl: string;
|
|
}
|
|
|
|
export class WebDetector {
|
|
// subclasses
|
|
public platform = new Platform();
|
|
|
|
options: IWebDetectorOptions;
|
|
private onlineObservableIntake = new plugins.smartrx.ObservableIntake();
|
|
public onlineObservable = this.onlineObservableIntake.observable.pipe(
|
|
plugins.smartrx.rxjs.ops.throttleTime(10000)
|
|
);
|
|
latestState: 'online' | 'offline' = 'online';
|
|
|
|
constructor(optionsArg: IWebDetectorOptions) {
|
|
this.options = optionsArg;
|
|
}
|
|
|
|
/**
|
|
*
|
|
*/
|
|
async isOnline() {
|
|
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;
|
|
}
|
|
|
|
async startPeriodicChecks() {
|
|
while (true) {
|
|
await this.isOnline();
|
|
await plugins.smartdelay.delayFor(3000);
|
|
}
|
|
}
|
|
}
|