Files
otunes/packages/convex/convex/library.ts
T

1442 lines
39 KiB
TypeScript

import { paginationOptsValidator } from "convex/server"
import { getAuthUserId } from "@convex-dev/auth/server"
import { internalMutation, internalQuery, query } from "./_generated/server"
import { ConvexError, v } from "convex/values"
import type { Doc, Id } from "./_generated/dataModel"
import type { MutationCtx, QueryCtx } from "./_generated/server"
import type { PaginationOptions, PaginationResult } from "convex/server"
import type {
BrowseAlbum,
BrowseAlbumDetail,
BrowseAlbumTrack,
BrowseArtist,
BrowseArtistDetail,
BrowsePlaylistDetail,
BrowsePlaylistOwner,
BrowsePlaylistSummary,
BrowseSong,
LibrarySearchResults,
OwnedPlaylistForAdd,
PlaylistSummary,
SearchSong,
SearchTopResultItem,
SidebarPlaylists,
} from "./types"
import { purgeFavoriteEntities } from "./favoriteStore"
import { chunk, type Chunked } from "./limits"
import { recordIntentCatalogChanges } from "./intentCatalogChanges"
import { playlistCoverVersion } from "./playlistCover"
import { deleteSongLyrics, searchSongLyrics, writeSongLyrics } from "./lyrics"
export type {
BrowseAlbum,
BrowseAlbumDetail,
BrowseAlbumTrack,
BrowseArtist,
BrowseArtistDetail,
BrowsePlaylistDetail,
BrowsePlaylistOwner,
BrowsePlaylistSummary,
BrowseSong,
LibrarySearchResults,
OwnedPlaylistForAdd,
PlaylistSummary,
SearchSong,
SearchTopResultItem,
SidebarPlaylists,
} from "./types"
const EMPTY_PAGE = { page: [], isDone: true, continueCursor: "" }
/** Reactive queries return empty data when signed out so sign-out doesn't throw mid-render. */
export async function isSignedIn(ctx: QueryCtx) {
return (await getAuthUserId(ctx)) !== null
}
/** Imperative lookups throw instead, so callers that cache results don't cache an empty one. */
export async function requireSignedIn(ctx: QueryCtx) {
if (!(await isSignedIn(ctx))) {
throw new ConvexError("Not authenticated")
}
}
export function getSongArtistNames(artist: string | string[]): string[] {
if (Array.isArray(artist)) {
return artist.map((name) => name.trim()).filter((name) => name.length > 0)
}
const trimmed = artist.trim()
return trimmed.length > 0 ? [trimmed] : []
}
export function songArtistsMatchAlbum(
songArtists: string[],
albumArtistName: string
): boolean {
const albumLower = albumArtistName.toLowerCase()
if (songArtists.length === 0) {
return true
}
if (songArtists.length === 1) {
return songArtists[0].toLowerCase() === albumLower
}
return songArtists.every((name) => name.toLowerCase() === albumLower)
}
function toBrowseAlbumTrack(
song: Doc<"songs">,
albumArtistName: string
): BrowseAlbumTrack {
const artistNames = getSongArtistNames(song.artist)
return {
id: song._id,
title: song.name,
track: song.track,
diskNumber: song.diskNumber,
durationSeconds: Math.round(song.length),
artists: songArtistsMatchAlbum(artistNames, albumArtistName)
? null
: artistNames,
}
}
export function compareAlbumSongs(a: Doc<"songs">, b: Doc<"songs">) {
const aDisk = a.diskNumber ?? Number.MAX_SAFE_INTEGER
const bDisk = b.diskNumber ?? Number.MAX_SAFE_INTEGER
if (aDisk !== bDisk) {
return aDisk - bDisk
}
if (a.track !== b.track) {
return a.track - b.track
}
return a.name.localeCompare(b.name)
}
type SearchTopResult =
| { kind: "song"; item: BrowseSong; score: number }
| { kind: "album"; item: BrowseAlbum; score: number }
| { kind: "artist"; item: BrowseArtist; score: number }
function toSearchTopResultItem(result: SearchTopResult): SearchTopResultItem {
switch (result.kind) {
case "song":
return { kind: "song", item: result.item }
case "album":
return { kind: "album", item: result.item }
case "artist":
return { kind: "artist", item: result.item }
}
}
async function loadArtistMap(ctx: QueryCtx) {
const artists = await ctx.db.query("artists").collect()
return new Map(artists.map((artist) => [artist._id, artist]))
}
async function loadArtistMapForIds(ctx: QueryCtx, artistIds: Id<"artists">[]) {
const ids = [...new Set(artistIds)]
const artists = await Promise.all(ids.map((id) => ctx.db.get("artists", id)))
return new Map(
artists.flatMap((artist) => (artist ? [[artist._id, artist] as const] : []))
)
}
function toBrowseArtist(artist: Doc<"artists">): BrowseArtist {
return {
id: artist._id,
name: artist.name,
photo: artist.cover,
}
}
function toBrowseAlbum(
album: Doc<"albums">,
artist: Doc<"artists">
): BrowseAlbum {
return {
id: album._id,
title: album.name,
artist: toBrowseArtist(artist),
cover: album.cover,
}
}
/**
* Past this many songs, scanning the library takes fewer reads than a get per
* song, album and artist, which would hit Convex's 4,096 reads per function.
*/
const MAX_SONG_GETS = 1_000
export async function browseSongsFromIds(
ctx: QueryCtx,
songIds: Id<"songs">[]
): Promise<BrowseSong[]> {
if (songIds.length > MAX_SONG_GETS) {
return browseSongsByScan(ctx, songIds)
}
const songs = await Promise.all(
songIds.map((songId) => ctx.db.get("songs", songId))
)
return browseSongDocs(
ctx,
songs.filter((song): song is Doc<"songs"> => song !== null)
)
}
async function browseSongsByScan(
ctx: QueryCtx,
songIds: Id<"songs">[]
): Promise<BrowseSong[]> {
const [songs, albums, artistMap] = await Promise.all([
ctx.db.query("songs").collect(),
ctx.db.query("albums").collect(),
loadArtistMap(ctx),
])
const songMap = new Map(songs.map((song) => [song._id, song]))
const albumMap = new Map(albums.map((album) => [album._id, album]))
return songIds.flatMap((songId) => {
const song = songMap.get(songId)
const album = song && albumMap.get(song.album)
const albumArtist = song && artistMap.get(song.albumArtist)
return song && album && albumArtist
? [toBrowseSong(song, album, albumArtist)]
: []
})
}
async function browseSongDocs(
ctx: QueryCtx,
songs: Doc<"songs">[]
): Promise<BrowseSong[]> {
const albumIds = [...new Set(songs.map((song) => song.album))]
const albums = await Promise.all(
albumIds.map((albumId) => ctx.db.get("albums", albumId))
)
const albumMap = new Map(
albums.flatMap((album) => (album ? [[album._id, album] as const] : []))
)
const artistMap = await loadArtistMapForIds(
ctx,
songs.map((song) => song.albumArtist)
)
return songs.flatMap((song) => {
const album = albumMap.get(song.album)
const albumArtist = artistMap.get(song.albumArtist)
return album && albumArtist ? [toBrowseSong(song, album, albumArtist)] : []
})
}
function toBrowseSong(
song: Doc<"songs">,
album: Doc<"albums">,
albumArtist: Doc<"artists">
): BrowseSong {
return {
id: song._id,
title: song.name,
artist: {
id: albumArtist._id,
name: albumArtist.name,
photo: albumArtist.cover,
},
album: {
id: album._id,
title: album.name,
cover: album.cover,
},
durationSeconds: Math.round(song.length),
}
}
export const browseAlbums = query({
args: {},
handler: async (ctx): Promise<Chunked<BrowseAlbum>> => {
if (!(await isSignedIn(ctx))) {
return []
}
const artistMap = await loadArtistMap(ctx)
const albums = await ctx.db.query("albums").collect()
return chunk(
albums
.flatMap((album) => {
const artist = artistMap.get(album.artist)
return artist ? [toBrowseAlbum(album, artist)] : []
})
.sort((a, b) => a.title.localeCompare(b.title))
)
},
})
export const browseArtists = query({
args: {},
handler: async (ctx): Promise<Chunked<BrowseArtist>> => {
if (!(await isSignedIn(ctx))) {
return []
}
const artists = await ctx.db.query("artists").collect()
return chunk(
artists.map(toBrowseArtist).sort((a, b) => a.name.localeCompare(b.name))
)
},
})
function paginateSlice<T>(
items: T[],
paginationOpts: PaginationOptions
): PaginationResult<T> {
const cursor = paginationOpts.cursor
const start = cursor && cursor.length > 0 ? Number.parseInt(cursor, 10) : 0
const safeStart = Number.isFinite(start) ? start : 0
const page = items.slice(safeStart, safeStart + paginationOpts.numItems)
const next = safeStart + page.length
return {
page,
isDone: next >= items.length,
continueCursor: next >= items.length ? "" : String(next),
}
}
export const browseArtistsPaginated = query({
args: { paginationOpts: paginationOptsValidator },
handler: async (ctx, args) => {
if (!(await isSignedIn(ctx))) {
return EMPTY_PAGE
}
const result = await ctx.db
.query("artists")
.withIndex("by_name")
.order("asc")
.paginate(args.paginationOpts)
return {
...result,
page: result.page.map(toBrowseArtist),
}
},
})
export const browseAlbumsPaginated = query({
args: { paginationOpts: paginationOptsValidator },
handler: async (ctx, args) => {
if (!(await isSignedIn(ctx))) {
return EMPTY_PAGE
}
const result = await ctx.db
.query("albums")
.withIndex("by_name")
.order("asc")
.paginate(args.paginationOpts)
const artistMap = await loadArtistMapForIds(
ctx,
result.page.map((album) => album.artist)
)
return {
...result,
page: result.page.flatMap((album) => {
const artist = artistMap.get(album.artist)
return artist ? [toBrowseAlbum(album, artist)] : []
}),
}
},
})
export const songsSortKeyValidator = v.union(
v.literal("title"),
v.literal("artist"),
v.literal("album")
)
export const songsSortDirectionValidator = v.union(
v.literal("asc"),
v.literal("desc")
)
export type SongsSortKey = "title" | "artist" | "album"
export type SongsSortDirection = "asc" | "desc"
type GroupedSongsCursor = {
groupCursor: string | null
songIndex: number
}
function compareSongNames(
a: string,
b: string,
direction: SongsSortDirection
): number {
const comparison = a.localeCompare(b)
return direction === "asc" ? comparison : -comparison
}
async function paginateSongsByTitle(
ctx: QueryCtx,
paginationOpts: PaginationOptions,
sortDirection: SongsSortDirection
): Promise<PaginationResult<BrowseSong>> {
const result = await ctx.db
.query("songs")
.withIndex("by_name")
.order(sortDirection)
.paginate(paginationOpts)
return {
...result,
page: await browseSongDocs(ctx, result.page),
}
}
async function paginateSongsByGroup(
ctx: QueryCtx,
paginationOpts: PaginationOptions,
sortDirection: SongsSortDirection,
sortKey: "artist" | "album"
): Promise<PaginationResult<BrowseSong>> {
let cursor: GroupedSongsCursor = { groupCursor: null, songIndex: 0 }
if (paginationOpts.cursor) {
const parsed = JSON.parse(
paginationOpts.cursor
) as Partial<GroupedSongsCursor>
if (
(typeof parsed.groupCursor === "string" || parsed.groupCursor === null) &&
Number.isInteger(parsed.songIndex) &&
(parsed.songIndex ?? -1) >= 0
) {
cursor = parsed as GroupedSongsCursor
}
}
const songDocs: Doc<"songs">[] = []
let { groupCursor, songIndex } = cursor
let isDone = false
while (songDocs.length < paginationOpts.numItems && !isDone) {
const groupResult =
sortKey === "artist"
? await ctx.db
.query("artists")
.withIndex("by_name")
.order(sortDirection)
.paginate({ cursor: groupCursor, numItems: 1 })
: await ctx.db
.query("albums")
.withIndex("by_name")
.order(sortDirection)
.paginate({ cursor: groupCursor, numItems: 1 })
const group = groupResult.page[0]
if (!group) {
isDone = true
break
}
const songs =
sortKey === "artist"
? await ctx.db
.query("songs")
.withIndex("by_artist", (q) =>
q.eq("albumArtist", group._id as Id<"artists">)
)
.collect()
: await ctx.db
.query("songs")
.withIndex("by_album", (q) =>
q.eq("album", group._id as Id<"albums">)
)
.collect()
songs.sort((a, b) => compareSongNames(a.name, b.name, sortDirection))
while (
songIndex < songs.length &&
songDocs.length < paginationOpts.numItems
) {
songDocs.push(songs[songIndex])
songIndex++
}
if (songIndex >= songs.length) {
groupCursor = groupResult.continueCursor || null
songIndex = 0
isDone = groupResult.isDone
}
}
return {
page: await browseSongDocs(ctx, songDocs),
isDone,
continueCursor: isDone
? ""
: JSON.stringify({ groupCursor, songIndex } satisfies GroupedSongsCursor),
}
}
export async function getSortedLibrarySongIds(
ctx: QueryCtx,
sortKey: SongsSortKey,
sortDirection: SongsSortDirection
): Promise<Id<"songs">[]> {
if (sortKey === "title") {
const songs = await ctx.db
.query("songs")
.withIndex("by_name")
.order(sortDirection)
.collect()
return songs.map((song) => song._id)
}
const songs = await ctx.db.query("songs").collect()
const groupNames =
sortKey === "artist"
? new Map(
[...(await loadArtistMap(ctx)).values()].map((artist) => [
artist._id as string,
artist.name,
])
)
: new Map(
(await ctx.db.query("albums").collect()).map((album) => [
album._id as string,
album.name,
])
)
const validSongs = songs.filter((song) =>
groupNames.has(sortKey === "artist" ? song.albumArtist : song.album)
)
validSongs.sort((a, b) => {
const groupA =
groupNames.get(sortKey === "artist" ? a.albumArtist : a.album) ?? ""
const groupB =
groupNames.get(sortKey === "artist" ? b.albumArtist : b.album) ?? ""
return (
compareSongNames(groupA, groupB, sortDirection) ||
compareSongNames(a.name, b.name, sortDirection)
)
})
return validSongs.map((song) => song._id)
}
export const browseSongsPaginated = query({
args: {
paginationOpts: paginationOptsValidator,
sortKey: songsSortKeyValidator,
sortDirection: songsSortDirectionValidator,
},
handler: async (ctx, args) => {
if (!(await isSignedIn(ctx))) {
return EMPTY_PAGE
}
if (args.sortKey === "title") {
return paginateSongsByTitle(ctx, args.paginationOpts, args.sortDirection)
}
return paginateSongsByGroup(
ctx,
args.paginationOpts,
args.sortDirection,
args.sortKey
)
},
})
export const browseSortedSongIds = query({
args: {
sortKey: songsSortKeyValidator,
sortDirection: songsSortDirectionValidator,
},
handler: async (ctx, args) => {
await requireSignedIn(ctx)
return chunk(
await getSortedLibrarySongIds(ctx, args.sortKey, args.sortDirection)
)
},
})
const MAX_SONGS_BY_IDS = 200
export const browseSongsByIds = query({
args: { ids: v.array(v.id("songs")) },
handler: async (ctx, args): Promise<BrowseSong[]> => {
await requireSignedIn(ctx)
if (args.ids.length > MAX_SONGS_BY_IDS) {
throw new ConvexError(`Request at most ${MAX_SONGS_BY_IDS} songs`)
}
return browseSongsFromIds(ctx, args.ids)
},
})
/** Public: shared /album links render this without a session. */
export const browseAlbumDetail = query({
args: { id: v.id("albums") },
handler: async (ctx, args): Promise<BrowseAlbumDetail | null> => {
const album = await ctx.db.get("albums", args.id)
const artist = album ? await ctx.db.get("artists", album.artist) : null
if (!album || !artist) {
return null
}
const songs = await ctx.db
.query("songs")
.withIndex("by_album", (q) => q.eq("album", args.id))
.collect()
songs.sort(compareAlbumSongs)
const primarySong = songs[0]
return {
...toBrowseAlbum(album, artist),
year: primarySong?.year || null,
genre: primarySong?.genres[0] ?? null,
releaseDate: album.date,
hasLossless: songs.some((song) => "lossless" in song.files),
hasAtmos: songs.some((song) => "atmos" in song.files),
tracks: songs.map((song) => toBrowseAlbumTrack(song, artist.name)),
}
},
})
/** Public: shared /artist links render this without a session. */
export const browseArtistDetail = query({
args: { id: v.id("artists") },
handler: async (ctx, args) => {
const artist = await ctx.db.get("artists", args.id)
if (!artist) {
return null
}
const albums = await ctx.db
.query("albums")
.withIndex("by_artist", (q) => q.eq("artist", args.id))
.collect()
albums.sort((a, b) => a.name.localeCompare(b.name))
return {
artist: toBrowseArtist(artist),
albums: albums.map((album) => toBrowseAlbum(album, artist)),
}
},
})
function matchScore(text: string, query: string): number {
const lower = text.toLowerCase()
if (lower === query) {
return 100
}
if (lower.startsWith(query)) {
return 80
}
if (lower.split(/\s+/).some((word) => word.startsWith(query))) {
return 60
}
if (lower.includes(query)) {
return 40
}
return 0
}
function matchScoreSongArtists(
artist: string | string[],
query: string
): number {
return getSongArtistNames(artist).reduce(
(best, name) => Math.max(best, matchScore(name, query)),
0
)
}
/**
* Results kept per search section. Broad queries like "a" match most of the
* library, which would overflow Convex's array limit and is too long to scroll.
*/
const MAX_SEARCH_RESULTS = 500
/** Songs found by lyrics alone, listed after title, artist and album matches. */
const MAX_LYRICS_SEARCH_RESULTS = 50
export const searchLibrary = query({
args: { query: v.string() },
handler: async (ctx, args) => {
const queryText = args.query.trim().toLowerCase()
if (!queryText || !(await isSignedIn(ctx))) {
return {
topResults: [],
artists: [],
albums: [],
songs: [],
}
}
const artistMap = await loadArtistMap(ctx)
const albums = await ctx.db.query("albums").collect()
const albumMap = new Map(albums.map((album) => [album._id, album]))
const songs = await ctx.db.query("songs").collect()
const artistResults: Extract<SearchTopResult, { kind: "artist" }>[] = [
...artistMap.values(),
]
.map((artist) => ({
kind: "artist" as const,
item: toBrowseArtist(artist),
score: matchScore(artist.name, queryText),
}))
.filter((result) => result.score > 0)
.sort(
(a, b) => b.score - a.score || a.item.name.localeCompare(b.item.name)
)
const albumResults: Extract<SearchTopResult, { kind: "album" }>[] = albums
.flatMap((album) => {
const artist = artistMap.get(album.artist)
if (!artist) {
return []
}
const score = Math.max(
matchScore(album.name, queryText),
matchScore(artist.name, queryText)
)
if (score === 0) {
return []
}
return [
{
kind: "album" as const,
item: toBrowseAlbum(album, artist),
score,
},
]
})
.sort(
(a, b) => b.score - a.score || a.item.title.localeCompare(b.item.title)
)
const songResults: Extract<SearchTopResult, { kind: "song" }>[] = songs
.flatMap((song) => {
const album = albumMap.get(song.album)
const albumArtist = artistMap.get(song.albumArtist)
if (!album || !albumArtist) {
return []
}
const score = Math.max(
matchScore(song.name, queryText),
matchScoreSongArtists(song.artist, queryText),
matchScore(album.name, queryText),
matchScore(albumArtist.name, queryText)
)
if (score === 0) {
return []
}
return [
{
kind: "song" as const,
item: toBrowseSong(song, album, albumArtist),
score,
},
]
})
.sort(
(a, b) => b.score - a.score || a.item.title.localeCompare(b.item.title)
)
const songById = new Map(songs.map((song) => [song._id, song]))
const matchedSongIds = new Set(songResults.map((result) => result.item.id))
const lyricsResults: SearchSong[] = (
await searchSongLyrics(ctx, args.query, MAX_LYRICS_SEARCH_RESULTS)
).flatMap(({ song: songId, snippet }) => {
const song = songById.get(songId)
const album = song && albumMap.get(song.album)
const albumArtist = song && artistMap.get(song.albumArtist)
if (!song || !album || !albumArtist || matchedSongIds.has(songId)) {
return []
}
return [
{
...toBrowseSong(song, album, albumArtist),
lyricsSnippet: snippet,
},
]
})
const topResults: SearchTopResultItem[] = [
...songResults,
...albumResults,
...artistResults,
]
.sort((a, b) => b.score - a.score)
.slice(0, 6)
.map(toSearchTopResultItem)
const result: LibrarySearchResults = {
topResults,
artists: artistResults
.slice(0, MAX_SEARCH_RESULTS)
.map((result) => result.item),
albums: albumResults
.slice(0, MAX_SEARCH_RESULTS)
.map((result) => result.item),
songs: [
...songResults.map((result): SearchSong => result.item),
...lyricsResults,
].slice(0, MAX_SEARCH_RESULTS),
}
return result
},
})
export const browseRecentlyAdded = query({
args: { limit: v.optional(v.number()) },
handler: async (ctx, args): Promise<Chunked<BrowseAlbum>> => {
if (!(await isSignedIn(ctx))) {
return []
}
const albumQuery = ctx.db.query("albums").order("desc")
const albums = args.limit
? await albumQuery.take(args.limit)
: await albumQuery.collect()
const artistMap = await loadArtistMapForIds(
ctx,
albums.map((album) => album.artist)
)
return chunk(
albums.flatMap((album) => {
const artist = artistMap.get(album.artist)
return artist ? [toBrowseAlbum(album, artist)] : []
})
)
},
})
export const browseRecentlyAddedPaginated = query({
args: { paginationOpts: paginationOptsValidator },
handler: async (ctx, args) => {
if (!(await isSignedIn(ctx))) {
return EMPTY_PAGE
}
const result = await ctx.db
.query("albums")
.order("desc")
.paginate(args.paginationOpts)
const artistMap = await loadArtistMapForIds(
ctx,
result.page.map((album) => album.artist)
)
return {
...result,
page: result.page.flatMap((album) => {
const artist = artistMap.get(album.artist)
return artist ? [toBrowseAlbum(album, artist)] : []
}),
}
},
})
async function browseRecentlyPlayedItems(ctx: QueryCtx, limit?: number) {
const userId = await getAuthUserId(ctx)
if (userId === null) {
return []
}
const user = await ctx.db.get(userId)
if (!user) {
return []
}
const recentlyPlayed = (user.recentlyPlayed ?? []).slice(0, limit)
if (recentlyPlayed.length === 0) {
return []
}
const loaded = await Promise.all(
recentlyPlayed.map(async (id) => {
const albumId = ctx.db.normalizeId("albums", id)
if (albumId !== null) {
const album = await ctx.db.get("albums", albumId)
return album ? ({ kind: "album", album } as const) : null
}
const playlistId = ctx.db.normalizeId("playlists", id)
if (playlistId === null) {
return null
}
const playlist = await ctx.db.get("playlists", playlistId)
return playlist ? ({ kind: "playlist", playlist } as const) : null
})
)
const artistMap = await loadArtistMapForIds(
ctx,
loaded.flatMap((entry) =>
entry?.kind === "album" ? [entry.album.artist] : []
)
)
const ownerIds = [
...new Set(
loaded.flatMap((entry) =>
entry?.kind === "playlist" ? [entry.playlist.owner] : []
)
),
]
const owners = await Promise.all(
ownerIds.map((ownerId) => ctx.db.get("users", ownerId))
)
const ownerMap = new Map(
owners.flatMap((owner) => (owner ? [[owner._id, owner] as const] : []))
)
const items: (BrowseAlbum | PlaylistSummary)[] = []
for (const entry of loaded) {
if (!entry) {
continue
}
if (entry.kind === "album") {
const artist = artistMap.get(entry.album.artist)
if (artist) {
items.push(toBrowseAlbum(entry.album, artist))
}
continue
}
items.push({
id: entry.playlist._id,
title: entry.playlist.name,
owner: ownerMap.get(entry.playlist.owner)?.name ?? "Unknown",
cover: playlistCoverVersion(entry.playlist),
})
}
return items
}
export const browseRecentlyPlayed = query({
args: { limit: v.optional(v.number()) },
handler: async (ctx, args) => browseRecentlyPlayedItems(ctx, args.limit),
})
export const browseRecentlyPlayedPaginated = query({
args: { paginationOpts: paginationOptsValidator },
handler: async (ctx, args) => {
const items = await browseRecentlyPlayedItems(ctx)
return paginateSlice(items, args.paginationOpts)
},
})
export const scanArtistsPage = internalQuery({
args: { paginationOpts: paginationOptsValidator },
handler: async (ctx, args) => {
const result = await ctx.db.query("artists").paginate(args.paginationOpts)
return {
...result,
page: result.page.map(({ _id, name, folder, cover }) => ({
_id,
name,
folder,
cover,
})),
}
},
})
export const scanAlbumsPage = internalQuery({
args: { paginationOpts: paginationOptsValidator },
handler: async (ctx, args) => {
const result = await ctx.db.query("albums").paginate(args.paginationOpts)
return {
...result,
page: result.page.map(({ _id, folder, cover, artist }) => ({
_id,
folder,
cover,
artist,
})),
}
},
})
export const scanSongsPage = internalQuery({
args: { paginationOpts: paginationOptsValidator },
handler: async (ctx, args) => {
const result = await ctx.db.query("songs").paginate(args.paginationOpts)
return {
...result,
page: result.page.map(({ _id, name, files, album, hasLyrics }) => ({
_id,
name,
files,
album,
hasLyrics,
})),
}
},
})
/** Public: share-link previews load covers without a session. */
export const getArtistCover = query({
args: { id: v.id("artists") },
handler: async (ctx, args) => {
return (await ctx.db.get("artists", args.id))?.cover ?? null
},
})
/** Public: share-link previews load covers without a session. */
export const getAlbumCover = query({
args: { id: v.id("albums") },
handler: async (ctx, args) => {
return (await ctx.db.get("albums", args.id))?.cover ?? null
},
})
/**
* Public: share-link previews load covers without a session. A storage URL
* the web server proxies, or `null` when the playlist has no artwork.
*/
export const getPlaylistCover = query({
args: { id: v.id("playlists") },
handler: async (ctx, args) => {
const storageId = (await ctx.db.get("playlists", args.id))?.coverStorageId
return storageId ? await ctx.storage.getUrl(storageId) : null
},
})
/** Public: share-link previews read song metadata without a session. Never returns file paths. */
export const getSong = query({
args: { id: v.id("songs") },
handler: async (ctx, args) => {
const song = await ctx.db.get("songs", args.id)
if (!song) {
return null
}
const { files: _files, ...clientSong } = song
return clientSong
},
})
/** Returns absolute file paths. Only the web streaming routes call this, as the listener. */
export const getSongSource = query({
args: { id: v.id("songs") },
handler: async (ctx, args) => {
await requireSignedIn(ctx)
const song = await ctx.db.get("songs", args.id)
if (!song) {
return null
}
return { _id: song._id, files: song.files, length: song.length }
},
})
/** Batch of `getSongSource` for download sizing. Missing songs are skipped. */
export const getSongSources = query({
args: { ids: v.array(v.id("songs")) },
handler: async (ctx, args) => {
await requireSignedIn(ctx)
if (args.ids.length > MAX_SONGS_BY_IDS) {
throw new ConvexError(`Request at most ${MAX_SONGS_BY_IDS} songs`)
}
const songs = await Promise.all(args.ids.map((id) => ctx.db.get(id)))
return songs.flatMap((song) =>
song
? [
{
_id: song._id,
files: song.files,
length: song.length,
album: song.album,
},
]
: []
)
},
})
function playbackCodecMap(files: Record<string, string>) {
return Object.fromEntries(Object.keys(files).map((codec) => [codec, true]))
}
export const getSongPlaybackInfo = query({
args: { id: v.id("songs") },
handler: async (ctx, args) => {
const userId = await getAuthUserId(ctx)
if (userId === null) {
return null
}
const song = await ctx.db.get("songs", args.id)
if (!song) {
return null
}
return {
id: song._id,
files: playbackCodecMap(song.files),
}
},
})
export const getSongsForPlayback = query({
args: { ids: v.array(v.id("songs")) },
handler: async (ctx, { ids }) => {
const userId = await getAuthUserId(ctx)
if (userId === null) {
return ids.map(() => null)
}
const songs = await Promise.all(ids.map((id) => ctx.db.get(id)))
return songs.map((song, index) => {
if (!song) {
return null
}
return {
id: ids[index],
title: song.name,
albumId: song.album,
files: playbackCodecMap(song.files),
}
})
},
})
/**
* Creates (or reuses, matched by folder) the artist and album for each entry
* together with its songs, so an album never exists without songs.
*/
export const importAlbums = internalMutation({
args: {
albums: v.array(
v.object({
artist: v.object({
name: v.string(),
folder: v.string(),
cover: v.nullable(v.string()),
}),
album: v.object({
name: v.string(),
folder: v.string(),
cover: v.nullable(v.string()),
year: v.number(),
date: v.string(),
}),
songs: v.array(
v.object({
name: v.string(),
files: v.record(v.string(), v.string()),
artist: v.union(v.string(), v.array(v.string())),
length: v.number(),
diskNumber: v.nullable(v.number()),
track: v.number(),
year: v.number(),
date: v.string(),
genres: v.array(v.string()),
/** The best lyrics tag among the song's files. */
lyrics: v.nullable(v.string()),
})
),
})
),
},
handler: async (ctx, args) => {
for (const entry of args.albums) {
if (entry.songs.length === 0) {
continue
}
const artistId =
(
await ctx.db
.query("artists")
.withIndex("by_folder", (q) => q.eq("folder", entry.artist.folder))
.first()
)?._id ?? (await ctx.db.insert("artists", entry.artist))
const albumId =
(
await ctx.db
.query("albums")
.withIndex("by_all", (q) =>
q.eq("artist", artistId).eq("folder", entry.album.folder)
)
.first()
)?._id ??
(await ctx.db.insert("albums", { ...entry.album, artist: artistId }))
for (const { lyrics, ...song } of entry.songs) {
const existing = await ctx.db
.query("songs")
.withIndex("by_all", (q) =>
q
.eq("name", song.name)
.eq("albumArtist", artistId)
.eq("album", albumId)
)
.first()
if (existing) {
await ctx.db.patch(existing._id, {
files: { ...existing.files, ...song.files },
})
continue
}
const songId = await ctx.db.insert("songs", {
...song,
album: albumId,
albumArtist: artistId,
})
await writeSongLyrics(ctx, songId, lyrics)
}
}
},
})
/** Deletes songs and removes them from every playlist, favorite and queue. */
export const deleteSongs = internalMutation({
args: { ids: v.array(v.id("songs")) },
handler: async (ctx, args) => {
for (const id of args.ids) {
await ctx.db.delete("songs", id)
await deleteSongLyrics(ctx, id)
}
await purgeSongsFromUsersAndPlaylists(ctx, new Set(args.ids))
await recordIntentCatalogChanges(ctx, "song", args.ids, true)
},
})
/** Deletes the albums that still have no songs when this mutation runs. */
export const deleteEmptyAlbums = internalMutation({
args: { ids: v.array(v.id("albums")) },
handler: async (ctx, args) => {
const deleted = new Set<Id<"albums">>()
for (const id of args.ids) {
const song = await ctx.db
.query("songs")
.withIndex("by_album", (q) => q.eq("album", id))
.first()
if (song === null && (await ctx.db.get("albums", id)) !== null) {
await ctx.db.delete("albums", id)
deleted.add(id)
}
}
await purgeAlbumsFromUsers(ctx, deleted)
await recordIntentCatalogChanges(ctx, "album", [...deleted], true)
return deleted.size
},
})
/** Deletes the artists that still have no albums when this mutation runs. */
export const deleteEmptyArtists = internalMutation({
args: { ids: v.array(v.id("artists")) },
handler: async (ctx, args) => {
const deleted = new Set<Id<"artists">>()
for (const id of args.ids) {
const album = await ctx.db
.query("albums")
.withIndex("by_artist", (q) => q.eq("artist", id))
.first()
if (album === null && (await ctx.db.get("artists", id)) !== null) {
await ctx.db.delete("artists", id)
deleted.add(id)
}
}
await purgeArtistsFromUsers(ctx, deleted)
await recordIntentCatalogChanges(ctx, "artist", [...deleted], true)
return deleted.size
},
})
async function purgeSongsFromUsersAndPlaylists(
ctx: MutationCtx,
remove: Set<Id<"songs">>
) {
if (remove.size === 0) {
return
}
for (const playlist of await ctx.db.query("playlists").collect()) {
if (playlist.songs.some((songId) => remove.has(songId))) {
await ctx.db.patch(playlist._id, {
songs: playlist.songs.filter((songId) => !remove.has(songId)),
})
}
}
for (const state of await ctx.db.query("playbackStates").collect()) {
if (
state.songQueue.some((songId) => remove.has(songId)) ||
state.queueHistory.some((songId) => remove.has(songId))
) {
await ctx.db.patch(state._id, {
songQueue: state.songQueue.filter((songId) => !remove.has(songId)),
queueHistory: state.queueHistory.filter(
(songId) => !remove.has(songId)
),
revision: state.revision + 1,
})
}
}
await purgeFavoriteEntities(ctx, remove)
// Legacy favorite and queue fields stay until `migrations.migrateUsers`
// clears them.
for (const user of await ctx.db.query("users").collect()) {
const favoriteSongs = user.favoriteSongs
const songQueue = user.songQueue
const queueHistory = user.queueHistory
const patch: Partial<
Pick<
Doc<"users">,
"favoriteSongs" | "songQueue" | "queueHistory" | "currentSongProgress"
>
> = {}
if (favoriteSongs?.some((songId) => remove.has(songId))) {
patch.favoriteSongs = favoriteSongs.filter(
(songId) => !remove.has(songId)
)
}
if (songQueue?.some((songId) => remove.has(songId))) {
const currentRemoved = remove.has(songQueue[0])
patch.songQueue = songQueue.filter((songId) => !remove.has(songId))
if (currentRemoved) {
patch.currentSongProgress = 0
}
}
if (queueHistory?.some((songId) => remove.has(songId))) {
patch.queueHistory = queueHistory.filter((songId) => !remove.has(songId))
}
if (Object.keys(patch).length > 0) {
await ctx.db.patch(user._id, patch)
}
}
}
async function purgeAlbumsFromUsers(
ctx: MutationCtx,
remove: Set<Id<"albums">>
) {
if (remove.size === 0) {
return
}
await purgeFavoriteEntities(ctx, remove)
// Legacy `favoriteAlbums` stays until `migrations.migrateUsers` clears it.
for (const user of await ctx.db.query("users").collect()) {
const favoriteAlbums = user.favoriteAlbums
const recentlyPlayed = user.recentlyPlayed
const patch: Partial<
Pick<Doc<"users">, "favoriteAlbums" | "recentlyPlayed">
> = {}
if (favoriteAlbums?.some((albumId) => remove.has(albumId))) {
patch.favoriteAlbums = favoriteAlbums.filter(
(albumId) => !remove.has(albumId)
)
}
if (recentlyPlayed?.some((itemId) => remove.has(itemId as Id<"albums">))) {
patch.recentlyPlayed = recentlyPlayed.filter(
(itemId) => !remove.has(itemId as Id<"albums">)
)
}
if (Object.keys(patch).length > 0) {
await ctx.db.patch(user._id, patch)
}
}
}
async function purgeArtistsFromUsers(
ctx: MutationCtx,
remove: Set<Id<"artists">>
) {
if (remove.size === 0) {
return
}
await purgeFavoriteEntities(ctx, remove)
// Legacy `favoriteArtists` stays until `migrations.migrateUsers` clears it.
for (const user of await ctx.db.query("users").collect()) {
const favoriteArtists = user.favoriteArtists
if (favoriteArtists?.some((artistId) => remove.has(artistId))) {
await ctx.db.patch(user._id, {
favoriteArtists: favoriteArtists.filter(
(artistId) => !remove.has(artistId)
),
})
}
}
}
export const changeFilesForSongs = internalMutation({
args: {
songs: v.array(
v.object({ id: v.id("songs"), files: v.record(v.string(), v.string()) })
),
},
handler: async (ctx, args) => {
for (const song of args.songs) {
await ctx.db.patch("songs", song.id, { files: song.files })
}
return
},
})
export const updateArtistCovers = internalMutation({
args: {
artists: v.array(
v.object({ id: v.id("artists"), cover: v.nullable(v.string()) })
),
},
handler: async (ctx, args) => {
for (const { id, cover } of args.artists) {
if ((await ctx.db.get("artists", id)) !== null) {
await ctx.db.patch("artists", id, { cover })
}
}
},
})
export const updateAlbumCovers = internalMutation({
args: {
albums: v.array(
v.object({ id: v.id("albums"), cover: v.nullable(v.string()) })
),
},
handler: async (ctx, args) => {
for (const { id, cover } of args.albums) {
if ((await ctx.db.get("albums", id)) !== null) {
await ctx.db.patch("albums", id, { cover })
}
}
},
})
/**
* Takes the single library scan lease if it is free or expired. The lease
* outlives the action timeout so a crashed scan cannot hold it forever.
*/
export const acquireLibraryScanLock = internalMutation({
args: { token: v.string(), leaseMs: v.number() },
handler: async (ctx, args) => {
const now = Date.now()
const lock = await ctx.db.query("libraryScanLock").first()
if (lock && lock.token !== args.token && lock.expiresAt > now) {
return false
}
const expiresAt = now + args.leaseMs
if (lock) {
await ctx.db.patch(lock._id, { token: args.token, expiresAt })
} else {
await ctx.db.insert("libraryScanLock", { token: args.token, expiresAt })
}
return true
},
})
export const releaseLibraryScanLock = internalMutation({
args: { token: v.string() },
handler: async (ctx, args) => {
const lock = await ctx.db.query("libraryScanLock").first()
if (lock?.token === args.token) {
await ctx.db.delete(lock._id)
}
},
})