fix(convex): move playback state and avatars off the users document
Playback queue, history and progress move into playbackStates and playbackProgress tables, so progress saves no longer rerun user queries. Avatars move to Convex file storage behind a web proxy route. The server caps queues at 5,000 songs, and the client stops retrying rejected syncs. migrations:migrateUsers moves existing data and runs on Docker boot. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
dce66b7697
commit
4da45b9707
17 files changed
+704
-201
No files matched your search
@@ -27,6 +27,7 @@ import {
|
||||
} from "@/lib/artwork-color-preference"
|
||||
import { initialsFromName } from "@/lib/format"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useProfileImageUrl } from "@/hooks/use-profile-image-url"
|
||||
import { changeServer, signOut } from "@/lib/session"
|
||||
import { radius, spacing, useThemeColors } from "@/lib/theme"
|
||||
import { showError } from "@/lib/toast"
|
||||
@@ -770,6 +771,7 @@ function ProfileAvatar({
|
||||
style?: StyleProp<ViewStyle>
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
const imageUrl = useProfileImageUrl(user.image)
|
||||
const avatarStyle = [
|
||||
styles.avatar,
|
||||
{
|
||||
@@ -781,11 +783,11 @@ function ProfileAvatar({
|
||||
style,
|
||||
]
|
||||
|
||||
if (user.image) {
|
||||
if (imageUrl) {
|
||||
return (
|
||||
<View style={avatarStyle}>
|
||||
<Image
|
||||
source={{ uri: user.image }}
|
||||
source={{ uri: imageUrl }}
|
||||
style={styles.avatarImage}
|
||||
contentFit="cover"
|
||||
/>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Image } from "expo-image"
|
||||
import { Pressable, StyleSheet, Text, View } from "react-native"
|
||||
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useProfileImageUrl } from "@/hooks/use-profile-image-url"
|
||||
import { initialsFromName } from "@/lib/format"
|
||||
import { radius, useThemeColors } from "@/lib/theme"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
@@ -13,6 +14,7 @@ export function ProfileHeaderButton() {
|
||||
const openSettings = useOpenSettings()
|
||||
const colors = useThemeColors()
|
||||
const user = useCachedQuery(api.auth.currentUser)
|
||||
const imageUrl = useProfileImageUrl(user?.image)
|
||||
|
||||
if (tabletLayout) return null
|
||||
|
||||
@@ -33,9 +35,9 @@ export function ProfileHeaderButton() {
|
||||
},
|
||||
]}
|
||||
>
|
||||
{user?.image ? (
|
||||
{imageUrl ? (
|
||||
<Image
|
||||
source={{ uri: user.image }}
|
||||
source={{ uri: imageUrl }}
|
||||
style={styles.image}
|
||||
contentFit="cover"
|
||||
/>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useIsFocused } from "expo-router"
|
||||
import { Platform, type ViewProps } from "react-native"
|
||||
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useProfileImageUrl } from "@/hooks/use-profile-image-url"
|
||||
import { initialsFromName } from "@/lib/format"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
|
||||
@@ -22,6 +23,7 @@ const NativeSidebar =
|
||||
|
||||
export function TabletSidebar() {
|
||||
const user = useCachedQuery(api.auth.currentUser)
|
||||
const imageUrl = useProfileImageUrl(user?.image)
|
||||
const openSettings = useOpenSettings()
|
||||
const active = useIsFocused()
|
||||
|
||||
@@ -31,7 +33,7 @@ export function TabletSidebar() {
|
||||
style={{ position: "absolute", width: 0, height: 0 }}
|
||||
accountName={user?.name ?? "Account"}
|
||||
initials={initialsFromName(user?.name ?? "Me")}
|
||||
imageURL={user?.image}
|
||||
imageURL={imageUrl}
|
||||
active={active}
|
||||
onProfilePress={openSettings}
|
||||
/>
|
||||
|
||||
@@ -229,17 +229,19 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSignedIn) return
|
||||
store.setTransport((state) =>
|
||||
syncPlaybackStateMutation({
|
||||
songQueue: state.queue,
|
||||
queueHistory: state.history,
|
||||
shuffleEnabled: state.shuffleEnabled,
|
||||
repeatEnabled: state.repeatEnabled,
|
||||
currentSongProgress: state.progressSeconds,
|
||||
})
|
||||
)
|
||||
store.setTransport({
|
||||
sync: (state) =>
|
||||
syncPlaybackStateMutation({
|
||||
songQueue: state.queue,
|
||||
queueHistory: state.history,
|
||||
shuffleEnabled: state.shuffleEnabled,
|
||||
repeatEnabled: state.repeatEnabled,
|
||||
currentSongProgress: state.progressSeconds,
|
||||
}),
|
||||
loadProgress: () => convex.query(api.playback.getSongProgress, {}),
|
||||
})
|
||||
return () => store.setTransport(null)
|
||||
}, [store, isSignedIn, syncPlaybackStateMutation])
|
||||
}, [store, isSignedIn, syncPlaybackStateMutation, convex])
|
||||
|
||||
useEffect(() => {
|
||||
if (!serverPlayback) return
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
|
||||
/**
|
||||
* Resolves `currentUser.image` to a loadable URI. Stored avatars come back as
|
||||
* paths on the oTunes web server; legacy ones are data URLs.
|
||||
*/
|
||||
export function useProfileImageUrl(image: string | undefined) {
|
||||
const { config } = useServerConfig()
|
||||
if (!image?.startsWith("/")) {
|
||||
return image
|
||||
}
|
||||
return config ? `${config.serverUrl.replace(/\/+$/, "")}${image}` : undefined
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import sharp from "sharp"
|
||||
import { getConvexClient, getConvexServerUrl } from "@/lib/convex-server"
|
||||
|
||||
const AVATAR_SIZE = 256
|
||||
|
||||
/**
|
||||
* Serves a profile photo from Convex storage, downscaled. URLs carry the
|
||||
* storage id (`?v=`), so a new photo gets a new URL and responses can be
|
||||
* cached for good.
|
||||
*/
|
||||
export async function GET(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const { id } = await params
|
||||
try {
|
||||
const storageUrl = await getConvexClient().query(
|
||||
api.users.getProfileImageUrl,
|
||||
{ userId: id as Id<"users"> }
|
||||
)
|
||||
if (!storageUrl) {
|
||||
return new Response("Not found", { status: 404 })
|
||||
}
|
||||
|
||||
// The backend builds storage URLs from its public origin, which may not
|
||||
// be reachable from here. Fetch the same path from the internal URL.
|
||||
const { pathname, search } = new URL(storageUrl)
|
||||
const upstream = await fetch(
|
||||
new URL(pathname + search, getConvexServerUrl())
|
||||
)
|
||||
if (!upstream.ok) {
|
||||
return new Response("Not found", { status: 404 })
|
||||
}
|
||||
|
||||
const data = await sharp(Buffer.from(await upstream.arrayBuffer()))
|
||||
.rotate()
|
||||
.resize(AVATAR_SIZE, AVATAR_SIZE, {
|
||||
fit: "cover",
|
||||
withoutEnlargement: true,
|
||||
})
|
||||
.webp({ quality: 85 })
|
||||
.toBuffer()
|
||||
|
||||
return new Response(new Uint8Array(data), {
|
||||
headers: {
|
||||
"Content-Type": "image/webp",
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
},
|
||||
})
|
||||
} catch {
|
||||
return new Response("Not found", { status: 404 })
|
||||
}
|
||||
}
|
||||
@@ -339,17 +339,19 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
if (!isSignedIn) {
|
||||
return
|
||||
}
|
||||
store.setTransport((state) =>
|
||||
syncPlaybackStateMutation({
|
||||
songQueue: state.queue,
|
||||
queueHistory: state.history,
|
||||
shuffleEnabled: state.shuffleEnabled,
|
||||
repeatEnabled: state.repeatEnabled,
|
||||
currentSongProgress: state.progressSeconds,
|
||||
})
|
||||
)
|
||||
store.setTransport({
|
||||
sync: (state) =>
|
||||
syncPlaybackStateMutation({
|
||||
songQueue: state.queue,
|
||||
queueHistory: state.history,
|
||||
shuffleEnabled: state.shuffleEnabled,
|
||||
repeatEnabled: state.repeatEnabled,
|
||||
currentSongProgress: state.progressSeconds,
|
||||
}),
|
||||
loadProgress: () => convex.query(api.playback.getSongProgress, {}),
|
||||
})
|
||||
return () => store.setTransport(null)
|
||||
}, [store, isSignedIn, syncPlaybackStateMutation])
|
||||
}, [store, isSignedIn, syncPlaybackStateMutation, convex])
|
||||
|
||||
useEffect(() => {
|
||||
if (!serverPlayback) {
|
||||
|
||||
@@ -85,6 +85,9 @@ admin_key=$(cd /convex && ./generate_admin_key.sh)
|
||||
log "Deploying Convex functions"
|
||||
convex_cli deploy --typecheck disable --codegen disable
|
||||
|
||||
log "Running data migrations"
|
||||
convex_cli run migrations:migrateUsers
|
||||
|
||||
if [ -z "$(convex_cli env get JWKS 2>/dev/null || true)" ]; then
|
||||
log "Generating Convex Auth signing keys"
|
||||
"$NODE" /opt/otunes/generate-auth-keys.mjs | convex_cli env set --force
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Id } from "../convex/_generated/dataModel"
|
||||
import { MAX_QUEUE_LENGTH } from "../convex/limits"
|
||||
import {
|
||||
EMPTY_PLAYBACK_QUEUE,
|
||||
type PlaybackQueueState,
|
||||
@@ -7,6 +8,11 @@ import {
|
||||
import { loadPersistentCache, readCache, writeCache } from "./persistent-cache"
|
||||
|
||||
const SYNC_DELAY_MS = 300
|
||||
/**
|
||||
* Backoff for failed syncs. Convex queues mutations while offline, so a
|
||||
* rejection means the server refused the state; after the last retry the
|
||||
* change is dropped until the next local edit instead of retrying forever.
|
||||
*/
|
||||
const RETRY_DELAYS_MS = [1_000, 3_000, 10_000, 30_000]
|
||||
|
||||
export type ServerPlaybackState = {
|
||||
@@ -14,7 +20,6 @@ export type ServerPlaybackState = {
|
||||
queueHistorySongIds: Id<"songs">[]
|
||||
shuffleEnabled: boolean
|
||||
repeatEnabled: RepeatMode
|
||||
currentSongProgress: number
|
||||
revision: number
|
||||
}
|
||||
|
||||
@@ -30,9 +35,12 @@ type PersistedPlayback = PlaybackQueueState & {
|
||||
dirty: boolean
|
||||
}
|
||||
|
||||
export type PlaybackSyncTransport = (
|
||||
state: PlaybackQueueState
|
||||
) => Promise<number>
|
||||
export type PlaybackSyncTransport = {
|
||||
/** Saves the state and resolves with the new server revision. */
|
||||
sync: (state: PlaybackQueueState) => Promise<number>
|
||||
/** One-shot read of the server's saved progress for its current song. */
|
||||
loadProgress: () => Promise<number>
|
||||
}
|
||||
|
||||
/**
|
||||
* Client-owned playback queue. Changes apply locally (and persist on this
|
||||
@@ -49,6 +57,7 @@ export class PlaybackStore {
|
||||
private retryAttempt = 0
|
||||
private syncTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private latestServerState: ServerPlaybackState | null = null
|
||||
private adopting = false
|
||||
private transport: PlaybackSyncTransport | null = null
|
||||
private readonly listeners = new Set<() => void>()
|
||||
|
||||
@@ -79,7 +88,7 @@ export class PlaybackStore {
|
||||
}
|
||||
|
||||
update(recipe: (state: PlaybackQueueState) => PlaybackQueueState) {
|
||||
const next = recipe(this.state)
|
||||
const next = capQueue(recipe(this.state))
|
||||
if (next === this.state) {
|
||||
return
|
||||
}
|
||||
@@ -102,7 +111,7 @@ export class PlaybackStore {
|
||||
receiveServerState(serverState: ServerPlaybackState) {
|
||||
this.latestServerState = serverState
|
||||
if (this.snapshot.hydrated) {
|
||||
this.adoptServerState()
|
||||
void this.adoptServerState()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,23 +125,52 @@ export class PlaybackStore {
|
||||
const { revision, dirty, ...state } = persisted
|
||||
this.revision = revision
|
||||
this.dirty = dirty
|
||||
this.state = { ...EMPTY_PLAYBACK_QUEUE, ...state }
|
||||
this.state = capQueue({ ...EMPTY_PLAYBACK_QUEUE, ...state })
|
||||
}
|
||||
|
||||
this.snapshot = toSnapshot(this.state, true)
|
||||
this.emit()
|
||||
this.adoptServerState()
|
||||
void this.adoptServerState()
|
||||
if (this.dirty) {
|
||||
this.scheduleSync(0)
|
||||
}
|
||||
}
|
||||
|
||||
private adoptServerState() {
|
||||
private canAdopt(serverState: ServerPlaybackState | null) {
|
||||
return (
|
||||
serverState !== null &&
|
||||
!this.dirty &&
|
||||
!this.inFlight &&
|
||||
(this.revision === null || serverState.revision > this.revision)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Adopts the latest server queue. Progress is not part of the queue query
|
||||
* (it changes every few seconds), so it is fetched once here.
|
||||
*/
|
||||
private async adoptServerState() {
|
||||
const serverState = this.latestServerState
|
||||
if (!serverState || this.dirty || this.inFlight) {
|
||||
if (this.adopting || !serverState || !this.canAdopt(serverState)) {
|
||||
return
|
||||
}
|
||||
if (this.revision !== null && serverState.revision <= this.revision) {
|
||||
|
||||
this.adopting = true
|
||||
let progressSeconds = 0
|
||||
try {
|
||||
progressSeconds = (await this.transport?.loadProgress()) ?? 0
|
||||
} catch {
|
||||
// Starting from 0 beats not adopting the queue at all.
|
||||
} finally {
|
||||
this.adopting = false
|
||||
}
|
||||
|
||||
// Newer server state or local edits may have arrived while loading.
|
||||
if (this.latestServerState !== serverState) {
|
||||
void this.adoptServerState()
|
||||
return
|
||||
}
|
||||
if (!this.canAdopt(serverState)) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -142,7 +180,7 @@ export class PlaybackStore {
|
||||
history: serverState.queueHistorySongIds,
|
||||
shuffleEnabled: serverState.shuffleEnabled,
|
||||
repeatEnabled: serverState.repeatEnabled,
|
||||
progressSeconds: serverState.currentSongProgress,
|
||||
progressSeconds,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -167,7 +205,7 @@ export class PlaybackStore {
|
||||
let failed = false
|
||||
|
||||
try {
|
||||
const revision = await transport(this.state)
|
||||
const revision = await transport.sync(this.state)
|
||||
this.revision = Math.max(revision, this.revision ?? 0)
|
||||
this.retryAttempt = 0
|
||||
if (this.changeCount === changeCountAtStart) {
|
||||
@@ -181,15 +219,17 @@ export class PlaybackStore {
|
||||
|
||||
this.persist()
|
||||
|
||||
if (failed) {
|
||||
const delay =
|
||||
RETRY_DELAYS_MS[Math.min(this.retryAttempt, RETRY_DELAYS_MS.length - 1)]
|
||||
if (failed && this.retryAttempt < RETRY_DELAYS_MS.length) {
|
||||
this.scheduleSync(RETRY_DELAYS_MS[this.retryAttempt])
|
||||
this.retryAttempt += 1
|
||||
this.scheduleSync(delay)
|
||||
} else if (failed) {
|
||||
this.retryAttempt = 0
|
||||
this.dirty = false
|
||||
this.persist()
|
||||
} else if (this.dirty) {
|
||||
this.scheduleSync(SYNC_DELAY_MS)
|
||||
} else {
|
||||
this.adoptServerState()
|
||||
void this.adoptServerState()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,6 +267,14 @@ export class PlaybackStore {
|
||||
}
|
||||
}
|
||||
|
||||
/** Mirrors the server's queue cap so local and synced state agree. */
|
||||
function capQueue(state: PlaybackQueueState): PlaybackQueueState {
|
||||
if (state.queue.length <= MAX_QUEUE_LENGTH) {
|
||||
return state
|
||||
}
|
||||
return { ...state, queue: state.queue.slice(0, MAX_QUEUE_LENGTH) }
|
||||
}
|
||||
|
||||
function toSnapshot(
|
||||
state: PlaybackQueueState,
|
||||
hydrated: boolean
|
||||
|
||||
+6
@@ -14,7 +14,10 @@ import type * as crons from "../crons.js";
|
||||
import type * as favorites from "../favorites.js";
|
||||
import type * as http from "../http.js";
|
||||
import type * as library from "../library.js";
|
||||
import type * as limits from "../limits.js";
|
||||
import type * as migrations from "../migrations.js";
|
||||
import type * as playback from "../playback.js";
|
||||
import type * as playbackState from "../playbackState.js";
|
||||
import type * as playlists from "../playlists.js";
|
||||
import type * as types from "../types.js";
|
||||
import type * as users from "../users.js";
|
||||
@@ -32,7 +35,10 @@ declare const fullApi: ApiFromModules<{
|
||||
favorites: typeof favorites;
|
||||
http: typeof http;
|
||||
library: typeof library;
|
||||
limits: typeof limits;
|
||||
migrations: typeof migrations;
|
||||
playback: typeof playback;
|
||||
playbackState: typeof playbackState;
|
||||
playlists: typeof playlists;
|
||||
types: typeof types;
|
||||
users: typeof users;
|
||||
|
||||
@@ -3,6 +3,7 @@ import { ConvexError } from "convex/values"
|
||||
import { Password } from "@convex-dev/auth/providers/Password"
|
||||
import { query } from "./_generated/server"
|
||||
import type { MutationCtx } from "./_generated/server"
|
||||
import { profileImagePath } from "./users"
|
||||
|
||||
export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({
|
||||
providers: [
|
||||
@@ -72,7 +73,7 @@ export const currentUser = query({
|
||||
return {
|
||||
_id: user._id,
|
||||
name: user.name,
|
||||
image: user.image,
|
||||
image: profileImagePath(user),
|
||||
email: user.email,
|
||||
isAdmin: user.isAdmin,
|
||||
playbackQuality: user.playbackQuality,
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Limits shared by Convex functions and clients. Convex rejects arrays longer
|
||||
* than 8,192 values in documents, arguments, and return values.
|
||||
*/
|
||||
|
||||
/** Songs kept in the playback queue, including the current song. */
|
||||
export const MAX_QUEUE_LENGTH = 5_000
|
||||
|
||||
/** Largest profile photo accepted, in bytes after base64 decoding. */
|
||||
export const MAX_PROFILE_IMAGE_BYTES = 2 * 1024 * 1024
|
||||
@@ -0,0 +1,39 @@
|
||||
import { v } from "convex/values"
|
||||
import { internal } from "./_generated/api"
|
||||
import { internalMutation } from "./_generated/server"
|
||||
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
|
||||
* entrypoint runs it on every boot. Run manually with
|
||||
* `npx convex run migrations:migrateUsers`.
|
||||
*/
|
||||
export const migrateUsers = internalMutation({
|
||||
args: { cursor: v.optional(v.union(v.string(), v.null())) },
|
||||
handler: async (ctx, { cursor }) => {
|
||||
const page = await ctx.db
|
||||
.query("users")
|
||||
.paginate({ cursor: cursor ?? null, numItems: BATCH_SIZE })
|
||||
|
||||
for (const user of page.page) {
|
||||
if (hasLegacyPlayback(user)) {
|
||||
await migrateUserPlayback(ctx, user)
|
||||
}
|
||||
if (!user.imageStorageId && user.image?.startsWith("data:")) {
|
||||
await ctx.scheduler.runAfter(0, internal.users.storeProfileImage, {
|
||||
userId: user._id,
|
||||
image: user.image,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (!page.isDone) {
|
||||
await ctx.scheduler.runAfter(0, internal.migrations.migrateUsers, {
|
||||
cursor: page.continueCursor,
|
||||
})
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -1,7 +1,7 @@
|
||||
import { getAuthUserId } from "@convex-dev/auth/server"
|
||||
import { paginationOptsValidator } from "convex/server"
|
||||
import { ConvexError, v } from "convex/values"
|
||||
import type { Doc, Id } from "./_generated/dataModel"
|
||||
import type { Id } from "./_generated/dataModel"
|
||||
import type { MutationCtx } from "./_generated/server"
|
||||
import { mutation, query } from "./_generated/server"
|
||||
import type { QueueSong } from "./types"
|
||||
@@ -12,10 +12,17 @@ import {
|
||||
songsSortDirectionValidator,
|
||||
songsSortKeyValidator,
|
||||
} from "./library"
|
||||
import {
|
||||
loadPlaybackForWrite,
|
||||
MAX_QUEUE_HISTORY,
|
||||
readPlaybackProgress,
|
||||
readPlaybackState,
|
||||
writePlayback,
|
||||
writeProgress,
|
||||
} from "./playbackState"
|
||||
|
||||
export type { HistorySong, QueueSong } from "./types"
|
||||
|
||||
const MAX_QUEUE_HISTORY = 30
|
||||
const MAX_RECENTLY_PLAYED = 30
|
||||
|
||||
type RecentlyPlayedItem = Id<"albums"> | Id<"playlists">
|
||||
@@ -144,28 +151,12 @@ function appendManyToQueueHistory(
|
||||
return next
|
||||
}
|
||||
|
||||
async function patchPlayback(
|
||||
ctx: MutationCtx,
|
||||
userId: Id<"users">,
|
||||
patch: Partial<
|
||||
Pick<
|
||||
Doc<"users">,
|
||||
| "songQueue"
|
||||
| "queueHistory"
|
||||
| "currentSongProgress"
|
||||
| "shuffleEnabled"
|
||||
| "repeatEnabled"
|
||||
>
|
||||
>
|
||||
) {
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
async function requirePlayback(ctx: MutationCtx, userId: Id<"users">) {
|
||||
const playback = await loadPlaybackForWrite(ctx, userId)
|
||||
if (!playback) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
const playbackRevision = (user.playbackRevision ?? 0) + 1
|
||||
await ctx.db.patch(userId, { ...patch, playbackRevision })
|
||||
return playbackRevision
|
||||
return playback
|
||||
}
|
||||
|
||||
async function setQueueState(
|
||||
@@ -174,13 +165,12 @@ async function setQueueState(
|
||||
patch: {
|
||||
songQueue: Id<"songs">[]
|
||||
shuffleEnabled?: boolean
|
||||
currentSongProgress?: number
|
||||
resetHistory?: boolean
|
||||
}
|
||||
) {
|
||||
await patchPlayback(ctx, userId, {
|
||||
await writePlayback(ctx, userId, {
|
||||
songQueue: patch.songQueue,
|
||||
currentSongProgress: patch.currentSongProgress ?? 0,
|
||||
progressSeconds: 0,
|
||||
...(patch.resetHistory ? { queueHistory: [] } : {}),
|
||||
...(patch.shuffleEnabled !== undefined
|
||||
? { shuffleEnabled: patch.shuffleEnabled }
|
||||
@@ -188,6 +178,7 @@ async function setQueueState(
|
||||
})
|
||||
}
|
||||
|
||||
/** Queue state without progress; progress comes from `getSongProgress`. */
|
||||
export const getPlaybackState = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
@@ -196,12 +187,8 @@ export const getPlaybackState = query({
|
||||
return null
|
||||
}
|
||||
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
return null
|
||||
}
|
||||
|
||||
const songIds = user.songQueue ?? []
|
||||
const playback = await readPlaybackState(ctx, userId)
|
||||
const songIds = playback.songQueue
|
||||
const currentSong =
|
||||
songIds.length > 0
|
||||
? ((await browseSongsFromIds(ctx, [songIds[0]]))[0] ?? null)
|
||||
@@ -209,12 +196,16 @@ export const getPlaybackState = query({
|
||||
|
||||
return {
|
||||
queueSongIds: songIds,
|
||||
queueHistorySongIds: user.queueHistory ?? [],
|
||||
queueHistorySongIds: playback.queueHistory,
|
||||
currentSong,
|
||||
shuffleEnabled: user.shuffleEnabled ?? false,
|
||||
repeatEnabled: user.repeatEnabled ?? ("none" as const),
|
||||
currentSongProgress: user.currentSongProgress ?? 0,
|
||||
revision: user.playbackRevision ?? 0,
|
||||
shuffleEnabled: playback.shuffleEnabled,
|
||||
repeatEnabled: playback.repeatEnabled,
|
||||
/**
|
||||
* @deprecated Always 0. Reading progress here would rerun this query on
|
||||
* every progress save. Kept for app builds that predate `getSongProgress`.
|
||||
*/
|
||||
currentSongProgress: 0,
|
||||
revision: playback.revision,
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -239,12 +230,12 @@ export const syncPlaybackState = mutation({
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
return await patchPlayback(ctx, userId, {
|
||||
return await writePlayback(ctx, userId, {
|
||||
songQueue: args.songQueue,
|
||||
queueHistory: args.queueHistory.slice(-MAX_QUEUE_HISTORY),
|
||||
queueHistory: args.queueHistory,
|
||||
shuffleEnabled: args.shuffleEnabled,
|
||||
repeatEnabled: args.repeatEnabled,
|
||||
currentSongProgress: Math.max(0, Math.floor(args.currentSongProgress)),
|
||||
progressSeconds: args.currentSongProgress,
|
||||
})
|
||||
},
|
||||
})
|
||||
@@ -272,13 +263,8 @@ export const getQueueHistory = query({
|
||||
return []
|
||||
}
|
||||
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
return []
|
||||
}
|
||||
|
||||
const songIds = user.queueHistory ?? []
|
||||
const songs = await browseSongsFromIds(ctx, songIds)
|
||||
const { queueHistory } = await readPlaybackState(ctx, userId)
|
||||
const songs = await browseSongsFromIds(ctx, queueHistory)
|
||||
|
||||
return songs.map((song, index) => ({
|
||||
...song,
|
||||
@@ -298,12 +284,7 @@ export const getQueuePaginated = query({
|
||||
return { page: [], isDone: true, continueCursor: "" }
|
||||
}
|
||||
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
return { page: [], isDone: true, continueCursor: "" }
|
||||
}
|
||||
|
||||
const songIds = user.songQueue ?? []
|
||||
const { songQueue: songIds } = await readPlaybackState(ctx, userId)
|
||||
const startIndex = args.paginationOpts.cursor
|
||||
? Number.parseInt(args.paginationOpts.cursor, 10)
|
||||
: 0
|
||||
@@ -378,13 +359,10 @@ export const addToQueueNext = mutation({
|
||||
}
|
||||
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
const playback = await requirePlayback(ctx, userId)
|
||||
|
||||
const toAdd = orderSongsForInsert(songIds, user.shuffleEnabled ?? false)
|
||||
const queue = user.songQueue ?? []
|
||||
const toAdd = orderSongsForInsert(songIds, playback.shuffleEnabled)
|
||||
const queue = playback.songQueue
|
||||
|
||||
if (queue.length === 0) {
|
||||
await setQueueState(ctx, userId, { songQueue: toAdd })
|
||||
@@ -406,13 +384,10 @@ export const addToQueueLast = mutation({
|
||||
}
|
||||
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
const playback = await requirePlayback(ctx, userId)
|
||||
|
||||
const toAdd = orderSongsForInsert(songIds, user.shuffleEnabled ?? false)
|
||||
const queue = user.songQueue ?? []
|
||||
const toAdd = orderSongsForInsert(songIds, playback.shuffleEnabled)
|
||||
const queue = playback.songQueue
|
||||
|
||||
await setQueueState(ctx, userId, {
|
||||
songQueue: queue.length === 0 ? toAdd : [...queue, ...toAdd],
|
||||
@@ -427,18 +402,15 @@ export const playFromSong = mutation({
|
||||
},
|
||||
handler: async (ctx, { songId, songIds }) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
const playback = await requirePlayback(ctx, userId)
|
||||
|
||||
const index = songIds.indexOf(songId)
|
||||
const rest = user.shuffleEnabled
|
||||
const rest = playback.shuffleEnabled
|
||||
? uniqueSongIds(songIds).filter((id) => id !== songId)
|
||||
: index === -1
|
||||
? []
|
||||
: songIds.slice(index + 1)
|
||||
const queueRest = user.shuffleEnabled ? shuffleArray(rest) : rest
|
||||
const queueRest = playback.shuffleEnabled ? shuffleArray(rest) : rest
|
||||
|
||||
await setQueueState(ctx, userId, {
|
||||
songQueue: [songId, ...queueRest],
|
||||
@@ -457,10 +429,7 @@ async function albumSongIds(ctx: MutationCtx, albumId: Id<"albums">) {
|
||||
return songs.map((song) => song._id)
|
||||
}
|
||||
|
||||
async function orderedArtistSongIds(
|
||||
ctx: MutationCtx,
|
||||
artistId: Id<"artists">
|
||||
) {
|
||||
async function orderedArtistSongIds(ctx: MutationCtx, artistId: Id<"artists">) {
|
||||
const songs = await ctx.db
|
||||
.query("songs")
|
||||
.withIndex("by_artist", (q) => q.eq("albumArtist", artistId))
|
||||
@@ -585,19 +554,16 @@ export const playFromLibrarySong = mutation({
|
||||
},
|
||||
handler: async (ctx, { songId, sortKey, sortDirection }) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
const playback = await requirePlayback(ctx, userId)
|
||||
|
||||
const songIds = await getSortedLibrarySongIds(ctx, sortKey, sortDirection)
|
||||
const index = songIds.indexOf(songId)
|
||||
const rest = user.shuffleEnabled
|
||||
const rest = playback.shuffleEnabled
|
||||
? uniqueSongIds(songIds).filter((id) => id !== songId)
|
||||
: index === -1
|
||||
? []
|
||||
: songIds.slice(index + 1)
|
||||
const queueRest = user.shuffleEnabled ? shuffleArray(rest) : rest
|
||||
const queueRest = playback.shuffleEnabled ? shuffleArray(rest) : rest
|
||||
|
||||
await setQueueState(ctx, userId, {
|
||||
songQueue: [songId, ...queueRest],
|
||||
@@ -611,24 +577,21 @@ export const toggleShuffle = mutation({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
const playback = await requirePlayback(ctx, userId)
|
||||
|
||||
const shuffleEnabled = !(user.shuffleEnabled ?? false)
|
||||
const queue = user.songQueue ?? []
|
||||
const shuffleEnabled = !playback.shuffleEnabled
|
||||
const queue = playback.songQueue
|
||||
|
||||
if (shuffleEnabled && queue.length > 1) {
|
||||
const [current, ...upNext] = queue
|
||||
await patchPlayback(ctx, userId, {
|
||||
await writePlayback(ctx, userId, {
|
||||
shuffleEnabled: true,
|
||||
songQueue: [current, ...shuffleArray(upNext)],
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
await patchPlayback(ctx, userId, { shuffleEnabled })
|
||||
await writePlayback(ctx, userId, { shuffleEnabled })
|
||||
},
|
||||
})
|
||||
|
||||
@@ -636,16 +599,13 @@ export const cycleRepeat = mutation({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
const playback = await requirePlayback(ctx, userId)
|
||||
|
||||
const current = user.repeatEnabled ?? "none"
|
||||
const current = playback.repeatEnabled
|
||||
const next =
|
||||
current === "none" ? "once" : current === "once" ? "always" : "none"
|
||||
|
||||
await patchPlayback(ctx, userId, { repeatEnabled: next })
|
||||
await writePlayback(ctx, userId, { repeatEnabled: next })
|
||||
},
|
||||
})
|
||||
|
||||
@@ -653,10 +613,10 @@ export const clearQueue = mutation({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
await patchPlayback(ctx, userId, {
|
||||
await writePlayback(ctx, userId, {
|
||||
songQueue: [],
|
||||
queueHistory: [],
|
||||
currentSongProgress: 0,
|
||||
progressSeconds: 0,
|
||||
})
|
||||
},
|
||||
})
|
||||
@@ -665,25 +625,22 @@ export const reorderQueue = mutation({
|
||||
args: { songIds: v.array(v.id("songs")) },
|
||||
handler: async (ctx, { songIds }) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
const playback = await requirePlayback(ctx, userId)
|
||||
|
||||
const queue = user.songQueue ?? []
|
||||
const queue = playback.songQueue
|
||||
if (!haveSameSongCounts(queue, songIds)) {
|
||||
throw new ConvexError("Invalid queue order")
|
||||
}
|
||||
const currentSongChanged = songIds.length > 0 && songIds[0] !== queue[0]
|
||||
const history =
|
||||
currentSongChanged && queue.length > 0
|
||||
? appendToQueueHistory(user.queueHistory ?? [], queue[0])
|
||||
: (user.queueHistory ?? [])
|
||||
? appendToQueueHistory(playback.queueHistory, queue[0])
|
||||
: playback.queueHistory
|
||||
|
||||
await patchPlayback(ctx, userId, {
|
||||
await writePlayback(ctx, userId, {
|
||||
songQueue: songIds,
|
||||
queueHistory: history,
|
||||
...(currentSongChanged ? { currentSongProgress: 0 } : {}),
|
||||
...(currentSongChanged ? { progressSeconds: 0 } : {}),
|
||||
})
|
||||
},
|
||||
})
|
||||
@@ -692,23 +649,20 @@ export const skipToQueueIndex = mutation({
|
||||
args: { index: v.number() },
|
||||
handler: async (ctx, { index }) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
const playback = await requirePlayback(ctx, userId)
|
||||
|
||||
const queue = user.songQueue ?? []
|
||||
const queue = playback.songQueue
|
||||
if (index < 0 || index >= queue.length || index === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const skipped = queue.slice(0, index)
|
||||
const history = appendManyToQueueHistory(user.queueHistory ?? [], skipped)
|
||||
const history = appendManyToQueueHistory(playback.queueHistory, skipped)
|
||||
|
||||
await patchPlayback(ctx, userId, {
|
||||
await writePlayback(ctx, userId, {
|
||||
songQueue: queue.slice(index),
|
||||
queueHistory: history,
|
||||
currentSongProgress: 0,
|
||||
progressSeconds: 0,
|
||||
})
|
||||
},
|
||||
})
|
||||
@@ -717,47 +671,44 @@ export const skipNext = mutation({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
const playback = await requirePlayback(ctx, userId)
|
||||
|
||||
const queue = user.songQueue ?? []
|
||||
const queue = playback.songQueue
|
||||
if (queue.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const repeat = user.repeatEnabled ?? "none"
|
||||
const repeat = playback.repeatEnabled
|
||||
|
||||
if (repeat === "once") {
|
||||
await patchPlayback(ctx, userId, { currentSongProgress: 0 })
|
||||
await writePlayback(ctx, userId, { progressSeconds: 0 })
|
||||
return
|
||||
}
|
||||
|
||||
const [current, ...rest] = queue
|
||||
|
||||
if (repeat === "always") {
|
||||
await patchPlayback(ctx, userId, {
|
||||
await writePlayback(ctx, userId, {
|
||||
songQueue: [...rest, current],
|
||||
currentSongProgress: 0,
|
||||
progressSeconds: 0,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (rest.length === 0) {
|
||||
await patchPlayback(ctx, userId, {
|
||||
await writePlayback(ctx, userId, {
|
||||
songQueue: [current],
|
||||
currentSongProgress: 0,
|
||||
progressSeconds: 0,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const history = appendToQueueHistory(user.queueHistory ?? [], current)
|
||||
const history = appendToQueueHistory(playback.queueHistory, current)
|
||||
|
||||
await patchPlayback(ctx, userId, {
|
||||
await writePlayback(ctx, userId, {
|
||||
songQueue: rest,
|
||||
queueHistory: history,
|
||||
currentSongProgress: 0,
|
||||
progressSeconds: 0,
|
||||
})
|
||||
},
|
||||
})
|
||||
@@ -766,20 +717,17 @@ export const skipPrevious = mutation({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
const playback = await requirePlayback(ctx, userId)
|
||||
|
||||
const queue = user.songQueue ?? []
|
||||
const history = user.queueHistory ?? []
|
||||
const queue = playback.songQueue
|
||||
const history = playback.queueHistory
|
||||
|
||||
if (queue.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
if (history.length === 0) {
|
||||
await patchPlayback(ctx, userId, { currentSongProgress: 0 })
|
||||
await writePlayback(ctx, userId, { progressSeconds: 0 })
|
||||
return
|
||||
}
|
||||
|
||||
@@ -787,14 +735,18 @@ export const skipPrevious = mutation({
|
||||
const previous = history[history.length - 1]
|
||||
const newHistory = history.slice(0, -1)
|
||||
|
||||
await patchPlayback(ctx, userId, {
|
||||
await writePlayback(ctx, userId, {
|
||||
songQueue: [previous, current, ...rest],
|
||||
queueHistory: newHistory,
|
||||
currentSongProgress: 0,
|
||||
progressSeconds: 0,
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
/**
|
||||
* Saved position of the current song. Subscribing reruns every few seconds
|
||||
* during playback, so clients fetch it once when adopting a new queue.
|
||||
*/
|
||||
export const getSongProgress = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
@@ -803,12 +755,11 @@ export const getSongProgress = query({
|
||||
throw new ConvexError("User not logged in")
|
||||
}
|
||||
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
return user.currentSongProgress ?? 0
|
||||
const [{ songQueue }, progress] = await Promise.all([
|
||||
readPlaybackState(ctx, userId),
|
||||
readPlaybackProgress(ctx, userId),
|
||||
])
|
||||
return progress.songId === songQueue[0] ? progress.progressSeconds : 0
|
||||
},
|
||||
})
|
||||
|
||||
@@ -819,15 +770,15 @@ export const updateSongProgress = mutation({
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
const playback = await requirePlayback(ctx, userId)
|
||||
|
||||
if ((user.songQueue ?? [])[0] !== args.songId) {
|
||||
if (playback.songQueue[0] !== args.songId) {
|
||||
return
|
||||
}
|
||||
|
||||
await ctx.db.patch(userId, { currentSongProgress: args.progressSeconds })
|
||||
await writeProgress(ctx, userId, {
|
||||
songId: args.songId,
|
||||
progressSeconds: args.progressSeconds,
|
||||
})
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,236 @@
|
||||
import { ConvexError } from "convex/values"
|
||||
import type { Doc, Id } from "./_generated/dataModel"
|
||||
import type { MutationCtx, QueryCtx } from "./_generated/server"
|
||||
import { MAX_QUEUE_LENGTH } from "./limits"
|
||||
|
||||
export const MAX_QUEUE_HISTORY = 30
|
||||
|
||||
export type RepeatMode = Doc<"playbackStates">["repeatEnabled"]
|
||||
|
||||
export type PlaybackState = Pick<
|
||||
Doc<"playbackStates">,
|
||||
"songQueue" | "queueHistory" | "shuffleEnabled" | "repeatEnabled" | "revision"
|
||||
>
|
||||
|
||||
export type PlaybackProgress = {
|
||||
songId: Id<"songs"> | null
|
||||
progressSeconds: number
|
||||
}
|
||||
|
||||
export type PlaybackPatch = Partial<
|
||||
Pick<
|
||||
PlaybackState,
|
||||
"songQueue" | "queueHistory" | "shuffleEnabled" | "repeatEnabled"
|
||||
>
|
||||
> & {
|
||||
/** Saved position of the new `songQueue[0]`. */
|
||||
progressSeconds?: number
|
||||
}
|
||||
|
||||
const LEGACY_PLAYBACK_FIELDS = [
|
||||
"songQueue",
|
||||
"queueHistory",
|
||||
"currentSongProgress",
|
||||
"playbackRevision",
|
||||
"shuffleEnabled",
|
||||
"repeatEnabled",
|
||||
] as const
|
||||
|
||||
const EMPTY_STATE: PlaybackState = {
|
||||
songQueue: [],
|
||||
queueHistory: [],
|
||||
shuffleEnabled: false,
|
||||
repeatEnabled: "none",
|
||||
revision: 0,
|
||||
}
|
||||
|
||||
function legacyState(user: Doc<"users"> | null): PlaybackState {
|
||||
if (!user) {
|
||||
return EMPTY_STATE
|
||||
}
|
||||
return {
|
||||
songQueue: (user.songQueue ?? []).slice(0, MAX_QUEUE_LENGTH),
|
||||
queueHistory: (user.queueHistory ?? []).slice(-MAX_QUEUE_HISTORY),
|
||||
shuffleEnabled: user.shuffleEnabled ?? false,
|
||||
repeatEnabled: user.repeatEnabled ?? "none",
|
||||
revision: user.playbackRevision ?? 0,
|
||||
}
|
||||
}
|
||||
|
||||
function legacyProgress(user: Doc<"users"> | null): PlaybackProgress {
|
||||
return {
|
||||
songId: user?.songQueue?.[0] ?? null,
|
||||
progressSeconds: user?.currentSongProgress ?? 0,
|
||||
}
|
||||
}
|
||||
|
||||
export function hasLegacyPlayback(user: Doc<"users">) {
|
||||
return LEGACY_PLAYBACK_FIELDS.some((field) => user[field] !== undefined)
|
||||
}
|
||||
|
||||
function stateDoc(ctx: QueryCtx, userId: Id<"users">) {
|
||||
return ctx.db
|
||||
.query("playbackStates")
|
||||
.withIndex("by_user", (q) => q.eq("userId", userId))
|
||||
.unique()
|
||||
}
|
||||
|
||||
function progressDoc(ctx: QueryCtx, userId: Id<"users">) {
|
||||
return ctx.db
|
||||
.query("playbackProgress")
|
||||
.withIndex("by_user", (q) => q.eq("userId", userId))
|
||||
.unique()
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the queue without touching progress, so progress saves do not rerun
|
||||
* the caller. Users that have not been migrated yet fall back to `users`.
|
||||
*/
|
||||
export async function readPlaybackState(
|
||||
ctx: QueryCtx,
|
||||
userId: Id<"users">
|
||||
): Promise<PlaybackState> {
|
||||
const doc = await stateDoc(ctx, userId)
|
||||
if (doc) {
|
||||
return doc
|
||||
}
|
||||
return legacyState(await ctx.db.get(userId))
|
||||
}
|
||||
|
||||
export async function readPlaybackProgress(
|
||||
ctx: QueryCtx,
|
||||
userId: Id<"users">
|
||||
): Promise<PlaybackProgress> {
|
||||
const doc = await progressDoc(ctx, userId)
|
||||
if (doc) {
|
||||
return { songId: doc.songId ?? null, progressSeconds: doc.progressSeconds }
|
||||
}
|
||||
return legacyProgress(await ctx.db.get(userId))
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves a user's playback fields from `users` into `playbackStates` and
|
||||
* `playbackProgress`. Safe to call repeatedly.
|
||||
*/
|
||||
export async function migrateUserPlayback(
|
||||
ctx: MutationCtx,
|
||||
user: Doc<"users">
|
||||
) {
|
||||
const [existingState, existingProgress] = await Promise.all([
|
||||
stateDoc(ctx, user._id),
|
||||
progressDoc(ctx, user._id),
|
||||
])
|
||||
|
||||
let state = existingState
|
||||
if (!state) {
|
||||
const stateId = await ctx.db.insert("playbackStates", {
|
||||
userId: user._id,
|
||||
...legacyState(user),
|
||||
})
|
||||
state = (await ctx.db.get(stateId))!
|
||||
}
|
||||
if (!existingProgress) {
|
||||
const progress = legacyProgress(user)
|
||||
await ctx.db.insert("playbackProgress", {
|
||||
userId: user._id,
|
||||
progressSeconds: progress.progressSeconds,
|
||||
...(progress.songId ? { songId: progress.songId } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
if (hasLegacyPlayback(user)) {
|
||||
await ctx.db.patch(user._id, {
|
||||
songQueue: undefined,
|
||||
queueHistory: undefined,
|
||||
currentSongProgress: undefined,
|
||||
playbackRevision: undefined,
|
||||
shuffleEnabled: undefined,
|
||||
repeatEnabled: undefined,
|
||||
})
|
||||
}
|
||||
|
||||
return state
|
||||
}
|
||||
|
||||
/** Loads the queue in a mutation, migrating the user first if needed. */
|
||||
export async function loadPlaybackForWrite(
|
||||
ctx: MutationCtx,
|
||||
userId: Id<"users">
|
||||
) {
|
||||
const doc = await stateDoc(ctx, userId)
|
||||
if (doc) {
|
||||
return doc
|
||||
}
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
return null
|
||||
}
|
||||
return await migrateUserPlayback(ctx, user)
|
||||
}
|
||||
|
||||
/** Applies `patch`, bumps the revision, and returns the new revision. */
|
||||
export async function writePlayback(
|
||||
ctx: MutationCtx,
|
||||
userId: Id<"users">,
|
||||
patch: PlaybackPatch
|
||||
): Promise<number> {
|
||||
const doc = await loadPlaybackForWrite(ctx, userId)
|
||||
if (!doc) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
const { progressSeconds, ...fields } = patch
|
||||
const revision = doc.revision + 1
|
||||
const songQueue = fields.songQueue?.slice(0, MAX_QUEUE_LENGTH)
|
||||
const queueHistory = fields.queueHistory?.slice(-MAX_QUEUE_HISTORY)
|
||||
await ctx.db.patch(doc._id, {
|
||||
...fields,
|
||||
...(songQueue ? { songQueue } : {}),
|
||||
...(queueHistory ? { queueHistory } : {}),
|
||||
revision,
|
||||
})
|
||||
|
||||
if (progressSeconds !== undefined) {
|
||||
await writeProgress(ctx, userId, {
|
||||
songId: (songQueue ?? doc.songQueue)[0] ?? null,
|
||||
progressSeconds,
|
||||
})
|
||||
}
|
||||
return revision
|
||||
}
|
||||
|
||||
export async function writeProgress(
|
||||
ctx: MutationCtx,
|
||||
userId: Id<"users">,
|
||||
progress: PlaybackProgress
|
||||
) {
|
||||
const value = {
|
||||
songId: progress.songId ?? undefined,
|
||||
progressSeconds: Math.max(0, Math.floor(progress.progressSeconds)),
|
||||
}
|
||||
const doc = await progressDoc(ctx, userId)
|
||||
if (!doc) {
|
||||
await ctx.db.insert("playbackProgress", { userId, ...value })
|
||||
} else if (
|
||||
doc.songId !== value.songId ||
|
||||
doc.progressSeconds !== value.progressSeconds
|
||||
) {
|
||||
await ctx.db.patch(doc._id, value)
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteUserPlayback(
|
||||
ctx: MutationCtx,
|
||||
userId: Id<"users">
|
||||
) {
|
||||
const [state, progress] = await Promise.all([
|
||||
stateDoc(ctx, userId),
|
||||
progressDoc(ctx, userId),
|
||||
])
|
||||
if (state) {
|
||||
await ctx.db.delete(state._id)
|
||||
}
|
||||
if (progress) {
|
||||
await ctx.db.delete(progress._id)
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,19 @@ import { defineSchema, defineTable } from "convex/server"
|
||||
import { v } from "convex/values"
|
||||
import { authTables } from "@convex-dev/auth/server"
|
||||
|
||||
const repeatModeValidator = v.union(
|
||||
v.literal("always"),
|
||||
v.literal("once"),
|
||||
v.literal("none")
|
||||
)
|
||||
|
||||
export default defineSchema({
|
||||
...authTables,
|
||||
users: defineTable({
|
||||
name: v.string(),
|
||||
/** Legacy base64 data URL; `migrations.migrateUsers` moves it to storage. */
|
||||
image: v.optional(v.string()),
|
||||
imageStorageId: v.optional(v.id("_storage")),
|
||||
email: v.string(),
|
||||
isAdmin: v.optional(v.boolean()),
|
||||
playbackQuality: v.optional(
|
||||
@@ -22,18 +30,34 @@ export default defineSchema({
|
||||
favoriteArtists: v.optional(v.array(v.id("artists"))),
|
||||
favoriteAlbums: v.optional(v.array(v.id("albums"))),
|
||||
favoriteSongs: v.optional(v.array(v.id("songs"))),
|
||||
songQueue: v.optional(v.array(v.id("songs"))),
|
||||
queueHistory: v.optional(v.array(v.id("songs"))),
|
||||
recentlyPlayed: v.optional(
|
||||
v.array(v.union(v.id("playlists"), v.id("albums")))
|
||||
),
|
||||
// Legacy playback fields, now in `playbackStates` and `playbackProgress`.
|
||||
// `migrations.migrateUsers` clears them; drop them once every deployment
|
||||
// has run it.
|
||||
songQueue: v.optional(v.array(v.id("songs"))),
|
||||
queueHistory: v.optional(v.array(v.id("songs"))),
|
||||
currentSongProgress: v.optional(v.number()),
|
||||
playbackRevision: v.optional(v.number()),
|
||||
shuffleEnabled: v.optional(v.boolean()),
|
||||
repeatEnabled: v.optional(
|
||||
v.union(v.literal("always"), v.literal("once"), v.literal("none"))
|
||||
),
|
||||
repeatEnabled: v.optional(repeatModeValidator),
|
||||
}).index("email", ["email"]),
|
||||
playbackStates: defineTable({
|
||||
userId: v.id("users"),
|
||||
songQueue: v.array(v.id("songs")),
|
||||
queueHistory: v.array(v.id("songs")),
|
||||
shuffleEnabled: v.boolean(),
|
||||
repeatEnabled: repeatModeValidator,
|
||||
revision: v.number(),
|
||||
}).index("by_user", ["userId"]),
|
||||
// Saved every few seconds during playback, so it lives apart from the queue
|
||||
// to keep those writes from rerunning queue queries.
|
||||
playbackProgress: defineTable({
|
||||
userId: v.id("users"),
|
||||
songId: v.optional(v.id("songs")),
|
||||
progressSeconds: v.number(),
|
||||
}).index("by_user", ["userId"]),
|
||||
authVerifiers: defineTable({
|
||||
sessionId: v.optional(v.id("authSessions")),
|
||||
signature: v.optional(v.string()),
|
||||
|
||||
@@ -5,9 +5,18 @@ import {
|
||||
} from "@convex-dev/auth/server"
|
||||
import { ConvexError, v } from "convex/values"
|
||||
import { api, internal } from "./_generated/api"
|
||||
import { action, internalQuery, mutation, query } from "./_generated/server"
|
||||
import type { Id } from "./_generated/dataModel"
|
||||
import {
|
||||
action,
|
||||
internalAction,
|
||||
internalMutation,
|
||||
internalQuery,
|
||||
mutation,
|
||||
query,
|
||||
} from "./_generated/server"
|
||||
import type { Doc, Id } from "./_generated/dataModel"
|
||||
import type { ActionCtx, MutationCtx } from "./_generated/server"
|
||||
import { MAX_PROFILE_IMAGE_BYTES } from "./limits"
|
||||
import { deleteUserPlayback } from "./playbackState"
|
||||
|
||||
const playbackQualityValidator = v.union(
|
||||
v.literal("low"),
|
||||
@@ -178,18 +187,114 @@ export const listUsers = query({
|
||||
},
|
||||
})
|
||||
|
||||
const DATA_URL_PATTERN = /^data:(image\/[\w.+-]+);base64,([A-Za-z0-9+/=]+)$/
|
||||
|
||||
/** Splits an image data URL, rejecting anything over the size cap. */
|
||||
function parseImageDataUrl(image: string) {
|
||||
const match = DATA_URL_PATTERN.exec(image)
|
||||
if (!match) {
|
||||
throw new ConvexError("Profile photo must be an image")
|
||||
}
|
||||
const [, contentType, base64] = match
|
||||
if (Math.floor((base64.length * 3) / 4) > MAX_PROFILE_IMAGE_BYTES) {
|
||||
throw new ConvexError(
|
||||
`Profile photo must be ${MAX_PROFILE_IMAGE_BYTES / 1024 / 1024} MB or smaller`
|
||||
)
|
||||
}
|
||||
return { contentType, base64 }
|
||||
}
|
||||
|
||||
/**
|
||||
* Path clients load the avatar from. The web server proxies it from Convex
|
||||
* storage, since the backend's storage URLs are not reachable from browsers
|
||||
* in every deployment. Legacy data URLs are returned as is until migrated.
|
||||
*/
|
||||
export function profileImagePath(user: Doc<"users">) {
|
||||
if (user.imageStorageId) {
|
||||
return `/api/user/${user._id}/avatar?v=${user.imageStorageId}`
|
||||
}
|
||||
return user.image
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes a data URL so existing clients keep working. The image is moved into
|
||||
* file storage in the background; `currentUser` updates once it lands.
|
||||
*/
|
||||
export const updateProfileImage = mutation({
|
||||
args: {
|
||||
image: v.union(v.string(), v.null()),
|
||||
},
|
||||
handler: async (ctx, { image }) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
await ctx.db.patch(userId, {
|
||||
image: image === null ? undefined : image,
|
||||
if (image === null) {
|
||||
await setProfileImage(ctx, userId, null)
|
||||
return
|
||||
}
|
||||
parseImageDataUrl(image)
|
||||
await ctx.scheduler.runAfter(0, internal.users.storeProfileImage, {
|
||||
userId,
|
||||
image,
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
/** Decodes a data URL into file storage and points the user at it. */
|
||||
export const storeProfileImage = internalAction({
|
||||
args: { userId: v.id("users"), image: v.string() },
|
||||
handler: async (ctx, { userId, image }) => {
|
||||
const { contentType, base64 } = parseImageDataUrl(image)
|
||||
const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0))
|
||||
const storageId = await ctx.storage.store(
|
||||
new Blob([bytes], { type: contentType })
|
||||
)
|
||||
await ctx.runMutation(internal.users.attachProfileImage, {
|
||||
userId,
|
||||
storageId,
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export const attachProfileImage = internalMutation({
|
||||
args: { userId: v.id("users"), storageId: v.id("_storage") },
|
||||
handler: async (ctx, { userId, storageId }) => {
|
||||
await setProfileImage(ctx, userId, storageId)
|
||||
},
|
||||
})
|
||||
|
||||
/** Replaces the avatar, deleting the previous file. Clears it for `null`. */
|
||||
async function setProfileImage(
|
||||
ctx: MutationCtx,
|
||||
userId: Id<"users">,
|
||||
storageId: Id<"_storage"> | null
|
||||
) {
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
if (storageId) {
|
||||
await ctx.storage.delete(storageId)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (user.imageStorageId && user.imageStorageId !== storageId) {
|
||||
await ctx.storage.delete(user.imageStorageId)
|
||||
}
|
||||
await ctx.db.patch(userId, {
|
||||
image: undefined,
|
||||
imageStorageId: storageId ?? undefined,
|
||||
})
|
||||
}
|
||||
|
||||
/** Storage URL behind `profileImagePath`, for the web server's proxy route. */
|
||||
export const getProfileImageUrl = query({
|
||||
args: { userId: v.id("users") },
|
||||
handler: async (ctx, { userId }) => {
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user?.imageStorageId) {
|
||||
return null
|
||||
}
|
||||
return await ctx.storage.getUrl(user.imageStorageId)
|
||||
},
|
||||
})
|
||||
|
||||
export const updateProfileName = mutation({
|
||||
args: { name: v.string() },
|
||||
handler: async (ctx, { name }) => {
|
||||
@@ -294,6 +399,8 @@ export const deleteUser = mutation({
|
||||
throw new ConvexError("You cannot delete your own account")
|
||||
}
|
||||
await deleteOwnedPlaylists(ctx, userId)
|
||||
await deleteUserPlayback(ctx, userId)
|
||||
await setProfileImage(ctx, userId, null)
|
||||
await deleteUserAuthData(ctx, userId)
|
||||
},
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user