summaryrefslogtreecommitdiff
path: root/app/index.php
blob: 3dc4b44d1b46c2a4d382f76c832a32d8f1975047 (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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
<?php
header("X-Frame-Options: DENY");
require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/session.php"; global $_PROFILE; ?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Mist</title>
    <!--<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">-->
    <link href="/assets/dark.css" rel="stylesheet">
    <link href="/assets/styles.css" rel="stylesheet">
    <!--<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>-->
    <script src="/assets/localforage.min.js"></script>
    <script src="/assets/js/shortcuts.js"></script>
    <link rel="shortcut icon" href="/assets/logo-display.svg" type="image/svg+xml">
    <link rel="manifest" href="/manifest.json" />
    <meta name="theme-color" content="#ffffff" media="(prefers-color-scheme: light)">
    <meta name="theme-color" content="#000000" media="(prefers-color-scheme: dark)">
    <meta name="apple-mobile-web-app-status-bar" content="#ffffff" media="(prefers-color-scheme: light)">
    <meta name="apple-mobile-web-app-status-bar" content="#000000" media="(prefers-color-scheme: dark)">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" media="(prefers-color-scheme: dark)">
    <meta name="apple-mobile-web-app-status-bar-style" content="white-translucent" media="(prefers-color-scheme: light)">
    <meta name="description" content="Mist Audio Player">
    <style>
        body {
            font-family: system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue","Noto Sans","Liberation Sans",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";
        }
    </style>
</head>
<body <?php if (!str_contains($_SERVER['HTTP_USER_AGENT'], "MistNative/")): ?>class="web"<?php endif; ?>>
    <script src="/assets/js/common.js"></script>
    <script>
        if (location.hash.trim() === "") location.hash = "#/albums";

        if (window.MistNative) {
            MistNative.version("<?= explode("|", trim(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/version")))[0]  ?>", "<?= trim(file_exists("/opt/spotify/build.txt") ? file_get_contents("/opt/spotify/build.txt") : "trunk") ?>");
            MistNative.userInfo(`<?= str_replace("`", "\\`", json_encode($_PROFILE)) ?>`);
        }
    </script>
    <div id="loading" style="z-index: 999999; position: fixed; inset: 0; display: flex; align-items: center; justify-content: center; background-color: white;">
        <span id="loading-text">Initializing...</span>
    </div>

    <iframe title="Player" id="player" src="ui/player.php" style="position: fixed; top: var(--android-status-bar); left: 320px; right: 0; width: calc(100vw - 320px); height: 64px; border-bottom: 1px solid rgba(0, 0, 0, .25); z-index: 9999;"></iframe>
    <iframe title="Navigation" id="navigation" src="ui/navigation.php" style="position: fixed; top: 0; bottom: var(--android-navigation-bar); left: 0; height: calc(100vh - var(--android-navigation-bar)); width: 320px; z-index: 9999;"></iframe>
    <iframe title="UI" id="ui" style="position: fixed; top: calc(65px + var(--android-status-bar)); bottom: var(--android-navigation-bar); left: 320px; height: calc(100vh - 64px - var(--android-status-bar) - var(--android-navigation-bar)); width: calc(100vw - 320px); z-index: 9999;"></iframe>
    <iframe title="Lyrics" id="lyrics-page" src="ui/lyrics.php" style="display: none; position: fixed; top: calc(64px + var(--android-status-bar)); bottom: var(--android-navigation-bar); left: 320px; height: calc(100vh - 64px - var(--android-status-bar) - var(--android-navigation-bar)); width: calc(100vw - 320px); z-index: 9999;"></iframe>
    <div id="player-mobile-container" style="background-color: white; position: fixed; left: 0; right: 0; height: 100vh; bottom: -100vh; transition: bottom 200ms; z-index: 99999;">
        <iframe title="Mobile player" style="background: #ddd; width: 100%; height: 100%;" src="ui/player-mobile.php" id="player-mobile"></iframe>
    </div>

    <script>
        window.onerror = (_1, _2, _3, _4, err) => {
            document.body.innerHTML = "";
            let pre = document.createElement("pre");
            pre.innerText = err.stack;
            document.body.append(pre);
        }

        window.playlist = [];

        window.showLyrics = () => {
            location.hash = "#/lyrics";
            document.getElementById("lyrics-page").style.display = "";
            document.getElementById("ui").style.display = "none";
            Array.from(document.getElementById("navigation").contentDocument.getElementsByClassName("navigation-item")).map(i => i.classList.remove("active"));
            document.getElementById("navigation").contentDocument.getElementById("lyrics").classList.add("active");
        }

        function openUI(name) {
            hideMobilePlayer();
            location.hash = "#/" + name;
            document.getElementById("lyrics-page").style.display = "none";
            document.getElementById("ui").style.display = "";
            document.getElementById("ui").src = "ui/" + name + ".php";
            Array.from(document.getElementById("navigation").contentDocument.getElementsByClassName("navigation-item")).map(i => i.classList.remove("active"));
            document.getElementById("navigation").contentDocument.getElementById(name).classList.add("active");
        }

        let name = location.hash.split("/")[1];

        if (name === "lyrics") {
            document.getElementById("ui").src = "ui/albums.php";
        } else if (name === "albums" && location.hash.split("/")[2]) {
            document.getElementById("ui").src = "ui/listing.php?a=" + location.hash.split("/")[2];
        } else {
            document.getElementById("ui").src = "ui/" + name + ".php";
        }

        document.getElementById("navigation").onload = () => {
            if (name === "lyrics") showLyrics();
            Array.from(document.getElementById("navigation").contentDocument.getElementsByClassName("navigation-item")).map(i => i.classList.remove("active"));
            document.getElementById("navigation").contentDocument.getElementById(name).classList.add("active");
        }

        let loadedPlayers = 0;

        document.getElementById("player").onload = document.getElementById("player-mobile").onload = () => {
            loadedPlayers++;
            if (loadedPlayers === 2) continueLoading();
        }

        window.onresize = window.onload = () => {
            if (window.innerWidth <= 863) {
                document.getElementById("player").contentDocument.getElementById("player").classList.add("mobilified");
            } else {
                document.getElementById("player").contentDocument.getElementById("player").classList.remove("mobilified");
            }
        }

        function continueLoading() {
            window.playerDocument = document.getElementById("player").contentDocument;
            window.playerDocumentMobile = document.getElementById("player-mobile").contentDocument;

            if (!localStorage.getItem("data-saving")) {
                localStorage.setItem("data-saving", "false");
            }

            if (!localStorage.getItem("desktop-notification")) {
                localStorage.setItem("desktop-notification", "true");
            }

            playerDocument.getElementById("seekbar-container").onclick = (e) => {
                playerDocument.getElementById("player-audio").currentTime = (e.offsetX / playerDocument.getElementById("seekbar-container").clientWidth) * playerDocument.getElementById("player-audio").duration;
            }

            playerDocumentMobile.getElementById("seekbar-container").onclick = (e) => {
                playerDocument.getElementById("player-audio").currentTime = (e.offsetX / playerDocumentMobile.getElementById("seekbar-container").clientWidth) * playerDocument.getElementById("player-audio").duration;
            }

            function parseTime(subject, max) {
                let minutesLength = Math.ceil(max / 60).toString().length;

                let minutes = Math.floor(subject / 60);
                let seconds = Math.floor(subject - (minutes * 60));

                let minutesStr = "0".repeat(minutesLength).substring(0, minutesLength - minutes.toString().length) + minutes.toString();
                let secondsStr = "00".substring(0, 2 - seconds.toString().length) + seconds.toString();

                return minutesStr + ":" + secondsStr;
            }

            playerDocument.getElementById("player-audio").onended = () => {
                next();
            }

            window.stop = () => {
                if (window.MistAndroid) {
                    window.MistAndroid.removeNotification();
                    window.MistAndroid.removeService();
                }

                if (window.discordRichPresenceData !== null) window.discordRichPresenceData = {
                    largeImageKey: "logo"
                };

                document.title = "Mist";
                window.currentSong = null;
                window.currentSongID = null;
                window.currentPlaylistID = null;
                window.playlist = [];

                document.getElementById("player").contentWindow.location.reload();
                document.getElementById("player").onload = () => {
                    window.playerDocument = document.getElementById("player").contentDocument;

                    if (window.innerWidth <= 863) {
                        document.getElementById("player").contentDocument.getElementById("player").classList.add("mobilified");
                    } else {
                        document.getElementById("player").contentDocument.getElementById("player").classList.remove("mobilified");
                    }

                    playerDocument.getElementById("player-audio").ontimeupdate = playerDocument.getElementById("player-audio").onchange = playerDocument.getElementById("player-audio").onunload = playerDocument.getElementById("player-audio").onstop = playerDocument.getElementById("player-audio").onplay = playerDocument.getElementById("player-audio").onpause = () => {
                        updateDisplay();
                    }
                }

                document.getElementById("player-mobile").contentWindow.location.reload();
                document.getElementById("player-mobile").onload = () => {
                    window.playerDocumentMobile = document.getElementById("player-mobile").contentDocument;
                }

                hideMobilePlayer();
            }

            window.showMobilePlayer = () => {
                if (window.MistAndroid) window.MistAndroid.setStatusBarTheme(false);

                if (window.currentSongID !== null) {
                    document.getElementById("player-mobile-container").style.bottom = "0";
                    document.getElementById("lyrics-page").classList.add("mobile-show");
                }
            }

            window.hideMobilePlayer = () => {
                if (window.MistAndroid) window.MistAndroid.setStatusBarTheme(true);

                document.getElementById("player-mobile-container").style.bottom = "-100vh";
                document.getElementById("lyrics-page").classList.remove("mobile-show");
            }

            document.getElementById("player-mobile-container").onclick = (e) => {
                if (e.target.id === "player-mobile-container") {
                    hideMobilePlayer();
                }
            }

            window.currentPlaylistPosition = 0;
            window.buffering = false;

            window.next = () => {
                if (window.repeat) {
                    playlist.push(playlist[currentPlaylistPosition]);
                }

                if (playlist[currentPlaylistPosition + 1]) {
                    currentPlaylistPosition++;
                    playSong(playlist[currentPlaylistPosition], "keep", false);
                } else {
                    stop();
                }
            }

            window.previous = () => {
                if (playlist[currentPlaylistPosition - 1]) {
                    playSong(playlist[currentPlaylistPosition - 1], "keep");
                    currentPlaylistPosition--;
                } else {
                    stop();
                }
            }

            playerDocument.getElementById("player-audio").ontimeupdate = playerDocument.getElementById("player-audio").onchange = playerDocument.getElementById("player-audio").onunload = playerDocument.getElementById("player-audio").onstop = playerDocument.getElementById("player-audio").onplay = playerDocument.getElementById("player-audio").onpause = () => {
                updateDisplay();
            }

            function updateDisplay() {
                if (window.MistAndroid && currentSong) {
                    window.MistAndroid.setNotificationData(currentSong.title,
                        currentSong.artist,
                        currentSong.album,
                        Math.round(playerDocument.getElementById("player-audio").currentTime * 1000),
                        Math.round(playerDocument.getElementById("player-audio").duration * 1000),
                        !playerDocument.getElementById("player-audio").paused),
                        buffering,
                        shuffle,
                        repeat
                    ;
                }

                if (playerDocument.getElementById("player-audio").paused) {
                    document.title = "Mist";
                } else if (currentSong) {
                    document.title = currentSong.artist + " — " + currentSong.title;
                } else {
                    document.title = "Mist";
                }

                if (window.discordRichPresenceData !== null && currentSong) window.discordRichPresenceData = {
                    largeImageKey: "https://" + location.hostname + "/albumart.php?i=" + currentSongID,
                    state: currentSong.title,
                    details: currentSong.artist,
                    smallImageKey: "logo",
                    smallImageText: "Listening on Mist",
                    largeImageText: currentSong.album ?? currentSong.artist
                };

                playerDocument.getElementById("info").style.display = "grid";
                playerDocument.getElementById("cover").style.display = "none";

                if ('mediaSession' in document.getElementById("player").contentWindow.navigator) {
                    document.getElementById("player").contentWindow.navigator.mediaSession.playbackState = playerDocument.getElementById("player-audio").paused ? "paused" : "playing";
                    let state = {
                        duration: isFinite(playerDocument.getElementById("player-audio").duration) ? playerDocument.getElementById("player-audio").duration : 0,
                        position: playerDocument.getElementById("player-audio").currentTime,
                        playbackRate: 1
                    }
                    document.getElementById("player").contentWindow.navigator.mediaSession.setPositionState(state);

                    document.getElementById("player").contentWindow.navigator.mediaSession.setActionHandler("play", () => {
                        playPause();
                    });
                    document.getElementById("player").contentWindow.navigator.mediaSession.setActionHandler("pause", () => {
                        playPause();
                    });
                    document.getElementById("player").contentWindow.navigator.mediaSession.setActionHandler("stop", () => {
                        stop();
                    });
                    document.getElementById("player").contentWindow.navigator.mediaSession.setActionHandler("seekbackward", (e) => {
                        let time = e.seekOffset ?? 10;

                        if (playerDocument.getElementById("player-audio").currentTime >= time) {
                            playerDocument.getElementById("player-audio").currentTime -= time;
                        } else {
                            playerDocument.getElementById("player-audio").currentTime = 0;
                        }
                    });
                    document.getElementById("player").contentWindow.navigator.mediaSession.setActionHandler("seekforward", (e) => {
                        let time = e.seekOffset ?? 10;

                        if (playerDocument.getElementById("player-audio").currentTime + time < playerDocument.getElementById("player-audio").duration) {
                            playerDocument.getElementById("player-audio").currentTime += time;
                        } else {
                            next();
                        }
                    });
                    document.getElementById("player").contentWindow.navigator.mediaSession.setActionHandler("seekto", (e) => {
                        if (e.seekTime) {
                            playerDocument.getElementById("player-audio").currentTime = e.seekTime;
                        }
                    });
                    document.getElementById("player").contentWindow.navigator.mediaSession.setActionHandler("previoustrack", () => {
                        if (playlist[currentPlaylistPosition - 1]) {
                            previous();
                        } else {
                            playerDocument.getElementById("player-audio").currentTime = 0;
                        }
                    });
                    document.getElementById("player").contentWindow.navigator.mediaSession.setActionHandler("nexttrack", () => {
                        next();
                    });
                }

                if (currentPlaylistPosition === 0) {
                    playerDocument.getElementById("btn-previous").classList.add("disabled");
                    playerDocumentMobile.getElementById("btn-previous").classList.add("disabled");
                } else {
                    playerDocument.getElementById("btn-previous").classList.remove("disabled");
                    playerDocumentMobile.getElementById("btn-previous").classList.remove("disabled");
                }

                if (currentPlaylistPosition === playlist.length - 1) {
                    playerDocument.getElementById("btn-next").classList.add("disabled");
                    playerDocumentMobile.getElementById("btn-next").classList.add("disabled");
                } else {
                    playerDocument.getElementById("btn-next").classList.remove("disabled");
                    playerDocumentMobile.getElementById("btn-next").classList.remove("disabled");
                }

                if (isFinite(playerDocument.getElementById("player-audio").duration)) {
                    playerDocument.getElementById("elapsed-time").innerText = playerDocumentMobile.getElementById("elapsed-time").innerText = parseTime(playerDocument.getElementById("player-audio").currentTime, playerDocument.getElementById("player-audio").duration);
                    playerDocument.getElementById("remaining-time").innerText = playerDocumentMobile.getElementById("remaining-time").innerText = "-" + parseTime(playerDocument.getElementById("player-audio").duration - playerDocument.getElementById("player-audio").currentTime, playerDocument.getElementById("player-audio").duration);
                } else {
                    playerDocument.getElementById("elapsed-time").innerText = playerDocumentMobile.getElementById("elapsed-time").innerText = parseTime(0, currentSong.length);
                    playerDocument.getElementById("remaining-time").innerText = playerDocumentMobile.getElementById("remaining-time").innerText = "-" + parseTime(currentSong.length, currentSong.length);
                }

                if (playerDocument.getElementById("player-audio").paused) {
                    playerDocument.getElementById("btn-play-icon").src = playerDocumentMobile.getElementById("btn-play-icon").src = "/assets/icons/play.svg";
                } else {
                    playerDocument.getElementById("btn-play-icon").src = playerDocumentMobile.getElementById("btn-play-icon").src = "/assets/icons/pause.svg";
                }

                if (localStorage.getItem("data-saving") === "true") {
                    playerDocument.getElementById("badge-lossy").style.display = "inline";
                    playerDocument.getElementById("badge-cd").style.display = "none";
                    playerDocument.getElementById("badge-hires").style.display = "none";
                    playerDocumentMobile.getElementById("badge-lossy").style.display = "inline";
                    playerDocumentMobile.getElementById("badge-cd").style.display = "none";
                    playerDocumentMobile.getElementById("badge-hires").style.display = "none";
                } else {
                    if (window.currentSong && window.currentSong.hiRes) {
                        playerDocument.getElementById("badge-lossy").style.display = "none";
                        playerDocument.getElementById("badge-cd").style.display = "none";
                        playerDocument.getElementById("badge-hires").style.display = "inline";
                        playerDocument.getElementById("badge-hires").innerHTML = "<span style='display: grid; grid-template-columns: max-content max-content'><span><img src='/assets/icons/lossless.svg' alt='' class='player-badge-icon' style='filter: invert(1);'>Hi-Res Lossless</span><span class='player-badge-desktop'>" + window.currentSong.bitDepth + "-bit " + (window.currentSong.sampleRate / 1000) + " kHz</span>";
                        playerDocumentMobile.getElementById("badge-lossy").style.display = "none";
                        playerDocumentMobile.getElementById("badge-cd").style.display = "none";
                        playerDocumentMobile.getElementById("badge-hires").style.display = "inline";
                    } else if (window.currentSong) {
                        playerDocument.getElementById("badge-lossy").style.display = "none";
                        playerDocument.getElementById("badge-cd").style.display = "inline";
                        playerDocument.getElementById("badge-hires").style.display = "none";
                        playerDocumentMobile.getElementById("badge-lossy").style.display = "none";
                        playerDocumentMobile.getElementById("badge-cd").style.display = "inline";
                        playerDocumentMobile.getElementById("badge-hires").style.display = "none";
                        playerDocument.getElementById("badge-cd").innerHTML = "<span style='display: grid; grid-template-columns: max-content max-content;'><span><img src='/assets/icons/lossless.svg' alt='' class='player-badge-icon' style='filter: invert(1);'>Lossless</span><span class='player-badge-desktop'>" + window.currentSong.bitDepth + "-bit " + (window.currentSong.sampleRate / 1000) + " kHz</span>";
                    }
                }

                if (window.currentSong) {
                    playerDocument.getElementById("title").innerText = playerDocumentMobile.getElementById("title").innerText = window.currentSong.title;
                    playerDocument.getElementById("artist").innerText = playerDocumentMobile.getElementById("artist").innerText = window.currentSong.artist;
                    playerDocument.getElementById("album").innerText = playerDocumentMobile.getElementById("album").innerText = window.currentSong.album;
                    playerDocument.getElementById("album-art").src = playerDocumentMobile.getElementById("album-art").src = "/assets/content/" + window.currentSongID + ".jpg";
                    playerDocumentMobile.getElementById("album-art-bg").style.backgroundImage = "url('/assets/content/" + window.currentSongID + ".jpg')";
                }

                if (isFinite(playerDocument.getElementById("player-audio").duration)) {
                    playerDocument.getElementById("seekbar").style.width = playerDocumentMobile.getElementById("seekbar").style.width = ((playerDocument.getElementById("player-audio").currentTime / playerDocument.getElementById("player-audio").duration) * 100) + "%";
                } else {
                    playerDocument.getElementById("seekbar").style.width = playerDocumentMobile.getElementById("seekbar").style.width = "0";
                }
            }

            window.playPause = () => {
                if (playlist.length === 0) return;

                if (playerDocument.getElementById("player-audio").paused) {
                    playerDocument.getElementById("player-audio").play();
                    if (window.MistAndroid) window.MistAndroid.updateNotificationAlbumArt("https://" + location.hostname + "/albumart.php?i=" + currentSongID);
                } else {
                    playerDocument.getElementById("player-audio").pause();
                    if (window.MistAndroid) window.MistAndroid.removeService();
                }
            }

            window.redownloadFavorites = async () => {
                document.getElementById("loading-text").innerText = "Downloading favorites...";
                window.favorites = await (await fetch("/api/getFavorites.php?_=" + [...crypto.getRandomValues(new Uint8Array(40))].map(m=>('0'+m.toString(16)).slice(-2)).join(''))).json();
            }

            window.redownloadLibrary = async () => {
                document.getElementById("loading-text").innerText = "Downloading library...";
                window.library = await (await fetch("/api/getLibrary.php?_=" + [...crypto.getRandomValues(new Uint8Array(40))].map(m=>('0'+m.toString(16)).slice(-2)).join(''))).json();
            }

            (async () => {
                document.getElementById("loading-text").innerText = "Downloading list of songs...";
                window.songs = await (await fetch("/assets/content/songs.json?_=" + [...crypto.getRandomValues(new Uint8Array(40))].map(m=>('0'+m.toString(16)).slice(-2)).join(''))).json();

                document.getElementById("loading-text").innerText = "Downloading list of albums...";
                window.albums = await (await fetch("/assets/content/albums.json?_=" + [...crypto.getRandomValues(new Uint8Array(40))].map(m=>('0'+m.toString(16)).slice(-2)).join(''))).json();

                document.getElementById("loading-text").innerText = "Downloading favorites...";
                window.favorites = await (await fetch("/api/getFavorites.php?_=" + [...crypto.getRandomValues(new Uint8Array(40))].map(m=>('0'+m.toString(16)).slice(-2)).join(''))).json();

                document.getElementById("loading-text").innerText = "Downloading library...";
                window.library = await (await fetch("/api/getLibrary.php?_=" + [...crypto.getRandomValues(new Uint8Array(40))].map(m=>('0'+m.toString(16)).slice(-2)).join(''))).json();

                document.getElementById("loading-text").innerText = "Saving database...";
                await localforage.setItem("albums", window.albums);
                await localforage.setItem("songs", window.songs);
                await localforage.setItem("favorites", window.favorites);
                await localforage.setItem("library", window.library);

                document.getElementById("loading-text").innerText = "Done loading.";
                document.getElementById("loading").style.display = "none";
            })();

            window.currentSong = null;
            window.currentSongID = null;
            window.preloaded = {};
            window.shuffle = false;
            window.repeat = false;

            window.toggleRepeat = () => {
                window.repeat = !window.repeat;
                updateRepeat();
            }

            window.setRepeat = (value) => {
                window.repeat = value;
                updateRepeat();
            }

            window.updateRepeat = () => {
                if (window.currentSong) {
                    updateDisplay();
                }

                if (window.repeat) {
                    playerDocument.getElementById("btn-repeat-icon").src = playerDocumentMobile.getElementById("btn-repeat-icon").src = "/assets/icons/repeat-on.svg";
                } else {
                    playerDocument.getElementById("btn-repeat-icon").src = playerDocumentMobile.getElementById("btn-repeat-icon").src = "/assets/icons/repeat-off.svg";
                }
            }

            function shuffleArray(array) {
                let currentIndex = array.length, temporaryValue, randomIndex;

                while (0 !== currentIndex) {
                    randomIndex = Math.floor(Math.random() * currentIndex);
                    currentIndex -= 1;

                    temporaryValue = array[currentIndex];
                    array[currentIndex] = array[randomIndex];
                    array[randomIndex] = temporaryValue;
                }

                return array;
            }

            window.toggleShuffle = () => {
                window.shuffle = !window.shuffle;
                updateShuffle();
            }

            window.setShuffle = (value) => {
                window.shuffle = value;
                updateShuffle();
            }

            window.updateShuffle = () => {
                if (window.currentSong) {
                    updateDisplay();
                }

                if (window.shuffle) {
                    window.playlist = shuffleArray(window.playlist);
                    playerDocument.getElementById("btn-shuffle-icon").src = playerDocumentMobile.getElementById("btn-shuffle-icon").src = "/assets/icons/shuffle-on.svg";
                } else {
                    if (currentPlaylistID) {
                        if (currentPlaylistID === "favorites") {
                            window.playlist = favorites;
                        } else if (currentPlaylistID.startsWith("album:")) {
                            window.playlist = albums[currentPlaylistID.substring(6)].tracks;
                        } else if (currentPlaylistID !== "keep") {
                            window.playlist = [currentSongID];
                        }
                    } else {
                        window.playlist = [currentSongID];
                    }

                    playerDocument.getElementById("btn-shuffle-icon").src = playerDocumentMobile.getElementById("btn-shuffle-icon").src = "/assets/icons/shuffle-off.svg";
                }
            }

            window.shuffleList = (playlistID) => {
                window.shuffle = true;
                playerDocument.getElementById("btn-shuffle-icon").src = playerDocumentMobile.getElementById("btn-shuffle-icon").src = "/assets/icons/shuffle-on.svg";

                if (playlistID) {
                    if (playlistID === "favorites") {
                        window.currentPlaylistID = playlistID;
                        window.playlist = favorites;
                    } else if (playlistID.startsWith("album:")) {
                        window.currentPlaylistID = playlistID;
                        window.playlist = albums[playlistID.substring(6)].tracks;
                    } else if (playlistID !== "keep") {
                        window.playlist = [];
                    }
                } else {
                    window.currentPlaylistID = null;
                    window.playlist = [];
                }

                window.playlist = shuffleArray(window.playlist);
                window.playSong(window.playlist[0], "keep");
            }

            window.currentPlaylistID = null;

            window.playSong = async (id, playlistID, updatePosition) => {
                playerDocument.getElementById("player-audio").pause();
                playerDocument.getElementById("player-audio").currentTime = 0;

                if (playlistID) {
                    if (playlistID === "favorites") {
                        window.currentPlaylistID = playlistID;
                        window.playlist = favorites;
                        window.currentPlaylistPosition = favorites.indexOf(id) ?? 0;
                    } else if (playlistID.startsWith("album:")) {
                        window.currentPlaylistID = playlistID;
                        window.playlist = albums[playlistID.substring(6)].tracks;
                        window.currentPlaylistPosition = albums[playlistID.substring(6)].tracks.indexOf(id) ?? 0;
                    } else if (playlistID !== "keep") {
                        window.playlist = [id];
                        window.currentPlaylistPosition = 0;
                    } else if (typeof updatePosition !== "boolean" || updatePosition) {
                        window.currentPlaylistPosition = window.playlist.indexOf(id) ?? 0;
                    }
                } else {
                    window.currentPlaylistID = null;
                    window.playlist = [id];
                    window.currentPlaylistPosition = 0;
                }

                window.currentSong = songs[id];
                window.currentSongID = id;
                updateDisplay();
                if (document.getElementById("ui").contentWindow.refreshQueue) document.getElementById("ui").contentWindow.refreshQueue();

                if (!window.preloaded[id]) {
                    window.buffering = true;

                    if (localStorage.getItem("data-saving") === "true") {
                        window.preloaded[id] = URL.createObjectURL(new Blob([await (await fetch("/assets/content/" + id + ".m4a")).arrayBuffer()], { type: "audio/mp4" }));
                    } else {
                        window.preloaded[id] = URL.createObjectURL(new Blob([await (await fetch("/assets/content/" + id + ".flac")).arrayBuffer()], { type: "audio/flac" }));
                    }
                }

                cleanupPreload();
                preloadMore();

                playerDocument.getElementById("player-audio").src = window.preloaded[id];
                playerDocument.getElementById("player-audio").play();
                window.buffering = false;

                if (window.MistNative && localStorage.getItem("desktop-notification") === "true") {
                    window.MistNative.notification(currentSong, await (async function() {
                        let blob = await fetch("/assets/content/" + currentSongID + ".jpg").then(r => r.blob());
                        return await new Promise(resolve => {
                            let reader = new FileReader();
                            reader.onload = () => resolve(reader.result);
                            reader.readAsDataURL(blob);
                        });
                    })());
                }

                if ('mediaSession' in document.getElementById("player").contentWindow.navigator) {
                    document.getElementById("player").contentWindow.navigator.mediaSession.metadata = new MediaMetadata({
                        title: currentSong.title,
                        artist: currentSong.artist,
                        album: currentSong.album,
                        artwork: [
                            {
                                src: location.protocol + "//" + location.host + '/assets/content/' + currentSongID + '.jpg',
                                sizes: playerDocument.getElementById("album-art").naturalWidth + "x" + playerDocument.getElementById("album-art").naturalHeight,
                                type: 'image/jpeg'
                            },
                        ]
                    });
                }

                if (window.MistAndroid) {
                    window.MistAndroid.updateNotificationAlbumArt("https://" + location.hostname + "/albumart.php?i=" + currentSongID);
                }
            }
        }

        async function preloadMore() {
            for (let i = 1; i <= 10; i++) {
                if (playlist[currentPlaylistPosition + i]) {
                    let id = playlist[currentPlaylistPosition + i];

                    if (!window.preloaded[id]) {
                        if (localStorage.getItem("data-saving") === "true") {
                            window.preloaded[id] = URL.createObjectURL(new Blob([await (await fetch("/assets/content/" + id + ".m4a")).arrayBuffer()], { type: "audio/mp4" }));
                        } else {
                            window.preloaded[id] = URL.createObjectURL(new Blob([await (await fetch("/assets/content/" + id + ".flac")).arrayBuffer()], { type: "audio/flac" }));
                        }
                    }
                }
            }

            cleanupPreload();
        }

        function cleanupPreload() {
            let keys = Object.keys(window.preloaded).slice(-20);

            for (let key of Object.keys(window.preloaded)) {
                if (!keys.includes(key)) {
                    URL.revokeObjectURL(window.preloaded[key]);
                    delete window.preloaded[key];
                }
            }
        }
    </script>

    <iframe id="modal" src="ui/modal.php" style="width: 100vw; height: 100vh; border: none; inset: 0; position: fixed; z-index: 99999; display: none;"></iframe>
    <script>
        function openModal(title, url, hideTitle) {
            document.getElementById("modal").style.display = "";

            if (hideTitle) {
                document.getElementById("modal").contentWindow.document.getElementById("modal-header").style.display = "none";
            } else {
                document.getElementById("modal").contentWindow.document.getElementById("modal-header").style.display = "";
            }

            document.getElementById("modal").contentWindow.document.getElementById("modal-title").innerText = title;
            document.getElementById("modal").contentWindow.document.getElementById("modal-frame").src = url;
            document.getElementById("modal").contentWindow.document.getElementById("modal-frame").style.height = "calc(100vh - 130px)";
            document.getElementById("modal").contentWindow._modal.show();
        }

        document.getElementById("modal").onload = () => {
            if (localStorage.getItem("welcomed") !== "true") {
                openModal("Welcome to Mist", "welcome.php", true);
            } else {
                if (localStorage.getItem("lastUpdate") !== "<?= trim(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/version")) ?>|<?= trim(file_exists("/opt/spotify/build.txt") ? file_get_contents("/opt/spotify/build.txt") : "trunk") ?>") {
                    openModal("What's new in Mist?", "update.php", true);
                }
            }
        }

        if (!localStorage.getItem("rich-presence")) {
            localStorage.setItem("rich-presence", "true");
        }

        if (localStorage.getItem("rich-presence") === "false") {
            window.discordRichPresenceData = null;
        } else {
            window.discordRichPresenceData = {
                largeImageKey: "logo"
            };
        }
    </script>
</body>
</html>