Player.vue 29.6 KB
Newer Older
1
<template>
2
3
4
5
  <section role="complementary" v-if="currentTrack" class="player-wrapper ui bottom-player component-player" aria-labelledby="player-label">
    <h1 id="player-label" class="visually-hidden">
      <translate translate-context="*/*/*">Audio player and controls</translate>
    </h1>
6
7
    <div class="ui inverted segment fixed-controls" @click.prevent.stop="toggleMobilePlayer">
      <div
Agate's avatar
Agate committed
8
        :class="['ui', 'top attached', 'small', 'inverted', {'indicating': isLoadingAudio}, 'progress']">
9
10
11
12
13
14
        <div class="buffer bar" :data-percent="bufferProgress" :style="{ 'width': bufferProgress + '%' }"></div>
        <div class="position bar" :data-percent="progress" :style="{ 'width': progress + '%' }"></div>
      </div>
      <div class="controls-row">

        <div class="controls track-controls queue-not-focused desktop-and-up">
Agate's avatar
Agate committed
15
          <div class="ui tiny image" @click.stop.prevent="$router.push({name: 'library.tracks.detail', params: {id: currentTrack.id }})">
16
            <img alt="" ref="cover" v-if="currentTrack.cover && currentTrack.cover.urls.original" :src="$store.getters['instance/absoluteUrl'](currentTrack.cover.urls.medium_square_crop)">
17
            <img alt="" ref="cover" v-else-if="currentTrack.album && currentTrack.album.cover && currentTrack.album.cover.urls && currentTrack.album.cover.urls.original" :src="$store.getters['instance/absoluteUrl'](currentTrack.album.cover.urls.medium_square_crop)">
18
            <img alt="" v-else src="../../assets/audio/default-cover.png">
19
          </div>
20
21
          <div @click.stop.prevent="" class="middle aligned content ellipsis">
            <strong>
Ciarán Ainsworth's avatar
Ciarán Ainsworth committed
22
              <router-link @click.stop.prevent="" class="small header discrete link track" :to="{name: 'library.tracks.detail', params: {id: currentTrack.id }}">
23
24
25
                {{ currentTrack.title }}
              </router-link>
            </strong>
26
            <div class="meta">
27
28
29
30
              <router-link @click.stop.prevent="" class="discrete link" :to="{name: 'library.artists.detail', params: {id: currentTrack.artist.id }}">{{ currentTrack.artist.name }}</router-link>
              <template v-if="currentTrack.album"> /
                <router-link @click.stop.prevent="" class="discrete link" :to="{name: 'library.albums.detail', params: {id: currentTrack.album.id }}">{{ currentTrack.album.title }}</router-link>
              </template>
31
            </div>
32
33
          </div>
        </div>
34
35
        <div class="controls track-controls queue-not-focused tablet-and-below">
          <div class="ui tiny image">
36
37
38
            <img alt="" ref="cover" v-if="currentTrack.cover && currentTrack.cover.urls.original" :src="$store.getters['instance/absoluteUrl'](currentTrack.cover.urls.medium_square_crop)">
            <img alt="" ref="cover" v-else-if="currentTrack.album && currentTrack.album.cover && currentTrack.album.cover.urls.original" :src="$store.getters['instance/absoluteUrl'](currentTrack.album.cover.urls.medium_square_crop)">
            <img alt="" v-else src="../../assets/audio/default-cover.png">
39
          </div>
40
41
42
43
44
          <div class="middle aligned content ellipsis">
            <strong>
              {{ currentTrack.title }}
            </strong>
            <div class="meta">
45
              {{ currentTrack.artist.name }}<template v-if="currentTrack.album"> / {{ currentTrack.album.title }}</template>
46
            </div>
47
48
          </div>
        </div>
