457 lines
12 KiB
TypeScript
457 lines
12 KiB
TypeScript
import { getAuthUserId } from "@convex-dev/auth/server"
|
|
import { ConvexError, v } from "convex/values"
|
|
import type { Doc, Id } from "./_generated/dataModel"
|
|
import type { MutationCtx, QueryCtx } from "./_generated/server"
|
|
import { mutation, query } from "./_generated/server"
|
|
import type { BrowsePlaylistDetail, BrowseSong } from "./library"
|
|
|
|
function uniqueIds<T extends string>(ids: T[]): T[] {
|
|
return [...new Set(ids)]
|
|
}
|
|
|
|
async function requireAuth(ctx: MutationCtx) {
|
|
const userId = await getAuthUserId(ctx)
|
|
if (userId === null) {
|
|
throw new ConvexError("Not authenticated")
|
|
}
|
|
return userId
|
|
}
|
|
|
|
async function getAlbumIdsForArtist(ctx: QueryCtx, artistId: Id<"artists">) {
|
|
const albums = await ctx.db
|
|
.query("albums")
|
|
.withIndex("by_artist", (q) => q.eq("artist", artistId))
|
|
.collect()
|
|
return albums.map((album) => album._id)
|
|
}
|
|
|
|
async function getSongIdsForAlbum(ctx: QueryCtx, albumId: Id<"albums">) {
|
|
const songs = await ctx.db
|
|
.query("songs")
|
|
.withIndex("by_album", (q) => q.eq("album", albumId))
|
|
.collect()
|
|
return songs.map((song) => song._id)
|
|
}
|
|
|
|
async function getSongIdsForArtist(ctx: QueryCtx, artistId: Id<"artists">) {
|
|
const songs = await ctx.db
|
|
.query("songs")
|
|
.withIndex("by_artist", (q) => q.eq("albumArtist", artistId))
|
|
.collect()
|
|
return songs.map((song) => song._id)
|
|
}
|
|
|
|
function allAlbumSongsFavorited(
|
|
albumSongIds: Id<"songs">[],
|
|
favoriteSongs: Id<"songs">[]
|
|
) {
|
|
if (albumSongIds.length === 0) {
|
|
return false
|
|
}
|
|
const favorited = new Set(favoriteSongs)
|
|
return albumSongIds.every((id) => favorited.has(id))
|
|
}
|
|
|
|
function allArtistAlbumsFavorited(
|
|
artistAlbumIds: Id<"albums">[],
|
|
favoriteAlbums: Id<"albums">[]
|
|
) {
|
|
if (artistAlbumIds.length === 0) {
|
|
return false
|
|
}
|
|
const favorited = new Set(favoriteAlbums)
|
|
return artistAlbumIds.every((id) => favorited.has(id))
|
|
}
|
|
|
|
async function promoteAlbumIfAllSongsFavorited(
|
|
ctx: MutationCtx,
|
|
favoriteSongs: Id<"songs">[],
|
|
favoriteAlbums: Id<"albums">[],
|
|
albumId: Id<"albums">
|
|
) {
|
|
const albumSongIds = await getSongIdsForAlbum(ctx, albumId)
|
|
if (!allAlbumSongsFavorited(albumSongIds, favoriteSongs)) {
|
|
return favoriteAlbums
|
|
}
|
|
return uniqueIds([...favoriteAlbums, albumId])
|
|
}
|
|
|
|
async function promoteArtistIfAllAlbumsFavorited(
|
|
ctx: MutationCtx,
|
|
favoriteAlbums: Id<"albums">[],
|
|
favoriteArtists: Id<"artists">[],
|
|
artistId: Id<"artists">
|
|
) {
|
|
const artistAlbumIds = await getAlbumIdsForArtist(ctx, artistId)
|
|
if (!allArtistAlbumsFavorited(artistAlbumIds, favoriteAlbums)) {
|
|
return favoriteArtists
|
|
}
|
|
return uniqueIds([...favoriteArtists, artistId])
|
|
}
|
|
|
|
async function cascadeUpFromSongs(
|
|
ctx: MutationCtx,
|
|
favoriteSongs: Id<"songs">[],
|
|
favoriteAlbums: Id<"albums">[],
|
|
favoriteArtists: Id<"artists">[],
|
|
songs: Doc<"songs">[]
|
|
) {
|
|
let albums = favoriteAlbums
|
|
let artists = favoriteArtists
|
|
|
|
const albumIds = new Set(songs.map((song) => song.album))
|
|
for (const albumId of albumIds) {
|
|
albums = await promoteAlbumIfAllSongsFavorited(ctx, favoriteSongs, albums, albumId)
|
|
}
|
|
|
|
const artistIds = new Set(songs.map((song) => song.albumArtist))
|
|
for (const artistId of artistIds) {
|
|
artists = await promoteArtistIfAllAlbumsFavorited(ctx, albums, artists, artistId)
|
|
}
|
|
|
|
return { favoriteAlbums: albums, favoriteArtists: artists }
|
|
}
|
|
|
|
function toBrowseArtist(artist: Doc<"artists">) {
|
|
return {
|
|
id: artist._id,
|
|
name: artist.name,
|
|
photo: artist.cover,
|
|
}
|
|
}
|
|
|
|
async function loadArtistMap(ctx: QueryCtx) {
|
|
const artists = await ctx.db.query("artists").collect()
|
|
return new Map(artists.map((artist) => [artist._id, artist]))
|
|
}
|
|
|
|
async function loadAlbumMap(ctx: QueryCtx) {
|
|
const albums = await ctx.db.query("albums").collect()
|
|
return new Map(albums.map((album) => [album._id, album]))
|
|
}
|
|
|
|
async function toBrowseSong(
|
|
ctx: QueryCtx,
|
|
songId: Id<"songs">,
|
|
artistMap: Map<Id<"artists">, Doc<"artists">>,
|
|
albumMap: Map<Id<"albums">, Doc<"albums">>
|
|
): Promise<BrowseSong | null> {
|
|
const song = await ctx.db.get("songs", songId)
|
|
if (!song) {
|
|
return null
|
|
}
|
|
|
|
const album = albumMap.get(song.album)
|
|
const albumArtist = artistMap.get(song.albumArtist)
|
|
if (!album || !albumArtist) {
|
|
return null
|
|
}
|
|
|
|
return {
|
|
id: song._id,
|
|
title: song.name,
|
|
artist: toBrowseArtist(albumArtist),
|
|
album: {
|
|
id: album._id,
|
|
title: album.name,
|
|
cover: album.cover,
|
|
},
|
|
durationSeconds: Math.round(song.length),
|
|
}
|
|
}
|
|
|
|
export const getUserFavorites = query({
|
|
args: {},
|
|
handler: async (ctx) => {
|
|
const userId = await getAuthUserId(ctx)
|
|
if (userId === null) {
|
|
return {
|
|
favoriteSongs: [] as Id<"songs">[],
|
|
favoriteAlbums: [] as Id<"albums">[],
|
|
favoriteArtists: [] as Id<"artists">[],
|
|
}
|
|
}
|
|
|
|
const user = await ctx.db.get("users", userId)
|
|
if (!user) {
|
|
return {
|
|
favoriteSongs: [] as Id<"songs">[],
|
|
favoriteAlbums: [] as Id<"albums">[],
|
|
favoriteArtists: [] as Id<"artists">[],
|
|
}
|
|
}
|
|
|
|
return {
|
|
favoriteSongs: user.favoriteSongs ?? [],
|
|
favoriteAlbums: user.favoriteAlbums ?? [],
|
|
favoriteArtists: user.favoriteArtists ?? [],
|
|
}
|
|
},
|
|
})
|
|
|
|
export const browseFavoritesPlaylistDetail = query({
|
|
args: {},
|
|
handler: async (ctx): Promise<BrowsePlaylistDetail | null> => {
|
|
const userId = await getAuthUserId(ctx)
|
|
if (userId === null) {
|
|
return null
|
|
}
|
|
|
|
const user = await ctx.db.get("users", userId)
|
|
if (!user) {
|
|
return null
|
|
}
|
|
|
|
const artistMap = await loadArtistMap(ctx)
|
|
const albumMap = await loadAlbumMap(ctx)
|
|
|
|
const songs: BrowseSong[] = []
|
|
for (const songId of user.favoriteSongs ?? []) {
|
|
const song = await toBrowseSong(ctx, songId, artistMap, albumMap)
|
|
if (song) {
|
|
songs.push(song)
|
|
}
|
|
}
|
|
|
|
return {
|
|
id: null,
|
|
isFavorites: true,
|
|
title: "Favorites",
|
|
owner: {
|
|
id: user._id,
|
|
name: user.name,
|
|
},
|
|
cover: null,
|
|
songs,
|
|
isOwner: true,
|
|
isSubscribed: false,
|
|
}
|
|
},
|
|
})
|
|
|
|
export const favoriteSong = mutation({
|
|
args: { songId: v.id("songs") },
|
|
handler: async (ctx, { songId }) => {
|
|
const userId = await requireAuth(ctx)
|
|
const user = await ctx.db.get("users", userId)
|
|
if (!user) {
|
|
throw new ConvexError("User not found")
|
|
}
|
|
|
|
const song = await ctx.db.get("songs", songId)
|
|
if (!song) {
|
|
throw new ConvexError("Song not found")
|
|
}
|
|
|
|
const favoriteSongs = uniqueIds([...(user.favoriteSongs ?? []), songId])
|
|
const cascaded = await cascadeUpFromSongs(
|
|
ctx,
|
|
favoriteSongs,
|
|
user.favoriteAlbums ?? [],
|
|
user.favoriteArtists ?? [],
|
|
[song]
|
|
)
|
|
|
|
await ctx.db.patch(userId, {
|
|
favoriteSongs,
|
|
favoriteAlbums: cascaded.favoriteAlbums,
|
|
favoriteArtists: cascaded.favoriteArtists,
|
|
})
|
|
},
|
|
})
|
|
|
|
export const favoriteSongs = mutation({
|
|
args: { songIds: v.array(v.id("songs")) },
|
|
handler: async (ctx, { songIds }) => {
|
|
const userId = await requireAuth(ctx)
|
|
const user = await ctx.db.get("users", userId)
|
|
if (!user) {
|
|
throw new ConvexError("User not found")
|
|
}
|
|
|
|
const songs: Doc<"songs">[] = []
|
|
for (const id of songIds) {
|
|
const song = await ctx.db.get("songs", id)
|
|
if (song) {
|
|
songs.push(song)
|
|
}
|
|
}
|
|
|
|
const favoriteSongs = uniqueIds([...(user.favoriteSongs ?? []), ...songIds])
|
|
const cascaded = await cascadeUpFromSongs(
|
|
ctx,
|
|
favoriteSongs,
|
|
user.favoriteAlbums ?? [],
|
|
user.favoriteArtists ?? [],
|
|
songs
|
|
)
|
|
|
|
await ctx.db.patch(userId, {
|
|
favoriteSongs,
|
|
favoriteAlbums: cascaded.favoriteAlbums,
|
|
favoriteArtists: cascaded.favoriteArtists,
|
|
})
|
|
},
|
|
})
|
|
|
|
export const unfavoriteSong = mutation({
|
|
args: { songId: v.id("songs") },
|
|
handler: async (ctx, { songId }) => {
|
|
await unfavoriteSongHandler(ctx, songId)
|
|
},
|
|
})
|
|
|
|
export const unfavoriteSongs = mutation({
|
|
args: { songIds: v.array(v.id("songs")) },
|
|
handler: async (ctx, { songIds }) => {
|
|
for (const songId of songIds) {
|
|
await unfavoriteSongHandler(ctx, songId)
|
|
}
|
|
},
|
|
})
|
|
|
|
async function unfavoriteSongHandler(ctx: MutationCtx, songId: Id<"songs">) {
|
|
const userId = await requireAuth(ctx)
|
|
const user = await ctx.db.get("users", userId)
|
|
if (!user) {
|
|
throw new ConvexError("User not found")
|
|
}
|
|
|
|
const song = await ctx.db.get("songs", songId)
|
|
if (!song) {
|
|
return
|
|
}
|
|
|
|
const favoriteSongs = (user.favoriteSongs ?? []).filter((id) => id !== songId)
|
|
let favoriteAlbums = user.favoriteAlbums ?? []
|
|
let favoriteArtists = user.favoriteArtists ?? []
|
|
|
|
if (favoriteAlbums.includes(song.album)) {
|
|
favoriteAlbums = favoriteAlbums.filter((id) => id !== song.album)
|
|
}
|
|
|
|
if (favoriteArtists.includes(song.albumArtist)) {
|
|
favoriteArtists = favoriteArtists.filter((id) => id !== song.albumArtist)
|
|
favoriteAlbums = favoriteAlbums.filter((id) => id !== song.album)
|
|
}
|
|
|
|
await ctx.db.patch(userId, {
|
|
favoriteSongs,
|
|
favoriteAlbums,
|
|
favoriteArtists,
|
|
})
|
|
}
|
|
|
|
export const favoriteAlbum = mutation({
|
|
args: { albumId: v.id("albums") },
|
|
handler: async (ctx, { albumId }) => {
|
|
const userId = await requireAuth(ctx)
|
|
const user = await ctx.db.get("users", userId)
|
|
if (!user) {
|
|
throw new ConvexError("User not found")
|
|
}
|
|
|
|
const album = await ctx.db.get("albums", albumId)
|
|
if (!album) {
|
|
throw new ConvexError("Album not found")
|
|
}
|
|
|
|
const songIds = await getSongIdsForAlbum(ctx, albumId)
|
|
|
|
const favoriteAlbums = uniqueIds([...(user.favoriteAlbums ?? []), albumId])
|
|
const favoriteSongs = uniqueIds([...(user.favoriteSongs ?? []), ...songIds])
|
|
const favoriteArtists = await promoteArtistIfAllAlbumsFavorited(
|
|
ctx,
|
|
favoriteAlbums,
|
|
user.favoriteArtists ?? [],
|
|
album.artist
|
|
)
|
|
|
|
await ctx.db.patch(userId, {
|
|
favoriteAlbums,
|
|
favoriteSongs,
|
|
favoriteArtists,
|
|
})
|
|
},
|
|
})
|
|
|
|
export const unfavoriteAlbum = mutation({
|
|
args: { albumId: v.id("albums") },
|
|
handler: async (ctx, { albumId }) => {
|
|
const userId = await requireAuth(ctx)
|
|
const user = await ctx.db.get("users", userId)
|
|
if (!user) {
|
|
throw new ConvexError("User not found")
|
|
}
|
|
|
|
const album = await ctx.db.get("albums", albumId)
|
|
if (!album) {
|
|
return
|
|
}
|
|
|
|
const albumSongIds = await getSongIdsForAlbum(ctx, albumId)
|
|
const removeSongs = new Set(albumSongIds)
|
|
|
|
const favoriteAlbums = (user.favoriteAlbums ?? []).filter((id) => id !== albumId)
|
|
const favoriteSongs = (user.favoriteSongs ?? []).filter((id) => !removeSongs.has(id))
|
|
let favoriteArtists = user.favoriteArtists ?? []
|
|
|
|
if (favoriteArtists.includes(album.artist)) {
|
|
favoriteArtists = favoriteArtists.filter((id) => id !== album.artist)
|
|
}
|
|
|
|
await ctx.db.patch(userId, {
|
|
favoriteSongs,
|
|
favoriteAlbums,
|
|
favoriteArtists,
|
|
})
|
|
},
|
|
})
|
|
|
|
export const favoriteArtist = mutation({
|
|
args: { artistId: v.id("artists") },
|
|
handler: async (ctx, { artistId }) => {
|
|
const userId = await requireAuth(ctx)
|
|
const user = await ctx.db.get("users", userId)
|
|
if (!user) {
|
|
throw new ConvexError("User not found")
|
|
}
|
|
|
|
const artist = await ctx.db.get("artists", artistId)
|
|
if (!artist) {
|
|
throw new ConvexError("Artist not found")
|
|
}
|
|
|
|
const albumIds = await getAlbumIdsForArtist(ctx, artistId)
|
|
const songIds = await getSongIdsForArtist(ctx, artistId)
|
|
|
|
await ctx.db.patch(userId, {
|
|
favoriteArtists: uniqueIds([...(user.favoriteArtists ?? []), artistId]),
|
|
favoriteAlbums: uniqueIds([...(user.favoriteAlbums ?? []), ...albumIds]),
|
|
favoriteSongs: uniqueIds([...(user.favoriteSongs ?? []), ...songIds]),
|
|
})
|
|
},
|
|
})
|
|
|
|
export const unfavoriteArtist = mutation({
|
|
args: { artistId: v.id("artists") },
|
|
handler: async (ctx, { artistId }) => {
|
|
const userId = await requireAuth(ctx)
|
|
const user = await ctx.db.get("users", userId)
|
|
if (!user) {
|
|
throw new ConvexError("User not found")
|
|
}
|
|
|
|
const albumIds = await getAlbumIdsForArtist(ctx, artistId)
|
|
const songIds = await getSongIdsForArtist(ctx, artistId)
|
|
const removeAlbums = new Set(albumIds)
|
|
const removeSongs = new Set(songIds)
|
|
|
|
await ctx.db.patch(userId, {
|
|
favoriteArtists: (user.favoriteArtists ?? []).filter((id) => id !== artistId),
|
|
favoriteAlbums: (user.favoriteAlbums ?? []).filter((id) => !removeAlbums.has(id)),
|
|
favoriteSongs: (user.favoriteSongs ?? []).filter((id) => !removeSongs.has(id)),
|
|
})
|
|
},
|
|
})
|