573 lines
16 KiB
TypeScript
573 lines
16 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 { internal } from "./_generated/api"
|
|
import { parseImageDataUrl } from "./images"
|
|
import { chunk, COVER_GRID_ALBUMS } from "./limits"
|
|
import {
|
|
drawCoverAlbums,
|
|
playlistCoverVersion,
|
|
refreshAutomaticCover,
|
|
} from "./playlistCover"
|
|
import type {
|
|
BrowsePlaylistDetail,
|
|
BrowsePlaylistSummary,
|
|
OwnedPlaylistForAdd,
|
|
PlaylistSummary,
|
|
SidebarPlaylists,
|
|
} from "./library"
|
|
import {
|
|
browseSongsFromIds,
|
|
compareAlbumSongs,
|
|
requireSignedIn,
|
|
} from "./library"
|
|
|
|
function toPlaylistSummary(
|
|
playlist: Doc<"playlists">,
|
|
ownerName: string
|
|
): PlaylistSummary {
|
|
return {
|
|
id: playlist._id,
|
|
title: playlist.name,
|
|
owner: ownerName,
|
|
cover: playlistCoverVersion(playlist),
|
|
}
|
|
}
|
|
|
|
async function loadPlaylists(ctx: QueryCtx, playlistIds: Id<"playlists">[]) {
|
|
const playlists = await Promise.all(
|
|
[...new Set(playlistIds)].map((playlistId) =>
|
|
ctx.db.get("playlists", playlistId)
|
|
)
|
|
)
|
|
return playlists.filter(
|
|
(playlist): playlist is Doc<"playlists"> => playlist !== null
|
|
)
|
|
}
|
|
|
|
async function summarizePlaylists(
|
|
ctx: QueryCtx,
|
|
playlists: Doc<"playlists">[]
|
|
) {
|
|
const ownerIds = [...new Set(playlists.map((playlist) => 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] : []))
|
|
)
|
|
return playlists.map((playlist) =>
|
|
toPlaylistSummary(playlist, ownerMap.get(playlist.owner)?.name ?? "Unknown")
|
|
)
|
|
}
|
|
|
|
async function requireAuth(ctx: MutationCtx) {
|
|
const userId = await getAuthUserId(ctx)
|
|
if (userId === null) {
|
|
throw new ConvexError("Not authenticated")
|
|
}
|
|
return userId
|
|
}
|
|
|
|
async function requirePlaylistOwner(
|
|
ctx: MutationCtx,
|
|
playlistId: Id<"playlists">
|
|
) {
|
|
const userId = await requireAuth(ctx)
|
|
const playlist = await ctx.db.get("playlists", playlistId)
|
|
if (!playlist) {
|
|
throw new ConvexError("Playlist not found")
|
|
}
|
|
if (playlist.owner !== userId) {
|
|
throw new ConvexError("Not authorized")
|
|
}
|
|
return { userId, playlist }
|
|
}
|
|
|
|
async function browsePlaylistSummaryHandler(
|
|
ctx: QueryCtx,
|
|
playlistId: Id<"playlists">
|
|
): Promise<BrowsePlaylistSummary | null> {
|
|
const playlist = await ctx.db.get("playlists", playlistId)
|
|
if (!playlist) {
|
|
return null
|
|
}
|
|
|
|
const owner = await ctx.db.get("users", playlist.owner)
|
|
if (!owner) {
|
|
return null
|
|
}
|
|
|
|
const userId = await getAuthUserId(ctx)
|
|
const currentUser = userId ? await ctx.db.get("users", userId) : null
|
|
const isOwner = userId === playlist.owner
|
|
const isSubscribed =
|
|
currentUser?.subscribedPlaylists?.includes(playlistId) ?? false
|
|
|
|
return {
|
|
id: playlist._id,
|
|
title: playlist.name,
|
|
owner: {
|
|
id: owner._id,
|
|
name: owner.name,
|
|
},
|
|
cover: playlistCoverVersion(playlist),
|
|
isOwner,
|
|
isSubscribed,
|
|
songIds: playlist.songs,
|
|
}
|
|
}
|
|
|
|
/** Public: shared /playlist links render this without a session. */
|
|
export const browsePlaylistDetail = query({
|
|
args: { id: v.id("playlists") },
|
|
handler: async (ctx, args): Promise<BrowsePlaylistDetail | null> => {
|
|
const summary = await browsePlaylistSummaryHandler(ctx, args.id)
|
|
if (!summary) {
|
|
return null
|
|
}
|
|
|
|
const songs = await browseSongsFromIds(ctx, summary.songIds)
|
|
|
|
return {
|
|
id: summary.id,
|
|
title: summary.title,
|
|
owner: summary.owner,
|
|
cover: summary.cover,
|
|
songs,
|
|
isOwner: summary.isOwner,
|
|
isSubscribed: summary.isSubscribed,
|
|
}
|
|
},
|
|
})
|
|
|
|
export const listOwnedPlaylists = query({
|
|
args: {},
|
|
handler: async (ctx) => {
|
|
const userId = await getAuthUserId(ctx)
|
|
if (userId === null) {
|
|
return []
|
|
}
|
|
|
|
const playlists = await ctx.db
|
|
.query("playlists")
|
|
.withIndex("by_owner", (q) => q.eq("owner", userId))
|
|
.collect()
|
|
|
|
const user = await ctx.db.get("users", userId)
|
|
const ownerName = user?.name ?? "You"
|
|
|
|
return playlists
|
|
.map((playlist): OwnedPlaylistForAdd => ({
|
|
...toPlaylistSummary(playlist, ownerName),
|
|
songIds: playlist.songs,
|
|
}))
|
|
.sort((a, b) => a.title.localeCompare(b.title))
|
|
},
|
|
})
|
|
|
|
export const listSidebarPlaylists = query({
|
|
args: {},
|
|
handler: async (ctx): Promise<SidebarPlaylists> => {
|
|
const userId = await getAuthUserId(ctx)
|
|
if (userId === null) {
|
|
return { owned: [], subscribed: [] }
|
|
}
|
|
|
|
const user = await ctx.db.get("users", userId)
|
|
if (!user) {
|
|
return { owned: [], subscribed: [] }
|
|
}
|
|
|
|
const ownedDocs = await ctx.db
|
|
.query("playlists")
|
|
.withIndex("by_owner", (q) => q.eq("owner", userId))
|
|
.collect()
|
|
|
|
const owned = ownedDocs
|
|
.map((playlist) => toPlaylistSummary(playlist, user.name))
|
|
.sort((a, b) => a.title.localeCompare(b.title))
|
|
|
|
const subscribedDocs = (
|
|
await loadPlaylists(ctx, user.subscribedPlaylists ?? [])
|
|
).filter((playlist) => playlist.owner !== userId)
|
|
const subscribed = await summarizePlaylists(ctx, subscribedDocs)
|
|
subscribed.sort((a, b) => a.title.localeCompare(b.title))
|
|
|
|
return { owned, subscribed }
|
|
},
|
|
})
|
|
|
|
export const searchPlaylists = query({
|
|
args: { query: v.string() },
|
|
handler: async (ctx, args) => {
|
|
const queryText = args.query.trim().toLowerCase()
|
|
if (!queryText) {
|
|
return []
|
|
}
|
|
|
|
const userId = await getAuthUserId(ctx)
|
|
if (userId === null) {
|
|
return []
|
|
}
|
|
|
|
const user = await ctx.db.get("users", userId)
|
|
if (!user) {
|
|
return []
|
|
}
|
|
|
|
const ownedDocs = await ctx.db
|
|
.query("playlists")
|
|
.withIndex("by_owner", (q) => q.eq("owner", userId))
|
|
.collect()
|
|
|
|
const ownedIds = new Set(ownedDocs.map((playlist) => playlist._id))
|
|
const matches: PlaylistSummary[] = []
|
|
|
|
for (const playlist of ownedDocs) {
|
|
if (playlist.name.toLowerCase().includes(queryText)) {
|
|
matches.push(toPlaylistSummary(playlist, user.name))
|
|
}
|
|
}
|
|
|
|
const subscribedDocs = (
|
|
await loadPlaylists(ctx, user.subscribedPlaylists ?? [])
|
|
).filter(
|
|
(playlist) =>
|
|
!ownedIds.has(playlist._id) &&
|
|
playlist.name.toLowerCase().includes(queryText)
|
|
)
|
|
matches.push(...(await summarizePlaylists(ctx, subscribedDocs)))
|
|
|
|
return matches.sort((a, b) => a.title.localeCompare(b.title))
|
|
},
|
|
})
|
|
|
|
export const listAllPlaylists = query({
|
|
args: {},
|
|
handler: async (ctx) => {
|
|
const userId = await getAuthUserId(ctx)
|
|
if (userId === null) {
|
|
return []
|
|
}
|
|
|
|
const user = await ctx.db.get("users", userId)
|
|
if (!user) {
|
|
return []
|
|
}
|
|
|
|
const ownedDocs = await ctx.db
|
|
.query("playlists")
|
|
.withIndex("by_owner", (q) => q.eq("owner", userId))
|
|
.collect()
|
|
|
|
const ownedIds = new Set(ownedDocs.map((playlist) => playlist._id))
|
|
const summaries: PlaylistSummary[] = ownedDocs.map((playlist) =>
|
|
toPlaylistSummary(playlist, user.name)
|
|
)
|
|
|
|
const subscribedDocs = (
|
|
await loadPlaylists(ctx, user.subscribedPlaylists ?? [])
|
|
).filter((playlist) => !ownedIds.has(playlist._id))
|
|
summaries.push(...(await summarizePlaylists(ctx, subscribedDocs)))
|
|
|
|
return summaries.sort((a, b) => a.title.localeCompare(b.title))
|
|
},
|
|
})
|
|
|
|
export const getAlbumSongIds = query({
|
|
args: { albumId: v.id("albums") },
|
|
handler: async (ctx, args) => {
|
|
await requireSignedIn(ctx)
|
|
const songs = await ctx.db
|
|
.query("songs")
|
|
.withIndex("by_album", (q) => q.eq("album", args.albumId))
|
|
.collect()
|
|
songs.sort(compareAlbumSongs)
|
|
return songs.map((song) => song._id)
|
|
},
|
|
})
|
|
|
|
export const getArtistSongIds = query({
|
|
args: { artistId: v.id("artists") },
|
|
handler: async (ctx, args) => {
|
|
await requireSignedIn(ctx)
|
|
const songs = await ctx.db
|
|
.query("songs")
|
|
.withIndex("by_artist", (q) => q.eq("albumArtist", args.artistId))
|
|
.collect()
|
|
return chunk(songs.map((song) => song._id))
|
|
},
|
|
})
|
|
|
|
export const getOrderedArtistSongIds = query({
|
|
args: { artistId: v.id("artists") },
|
|
handler: async (ctx, args) => {
|
|
await requireSignedIn(ctx)
|
|
const songs = await ctx.db
|
|
.query("songs")
|
|
.withIndex("by_artist", (q) => q.eq("albumArtist", args.artistId))
|
|
.collect()
|
|
|
|
const albums = await ctx.db
|
|
.query("albums")
|
|
.withIndex("by_artist", (q) => q.eq("artist", args.artistId))
|
|
.collect()
|
|
const albumMap = new Map(albums.map((album) => [album._id, album]))
|
|
|
|
songs.sort((a, b) => {
|
|
const albumA = albumMap.get(a.album)?.name ?? ""
|
|
const albumB = albumMap.get(b.album)?.name ?? ""
|
|
if (albumA !== albumB) {
|
|
return albumA.localeCompare(albumB)
|
|
}
|
|
if (a.track !== b.track) {
|
|
return a.track - b.track
|
|
}
|
|
return a.name.localeCompare(b.name)
|
|
})
|
|
|
|
return chunk(songs.map((song) => song._id))
|
|
},
|
|
})
|
|
|
|
export const getPlaylistSongIds = query({
|
|
args: { playlistId: v.id("playlists") },
|
|
handler: async (ctx, args) => {
|
|
await requireSignedIn(ctx)
|
|
const playlist = await ctx.db.get("playlists", args.playlistId)
|
|
return playlist?.songs ?? []
|
|
},
|
|
})
|
|
|
|
export const createPlaylist = mutation({
|
|
args: {
|
|
name: v.string(),
|
|
invocationId: v.optional(v.string()),
|
|
songIds: v.optional(v.array(v.id("songs"))),
|
|
},
|
|
handler: async (ctx, args) => {
|
|
const userId = await requireAuth(ctx)
|
|
const invocationId = args.invocationId
|
|
if (invocationId) {
|
|
const previous = await ctx.db
|
|
.query("appIntentPlaylists")
|
|
.withIndex("by_user_invocation", (q) =>
|
|
q.eq("userId", userId).eq("invocationId", invocationId)
|
|
)
|
|
.unique()
|
|
if (previous) return previous.playlistId
|
|
}
|
|
const trimmed = args.name.trim()
|
|
if (!trimmed) {
|
|
throw new ConvexError("Playlist name cannot be empty")
|
|
}
|
|
|
|
const uniqueSongIds = [...new Set(args.songIds ?? [])]
|
|
|
|
const playlistId = await ctx.db.insert("playlists", {
|
|
name: trimmed,
|
|
owner: userId,
|
|
cover: null,
|
|
songs: uniqueSongIds,
|
|
})
|
|
const playlist = await ctx.db.get("playlists", playlistId)
|
|
await refreshAutomaticCover(ctx, playlist!, uniqueSongIds)
|
|
if (args.invocationId)
|
|
await ctx.db.insert("appIntentPlaylists", {
|
|
userId,
|
|
invocationId: args.invocationId,
|
|
playlistId,
|
|
})
|
|
return playlistId
|
|
},
|
|
})
|
|
|
|
export const addSongsToPlaylist = mutation({
|
|
args: {
|
|
playlistId: v.id("playlists"),
|
|
songIds: v.array(v.id("songs")),
|
|
},
|
|
handler: async (ctx, args) => {
|
|
const { playlist } = await requirePlaylistOwner(ctx, args.playlistId)
|
|
const existing = new Set(playlist.songs)
|
|
const uniqueIncoming = [...new Set(args.songIds)]
|
|
const toAdd = uniqueIncoming.filter((songId) => !existing.has(songId))
|
|
|
|
if (toAdd.length > 0) {
|
|
const songs = [...playlist.songs, ...toAdd]
|
|
await ctx.db.patch(playlist._id, { songs })
|
|
await refreshAutomaticCover(ctx, playlist, songs)
|
|
}
|
|
|
|
return {
|
|
addedCount: toAdd.length,
|
|
skippedCount: uniqueIncoming.length - toAdd.length,
|
|
}
|
|
},
|
|
})
|
|
|
|
export const removeSongsFromPlaylist = mutation({
|
|
args: {
|
|
playlistId: v.id("playlists"),
|
|
songIds: v.array(v.id("songs")),
|
|
},
|
|
handler: async (ctx, args) => {
|
|
const { playlist } = await requirePlaylistOwner(ctx, args.playlistId)
|
|
const remove = new Set(args.songIds)
|
|
const songs = playlist.songs.filter((songId) => !remove.has(songId))
|
|
await ctx.db.patch(playlist._id, { songs })
|
|
await refreshAutomaticCover(ctx, playlist, songs)
|
|
},
|
|
})
|
|
|
|
export const reorderPlaylistSongs = mutation({
|
|
args: {
|
|
playlistId: v.id("playlists"),
|
|
songIds: v.array(v.id("songs")),
|
|
},
|
|
handler: async (ctx, args) => {
|
|
const { playlist } = await requirePlaylistOwner(ctx, args.playlistId)
|
|
const existing = new Set(playlist.songs)
|
|
if (
|
|
args.songIds.length !== playlist.songs.length ||
|
|
new Set(args.songIds).size !== args.songIds.length ||
|
|
!args.songIds.every((songId) => existing.has(songId))
|
|
) {
|
|
throw new ConvexError("Invalid song order")
|
|
}
|
|
await ctx.db.patch(playlist._id, { songs: args.songIds })
|
|
await refreshAutomaticCover(ctx, playlist, args.songIds)
|
|
},
|
|
})
|
|
|
|
export const deletePlaylist = mutation({
|
|
args: { playlistId: v.id("playlists") },
|
|
handler: async (ctx, args) => {
|
|
const { playlist } = await requirePlaylistOwner(ctx, args.playlistId)
|
|
|
|
const users = await ctx.db.query("users").collect()
|
|
for (const user of users) {
|
|
const subscribed = user.subscribedPlaylists
|
|
const recentlyPlayed = user.recentlyPlayed
|
|
const isSubscribed = subscribed?.includes(args.playlistId) ?? false
|
|
const isRecentlyPlayed =
|
|
recentlyPlayed?.includes(args.playlistId) ?? false
|
|
if (!isSubscribed && !isRecentlyPlayed) {
|
|
continue
|
|
}
|
|
await ctx.db.patch(user._id, {
|
|
...(isSubscribed
|
|
? {
|
|
subscribedPlaylists: subscribed!.filter(
|
|
(id) => id !== args.playlistId
|
|
),
|
|
}
|
|
: {}),
|
|
...(isRecentlyPlayed
|
|
? {
|
|
recentlyPlayed: recentlyPlayed!.filter(
|
|
(id) => id !== args.playlistId
|
|
),
|
|
}
|
|
: {}),
|
|
})
|
|
}
|
|
|
|
if (playlist.coverStorageId) {
|
|
await ctx.storage.delete(playlist.coverStorageId)
|
|
}
|
|
await ctx.db.delete("playlists", args.playlistId)
|
|
},
|
|
})
|
|
|
|
/**
|
|
* Draws these album covers as the playlist's artwork: one alone, or four
|
|
* tiled 2x2. Replaces automatic or uploaded artwork.
|
|
*/
|
|
export const setPlaylistCoverAlbums = mutation({
|
|
args: {
|
|
playlistId: v.id("playlists"),
|
|
albumIds: v.array(v.id("albums")),
|
|
},
|
|
handler: async (ctx, { playlistId, albumIds }) => {
|
|
const { playlist } = await requirePlaylistOwner(ctx, playlistId)
|
|
if (
|
|
(albumIds.length !== 1 && albumIds.length !== COVER_GRID_ALBUMS) ||
|
|
new Set(albumIds).size !== albumIds.length
|
|
) {
|
|
throw new ConvexError("Pick one album or four different albums")
|
|
}
|
|
for (const albumId of albumIds) {
|
|
const album = await ctx.db.get("albums", albumId)
|
|
if (!album?.cover) {
|
|
throw new ConvexError("Album has no artwork")
|
|
}
|
|
}
|
|
await drawCoverAlbums(ctx, playlist, albumIds, "albums")
|
|
},
|
|
})
|
|
|
|
/**
|
|
* Takes an image data URL. It is cropped into storage in the background and
|
|
* the cover version changes once it lands.
|
|
*/
|
|
export const uploadPlaylistCover = mutation({
|
|
args: { playlistId: v.id("playlists"), image: v.string() },
|
|
handler: async (ctx, { playlistId, image }) => {
|
|
await requirePlaylistOwner(ctx, playlistId)
|
|
parseImageDataUrl(image, "Cover")
|
|
await ctx.scheduler.runAfter(
|
|
0,
|
|
internal.playlistCoverImages.storeUploadedCover,
|
|
{ playlistId, image }
|
|
)
|
|
},
|
|
})
|
|
|
|
export const subscribeToPlaylist = mutation({
|
|
args: { playlistId: v.id("playlists") },
|
|
handler: async (ctx, args) => {
|
|
const userId = await requireAuth(ctx)
|
|
const playlist = await ctx.db.get("playlists", args.playlistId)
|
|
if (!playlist) {
|
|
throw new ConvexError("Playlist not found")
|
|
}
|
|
if (playlist.owner === userId) {
|
|
throw new ConvexError("You already own this playlist")
|
|
}
|
|
|
|
const user = await ctx.db.get("users", userId)
|
|
if (!user) {
|
|
throw new ConvexError("User not found")
|
|
}
|
|
|
|
const subscribed = user.subscribedPlaylists ?? []
|
|
if (subscribed.includes(args.playlistId)) {
|
|
return
|
|
}
|
|
|
|
await ctx.db.patch(userId, {
|
|
subscribedPlaylists: [...subscribed, args.playlistId],
|
|
})
|
|
},
|
|
})
|
|
|
|
export const unsubscribeFromPlaylist = mutation({
|
|
args: { playlistId: v.id("playlists") },
|
|
handler: async (ctx, args) => {
|
|
const userId = await requireAuth(ctx)
|
|
const user = await ctx.db.get("users", userId)
|
|
if (!user) {
|
|
throw new ConvexError("User not found")
|
|
}
|
|
|
|
const subscribed = user.subscribedPlaylists ?? []
|
|
await ctx.db.patch(userId, {
|
|
subscribedPlaylists: subscribed.filter((id) => id !== args.playlistId),
|
|
})
|
|
},
|
|
})
|