File size: 21,575 Bytes
f4fd3b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18d1fff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4fd3b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311b8c4
 
 
 
f4fd3b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57d4d36
32d910e
 
57d4d36
18d1fff
 
32d910e
18d1fff
 
 
 
 
f4fd3b7
 
32d910e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4fd3b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
const videoContainer = document.querySelector("#videocontainer");
const fullscreenButton = document.querySelector("#fullscreen");
const playpauseButton = document.querySelector("#playpause");
const nextButton = document.querySelector("#next");
const previousButton = document.querySelector("#previous");
const mainControls = document.querySelector("#main-controls");
const otherControls = document.querySelector("#other-controls");
const playPauseIcon = document.querySelector("#playpause i");
const fullscreenIcon = document.querySelector("#fullscreen i");
const muteIcon = document.querySelector("#mute i");
const input = document.querySelector("input[list=tags]");
const tagsDatalist = document.querySelector("#tags");
const generalTagsList = document.querySelector("#general-tags");
const characterTagsList = document.querySelector("#character-tags");
const artistTagsList = document.querySelector("#artist-tags");
const copyrightTagsList = document.querySelector("#copyright-tags");
const muteButton = document.querySelector("#mute");
const tagsToExclude = ["animated", "artist_unknown", "presumed"];
const questionableContentButton = document.querySelector(
  "#questionable-content"
);
const explicitContentButton = document.querySelector("#explicit-content");
const showTitlesButton = document.querySelector("#show-titles");
const title = document.querySelector("#title");
const titleDelaySlider = document.querySelector("#title-delay");

const SHOW_TITLE_DURATION = 2500;
const PREVIOUS = 0;
const CURRENT = 1;
const NEXT = 2;
const PLAYING = 1;
const GENERAL = 0;
const ARTIST = 1;
const COPYRIGHT = 3;
const CHARACTER = 4;

const videos = document.querySelectorAll("video");
const videoPlayers = [videos[PREVIOUS], videos[CURRENT], videos[NEXT]];
const videoData = [null, null, null];
const videoIndexes = [null, null, null];

var tagsByName = new Map();
var playlist = [];
var currentTag = null;
var skipNextPlayPause = false;
var musicPlayer = null;
var muted = true;
let options = {
  "show-titles": false,
  "title-delay": 0,
  "questionable-content": false,
  "explicit-content": false,
};

let hideTitleTimeout;
let showTitleTimeout;

Array.prototype.rotate = function (n) {
  while (this.length && n < 0) n += this.length;
  this.push.apply(this, this.splice(0, n));
  return this;
};

function playPlaylist(tag, videoId) {
  currentTag = tag;
  var count;
  if (!tag) {
    count = 50000;
  } else {
    count = tagsByName.get(tag).count;
  }
  saveTagToUrl(currentTag);

  playlist = shuffle(Array.from(Array(count).keys()).map((n) => ++n));

  videoIndexes[NEXT] = 0;

  const videoDataPromise = videoId
    ? fetchVideoDataById(videoId)
    : fetchVideoData(videoIndexes[NEXT], 1);
  videoDataPromise
    .then((data) => {
      videoIndexes[NEXT] = data.index;
      preloadVideo(data.video, NEXT);
    })
    .then(playNextPreloadedVideo);
}

