Cleanup old queue and player logic

environments/review-docs-renov-b1i8ag/deployments/15025
wvffle 2022-10-28 10:40:55 +00:00 zatwierdzone przez Georg Krause
rodzic f06464ffa2
commit 9f36c4b3a8
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: 2970D504B2183D22
22 zmienionych plików z 127 dodań i 1135 usunięć

Wyświetl plik

@ -1,8 +1,10 @@
<script setup lang="ts">
import type { Track } from '~/types'
import type { QueueTrack } from '~/composables/audio/queue'
import { useIntervalFn, useToggle, useWindowSize } from '@vueuse/core'
import { computed, nextTick, onMounted, ref, watchEffect } from 'vue'
import { useQueue } from '~/composables/audio/queue'
import { useStore } from '~/store'
import ChannelUploadModal from '~/components/channels/UploadModal.vue'
@ -17,19 +19,17 @@ import Sidebar from '~/components/Sidebar.vue'
import Queue from '~/components/Queue.vue'
import onKeyboardShortcut from '~/composables/onKeyboardShortcut'
import useQueue from '~/composables/audio/useQueue'
const store = useStore()
// Tracks
const { currentTrack } = useQueue()
const getTrackInformationText = (track: Track | undefined) => {
const { currentTrack, tracks } = useQueue()
const getTrackInformationText = (track: QueueTrack | undefined) => {
if (!track) {
return null
}
const artist = track.artist ?? track.album?.artist
return `${track.title}${artist?.name}`
return `${track.title}${track.artistName}`
}
// Update title
@ -76,9 +76,11 @@ store.dispatch('auth/fetchUser')
<template>
<div
:key="String(store.state.instance.instanceUrl)"
:class="[store.state.ui.queueFocused ? 'queue-focused' : '',
{'has-bottom-player': store.state.queue.tracks.length > 0}]"
:key="store.state.instance.instanceUrl"
:class="{
'has-bottom-player': tracks.length > 0,
'queue-focused': store.state.ui.queueFocused
}"
>
<!-- here, we display custom stylesheets, if any -->
<link

Wyświetl plik

