Add library manager with tracks, albums and uploads sections
This commit is contained in:
@@ -36,7 +36,7 @@
|
||||
</PageHeader>
|
||||
|
||||
{#if items.length > 0}
|
||||
<div class="grid-cards">
|
||||
<div class="grid-cards-lg">
|
||||
{#each items as album, i (album.id)}
|
||||
<MediaCard
|
||||
href="/albums/{album.id}"
|
||||
|
||||
@@ -1,32 +1,165 @@
|
||||
import type { PageServerLoad, Actions } from './$types';
|
||||
import { fail } from '@sveltejs/kit';
|
||||
import { toDatedTrack, toPage } from '$lib/server/mappers';
|
||||
import { apiFor, failOnError, unwrapOrError } from '$lib/server/api';
|
||||
import { fail, isActionFailure, redirect } from '@sveltejs/kit';
|
||||
import type { Album } from '$lib/types';
|
||||
import { toAlbum, toLibraryTrack, toPage } from '$lib/server/mappers';
|
||||
import { apiFor, failOnError, unwrapOrError, type ApiClient } from '$lib/server/api';
|
||||
import { requireUser } from '$lib/server/guards';
|
||||
import { formString } from '$lib/server/forms/fields';
|
||||
import { formFile, formString } from '$lib/server/forms/fields';
|
||||
import { parseAlbumForm } from '$lib/server/forms/albumForm';
|
||||
import { uploadOptionalCover } from '$lib/server/upload';
|
||||
import { authedAction } from '$lib/server/actions/authedAction';
|
||||
import { LIBRARY_PAGE_SIZE } from '$lib/config';
|
||||
import { ALBUMS_PAGE_SIZE, ALBUM_TRACKS_PAGE_SIZE, LIBRARY_PAGE_SIZE } from '$lib/config';
|
||||
|
||||
const ALBUMS_SECTION_URL = '/library?section=albums';
|
||||
|
||||
async function trackIdsByAlbum(api: ApiClient, albums: Album[]): Promise<Record<string, string[]>> {
|
||||
const entries = await Promise.all(
|
||||
albums.map(async (album) => {
|
||||
const tracks = await api.GET('/albums/{id}/tracks', {
|
||||
params: {
|
||||
path: { id: album.id },
|
||||
query: { pageNumber: 1, pageSize: ALBUM_TRACKS_PAGE_SIZE }
|
||||
}
|
||||
});
|
||||
return [album.id, (tracks.data?.items ?? []).map((track) => track.id)] as const;
|
||||
})
|
||||
);
|
||||
return Object.fromEntries(entries);
|
||||
}
|
||||
|
||||
function albumTitleByTrackId(albums: Album[], trackIds: Record<string, string[]>) {
|
||||
return new Map(
|
||||
albums.flatMap((album) => (trackIds[album.id] ?? []).map((id) => [id, album.title] as const))
|
||||
);
|
||||
}
|
||||
|
||||
function formIds(form: FormData, key: string): string[] {
|
||||
return formString(form, key).split(',').filter(Boolean);
|
||||
}
|
||||
|
||||
export const load: PageServerLoad = async ({ locals, url, fetch }) => {
|
||||
const user = requireUser(locals, url);
|
||||
const api = apiFor({ fetch, locals });
|
||||
const result = await api.GET('/tracks/users/{userId}', {
|
||||
params: { path: { userId: user.sub }, query: { pageNumber: 1, pageSize: LIBRARY_PAGE_SIZE } }
|
||||
});
|
||||
const [tracksResult, albumsResult, genresResult] = await Promise.all([
|
||||
api.GET('/tracks/users/{userId}', {
|
||||
params: { path: { userId: user.sub }, query: { pageNumber: 1, pageSize: LIBRARY_PAGE_SIZE } }
|
||||
}),
|
||||
api.GET('/albums/users/{userId}', {
|
||||
params: { path: { userId: user.sub }, query: { pageNumber: 1, pageSize: ALBUMS_PAGE_SIZE } }
|
||||
}),
|
||||
api.GET('/genres/available')
|
||||
]);
|
||||
|
||||
const albums = toPage(unwrapOrError(albumsResult, 'No se pudieron cargar tus álbumes.'), toAlbum);
|
||||
const albumTrackIds = await trackIdsByAlbum(api, albums.items);
|
||||
const albumTitles = albumTitleByTrackId(albums.items, albumTrackIds);
|
||||
|
||||
return {
|
||||
tracks: toPage(unwrapOrError(result, 'No se pudo cargar tu biblioteca.'), toDatedTrack)
|
||||
tracks: toPage(unwrapOrError(tracksResult, 'No se pudo cargar tu biblioteca.'), (dto) =>
|
||||
toLibraryTrack(dto, albumTitles.get(dto.id) ?? null)
|
||||
),
|
||||
albums,
|
||||
albumTrackIds,
|
||||
genres: genresResult.data ?? []
|
||||
};
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
deleteTrack: authedAction(async ({ api, form }) => {
|
||||
const trackId = formString(form, 'trackId');
|
||||
if (!trackId) return fail(400, { message: 'Falta la canción.' });
|
||||
function tagged<T extends object>(
|
||||
action: string,
|
||||
handler: (event: Parameters<Parameters<typeof authedAction>[0]>[0]) => Promise<T>
|
||||
) {
|
||||
return authedAction(async (event) => {
|
||||
const result = await handler(event);
|
||||
return isActionFailure(result)
|
||||
? fail(result.status, { ...(result.data as Record<string, unknown> | undefined), action })
|
||||
: { ...result, action };
|
||||
});
|
||||
}
|
||||
|
||||
const result = await api.DELETE('/tracks/{id}', {
|
||||
params: { path: { id: trackId } }
|
||||
});
|
||||
return failOnError(result, 'No se pudo borrar la canción.') ?? { deleted: true };
|
||||
export const actions: Actions = {
|
||||
deleteTracks: tagged('deleteTracks', async ({ api, form }) => {
|
||||
const trackIds = formIds(form, 'trackIds');
|
||||
if (trackIds.length === 0) return fail(400, { message: 'Falta la canción.' });
|
||||
|
||||
const results = await Promise.all(
|
||||
trackIds.map((id) => api.DELETE('/tracks/{id}', { params: { path: { id } } }))
|
||||
);
|
||||
const failed = results.find((result) => result.error);
|
||||
return (
|
||||
(failed &&
|
||||
failOnError(
|
||||
failed,
|
||||
trackIds.length === 1
|
||||
? 'No se pudo borrar la canción.'
|
||||
: 'No se pudieron borrar todas las canciones.'
|
||||
)) ?? { deleted: true }
|
||||
);
|
||||
}),
|
||||
|
||||
saveAlbum: tagged('saveAlbum', async ({ api, form }) => {
|
||||
const parsed = parseAlbumForm(form);
|
||||
if ('failMessage' in parsed) return fail(400, { message: parsed.failMessage });
|
||||
|
||||
const existingId = formString(form, 'albumId');
|
||||
const cover = await uploadOptionalCover(api, '/albums/upload-picture', formFile(form, 'cover'));
|
||||
if ('failMessage' in cover)
|
||||
return fail(502, { message: cover.failMessage, detail: cover.detail });
|
||||
|
||||
let albumId = existingId;
|
||||
if (existingId) {
|
||||
const updated = await api.PUT('/albums/{id}', {
|
||||
params: { path: { id: existingId } },
|
||||
body: parsed.body
|
||||
});
|
||||
const failure = failOnError(updated, 'No se pudo actualizar el álbum.');
|
||||
if (failure) return failure;
|
||||
|
||||
if (cover.intentId) {
|
||||
const picture = await api.PUT('/albums/{id}/picture', {
|
||||
params: { path: { id: existingId } },
|
||||
body: { pictureIntentId: cover.intentId }
|
||||
});
|
||||
const pictureFailure = failOnError(picture, 'No se pudo actualizar la portada.');
|
||||
if (pictureFailure) return pictureFailure;
|
||||
}
|
||||
} else {
|
||||
if (!cover.intentId) return fail(400, { message: 'La portada es obligatoria.' });
|
||||
const created = await api.POST('/albums', {
|
||||
body: { ...parsed.body, pictureIntentId: cover.intentId }
|
||||
});
|
||||
if (created.error || !created.data)
|
||||
return fail(502, { message: 'No se pudo crear el álbum.' });
|
||||
albumId = created.data.id;
|
||||
}
|
||||
|
||||
const addIds = formIds(form, 'addTrackIds');
|
||||
if (addIds.length > 0) {
|
||||
const added = await api.POST('/albums/{id}/tracks', {
|
||||
params: { path: { id: albumId } },
|
||||
body: { trackIds: addIds }
|
||||
});
|
||||
const failure = failOnError(added, 'No se pudieron añadir las canciones.');
|
||||
if (failure) return failure;
|
||||
}
|
||||
|
||||
const removed = await Promise.all(
|
||||
formIds(form, 'removeTrackIds').map((trackId) =>
|
||||
api.DELETE('/albums/{id}/tracks/{trackId}', { params: { path: { id: albumId, trackId } } })
|
||||
)
|
||||
);
|
||||
const removeFailed = removed.find((result) => result.error);
|
||||
const failure =
|
||||
removeFailed && failOnError(removeFailed, 'No se pudieron quitar las canciones.');
|
||||
return failure ?? { saved: true };
|
||||
}),
|
||||
|
||||
deleteAlbum: tagged('deleteAlbum', async ({ api, form }) => {
|
||||
const albumId = formString(form, 'albumId');
|
||||
if (!albumId) return fail(400, { message: 'Falta el álbum.' });
|
||||
|
||||
const result = await api.DELETE('/albums/{id}', { params: { path: { id: albumId } } });
|
||||
const failure = failOnError(result, 'No se pudo eliminar el álbum.');
|
||||
if (failure) return failure;
|
||||
redirect(303, ALBUMS_SECTION_URL);
|
||||
})
|
||||
};
|
||||
|
||||
@@ -1,81 +1,82 @@
|
||||
<script lang="ts" module>
|
||||
const SECTIONS = [
|
||||
{ value: 'tracks', label: 'Canciones' },
|
||||
{ value: 'albums', label: 'Álbumes' },
|
||||
{ value: 'uploads', label: 'Subidas' }
|
||||
] as const;
|
||||
|
||||
type Section = (typeof SECTIONS)[number]['value'];
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import Upload from '@lucide/svelte/icons/upload';
|
||||
import X from '@lucide/svelte/icons/x';
|
||||
import Music from '@lucide/svelte/icons/music';
|
||||
import { player } from '$lib/player/player.svelte';
|
||||
import { page } from '$app/state';
|
||||
import { plural } from '$lib/utils/format';
|
||||
import Page from '$lib/components/ui/layout/Page.svelte';
|
||||
import PageHeader from '$lib/components/ui/layout/PageHeader.svelte';
|
||||
import EmptyState from '$lib/components/ui/primitives/EmptyState.svelte';
|
||||
import Button from '$lib/components/ui/primitives/Button.svelte';
|
||||
import ConfirmDialog from '$lib/components/ui/overlay/ConfirmDialog.svelte';
|
||||
import TrackList from '$lib/components/music/TrackList.svelte';
|
||||
import LibraryTracksSection from '$lib/components/music/library/LibraryTracksSection.svelte';
|
||||
import LibraryAlbumsSection from '$lib/components/music/library/LibraryAlbumsSection.svelte';
|
||||
import LibraryUploadsSection from '$lib/components/music/library/LibraryUploadsSection.svelte';
|
||||
|
||||
let { data } = $props();
|
||||
let { data, form } = $props();
|
||||
|
||||
const items = $derived(data.tracks.items);
|
||||
const total = $derived(data.tracks.totalItemCount);
|
||||
|
||||
let deleting = $state<(typeof items)[number] | null>(null);
|
||||
let section = $state<Section>(
|
||||
SECTIONS.find((option) => option.value === page.url.searchParams.get('section'))?.value ??
|
||||
'tracks'
|
||||
);
|
||||
let resetKey = $state(0);
|
||||
|
||||
function togglePlay(index: number) {
|
||||
player.playOrToggle(items, index);
|
||||
function selectSection(value: Section) {
|
||||
if (value === section) resetKey += 1;
|
||||
section = value;
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Tus canciones subidas</title>
|
||||
<title>Gestionar música</title>
|
||||
<meta name="description" content="Todas tus canciones subidas a Musify." />
|
||||
</svelte:head>
|
||||
|
||||
<Page>
|
||||
<PageHeader
|
||||
title="Tus canciones subidas"
|
||||
description="{plural(total, 'canción', 'canciones')} subida{total === 1 ? '' : 's'}."
|
||||
>
|
||||
{#snippet actions()}
|
||||
{#if items.length > 0}
|
||||
<Button href="/upload">
|
||||
<Upload class="size-icon-sm" />
|
||||
Subir canción
|
||||
</Button>
|
||||
{/if}
|
||||
{/snippet}
|
||||
</PageHeader>
|
||||
title="Gestionar música"
|
||||
description="{plural(total, 'canción', 'canciones')} subida{total === 1
|
||||
? ''
|
||||
: 's'}. Puedes borrarlas o reproducirlas desde aquí."
|
||||
/>
|
||||
|
||||
{#if items.length > 0}
|
||||
<TrackList
|
||||
<div class="flex gap-2">
|
||||
{#each SECTIONS as option (option.value)}
|
||||
<Button
|
||||
variant={section === option.value ? 'primary' : 'secondary'}
|
||||
onclick={() => selectSection(option.value)}
|
||||
size="sm"
|
||||
>
|
||||
{option.label}
|
||||
</Button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
{#if section === 'tracks'}
|
||||
<LibraryTracksSection
|
||||
tracks={items}
|
||||
columns={['uploaded', 'plays']}
|
||||
onPlay={togglePlay}
|
||||
rowAction={{
|
||||
onclick: (track) => (deleting = items.find((item) => item.id === track.id) ?? null),
|
||||
icon: X,
|
||||
label: 'Borrar canción'
|
||||
}}
|
||||
errorMessage={form?.action === 'deleteTracks' ? form.message : undefined}
|
||||
/>
|
||||
{:else if section === 'albums'}
|
||||
{#key resetKey}
|
||||
<LibraryAlbumsSection
|
||||
albums={data.albums.items}
|
||||
tracks={items}
|
||||
albumTrackIds={data.albumTrackIds}
|
||||
formMessage={form?.action === 'saveAlbum' || form?.action === 'deleteAlbum'
|
||||
? form.message
|
||||
: undefined}
|
||||
/>
|
||||
{/key}
|
||||
{:else}
|
||||
<EmptyState
|
||||
icon={Music}
|
||||
title="Todavía no tienes canciones"
|
||||
description="Sube la primera y aparecerá aquí lista para reproducir."
|
||||
>
|
||||
{#snippet actions()}
|
||||
<Button href="/upload">
|
||||
<Upload class="size-icon-sm" />
|
||||
Sube la primera
|
||||
</Button>
|
||||
{/snippet}
|
||||
</EmptyState>
|
||||
<LibraryUploadsSection genres={data.genres} />
|
||||
{/if}
|
||||
</Page>
|
||||
|
||||
<ConfirmDialog
|
||||
open={deleting !== null}
|
||||
onClose={() => (deleting = null)}
|
||||
title="¿Borrar «{deleting?.title ?? ''}»?"
|
||||
description="Esta acción no se puede deshacer, la canción se eliminará de tu biblioteca, de tus álbumes y de las playlists donde esté."
|
||||
confirmLabel="Borrar"
|
||||
action="?/deleteTrack"
|
||||
fields={{ trackId: deleting?.id ?? '' }}
|
||||
/>
|
||||
|
||||
@@ -271,6 +271,16 @@
|
||||
}
|
||||
|
||||
@layer base {
|
||||
input[type='number'] {
|
||||
appearance: textfield;
|
||||
}
|
||||
|
||||
input[type='number']::-webkit-inner-spin-button,
|
||||
input[type='number']::-webkit-outer-spin-button {
|
||||
appearance: none;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
svg.lucide {
|
||||
stroke-width: 1.5;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user