1081 lines
27 KiB
TypeScript
1081 lines
27 KiB
TypeScript
import { paginationOptsValidator } from "convex/server"
|
|
import { mutation, query } from "./_generated/server"
|
|
import { v } from "convex/values"
|
|
import type { Doc, Id } from "./_generated/dataModel"
|
|
import type { QueryCtx } from "./_generated/server"
|
|
import type { PaginationOptions, PaginationResult } from "convex/server"
|
|
|
|
export type BrowseArtist = {
|
|
id: Id<"artists">
|
|
name: string
|
|
photo: string | null
|
|
}
|
|
|
|
export type BrowseAlbum = {
|
|
id: Id<"albums">
|
|
title: string
|
|
artist: BrowseArtist
|
|
cover: string | null
|
|
}
|
|
|
|
export type BrowseSong = {
|
|
id: Id<"songs">
|
|
title: string
|
|
artist: BrowseArtist
|
|
album: Pick<BrowseAlbum, "id" | "title" | "cover">
|
|
durationSeconds: number
|
|
explicit?: boolean
|
|
}
|
|
|
|
export type BrowseAlbumTrack = {
|
|
id: Id<"songs">
|
|
title: string
|
|
track: number
|
|
diskNumber: number | null
|
|
durationSeconds: number
|
|
/** Present when track artist(s) differ from the album artist. */
|
|
artists: string[] | null
|
|
}
|
|
|
|
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] : []
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
export type BrowseAlbumDetail = BrowseAlbum & {
|
|
year: number | null
|
|
genre: string | null
|
|
tracks: BrowseAlbumTrack[]
|
|
}
|
|
|
|
export type BrowseArtistDetail = {
|
|
artist: BrowseArtist
|
|
albums: BrowseAlbum[]
|
|
recentlyAdded: BrowseAlbum[]
|
|
recentlyPlayed: BrowseAlbum[]
|
|
}
|
|
|
|
export type PlaylistSummary = {
|
|
id: Id<"playlists">
|
|
title: string
|
|
owner: string
|
|
cover: string | null
|
|
}
|
|
|
|
export type BrowsePlaylistOwner = {
|
|
id: Id<"users">
|
|
name: string
|
|
}
|
|
|
|
export type BrowsePlaylistDetail = {
|
|
id: Id<"playlists"> | null
|
|
isFavorites?: boolean
|
|
title: string
|
|
owner: BrowsePlaylistOwner
|
|
cover: string | null
|
|
songs: BrowseSong[]
|
|
isOwner: boolean
|
|
isSubscribed: boolean
|
|
}
|
|
|
|
export type SidebarPlaylists = {
|
|
owned: PlaylistSummary[]
|
|
subscribed: PlaylistSummary[]
|
|
}
|
|
|
|
export type SearchTopResultItem =
|
|
| { kind: "song"; item: BrowseSong }
|
|
| { kind: "album"; item: BrowseAlbum }
|
|
| { kind: "artist"; item: BrowseArtist }
|
|
|
|
export type LibrarySearchResults = {
|
|
topResults: SearchTopResultItem[]
|
|
artists: BrowseArtist[]
|
|
albums: BrowseAlbum[]
|
|
songs: BrowseSong[]
|
|
}
|
|
|
|
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]))
|
|
}
|
|
|
|
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,
|
|
}
|
|
}
|
|
|
|
export async function browseSongsFromIds(
|
|
ctx: QueryCtx,
|
|
songIds: Id<"songs">[]
|
|
): Promise<BrowseSong[]> {
|
|
const songs: BrowseSong[] = []
|
|
for (const songId of songIds) {
|
|
const song = await ctx.db.get("songs", songId)
|
|
if (!song) {
|
|
continue
|
|
}
|
|
const album = await ctx.db.get("albums", song.album)
|
|
const albumArtist = await ctx.db.get("artists", song.albumArtist)
|
|
if (!album || !albumArtist) {
|
|
continue
|
|
}
|
|
songs.push(toBrowseSong(song, album, albumArtist))
|
|
}
|
|
return songs
|
|
}
|
|
|
|
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) => {
|
|
const artistMap = await loadArtistMap(ctx)
|
|
const albums = await ctx.db.query("albums").collect()
|
|
|
|
return 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) => {
|
|
const artists = await ctx.db.query("artists").collect()
|
|
return artists
|
|
.map(toBrowseArtist)
|
|
.sort((a, b) => a.name.localeCompare(b.name))
|
|
},
|
|
})
|
|
|
|
export const browseSongs = query({
|
|
args: {},
|
|
handler: async (ctx) => {
|
|
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()
|
|
|
|
return songs
|
|
.flatMap((song) => {
|
|
const album = albumMap.get(song.album)
|
|
const albumArtist = artistMap.get(song.albumArtist)
|
|
if (!album || !albumArtist) {
|
|
return []
|
|
}
|
|
return [toBrowseSong(song, album, albumArtist)]
|
|
})
|
|
.sort((a, b) => a.title.localeCompare(b.title))
|
|
},
|
|
})
|
|
|
|
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 = {
|
|
groupIndex: number
|
|
songIndex: number
|
|
}
|
|
|
|
function compareSongNames(
|
|
a: string,
|
|
b: string,
|
|
direction: SongsSortDirection
|
|
): number {
|
|
const comparison = a.localeCompare(b)
|
|
return direction === "asc" ? comparison : -comparison
|
|
}
|
|
|
|
function mapSongToBrowse(
|
|
song: Doc<"songs">,
|
|
artistMap: Map<Id<"artists">, Doc<"artists">>,
|
|
albumMap: Map<Id<"albums">, Doc<"albums">>
|
|
): BrowseSong | null {
|
|
const album = albumMap.get(song.album)
|
|
const albumArtist = artistMap.get(song.albumArtist)
|
|
if (!album || !albumArtist) {
|
|
return null
|
|
}
|
|
return toBrowseSong(song, album, albumArtist)
|
|
}
|
|
|
|
async function paginateSongsByTitle(
|
|
ctx: QueryCtx,
|
|
paginationOpts: PaginationOptions,
|
|
sortDirection: SongsSortDirection,
|
|
artistMap: Map<Id<"artists">, Doc<"artists">>,
|
|
albumMap: Map<Id<"albums">, Doc<"albums">>
|
|
): Promise<PaginationResult<BrowseSong>> {
|
|
const result = await ctx.db
|
|
.query("songs")
|
|
.withIndex("by_name")
|
|
.order(sortDirection)
|
|
.paginate(paginationOpts)
|
|
|
|
return {
|
|
...result,
|
|
page: result.page.flatMap((song) => {
|
|
const mapped = mapSongToBrowse(song, artistMap, albumMap)
|
|
return mapped ? [mapped] : []
|
|
}),
|
|
}
|
|
}
|
|
|
|
async function paginateSongsByGroup(
|
|
ctx: QueryCtx,
|
|
paginationOpts: PaginationOptions,
|
|
sortDirection: SongsSortDirection,
|
|
artistMap: Map<Id<"artists">, Doc<"artists">>,
|
|
albumMap: Map<Id<"albums">, Doc<"albums">>,
|
|
sortKey: "artist" | "album"
|
|
): Promise<PaginationResult<BrowseSong>> {
|
|
const cursor: GroupedSongsCursor = paginationOpts.cursor
|
|
? (JSON.parse(paginationOpts.cursor) as GroupedSongsCursor)
|
|
: { groupIndex: 0, songIndex: 0 }
|
|
|
|
const groups =
|
|
sortKey === "artist"
|
|
? [...artistMap.values()].sort((a, b) =>
|
|
compareSongNames(a.name, b.name, sortDirection)
|
|
)
|
|
: [...albumMap.values()].sort((a, b) =>
|
|
compareSongNames(a.name, b.name, sortDirection)
|
|
)
|
|
|
|
const page: BrowseSong[] = []
|
|
let { groupIndex, songIndex } = cursor
|
|
|
|
while (page.length < paginationOpts.numItems && groupIndex < groups.length) {
|
|
const group = groups[groupIndex]
|
|
const songs = await ctx.db
|
|
.query("songs")
|
|
.withIndex(sortKey === "artist" ? "by_artist" : "by_album", (q) =>
|
|
sortKey === "artist"
|
|
? q.eq("albumArtist", group._id as Id<"artists">)
|
|
: q.eq("album", group._id as Id<"albums">)
|
|
)
|
|
.collect()
|
|
|
|
songs.sort((a, b) => compareSongNames(a.name, b.name, sortDirection))
|
|
|
|
while (songIndex < songs.length && page.length < paginationOpts.numItems) {
|
|
const mapped = mapSongToBrowse(songs[songIndex], artistMap, albumMap)
|
|
if (mapped) {
|
|
page.push(mapped)
|
|
}
|
|
songIndex++
|
|
}
|
|
|
|
if (songIndex >= songs.length) {
|
|
groupIndex++
|
|
songIndex = 0
|
|
}
|
|
}
|
|
|
|
const isDone = groupIndex >= groups.length
|
|
|
|
return {
|
|
page,
|
|
isDone,
|
|
continueCursor: isDone
|
|
? ""
|
|
: JSON.stringify({ groupIndex, 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 artistMap = await loadArtistMap(ctx)
|
|
const albums = await ctx.db.query("albums").collect()
|
|
const albumMap = new Map(albums.map((album) => [album._id, album]))
|
|
|
|
const groups =
|
|
sortKey === "artist"
|
|
? [...artistMap.values()].sort((a, b) =>
|
|
compareSongNames(a.name, b.name, sortDirection)
|
|
)
|
|
: [...albumMap.values()].sort((a, b) =>
|
|
compareSongNames(a.name, b.name, sortDirection)
|
|
)
|
|
|
|
const songIds: Id<"songs">[] = []
|
|
|
|
for (const group of groups) {
|
|
const songs = await ctx.db
|
|
.query("songs")
|
|
.withIndex(sortKey === "artist" ? "by_artist" : "by_album", (q) =>
|
|
sortKey === "artist"
|
|
? q.eq("albumArtist", group._id as Id<"artists">)
|
|
: q.eq("album", group._id as Id<"albums">)
|
|
)
|
|
.collect()
|
|
|
|
songs.sort((a, b) => compareSongNames(a.name, b.name, sortDirection))
|
|
for (const song of songs) {
|
|
songIds.push(song._id)
|
|
}
|
|
}
|
|
|
|
return songIds
|
|
}
|
|
|
|
export const browseSongsPaginated = query({
|
|
args: {
|
|
paginationOpts: paginationOptsValidator,
|
|
sortKey: songsSortKeyValidator,
|
|
sortDirection: songsSortDirectionValidator,
|
|
},
|
|
handler: async (ctx, args) => {
|
|
const artistMap = await loadArtistMap(ctx)
|
|
const albums = await ctx.db.query("albums").collect()
|
|
const albumMap = new Map(albums.map((album) => [album._id, album]))
|
|
|
|
if (args.sortKey === "title") {
|
|
return paginateSongsByTitle(
|
|
ctx,
|
|
args.paginationOpts,
|
|
args.sortDirection,
|
|
artistMap,
|
|
albumMap
|
|
)
|
|
}
|
|
|
|
return paginateSongsByGroup(
|
|
ctx,
|
|
args.paginationOpts,
|
|
args.sortDirection,
|
|
artistMap,
|
|
albumMap,
|
|
args.sortKey
|
|
)
|
|
},
|
|
})
|
|
|
|
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)
|
|
if (!album) {
|
|
return null
|
|
}
|
|
|
|
const artist = await ctx.db.get("artists", album.artist)
|
|
if (!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,
|
|
tracks: songs.map((song) => toBrowseAlbumTrack(song, artist.name)),
|
|
}
|
|
},
|
|
})
|
|
|
|
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()
|
|
|
|
const recentlyAdded = [...albums]
|
|
.sort((a, b) => b._creationTime - a._creationTime)
|
|
.map((album) => toBrowseAlbum(album, artist))
|
|
|
|
const recentlyPlayed = [...albums]
|
|
.sort((a, b) => a.name.localeCompare(b.name))
|
|
.map((album) => toBrowseAlbum(album, artist))
|
|
|
|
return {
|
|
artist: toBrowseArtist(artist),
|
|
albums: recentlyPlayed,
|
|
recentlyAdded,
|
|
recentlyPlayed,
|
|
}
|
|
},
|
|
})
|
|
|
|
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
|
|
)
|
|
}
|
|
|
|
export const searchLibrary = query({
|
|
args: { query: v.string() },
|
|
handler: async (ctx, args) => {
|
|
const queryText = args.query.trim().toLowerCase()
|
|
if (!queryText) {
|
|
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 topResults: SearchTopResultItem[] = [
|
|
...songResults,
|
|
...albumResults,
|
|
...artistResults,
|
|
]
|
|
.sort((a, b) => b.score - a.score)
|
|
.slice(0, 6)
|
|
.map(toSearchTopResultItem)
|
|
|
|
const result: LibrarySearchResults = {
|
|
topResults,
|
|
artists: artistResults.map((result) => result.item),
|
|
albums: albumResults.map((result) => result.item),
|
|
songs: songResults.map((result) => result.item),
|
|
}
|
|
return result
|
|
},
|
|
})
|
|
|
|
export const browseRecentlyAdded = query({
|
|
args: {},
|
|
handler: async (ctx) => {
|
|
const artistMap = await loadArtistMap(ctx)
|
|
const albums = await ctx.db.query("albums").collect()
|
|
|
|
return albums
|
|
.flatMap((album) => {
|
|
const artist = artistMap.get(album.artist)
|
|
return artist ? [{ album, artist, addedAt: album._creationTime }] : []
|
|
})
|
|
.sort((a, b) => b.addedAt - a.addedAt)
|
|
.map(({ album, artist }) => toBrowseAlbum(album, artist))
|
|
},
|
|
})
|
|
|
|
export const getArtists = query({
|
|
args: {},
|
|
handler: async (ctx) => {
|
|
return await ctx.db.query("artists").collect()
|
|
},
|
|
})
|
|
|
|
export const getAlbums = query({
|
|
args: {},
|
|
handler: async (ctx) => {
|
|
return await ctx.db.query("albums").collect()
|
|
},
|
|
})
|
|
|
|
export const getAlbumsInArtist = query({
|
|
args: { artistID: v.id("artists") },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db
|
|
.query("albums")
|
|
.withIndex("by_artist", (q) => q.eq("artist", args.artistID))
|
|
.collect()
|
|
},
|
|
})
|
|
|
|
export const getSongs = query({
|
|
args: {},
|
|
handler: async (ctx) => {
|
|
return await ctx.db.query("songs").collect()
|
|
},
|
|
})
|
|
|
|
export const getSongsInArtist = query({
|
|
args: { artistID: v.id("artists") },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db
|
|
.query("songs")
|
|
.withIndex("by_artist", (q) => q.eq("albumArtist", args.artistID))
|
|
.collect()
|
|
},
|
|
})
|
|
|
|
export const getSongsInAlbum = query({
|
|
args: { albumID: v.id("albums") },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db
|
|
.query("songs")
|
|
.withIndex("by_album", (q) => q.eq("album", args.albumID))
|
|
.collect()
|
|
},
|
|
})
|
|
|
|
export const getArtist = query({
|
|
args: { id: v.id("artists") },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db.get("artists", args.id)
|
|
},
|
|
})
|
|
|
|
export const getArtistByName = query({
|
|
args: { name: v.string() },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db
|
|
.query("artists")
|
|
.withIndex("by_name", (q) => q.eq("name", args.name))
|
|
.first()
|
|
},
|
|
})
|
|
|
|
export const getAlbum = query({
|
|
args: { id: v.id("albums") },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db.get("albums", args.id)
|
|
},
|
|
})
|
|
|
|
export const getAlbumByName = query({
|
|
args: { name: v.string() },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db
|
|
.query("albums")
|
|
.withIndex("by_name", (q) => q.eq("name", args.name))
|
|
.first()
|
|
},
|
|
})
|
|
|
|
export const getAlbumByAll = query({
|
|
args: { folder: v.string(), artist: v.id("artists") },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db
|
|
.query("albums")
|
|
.withIndex("by_all", (q) =>
|
|
q
|
|
.eq("artist", args.artist)
|
|
.eq("folder", args.folder)
|
|
)
|
|
.first()
|
|
},
|
|
})
|
|
|
|
export const getPlaylist = query({
|
|
args: { id: v.id("playlists") },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db.get("playlists", args.id)
|
|
},
|
|
})
|
|
|
|
export const getSong = query({
|
|
args: { id: v.id("songs") },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db.get("songs", args.id)
|
|
},
|
|
})
|
|
|
|
export const getSongByName = query({
|
|
args: { name: v.string() },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db
|
|
.query("songs")
|
|
.withIndex("by_name", (q) => q.eq("name", args.name))
|
|
.first()
|
|
},
|
|
})
|
|
|
|
export const getSongByAll = query({
|
|
args: {
|
|
name: v.string(),
|
|
albumArtist: v.id("artists"),
|
|
album: v.id("albums"),
|
|
},
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db
|
|
.query("songs")
|
|
.withIndex("by_all", (q) =>
|
|
q
|
|
.eq("name", args.name)
|
|
.eq("albumArtist", args.albumArtist)
|
|
.eq("album", args.album)
|
|
)
|
|
.first()
|
|
},
|
|
})
|
|
|
|
export const createArtist = mutation({
|
|
args: { name: v.string(), folder: v.string(), cover: v.nullable(v.string()) },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db.insert("artists", args)
|
|
},
|
|
})
|
|
|
|
export const createArtists = mutation({
|
|
args: {
|
|
artists: v.array(
|
|
v.object({ name: v.string(), folder: v.string(), cover: v.nullable(v.string()) })
|
|
),
|
|
},
|
|
handler: async (ctx, args) => {
|
|
for (const artist of args.artists) {
|
|
await ctx.db.insert("artists", artist)
|
|
}
|
|
},
|
|
})
|
|
|
|
export const createAlbum = mutation({
|
|
args: {
|
|
name: v.string(),
|
|
folder: v.string(),
|
|
cover: v.nullable(v.string()),
|
|
artist: v.id("artists"),
|
|
},
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db.insert("albums", args)
|
|
},
|
|
})
|
|
|
|
export const createAlbums = mutation({
|
|
args: {
|
|
albums: v.array(
|
|
v.object({
|
|
name: v.string(),
|
|
folder: v.string(),
|
|
cover: v.nullable(v.string()),
|
|
artist: v.id("artists"),
|
|
})
|
|
),
|
|
},
|
|
handler: async (ctx, args) => {
|
|
for (const album of args.albums) {
|
|
await ctx.db.insert("albums", album)
|
|
}
|
|
},
|
|
})
|
|
|
|
export const updateAlbumName = mutation({
|
|
args: {
|
|
id: v.id("albums"),
|
|
newName: v.string(),
|
|
},
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db.patch("albums", args.id, { name: args.newName })
|
|
},
|
|
})
|
|
|
|
export const createSong = mutation({
|
|
args: {
|
|
name: v.string(),
|
|
files: v.record(v.string(), v.string()),
|
|
album: v.id("albums"),
|
|
artist: v.union(v.string(), v.array(v.string())),
|
|
albumArtist: v.id("artists"),
|
|
length: v.number(),
|
|
diskNumber: v.nullable(v.number()),
|
|
track: v.number(),
|
|
year: v.number(),
|
|
genres: v.array(v.string()),
|
|
},
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db.insert("songs", args)
|
|
},
|
|
})
|
|
|
|
export const createSongs = mutation({
|
|
args: {
|
|
songs: v.array(
|
|
v.object({
|
|
name: v.string(),
|
|
files: v.record(v.string(), v.string()),
|
|
album: v.id("albums"),
|
|
artist: v.union(v.string(), v.array(v.string())),
|
|
albumArtist: v.id("artists"),
|
|
length: v.number(),
|
|
diskNumber: v.nullable(v.number()),
|
|
track: v.number(),
|
|
year: v.number(),
|
|
genres: v.array(v.string()),
|
|
})
|
|
),
|
|
},
|
|
handler: async (ctx, args) => {
|
|
for (const song of args.songs) {
|
|
await ctx.db.insert("songs", song)
|
|
}
|
|
|
|
return
|
|
},
|
|
})
|
|
|
|
export const purgeSongsFromUsersAndPlaylists = mutation({
|
|
args: { ids: v.array(v.id("songs")) },
|
|
handler: async (ctx, args) => {
|
|
const remove = new Set(args.ids)
|
|
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 user of await ctx.db.query("users").collect()) {
|
|
const favoriteSongs = user.favoriteSongs
|
|
if (favoriteSongs?.some((songId) => remove.has(songId))) {
|
|
await ctx.db.patch(user._id, {
|
|
favoriteSongs: favoriteSongs.filter((songId) => !remove.has(songId)),
|
|
})
|
|
}
|
|
}
|
|
},
|
|
})
|
|
|
|
export const purgeAlbumsFromUsers = mutation({
|
|
args: { ids: v.array(v.id("albums")) },
|
|
handler: async (ctx, args) => {
|
|
const remove = new Set(args.ids)
|
|
if (remove.size === 0) {
|
|
return
|
|
}
|
|
|
|
for (const user of await ctx.db.query("users").collect()) {
|
|
const favoriteAlbums = user.favoriteAlbums
|
|
if (favoriteAlbums?.some((albumId) => remove.has(albumId))) {
|
|
await ctx.db.patch(user._id, {
|
|
favoriteAlbums: favoriteAlbums.filter(
|
|
(albumId) => !remove.has(albumId)
|
|
),
|
|
})
|
|
}
|
|
}
|
|
},
|
|
})
|
|
|
|
export const purgeArtistsFromUsers = mutation({
|
|
args: { ids: v.array(v.id("artists")) },
|
|
handler: async (ctx, args) => {
|
|
const remove = new Set(args.ids)
|
|
if (remove.size === 0) {
|
|
return
|
|
}
|
|
|
|
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 removeArtist = mutation({
|
|
args: { id: v.id("artists") },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db.delete("artists", args.id)
|
|
},
|
|
})
|
|
|
|
export const removeArtists = mutation({
|
|
args: { ids: v.array(v.id("artists")) },
|
|
handler: async (ctx, args) => {
|
|
for (const id of args.ids) {
|
|
await ctx.db.delete("artists", id)
|
|
}
|
|
},
|
|
})
|
|
|
|
export const removeAlbum = mutation({
|
|
args: { id: v.id("albums") },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db.delete("albums", args.id)
|
|
},
|
|
})
|
|
|
|
export const removeAlbums = mutation({
|
|
args: { ids: v.array(v.id("albums")) },
|
|
handler: async (ctx, args) => {
|
|
for (const id of args.ids) {
|
|
await ctx.db.delete("albums", id)
|
|
}
|
|
},
|
|
})
|
|
|
|
export const removeSong = mutation({
|
|
args: { id: v.id("songs") },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db.delete("songs", args.id)
|
|
},
|
|
})
|
|
|
|
export const changeFilesForSong = mutation({
|
|
args: { id: v.id("songs"), files: v.record(v.string(), v.string()) },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db.patch("songs", args.id, { files: args.files })
|
|
},
|
|
})
|
|
|
|
export const changeFilesForSongs = mutation({
|
|
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 updateArtistCover = mutation({
|
|
args: { id: v.id("artists"), cover: v.nullable(v.string()) },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db.patch("artists", args.id, { cover: args.cover })
|
|
},
|
|
})
|
|
|
|
export const updateAlbumCover = mutation({
|
|
args: { id: v.id("albums"), cover: v.nullable(v.string()) },
|
|
handler: async (ctx, args) => {
|
|
return await ctx.db.patch("albums", args.id, { cover: args.cover })
|
|
},
|
|
})
|
|
|
|
export const removeSongs = mutation({
|
|
args: { ids: v.array(v.id("songs")) },
|
|
handler: async (ctx, args) => {
|
|
for (const id of args.ids) {
|
|
await ctx.db.delete("songs", id)
|
|
}
|
|
},
|
|
})
|