import axios from '@nextcloud/axios' import { decodeUrl } from '../utils/url.js' import { defineStore } from 'pinia' import { formatEpisodeTimestamp } from '../utils/time.js' import { generateUrl } from '@nextcloud/router' import router from '../router.js' const audio = new Audio() export const usePlayer = defineStore('player', { state: () => ({ currentTime: null, duration: null, episode: null, loaded: false, paused: null, podcastUrl: null, volume: 1, rate: 1, started: 0, }), actions: { load: async (episode) => { this.episode = episode if (this.episode) { this.podcastUrl = decodeUrl(router.currentRoute.params.url) audio.src = this.episode.url audio.load() try { const action = await axios.get( generateUrl('/apps/repod/episodes/action?url={url}', { url: this.episode.url, }), ) this.episode.action = action } catch {} if ( this.episode.action && this.episode.action.position && this.episode.action.position < this.episode.action.total ) { audio.currentTime = this.episode.action.position this.started = audio.currentTime } audio.play() } else { this.loaded = false this.podcastUrl = null audio.src = '' } }, pause: () => { audio.pause() this.paused = true }, play: () => { audio.play() this.paused = false this.started = audio.currentTime }, seek: (currentTime) => { audio.currentTime = currentTime this.time() }, stop: () => { this.pause() this.episode = null }, time: () => { this.episode.action = { podcast: this.podcastUrl, episode: this.episode.url, guid: this.episode.guid, action: 'play', timestamp: formatEpisodeTimestamp(new Date()), started: Math.round(this.started), position: Math.round(audio.currentTime), total: Math.round(audio.duration), } axios.post(generateUrl('/apps/gpoddersync/episode_action/create'), [ this.episode.action, ]) }, setVolume: (volume) => { audio.volume = volume }, setRate: (rate) => { audio.playbackRate = rate }, }, }) const player = usePlayer() audio.ondurationchange = () => (player.duration = audio.duration) audio.onended = () => player.stop() audio.onloadeddata = () => (player.loaded = true) audio.onpause = () => player.pause() audio.onplay = () => player.play() audio.onratechange = () => (player.rate = audio.playbackRate) audio.onseeked = () => (player.currentTime = audio.currentTime) audio.ontimeupdate = () => (player.currentTime = audio.currentTime) audio.onvolumechange = () => (player.volume = audio.volume) setInterval(() => { if (player.paused === false) { player.time() } }, 40000)