49
50
51
52
53
54
55
56
57
58
59
60
61
62
        <div class="controls desktop-and-up fluid align-right" v-if="$store.state.auth.authenticated">
          <track-favorite-icon
            class="control white"
            :track="currentTrack"></track-favorite-icon>
          <track-playlist-icon
            class="control white"
            :track="currentTrack"></track-playlist-icon>
          <button
            @click="$store.dispatch('moderation/hide', {type: 'artist', target: currentTrack.artist})"
            :class="['ui', 'really', 'basic', 'circular', 'icon', 'button', 'control']"
            :aria-label="labels.addArtistContentFilter"
            :title="labels.addArtistContentFilter">
            <i :class="['eye slash outline', 'basic', 'icon']"></i>
          </button>
63
        </div>
64
        <div class="player-controls controls queue-not-focused">
65
          <button
66
67
            :title="labels.previous"
            :aria-label="labels.previous"
68
            class="circular button control tablet-and-up"
69
70
71
            @click.prevent.stop="$store.dispatch('queue/previous')"
            :disabled="!hasPrevious">
              <i :class="['ui', 'large', {'disabled': !hasPrevious}, 'backward step', 'icon']" ></i>
72
73
          </button>
          <button
74
75
76
77
            v-if="!playing"
            :title="labels.play"
            :aria-label="labels.play"
            @click.prevent.stop="togglePlay"
78
            class="circular button control">
79
              <i :class="['ui', 'big', 'play', {'disabled': !currentTrack}, 'icon']"></i>
80
81
          </button>
          <button
82
            v-else
83
84
85
            :title="labels.pause"
            :aria-label="labels.pause"
            @click.prevent.stop="togglePlay"
86
            class="circular button control">
87
              <i :class="['ui', 'big', 'pause', {'disabled': !currentTrack}, 'icon']"></i>
88
89
          </button>
          <button
90
91
            :title="labels.next"
            :aria-label="labels.next"
92
            class="circular button control"
93
94
95
            @click.prevent.stop="$store.dispatch('queue/next')"
            :disabled="!hasNext">
              <i :class="['ui', 'large', {'disabled': !hasNext}, 'forward step', 'icon']" ></i>
96
          </button>
97
        </div>
98
99
100
101

        <div class="controls progress-controls queue-not-focused tablet-and-up small align-left">
          <div class="timer">
            <template v-if="!isLoadingAudio">
102
              <span class="start" @click.stop.prevent="setCurrentTime(0)">{{currentTimeFormatted}}</span>
103
104
105
106
107
108
109
110
111
112
              | <span class="total">{{durationFormatted}}</span>
            </template>
            <template v-else>
              00:00 | 00:00
            </template>
          </div>
        </div>
        <div class="controls queue-controls when-queue-focused align-right">
          <div class="group">
            <volume-control class="expandable" />
113
114
            <button
              class="circular control button"
115
116
117
118
119
120
              v-if="looping === 0"
              :title="labels.loopingDisabled"
              :aria-label="labels.loopingDisabled"
              @click.prevent.stop="$store.commit('player/looping', 1)"
              :disabled="!currentTrack">
              <i :class="['ui', {'disabled': !currentTrack}, 'step', 'repeat', 'icon']"></i>
121
122
123
            </button>
            <button
              class="looping circular control button"
124
125
126
127
128
129
130
              @click.prevent.stop="$store.commit('player/looping', 2)"
              :title="labels.loopingSingle"
              :aria-label="labels.loopingSingle"
              v-if="looping === 1"
              :disabled="!currentTrack">
              <i
                class="repeat icon">
Agate's avatar
Agate committed
131
                <span class="ui circular tiny vibrant label">1</span>
132
              </i>
133
134
135
            </button>
            <button
              class="looping circular control button"
136
137
138
139
140
141
142
              :title="labels.loopingWhole"
              :aria-label="labels.loopingWhole"
              v-if="looping === 2"
              :disabled="!currentTrack"
              @click.prevent.stop="$store.commit('player/looping', 0)">
              <i
                class="repeat icon">
Agate's avatar
Agate committed
143
                <span class="ui circular tiny vibrant label">&infin;</span>
144
              </i>
145
146
147
            </button>
            <button
              class="circular control button"