function shuffle(array) {
  var currentIndex = array.length,
    temporaryValue,
    randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

function shiftIndex(index, offset) {
  // increase or decrease index with wraparound
  return (index + offset + playlist.length) % playlist.length;
}

async function fetchVideoData(index, direction) {
  var url = "/api/post.json?limit=1&page=" + playlist[index] + "&tags=";
  if (currentTag) {
    url = url + useUnderscores(currentTag);
  }
  url = url + explicitUrlFilter();
  return fetchNextValidVideoData(url, index, direction);
}

async function fetchVideoDataById(videoId) {
  var url = "/api/post.json?tags=id:" + videoId;
  return fetchNextValidVideoData(url, 1, 1);
}

function videoIsValid(video) {
  return (
    video &&
    video.file_url &&
    (video.file_ext === "mp4" || video.file_ext === "webm") &&
    video.id
  );
}

function explicitUrlFilter() {
  const questionable = questionableContentButton.checked;
  const explicit = explicitContentButton.checked;
  if (!questionable && !explicit) {
    return " rating:safe";
  } else if (questionable && !explicit) {
    return " -rating:explicit";
  } else {
    return "";
  }
}

function tagIsValid(tag) {
  return tagsByName.has(tag);
}

function showPauseIcon() {
  playPauseIcon.innerHTML = "pause";
}

function showPlayIcon() {
  playPauseIcon.innerHTML = "play_arrow";
}

function toggleControlsOnTouch(event) {
  toggleControls();
  if (event.target === videoPlayers[CURRENT]) {
    event.preventDefault();
  }
}

function toggleMute() {
  muted = !muted;
  if (muted) {
    musicPlayer.pauseVideo();
    muteIcon.innerHTML = "volume_off";
  } else {
    musicPlayer.playVideo();
    muteIcon.innerHTML = "volume_up";
  }
}

function togglePause() {
  if (skipNextPlayPause) {
    skipNextPlayPause = false;
    return;
  }
  if (isPaused()) {
    videoPlayers[CURRENT].play();
    if (!muted) {
      musicPlayer.playVideo();
    }
  } else {
    videoPlayers[CURRENT].pause();
    musicPlayer.pauseVideo();
  }
}

const FRAME_RATE = 1 / 24;

function previousFrame() {
  videoPlayers[CURRENT].currentTime = Math.max(
    0,
    videoPlayers[CURRENT].currentTime - FRAME_RATE
  );
}

function nextFrame() {
  videoPlayers[CURRENT].currentTime = Math.min(
    videoPlayers[CURRENT].duration,
    videoPlayers[CURRENT].currentTime + FRAME_RATE
  );
}
function isPaused() {
  return videoPlayers[CURRENT].paused || videoPlayers[CURRENT].ended;
}

function handleNext() {
  if (isPaused()) {
    nextFrame();
  } else {
    playNextPreloadedVideo();
  }
}

function handlePrevious() {
  if (isPaused()) {
    previousFrame();
  } else {
    playPreviousPreloadedVideo();
  }
}

function playNextPreloadedVideo() {
  playPreloadedVideo(1);
}

function playPreviousPreloadedVideo() {
  playPreloadedVideo(-1);
}

function playPreloadedVideo(direction) {
  const nextVideoIndexToPreload = CURRENT + direction;
  const previouslyPlayingVideo = videoPlayers[CURRENT];

  if (videoData[nextVideoIndexToPreload] === null) {
    return;
  }
  videoData.rotate(direction);
  videoPlayers.rotate(direction);
  videoIndexes.rotate(direction);

  videoData[nextVideoIndexToPreload] = null;
  videoIndexes[nextVideoIndexToPreload] = shiftIndex(
    videoIndexes[CURRENT],
    direction
  );

  removeVideoEventListeners(previouslyPlayingVideo);
  addVideoEventListeners(videoPlayers[CURRENT]);

  removeClass(previouslyPlayingVideo, "active");
  addClass(videoPlayers[CURRENT], "active");

  previouslyPlayingVideo.pause();
  previouslyPlayingVideo.currentTime = 0;
  playVideo();
  fetchVideoData(videoIndexes[nextVideoIndexToPreload], direction).then(
    (data) => {
      videoIndexes[nextVideoIndexToPreload] = data.index;
      preloadVideo(data.video, nextVideoIndexToPreload);
    }
  );
}

function removeClass(element, cssClass) {
  if (element.classList.contains(cssClass)) {
    element.classList.remove(cssClass);
  }
}

function addClass(element, cssClass) {
  if (!element.classList.contains(cssClass)) {
    element.classList.add(cssClass);
  }
}

function preloadVideo(video, index) {
  videoData[index] = video;
  videoPlayers[index].src = video.file_url;
}

async function playVideo() {
    const video = videoPlayers[CURRENT];
    
    // 1. Reset tags/UI first
    var tags = videoData[CURRENT].tags.split(" ").map(makeReadable);
    hideTitle();
    showTitleAfterDelay(tags);
    addVideoTagsToUi(tags);
    saveVideoIdToUrl(videoData[CURRENT]);

    // 2. Play with a safety catch
    try {
        // Ensure video is unmuted if you want sound, or stay muted for autoplay
        video.muted = true; 
        await video.play();
    } catch (err) {
        if (err.name !== "AbortError") {
            console.error("Playback error:", err);
        }
        // AbortErrors are ignored because they just mean the video switched quickly
    }
}

function showTitleAfterDelay(tags) {
  clearTimeout(showTitleTimeout);
  if (showTitlesButton.checked) {
    const longestPossibleDelay =
      videoPlayers[CURRENT].duration * 1000 - SHOW_TITLE_DURATION;
    const delayUntilTitle = Math.min(
      options["title-delay"] * 1000,
      longestPossibleDelay
    );
    showTitleTimeout = setTimeout(
      () => showTitleBriefly(tags),
      delayUntilTitle
    );
  }
}

function showTitleBriefly(tags) {
  const titles = tags.filter(isTagType(COPYRIGHT));
  if (titles.length === 0) {
    titles.push("unknown");
  }
  title.innerHTML = pickBestTitle(titles);
  showTitle();
  clearTimeout(hideTitleTimeout);
  hideTitleTimeout = setTimeout(hideTitle, SHOW_TITLE_DURATION);
}

function pickBestTitle(titles) {
  return titles[titles.length - 1];
}

function addVideoTagsToUi(tags) {
  const artistTags = tags.filter(isTagType(ARTIST));
  const generalTags = tags.filter(isTagType(GENERAL));
  const copyrightTags = tags.filter(isTagType(COPYRIGHT));
  const characterTags = tags.filter(isTagType(CHARACTER));

  generalTagsList.innerHTML = generateTagsHtml(generalTags);
  artistTagsList.innerHTML = generateTagsHtml(artistTags);
  copyrightTagsList.innerHTML = generateTagsHtml(copyrightTags);
  characterTagsList.innerHTML = generateTagsHtml(characterTags);
}

function generateTagsHtml(tags) {
  var tagsHtml = "";

  for (tag of tags) {
    if (tagIsValid(tag)) {
      tagsHtml = tagsHtml + "<li><a ";
      if (currentTag === tag) {
        tagsHtml = tagsHtml + 'class="current-tag" ';
      }
      tagsHtml = tagsHtml + 'href="?tag=' + tag + '">' + tag + "</a></li>";
    }
  }
  return tagsHtml;
}

function isTagType(tagType) {
  return (tagName) => {
    const tag = tagsByName.get(tagName);
    return tag && tag.type === tagType;
  };
}

var fullScreenEnabled = !!(
  document.fullscreenEnabled ||
  document.mozFullScreenEnabled ||
  document.msFullscreenEnabled ||
  document.webkitSupportsFullscreen ||
  document.webkitFullscreenEnabled ||
  document.createElement("video").webkitRequestFullScreen
);
if (!fullScreenEnabled) {
  fullscreenButton.style.display = "none";
}
var isFullScreen = function () {
  return !!(
    document.fullScreen ||
    document.webkitIsFullScreen ||
    document.mozFullScreen ||
    document.msFullscreenElement ||
    document.fullscreenElement
  );
};
var setFullscreenData = function (state) {
  videoContainer.setAttribute("data-fullscreen", !!state);
  fullscreenIcon.innerHTML = state ? "fullscreen_exit" : "fullscreen";
};
var handleFullscreen = function () {
  if (isFullScreen()) {
    if (document.exitFullscreen) document.exitFullscreen();
    else if (document.mozCancelFullScreen) document.mozCancelFullScreen();
    else if (document.webkitCancelFullScreen) document.webkitCancelFullScreen();
    else if (document.msExitFullscreen) document.msExitFullscreen();
    setFullscreenData(false);
  } else {
    if (videoContainer.requestFullscreen) videoContainer.requestFullscreen();
    else if (videoContainer.mozRequestFullScreen)
      videoContainer.mozRequestFullScreen();
    else if (videoContainer.webkitRequestFullScreen)
      videoContainer.webkitRequestFullScreen();
    else if (videoContainer.msRequestFullscreen)
      videoContainer.msRequestFullscreen();
    setFullscreenData(true);
  }
};
function saveOptions(options) {
  localStorage.setItem("options", JSON.stringify(options));
}
explicitContentButton.addEventListener("change", () => {
  options["explicit-content"] = explicitContentButton.checked;
  saveOptions(options);
});
questionableContentButton.addEventListener("change", () => {
  options["questionable-content"] = questionableContentButton.checked;
  saveOptions(options);
});
showTitlesButton.addEventListener("change", () => {
  if (showTitlesButton.checked) {
    options["show-titles"] = true;
    if (videoData[CURRENT] && videoData[CURRENT].tags) {
      var tags = videoData[CURRENT].tags.split(" ").map(makeReadable);
      showTitleAfterDelay(tags);
    }
  } else {
    options["show-titles"] = false;
    hideTitle();
  }
  saveOptions(options);
});
titleDelaySlider.addEventListener("change", () => {
  options["title-delay"] = titleDelaySlider.value;
  saveOptions(options);
});
document.addEventListener("fullscreenchange", (e) =>
  setFullscreenData(!!(document.fullScreen || document.fullscreenElement))
);
document.addEventListener("webkitfullscreenchange", () =>
  setFullscreenData(!!document.webkitIsFullScreen)
);
document.addEventListener("mozfullscreenchange", () =>
  setFullscreenData(!!document.mozFullScreen)
);
document.addEventListener("msfullscreenchange", () =>
  setFullscreenData(!!document.msFullscreenElement)
);
fullscreenButton.addEventListener("click", handleFullscreen);
playpauseButton.addEventListener("click", togglePause);
nextButton.addEventListener("click", handleNext);
previousButton.addEventListener("click", handlePrevious);
muteButton.addEventListener("click", toggleMute);
generalTagsList.addEventListener("click", tagClicked);
artistTagsList.addEventListener("click", tagClicked);
copyrightTagsList.addEventListener("click", tagClicked);
characterTagsList.addEventListener("click", tagClicked);

function tagClicked(event) {
  const node = event.target;
  if (node.tagName === "A") {
    event.preventDefault();
    const tag = parseTagFromQueryParams(node.getAttribute("href"));
    if (currentTag !== tag) {
      setCurrentTag(tag);
    } else {
      clearCurrentTag();
    }
  }
}

var userActivity, activityCheck, inactivityTimeout, controlsHovered;

videoContainer.addEventListener("mousemove", (event) => (userActivity = true));
mainControls.addEventListener("click", (event) => (userActivity = true));
otherControls.addEventListener("click", (event) => (userActivity = true));

function removeVideoEventListeners(videoElement) {
  videoElement.removeEventListener("touchstart", toggleControlsOnTouch);
  videoElement.removeEventListener("click", togglePause);
  videoElement.removeEventListener("mousedown", preventNextPlayPause);
  videoElement.removeEventListener("ended", playNextPreloadedVideo);
  videoElement.removeEventListener("play", showPauseIcon);
  videoElement.removeEventListener("pause", showPlayIcon);
}

function addVideoEventListeners(videoElement) {
  videoElement.addEventListener("touchstart", toggleControlsOnTouch);
  videoElement.addEventListener("click", togglePause);
  videoElement.addEventListener("mousedown", preventNextPlayPause);
  videoElement.addEventListener("ended", playNextPreloadedVideo);
  videoElement.addEventListener("play", showPauseIcon);
  videoElement.addEventListener("pause", showPlayIcon);
}

function tagSearchActive() {
  return document.activeElement === input;
}

function hideControlsTimeout() {
  return controlsHovered ? 3500 : 750;
}

activityCheck = setInterval(() => {
  if (userActivity) {
    userActivity = false;
    showControls();

    // Clear any existing inactivity timeout to start the timer over
    clearTimeout(inactivityTimeout);

    // In X seconds, if no more activity has occurred
    // the user will be considered inactive
    inactivityTimeout = setTimeout(() => {
      // Protect against the case where the inactivity timeout can trigger
      // before the next user activity is picked up  by the
      // activityCheck loop.
      if (!userActivity && !tagSearchActive()) {
        hideControls();
      }
    }, hideControlsTimeout());
  }
}, 250);

async function getTags() {
    const targetUrl = "https://www.sakugabooru.com/tag.json?limit=1500&order=count";
    // corsproxy.io is usually more stable for large JSON sets
    const proxyUrl = `https://corsproxy.io/?${encodeURIComponent(targetUrl)}`;
    
    try {
        const response = await fetch(proxyUrl);
        if (!response.ok) throw new Error('Network error');
        return await response.json();
    } catch (error) {
        console.error("Fetch failed, trying cache...");
        return JSON.parse(localStorage.getItem("tags")) || [];
    }
}

async function fetchNextValidVideoData(tags, page) {
    // FIX: Ensure 'tags' doesn't contain a path by accident
    const cleanTags = tags.replace('/api/', ''); 
    const targetUrl = `https://www.sakugabooru.com/post.json?limit=1&page=${page}&tags=${cleanTags}`;
    const proxyUrl = `https://corsproxy.io/?${encodeURIComponent(targetUrl)}`;
    
    try {
        const response = await fetch(proxyUrl);
        if (!response.ok) return null;
        return await response.json();
    } catch (error) {
        return null;
    }
}

function putTagsInForm(tags) {
  var innerString = "";
  for (tag of tags) {
    innerString = innerString + "<option>" + tag + "</option>";
  }
  tagsDatalist.innerHTML = innerString;
}

mainControls.addEventListener("mouseenter", () => {
  controlsHovered = true;
});

mainControls.addEventListener("mouseleave", () => {
  controlsHovered = false;
});

otherControls.addEventListener("mouseenter", () => {
  controlsHovered = true;
});

otherControls.addEventListener("mouseleave", () => {
  controlsHovered = false;
});

input.addEventListener("input", () => {
  const tag = input.value;
  if (tagIsValid(tag)) {
    playPlaylist(tag, null);
  }
});
input.addEventListener("keyup", (event) => {
  if (event.key === "Enter") {
    input.blur();
  }
});
input.addEventListener("blur", (event) => {
  hideControls();
  input.value = "";
});

function preventNextPlayPause() {
  if (tagSearchActive()) {
    skipNextPlayPause = true;
  }
}

window.addEventListener("keyup", (event) => {
  if (event.target === input) {
    return;
  }
  if (event.key === "ArrowRight") {
    handleNext();
  }
  if (event.key === "ArrowLeft") {
    handlePrevious();
  }
  if (event.key === " ") {
    togglePause();
  }
});
window.addEventListener("popstate", (event) => {
  setCurrentTag(event.state.tag);
});

function setCurrentTag(tag) {
  if (tag && tag !== currentTag) {
    playPlaylist(tag, null);
  }
}

function clearCurrentTag() {
  if (currentTag) {
    playPlaylist(null, null);
  }
}

function toggleControls() {
  if (controlsHidden()) {
    showControls();
  } else {
    hideControls();
  }
}

function controlsHidden() {
  return videoContainer.classList.contains("fade-out");
}

function titleHidden() {
  return title.classList.contains("fade-out");
}

function showTitle() {
  if (titleHidden()) {
    title.classList.remove("fade-out");
  }
}

function hideTitle() {
  if (!titleHidden()) {
    title.classList.add("fade-out");
  }
}

function showControls() {
  if (controlsHidden()) {
    videoContainer.classList.remove("fade-out");
  }
}

function hideControls() {
  if (!controlsHidden()) {
    videoContainer.classList.add("fade-out");
  }
}

function useUnderscores(tag) {
  return tag.split(" ").join("_");
}

function makeReadable(tag) {
  return tag.split("_").join(" ");
}

function saveTagToUrl(tag) {
  if (tag !== parseTagFromUrl()) {
    if (tag) {
      history.pushState(
        { tag: tag },
        tag + " videos",
        "?tag=" + encodeURIComponent(useUnderscores(tag))
      );
    } else {
      history.pushState({ tag: tag }, "All videos", "./");
    }
  }
}

function saveVideoIdToUrl(video) {
  const tag = new URLSearchParams(window.location.search).get("tag");
  var queryParams = "?video=" + video.id;
  if (tag) {
    queryParams += "&tag=" + tag;
  }
  history.replaceState(history.state, tag + " videos", queryParams);
}

function parseTagFromUrl() {
  return parseTagFromQueryParams(window.location.search);
}

function parseTagFromQueryParams(queryParams) {
  const encodedTag = new URLSearchParams(queryParams).get("tag");
  if (encodedTag) {
    return makeReadable(decodeURIComponent(encodedTag));
  } else {
    return null;
  }
}

function parseVideoIdFromUrl() {
  const videoId = new URLSearchParams(window.location.search).get("video");
  return videoId ? videoId : null;
}

function putTagsInUi(tags) {
  tagsByName = new Map(
    tags.filter(shouldIncludeTag).map((tag) => [makeReadable(tag.name), tag])
  );
  putTagsInForm(tagsByName.keys());
}

function shouldIncludeTag(tag) {
  return !tagsToExclude.includes(tag.name);
}

function setupMusic() {
  var youtubeScriptTag = document.createElement("script");
  youtubeScriptTag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName("script")[0];
  firstScriptTag.parentNode.insertBefore(youtubeScriptTag, firstScriptTag);
}

// required by youtube script
function onYouTubeIframeAPIReady() {
  musicPlayer = new YT.Player("youtube-player");
}

function startPage() {
  setupMusic();
  addClass(videoPlayers[CURRENT], "active");
  addVideoEventListeners(videoPlayers[CURRENT]);
  const tag = parseTagFromUrl();
  const videoId = parseVideoIdFromUrl();
  if (tag) {
    history.replaceState({ tag: tag }, null);
  }
  const tagsSavedFuture = getTags().then((tags) => {
    localStorage.setItem("tags", JSON.stringify(tags));
    putTagsInUi(tags);
  });
  const cachedTags = JSON.parse(localStorage.getItem("tags"));
  options = JSON.parse(localStorage.getItem("options")) || options;
  showTitlesButton.checked = options["show-titles"];
  questionableContentButton.checked = options["questionable-content"];
  explicitContentButton.checked = options["explicit-content"];
  titleDelaySlider.value = options["title-delay"];
  if (cachedTags) {
    putTagsInUi(cachedTags);
    playPlaylist(tag, videoId);
  } else {
    tagsSavedFuture.then(() => playPlaylist(tag, videoId));
  }
}

startPage();