import type { PodcastDataInterface, PodcastMetricsInterface, SubscriptionInterface, } from '../utils/types' import { getCookie, setCookie } from '../utils/cookies' import axios from '@nextcloud/axios' import { defineStore } from 'pinia' import { generateUrl } from '@nextcloud/router' export const useSubscriptions = defineStore('subscriptions', { state: () => ({ subs: [] as SubscriptionInterface[], }), getters: { getSubByUrl: (state) => (url: string) => state.subs.find((sub) => sub.metrics.url === url), }, actions: { async fetch() { let favorites: string[] = [] try { favorites = JSON.parse(getCookie('repod.favorites') || '[]') || [] } catch {} const metrics = await axios.get( generateUrl('/apps/gpoddersync/personal_settings/metrics'), ) this.subs = [...metrics.data.subscriptions] .sort((a, b) => b.listenedSeconds - a.listenedSeconds) .map((sub) => ({ metrics: sub, isFavorite: favorites.includes(sub.url), data: this.subs.find((s) => s.metrics.url === sub.url)?.data, })) }, addFavoriteData(data: PodcastDataInterface) { this.subs = this.subs.map((sub) => sub.metrics.url === data.link ? { ...sub, data } : sub, ) }, setFavorite(link: string, isFavorite: boolean) { this.subs.map((sub) => sub.metrics.url === link ? { ...sub, isFavorite } : sub, ) setCookie( 'repod.favorites', JSON.stringify( this.subs .filter((sub) => sub.isFavorite) .map((sub) => sub.metrics.url), ), 365, ) }, }, })