45 lines
1.2 KiB
JavaScript
45 lines
1.2 KiB
JavaScript
const STORAGE_KEY = 'wedding_music_pick_v1'
|
|
const DAY_MS = 24 * 60 * 60 * 1000
|
|
|
|
function readCache() {
|
|
try {
|
|
const raw = localStorage.getItem(STORAGE_KEY)
|
|
if (!raw) return null
|
|
const parsed = JSON.parse(raw)
|
|
if (!parsed?.url || !parsed?.ts) return null
|
|
return parsed
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
export function rememberMusicPick(url) {
|
|
if (!url) return
|
|
try {
|
|
localStorage.setItem(STORAGE_KEY, JSON.stringify({ url, ts: Date.now() }))
|
|
} catch { /* ignore quota */ }
|
|
}
|
|
|
|
/**
|
|
* Resolve which track to play.
|
|
* When random is enabled, reuse local cache within 24h if still in list; otherwise pick randomly.
|
|
*/
|
|
export function pickMusicUrl(musicList, activeMusicUrl, musicRandomEnabled) {
|
|
const list = Array.isArray(musicList) ? musicList.filter((t) => t && t.url) : []
|
|
if (!list.length) return ''
|
|
|
|
if (!musicRandomEnabled) {
|
|
if (activeMusicUrl && list.some((t) => t.url === activeMusicUrl)) return activeMusicUrl
|
|
return list[0].url
|
|
}
|
|
|
|
const cache = readCache()
|
|
if (cache && Date.now() - cache.ts < DAY_MS && list.some((t) => t.url === cache.url)) {
|
|
return cache.url
|
|
}
|
|
|
|
const picked = list[Math.floor(Math.random() * list.length)].url
|
|
rememberMusicPick(picked)
|
|
return picked
|
|
}
|