148
149
150
151
152
153
              :disabled="queue.tracks.length === 0"
              :title="labels.shuffle"
              :aria-label="labels.shuffle"
              @click.prevent.stop="shuffle()">
              <div v-if="isShuffling" class="ui inline shuffling inverted tiny active loader"></div>
              <i v-else :class="['ui', 'random', {'disabled': queue.tracks.length === 0}, 'icon']" ></i>
154
            </button>
155
156
157
          </div>
          <div class="group">
            <div class="fake-dropdown">
158
              <button class="position circular control button desktop-and-up" @click.stop="toggleMobilePlayer" aria-expanded="true">
159
160
161
162
                <i class="stream icon"></i>
                <translate translate-context="Sidebar/Queue/Text" :translate-params="{index: queue.currentIndex + 1, length: queue.tracks.length}">
                  %{ index } of %{ length }
                </translate>
163
164
              </button>
              <button class="position circular control button tablet-and-below" @click.stop="switchTab">
165
166
167
168
                <i class="stream icon"></i>
                <translate translate-context="Sidebar/Queue/Text" :translate-params="{index: queue.currentIndex + 1, length: queue.tracks.length}">
                  %{ index } of %{ length }
                </translate>
169
              </button>
170

171
172
              <button
                class="circular control button close-control desktop-and-up"
173
174
175
                v-if="$store.state.ui.queueFocused"
                @click.stop="toggleMobilePlayer">
                <i class="large down angle icon"></i>
176
177
178
              </button>
              <button
                class="circular control button desktop-and-up"
179
180
181
                v-else
                @click.stop="toggleMobilePlayer">
                <i class="large up angle icon"></i>
182
183
184
              </button>
              <button
                class="circular control button close-control tablet-and-below"
185
186
187
                v-if="$store.state.ui.queueFocused === 'player'"
                @click.stop="switchTab">
                <i class="large up angle icon"></i>
188
189
190
              </button>
              <button
                class="circular control button tablet-and-below"
191
192
193
                v-if="$store.state.ui.queueFocused === 'queue'"
                @click.stop="switchTab">
                <i class="large down angle icon"></i>
194
              </button>
195
            </div>
196
197
            <button
              class="circular control button close-control tablet-and-below"
198
199
              @click.stop="$store.commit('ui/queueFocused', null)">
              <i class="x icon"></i>
200
            </button>
201
202
          </div>
        </div>
203
204
      </div>
    </div>
205
    <GlobalEvents
206
      @keydown.p.prevent.exact="togglePlay"
207
      @keydown.esc.prevent.exact="$store.commit('ui/queueFocused', null)"
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
      @keydown.ctrl.shift.left.prevent.exact="previous"
      @keydown.ctrl.shift.right.prevent.exact="next"
      @keydown.shift.down.prevent.exact="$store.commit('player/incrementVolume', -0.1)"
      @keydown.shift.up.prevent.exact="$store.commit('player/incrementVolume', 0.1)"
      @keydown.right.prevent.exact="seek (5)"
      @keydown.left.prevent.exact="seek (-5)"
      @keydown.shift.right.prevent.exact="seek (30)"
      @keydown.shift.left.prevent.exact="seek (-30)"
      @keydown.m.prevent.exact="toggleMute"
      @keydown.l.exact="$store.commit('player/toggleLooping')"
      @keydown.s.exact="shuffle"
      @keydown.f.exact="$store.dispatch('favorites/toggle', currentTrack.id)"
      @keydown.q.exact="clean"
      @keydown.e.exact="toggleMobilePlayer"
      />
223
  </section>
224
225
226
</template>

<script>
227
228
229
import { mapState, mapGetters, mapActions } from "vuex"
import GlobalEvents from "@/components/utils/global-events"
import { Howl } from "howler"
230
import $ from 'jquery'
231
232
233
import _ from '@/lodash'
import url from '@/utils/url'
import axios from 'axios'
234