@ -192,7 +192,7 @@ const reorderTracks = async (from: number, to: number) => {
The track cannot be loaded
</translate>
</h3>
<p v-if="hasNext && isPlaying && $store.state.player.errorCount < $store.state.player.maxConsecutiveErrors">
<p v-if="hasNext && isPlaying && errored">
<translate translate-context="Sidebar/Player/Error message.Paragraph">
The next track will play automatically in a few seconds
</translate>

Wyświetl plik

@ -1,12 +1,14 @@
<script setup lang="ts">
import type { Cover, Track } from '~/types'
import PlayButton from '~/components/audio/PlayButton.vue'
import TrackFavoriteIcon from '~/components/favorites/TrackFavoriteIcon.vue'
import useQueue from '~/composables/audio/useQueue'
import usePlayer from '~/composables/audio/usePlayer'
import { computed } from 'vue'
import { usePlayer } from '~/composables/audio/player'
import { useQueue } from '~/composables/audio/queue'
import TrackFavoriteIcon from '~/components/favorites/TrackFavoriteIcon.vue'
import PlayButton from '~/components/audio/PlayButton.vue'
interface Props {
entry: Track
defaultCover: Cover
@ -15,14 +17,14 @@ interface Props {
const props = defineProps<Props>()
const { currentTrack } = useQueue()
const { playing } = usePlayer()
const { isPlaying } = usePlayer()
const cover = computed(() => props.entry.cover ?? null)
const duration = computed(() => props.entry.uploads.find(upload => upload.duration)?.duration ?? null)
</script>
<template>
<div :class="[{active: currentTrack && playing && entry.id === currentTrack.id}, 'channel-entry-card']">
<div :class="[{active: currentTrack && isPlaying && entry.id === currentTrack.id}, 'channel-entry-card']">
<div class="controls">
<play-button
class="basic circular icon"

Wyświetl plik

@ -1,15 +1,17 @@
<script setup lang="ts">
import type { Track, Artist, Album, Playlist, Library, Channel, Actor } from '~/types'
import type { PlayOptionsProps } from '~/composables/audio/usePlayOptions'
// import type { Track } from '~/types'
import { ref, computed } from 'vue'
import { useGettext } from 'vue3-gettext'
import { ref, computed } from 'vue'
import { usePlayer } from '~/composables/audio/player'
import { useQueue } from '~/composables/audio/queue'
import usePlayOptions from '~/composables/audio/usePlayOptions'
import TrackFavoriteIcon from '~/components/favorites/TrackFavoriteIcon.vue'
import TrackModal from '~/components/audio/track/Modal.vue'
import usePlayOptions from '~/composables/audio/usePlayOptions'
import useQueue from '~/composables/audio/useQueue'
import usePlayer from '~/composables/audio/usePlayer'
interface Props extends PlayOptionsProps {
track: Track
@ -47,7 +49,7 @@ const props = withDefaults(defineProps<Props>(), {
const showTrackModal = ref(false)
const { currentTrack } = useQueue()
const { playing } = usePlayer()
const { isPlaying } = usePlayer()
const { activateTrack } = usePlayOptions(props)
const { $pgettext } = useGettext()
@ -101,7 +103,7 @@ const actionsButtonLabel = computed(() => $pgettext('Content/Track/Icon.Tooltip/
:class="[
'track-title',
'mobile',
{ 'play-indicator': playing && track.id === currentTrack?.id },
{ 'play-indicator': isPlaying && track.id === currentTrack?.id },
]"
>
{{ track.title }}

Wyświetl plik

@ -1,16 +1,17 @@
<script setup lang="ts">
import type { Track, Artist, Album, Playlist, Library, Channel, Actor, /* Track, */ Cover } from '~/types'
import type { Track, Artist, Album, Playlist, Library, Channel, Actor, Cover } from '~/types'
import type { PlayOptionsProps } from '~/composables/audio/usePlayOptions'
import { ref } from 'vue'
import { useQueue } from '~/composables/audio/queue'
import axios from 'axios'
import PlayButton from '~/components/audio/PlayButton.vue'
import usePlayOptions from '~/composables/audio/usePlayOptions'
import useErrorHandler from '~/composables/useErrorHandler'
import useQueue from '~/composables/audio/useQueue'
interface Props extends PlayOptionsProps {
tracks: Track[]

Wyświetl plik

@ -1,15 +1,17 @@
<script setup lang="ts">
import type { Track, Artist, Album, Playlist, Library, Channel, Actor } from '~/types'
import type { PlayOptionsProps } from '~/composables/audio/usePlayOptions'
// import type { Track } from '~/types'
import { ref, computed } from 'vue'
import { useGettext } from 'vue3-gettext'
import { ref, computed } from 'vue'
import { usePlayer } from '~/composables/audio/player'
import { useQueue } from '~/composables/audio/queue'
import usePlayOptions from '~/composables/audio/usePlayOptions'
import TrackFavoriteIcon from '~/components/favorites/TrackFavoriteIcon.vue'
import TrackModal from '~/components/audio/track/Modal.vue'
import usePlayOptions from '~/composables/audio/usePlayOptions'
import useQueue from '~/composables/audio/useQueue'
import usePlayer from '~/composables/audio/usePlayer'
interface Props extends PlayOptionsProps {
track: Track
@ -47,7 +49,7 @@ const props = withDefaults(defineProps<Props>(), {
const showTrackModal = ref(false)
const { currentTrack } = useQueue()
const { playing } = usePlayer()
const { isPlaying } = usePlayer()
const { activateTrack } = usePlayOptions(props)
const { $pgettext } = useGettext()
@ -101,7 +103,7 @@ const actionsButtonLabel = computed(() => $pgettext('Content/Track/Icon.Tooltip/
:class="[
'track-title',
'mobile',
{ 'play-indicator': playing && track.id === currentTrack?.id },
{ 'play-indicator': isPlaying && track.id === currentTrack?.id },
]"
>
{{ track.title }}

Wyświetl plik

@ -1,16 +1,17 @@
<script setup lang="ts">
import type { Track, Artist, Album, Playlist, Library, Channel, Actor } from '~/types'
import type { PlayOptionsProps } from '~/composables/audio/usePlayOptions'
// import type { Track } from '~/types'
import PlayIndicator from '~/components/audio/track/PlayIndicator.vue'
import TrackFavoriteIcon from '~/components/favorites/TrackFavoriteIcon.vue'
import PlayButton from '~/components/audio/PlayButton.vue'
import usePlayOptions from '~/composables/audio/usePlayOptions'
import useQueue from '~/composables/audio/useQueue'
import usePlayer from '~/composables/audio/usePlayer'
import { computed } from 'vue'
import usePlayOptions from '~/composables/audio/usePlayOptions'
import TrackFavoriteIcon from '~/components/favorites/TrackFavoriteIcon.vue'
import PlayIndicator from '~/components/audio/track/PlayIndicator.vue'
import PlayButton from '~/components/audio/PlayButton.vue'
import { usePlayer } from '~/composables/audio/player'
import { useQueue } from '~/composables/audio/queue'
interface Props extends PlayOptionsProps {
track: Track
index: number
@ -51,9 +52,9 @@ const props = withDefaults(defineProps<Props>(), {
account: null
})
const { playing, loading } = usePlayer()
const { currentTrack } = useQueue()
const { activateTrack } = usePlayOptions(props)
const { isPlaying, loading } = usePlayer()
const { currentTrack } = useQueue()
const active = computed(() => props.track.id === currentTrack.value?.id && props.track.position === currentTrack.value?.position)
</script>
@ -71,14 +72,14 @@ const active = computed(() => props.track.id === currentTrack.value?.id && props
<play-indicator
v-if="
!loading &&
playing &&
isPlaying &&
active &&
!hover
"
/>
<button
v-else-if="
!playing &&
!isPlaying &&
active &&
!hover
"
@ -88,7 +89,7 @@ const active = computed(() => props.track.id === currentTrack.value?.id && props
</button>
<button
v-else-if="
playing &&
isPlaying &&
active &&
hover
"

Wyświetl plik

@ -1,9 +1,11 @@
<script setup lang="ts">
import type { Playlist, Track, PlaylistTrack, BackendError, APIErrorResponse } from '~/types'
import type { Playlist, PlaylistTrack, BackendError, APIErrorResponse } from '~/types'
import { useGettext } from 'vue3-gettext'
import { useVModels } from '@vueuse/core'
import { computed, ref } from 'vue'
import { useQueue } from '~/composables/audio/queue'
import { useStore } from '~/store'
import draggable from 'vuedraggable'
@ -11,8 +13,6 @@ import axios from 'axios'
import PlaylistForm from '~/components/playlists/Form.vue'
import useQueue from '~/composables/audio/useQueue'
interface Events {
(e: 'update:playlistTracks', value: PlaylistTrack[]): void
(e: 'update:playlist', value: Playlist): void
@ -137,13 +137,13 @@ const clearPlaylist = async () => {
isLoading.value = false
}
const insertMany = async (insertedTracks: Track[], allowDuplicates: boolean) => {
const insertMany = async (insertedTracks: number[], allowDuplicates: boolean) => {
isLoading.value = true
try {
const response = await axios.post(`playlists/${playlist.value?.id}/add/`, {
allow_duplicates: allowDuplicates,
tracks: insertedTracks.map(track => track.id)
tracks: insertedTracks
})
tracks.value.push(...response.data.results)

Wyświetl plik

@ -30,7 +30,6 @@ export const isPlaying = ref(false)
export const usePlayer = createGlobalState(() => {
const { currentSound, createTrack } = useTracks()
const { playNext } = useQueue()
const store = useStore()
watchEffect(() => {
const sound = currentSound.value
@ -50,6 +49,11 @@ export const usePlayer = createGlobalState(() => {
const { initialize } = useTracks()
initialize()
const { trackRadioPopulating } = useQueue()
trackRadioPopulating()
trackListenSubmissions()
createTrack(currentIndex.value)
}))
@ -57,7 +61,7 @@ export const usePlayer = createGlobalState(() => {
const lastVolume = useStorage('player:last-volume', 0.7)
const volume: Ref<number> = useStorage('player:volume', 0.7)
watch(volume, (to, from) => setGain(to))
watch(volume, (gain) => setGain(gain))
const mute = () => {
if (volume.value > 0) {
@ -113,14 +117,17 @@ export const usePlayer = createGlobalState(() => {
// Submit listens
const listenSubmitted = ref(false)
whenever(listenSubmitted, async () => {
console.log('Listening submitted!')
if (!store.state.auth.authenticated) return
if (!currentTrack.value) return
const trackListenSubmissions = () => {
const store = useStore()
whenever(listenSubmitted, async () => {
console.log('Listening submitted!')
if (!store.state.auth.authenticated) return
if (!currentTrack.value) return
await axios.post('history/listenings/', { track: currentTrack.value.id })
.catch((error) => console.error('Could not record track in history', error))
})
await axios.post('history/listenings/', { track: currentTrack.value.id })
.catch((error) => console.error('Could not record track in history', error))
})
}
watch(currentTime, (time) => {
const sound = currentSound.value

Wyświetl plik

@ -69,7 +69,6 @@ export const currentTrack = computed(() => queue.value[currentIndex.value])
// Use Queue
export const useQueue = createGlobalState(() => {
const { currentSound } = useTracks()
const store = useStore()
const createQueueTrack = async (track: Track): Promise<QueueTrack> => {
if (track.uploads.length === 0) {
@ -236,18 +235,26 @@ export const useQueue = createGlobalState(() => {
}))
// Clear
const clear = () => {
store.commit('radios/reset')
const clear = async () => {
tracks.value.length = 0
}
// Radio queue populating
watchEffect(() => {
if (store.state.radios.running && currentIndex.value === tracks.value.length - 1) {
console.log('POPULATING QUEUE FROM RADIO')
return store.dispatch('radios/populateQueue')
}
})
const trackRadioPopulating = () => {
const store = useStore()
watchEffect(() => {
if (store.state.radios.running && currentIndex.value === tracks.value.length - 1) {
console.log('POPULATING QUEUE FROM RADIO')
return store.dispatch('radios/populateQueue')
}
})
watchEffect(() => {
if (tracks.value.length === 0) {
return store.dispatch('radios/stop')
}
})
}
return {
tracks,
@ -267,6 +274,7 @@ export const useQueue = createGlobalState(() => {
reshuffleUpcomingTracks,
reorder,
endsIn,
clear
clear,
trackRadioPopulating
}
})

Wyświetl plik

@ -1,11 +0,0 @@
export const DYNAMIC_RANGE = 40 // dB
export default (volume: number) => {
if (volume <= 0.0) {
return 0.0
}
// (1.0; 0.0) -> (0; -DYNAMIC_RANGE) dB
const dB = (volume - 1) * DYNAMIC_RANGE
return Math.pow(10, dB / 20)
}

Wyświetl plik

@ -114,7 +114,9 @@ export const useTracks = createGlobalState(() => {
const initialize = createGlobalState(() => {
const { currentTrack: track, currentIndex } = useQueue()
watch(currentIndex, (index) => createTrack(index))
syncRef(currentTrack, track)
syncRef(track, currentTrack, {
direction: 'ltr'
})
})
const currentSound = computed(() => soundCache.get(currentTrack.value?.id ?? -1))

Wyświetl plik

@ -9,8 +9,8 @@ import { useStore } from '~/store'
import { usePlayer } from '~/composables/audio/player'
import { useQueue } from '~/composables/audio/queue'
import axios from 'axios'
import jQuery from 'jquery'
import axios from 'axios'
export interface PlayOptionsProps {
isPlayable?: boolean

Wyświetl plik

@ -1,262 +0,0 @@
import type { Track } from '~/types'
import { computed, watchEffect, ref, watch } from 'vue'
import { Howler } from 'howler'
import { useRafFn, useTimeoutFn } from '@vueuse/core'
import useQueue from '~/composables/audio/useQueue'
import useSound from '~/composables/audio/useSound'
import toLinearVolumeScale from '~/composables/audio/toLinearVolumeScale'
import store from '~/store'
import axios from 'axios'
const PRELOAD_DELAY = 15
const { currentSound, loadSound, onSoundProgress } = useSound()
const { isShuffling, currentTrack, currentIndex } = useQueue()
const looping = computed(() => store.state.player.looping)
const playing = computed(() => store.state.player.playing)
const loading = computed(() => store.state.player.isLoadingAudio)
const errored = computed(() => store.state.player.errored)
const focused = computed(() => store.state.ui.queueFocused === 'player')
// Cache sound if we have currentTrack available
if (currentTrack.value) {
loadSound(currentTrack.value)
}
// Playing
const playTrack = async (track: Track, oldTrack?: Track) => {
const oldSound = currentSound.value
// TODO (wvffle): Move oldTrack to watcher
if (oldSound && track !== oldTrack) {
oldSound.stop()
}
if (!track) {
return
}
if (!isShuffling.value) {
if (!track.uploads.length) {
// we don't have any information for this track, we need to fetch it
track = await axios.get(`tracks/${track.id}/`)
.then(response => response.data, () => null)
}
if (track === null) {
store.commit('player/isLoadingAudio', false)
store.dispatch('player/trackErrored')
return
}
currentSound.value = loadSound(track)
if (playing.value) {
currentSound.value.play()
store.commit('player/playing', true)
} else {
store.commit('player/isLoadingAudio', false)
}
store.commit('player/errored', false)
store.dispatch('player/updateProgress', 0)
}
}
const { start: loadTrack, stop: cancelLoading } = useTimeoutFn((track, oldTrack) => {
playTrack(track as Track, oldTrack as Track)
}, 100, { immediate: false }) as {
start: (a: Track, b: Track) => void
stop: () => void
}
watch(currentTrack, (track, oldTrack) => {
cancelLoading()
currentSound.value?.pause()
store.commit('player/isLoadingAudio', true)
loadTrack(track, oldTrack)
})
// Volume
const volume = computed({
get: () => store.state.player.volume,
set: (value) => store.commit('player/volume', value)
})
watchEffect(() => Howler.volume(toLinearVolumeScale(volume.value)))
const mute = () => store.dispatch('player/mute')
const unmute = () => store.dispatch('player/unmute')
// Time and duration
const duration = computed(() => store.state.player.duration)
const currentTime = computed({
get: () => store.state.player.currentTime,
set: (time) => {
if (time < 0 || time > duration.value) {
return
}
if (!currentSound.value?.getSource() || time === currentSound.value.seek()) {
return
}
currentSound.value.seek(time)
// Update progress immediately to ensure updated UI
progress.value = time
}
})
const durationFormatted = computed(() => store.getters['player/durationFormatted'])
const currentTimeFormatted = computed(() => store.getters['player/currentTimeFormatted'])
// Progress
const progress = computed({
get: () => store.getters['player/progress'],
set: (time) => {
if (currentSound.value?.state() === 'loaded') {
store.state.player.currentTime = time
const duration = currentSound.value.duration()
currentSound.value.triggerSoundProgress(time, duration)
}
}
})
const bufferProgress = computed(() => store.state.player.bufferProgress)
onSoundProgress(({ node, time, duration }) => {
const toPreload = store.state.queue.tracks[currentIndex.value + 1]
if (!nextTrackPreloaded.value && toPreload && (time > PRELOAD_DELAY || duration - time < 30)) {
loadSound(toPreload)
nextTrackPreloaded.value = true
}
if (time > duration / 2) {
if (!isListeningSubmitted.value) {
store.dispatch('player/trackListened', currentTrack.value)
isListeningSubmitted.value = true
}
}
// from https://github.com/goldfire/howler.js/issues/752#issuecomment-372083163
const { buffered, currentTime } = node
let range = 0
try {
while (buffered.start(range) >= currentTime || currentTime >= buffered.end(range)) {
range += 1
}
} catch (IndexSizeError) {
return
}
let loadPercentage
const start = buffered.start(range)
const end = buffered.end(range)
if (range === 0) {
// easy case, no user-seek
const loadStartPercentage = start / node.duration
const loadEndPercentage = end / node.duration
loadPercentage = loadEndPercentage - loadStartPercentage
} else {
const loaded = end - start
const 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 === bufferProgress.value) {
return
}
store.commit('player/bufferProgress', loadPercentage * 100)
})
const observeProgress = ref(false)
useRafFn(() => {
if (observeProgress.value && currentSound.value?.state() === 'loaded') {
progress.value = currentSound.value.seek()
}
})
watch(playing, async (isPlaying) => {
if (currentSound.value) {
if (isPlaying) {
currentSound.value.play()
} else {
currentSound.value.pause()
}
} else {
await playTrack(currentTrack.value)
}
observeProgress.value = isPlaying
})
const isListeningSubmitted = ref(false)
const nextTrackPreloaded = ref(false)
watch(currentTrack, () => (nextTrackPreloaded.value = false))
// Controls
const pause = () => store.dispatch('player/pausePlayback')
const resume = () => store.dispatch('player/resumePlayback')
const { next } = useQueue()
const seek = (step: number) => {
// seek right
if (step > 0) {
if (currentTime.value + step < duration.value) {
store.dispatch('player/updateProgress', (currentTime.value + step))
} else {
next()
}
return
}
// seek left
const position = Math.max(currentTime.value + step, 0)
store.dispatch('player/updateProgress', position)
}
const togglePlayback = () => {
if (playing.value) return pause()
return resume()
}
export default () => {
return {
looping,
playing,
loading,
errored,
focused,
isListeningSubmitted,
playTrack,
volume,
mute,
unmute,
duration,
currentTime,
durationFormatted,
currentTimeFormatted,
progress,
bufferProgress,
pause,
resume,
seek,
togglePlayback
}
}

Wyświetl plik

@ -1,106 +0,0 @@
import type { Track } from '~/types'
import { useTimeoutFn, useThrottleFn, useTimeAgo, useNow, whenever } from '@vueuse/core'
import { Howler } from 'howler'
import { gettext } from '~/init/locale'
import { ref, computed } from 'vue'
import { sum } from 'lodash-es'
import store from '~/store'
const { $pgettext } = gettext
const currentTrack = computed(() => store.getters['queue/currentTrack'])
const currentIndex = computed(() => store.state.queue.currentIndex)
const hasNext = computed(() => store.getters['queue/hasNext'])
const hasPrevious = computed(() => store.getters['queue/hasPrevious'])
const isEmpty = computed(() => store.getters['queue/isEmpty'])
whenever(isEmpty, () => Howler.unload())
const removeTrack = (index: number) => store.dispatch('queue/cleanTrack', index)
const clear = () => store.dispatch('queue/clean')
const next = () => store.dispatch('queue/next')
const previous = () => store.dispatch('queue/previous')
const focused = computed(() => store.state.ui.queueFocused === 'queue')
//
// Track list
//
const tracks = computed<Track[]>(() => store.state.queue.tracks)
const reorder = (oldIndex: number, newIndex: number) => {
store.commit('queue/reorder', {
oldIndex,
newIndex
})
}
//
// Shuffle
//
const isShuffling = ref(false)
const forceShuffle = useThrottleFn(() => {
isShuffling.value = true
useTimeoutFn(async () => {
await store.dispatch('queue/shuffle')
store.commit('ui/addMessage', {
content: $pgettext('Content/Queue/Message', 'Queue shuffled!'),
date: new Date()
})
isShuffling.value = false
}, 100)
})
const shuffle = useThrottleFn(() => {
if (isShuffling.value || isEmpty.value) {
return
}
return forceShuffle()
}, 101, false)
//
// Time left
//
const now = useNow()
const endsIn = useTimeAgo(computed(() => {
const seconds = sum(
tracks.value
.slice(currentIndex.value)
.map((track) => track.uploads?.[0]?.duration ?? 0)
)
const date = new Date(now.value)
date.setSeconds(date.getSeconds() + seconds)
return date
}))
export default () => {
return {
currentTrack,
currentIndex,
hasNext,
hasPrevious,
isEmpty,
isShuffling,
removeTrack,
clear,
next,
previous,
tracks,
reorder,
shuffle,
forceShuffle,
endsIn,
focused
}
}

Wyświetl plik

@ -1,156 +0,0 @@
import type { Track } from '~/types'
import { ref, computed } from 'vue'
import { Howl } from 'howler'
import useTrackSources from '~/composables/audio/useTrackSources'
import useSoundCache from '~/composables/audio/useSoundCache'
import usePlayer from '~/composables/audio/usePlayer'
import store from '~/store'
import { createEventHook, useThrottleFn } from '@vueuse/core'
interface Sound {
id?: number
howl: Howl
stop: () => void
play: () => void
pause: () => void
state: () => 'unloaded' | 'loading' | 'loaded'
seek: (time?: number) => number
duration: () => number
getSource: () => boolean
triggerSoundProgress: (time: number, duration: number) => void
}
const soundCache = useSoundCache()
const currentTrack = computed(() => store.getters['queue/currentTrack'])
const looping = computed(() => store.state.player.looping)
const currentSound = ref<Sound>()
const soundId = ref()
const soundProgress = createEventHook<{ node: HTMLAudioElement, time: number, duration: number }>()
const createSound = (howl: Howl): Sound => ({
howl,
play () {
this.id = howl.play(this.id)
},
stop () {
howl.stop(this.id)
this.id = undefined
},
pause () {
howl.pause(this.id)
},
state: () => howl.state(),
seek: (time?: number) => howl.seek(time),
duration: () => howl.duration(),
getSource: () => (howl as any)._sounds[0],
triggerSoundProgress: useThrottleFn((time: number, duration: number) => {
const node = (howl as any)._sounds[0]?._node
if (node) {
soundProgress.trigger({ node, time, duration })
}
}, 1000)
})
const loadSound = (track: Track): Sound => {
const cached = soundCache.get(track.id)
if (cached) {
return createSound(cached.howl)
}
const sources = useTrackSources(track)
const howl = new Howl({
src: sources.map((source) => source.url),
format: sources.map((source) => source.type),
autoplay: false,
loop: false,
html5: true,
preload: true,
onend () {
const onlyTrack = store.state.queue.tracks.length === 1
// NOTE: We need to send trackListened when we've finished track playback and we are not focused on the tab
const { isListeningSubmitted } = usePlayer()
if (!isListeningSubmitted.value) {
store.dispatch('player/trackListened', currentTrack.value)
isListeningSubmitted.value = true
}
if (looping.value === 1 || (onlyTrack && looping.value === 2)) {
currentSound.value?.seek(0)
store.dispatch('player/updateProgress', 0)
soundId.value = currentSound.value?.play()
} else {
store.dispatch('player/trackEnded', currentTrack.value)
}
},
onunlock () {
if (store.state.player.playing && currentSound.value) {
soundId.value = currentSound.value.play()
}
},
onplay () {
const [otherId] = (this as any)._getSoundIds()
const [currentId] = (currentSound.value?.howl as any)?._getSoundIds() ?? []
if (otherId !== currentId) {
return (this as any).stop()
}
const time = currentSound.value?.seek() ?? 0
const duration = currentSound.value?.duration() ?? 0
if (time <= duration / 2) {
const { isListeningSubmitted } = usePlayer()
isListeningSubmitted.value = false
}
store.commit('player/isLoadingAudio', false)
store.commit('player/resetErrorCount')
store.commit('player/errored', false)
store.commit('player/duration', howl.duration())
},
onplayerror (soundId, error) {
console.error('play error', soundId, error)
},
onloaderror (soundId, error) {
soundCache.delete(track.id)
howl.unload()
const [otherId] = (this as any)._getSoundIds()
const [currentId] = (currentSound.value?.howl as any)._getSoundIds() ?? []
if (otherId !== currentId) {
console.error('load error', soundId, error)
return
}
console.error('Error while playing:', soundId, error)
store.commit('player/isLoadingAudio', false)
store.dispatch('player/trackErrored')
}
})
soundCache.set(track.id, {
id: track.id,
date: new Date(),
howl
})
return createSound(howl)
}
export default () => {
return {
loadSound,
currentSound,
onSoundProgress: soundProgress.on
}
}

Wyświetl plik

@ -1,38 +0,0 @@
import type { Howl } from 'howler'
import { sortBy } from 'lodash-es'
import { reactive, watchEffect, ref } from 'vue'
const MAX_PRELOADED = 3
export interface CachedSound {
id: number
date: Date
howl: Howl
}
const soundCache = reactive(new Map<number, CachedSound>())
const cleaningCache = ref(false)
watchEffect(() => {
const toRemove = soundCache.size - MAX_PRELOADED
if (toRemove > 0 && !cleaningCache.value) {
cleaningCache.value = true
const excess = sortBy([...soundCache.values()], [(cached: CachedSound) => cached.date])
.slice(0, toRemove)
for (const cached of excess) {
console.log('Removing cached element:', cached)
soundCache.delete(cached.id)
cached.howl.unload()
}
cleaningCache.value = false
}
})
export default () => {
return soundCache
}

Wyświetl plik

@ -1,51 +0,0 @@
import type { Track } from '~/types'
import store from '~/store'
import updateQueryString from '~/composables/updateQueryString'
export interface TrackSource {
url: string
type: string
}
export default (trackData: Track): TrackSource[] => {
const audio = document.createElement('audio')
const allowed = ['probably', 'maybe']
const sources = trackData.uploads
.filter(upload => {
const canPlay = audio.canPlayType(upload.mimetype)
return allowed.indexOf(canPlay) > -1
})
.map(upload => ({
type: upload.extension,
url: store.getters['instance/absoluteUrl'](upload.listen_url)
}))
// 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: updateQueryString(
store.getters['instance/absoluteUrl'](trackData.listen_url),
'to',
'mp3'
)
})
const token = store.state.auth.scopedTokens.listen
if (store.state.auth.authenticated && token !== null) {
// 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
return sources.map(source => ({
...source,
url: updateQueryString(source.url, 'token', token)
}))
}
return sources
}

Wyświetl plik

@ -1,42 +1,46 @@
import type { InitModule } from '~/types'
import { whenever } from '@vueuse/core'
import useQueue from '~/composables/audio/useQueue'
import usePlayer from '~/composables/audio/usePlayer'
import { useQueue } from '~/composables/audio/queue'
import { usePlayer } from '~/composables/audio/player'
export const install: InitModule = ({ app }) => {
const { currentTrack, next, previous } = useQueue()
const { resume, pause, seek } = usePlayer()
const { currentTrack, playNext, playPrevious } = useQueue()
const { isPlaying, seekBy } = usePlayer()
// Add controls for notification drawer
if ('mediaSession' in navigator) {
navigator.mediaSession.setActionHandler('play', resume)
navigator.mediaSession.setActionHandler('pause', pause)
navigator.mediaSession.setActionHandler('seekforward', () => seek(5))
navigator.mediaSession.setActionHandler('seekbackward', () => seek(-5))
navigator.mediaSession.setActionHandler('nexttrack', next)
navigator.mediaSession.setActionHandler('previoustrack', previous)
navigator.mediaSession.setActionHandler('play', () => (isPlaying.value = true))
navigator.mediaSession.setActionHandler('pause', () => (isPlaying.value = false))
navigator.mediaSession.setActionHandler('seekforward', () => seekBy(5))
navigator.mediaSession.setActionHandler('seekbackward', () => seekBy(-5))
navigator.mediaSession.setActionHandler('nexttrack', () => playNext())
navigator.mediaSession.setActionHandler('previoustrack', () => playPrevious())
// TODO (wvffle): set metadata to null when we don't have currentTrack?
// If the session is playing as a PWA, populate the notification
// with details from the track
whenever(currentTrack, () => {
const { title, artist, album } = currentTrack.value
whenever(currentTrack, (track) => {
if (!track) {
navigator.mediaSession.metadata = null
return
}
const { title, artistName, albumTitle, coverUrl, albumId } = track
const metadata: MediaMetadataInit = {
title,
artist: artist.name
artist: artistName
}
if (album?.cover) {
metadata.album = album.title
if (albumId !== -1) {
metadata.album = albumTitle
metadata.artwork = [
{ src: album.cover.urls.original, sizes: '96x96', type: 'image/png' },
{ src: album.cover.urls.original, sizes: '128x128', type: 'image/png' },
{ src: album.cover.urls.original, sizes: '192x192', type: 'image/png' },
{ src: album.cover.urls.original, sizes: '256x256', type: 'image/png' },
{ src: album.cover.urls.original, sizes: '384x384', type: 'image/png' },
{ src: album.cover.urls.original, sizes: '512x512', type: 'image/png' }
{ src: coverUrl, sizes: '96x96', type: 'image/png' },
{ src: coverUrl, sizes: '128x128', type: 'image/png' },
{ src: coverUrl, sizes: '192x192', type: 'image/png' },
{ src: coverUrl, sizes: '256x256', type: 'image/png' },
{ src: coverUrl, sizes: '384x384', type: 'image/png' },
{ src: coverUrl, sizes: '512x512', type: 'image/png' }
]
}

Wyświetl plik

@ -5,8 +5,6 @@ import type { State as LibrariesState } from './libraries'
import type { State as ChannelsState } from './channels'
import type { State as InstanceState } from './instance'
import type { State as RadiosState } from './radios'
import type { State as PlayerState } from './player'
import type { State as QueueState } from './queue'
import type { State as AuthState } from './auth'
import type { State as UiState } from './ui'
import type { InjectionKey } from 'vue'
@ -21,8 +19,6 @@ import libraries from './libraries'
import channels from './channels'
import instance from './instance'
import radios from './radios'
import player from './player'
import queue from './queue'
import auth from './auth'
import ui from './ui'
@ -34,8 +30,6 @@ export interface RootState {
channels: ChannelsState
instance: InstanceState
radios: RadiosState
player: PlayerState
queue: QueueState
auth: AuthState
ui: UiState
}
@ -50,8 +44,6 @@ export default createStore<RootState>({
channels,
instance,
radios,
player,
queue,
auth,
ui
},
@ -73,7 +65,10 @@ export default createStore<RootState>({
}),
createPersistedState({
key: 'radios',
paths: ['radios'],
paths: [
'radios.current',
'radios.running'
],
filter: (mutation) => {
return mutation.type.startsWith('radios/')
}
@ -87,47 +82,6 @@ export default createStore<RootState>({
filter: (mutation) => {
return mutation.type.startsWith('player/') && mutation.type !== 'player/currentTime'
}
}),
createPersistedState({
key: 'queue',
filter: (mutation) => {
return mutation.type.startsWith('queue/')
},
reducer: (state) => {
return {
queue: {
currentIndex: state.queue.currentIndex,
tracks: state.queue.tracks.map((track: any) => {
// we keep only valuable fields to make the cache lighter and avoid
// cyclic value serialization errors
const artist = {
id: track.artist.id,
mbid: track.artist.mbid,
name: track.artist.name
}
const data = {
id: track.id,
title: track.title,
mbid: track.mbid,
uploads: track.uploads,
listen_url: track.listen_url,
artist,
album: {}
}
if (track.album) {
data.album = {
id: track.album.id,
title: track.album.title,
mbid: track.album.mbid,
cover: track.album.cover,
artist
}
}
return data
})
}
}
}
})
]
})

Wyświetl plik

@ -1,186 +0,0 @@
import type { Module } from 'vuex'
import type { RootState } from '~/store/index'
import axios from 'axios'
import time from '~/utils/time'
import useLogger from '~/composables/useLogger'
export interface State {
maxConsecutiveErrors: number
errorCount: number
playing: boolean
isLoadingAudio: boolean
volume: number
tempVolume: number
duration: number
currentTime: number
errored: boolean
bufferProgress: number
looping: 0 | 1 | 2 // 0 -> no, 1 -> on track, 2 -> on queue
}
const logger = useLogger()
const store: Module<State, RootState> = {
namespaced: true,
state: {
maxConsecutiveErrors: 5,
errorCount: 0,
playing: false,
isLoadingAudio: false,
volume: 1,
tempVolume: 0.5,
duration: 0,
currentTime: 0,
errored: false,
bufferProgress: 0,
looping: 0
},
mutations: {
reset (state) {
state.errorCount = 0
state.playing = false
},
volume (state, value) {
value = parseFloat(value)
value = Math.min(value, 1)
value = Math.max(value, 0)
state.volume = value
},
tempVolume (state, value) {
value = parseFloat(value)
value = Math.min(value, 1)
value = Math.max(value, 0)
state.tempVolume = value
},
incrementVolume (state, value) {
value = parseFloat(state.volume + value)
value = Math.min(value, 1)
value = Math.max(value, 0)
state.volume = value
},
incrementErrorCount (state) {
state.errorCount += 1
},
resetErrorCount (state) {
state.errorCount = 0
},
duration (state, value) {
state.duration = value
},
errored (state, value) {
state.errored = value
},
currentTime (state, value) {
state.currentTime = value
},
looping (state, value) {
state.looping = value
},
playing (state, value) {
state.playing = value
},
bufferProgress (state, value) {
state.bufferProgress = value
},
toggleLooping (state) {
if (state.looping > 1) {
state.looping = 0
} else {
state.looping += 1
}
},
isLoadingAudio (state, value) {
state.isLoadingAudio = value
}
},
getters: {
durationFormatted: state => {
return time.parse(Math.round(state.duration))
},
currentTimeFormatted: state => {
return time.parse(Math.round(state.currentTime))
},
progress: state => {
return Math.min(state.currentTime / state.duration * 100, 100)
}
},
actions: {
incrementVolume ({ commit, state }, value) {
commit('volume', state.volume + value)
},
stop ({ commit }) {
commit('errored', false)
commit('resetErrorCount')
},
togglePlayback ({ commit, state, dispatch }) {
commit('playing', !state.playing)
if (state.errored && state.errorCount < state.maxConsecutiveErrors) {
setTimeout(() => {
if (state.playing) {
dispatch('queue/next', null, { root: true })
}
}, 3000)
}
},
async resumePlayback ({ commit, state, dispatch }) {
commit('playing', true)
if (state.errored && state.errorCount < state.maxConsecutiveErrors) {
// TODO (wvffle): Cancel whenever we skip track
await new Promise(resolve => setTimeout(resolve, 3000))
if (state.playing) {
return dispatch('queue/next', null, { root: true })
}
}
},
pausePlayback ({ commit }) {
commit('playing', false)
},
trackListened ({ rootState }, track) {
if (!rootState.auth.authenticated) {
return
}
return axios.post('history/listenings/', { track: track.id }).catch((error) => {
logger.error('Could not record track in history', error)
})
},
trackEnded ({ commit, dispatch, rootState }) {
const queueState = rootState.queue
if (queueState.currentIndex === queueState.tracks.length - 1) {
// we've reached last track of queue, trigger a reload
// from radio if any
dispatch('radios/populateQueue', null, { root: true })
}
dispatch('queue/next', null, { root: true })
if (queueState.ended) {
// Reset playback
commit('playing', false)
dispatch('updateProgress', 0)
}
},
trackErrored ({ commit, dispatch, state }) {
commit('errored', true)
commit('incrementErrorCount')
if (state.errorCount < state.maxConsecutiveErrors) {
setTimeout(() => {
if (state.playing) {
dispatch('queue/next', null, { root: true })
}
}, 3000)
}
},
updateProgress ({ commit }, time: number) {
commit('currentTime', time)
},
mute ({ commit, state }) {
commit('tempVolume', state.volume)
commit('volume', 0)
},
unmute ({ commit, state }) {
commit('volume', state.tempVolume)
}
}
}
export default store

Wyświetl plik

@ -1,183 +0,0 @@
import type { Module } from 'vuex'
import type { RootState } from '~/store/index'
import type { Track } from '~/types'
import { shuffle } from 'lodash-es'
import useLogger from '~/composables/useLogger'
export interface State {
tracks: Track[]
currentIndex: number
ended: boolean
}
const logger = useLogger()
const store: Module<State, RootState> = {
namespaced: true,
state: {
tracks: [],
currentIndex: -1,
ended: true
},
mutations: {
reset (state) {
state.tracks.length = 0
state.currentIndex = -1
state.ended = true
},
currentIndex (state, value) {
state.currentIndex = value
},
ended (state, value) {
state.ended = value
},
splice (state, { start, size }) {
state.tracks.splice(start, size)
},
tracks (state, value) {
state.tracks = value
},
reorder (state, { oldIndex, newIndex }) {
// called when the user uses drag / drop to reorder
// tracks in queue
const [track] = state.tracks.splice(oldIndex, 1)
state.tracks.splice(newIndex, 0, track)
if (oldIndex === state.currentIndex) {
state.currentIndex = newIndex
return
}
if (oldIndex < state.currentIndex && newIndex >= state.currentIndex) {
// item before was moved after
state.currentIndex -= 1
}
if (oldIndex > state.currentIndex && newIndex <= state.currentIndex) {
// item after was moved before
state.currentIndex += 1
}
}
},
getters: {
currentTrack: state => {
return state.tracks[state.currentIndex]
},
hasNext: state => {
return state.currentIndex < state.tracks.length - 1
},
hasPrevious: state => {
return state.currentIndex > 0 && state.tracks.length > 1
},
isEmpty: state => state.tracks.length === 0
},
actions: {
append ({ dispatch, state }, { track, index = state.tracks.length }) {
return dispatch('appendMany', { tracks: [track], index })
},
appendMany ({ state, dispatch }, { tracks, index = state.tracks.length }) {
logger.info(
'Enqueueing tracks',
tracks.map((track: Track) => [track.artist?.name, track.title].join(' - '))
)
const shouldPlay = state.tracks.length === 0
if (shouldPlay) {
index = 0
state.currentIndex = 0
}
if (index >= state.tracks.length) {
// we simply push to the end
state.tracks.push(...tracks)
} else {
// we insert the track at given position
state.tracks.splice(index, 0, ...tracks)
}
if (shouldPlay) {
return dispatch('next')
}
},
cleanTrack ({ state, dispatch, commit }, index) {
// are we removing current playin track
const current = index === state.currentIndex
if (current) {
dispatch('player/stop', null, { root: true })
}
commit('splice', { start: index, size: 1 })
if (index < state.currentIndex) {
commit('currentIndex', state.currentIndex - 1)
} else if (index > 0 && index === state.tracks.length && current) {
// kind of a edge case: if you delete the last track of the queue
// while it's playing we set current index to the previous one to
// avoid the queue tab from being stuck because the player
// disappeared cf #1092
commit('currentIndex', state.tracks.length - 1)
} else if (current) {
// we play next track, which now have the same index
commit('currentIndex', index)
}
if (state.currentIndex + 1 === state.tracks.length) {
dispatch('radios/populateQueue', null, { root: true })
}
},
previous ({ state, dispatch, rootState }) {
if (state.currentIndex > 0 && rootState.player.currentTime < 3) {
dispatch('currentIndex', state.currentIndex - 1)
} else {
dispatch('currentIndex', state.currentIndex)
}
},
next ({ state, dispatch, commit, rootState }) {
if (rootState.player.looping === 2 && state.currentIndex >= state.tracks.length - 1) {
logger.info('Going back to the beginning of the queue')
return dispatch('currentIndex', 0)
} else {
if (state.currentIndex < state.tracks.length - 1) {
logger.debug('Playing next track')
return dispatch('currentIndex', state.currentIndex + 1)
} else {
commit('ended', true)
}
}
},
last ({ state, dispatch }) {
return dispatch('currentIndex', state.tracks.length - 1)
},
currentIndex ({ commit, state, rootState, dispatch }, index) {
commit('ended', false)
commit('player/currentTime', 0, { root: true })
commit('currentIndex', index)
if (state.tracks.length - index <= 2 && rootState.radios.running) {
return dispatch('radios/populateQueue', null, { root: true })
}
},
clean ({ dispatch, commit, state }) {
dispatch('radios/stop', null, { root: true })
dispatch('player/stop', null, { root: true })
state.tracks.length = 0
dispatch('currentIndex', -1)
// so we replay automatically on next track append
commit('ended', true)
},
async shuffle ({ dispatch, state }) {
const shuffled = shuffle(state.tracks)
state.tracks.length = 0
await dispatch('appendMany', { tracks: shuffled })
await dispatch('currentIndex', 0)
}
}
}
export default store