summaryrefslogtreecommitdiff
path: root/webroot/js/app.js
blob: 1d855beee836ae2588d78e394da615916bca59ce (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
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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
import { h, Component } from '/js/web_modules/preact.js';
import htm from '/js/web_modules/htm.js';
const html = htm.bind(h);

import { OwncastPlayer } from './components/player.js';
import SocialIconsList from './components/platform-logos-list.js';
import UsernameForm from './components/chat/username.js';
import VideoPoster from './components/video-poster.js';
import Followers from './components/federation/followers.js';

import Chat from './components/chat/chat.js';
import Websocket, {
  CALLBACKS,
  SOCKET_MESSAGE_TYPES,
} from './utils/websocket.js';
import { registerChat } from './chat/register.js';

import ExternalActionModal, {
  ExternalActionButton,
} from './components/external-action-modal.js';

import FediverseFollowModal, {
  FediverseFollowButton,
} from './components/fediverse-follow-modal.js';

import { NotifyButton, NotifyModal } from './components/notification.js';

import {
  addNewlines,
  checkUrlPathForDisplay,
  classNames,
  debounce,
  getLocalStorage,
  getOrientation,
  hasTouchScreen,
  makeLastOnlineString,
  parseSecondsToDurationString,
  pluralize,
  ROUTE_RECORDINGS,
  setLocalStorage,
} from './utils/helpers.js';
import {
  CHAT_MAX_MESSAGE_LENGTH,
  EST_SOCKET_PAYLOAD_BUFFER,
  HEIGHT_SHORT_WIDE,
  KEY_ACCESS_TOKEN,
  KEY_CHAT_DISPLAYED,
  KEY_USERNAME,
  MESSAGE_OFFLINE,
  MESSAGE_ONLINE,
  ORIENTATION_PORTRAIT,
  OWNCAST_LOGO_LOCAL,
  TEMP_IMAGE,
  TIMER_DISABLE_CHAT_AFTER_OFFLINE,
  TIMER_STATUS_UPDATE,
  TIMER_STREAM_DURATION_COUNTER,
  URL_CONFIG,
  URL_OWNCAST,
  URL_STATUS,
  URL_VIEWER_PING,
  WIDTH_SINGLE_COL,
} from './utils/constants.js';
import { checkIsModerator } from './utils/chat.js';
import TabBar from './components/tab-bar.js';

import TabBar from './components/tab-bar.js';

export default class App extends Component {
  constructor(props, context) {
    super(props, context);

    const chatStorage = getLocalStorage(KEY_CHAT_DISPLAYED);
    this.hasTouchScreen = hasTouchScreen();
    this.windowBlurred = false;

    this.state = {
      websocket: null,
      canChat: false, // all of chat functionality (panel + username)
      displayChatPanel: chatStorage === null ? true : chatStorage === 'true', // just the chat panel
      chatInputEnabled: false, // chat input box state
      accessToken: null,
      username: getLocalStorage(KEY_USERNAME),
      isModerator: false,

      isRegistering: false,
      touchKeyboardActive: false,

      configData: {
        loading: true,
      },
      extraPageContent: '',

      playerActive: false, // player object is active
      streamOnline: null, // stream is active/online
      isPlaying: false, // player is actively playing video

      // status
      streamStatusMessage: MESSAGE_OFFLINE,
      viewerCount: '',
      lastDisconnectTime: null,

      // dom
      windowWidth: window.innerWidth,
      windowHeight: window.innerHeight,
      orientation: getOrientation(this.hasTouchScreen),

      // modals
      externalActionModalData: null,
      fediverseModalData: null,

      // routing & tabbing
      section: '',
      sectionId: '',
    };

    // timers
    this.playerRestartTimer = null;
    this.offlineTimer = null;
    this.statusTimer = null;
    this.disableChatInputTimer = null;
    this.streamDurationTimer = null;

    // misc dom events
    this.handleChatPanelToggle = this.handleChatPanelToggle.bind(this);
    this.handleUsernameChange = this.handleUsernameChange.bind(this);
    this.handleFormFocus = this.handleFormFocus.bind(this);
    this.handleFormBlur = this.handleFormBlur.bind(this);
    this.handleWindowBlur = this.handleWindowBlur.bind(this);
    this.handleWindowFocus = this.handleWindowFocus.bind(this);
    this.handleWindowResize = debounce(this.handleWindowResize.bind(this), 250);

    this.handleOfflineMode = this.handleOfflineMode.bind(this);
    this.handleOnlineMode = this.handleOnlineMode.bind(this);
    this.disableChatInput = this.disableChatInput.bind(this);
    this.setCurrentStreamDuration = this.setCurrentStreamDuration.bind(this);

    this.handleKeyPressed = this.handleKeyPressed.bind(this);
    this.displayExternalAction = this.displayExternalAction.bind(this);
    this.closeExternalActionModal = this.closeExternalActionModal.bind(this);
    this.displayFediverseFollowModal =
      this.displayFediverseFollowModal.bind(this);
    this.closeFediverseFollowModal = this.closeFediverseFollowModal.bind(this);
    this.displayNotificationModal = this.displayNotificationModal.bind(this);
    this.closeNotificationModal = this.closeNotificationModal.bind(this);

    // player events
    this.handlePlayerReady = this.handlePlayerReady.bind(this);
    this.handlePlayerPlaying = this.handlePlayerPlaying.bind(this);
    this.handlePlayerEnded = this.handlePlayerEnded.bind(this);
    this.handlePlayerError = this.handlePlayerError.bind(this);

    // fetch events
    this.getConfig = this.getConfig.bind(this);
    this.getStreamStatus = this.getStreamStatus.bind(this);

    // user events
    this.handleWebsocketMessage = this.handleWebsocketMessage.bind(this);

    // chat
    this.hasConfiguredChat = false;
    this.setupChatAuth = this.setupChatAuth.bind(this);
    this.disableChat = this.disableChat.bind(this);
  }

  componentDidMount() {
    this.getConfig();
    if (!this.hasTouchScreen) {
      window.addEventListener('resize', this.handleWindowResize);
    }
    window.addEventListener('blur', this.handleWindowBlur);
    window.addEventListener('focus', this.handleWindowFocus);
    if (this.hasTouchScreen) {
      window.addEventListener('orientationchange', this.handleWindowResize);
    }
    window.addEventListener('keypress', this.handleKeyPressed);
    this.player = new OwncastPlayer();
    this.player.setupPlayerCallbacks({
      onReady: this.handlePlayerReady,
      onPlaying: this.handlePlayerPlaying,
      onEnded: this.handlePlayerEnded,
      onError: this.handlePlayerError,
    });
    this.player.init();

    this.registerServiceWorker();

    // check routing
    this.getRoute();
  }

  componentWillUnmount() {
    // clear all the timers
    clearInterval(this.playerRestartTimer);
    clearInterval(this.offlineTimer);
    clearInterval(this.statusTimer);
    clearTimeout(this.disableChatInputTimer);
    clearInterval(this.streamDurationTimer);
    window.removeEventListener('resize', this.handleWindowResize);
    window.removeEventListener('blur', this.handleWindowBlur);
    window.removeEventListener('focus', this.handleWindowFocus);
    window.removeEventListener('keypress', this.handleKeyPressed);
    if (this.hasTouchScreen) {
      window.removeEventListener('orientationchange', this.handleWindowResize);
    }
  }

  getRoute() {
    const routeInfo = checkUrlPathForDisplay();
    this.setState({
      ...routeInfo,
    });
  }

  // fetch /config data
  getConfig() {
    fetch(URL_CONFIG)
      .then((response) => {
        if (!response.ok) {
          throw new Error(`Network response was not ok ${response.ok}`);
        }
        return response.json();
      })
      .then((json) => {
        this.setConfigData(json);
      })
      .catch((error) => {
        this.handleNetworkingError(`Fetch config: ${error}`);
      });
  }

  // fetch stream status
  getStreamStatus() {
    fetch(URL_STATUS)
      .then((response) => {
        if (!response.ok) {
          throw new Error(`Network response was not ok ${response.ok}`);
        }
        return response.json();
      })
      .then((json) => {
        this.updateStreamStatus(json);
      })
      .catch((error) => {
        this.handleOfflineMode();
        this.handleNetworkingError(`Stream status: ${error}`);
      });

    // Ping the API to let them know we're an active viewer
    fetch(URL_VIEWER_PING).catch((error) => {
      this.handleOfflineMode();
      this.handleNetworkingError(`Viewer PING error: ${error}`);
    });
  }

  setConfigData(data = {}) {
    const { name, summary, chatDisabled, notifications } = data;
    window.document.title = name;

    // If this is the first time setting the config
    // then setup chat if it's enabled.
    if (!this.hasConfiguredChat && !chatDisabled) {
      this.setupChatAuth();
    }

    this.hasConfiguredChat = true;

    this.setState({
      canChat: !chatDisabled,
      notifications,
      configData: {
        ...data,
        summary: summary && addNewlines(summary),
      },
    });
  }

  // handle UI things from stream status result
  updateStreamStatus(status = {}) {
    const { streamOnline: curStreamOnline } = this.state;

    if (!status) {
      return;
    }
    const {
      viewerCount,
      online,
      lastConnectTime,
      streamTitle,
      lastDisconnectTime,
    } = status;

    this.setState({
      viewerCount,
      lastConnectTime,
      streamOnline: online,
      streamTitle,
      lastDisconnectTime,
    });

    if (status.online !== curStreamOnline) {
      if (status.online) {
        // stream has just come online.
        this.handleOnlineMode();
      } else {
        // stream has just flipped offline or app just got loaded and stream is offline.
        this.handleOfflineMode(lastDisconnectTime);
      }
    }
  }

  // when videojs player is ready, start polling for stream
  handlePlayerReady() {
    this.getStreamStatus();
    this.statusTimer = setInterval(this.getStreamStatus, TIMER_STATUS_UPDATE);
  }

  handlePlayerPlaying() {
    this.setState({
      isPlaying: true,
    });
  }

  // likely called some time after stream status has gone offline.
  // basically hide video and show underlying "poster"
  handlePlayerEnded() {
    this.setState({
      playerActive: false,
      isPlaying: false,
    });
  }

  handlePlayerError() {
    // do something?
    this.handleOfflineMode();
    this.handlePlayerEnded();
  }

  // stop status timer and disable chat after some time.
  handleOfflineMode(lastDisconnectTime) {
    clearInterval(this.streamDurationTimer);

    if (lastDisconnectTime) {
      const remainingChatTime =
        TIMER_DISABLE_CHAT_AFTER_OFFLINE -
        (Date.now() - new Date(lastDisconnectTime));
      const countdown = remainingChatTime < 0 ? 0 : remainingChatTime;
      if (countdown > 0) {
        this.setState({
          chatInputEnabled: true,
        });
      }
      this.disableChatInputTimer = setTimeout(this.disableChatInput, countdown);
    }

    this.setState({
      streamOnline: false,
      streamStatusMessage: MESSAGE_OFFLINE,
    });

    if (this.player.vjsPlayer && this.player.vjsPlayer.paused()) {
      this.handlePlayerEnded();
    }

    if (this.windowBlurred) {
      document.title = ` 🔴 ${
        this.state.configData && this.state.configData.name
      }`;
    }
  }

  // play video!
  handleOnlineMode() {
    this.player.startPlayer();
    clearTimeout(this.disableChatInputTimer);
    this.disableChatInputTimer = null;

    this.streamDurationTimer = setInterval(
      this.setCurrentStreamDuration,
      TIMER_STREAM_DURATION_COUNTER
    );

    this.setState({
      playerActive: true,
      streamOnline: true,
      chatInputEnabled: true,
      streamTitle: '',
      streamStatusMessage: MESSAGE_ONLINE,
    });

    if (this.windowBlurred) {
      document.title = ` 🟢 ${
        this.state.configData && this.state.configData.name
      }`;
    }
  }

  setCurrentStreamDuration() {
    let streamDurationString = '';
    if (this.state.lastConnectTime) {
      const diff = (Date.now() - Date.parse(this.state.lastConnectTime)) / 1000;
      streamDurationString = parseSecondsToDurationString(diff);
    }
    this.setState({
      streamStatusMessage: `${MESSAGE_ONLINE} ${streamDurationString}`,
    });
  }

  handleUsernameChange(newName) {
    this.setState({
      username: newName,
    });

    this.sendUsernameChange(newName);
  }

  handleFormFocus() {
    if (this.hasTouchScreen) {
      this.setState({
        touchKeyboardActive: true,
      });
    }
  }

  handleFormBlur() {
    if (this.hasTouchScreen) {
      this.setState({
        touchKeyboardActive: false,
      });
    }
  }

  handleChatPanelToggle() {
    const { displayChatPanel: curDisplayed } = this.state;

    const displayChat = !curDisplayed;
    setLocalStorage(KEY_CHAT_DISPLAYED, displayChat);
    this.setState({
      displayChatPanel: displayChat,
    });
  }

  disableChatInput() {
    this.setState({
      chatInputEnabled: false,
    });
  }

  handleNetworkingError(error) {
    console.error(`>>> App Error: ${error}`);
  }

  handleWindowResize() {
    this.setState({
      windowWidth: window.innerWidth,
      windowHeight: window.innerHeight,
      orientation: getOrientation(this.hasTouchScreen),
    });
  }

  handleWindowBlur() {
    this.windowBlurred = true;
  }

  handleWindowFocus() {
    this.windowBlurred = false;
    window.document.title = this.state.configData && this.state.configData.name;
  }

  handleSpaceBarPressed(e) {
    e.preventDefault();
    if (this.state.isPlaying) {
      this.setState({
        isPlaying: false,
      });
      try {
        this.player.vjsPlayer.pause();
      } catch (err) {
        console.warn(err);
      }
    } else {
      this.setState({
        isPlaying: true,
      });
      this.player.vjsPlayer.play();
    }
  }

  handleMuteKeyPressed() {
    const muted = this.player.vjsPlayer.muted();
    const volume = this.player.vjsPlayer.volume();

    try {
      if (volume === 0) {
        this.player.vjsPlayer.volume(0.5);
        this.player.vjsPlayer.muted(false);
      } else {
        this.player.vjsPlayer.muted(!muted);
      }
    } catch (err) {
      console.warn(err);
    }
  }

  handleFullScreenKeyPressed() {
    if (this.player.vjsPlayer.isFullscreen()) {
      this.player.vjsPlayer.exitFullscreen();
    } else {
      this.player.vjsPlayer.requestFullscreen();
    }
  }

  handleVolumeSet(factor) {
    this.player.vjsPlayer.volume(this.player.vjsPlayer.volume() + factor);
  }

  handleKeyPressed(e) {
    // Only handle shortcuts if the focus is on the general page body,
    // not a specific input field.
    if (e.target !== document.getElementById('app-body')) {
      return;
    }

    if (this.state.streamOnline) {
      switch (e.code) {
        case 'MediaPlayPause':
        case 'KeyP':
        case 'Space':
          this.handleSpaceBarPressed(e);
          break;
        case 'KeyM':
          this.handleMuteKeyPressed(e);
          break;
        case 'KeyF':
          this.handleFullScreenKeyPressed(e);
          break;
        case 'KeyC':
          this.handleChatPanelToggle();
          break;
        case 'Digit9':
          this.handleVolumeSet(-0.1);
          break;
        case 'Digit0':
          this.handleVolumeSet(0.1);
      }
    }
  }

  displayExternalAction(action) {
    const { username } = this.state;
    if (!action) {
      return;
    }
    const { url: actionUrl, openExternally } = action || {};
    let url = new URL(actionUrl);
    // Append url and username to params so the link knows where we came from and who we are.
    url.searchParams.append('username', username);
    url.searchParams.append('instance', window.location);

    const fullUrl = url.toString();

    if (openExternally) {
      var win = window.open(fullUrl, '_blank');
      win.focus();
      return;
    }
    this.setState({
      externalActionModalData: {
        ...action,
        url: fullUrl,
      },
    });
  }
  closeExternalActionModal() {
    this.setState({
      externalActionModalData: null,
    });
  }

  displayFediverseFollowModal(data) {
    this.setState({ fediverseModalData: data });
  }
  closeFediverseFollowModal() {
    this.setState({ fediverseModalData: null });
  }

  displayNotificationModal(data) {
    this.setState({ notificationModalData: data });
  }
  closeNotificationModal() {
    this.setState({ notificationModalData: null });
  }

  async registerServiceWorker() {
    try {
      const reg = await navigator.serviceWorker.register('/serviceWorker.js', {
        scope: '/',
      });
    } catch (err) {
      console.error('Owncast service worker registration failed!', err);
    }
  }

  handleWebsocketMessage(e) {
    if (e.type === SOCKET_MESSAGE_TYPES.ERROR_USER_DISABLED) {
      // User has been actively disabled on the backend. Turn off chat for them.
      this.handleBlockedChat();
    } else if (
      e.type === SOCKET_MESSAGE_TYPES.ERROR_NEEDS_REGISTRATION &&
      !this.isRegistering
    ) {
      // User needs an access token, so start the user auth flow.
      this.state.websocket.shutdown();
      this.setState({ websocket: null });
      this.setupChatAuth(true);
    } else if (e.type === SOCKET_MESSAGE_TYPES.ERROR_MAX_CONNECTIONS_EXCEEDED) {
      // Chat server cannot support any more chat clients. Turn off chat for them.
      this.disableChat();
    } else if (e.type === SOCKET_MESSAGE_TYPES.CONNECTED_USER_INFO) {
      // When connected the user will return an event letting us know what our
      // user details are so we can display them properly.
      const { user } = e;
      const { displayName } = user;

      this.setState({
        username: displayName,
        isModerator: checkIsModerator(e),
      });
    }
  }

  handleBlockedChat() {
    this.disableChat();
  }

  disableChat() {
    this.state.websocket.shutdown();
    this.setState({ websocket: null, canChat: false });
  }

  async setupChatAuth(force) {
    var accessToken = getLocalStorage(KEY_ACCESS_TOKEN);
    var username = getLocalStorage(KEY_USERNAME);

    if (!accessToken || force) {
      try {
        this.isRegistering = true;
        const registration = await registerChat(this.state.username);
        accessToken = registration.accessToken;
        username = registration.displayName;

        setLocalStorage(KEY_ACCESS_TOKEN, accessToken);
        setLocalStorage(KEY_USERNAME, username);

        this.isRegistering = false;
      } catch (e) {
        console.error('registration error:', e);
      }
    }

    if (this.state.websocket) {
      this.state.websocket.shutdown();
      this.setState({
        websocket: null,
      });
    }

    // Without a valid access token he websocket connection will be rejected.
    const websocket = new Websocket(accessToken);
    websocket.addListener(
      CALLBACKS.RAW_WEBSOCKET_MESSAGE_RECEIVED,
      this.handleWebsocketMessage
    );

    this.setState({
      username,
      websocket,
      accessToken,
    });
  }

  sendUsernameChange(newName) {
    const nameChange = {
      type: SOCKET_MESSAGE_TYPES.NAME_CHANGE,
      newName,
    };
    this.state.websocket.send(nameChange);
  }

  render(props, state) {
    const {
      accessToken,
      chatInputEnabled,
      configData,
      displayChatPanel,
      canChat,
      isModerator,

      isPlaying,
      orientation,
      playerActive,
      streamOnline,
      streamStatusMessage,
      streamTitle,
      touchKeyboardActive,
      username,
      viewerCount,
      websocket,
      windowHeight,
      windowWidth,
      fediverseModalData,
      externalActionModalData,
      notificationModalData,
      notifications,
      lastDisconnectTime,
      section,
      sectionId,
    } = state;

    const {
      version: appVersion,
      logo = TEMP_IMAGE,
      socialHandles = [],
      summary,
      tags = [],
      name,
      extraPageContent,
      chatDisabled,
      externalActions,
      customStyles,
      maxSocketPayloadSize,
      federation = {},
    } = configData;

    const bgUserLogo = { backgroundImage: `url(${logo})` };

    const tagList = tags !== null && tags.length > 0 && tags.join(' #');

    let viewerCountMessage = '';
    if (streamOnline && viewerCount > 0) {
      viewerCountMessage = html`${viewerCount}
      ${pluralize(' viewer', viewerCount)}`;
    } else if (lastDisconnectTime) {
      viewerCountMessage = makeLastOnlineString(lastDisconnectTime);
    }

    const mainClass = playerActive ? 'online' : '';
    const isPortrait =
      this.hasTouchScreen && orientation === ORIENTATION_PORTRAIT;
    const shortHeight = windowHeight <= HEIGHT_SHORT_WIDE && !isPortrait;
    const singleColMode = windowWidth <= WIDTH_SINGLE_COL && !shortHeight;

    const noVideoContent =
      !playerActive || (section === ROUTE_RECORDINGS && sectionId !== '');
    const shouldDisplayChat =
      displayChatPanel && !chatDisabled && !noVideoContent;
    const usernameStyle = chatDisabled ? 'none' : 'flex';
    // const shouldDisplayChat = displayChatPanel && canChat && !chatDisabled;

    const extraAppClasses = classNames({
      'config-loading': configData.loading,

      chat: shouldDisplayChat,
      'no-chat': !shouldDisplayChat,
      'no-video': noVideoContent,
      'chat-hidden': !displayChatPanel && canChat && !chatDisabled, // hide panel
      'chat-disabled': !canChat || chatDisabled,
      'single-col': singleColMode,
      'bg-gray-800': singleColMode && shouldDisplayChat,
      'short-wide': shortHeight && windowWidth > WIDTH_SINGLE_COL,
      'touch-screen': this.hasTouchScreen,
      'touch-keyboard-active': touchKeyboardActive,
    });

    const poster = isPlaying
      ? null
      : html` <${VideoPoster} offlineImage=${logo} active=${streamOnline} /> `;

    // modal buttons
    const notificationsButton =
      notifications &&
      ((notifications.browser.enabled && !!window.chrome) ||
        notifications.textMessages.enabled) &&
      html`<${NotifyButton} onClick=${this.displayNotificationModal} />`;
    const externalActionButtons = html`<div
      id="external-actions-container"
      class="flex flex-row flex-wrap justify-end"
    >
      ${externalActions &&
      externalActions.map(
        function (action) {
          return html`<${ExternalActionButton}
            onClick=${this.displayExternalAction}
            action=${action}
          />`;
        }.bind(this)
      )}

      <!-- fediverse follow button -->
      ${federation.enabled &&
      html`<${FediverseFollowButton}
        onClick=${this.displayFediverseFollowModal}
        federationInfo=${federation}
        serverName=${name}
      />`}
      ${notificationsButton}
    </div>`;

    // modal component
    const externalActionModal =
      externalActionModalData &&
      html`<${ExternalActionModal}
        action=${externalActionModalData}
        onClose=${this.closeExternalActionModal}
      />`;

    const fediverseFollowModal =
      fediverseModalData &&
      html`
        <${ExternalActionModal}
          onClose=${this.closeFediverseFollowModal}
          action=${fediverseModalData}
          useIframe=${false}
          customContent=${html`<${FediverseFollowModal}
            name=${name}
            logo=${logo}
            federationInfo=${federation}
            onClose=${this.closeFediverseFollowModal}
          />`}
        />
      `;

    const notificationModal =
      notificationModalData &&
      html` <${ExternalActionModal}
        onClose=${this.closeNotificationModal}
        action=${notificationModalData}
        useIframe=${false}
        customContent=${html`<${NotifyModal}
          notifications=${notifications}
          streamName=${name}
          accessToken=${accessToken}
        />`}
      />`;

    const chat = this.state.websocket
      ? html`
          <${Chat}
            websocket=${websocket}
            username=${username}
            chatInputEnabled=${chatInputEnabled && !chatDisabled}
            instanceTitle=${name}
            accessToken=${accessToken}
            inputMaxBytes=${maxSocketPayloadSize - EST_SOCKET_PAYLOAD_BUFFER ||
            CHAT_MAX_MESSAGE_LENGTH}
          />
        `
      : null;

    const TAB_CONTENT = [
      {
        label: 'About',
        content: html`
          <div>
            <div
              id="stream-summary"
              class="stream-summary my-4"
              dangerouslySetInnerHTML=${{ __html: summary }}
            ></div>
            <div id="tag-list" class="tag-list text-gray-600 mb-3">
              ${tagList && `#${tagList}`}
            </div>
            <div
              id="extra-user-content"
              class="extra-user-content"
              dangerouslySetInnerHTML=${{ __html: extraPageContent }}
            ></div>
          </div>
        `,
      },
    ];

    if (federation.enabled) {
      TAB_CONTENT.push({
        label: 'Followers',
        content: html`<${Followers} />`,
      });
    }

    return html`
      <div
        id="app-container"
        class="flex w-full flex-col justify-start relative ${extraAppClasses}"
      >
        <style>
          ${customStyles}
        </style>

        <div id="top-content" class="z-50">
          <header
            class="flex border-b border-gray-900 border-solid shadow-md fixed z-10 w-full top-0	left-0 flex flex-row justify-between flex-no-wrap"
          >
            <h1
              class="flex flex-row items-center justify-start p-2 uppercase text-gray-400 text-xl	font-thin tracking-wider overflow-hidden whitespace-no-wrap"
            >
              <span
                id="logo-container"
                class="inline-block	rounded-full bg-white w-8 min-w-8 min-h-8 h-8 mr-2 bg-no-repeat bg-center"
              >
                <img
                  class="logo visually-hidden"
                  src=${OWNCAST_LOGO_LOCAL}
                  alt="owncast logo"
                />
              </span>
              <span class="instance-title overflow-hidden truncate"
                >${streamOnline && streamTitle ? streamTitle : name}</span
              >
            </h1>
            <div
              id="user-options-container"
              class="flex flex-row justify-end items-center flex-no-wrap"
            >
              <${UsernameForm}
                username=${username}
                isModerator=${isModerator}
                onUsernameChange=${this.handleUsernameChange}
                onFocus=${this.handleFormFocus}
                onBlur=${this.handleFormBlur}
              />
              <button
                type="button"
                id="chat-toggle"
                onClick=${this.handleChatPanelToggle}
                class="flex cursor-pointer text-center justify-center items-center min-w-12 h-full bg-gray-800 hover:bg-gray-700"
                style=${{
                  display: chatDisabled || noVideoContent ? 'none' : 'block',
                }}
              >
                💬
              </button>
            </div>
          </header>
        </div>

        <main class=${mainClass}>
          <div
            id="video-container"
            class="flex owncast-video-container bg-black w-full bg-center bg-no-repeat flex flex-col items-center justify-start"
          >
            <video
              class="video-js vjs-big-play-centered display-block w-full h-full"
              id="video"
              preload="auto"
              controls
              playsinline
            ></video>
            ${poster}
          </div>

          <section
            id="stream-info"
            aria-label="Stream status"
            class="flex text-center flex-row justify-between font-mono py-2 px-4 bg-gray-900 text-indigo-200 shadow-md border-b border-gray-100 border-solid"
          >
            <span class="text-xs">${streamStatusMessage}</span>
            <span id="stream-viewer-count" class="text-xs text-right"
              >${viewerCountMessage}</span
            >
          </section>
        </main>

        <section
          id="user-content"
          aria-label="Owncast server information"
          class="p-2"
        >
          ${externalActionButtons && html`${externalActionButtons}`}

          <div class="user-content flex flex-row p-8">
            <div
              class="user-logo-icons flex flex-col items-center justify-start mr-8"
            >
              <div
                class="user-image rounded-full bg-white p-4 bg-no-repeat bg-center"
                style=${bgUserLogo}
              >
                <img class="logo visually-hidden" alt="" src=${logo} />
              </div>
              <div class="social-actions">
                <${SocialIconsList} handles=${socialHandles} />
              </div>
            </div>

            <div class="user-content-header">
              <h2 class="server-name font-semibold text-5xl">
                <span class="streamer-name text-indigo-600">${name}</span>
              </h2>
              <h3 class="font-semibold text-3xl">
                ${streamOnline && streamTitle}
              </h3>

              <!-- tab bar -->
              <div class="${TAB_CONTENT.length > 1 ? 'my-8' : 'my-3'}">
                <${TabBar} tabs=${TAB_CONTENT} ariaLabel="User Content" />
              </div>
            </div>
          </div>
        </section>

        <footer class="flex flex-row justify-start p-8 opacity-50 text-xs">
          <span class="mx-1 inline-block">
            <a href="${URL_OWNCAST}" rel="noopener noreferrer" target="_blank"
              >${appVersion}</a
            >
          </span>
        </footer>

        ${chat} ${externalActionModal} ${fediverseFollowModal}
        ${notificationModal}
      </div>
    `;
  }
}