FIX: Looping attempt to reconnect in network connectivity service (#22783)
This commit is contained in:
parent
1ab1116cda
commit
b91228d6c2
|
@ -1,5 +1,8 @@
|
|||
import Service from "@ember/service";
|
||||
import discourseDebounce from "discourse-common/lib/debounce";
|
||||
import { ajax } from "discourse/lib/ajax";
|
||||
import { bind } from "discourse-common/utils/decorators";
|
||||
import { cancel } from "@ember/runloop";
|
||||
import { tracked } from "@glimmer/tracking";
|
||||
|
||||
const CONNECTIVITY_ERROR_CLASS = "network-disconnected";
|
||||
|
@ -14,28 +17,53 @@ export default class NetworkConnectivity extends Service {
|
|||
|
||||
window.addEventListener("offline", () => {
|
||||
this.setConnectivity(false);
|
||||
this.startTimerToCheckNavigator();
|
||||
});
|
||||
|
||||
window.addEventListener(
|
||||
"online",
|
||||
this.pingServerAndSetConnectivity.bind(this)
|
||||
);
|
||||
window.addEventListener("online", this.pingServerAndSetConnectivity);
|
||||
|
||||
window.addEventListener("visibilitychange", this.onFocus.bind(this));
|
||||
window.addEventListener("visibilitychange", this.onFocus);
|
||||
}
|
||||
|
||||
@bind
|
||||
onFocus() {
|
||||
if (!this.connected && document.visibilityState === "visible") {
|
||||
this.pingServerAndSetConnectivity();
|
||||
}
|
||||
}
|
||||
|
||||
@bind
|
||||
async pingServerAndSetConnectivity() {
|
||||
let response = await ajax("/srv/status", { dataType: "text" }).catch(() => {
|
||||
this.setConnectivity(false);
|
||||
});
|
||||
try {
|
||||
let response = await ajax("/srv/status", { dataType: "text" });
|
||||
if (response === "ok") {
|
||||
cancel(this._timer);
|
||||
this.setConnectivity(true);
|
||||
} else {
|
||||
throw "disconnected";
|
||||
}
|
||||
} catch {
|
||||
// Either the request didn't go out at all or the response wasn't "ok". Both are failures.
|
||||
// Start the timer to check every second if `navigator.onLine` comes back online in the event that
|
||||
// we miss the `online` event firing
|
||||
this.startTimerToCheckNavigator();
|
||||
}
|
||||
}
|
||||
|
||||
this.setConnectivity(response === "ok");
|
||||
@bind
|
||||
startTimerToCheckNavigator() {
|
||||
cancel(this._timer);
|
||||
|
||||
this._timer = discourseDebounce(this, this.checkNavigatorOnline, 1000);
|
||||
}
|
||||
|
||||
@bind
|
||||
checkNavigatorOnline() {
|
||||
if (navigator.onLine) {
|
||||
this.pingServerAndSetConnectivity();
|
||||
} else {
|
||||
this.startTimerToCheckNavigator();
|
||||
}
|
||||
}
|
||||
|
||||
setConnectivity(connected) {
|
||||
|
|
Loading…
Reference in New Issue