webdetector/ts/index.ts

70 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-06-10 11:46:58 +00:00
import * as plugins from './webdetector.plugins.js';
2018-12-18 16:58:06 +00:00
2023-06-10 11:46:58 +00:00
import { Platform } from './webdetector.classes.platform.js';
2018-12-19 16:17:25 +00:00
export interface IWebDetectorOptions {
checkOnlineUrl: string;
}
2018-12-18 16:58:06 +00:00
export class WebDetector {
2023-06-10 11:46:58 +00:00
// subclasses
public platform = new Platform();
2018-12-19 16:17:25 +00:00
options: IWebDetectorOptions;
private onlineObservableIntake = new plugins.smartrx.ObservableIntake();
2023-06-10 11:46:58 +00:00
public onlineObservable = this.onlineObservableIntake.observable.pipe(
plugins.smartrx.rxjs.ops.throttleTime(10000)
);
2018-12-19 16:17:25 +00:00
latestState: 'online' | 'offline' = 'online';
constructor(optionsArg: IWebDetectorOptions) {
this.options = optionsArg;
}
2018-12-18 16:58:06 +00:00
/**
2023-06-10 11:46:58 +00:00
*
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);
2023-06-10 11:46:58 +00:00
await fetchPromise
.then(async (response) => {
reachesInternet = true;
})
.catch((err) => {
// console.log(`request to ${this.options.checkOnlineUrl} failed}`)
});
2018-12-19 16:17:25 +00:00
const latestLocalState = (() => {
2023-06-10 11:46:58 +00:00
if (reachesInternet) {
return 'online';
2018-12-19 16:17:25 +00:00
} else {
2023-06-10 11:46:58 +00:00
return 'offline';
2018-12-19 16:17:25 +00:00
}
})();
2023-06-10 11:46:58 +00:00
if (latestLocalState !== this.latestState) {
2018-12-19 16:17:25 +00:00
this.onlineObservableIntake.push(this.latestState);
}
this.latestState = latestLocalState;
return reachesInternet;
}
2018-12-18 16:58:06 +00:00
2023-06-10 14:43:20 +00:00
private periodicChecksRunning = false;
public async startPeriodicChecks() {
this.periodicChecksRunning = true;
while (this.periodicChecksRunning) {
2018-12-19 16:17:25 +00:00
await this.isOnline();
await plugins.smartdelay.delayFor(3000);
2018-12-18 16:58:06 +00:00
}
}
2023-06-10 14:43:20 +00:00
public async stopPeriodicChecks() {
this.periodicChecksRunning = false;
}
2023-06-10 11:46:58 +00:00
}