summaryrefslogtreecommitdiff
path: root/app/load.js
blob: 9e4d3b96db51bcd78121e526cbabeec404d6eac2 (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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
// noinspection JSUnresolvedVariable

async function fetchPlus(resource, options = {}) {
    const { timeout = 8000 } = options;

    const controller = new AbortController();
    const id = setTimeout(() => controller.abort(), timeout);
    const response = await fetch(resource, {
        ...options,
        signal: controller.signal
    });
    clearTimeout(id);
    return response;
}

window.connected = false;

let valuesToGet = {
    "pluralkit-cloudburst-members": {
        url: "/api/data?f=ynmuc-members.json",
        limited: false,
        name: "Members at Cloudburst...",
    },
    "pluralkit-cloudburst-fronters": {
        url: "/api/data?f=ynmuc-fronters.json",
        limited: false,
        name: "Fronters at Cloudburst...",
    },
    "pluralkit-cloudburst-switches": {
        url: "/api/data?f=ynmuc-switches.json",
        limited: false,
        name: "Switches at Cloudburst...",
    },
    "pluralkit-raindrops-members": {
        url: "/api/data?f=gdapd-members.json",
        limited: false,
        name: "Members at Raindrops...",
    },
    "pluralkit-raindrops-fronters": {
        url: "/api/data?f=gdapd-fronters.json",
        limited: false,
        name: "Fronters at Raindrops...",
    },
    "pluralkit-raindrops-switches": {
        url: "/api/data?f=gdapd-switches.json",
        limited: false,
        name: "Switches at Raindrops...",
    },
    "peh-cloudburst-data": {
        url: "/api/cloudburst-data",
        limited: false,
        name: "Cloudburst data...",
    },
    "peh-raindrops-data": {
        url: "/api/raindrops-data",
        limited: false,
        name: "Raindrops data...",
    },
    "peh-cloudburst-banners": {
        url: "/api/cloudburst-banners",
        limited: false,
        name: "Cloudburst banner data...",
    },
    "peh-raindrops-banners": {
        url: "/api/raindrops-banners",
        limited: false,
        name: "Raindrops banner data...",
    },
    "identity": {
        url: "/api/me",
        limited: false,
        name: "Identity...",
    },
    "images": {
        url: "/api/app-images",
        limited: false,
        name: "Images...",
        condition: async () => {
            let known = await localforage.getItem("images-refresh");
            let currentKnown;

            try {
                currentKnown = btoa(Object.keys(JSON.parse(await localforage.getItem("peh-cloudburst-data")).members).join("") + Object.keys(JSON.parse(await localforage.getItem("peh-raindrops-data")).members).join("") + new Date().toDateString());
            } catch (e) {
                return true;
            }

            localforage.setItem("images-refresh", currentKnown);

            if (known) {
                return known !== currentKnown;
            } else {
                return true;
            }
        }
    },
    "image-me": {
        url: "/api/me-picture",
        limited: false,
        name: "Identity avatar...",
    },
    "bits-transactions": {
        url: "/bits/Application/TransactionsList/index.php",
        limited: false,
        name: "Bits transactions...",
    },
    "bits-goal": {
        url: "/bits/Application/GetGoal/index.php",
        limited: false,
        name: "Bits goal...",
    },
    "bits-username": {
        url: "/bits/Authentication/Username/index.php",
        limited: false,
        name: "Bits user info...",
    }
}

let keys = Object.keys(valuesToGet);
let index = 2;

window.onerror = (event, source, lineno, colno, error) => {
    console.log(event, source, lineno, colno, error);
    document.getElementById("loader-message").classList.add("text-danger");
    document.getElementById("loader-message").innerText = "An error occurred.";
}

window.onunhandledrejection = (handler, event) => {
    console.log(handler, event);
    document.getElementById("loader-message").classList.add("text-danger");
    document.getElementById("loader-message").innerText = "An error occurred.";
}

async function getNewValue() {
    if (!keys[0]) {
        await postLoad();
        return;
    }

    try {
        if (valuesToGet[keys[0]].condition && !(await valuesToGet[keys[0]].condition())) throw new Error();

        document.getElementById("loader-message").innerText = valuesToGet[keys[0]].name;
        await localforage.setItem(keys[0], (await (await fetchPlus(valuesToGet[keys[0]]["url"], { timeout: 3000 })).text()));
        keys.shift();

        if (!keys[0]) {
            await postLoad();
            return;
        }

        setTimeout(async () => {
            document.getElementById("progress-inner").style.width = ((index / Object.keys(valuesToGet).length) * 100) + "%";
            index++;
            await getNewValue();
        }, valuesToGet[keys[0]]["limited"] ? 550 : 0);
    } catch (e) {
        for (let key of Object.keys(valuesToGet)) {
            if (await localforage.getItem(key) === null) {
                throw new Error("App requested key '" + key + "' but it can't be retrieved at the moment");
            }
        }

        await postLoad();
    }
}

async function load() {
    await localforage.setItem("values-to-get", JSON.stringify(valuesToGet));

    try {
        let online = (await (await fetchPlus("/api/test", { timeout: 3000 })).text());
        if (online === "SUCCESS") window.connected = true;
    } catch (e) {}

    await getNewValue();
}

async function postLoad() {
    for (let key of await localforage.keys()) {
        if (key !== "images") localStorage.setItem(key, await localforage.getItem(key))
    }

    localStorage.setItem("pluralkit-0", localStorage.getItem("pluralkit-raindrops-members"));
    localStorage.setItem("pluralkit-1", localStorage.getItem("pluralkit-cloudburst-members"));

    window.data = {};

    for (let value of Object.keys(valuesToGet)) {
        try {
            window.data[value] = JSON.parse(localStorage.getItem(value));
        } catch (e) {
            window.data[value] = localStorage.getItem(value);
        }
    }

    window.currentFronter = window.data['pluralkit-' + window.data['identity'].id + '-fronters'].members[0]

    try {
        let member = window.currentFronter;
        await (await window.fetch("/bits/Application/SetCurrentIdentity/index.php?Name=" + btoa(member['display_name'] ?? member['name']).replaceAll("+", "-").replaceAll("/", "_") + "&Picture=" + btoa(member['avatar_url'] ?? "./assets/default.png").replaceAll("+", "-").replaceAll("/", "_"))).text();
    } catch (e) {}

    document.getElementById("home-name").innerText = getMiniName(window.currentFronter['display_name'] ?? window.currentFronter['name']);
    document.getElementById("home-avatar").src = window.data['image-me'];

    switch (new Date().getHours()) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            document.getElementById("home-greeting").innerText = "Good night";
            break;

        case 6:
        case 7:
        case 8:
        case 9:
        case 10:
        case 11:
            document.getElementById("home-greeting").innerText = "Good morning";
            break;

        case 12:
        case 13:
        case 14:
        case 15:
        case 16:
        case 17:
            document.getElementById("home-greeting").innerText = "Good afternoon";
            break;

        case 18:
        case 19:
        case 20:
        case 21:
        case 22:
        case 23:
            document.getElementById("home-greeting").innerText = "Good evening";
            break;
    }

    if (!window.connected) {
        document.getElementById("home-app-planner").classList.add("disabled");
        document.getElementById("home-app-emergency").classList.add("disabled");
    }

    if (window.serviceWorkerRegistration) {
        if (window.serviceWorkerRegistration.sync) {
            window.serviceWorkerRegistration.sync.register('data-sync')
                .catch(function(err) {
                    return err;
                })
                .then(() => {
                    console.log("Scheduled background sync for the next time connection is available");
                })
        } else {
            console.log("Background sync not possible on this platform");
        }
    }

    window.currentMemberData = JSON.parse(localStorage.getItem("peh-" + JSON.parse(localStorage.getItem("identity")).id + "-banners"))[JSON.parse(localStorage.getItem("pluralkit-" + JSON.parse(localStorage.getItem("identity")).id + "-fronters")).members[0].name];

    //await refreshBanner(true); refreshTooltips();

    setInterval(async () => {
        Array.from(document.getElementsByClassName("relative-time")).forEach((el) => {
            el.innerText = timeAgo(parseInt(el.getAttribute("data-relative-timestamp")) * 1000);
        })
    }, 1000)

    document.getElementById("loader").style.display = "none";
}