import axios from '@nextcloud/axios' import { formatEpisodeTimestamp } from '../utils/time.js' import { generateUrl } from '@nextcloud/router' import router from '../router.js' import store from './main.js' const audio = new Audio() audio.ondurationchange = () => store.commit('player/duration', audio.duration) audio.onended = () => store.dispatch('player/stop') audio.onloadeddata = () => store.commit('player/loaded', true) audio.onplay = () => store.commit('player/paused', false) audio.onpause = () => store.commit('player/paused', true) audio.onseeked = () => store.commit('player/currentTime', audio.currentTime) audio.ontimeupdate = () => store.commit('player/currentTime', audio.currentTime) audio.onvolumechange = () => store.commit('player/volume', audio.volume) export const player = { namespaced: true, state: { action: null, currentTime: null, duration: null, episode: null, loaded: false, paused: null, podcastUrl: null, volume: null, }, mutations: { action: (state, action) => { state.action = action if (action && action.position) { audio.currentTime = action.position } }, currentTime: (state, currentTime) => { state.currentTime = currentTime }, duration: (state, duration) => { state.duration = duration }, episode: (state, episode) => { state.episode = episode if (episode) { state.podcastUrl = router.currentRoute.params.url audio.src = episode.episodeUrl audio.load() audio.play() } else { state.loaded = false state.podcastUrl = null audio.src = '' } }, loaded: (state, loaded) => { state.loaded = loaded }, paused: (state, paused) => { state.paused = paused }, volume: (state, volume) => { state.volume = volume }, }, actions: { load: async (context, episode) => { context.commit('episode', episode) const action = await axios.get(generateUrl('/apps/repod/episodes/action?url={url}', { url: episode.episodeUrl })) context.commit('action', action.data) }, pause: (context) => { audio.pause() axios.post(generateUrl('/apps/gpoddersync/episode_action/create'), [{ podcast: context.state.podcastUrl, episode: context.state.episode.episodeUrl, guid: context.state.episode.episodeGuid, action: 'play', timestamp: formatEpisodeTimestamp(new Date()), started: Math.round(context.state.action ? context.state.action.started : 0), position: Math.round(audio.currentTime), total: Math.round(audio.duration), }]) }, play: () => audio.play(), seek: (context, currentTime) => { audio.currentTime = currentTime }, stop: (context) => { context.dispatch('pause') context.commit('episode', null) context.commit('action', null) }, volume: (context, volume) => { audio.volume = volume }, }, }