feat(ui): persist user settings and audio position across sessions
- Replace double inline player controls with compact 'now playing' indicator when mini-bar is active - Add user_settings PocketBase collection (auto_next, voice, speed) and audio_time field on progress - Add getSettings/saveSettings/setAudioTime/getAudioTime server functions - Add GET/PUT /api/settings and GET/PATCH /api/progress/audio-time API routes - Load settings server-side in layout and apply to audioStore on mount - Debounced 800ms effect persists settings changes to DB - Save audio currentTime on pause/end; restore position when replaying a chapter
This commit is contained in:
@@ -181,9 +181,24 @@ create_collection "app_users" '{
|
|||||||
]
|
]
|
||||||
}'
|
}'
|
||||||
|
|
||||||
|
create_collection "user_settings" '{
|
||||||
|
"name": "user_settings",
|
||||||
|
"type": "base",
|
||||||
|
"fields": [
|
||||||
|
{"name": "session_id", "type": "text", "required": true},
|
||||||
|
{"name": "user_id", "type": "text"},
|
||||||
|
{"name": "auto_next", "type": "bool"},
|
||||||
|
{"name": "voice", "type": "text"},
|
||||||
|
{"name": "speed", "type": "number"},
|
||||||
|
{"name": "updated", "type": "date"}
|
||||||
|
]
|
||||||
|
}'
|
||||||
|
|
||||||
# ─── 5. Schema migrations (idempotent field additions) ───────────────────────
|
# ─── 5. Schema migrations (idempotent field additions) ───────────────────────
|
||||||
# Ensures fields added after initial deploy are present in existing instances.
|
# Ensures fields added after initial deploy are present in existing instances.
|
||||||
|
|
||||||
ensure_field "progress" "user_id" "text"
|
ensure_field "progress" "user_id" "text"
|
||||||
|
ensure_field "progress" "audio_time" "number"
|
||||||
|
ensure_field "user_settings" "user_id" "text"
|
||||||
|
|
||||||
log "all collections ready"
|
log "all collections ready"
|
||||||
|
|||||||
@@ -138,6 +138,8 @@
|
|||||||
if (url) {
|
if (url) {
|
||||||
audioStore.audioUrl = url;
|
audioStore.audioUrl = url;
|
||||||
audioStore.status = 'ready';
|
audioStore.status = 'ready';
|
||||||
|
// Restore last saved position after the audio element loads
|
||||||
|
restoreSavedAudioTime();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -158,6 +160,7 @@
|
|||||||
if (!url2) throw new Error('Audio generated but presign returned 404');
|
if (!url2) throw new Error('Audio generated but presign returned 404');
|
||||||
audioStore.audioUrl = url2;
|
audioStore.audioUrl = url2;
|
||||||
audioStore.status = 'ready';
|
audioStore.status = 'ready';
|
||||||
|
// Don't restore time for freshly generated audio — position is 0
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
stopProgress();
|
stopProgress();
|
||||||
audioStore.progress = 0;
|
audioStore.progress = 0;
|
||||||
@@ -166,6 +169,27 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch the saved audio time for this chapter and seek to it after a short
|
||||||
|
* delay (to allow the audio element to load the source).
|
||||||
|
*/
|
||||||
|
async function restoreSavedAudioTime() {
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams({ slug, chapter: String(chapter) });
|
||||||
|
const res = await fetch(`/api/progress/audio-time?${params}`);
|
||||||
|
if (!res.ok) return;
|
||||||
|
const data = (await res.json()) as { audioTime: number | null };
|
||||||
|
if (data.audioTime && data.audioTime > 5) {
|
||||||
|
// Small delay to let the <audio> element fully load the src before seeking
|
||||||
|
setTimeout(() => {
|
||||||
|
audioStore.seekRequest = data.audioTime as number;
|
||||||
|
}, 300);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Non-critical — silently ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function handlePlay() {
|
async function handlePlay() {
|
||||||
const isCurrent = audioStore.isCurrentChapter(slug, chapter);
|
const isCurrent = audioStore.isCurrentChapter(slug, chapter);
|
||||||
|
|
||||||
@@ -237,62 +261,44 @@
|
|||||||
<p class="text-xs text-zinc-500 tabular-nums">{Math.round(audioStore.progress)}%</p>
|
<p class="text-xs text-zinc-500 tabular-nums">{Math.round(audioStore.progress)}%</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{:else if audioStore.status === 'ready'}
|
{:else if audioStore.status === 'ready'}
|
||||||
<!-- Inline full-size controls (larger than the mini-bar) -->
|
<!-- Mini-bar is the canonical control surface — show a compact indicator here -->
|
||||||
<div class="flex flex-col gap-2">
|
<div class="flex items-center justify-between gap-3">
|
||||||
<!-- Seek bar -->
|
<div class="flex items-center gap-2 text-xs text-zinc-400">
|
||||||
<input
|
{#if audioStore.isPlaying}
|
||||||
type="range"
|
<svg class="w-3.5 h-3.5 text-amber-400 flex-shrink-0" fill="currentColor" viewBox="0 0 24 24">
|
||||||
min="0"
|
<path d="M6 4h4v16H6V4zm8 0h4v16h-4V4z"/>
|
||||||
max={audioStore.duration || 0}
|
</svg>
|
||||||
value={audioStore.currentTime}
|
<span>Playing — controls below</span>
|
||||||
oninput={(e) => {
|
{:else}
|
||||||
audioStore.seekRequest = parseFloat((e.target as HTMLInputElement).value);
|
<svg class="w-3.5 h-3.5 flex-shrink-0 ml-0.5" fill="currentColor" viewBox="0 0 24 24">
|
||||||
}}
|
<path d="M8 5v14l11-7z"/>
|
||||||
class="w-full accent-amber-400 h-1.5 rounded cursor-pointer"
|
</svg>
|
||||||
/>
|
<span>Paused — controls below</span>
|
||||||
|
{/if}
|
||||||
<div class="flex items-center gap-3">
|
<span class="tabular-nums text-zinc-500">
|
||||||
<!-- Play/Pause -->
|
{formatTime(audioStore.currentTime)} / {formatTime(audioStore.duration)}
|
||||||
<button
|
</span>
|
||||||
onclick={handlePlay}
|
|
||||||
class="w-9 h-9 rounded-full bg-amber-400 text-zinc-900 flex items-center justify-center hover:bg-amber-300 transition-colors flex-shrink-0"
|
|
||||||
aria-label={audioStore.isPlaying ? 'Pause' : 'Play'}
|
|
||||||
>
|
|
||||||
{#if audioStore.isPlaying}
|
|
||||||
<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
|
|
||||||
<path d="M6 4h4v16H6V4zm8 0h4v16h-4V4z"/>
|
|
||||||
</svg>
|
|
||||||
{:else}
|
|
||||||
<svg class="w-4 h-4 ml-0.5" fill="currentColor" viewBox="0 0 24 24">
|
|
||||||
<path d="M8 5v14l11-7z"/>
|
|
||||||
</svg>
|
|
||||||
{/if}
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<span class="text-xs text-zinc-400 tabular-nums flex-1">
|
|
||||||
{formatTime(audioStore.currentTime)} / {formatTime(audioStore.duration)}
|
|
||||||
</span>
|
|
||||||
|
|
||||||
<!-- Auto-next toggle (inline, only visible when there is a next chapter) -->
|
|
||||||
{#if nextChapter !== null && nextChapter !== undefined}
|
|
||||||
<button
|
|
||||||
onclick={() => (audioStore.autoNext = !audioStore.autoNext)}
|
|
||||||
class="flex items-center gap-1.5 px-2 py-1 rounded text-xs font-medium transition-colors flex-shrink-0 {audioStore.autoNext
|
|
||||||
? 'text-amber-400 bg-amber-400/15 hover:bg-amber-400/25'
|
|
||||||
: 'text-zinc-500 bg-zinc-700 hover:bg-zinc-600 hover:text-zinc-200'}"
|
|
||||||
title={audioStore.autoNext ? 'Auto-next on — will play Ch.{nextChapter} automatically' : 'Auto-next off'}
|
|
||||||
aria-pressed={audioStore.autoNext}
|
|
||||||
>
|
|
||||||
<svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 24 24">
|
|
||||||
<path d="M6 18l8.5-6L6 6v12zm8.5-6L23 6v12l-8.5-6z"/>
|
|
||||||
</svg>
|
|
||||||
Auto
|
|
||||||
</button>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
|
||||||
|
<!-- Auto-next toggle (keep here as useful context) -->
|
||||||
|
{#if nextChapter !== null && nextChapter !== undefined}
|
||||||
|
<button
|
||||||
|
onclick={() => (audioStore.autoNext = !audioStore.autoNext)}
|
||||||
|
class="flex items-center gap-1.5 px-2 py-1 rounded text-xs font-medium transition-colors flex-shrink-0 {audioStore.autoNext
|
||||||
|
? 'text-amber-400 bg-amber-400/15 hover:bg-amber-400/25'
|
||||||
|
: 'text-zinc-500 bg-zinc-700 hover:bg-zinc-600 hover:text-zinc-200'}"
|
||||||
|
title={audioStore.autoNext ? `Auto-next on — will play Ch.${nextChapter} automatically` : 'Auto-next off'}
|
||||||
|
aria-pressed={audioStore.autoNext}
|
||||||
|
>
|
||||||
|
<svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path d="M6 18l8.5-6L6 6v12zm8.5-6L23 6v12l-8.5-6z"/>
|
||||||
|
</svg>
|
||||||
|
Auto
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
{:else if audioStore.active}
|
{:else if audioStore.active}
|
||||||
<!-- ── A different chapter is currently playing ── -->
|
<!-- ── A different chapter is currently playing ── -->
|
||||||
|
|||||||
@@ -42,9 +42,20 @@ export interface Progress {
|
|||||||
user_id?: string;
|
user_id?: string;
|
||||||
slug: string;
|
slug: string;
|
||||||
chapter: number;
|
chapter: number;
|
||||||
|
audio_time?: number;
|
||||||
updated: string;
|
updated: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface UserSettings {
|
||||||
|
id?: string;
|
||||||
|
session_id: string;
|
||||||
|
user_id?: string;
|
||||||
|
auto_next: boolean;
|
||||||
|
voice: string;
|
||||||
|
speed: number;
|
||||||
|
updated?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface User {
|
export interface User {
|
||||||
id: string;
|
id: string;
|
||||||
username: string;
|
username: string;
|
||||||
@@ -395,3 +406,102 @@ export async function loginUser(username: string, password: string): Promise<Use
|
|||||||
log.info('pocketbase', 'loginUser: success', { username, role: user.role });
|
log.info('pocketbase', 'loginUser: success', { username, role: user.role });
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── User settings ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function settingsFilter(sessionId: string, userId?: string): string {
|
||||||
|
if (userId) return `user_id="${userId}"`;
|
||||||
|
return `session_id="${sessionId}"`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getSettings(
|
||||||
|
sessionId: string,
|
||||||
|
userId?: string
|
||||||
|
): Promise<UserSettings | null> {
|
||||||
|
return listOne<UserSettings>('user_settings', settingsFilter(sessionId, userId));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveSettings(
|
||||||
|
sessionId: string,
|
||||||
|
settings: { autoNext: boolean; voice: string; speed: number },
|
||||||
|
userId?: string
|
||||||
|
): Promise<void> {
|
||||||
|
const existing = await listOne<UserSettings & { id: string }>(
|
||||||
|
'user_settings',
|
||||||
|
settingsFilter(sessionId, userId)
|
||||||
|
);
|
||||||
|
|
||||||
|
const payload: Partial<UserSettings> = {
|
||||||
|
session_id: sessionId,
|
||||||
|
auto_next: settings.autoNext,
|
||||||
|
voice: settings.voice,
|
||||||
|
speed: settings.speed,
|
||||||
|
updated: new Date().toISOString()
|
||||||
|
};
|
||||||
|
if (userId) payload.user_id = userId;
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
const res = await pbPatch(`/api/collections/user_settings/records/${existing.id}`, payload);
|
||||||
|
if (!res.ok) {
|
||||||
|
const body = await res.text().catch(() => '');
|
||||||
|
log.error('pocketbase', 'saveSettings PATCH failed', { status: res.status, body });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const res = await pbPost('/api/collections/user_settings/records', payload);
|
||||||
|
if (!res.ok) {
|
||||||
|
const body = await res.text().catch(() => '');
|
||||||
|
log.error('pocketbase', 'saveSettings POST failed', { status: res.status, body });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Audio time ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export async function setAudioTime(
|
||||||
|
sessionId: string,
|
||||||
|
slug: string,
|
||||||
|
chapter: number,
|
||||||
|
audioTime: number,
|
||||||
|
userId?: string
|
||||||
|
): Promise<void> {
|
||||||
|
const existing = await listOne<Progress & { id: string }>(
|
||||||
|
'progress',
|
||||||
|
progressFilter(sessionId, slug, userId)
|
||||||
|
);
|
||||||
|
if (!existing) {
|
||||||
|
// No progress record yet — create one with audio_time
|
||||||
|
const payload: Partial<Progress> = {
|
||||||
|
session_id: sessionId,
|
||||||
|
slug,
|
||||||
|
chapter,
|
||||||
|
audio_time: audioTime,
|
||||||
|
updated: new Date().toISOString()
|
||||||
|
};
|
||||||
|
if (userId) payload.user_id = userId;
|
||||||
|
const res = await pbPost('/api/collections/progress/records', payload);
|
||||||
|
if (!res.ok) {
|
||||||
|
const body = await res.text().catch(() => '');
|
||||||
|
log.error('pocketbase', 'setAudioTime POST failed', { slug, chapter, status: res.status, body });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const res = await pbPatch(`/api/collections/progress/records/${existing.id}`, {
|
||||||
|
audio_time: audioTime,
|
||||||
|
updated: new Date().toISOString()
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const body = await res.text().catch(() => '');
|
||||||
|
log.error('pocketbase', 'setAudioTime PATCH failed', { slug, chapter, status: res.status, body });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAudioTime(
|
||||||
|
sessionId: string,
|
||||||
|
slug: string,
|
||||||
|
chapter: number,
|
||||||
|
userId?: string
|
||||||
|
): Promise<number | null> {
|
||||||
|
const row = await listOne<Progress>('progress', progressFilter(sessionId, slug, userId));
|
||||||
|
if (!row || !row.audio_time) return null;
|
||||||
|
return row.audio_time;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { redirect } from '@sveltejs/kit';
|
import { redirect } from '@sveltejs/kit';
|
||||||
import type { LayoutServerLoad } from './$types';
|
import type { LayoutServerLoad } from './$types';
|
||||||
|
import { getSettings } from '$lib/server/pocketbase';
|
||||||
|
import { log } from '$lib/server/logger';
|
||||||
|
|
||||||
// Routes that are accessible without being logged in
|
// Routes that are accessible without being logged in
|
||||||
const PUBLIC_ROUTES = new Set(['/login']);
|
const PUBLIC_ROUTES = new Set(['/login']);
|
||||||
@@ -9,7 +11,22 @@ export const load: LayoutServerLoad = async ({ locals, url }) => {
|
|||||||
redirect(302, `/login`);
|
redirect(302, `/login`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let settings = { autoNext: false, voice: 'af_bella', speed: 1.0 };
|
||||||
|
try {
|
||||||
|
const row = await getSettings(locals.sessionId, locals.user?.id);
|
||||||
|
if (row) {
|
||||||
|
settings = {
|
||||||
|
autoNext: row.auto_next ?? false,
|
||||||
|
voice: row.voice ?? 'af_bella',
|
||||||
|
speed: row.speed ?? 1.0
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
log.warn('layout', 'failed to load settings', { err: String(e) });
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
user: locals.user
|
user: locals.user,
|
||||||
|
settings
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -12,6 +12,38 @@
|
|||||||
// AudioPlayer components in chapter pages control it via audioStore.
|
// AudioPlayer components in chapter pages control it via audioStore.
|
||||||
let audioEl = $state<HTMLAudioElement | null>(null);
|
let audioEl = $state<HTMLAudioElement | null>(null);
|
||||||
|
|
||||||
|
// Apply persisted settings once on mount (server-loaded data).
|
||||||
|
let settingsApplied = false;
|
||||||
|
$effect(() => {
|
||||||
|
if (!settingsApplied && data.settings) {
|
||||||
|
settingsApplied = true;
|
||||||
|
audioStore.autoNext = data.settings.autoNext;
|
||||||
|
audioStore.voice = data.settings.voice;
|
||||||
|
audioStore.speed = data.settings.speed;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Persist settings changes (debounced 800ms) ──────────────────────────
|
||||||
|
let settingsSaveTimer = 0;
|
||||||
|
$effect(() => {
|
||||||
|
// Subscribe to the three settings fields
|
||||||
|
const autoNext = audioStore.autoNext;
|
||||||
|
const voice = audioStore.voice;
|
||||||
|
const speed = audioStore.speed;
|
||||||
|
|
||||||
|
// Skip saving until settings have been applied from the server
|
||||||
|
if (!settingsApplied) return;
|
||||||
|
|
||||||
|
clearTimeout(settingsSaveTimer);
|
||||||
|
settingsSaveTimer = setTimeout(() => {
|
||||||
|
fetch('/api/settings', {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ autoNext, voice, speed })
|
||||||
|
}).catch(() => {});
|
||||||
|
}, 800) as unknown as number;
|
||||||
|
});
|
||||||
|
|
||||||
// Keep the audio element's playback rate in sync with the store speed.
|
// Keep the audio element's playback rate in sync with the store speed.
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (audioEl) audioEl.playbackRate = audioStore.speed;
|
if (audioEl) audioEl.playbackRate = audioStore.speed;
|
||||||
@@ -55,6 +87,23 @@
|
|||||||
audioStore.seekRequest = null;
|
audioStore.seekRequest = null;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ── Save audio time on pause/end (debounced 2s) ─────────────────────────
|
||||||
|
let audioTimeSaveTimer = 0;
|
||||||
|
function saveAudioTime() {
|
||||||
|
if (!audioStore.slug || !audioStore.chapter) return;
|
||||||
|
const slug = audioStore.slug;
|
||||||
|
const chapter = audioStore.chapter;
|
||||||
|
const currentTime = audioStore.currentTime;
|
||||||
|
clearTimeout(audioTimeSaveTimer);
|
||||||
|
audioTimeSaveTimer = setTimeout(() => {
|
||||||
|
fetch('/api/progress/audio-time', {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ slug, chapter, audioTime: currentTime })
|
||||||
|
}).catch(() => {});
|
||||||
|
}, 2000) as unknown as number;
|
||||||
|
}
|
||||||
|
|
||||||
function formatTime(s: number): string {
|
function formatTime(s: number): string {
|
||||||
if (!isFinite(s) || s < 0) return '0:00';
|
if (!isFinite(s) || s < 0) return '0:00';
|
||||||
const m = Math.floor(s / 60);
|
const m = Math.floor(s / 60);
|
||||||
@@ -122,9 +171,13 @@
|
|||||||
bind:currentTime={audioStore.currentTime}
|
bind:currentTime={audioStore.currentTime}
|
||||||
bind:duration={audioStore.duration}
|
bind:duration={audioStore.duration}
|
||||||
onplay={() => (audioStore.isPlaying = true)}
|
onplay={() => (audioStore.isPlaying = true)}
|
||||||
onpause={() => (audioStore.isPlaying = false)}
|
onpause={() => {
|
||||||
|
audioStore.isPlaying = false;
|
||||||
|
saveAudioTime();
|
||||||
|
}}
|
||||||
onended={() => {
|
onended={() => {
|
||||||
audioStore.isPlaying = false;
|
audioStore.isPlaying = false;
|
||||||
|
saveAudioTime();
|
||||||
if (audioStore.autoNext && audioStore.nextChapter !== null && audioStore.slug) {
|
if (audioStore.autoNext && audioStore.nextChapter !== null && audioStore.slug) {
|
||||||
audioStore.autoStartPending = true;
|
audioStore.autoStartPending = true;
|
||||||
goto(`/books/${audioStore.slug}/chapters/${audioStore.nextChapter}`);
|
goto(`/books/${audioStore.slug}/chapters/${audioStore.nextChapter}`);
|
||||||
|
|||||||
56
ui/src/routes/api/progress/audio-time/+server.ts
Normal file
56
ui/src/routes/api/progress/audio-time/+server.ts
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
import { json, error } from '@sveltejs/kit';
|
||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
import { setAudioTime, getAudioTime } from '$lib/server/pocketbase';
|
||||||
|
import { log } from '$lib/server/logger';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /api/progress/audio-time?slug=&chapter=
|
||||||
|
* Returns the last saved audio position for a chapter, or null.
|
||||||
|
*/
|
||||||
|
export const GET: RequestHandler = async ({ url, locals }) => {
|
||||||
|
const slug = url.searchParams.get('slug');
|
||||||
|
const chapterParam = url.searchParams.get('chapter');
|
||||||
|
|
||||||
|
if (!slug || !chapterParam) {
|
||||||
|
error(400, 'Missing slug or chapter query params');
|
||||||
|
}
|
||||||
|
|
||||||
|
const chapter = parseInt(chapterParam, 10);
|
||||||
|
if (isNaN(chapter)) {
|
||||||
|
error(400, 'chapter must be a number');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const audioTime = await getAudioTime(locals.sessionId, slug, chapter, locals.user?.id);
|
||||||
|
return json({ audioTime });
|
||||||
|
} catch (e) {
|
||||||
|
log.error('audio-time', 'GET failed', { slug, chapter, err: String(e) });
|
||||||
|
error(500, 'Failed to load audio time');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PATCH /api/progress/audio-time
|
||||||
|
* Body: { slug: string, chapter: number, audioTime: number }
|
||||||
|
* Saves the current audio playback position.
|
||||||
|
*/
|
||||||
|
export const PATCH: RequestHandler = async ({ request, locals }) => {
|
||||||
|
const body = await request.json().catch(() => null);
|
||||||
|
|
||||||
|
if (
|
||||||
|
!body ||
|
||||||
|
typeof body.slug !== 'string' ||
|
||||||
|
typeof body.chapter !== 'number' ||
|
||||||
|
typeof body.audioTime !== 'number'
|
||||||
|
) {
|
||||||
|
error(400, 'Invalid body — expected { slug, chapter, audioTime }');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await setAudioTime(locals.sessionId, body.slug, body.chapter, body.audioTime, locals.user?.id);
|
||||||
|
} catch (e) {
|
||||||
|
log.error('audio-time', 'PATCH failed', { slug: body.slug, chapter: body.chapter, err: String(e) });
|
||||||
|
error(500, 'Failed to save audio time');
|
||||||
|
}
|
||||||
|
return json({ ok: true });
|
||||||
|
};
|
||||||
49
ui/src/routes/api/settings/+server.ts
Normal file
49
ui/src/routes/api/settings/+server.ts
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import { json, error } from '@sveltejs/kit';
|
||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
import { getSettings, saveSettings } from '$lib/server/pocketbase';
|
||||||
|
import { log } from '$lib/server/logger';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /api/settings
|
||||||
|
* Returns the current user's settings (auto_next, voice, speed).
|
||||||
|
* Returns defaults if no settings record exists yet.
|
||||||
|
*/
|
||||||
|
export const GET: RequestHandler = async ({ locals }) => {
|
||||||
|
try {
|
||||||
|
const settings = await getSettings(locals.sessionId, locals.user?.id);
|
||||||
|
return json({
|
||||||
|
autoNext: settings?.auto_next ?? false,
|
||||||
|
voice: settings?.voice ?? 'af_bella',
|
||||||
|
speed: settings?.speed ?? 1.0
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
log.error('settings', 'GET failed', { err: String(e) });
|
||||||
|
error(500, 'Failed to load settings');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PUT /api/settings
|
||||||
|
* Body: { autoNext: boolean, voice: string, speed: number }
|
||||||
|
* Saves user preferences.
|
||||||
|
*/
|
||||||
|
export const PUT: RequestHandler = async ({ request, locals }) => {
|
||||||
|
const body = await request.json().catch(() => null);
|
||||||
|
|
||||||
|
if (
|
||||||
|
!body ||
|
||||||
|
typeof body.autoNext !== 'boolean' ||
|
||||||
|
typeof body.voice !== 'string' ||
|
||||||
|
typeof body.speed !== 'number'
|
||||||
|
) {
|
||||||
|
error(400, 'Invalid body — expected { autoNext, voice, speed }');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await saveSettings(locals.sessionId, body, locals.user?.id);
|
||||||
|
} catch (e) {
|
||||||
|
log.error('settings', 'PUT failed', { err: String(e) });
|
||||||
|
error(500, 'Failed to save settings');
|
||||||
|
}
|
||||||
|
return json({ ok: true });
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user