235
236
export default {
  components: {
237
238
239
    VolumeControl:  () => import(/* webpackChunkName: "audio" */ "./VolumeControl"),
    TrackFavoriteIcon:  () => import(/* webpackChunkName: "auth-audio" */ "@/components/favorites/TrackFavoriteIcon"),
    TrackPlaylistIcon:  () => import(/* webpackChunkName: "auth-audio" */ "@/components/playlists/TrackPlaylistIcon"),
240
    GlobalEvents,
241
  },
242
  data() {
243
    return {
244
      isShuffling: false,
245
      sliderVolume: this.volume,
RenonDis's avatar
RenonDis committed
246
      showVolume: false,
247
248
249
250
251
252
253
      currentSound: null,
      dummyAudio: null,
      isUpdatingTime: false,
      sourceErrors: 0,
      progressInterval: null,
      maxPreloaded: 3,
      preloadDelay: 15,
254
255
      listenDelay: 15,
      listeningRecorded: null,
256
      soundsCache: [],
257
      soundId: null,
258
259
      playTimeout: null,
      nextTrackPreloaded: false
260
261
    }
  },
262
  mounted() {
263
264
265
    this.$store.dispatch('player/updateProgress', 0)
    this.$store.commit('player/playing', false)
    this.$store.commit("player/isLoadingAudio", false)
Eliot Berriot's avatar
Eliot Berriot committed
266
    Howler.unload()  // clear existing cache, if any
267
    this.nextTrackPreloaded = false
268
    // we trigger the watcher explicitely it does not work otherwise
269
    this.sliderVolume = this.volume
270
271
272
273
274
275
    // this is needed to unlock audio playing under some browsers,
    // cf https://github.com/goldfire/howler.js#mobilechrome-playback
    // but we never actually load those audio files
    this.dummyAudio = new Howl({
      preload: false,
      autoplay: false,
276
      src: ["noop.webm", "noop.mp3"]
277
    })
278
279
    if (this.currentTrack) {
      this.getSound(this.currentTrack)
280
      this.updateMetadata()
281
    }
282
283
284
285
286
287
288
289
290
    // Add controls for notification drawer
    if ('mediaSession' in navigator) {
      navigator.mediaSession.setActionHandler('play', this.togglePlay);
      navigator.mediaSession.setActionHandler('pause', this.togglePlay);
      navigator.mediaSession.setActionHandler('seekforward', this.seekForward);
      navigator.mediaSession.setActionHandler('seekbackward', this.seekBackward);
      navigator.mediaSession.setActionHandler('nexttrack', this.next);
      navigator.mediaSession.setActionHandler('previoustrack', this.previous);
    }
291
  },
292
  beforeDestroy () {
293
    this.dummyAudio.unload()
294
    this.observeProgress(false)
295
  },
296
297
  destroyed() {
  },
298
  methods: {
299
    ...mapActions({
300
301
302
303
      togglePlay: "player/togglePlay",
      mute: "player/mute",
      unmute: "player/unmute",
      clean: "queue/clean",
304
      toggleMute: "player/toggleMute",
305
    }),
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
    async getTrackData (trackData) {
      let data = null
      if (!trackData.uploads.length || trackData.uploads.length === 0) {
        // we don't have upload informations for this track, we need to fetch it
        await axios.get(`tracks/${trackData.id}/`).then((response) => {
          data = response.data
        }, error => {
          data = null
        })
      } else {
        return trackData
      }
      if (data === null) {
        return
      }
      return data
    },
323
    shuffle() {
RenonDis's avatar
RenonDis committed
324
325
      let disabled = this.queue.tracks.length === 0
      if (this.isShuffling || disabled) {
326
327
328
        return
      }
      let self = this
Jo Vuit's avatar
Jo Vuit committed
329
      let msg = this.$pgettext('Content/Queue/Message', "Queue shuffled!")
330
331
      this.isShuffling = true
      setTimeout(() => {
332
        self.$store.dispatch("queue/shuffle", () => {
333
          self.isShuffling = false
334
          self.$store.commit("ui/addMessage", {
335
            content: msg,
336
337
338
339
340
            date: new Date()
          })
        })
      }, 100)
    },
341
    next() {
342
      let self = this
343
344
      this.$store.dispatch("queue/next").then(() => {
        self.$emit("next")
345
346
      })
    },
347
    previous() {
348
      let self = this
349
350
      this.$store.dispatch("queue/previous").then(() => {
        self.$emit("previous")
351
352
      })
    },
353
354
355
    handleError({ sound, error }) {
      this.$store.commit("player/isLoadingAudio", false)
      this.$store.dispatch("player/trackErrored")
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
    },
    getSound (trackData) {
      let cached = this.getSoundFromCache(trackData)
      if (cached) {
        return cached.sound
      }
      let srcs = this.getSrcs(trackData)
      let self = this
      let sound = new Howl({
        src: srcs.map((s) => { return s.url }),
        format: srcs.map((s) => { return s.type }),
        autoplay: false,
        loop: false,
        html5: true,
        preload: true,
        volume: this.volume,
        onend: function () {
          self.ended()
        },
        onunlock: function () {
376
          if (self.$store.state.player.playing && self.sound) {
Eliot Berriot's avatar
Eliot Berriot committed
377
            self.soundId = self.sound.play(self.soundId)
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
          }
        },
        onload: function () {
          let sound = this
          let node = this._sounds[0]._node;
          node.addEventListener('progress', () => {
            if (sound != self.currentSound) {
              return
            }
            self.updateBuffer(node)
          })
        },
        onplay: function () {
          self.$store.commit('player/isLoadingAudio', false)
          self.$store.commit('player/resetErrorCount')
          self.$store.commit('player/errored', false)
          self.$store.commit('player/duration', this.duration())
395

396
397
        },
        onloaderror: function (sound, error) {
398
          self.removeFromCache(this)
399
400
401
402
403
404
405
406
407
408
409
          if (this != self.currentSound) {
            return
          }
          console.log('Error while playing:', sound, error)
          self.handleError({sound, error})
        },
      })
      this.addSoundToCache(sound, trackData)
      return sound
    },
    getSrcs: function (trackData) {
410
411
412
413
414
415
      let a = document.createElement('audio')
      let allowed = ['probably', 'maybe']
      let sources = trackData.uploads.filter(u => {
        let canPlay = a.canPlayType(u.mimetype)
        return allowed.indexOf(canPlay) > -1
      }).map(u => {
416
417
418
419
420
        return {
          type: u.extension,
          url: this.$store.getters['instance/absoluteUrl'](u.listen_url),
        }
      })
421
      a.remove()
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
      // We always add a transcoded MP3 src at the end
      // because transcoding is expensive, but we want browsers that do
      // not support other codecs to be able to play it :)
      sources.push({
        type: 'mp3',
        url: url.updateQueryString(
          this.$store.getters['instance/absoluteUrl'](trackData.listen_url),
          'to',
          'mp3'
        )
      })
      if (this.$store.state.auth.authenticated) {
        // we need to send the token directly in url
        // so authentication can be checked by the backend
        // because for audio files we cannot use the regular Authentication
        // header
438
439
440
441
442
443
444
445
        let param = "jwt"
        let value = this.$store.state.auth.token
        if (this.$store.state.auth.scopedTokens && this.$store.state.auth.scopedTokens.listen) {
          // used scoped tokens instead of JWT to reduce the attack surface if the token
          // is leaked
          param = "token"
          value = this.$store.state.auth.scopedTokens.listen
        }
446
        sources.forEach(e => {
447
          e.url = url.updateQueryString(e.url, param, value)
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
        })
      }
      return sources
    },

    updateBuffer (node) {
      // from https://github.com/goldfire/howler.js/issues/752#issuecomment-372083163
      let range = 0;
      let bf = node.buffered;
      let time = node.currentTime;
      try {
        while(!(bf.start(range) <= time && time <= bf.end(range))) {
          range += 1;
        }
      } catch (IndexSizeError) {
        return
      }
      let loadPercentage
      let start =  bf.start(range)
      let end =  bf.end(range)
      if (range === 0) {
        // easy case, no user-seek
        let loadStartPercentage = start / node.duration;
        let loadEndPercentage = end / node.duration;
        loadPercentage = loadEndPercentage - loadStartPercentage;
      } else {
        let loaded = end - start
        let remainingToLoad = node.duration - start
        // user seeked a specific position in the audio, our progress must be
        // computed based on the remaining portion of the track
        loadPercentage = loaded / remainingToLoad;
      }
      if (loadPercentage * 100 === this.bufferProgress) {
        return
      }
      this.$store.commit('player/bufferProgress', loadPercentage * 100)
    },
    updateProgress: function () {
      this.isUpdatingTime = true
      if (this.currentSound && this.currentSound.state() === 'loaded') {
        let t = this.currentSound.seek()
        let d = this.currentSound.duration()
        this.$store.dispatch('player/updateProgress', t)
        this.updateBuffer(this.currentSound._sounds[0]._node)
        let toPreload = this.$store.state.queue.tracks[this.currentIndex + 1]
493
        if (!this.nextTrackPreloaded && toPreload && !this.getSoundFromCache(toPreload) && (t > this.preloadDelay || d - t < 30)) {
494
          this.getSound(toPreload)
495
          this.nextTrackPreloaded = true
496
        }
497
        if (t > (d / 2)) {
498
499
500
501
502
503
          let onlyTrack = this.$store.state.queue.tracks.length === 1
          if (this.listeningRecorded != this.currentTrack) {
            this.listeningRecorded = this.currentTrack
            this.$store.dispatch('player/trackListened', this.currentTrack)
          }
        }
504
505
      }
    },
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
    seek (step) {
      if (step > 0) {
        // seek right
        if (this.currentTime + step < this.duration) {
        this.$store.dispatch('player/updateProgress', (this.currentTime + step))
        } else {
        this.next() // parenthesis where missing here
        }
      }
      else {
        // seek left
        let position = Math.max(this.currentTime + step, 0)
        this.$store.dispatch('player/updateProgress', position)
      }
    },
521
522
523
524
525
526
    seekForward () {
      this.seek (5)
    },
    seekBackward () {
      this.seek (-5)
    },
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
    observeProgress: function (enable) {
      let self = this
      if (enable) {
        if (self.progressInterval) {
          clearInterval(self.progressInterval)
        }
        self.progressInterval = setInterval(() => {
          self.updateProgress()
        }, 1000)
      } else {
        clearInterval(self.progressInterval)
      }
    },
    setCurrentTime (t) {
      if (t < 0 | t > this.duration) {
        return
      }
      if (!this.currentSound || !this.currentSound._sounds[0]) {
        return
      }
      if (t === this.currentSound.seek()) {
        return
      }
      if (t === 0) {
        this.updateProgressThrottled.cancel()
      }
      this.currentSound.seek(t)
554
555
556
557
      // If player is paused update progress immediately to ensure updated UI
      if (!this.$store.state.player.playing) {
        this.updateProgress()
      }
558
559
560
561
562
    },
    ended: function () {
      let onlyTrack = this.$store.state.queue.tracks.length === 1
      if (this.looping === 1 || (onlyTrack && this.looping === 2)) {
        this.currentSound.seek(0)
Eliot Berriot's avatar
Eliot Berriot committed
563
564
        this.$store.dispatch('player/updateProgress', 0)
        this.soundId = this.currentSound.play(this.soundId)
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
      } else {
        this.$store.dispatch('player/trackEnded', this.currentTrack)
      }
    },
    getSoundFromCache (trackData) {
      return this.soundsCache.filter((d) => {
        if (d.track.id !== trackData.id) {
          return false
        }

        return true
      })[0]
    },
    addSoundToCache (sound, trackData) {
      let data = {
        date: new Date(),
        track: trackData,
        sound: sound
      }
      this.soundsCache.push(data)
      this.checkCache()
    },
    checkCache () {
      let self = this
      let toKeep = []
      _.reverse(this.soundsCache).forEach((e) => {
        if (toKeep.length < self.maxPreloaded) {
          toKeep.push(e)
        } else {
          let src = e.sound._src
          e.sound.unload()
        }
      })
      this.soundsCache = _.reverse(toKeep)
    },
600
601
602
603
604
605
606
607
608
609
610
    removeFromCache (sound) {
      let toKeep = []
      this.soundsCache.forEach((e) => {
        if (e.sound === sound) {
          e.sound.unload()
        } else {
          toKeep.push(e)
        }
      })
      this.soundsCache = toKeep
    },
611
612
613
614
    async loadSound (newValue, oldValue) {
      let trackData = newValue
      let oldSound = this.currentSound
      if (oldSound && trackData !== oldValue) {
Eliot Berriot's avatar
Eliot Berriot committed
615
616
        oldSound.stop(this.soundId)
        this.soundId = null
617
618
619
620
621
622
623
624
625
626
627
      }
      if (!trackData) {
        return
      }
      if (!this.isShuffling && trackData != oldValue) {
        trackData = await this.getTrackData(trackData)
        if (trackData === null) {
          this.handleError({})
        }
        this.currentSound = this.getSound(trackData)
        this.$store.commit('player/isLoadingAudio', true)
628
629
630
631
632
        this.soundId = this.currentSound.play()
        this.$store.commit('player/errored', false)
        this.$store.commit('player/playing', true)
        this.$store.dispatch('player/updateProgress', 0)
        this.observeProgress(true)
633
      }
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
    },
    toggleMobilePlayer () {
      if (['queue', 'player'].indexOf(this.$store.state.ui.queueFocused) > -1) {
        this.$store.commit('ui/queueFocused', null)
      } else {
        this.$store.commit('ui/queueFocused', 'player')
      }
    },
    switchTab () {
      if (this.$store.state.ui.queueFocused === 'player') {
        this.$store.commit('ui/queueFocused', 'queue')
      } else {
        this.$store.commit('ui/queueFocused', 'player')

      }
    },
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
    updateMetadata () {
      // If the session is playing as a PWA, populate the notification
      // with details from the track
      if (this.currentTrack && 'mediaSession' in navigator) {
        let metadata = {
          title: this.currentTrack.title,
          artist: this.currentTrack.artist.name,
        }
        if (this.currentTrack.album && this.currentTrack.album.cover) {
          metadata.album = this.currentTrack.album.title
          metadata.artwork = [
            { src: this.currentTrack.album.cover.urls.original, sizes: '96x96',   type: 'image/png' },
            { src: this.currentTrack.album.cover.urls.original, sizes: '128x128', type: 'image/png' },
            { src: this.currentTrack.album.cover.urls.original, sizes: '192x192', type: 'image/png' },
            { src: this.currentTrack.album.cover.urls.original, sizes: '256x256', type: 'image/png' },
            { src: this.currentTrack.album.cover.urls.original, sizes: '384x384', type: 'image/png' },
            { src: this.currentTrack.album.cover.urls.original, sizes: '512x512', type: 'image/png' },
          ]
        }
        navigator.mediaSession.metadata = new MediaMetadata(metadata)
      }
    }
672
673
  },
  computed: {
674
675
676
    ...mapState({
      currentIndex: state => state.queue.currentIndex,
      playing: state => state.player.playing,
677
      isLoadingAudio: state => state.player.isLoadingAudio,
678
679
680
      volume: state => state.player.volume,
      looping: state => state.player.looping,
      duration: state => state.player.duration,
681
      bufferProgress: state => state.player.bufferProgress,
682
      errored: state => state.player.errored,
683
      currentTime: state => state.player.currentTime,
684
685
686
      queue: state => state.queue
    }),
    ...mapGetters({
687
688
      currentTrack: "queue/currentTrack",
      hasNext: "queue/hasNext",
689
      hasPrevious: "queue/hasPrevious",
690
691
692
693
      emptyQueue: "queue/isEmpty",
      durationFormatted: "player/durationFormatted",
      currentTimeFormatted: "player/currentTimeFormatted",
      progress: "player/progress"
694
    }),
695
    updateProgressThrottled () {
696
      return _.throttle(this.updateProgress, 50)
697
    },
698
    labels() {
Jo Vuit's avatar
Jo Vuit committed
699
      let audioPlayer = this.$pgettext('Sidebar/Player/Hidden text', "Media player")
Agate's avatar
Agate committed
700
      let previous = this.$pgettext('Sidebar/Player/Icon.Tooltip', "Previous track")
Jo Vuit's avatar
Jo Vuit committed
701
702
703
704
705
      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 unmute = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', "Unmute")
      let mute = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', "Mute")
706
      let expandQueue = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', "Expand queue")
707
      let loopingDisabled = this.$pgettext('Sidebar/Player/Icon.Tooltip',
708
709
        "Looping disabled. Click to switch to single-track looping."
      )
710
      let loopingSingle = this.$pgettext('Sidebar/Player/Icon.Tooltip',
711
712
        "Looping on a single track. Click to switch to whole queue looping."
      )
713
      let loopingWhole = this.$pgettext('Sidebar/Player/Icon.Tooltip',
714
715
        "Looping on whole queue. Click to disable looping."
      )
Jo Vuit's avatar
Jo Vuit committed
716
717
      let shuffle = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', "Shuffle your queue")
      let clear = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', "Clear your queue")
718
      let addArtistContentFilter = this.$pgettext('Sidebar/Player/Icon.Tooltip/Verb', 'Hide content from this artist…')
Eliot Berriot's avatar
Eliot Berriot committed
719
      return {
720
        audioPlayer,
Agate's avatar
Agate committed
721
        previous,
Eliot Berriot's avatar
Eliot Berriot committed
722
723
724
725
726
727
728
729
730
        play,
        pause,
        next,
        unmute,
        mute,
        loopingDisabled,
        loopingSingle,
        loopingWhole,
        shuffle,
731
        clear,
732
        expandQueue,
733
        addArtistContentFilter,
Eliot Berriot's avatar
Eliot Berriot committed
734
735
      }
    },
736
737
  },
  watch: {
738
739
    currentTrack: {
      async handler (newValue, oldValue) {
Eliot Berriot's avatar
Eliot Berriot committed
740
741
742
        if (newValue === oldValue) {
          return
        }
743
        this.nextTrackPreloaded = false
744
745
746
747
        clearTimeout(this.playTimeout)
        let self = this
        if (this.currentSound) {
          this.currentSound.pause()
748
        }
749
750
751
752
        this.$store.commit("player/isLoadingAudio", true)
        this.playTimeout = setTimeout(async () => {
          await self.loadSound(newValue, oldValue)
        }, 500);
753
        this.updateMetadata()
754
755
      },
      immediate: false
756
    },
757
    volume(newValue) {
758
      this.sliderVolume = newValue
759
760
761
      if (this.currentSound) {
        this.currentSound.volume(newValue)
      }
762
    },
763
764
    sliderVolume(newValue) {
      this.$store.commit("player/volume", newValue)
765
766
767
768
    },
    playing: async function (newValue) {
      if (this.currentSound) {
        if (newValue === true) {
Eliot Berriot's avatar
Eliot Berriot committed
769
          this.soundId = this.currentSound.play(this.soundId)
770
        } else {
Eliot Berriot's avatar
Eliot Berriot committed
771
          this.currentSound.pause(this.soundId)
772
773
774
775
776
777
778
779
780
781
782
783
        }
      } else {
        await this.loadSound(this.currentTrack, null)
      }

      this.observeProgress(newValue)
    },
    currentTime (newValue) {
      if (!this.isUpdatingTime) {
        this.setCurrentTime(newValue)
      }
      this.isUpdatingTime = false
Eliot Berriot's avatar
Eliot Berriot committed
784
785
786
787
788
    },
    emptyQueue (newValue) {
      if (newValue) {
        Howler.unload()
      }
789
790
791
792
    }
  }
}
</script>