App.vue 19.5 KB
Newer Older
1
<template>
2
  <div id="app" :key="String($store.state.instance.instanceUrl)" :class="[$store.state.ui.queueFocused ? 'queue-focused' : '', {'has-bottom-player': $store.state.queue.tracks.length > 0}, `is-${ $store.getters['ui/windowSize']}`]">
3
    <!-- here, we display custom stylesheets, if any -->
Eliot Berriot's avatar
Eliot Berriot committed
4
5
6
7
8
9
10
    <link
      v-for="url in customStylesheets"
      rel="stylesheet"
      property="stylesheet"
      :href="url"
      :key="url"
    >
11
    <template>
12
      <sidebar></sidebar>
13
      <set-instance-modal @update:show="showSetInstanceModal = $event" :show="showSetInstanceModal"></set-instance-modal>
Eliot Berriot's avatar
Eliot Berriot committed
14
      <service-messages></service-messages>
15
16
17
      <transition name="queue">
        <queue @touch-progress="$refs.player.setCurrentTime($event)" v-if="$store.state.ui.queueFocused"></queue>
      </transition>
18
      <router-view :class="{hidden: $store.state.ui.queueFocused}"></router-view>
19
      <player ref="player"></player>
Eliot Berriot's avatar
Eliot Berriot committed
20
      <app-footer
21
        :class="{hidden: $store.state.ui.queueFocused}"
Eliot Berriot's avatar
Eliot Berriot committed
22
23
        :version="version"
        @show:shortcuts-modal="showShortcutsModal = !showShortcutsModal"
24
        @show:set-instance-modal="showSetInstanceModal = !showSetInstanceModal"
Eliot Berriot's avatar
Eliot Berriot committed
25
      ></app-footer>
26
      <playlist-modal v-if="$store.state.auth.authenticated"></playlist-modal>
27
      <channel-upload-modal v-if="$store.state.auth.authenticated"></channel-upload-modal>
28
      <filter-modal v-if="$store.state.auth.authenticated"></filter-modal>
Eliot Berriot's avatar
Eliot Berriot committed
29
      <report-modal></report-modal>
30
      <shortcuts-modal @update:show="showShortcutsModal = $event" :show="showShortcutsModal"></shortcuts-modal>
Eliot Berriot's avatar
Eliot Berriot committed
31
      <GlobalEvents @keydown.h.exact="showShortcutsModal = !showShortcutsModal"/>
32
    </template>
33
34
35
36
  </div>
</template>

<script>
37
import Vue from 'vue'
38
import axios from 'axios'
39
import _ from '@/lodash'
40
import {mapState, mapGetters, mapActions} from 'vuex'
41
import { WebSocketBridge } from 'django-channels'
42
import GlobalEvents from '@/components/utils/global-events'
43
import moment from  'moment'
44
import locales from './locales'
45
import {getClientOnlyRadio} from '@/radios'
Eliot Berriot's avatar
Eliot Berriot committed
46

