aboutsummaryrefslogtreecommitdiff
path: root/src/app/js/request.js
blob: bec9d7c55a8d92c5f7ec3262c33f783ffe86c40f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const set_buttons = require("./set_buttons");
const ipcRenderer = require("electron").ipcRenderer;

// invokes `requests.get()` from `src/modules/requests.js` through the
// main process, and returns the output
let request = async (...args) => {
	return await ipcRenderer.invoke("request", ...args);
}

// invokes `requests.check()` from `src/modules/requests.js` through the
// main process, and returns the output
request.check = async (...args) => {
	return await ipcRenderer.invoke("request-check", ...args);
}

request.delete_cache = () => {
	ipcRenderer.send("delete-request-cache");
}

// keeps track of whether we've already sent a toast since we last went
// offline, to prevent multiple toasts
let sent_error_toast = false;

// shows or hides offline icon, and shows toast depending on `is_online`
let state_action = (is_online) => {
	if (is_online) {
		// hide offline icon
		sent_error_toast = false;
		offline.classList.add("hidden");

		// re-enable buttons that require internet
		set_buttons(
			true, false,
			document.querySelectorAll(".requires-internet")
		)
	} else {
		// show toast
		if (! sent_error_toast) {
			sent_error_toast = true;
			ipcRenderer.send("no-internet");
		}

		// show offline icon
		offline.classList.remove("hidden");

		// disable buttons that require internet
		set_buttons(
			false, false,
			document.querySelectorAll(".requires-internet")
		)

		// close mod browser
		try {
			require("./browser").toggle(false);
		} catch(err) {}
	}
}

setTimeout(() => state_action(navigator.onLine), 100);
window.addEventListener("online", () => state_action(navigator.onLine));
window.addEventListener("offline", () => state_action(navigator.onLine));

// checks a list of endpoints/domains we need to be functioning for a
// lot of the WAN functionality
let check_endpoints = async () => {
	// if we're not online according to the navigator, it's highly
	// unlikely the endpoints will succeed
	if (! navigator.onLine) {
		return state_action(false);
	}

	// check endpoints
	let status = await request.check([
		"https://github.com",
		"https://northstar.tf",
		"https://thunderstore.io"
	])

	// handle result of check
	state_action(!! status.succeeded.length);
}

// check endpoints on startup
setTimeout(check_endpoints, 100);

// check endpoints every 30 seconds
setInterval(check_endpoints, 30000);

module.exports = request;