fix(convex): move favorites off the users document
Favorites now live in a `favorites` table, one row per favorite. `migrations.migrateUsers` schedules a per-user copy of the legacy arrays, and writes migrate the caller first. Public query and mutation shapes are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2932aca3f4
commit
0fcae7ce72
7 files changed
+356
-240
No files matched your search
+2
@@ -11,6 +11,7 @@
|
||||
import type * as actions from "../actions.js";
|
||||
import type * as auth from "../auth.js";
|
||||
import type * as crons from "../crons.js";
|
||||
import type * as favoriteStore from "../favoriteStore.js";
|
||||
import type * as favorites from "../favorites.js";
|
||||
import type * as http from "../http.js";
|
||||
import type * as intentCatalog from "../intentCatalog.js";
|
||||
@@ -34,6 +35,7 @@ declare const fullApi: ApiFromModules<{
|
||||
actions: typeof actions;
|
||||
auth: typeof auth;
|
||||
crons: typeof crons;
|
||||
favoriteStore: typeof favoriteStore;
|
||||
favorites: typeof favorites;
|
||||
http: typeof http;
|
||||
intentCatalog: typeof intentCatalog;
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
import type { WithoutSystemFields } from "convex/server"
|
||||
import { ConvexError } from "convex/values"
|
||||
import type { Doc, Id } from "./_generated/dataModel"
|
||||
import type { MutationCtx, QueryCtx } from "./_generated/server"
|
||||
|
||||
export type FavoriteKind = Doc<"favorites">["kind"]
|
||||
|
||||
type FavoriteEntityId = {
|
||||
[Kind in FavoriteKind]: Extract<Doc<"favorites">, { kind: Kind }>["entityId"]
|
||||
}
|
||||
|
||||
/** The `favorites.getUserFavorites` shape, kept from when these lived on `users`. */
|
||||
export type FavoriteIds = {
|
||||
favoriteSongs: Id<"songs">[]
|
||||
favoriteAlbums: Id<"albums">[]
|
||||
favoriteArtists: Id<"artists">[]
|
||||
}
|
||||
|
||||
function legacyFavorites(user: Doc<"users"> | null): FavoriteIds {
|
||||
return {
|
||||
favoriteSongs: user?.favoriteSongs ?? [],
|
||||
favoriteAlbums: user?.favoriteAlbums ?? [],
|
||||
favoriteArtists: user?.favoriteArtists ?? [],
|
||||
}
|
||||
}
|
||||
|
||||
export function hasLegacyFavorites(user: Doc<"users">) {
|
||||
return (
|
||||
user.favoriteSongs !== undefined ||
|
||||
user.favoriteAlbums !== undefined ||
|
||||
user.favoriteArtists !== undefined
|
||||
)
|
||||
}
|
||||
|
||||
/** Favorited ids of one kind, oldest first. */
|
||||
async function readKind<Kind extends FavoriteKind>(
|
||||
ctx: QueryCtx,
|
||||
userId: Id<"users">,
|
||||
kind: Kind
|
||||
): Promise<FavoriteEntityId[Kind][]> {
|
||||
const rows = await ctx.db
|
||||
.query("favorites")
|
||||
.withIndex("by_user_kind", (q) => q.eq("userId", userId).eq("kind", kind))
|
||||
.collect()
|
||||
return rows.map((row) => row.entityId as FavoriteEntityId[Kind])
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads every favorite, oldest first. Users without rows fall back to the
|
||||
* legacy arrays on `users` until `migrations.migrateUsers` moves them, so
|
||||
* migrated users never read (or rerun on) their user doc here.
|
||||
*/
|
||||
export async function readFavorites(
|
||||
ctx: QueryCtx,
|
||||
userId: Id<"users">
|
||||
): Promise<FavoriteIds> {
|
||||
const [favoriteSongs, favoriteAlbums, favoriteArtists] = await Promise.all([
|
||||
readKind(ctx, userId, "song"),
|
||||
readKind(ctx, userId, "album"),
|
||||
readKind(ctx, userId, "artist"),
|
||||
])
|
||||
if (
|
||||
favoriteSongs.length > 0 ||
|
||||
favoriteAlbums.length > 0 ||
|
||||
favoriteArtists.length > 0
|
||||
) {
|
||||
return { favoriteSongs, favoriteAlbums, favoriteArtists }
|
||||
}
|
||||
return legacyFavorites(await ctx.db.get(userId))
|
||||
}
|
||||
|
||||
function favoriteRow(
|
||||
ctx: QueryCtx,
|
||||
userId: Id<"users">,
|
||||
entityId: FavoriteEntityId[FavoriteKind]
|
||||
) {
|
||||
return ctx.db
|
||||
.query("favorites")
|
||||
.withIndex("by_user_entity", (q) =>
|
||||
q.eq("userId", userId).eq("entityId", entityId)
|
||||
)
|
||||
.unique()
|
||||
}
|
||||
|
||||
export async function isFavorite(
|
||||
ctx: QueryCtx,
|
||||
userId: Id<"users">,
|
||||
entityId: FavoriteEntityId[FavoriteKind]
|
||||
) {
|
||||
return (await favoriteRow(ctx, userId, entityId)) !== null
|
||||
}
|
||||
|
||||
/** Appends ids that are not favorited yet, keeping existing ones in place. */
|
||||
export async function addFavorites<Kind extends FavoriteKind>(
|
||||
ctx: MutationCtx,
|
||||
userId: Id<"users">,
|
||||
kind: Kind,
|
||||
ids: FavoriteEntityId[Kind][]
|
||||
) {
|
||||
for (const entityId of new Set(ids)) {
|
||||
if (!(await isFavorite(ctx, userId, entityId))) {
|
||||
// TS cannot tie a generic `kind` to its `entityId` union member.
|
||||
await ctx.db.insert("favorites", {
|
||||
userId,
|
||||
kind,
|
||||
entityId,
|
||||
} as WithoutSystemFields<Doc<"favorites">>)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeFavorites(
|
||||
ctx: MutationCtx,
|
||||
userId: Id<"users">,
|
||||
ids: Iterable<FavoriteEntityId[FavoriteKind]>
|
||||
) {
|
||||
for (const entityId of new Set(ids)) {
|
||||
const row = await favoriteRow(ctx, userId, entityId)
|
||||
if (row) {
|
||||
await ctx.db.delete(row._id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves a user's legacy favorite arrays into `favorites` rows, keeping their
|
||||
* order, then clears them. Safe to call repeatedly.
|
||||
*/
|
||||
export async function migrateUserFavorites(
|
||||
ctx: MutationCtx,
|
||||
user: Doc<"users">
|
||||
) {
|
||||
if (!hasLegacyFavorites(user)) {
|
||||
return
|
||||
}
|
||||
const legacy = legacyFavorites(user)
|
||||
await addFavorites(ctx, user._id, "song", legacy.favoriteSongs)
|
||||
await addFavorites(ctx, user._id, "album", legacy.favoriteAlbums)
|
||||
await addFavorites(ctx, user._id, "artist", legacy.favoriteArtists)
|
||||
await ctx.db.patch(user._id, {
|
||||
favoriteSongs: undefined,
|
||||
favoriteAlbums: undefined,
|
||||
favoriteArtists: undefined,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Called before every favorites write, so a user toggling a favorite before
|
||||
* the boot migration reaches them does not end up with half their favorites
|
||||
* in rows and half on `users`.
|
||||
*/
|
||||
export async function requireMigratedFavorites(
|
||||
ctx: MutationCtx,
|
||||
userId: Id<"users">
|
||||
) {
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
await migrateUserFavorites(ctx, user)
|
||||
}
|
||||
|
||||
/** Removes deleted songs, albums or artists from every user's favorites. */
|
||||
export async function purgeFavoriteEntities(
|
||||
ctx: MutationCtx,
|
||||
ids: Iterable<FavoriteEntityId[FavoriteKind]>
|
||||
) {
|
||||
for (const entityId of ids) {
|
||||
const rows = await ctx.db
|
||||
.query("favorites")
|
||||
.withIndex("by_entity", (q) => q.eq("entityId", entityId))
|
||||
.collect()
|
||||
for (const row of rows) {
|
||||
await ctx.db.delete(row._id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteUserFavorites(
|
||||
ctx: MutationCtx,
|
||||
userId: Id<"users">
|
||||
) {
|
||||
for (const kind of ["song", "album", "artist"] as const) {
|
||||
const rows = await ctx.db
|
||||
.query("favorites")
|
||||
.withIndex("by_user_kind", (q) => q.eq("userId", userId).eq("kind", kind))
|
||||
.collect()
|
||||
for (const row of rows) {
|
||||
await ctx.db.delete(row._id)
|
||||
}
|
||||
}
|
||||
}
|
||||
+101
-237
@@ -3,18 +3,24 @@ 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 {
|
||||
addFavorites,
|
||||
isFavorite,
|
||||
readFavorites,
|
||||
removeFavorites,
|
||||
requireMigratedFavorites,
|
||||
type FavoriteIds,
|
||||
} from "./favoriteStore"
|
||||
import type { BrowsePlaylistDetail, BrowsePlaylistSummary } from "./library"
|
||||
import { browseSongsFromIds } from "./library"
|
||||
|
||||
function uniqueIds<T extends string>(ids: T[]): T[] {
|
||||
return [...new Set(ids)]
|
||||
}
|
||||
|
||||
async function requireAuth(ctx: MutationCtx) {
|
||||
/** Resolves the signed-in user and moves any legacy favorites into rows. */
|
||||
async function requireFavoritesUser(ctx: MutationCtx) {
|
||||
const userId = await getAuthUserId(ctx)
|
||||
if (userId === null) {
|
||||
throw new ConvexError("Not authenticated")
|
||||
}
|
||||
await requireMigratedFavorites(ctx, userId)
|
||||
return userId
|
||||
}
|
||||
|
||||
@@ -42,113 +48,59 @@ async function getSongIdsForArtist(ctx: QueryCtx, artistId: Id<"artists">) {
|
||||
return songs.map((song) => song._id)
|
||||
}
|
||||
|
||||
function allAlbumSongsFavorited(
|
||||
albumSongIds: Id<"songs">[],
|
||||
favoriteSongs: Id<"songs">[]
|
||||
/** True when `ids` is non-empty and every one of them is favorited. */
|
||||
async function allFavorited(
|
||||
ctx: QueryCtx,
|
||||
userId: Id<"users">,
|
||||
ids: (Id<"songs"> | Id<"albums">)[]
|
||||
) {
|
||||
if (albumSongIds.length === 0) {
|
||||
if (ids.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
|
||||
for (const id of ids) {
|
||||
if (!(await isFavorite(ctx, userId, id))) {
|
||||
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])
|
||||
return true
|
||||
}
|
||||
|
||||
async function promoteArtistIfAllAlbumsFavorited(
|
||||
ctx: MutationCtx,
|
||||
favoriteAlbums: Id<"albums">[],
|
||||
favoriteArtists: Id<"artists">[],
|
||||
userId: Id<"users">,
|
||||
artistId: Id<"artists">
|
||||
) {
|
||||
const artistAlbumIds = await getAlbumIdsForArtist(ctx, artistId)
|
||||
if (!allArtistAlbumsFavorited(artistAlbumIds, favoriteAlbums)) {
|
||||
return favoriteArtists
|
||||
const albumIds = await getAlbumIdsForArtist(ctx, artistId)
|
||||
if (await allFavorited(ctx, userId, albumIds)) {
|
||||
await addFavorites(ctx, userId, "artist", [artistId])
|
||||
}
|
||||
return uniqueIds([...favoriteArtists, artistId])
|
||||
}
|
||||
|
||||
/** Favorites albums whose songs are now all favorited, then their artists. */
|
||||
async function cascadeUpFromSongs(
|
||||
ctx: MutationCtx,
|
||||
favoriteSongs: Id<"songs">[],
|
||||
favoriteAlbums: Id<"albums">[],
|
||||
favoriteArtists: Id<"artists">[],
|
||||
userId: Id<"users">,
|
||||
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
|
||||
)
|
||||
for (const albumId of new Set(songs.map((song) => song.album))) {
|
||||
const songIds = await getSongIdsForAlbum(ctx, albumId)
|
||||
if (await allFavorited(ctx, userId, songIds)) {
|
||||
await addFavorites(ctx, userId, "album", [albumId])
|
||||
}
|
||||
}
|
||||
|
||||
const artistIds = new Set(songs.map((song) => song.albumArtist))
|
||||
for (const artistId of artistIds) {
|
||||
artists = await promoteArtistIfAllAlbumsFavorited(
|
||||
ctx,
|
||||
albums,
|
||||
artists,
|
||||
artistId
|
||||
)
|
||||
for (const artistId of new Set(songs.map((song) => song.albumArtist))) {
|
||||
await promoteArtistIfAllAlbumsFavorited(ctx, userId, artistId)
|
||||
}
|
||||
|
||||
return { favoriteAlbums: albums, favoriteArtists: artists }
|
||||
}
|
||||
|
||||
export const getUserFavorites = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
handler: async (ctx): Promise<FavoriteIds> => {
|
||||
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 ?? [],
|
||||
return { favoriteSongs: [], favoriteAlbums: [], favoriteArtists: [] }
|
||||
}
|
||||
return readFavorites(ctx, userId)
|
||||
},
|
||||
})
|
||||
|
||||
@@ -165,6 +117,7 @@ async function browseFavoritesSummaryHandler(
|
||||
return null
|
||||
}
|
||||
|
||||
const { favoriteSongs } = await readFavorites(ctx, userId)
|
||||
return {
|
||||
id: null,
|
||||
isFavorites: true,
|
||||
@@ -176,7 +129,7 @@ async function browseFavoritesSummaryHandler(
|
||||
cover: null,
|
||||
isOwner: true,
|
||||
isSubscribed: false,
|
||||
songIds: user.favoriteSongs ?? [],
|
||||
songIds: favoriteSongs,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,69 +159,35 @@ export const browseFavoritesPlaylistDetail = query({
|
||||
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 userId = await requireFavoritesUser(ctx)
|
||||
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,
|
||||
})
|
||||
await addFavorites(ctx, userId, "song", [songId])
|
||||
await cascadeUpFromSongs(ctx, userId, [song])
|
||||
},
|
||||
})
|
||||
|
||||
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 uniqueRequestedIds = uniqueIds(songIds)
|
||||
const userId = await requireFavoritesUser(ctx)
|
||||
const loadedSongs = await Promise.all(
|
||||
uniqueRequestedIds.map((id) => ctx.db.get("songs", id))
|
||||
[...new Set(songIds)].map((id) => ctx.db.get("songs", id))
|
||||
)
|
||||
const songs = loadedSongs.filter(
|
||||
(song): song is Doc<"songs"> => song !== null
|
||||
)
|
||||
const validSongIds = songs.map((song) => song._id)
|
||||
|
||||
const favoriteSongs = uniqueIds([
|
||||
...(user.favoriteSongs ?? []),
|
||||
...validSongIds,
|
||||
])
|
||||
const cascaded = await cascadeUpFromSongs(
|
||||
await addFavorites(
|
||||
ctx,
|
||||
favoriteSongs,
|
||||
user.favoriteAlbums ?? [],
|
||||
user.favoriteArtists ?? [],
|
||||
songs
|
||||
userId,
|
||||
"song",
|
||||
songs.map((song) => song._id)
|
||||
)
|
||||
|
||||
await ctx.db.patch(userId, {
|
||||
favoriteSongs,
|
||||
favoriteAlbums: cascaded.favoriteAlbums,
|
||||
favoriteArtists: cascaded.favoriteArtists,
|
||||
})
|
||||
await cascadeUpFromSongs(ctx, userId, songs)
|
||||
},
|
||||
})
|
||||
|
||||
@@ -286,159 +205,104 @@ export const unfavoriteSongs = mutation({
|
||||
},
|
||||
})
|
||||
|
||||
/** Unfavorites songs along with their albums and artists. */
|
||||
async function unfavoriteSongsHandler(
|
||||
ctx: MutationCtx,
|
||||
songIds: Id<"songs">[]
|
||||
) {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get("users", userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
const removeSongs = new Set(songIds)
|
||||
const userId = await requireFavoritesUser(ctx)
|
||||
const loadedSongs = await Promise.all(
|
||||
[...removeSongs].map((songId) => ctx.db.get("songs", songId))
|
||||
[...new Set(songIds)].map((songId) => ctx.db.get("songs", songId))
|
||||
)
|
||||
const removeAlbums = new Set(
|
||||
loadedSongs.flatMap((song) => (song ? [song.album] : []))
|
||||
)
|
||||
const removeArtists = new Set(
|
||||
loadedSongs.flatMap((song) => (song ? [song.albumArtist] : []))
|
||||
const songs = loadedSongs.filter(
|
||||
(song): song is Doc<"songs"> => song !== null
|
||||
)
|
||||
|
||||
await ctx.db.patch(userId, {
|
||||
favoriteSongs: (user.favoriteSongs ?? []).filter(
|
||||
(id) => !removeSongs.has(id)
|
||||
),
|
||||
favoriteAlbums: (user.favoriteAlbums ?? []).filter(
|
||||
(id) => !removeAlbums.has(id)
|
||||
),
|
||||
favoriteArtists: (user.favoriteArtists ?? []).filter(
|
||||
(id) => !removeArtists.has(id)
|
||||
),
|
||||
})
|
||||
await removeFavorites(ctx, userId, songIds)
|
||||
await removeFavorites(
|
||||
ctx,
|
||||
userId,
|
||||
songs.map((song) => song.album)
|
||||
)
|
||||
await removeFavorites(
|
||||
ctx,
|
||||
userId,
|
||||
songs.map((song) => song.albumArtist)
|
||||
)
|
||||
}
|
||||
|
||||
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 userId = await requireFavoritesUser(ctx)
|
||||
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(
|
||||
await addFavorites(ctx, userId, "album", [albumId])
|
||||
await addFavorites(
|
||||
ctx,
|
||||
favoriteAlbums,
|
||||
user.favoriteArtists ?? [],
|
||||
album.artist
|
||||
userId,
|
||||
"song",
|
||||
await getSongIdsForAlbum(ctx, albumId)
|
||||
)
|
||||
|
||||
await ctx.db.patch(userId, {
|
||||
favoriteAlbums,
|
||||
favoriteSongs,
|
||||
favoriteArtists,
|
||||
})
|
||||
await promoteArtistIfAllAlbumsFavorited(ctx, userId, album.artist)
|
||||
},
|
||||
})
|
||||
|
||||
/** Unfavorites an album along with its songs and artist. */
|
||||
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 userId = await requireFavoritesUser(ctx)
|
||||
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,
|
||||
})
|
||||
await removeFavorites(ctx, userId, [albumId, album.artist])
|
||||
await removeFavorites(ctx, userId, await getSongIdsForAlbum(ctx, albumId))
|
||||
},
|
||||
})
|
||||
|
||||
/** Favorites an artist along with all of their albums and songs. */
|
||||
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 userId = await requireFavoritesUser(ctx)
|
||||
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]),
|
||||
})
|
||||
await addFavorites(ctx, userId, "artist", [artistId])
|
||||
await addFavorites(
|
||||
ctx,
|
||||
userId,
|
||||
"album",
|
||||
await getAlbumIdsForArtist(ctx, artistId)
|
||||
)
|
||||
await addFavorites(
|
||||
ctx,
|
||||
userId,
|
||||
"song",
|
||||
await getSongIdsForArtist(ctx, artistId)
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
/** Unfavorites an artist along with all of their albums and songs. */
|
||||
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)
|
||||
),
|
||||
})
|
||||
const userId = await requireFavoritesUser(ctx)
|
||||
await removeFavorites(ctx, userId, [artistId])
|
||||
await removeFavorites(
|
||||
ctx,
|
||||
userId,
|
||||
await getAlbumIdsForArtist(ctx, artistId)
|
||||
)
|
||||
await removeFavorites(ctx, userId, await getSongIdsForArtist(ctx, artistId))
|
||||
},
|
||||
})
|
||||
@@ -21,6 +21,7 @@ import type {
|
||||
SearchTopResultItem,
|
||||
SidebarPlaylists,
|
||||
} from "./types"
|
||||
import { purgeFavoriteEntities } from "./favoriteStore"
|
||||
import { recordIntentCatalogChanges } from "./intentCatalogChanges"
|
||||
|
||||
export type {
|
||||
@@ -1162,7 +1163,10 @@ async function purgeSongsFromUsersAndPlaylists(
|
||||
}
|
||||
}
|
||||
|
||||
// Legacy queue fields stay until `migrations.migrateUsers` clears them.
|
||||
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
|
||||
@@ -1203,6 +1207,9 @@ async function purgeAlbumsFromUsers(
|
||||
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
|
||||
@@ -1233,6 +1240,9 @@ async function purgeArtistsFromUsers(
|
||||
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))) {
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { v } from "convex/values"
|
||||
import { internal } from "./_generated/api"
|
||||
import { internalMutation } from "./_generated/server"
|
||||
import { hasLegacyFavorites, migrateUserFavorites } from "./favoriteStore"
|
||||
import { hasLegacyPlayback, migrateUserPlayback } from "./playbackState"
|
||||
|
||||
const BATCH_SIZE = 25
|
||||
|
||||
/**
|
||||
* Moves playback state off `users` into `playbackStates`/`playbackProgress`
|
||||
* and legacy data URL avatars into file storage. Idempotent; the Docker
|
||||
* Moves playback state off `users` into `playbackStates`/`playbackProgress`,
|
||||
* favorite arrays into `favorites` rows, and legacy data URL avatars into
|
||||
* file storage. Idempotent; the Docker
|
||||
* entrypoint runs it on every boot. Run manually with
|
||||
* `npx convex run migrations:migrateUsers`.
|
||||
*/
|
||||
@@ -22,6 +24,12 @@ export const migrateUsers = internalMutation({
|
||||
if (hasLegacyPlayback(user)) {
|
||||
await migrateUserPlayback(ctx, user)
|
||||
}
|
||||
if (hasLegacyFavorites(user)) {
|
||||
// One mutation per user: a large library can mean thousands of rows.
|
||||
await ctx.scheduler.runAfter(0, internal.migrations.migrateFavorites, {
|
||||
userId: user._id,
|
||||
})
|
||||
}
|
||||
if (!user.imageStorageId && user.image?.startsWith("data:")) {
|
||||
await ctx.scheduler.runAfter(0, internal.users.storeProfileImage, {
|
||||
userId: user._id,
|
||||
@@ -37,3 +45,14 @@ export const migrateUsers = internalMutation({
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
/** Moves one user's favorites into rows. Scheduled by `migrateUsers`. */
|
||||
export const migrateFavorites = internalMutation({
|
||||
args: { userId: v.id("users") },
|
||||
handler: async (ctx, { userId }) => {
|
||||
const user = await ctx.db.get(userId)
|
||||
if (user) {
|
||||
await migrateUserFavorites(ctx, user)
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -27,6 +27,8 @@ export default defineSchema({
|
||||
),
|
||||
preferAtmos: v.optional(v.boolean()),
|
||||
subscribedPlaylists: v.optional(v.array(v.id("playlists"))),
|
||||
// Legacy favorites, now rows in `favorites`. `migrations.migrateUsers`
|
||||
// clears them; drop them once every deployment has run it.
|
||||
favoriteArtists: v.optional(v.array(v.id("artists"))),
|
||||
favoriteAlbums: v.optional(v.array(v.id("albums"))),
|
||||
favoriteSongs: v.optional(v.array(v.id("songs"))),
|
||||
@@ -58,6 +60,31 @@ export default defineSchema({
|
||||
songId: v.optional(v.id("songs")),
|
||||
progressSeconds: v.number(),
|
||||
}).index("by_user", ["userId"]),
|
||||
// One row per favorite. `by_user_kind` lists them in the order they were
|
||||
// favorited (the Favorites playlist order), `by_user_entity` answers "is this
|
||||
// favorited", and `by_entity` lets the scanner purge deleted media.
|
||||
favorites: defineTable(
|
||||
v.union(
|
||||
v.object({
|
||||
userId: v.id("users"),
|
||||
kind: v.literal("song"),
|
||||
entityId: v.id("songs"),
|
||||
}),
|
||||
v.object({
|
||||
userId: v.id("users"),
|
||||
kind: v.literal("album"),
|
||||
entityId: v.id("albums"),
|
||||
}),
|
||||
v.object({
|
||||
userId: v.id("users"),
|
||||
kind: v.literal("artist"),
|
||||
entityId: v.id("artists"),
|
||||
})
|
||||
)
|
||||
)
|
||||
.index("by_user_kind", ["userId", "kind"])
|
||||
.index("by_user_entity", ["userId", "entityId"])
|
||||
.index("by_entity", ["entityId"]),
|
||||
authVerifiers: defineTable({
|
||||
sessionId: v.optional(v.id("authSessions")),
|
||||
signature: v.optional(v.string()),
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import type { Doc, Id } from "./_generated/dataModel"
|
||||
import type { ActionCtx, MutationCtx } from "./_generated/server"
|
||||
import { MAX_PROFILE_IMAGE_BYTES } from "./limits"
|
||||
import { deleteUserFavorites } from "./favoriteStore"
|
||||
import { deleteUserPlayback } from "./playbackState"
|
||||
|
||||
const playbackQualityValidator = v.union(
|
||||
@@ -400,6 +401,7 @@ export const deleteUser = mutation({
|
||||
}
|
||||
await deleteOwnedPlaylists(ctx, userId)
|
||||
await deleteUserPlayback(ctx, userId)
|
||||
await deleteUserFavorites(ctx, userId)
|
||||
await setProfileImage(ctx, userId, null)
|
||||
await deleteUserAuthData(ctx, userId)
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user