47
48
export default {
  name: 'app',
Eliot Berriot's avatar
Eliot Berriot committed
49
  components: {
50
51
52
    Player:  () => import(/* webpackChunkName: "audio" */ "@/components/audio/Player"),
    Queue:  () => import(/* webpackChunkName: "audio" */ "@/components/Queue"),
    PlaylistModal:  () => import(/* webpackChunkName: "auth-audio" */ "@/components/playlists/PlaylistModal"),
53
    ChannelUploadModal:  () => import(/* webpackChunkName: "auth-audio" */ "@/components/channels/UploadModal"),
54
55
56
57
58
59
60
    Sidebar:  () => import(/* webpackChunkName: "core" */ "@/components/Sidebar"),
    AppFooter:  () => import(/* webpackChunkName: "core" */ "@/components/Footer"),
    ServiceMessages:  () => import(/* webpackChunkName: "core" */ "@/components/ServiceMessages"),
    SetInstanceModal:  () => import(/* webpackChunkName: "core" */ "@/components/SetInstanceModal"),
    ShortcutsModal:  () => import(/* webpackChunkName: "core" */ "@/components/ShortcutsModal"),
    FilterModal:  () => import(/* webpackChunkName: "moderation" */ "@/components/moderation/FilterModal"),
    ReportModal:  () => import(/* webpackChunkName: "moderation" */ "@/components/moderation/ReportModal"),
61
    GlobalEvents,
Eliot Berriot's avatar
Eliot Berriot committed
62
  },
63
64
  data () {
    return {
65
      bridge: null,
66
67
      instanceUrl: null,
      showShortcutsModal: false,
68
      showSetInstanceModal: false,
69
70
    }
  },
71
  async created () {
72
73
74
75
76
77
78
79
80
81
82
83
84

    if (navigator.serviceWorker) {
      navigator.serviceWorker.addEventListener(
        'controllerchange', () => {
          if (this.serviceWorker.refreshing) return;
          this.$store.commit('ui/serviceWorker', {
            refreshing: true
          })
          window.location.reload();
        }
      );
    }

85
    this.openWebsocket()
Eliot Berriot's avatar
Eliot Berriot committed
86
    let self = this
87
88
89
    if (!this.$store.state.ui.selectedLanguage) {
      this.autodetectLanguage()
    }
90
91
92
93
    setInterval(() => {
      // used to redraw ago dates every minute
      self.$store.commit('ui/computeLastDate')
    }, 1000 * 60)
94
95
96
97
98
    const urlParams = new URLSearchParams(window.location.search);
    const serverUrl = urlParams.get('_server')
    if (serverUrl) {
      this.$store.commit('instance/instanceUrl', serverUrl)
    }
99
100
101
102
    const url = urlParams.get('_url')
    if (url) {
      this.$router.replace(url)
    }
103
    else if (!this.$store.state.instance.instanceUrl) {
104
105
106
107
108
      // we have several way to guess the API server url. By order of precedence:
      // 1. use the url provided in settings.json, if any
      // 2. use the url specified when building via VUE_APP_INSTANCE_URL
      // 3. use the current url
      let defaultInstanceUrl = this.$store.state.instance.frontSettings.defaultServerUrl || process.env.VUE_APP_INSTANCE_URL || this.$store.getters['instance/defaultUrl']()
109
      this.$store.commit('instance/instanceUrl', defaultInstanceUrl)
Eliot Berriot's avatar
Eliot Berriot committed
110
    } else {
111
      // needed to trigger initialization of axios / service worker
Eliot Berriot's avatar
Eliot Berriot committed
112
      this.$store.commit('instance/instanceUrl', this.$store.state.instance.instanceUrl)
113
    }
114
    await this.fetchNodeInfo()
115
116
    this.$store.dispatch('auth/check')
    this.$store.dispatch('instance/fetchSettings')
117
118
119
120
121
    this.$store.commit('ui/addWebsocketEventHandler', {
      eventName: 'inbox.item_added',
      id: 'sidebarCount',
      handler: this.incrementNotificationCountInSidebar
    })
122
123
124
125
126
127
128
129
130
131
    this.$store.commit('ui/addWebsocketEventHandler', {
      eventName: 'mutation.created',
      id: 'sidebarReviewEditCount',
      handler: this.incrementReviewEditCountInSidebar
    })
    this.$store.commit('ui/addWebsocketEventHandler', {
      eventName: 'mutation.updated',
      id: 'sidebarReviewEditCount',
      handler: this.incrementReviewEditCountInSidebar
    })
132
133
134
135
136
    this.$store.commit('ui/addWebsocketEventHandler', {
      eventName: 'report.created',
      id: 'sidebarPendingReviewReportCount',
      handler: this.incrementPendingReviewReportsCountInSidebar
    })
137
138
139
140
141
    this.$store.commit('ui/addWebsocketEventHandler', {
      eventName: 'user_request.created',
      id: 'sidebarPendingReviewRequestCount',
      handler: this.incrementPendingReviewRequestsCountInSidebar
    })
142
143
144
145
146
    this.$store.commit('ui/addWebsocketEventHandler', {
      eventName: 'Listen',
      id: 'handleListen',
      handler: this.handleListen
    })
147
  },
148
149
150
151
152
153
154
155
156
157
  mounted () {
    let self = this

    // slight hack to allow use to have internal links in <translate> tags
    // while preserving router behaviour
    document.documentElement.addEventListener('click', function (event) {
      if (!event.target.matches('a.internal')) return;
      self.$router.push(event.target.getAttribute('href'))
      event.preventDefault();
    }, false);
158
159
160
    this.$nextTick(() => {
      document.getElementById('fake-content').classList.add('loaded')
    })
161
162

  },
163
164
165
166
167
  destroyed () {
    this.$store.commit('ui/removeWebsocketEventHandler', {
      eventName: 'inbox.item_added',
      id: 'sidebarCount',
    })
168
169
170
171
172
173
174
175
    this.$store.commit('ui/removeWebsocketEventHandler', {
      eventName: 'mutation.created',
      id: 'sidebarReviewEditCount',
    })
    this.$store.commit('ui/removeWebsocketEventHandler', {
      eventName: 'mutation.updated',
      id: 'sidebarReviewEditCount',
    })
176
177
178
179
    this.$store.commit('ui/removeWebsocketEventHandler', {
      eventName: 'mutation.updated',
      id: 'sidebarPendingReviewReportCount',
    })
180
181
182
183
    this.$store.commit('ui/removeWebsocketEventHandler', {
      eventName: 'user_request.created',
      id: 'sidebarPendingReviewRequestCount',
    })
184
185
186
187
    this.$store.commit('ui/removeWebsocketEventHandler', {
      eventName: 'Listen',
      id: 'handleListen',
    })
188
    this.disconnect()
189
190
  },
  methods: {
191
192
193
    incrementNotificationCountInSidebar (event) {
      this.$store.commit('ui/incrementNotifications', {type: 'inbox', count: 1})
    },
194
195
196
    incrementReviewEditCountInSidebar (event) {
      this.$store.commit('ui/incrementNotifications', {type: 'pendingReviewEdits', value: event.pending_review_count})
    },
197
198
199
    incrementPendingReviewReportsCountInSidebar (event) {
      this.$store.commit('ui/incrementNotifications', {type: 'pendingReviewReports', value: event.unresolved_count})
    },
200
201
202
    incrementPendingReviewRequestsCountInSidebar (event) {
      this.$store.commit('ui/incrementNotifications', {type: 'pendingReviewRequests', value: event.pending_count})
    },
203
204
205
206
207
208
209
210
    handleListen (event) {
      if (this.$store.state.radios.current && this.$store.state.radios.running) {
        let current = this.$store.state.radios.current
        if (current.clientOnly && current.type === 'account') {
          getClientOnlyRadio(current).handleListen(current, event, this.$store)
        }
      }
    },
211
212
213
    async fetchNodeInfo () {
      let response = await axios.get('instance/nodeinfo/2.0/')
      this.$store.commit('instance/nodeinfo', response.data)
214
    },
215
216
    autodetectLanguage () {
      let userLanguage = navigator.language || navigator.userLanguage
217
      let available = locales.locales.map(e => { return e.code })
218
219
      let self = this
      let candidate
220
221
222
223
224
225
226
      let matching = available.filter((a) => {
        return userLanguage.replace('-', '_') === a
      })
      let almostMatching = available.filter((a) => {
        return userLanguage.replace('-', '_').split('_')[0] === a.split('_')[0]
      })
      if (matching.length > 0) {
227
        candidate = matching[0]
228
      } else if (almostMatching.length > 0) {
229
230
231
        candidate = almostMatching[0]
      } else {
        return
232
      }
233
      this.$store.commit('ui/currentLanguage', candidate)
234
235
236
237
238
239
240
241
242
243
244
245
246
    },
    disconnect () {
      if (!this.bridge) {
        return
      }
      this.bridge.socket.close(1000, 'goodbye', {keepClosed: true})
    },
    openWebsocket () {
      if (!this.$store.state.auth.authenticated) {
        return
      }
      this.disconnect()
      let self = this
247
248
      let token = this.$store.state.auth.token
      // let token = 'test'
249
250
      const bridge = new WebSocketBridge()
      this.bridge = bridge
251
      let url = this.$store.getters['instance/absoluteUrl'](`api/v1/activity?token=${token}`)
252
253
254
255
      url = url.replace('http://', 'ws://')
      url = url.replace('https://', 'wss://')
      bridge.connect(
        url,
256
        [],
257
        {reconnectInterval: 1000 * 60})
258
259
260
261
262
263
      bridge.listen(function (event) {
        self.$store.dispatch('ui/websocketEvent', event)
      })
      bridge.socket.addEventListener('open', function () {
        console.log('Connected to WebSocket')
      })
264
    },
265
266
    getTrackInformationText(track) {
      const trackTitle = track.title
267
      const albumArtist = (track.album) ? track.album.artist.name : null
268
      const artistName = (
269
        (track.artist) ? track.artist.name : albumArtist)
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
      const text = `♫ ${trackTitle}${artistName} ♫`
      return text
    },
    updateDocumentTitle() {
      let parts = []
      const currentTrackPart = (
        (this.currentTrack) ? this.getTrackInformationText(this.currentTrack)
        : null)
      if (currentTrackPart) {
        parts.push(currentTrackPart)
      }
      if (this.$store.state.ui.pageTitle) {
        parts.push(this.$store.state.ui.pageTitle)
      }
      parts.push(this.$store.state.instance.settings.instance.name.value || 'Funkwhale')
      document.title = parts.join('')
    },
Eliot Berriot's avatar
Eliot Berriot committed
287

288
289
290
    updateApp () {
      this.$store.commit('ui/serviceWorker', {updateAvailable: false})
      if (!this.serviceWorker.registration || !this.serviceWorker.registration.waiting) { return; }
291
      this.serviceWorker.registration.waiting.postMessage({command: 'skipWaiting'})
292
    }
293
294
  },
  computed: {
295
    ...mapState({
296
297
      messages: state => state.ui.messages,
      nodeinfo: state => state.instance.nodeinfo,
298
299
300
      playing: state => state.player.playing,
      bufferProgress: state => state.player.bufferProgress,
      isLoadingAudio: state => state.player.isLoadingAudio,
301
      serviceWorker: state => state.ui.serviceWorker,
302
    }),
303
    ...mapGetters({
304
305
306
      hasNext: "queue/hasNext",
      currentTrack: 'queue/currentTrack',
      progress: "player/progress",
307
    }),
308
309
310
311
312
313
314
315
316
317
318
319
    labels() {
      let play = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', "Play track")
      let pause = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', "Pause track")
      let next = this.$pgettext('Sidebar/Player/Icon.Tooltip', "Next track")
      let expandQueue = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', "Expand queue")
      return {
        play,
        pause,
        next,
        expandQueue,
      }
    },
320
    suggestedInstances () {
321
      let instances = this.$store.state.instance.knownInstances.slice(0)
322
      if (this.$store.state.instance.frontSettings.defaultServerUrl) {
323
324
325
326
327
        let serverUrl = this.$store.state.instance.frontSettings.defaultServerUrl
        if (!serverUrl.endsWith('/')) {
          serverUrl = serverUrl + '/'
        }
        instances.push(serverUrl)
328
      }
329
330
      instances.push(this.$store.getters['instance/defaultUrl'](), 'https://demo.funkwhale.audio/')
      return _.uniq(instances.filter((e) => {return e}))
331
    },
332
333
334
335
336
    version () {
      if (!this.nodeinfo) {
        return null
      }
      return _.get(this.nodeinfo, 'software.version')
337
338
339
340
341
    },
    customStylesheets () {
      if (this.$store.state.instance.frontSettings) {
        return this.$store.state.instance.frontSettings.additionalStylesheets || []
      }
342
    },
343
344
  },
  watch: {
345
    '$store.state.instance.instanceUrl' (v) {
346
347
      this.$store.dispatch('instance/fetchSettings')
      this.fetchNodeInfo()
348
    },
Eliot Berriot's avatar
Eliot Berriot committed
349
350
351
352
353
354
355
356
    '$store.state.ui.theme': {
      immediate: true,
      handler (newValue, oldValue) {
        let oldTheme = oldValue || 'light'
        document.body.classList.remove(`theme-${oldTheme}`)
        document.body.classList.add(`theme-${newValue}`)
      },
    },
357
358
359
360
361
362
363
    '$store.state.auth.authenticated' (newValue) {
      if (!newValue) {
        this.disconnect()
      } else {
        this.openWebsocket()
      }
    },
364
365
366
367
    '$store.state.ui.currentLanguage': {
      immediate: true,
      handler(newValue) {
        let self = this
368
369
370
371
372
        if (newValue === 'en_US') {
          self.$language.current = 'noop'
          self.$language.current = newValue
          return self.$store.commit('ui/momentLocale', 'en')
        }
373
        import(/* webpackChunkName: "locale-[request]" */ `./translations/${newValue}.json`).then((response) =>{
374
375
376
377
378
379
380
381
          Vue.$translations[newValue] = response.default[newValue]
        }).finally(() => {
          // set current language twice, otherwise we seem to have a cache somewhere
          // and rendering does not happen
          self.$language.current = 'noop'
          self.$language.current = newValue
        })
        let momentLocale = newValue.replace('_', '-').toLowerCase()
382
        import(/* webpackChunkName: "moment-locale-[request]" */ `moment/locale/${momentLocale}.js`).then(() => {
383
384
385
386
          self.$store.commit('ui/momentLocale', momentLocale)
        }).catch(() => {
          console.log('No momentjs locale available for', momentLocale)
          let shortLocale = momentLocale.split('-')[0]
387
          import(/* webpackChunkName: "moment-locale-[request]" */ `moment/locale/${shortLocale}.js`).then(() => {
388
389
390
391
392
393
            self.$store.commit('ui/momentLocale', shortLocale)
          }).catch(() => {
            console.log('No momentjs locale available for', shortLocale)
          })
        })
      }
394
395
396
397
398
399
400
401
402
403
404
405
406
    },
    'currentTrack': {
      immediate: true,
      handler(newValue) {
        this.updateDocumentTitle()
      },
    },
    '$store.state.ui.pageTitle': {
      immediate: true,
      handler(newValue) {
        this.updateDocumentTitle()
      },
    },
Eliot Berriot's avatar
Eliot Berriot committed
407
408
    'serviceWorker.updateAvailable': {
      handler (v) {
409
410
411
        // if (!v) {
        //   return
        // }
Eliot Berriot's avatar
Eliot Berriot committed
412
413
414
415
416
417
        let self = this
        this.$store.commit('ui/addMessage', {
          content: this.$pgettext("App/Message/Paragraph", "A new version of the app is available."),
          date: new Date(),
          key: 'refreshApp',
          displayTime: 0,
418
          classActions: 'bottom attached opaque',
Eliot Berriot's avatar
Eliot Berriot committed
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
          actions: [
            {
              text: this.$pgettext("App/Message/Paragraph", "Update"),
              class: "primary",
              click: function () {
                self.updateApp()
              },
            },
            {
              text: this.$pgettext("App/Message/Paragraph", "Later"),
              class: "basic",
            }
          ]
        })
      },
      immediate: true,
    }
436
  }
437
438
439
440
}
</script>

<style lang="scss">
441
@import "style/_main";
442
443
444
445
446

.ui.bottom-player {
  z-index: 999999;
  width: 100%;
  width: 100vw;
447
448
449
  .ui.top.attached.progress {
    top: 0;
  }
450
}
451
452
453
454
455
456
457
.dimmed {
  .ui.bottom-player {
    @include media("<desktop") {
      z-index: 0;
    }
  }
}
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
#app.queue-focused {
  .queue-not-focused {
    @include media("<desktop") {
      display: none;
    }
  }
}
.when-queue-focused {
  .group {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 1.1em;
    > * {
      margin-left: 0.5em;
    }
  }
  @include media("<desktop") {
    width: 100%;
    justify-content: space-between !important;
  }
}
#app:not(.queue-focused) {
  .when-queue-focused {
    @include media("<desktop") {
      display: none;
    }
  }
}
.ui.bottom-player > .segment.fixed-controls {
  width: 100%;
  width: 100vw;
  border-radius: 0;
  padding: 0em;
  position: fixed;
  bottom: 0;
  left: 0;
  margin: 0;
  z-index: 1001;
  height: $bottom-player-height;
  .controls-row {
    height: $bottom-player-height;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: space-between;
    @include media(">desktop") {
      padding: 0 1em;
      justify-content: space-around;
    }
  }
  cursor: pointer;
  .indicating.progress {
    overflow: hidden;
  }

  .ui.progress .bar {
    transition: none;
  }

  .ui.progress .buffer.bar {
    position: absolute;
  }

  @keyframes MOVE-BG {
    from {
      transform: translateX(0px);
    }
    to {
      transform: translateX(46px);
    }
  }
  .discrete.link {
    color: inherit;
  }
  .indicating.progress .bar {
    left: -46px;
    width: 200% !important;
    color: grey;
    background: repeating-linear-gradient(
      -55deg,
      grey 1px,
      grey 10px,
      transparent 10px,
      transparent 20px
    ) !important;

    animation-name: MOVE-BG;
    animation-duration: 2s;
    animation-timing-function: linear;
    animation-iteration-count: infinite;
  }
  .ui.progress:not([data-percent]):not(.indeterminate)
    .bar.position:not(.buffer) {
    background: #ff851b;
    min-width: 0;
  }

  .track-controls {
    display: flex;
    align-items: center;
    justify-content: start;
    flex-grow: 1;
    .image {
      padding: 0.5em;
      width: auto;
      margin-right: 0.5em;
      > img {
        max-height: 3.7em;
        max-width: 4.7em;
      }
    }
  }
  .controls {
    min-width: 8em;
    font-size: 1.1em;
    @include media(">desktop") {
      &:not(.fluid) {
        width: 20%;
      }
      &.queue-controls {
        width: 32.5%;
      }
      &.progress-controls {
        width: 10%;
      }
      &.player-controls {
        width: 15%;
      }
    }
    &.small, .small {
      @include media(">desktop") {
        font-size: 0.9em;
      }
    }
    .icon {
      font-size: 1.1em;
    }
    .icon.large {
      font-size: 1.4em;
    }
    &:not(.track-controls) {
      @include media(">desktop") {
        line-height: 1em;
      }
      justify-content: center;
      align-items: center;
      &.align-right {
        justify-content: flex-end;
      }
      &.align-left {
        justify-content: flex-start;
      }
      > * {
612
        padding: 0.5em;
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
      }
    }
    &.player-controls {
      .icon {
        margin: 0;
      }
    }

  }
}
.queue-enter-active, .queue-leave-active {
  transition: all 0.2s ease-in-out;
  .current-track, .queue-column {
    opacity: 0;
  }
}
.queue-enter, .queue-leave-to {
  transform: translateY(100vh);
  opacity: 0;
}
633
</style>