596 lines
14 KiB
TypeScript
596 lines
14 KiB
TypeScript
import { getAuthUserId } from "@convex-dev/auth/server"
|
|
import { paginationOptsValidator } from "convex/server"
|
|
import { ConvexError, v } from "convex/values"
|
|
import type { Id } from "./_generated/dataModel"
|
|
import type { MutationCtx } from "./_generated/server"
|
|
import { mutation, query } from "./_generated/server"
|
|
import {
|
|
browseSongsFromIds,
|
|
type BrowseSong,
|
|
getSortedLibrarySongIds,
|
|
songsSortDirectionValidator,
|
|
songsSortKeyValidator,
|
|
} from "./library"
|
|
|
|
export type QueueSong = BrowseSong & { queueIndex: number }
|
|
export type HistorySong = BrowseSong & { historyIndex: number }
|
|
|
|
const MAX_QUEUE_HISTORY = 30
|
|
const MAX_RECENTLY_PLAYED = 30
|
|
|
|
type RecentlyPlayedItem = Id<"albums"> | Id<"playlists">
|
|
|
|
function pushRecentlyPlayed(
|
|
history: RecentlyPlayedItem[],
|
|
item: RecentlyPlayedItem
|
|
): RecentlyPlayedItem[] {
|
|
const next = [item, ...history.filter((id) => id !== item)]
|
|
if (next.length <= MAX_RECENTLY_PLAYED) {
|
|
return next
|
|
}
|
|
return next.slice(0, MAX_RECENTLY_PLAYED)
|
|
}
|
|
|
|
async function recordRecentlyPlayed(
|
|
ctx: MutationCtx,
|
|
userId: Id<"users">,
|
|
item: RecentlyPlayedItem
|
|
) {
|
|
const user = await ctx.db.get(userId)
|
|
if (!user) {
|
|
return
|
|
}
|
|
|
|
await ctx.db.patch(userId, {
|
|
recentlyPlayed: pushRecentlyPlayed(user.recentlyPlayed ?? [], item),
|
|
})
|
|
}
|
|
|
|
async function recordRecentlyPlayedFromSong(
|
|
ctx: MutationCtx,
|
|
userId: Id<"users">,
|
|
songId: Id<"songs">
|
|
) {
|
|
const song = await ctx.db.get(songId)
|
|
if (!song) {
|
|
return
|
|
}
|
|
|
|
await recordRecentlyPlayed(ctx, userId, song.album)
|
|
}
|
|
|
|
async function recordPlaybackStart(
|
|
ctx: MutationCtx,
|
|
userId: Id<"users">,
|
|
options: {
|
|
songIds: Id<"songs">[]
|
|
playlistId?: Id<"playlists">
|
|
}
|
|
) {
|
|
if (options.songIds.length === 0) {
|
|
return
|
|
}
|
|
|
|
if (options.playlistId) {
|
|
await recordRecentlyPlayed(ctx, userId, options.playlistId)
|
|
return
|
|
}
|
|
|
|
await recordRecentlyPlayedFromSong(ctx, userId, options.songIds[0])
|
|
}
|
|
|
|
function shuffleArray<T>(items: T[]): T[] {
|
|
const next = [...items]
|
|
for (let i = next.length - 1; i > 0; i--) {
|
|
const j = Math.floor(Math.random() * (i + 1))
|
|
;[next[i], next[j]] = [next[j], next[i]]
|
|
}
|
|
return next
|
|
}
|
|
|
|
async function requireAuth(ctx: MutationCtx) {
|
|
const userId = await getAuthUserId(ctx)
|
|
if (userId === null) {
|
|
throw new ConvexError("Not authenticated")
|
|
}
|
|
return userId
|
|
}
|
|
|
|
function uniqueSongIds(songIds: Id<"songs">[]) {
|
|
return [...new Set(songIds)]
|
|
}
|
|
|
|
function appendToQueueHistory(
|
|
history: Id<"songs">[],
|
|
songId: Id<"songs">
|
|
): Id<"songs">[] {
|
|
const next = [...history, songId]
|
|
if (next.length <= MAX_QUEUE_HISTORY) {
|
|
return next
|
|
}
|
|
return next.slice(next.length - MAX_QUEUE_HISTORY)
|
|
}
|
|
|
|
function appendManyToQueueHistory(
|
|
history: Id<"songs">[],
|
|
songIds: Id<"songs">[]
|
|
): Id<"songs">[] {
|
|
let next = history
|
|
for (const songId of songIds) {
|
|
next = appendToQueueHistory(next, songId)
|
|
}
|
|
return next
|
|
}
|
|
|
|
async function setQueueState(
|
|
ctx: MutationCtx,
|
|
userId: Id<"users">,
|
|
patch: {
|
|
songQueue: Id<"songs">[]
|
|
shuffleEnabled?: boolean
|
|
currentSongProgress?: number
|
|
resetHistory?: boolean
|
|
}
|
|
) {
|
|
await ctx.db.patch(userId, {
|
|
songQueue: patch.songQueue,
|
|
currentSongProgress: patch.currentSongProgress ?? 0,
|
|
...(patch.resetHistory ? { queueHistory: [] } : {}),
|
|
...(patch.shuffleEnabled !== undefined
|
|
? { shuffleEnabled: patch.shuffleEnabled }
|
|
: {}),
|
|
})
|
|
}
|
|
|
|
export const getPlaybackState = query({
|
|
args: {},
|
|
handler: async (ctx) => {
|
|
const userId = await getAuthUserId(ctx)
|
|
if (userId === null) {
|
|
return null
|
|
}
|
|
|
|
const user = await ctx.db.get(userId)
|
|
if (!user) {
|
|
return null
|
|
}
|
|
|
|
const songIds = user.songQueue ?? []
|
|
const currentSong =
|
|
songIds.length > 0
|
|
? ((await browseSongsFromIds(ctx, [songIds[0]]))[0] ?? null)
|
|
: null
|
|
|
|
return {
|
|
queueSongIds: songIds,
|
|
queueHistorySongIds: user.queueHistory ?? [],
|
|
currentSong,
|
|
shuffleEnabled: user.shuffleEnabled ?? false,
|
|
repeatEnabled: user.repeatEnabled ?? ("none" as const),
|
|
currentSongProgress: user.currentSongProgress ?? 0,
|
|
}
|
|
},
|
|
})
|
|
|
|
export const getQueueHistory = query({
|
|
args: {},
|
|
handler: async (ctx) => {
|
|
const userId = await getAuthUserId(ctx)
|
|
if (userId === null) {
|
|
return []
|
|
}
|
|
|
|
const user = await ctx.db.get(userId)
|
|
if (!user) {
|
|
return []
|
|
}
|
|
|
|
const songIds = user.queueHistory ?? []
|
|
const songs = await browseSongsFromIds(ctx, songIds)
|
|
|
|
return songs.map((song, index) => ({
|
|
...song,
|
|
historyIndex: index,
|
|
}))
|
|
},
|
|
})
|
|
|
|
export const getQueuePaginated = query({
|
|
args: {
|
|
paginationOpts: paginationOptsValidator,
|
|
queueVersion: v.string(),
|
|
},
|
|
handler: async (ctx, args) => {
|
|
const userId = await getAuthUserId(ctx)
|
|
if (userId === null) {
|
|
return { page: [], isDone: true, continueCursor: "" }
|
|
}
|
|
|
|
const user = await ctx.db.get(userId)
|
|
if (!user) {
|
|
return { page: [], isDone: true, continueCursor: "" }
|
|
}
|
|
|
|
const songIds = user.songQueue ?? []
|
|
const startIndex = args.paginationOpts.cursor
|
|
? Number.parseInt(args.paginationOpts.cursor, 10)
|
|
: 0
|
|
const endIndex = Math.min(
|
|
startIndex + args.paginationOpts.numItems,
|
|
songIds.length
|
|
)
|
|
const pageIds = songIds.slice(startIndex, endIndex)
|
|
const songs = await browseSongsFromIds(ctx, pageIds)
|
|
|
|
const page: QueueSong[] = songs.map((song, index) => ({
|
|
...song,
|
|
queueIndex: startIndex + index,
|
|
}))
|
|
|
|
const isDone = endIndex >= songIds.length
|
|
|
|
return {
|
|
page,
|
|
isDone,
|
|
continueCursor: isDone ? "" : String(endIndex),
|
|
}
|
|
},
|
|
})
|
|
|
|
export const playInOrder = mutation({
|
|
args: {
|
|
songIds: v.array(v.id("songs")),
|
|
playlistId: v.optional(v.id("playlists")),
|
|
},
|
|
handler: async (ctx, { songIds, playlistId }) => {
|
|
const userId = await requireAuth(ctx)
|
|
const queue = uniqueSongIds(songIds)
|
|
await setQueueState(ctx, userId, {
|
|
songQueue: queue,
|
|
shuffleEnabled: false,
|
|
resetHistory: true,
|
|
})
|
|
await recordPlaybackStart(ctx, userId, { songIds: queue, playlistId })
|
|
},
|
|
})
|
|
|
|
export const playShuffled = mutation({
|
|
args: {
|
|
songIds: v.array(v.id("songs")),
|
|
playlistId: v.optional(v.id("playlists")),
|
|
},
|
|
handler: async (ctx, { songIds, playlistId }) => {
|
|
const userId = await requireAuth(ctx)
|
|
const queue = shuffleArray(uniqueSongIds(songIds))
|
|
await setQueueState(ctx, userId, {
|
|
songQueue: queue,
|
|
resetHistory: true,
|
|
})
|
|
await recordPlaybackStart(ctx, userId, { songIds: queue, playlistId })
|
|
},
|
|
})
|
|
|
|
function orderSongsForInsert(
|
|
songIds: Id<"songs">[],
|
|
shuffleEnabled: boolean
|
|
): Id<"songs">[] {
|
|
return shuffleEnabled ? shuffleArray(songIds) : songIds
|
|
}
|
|
|
|
export const addToQueueNext = mutation({
|
|
args: { songIds: v.array(v.id("songs")) },
|
|
handler: async (ctx, { songIds }) => {
|
|
if (songIds.length === 0) {
|
|
return
|
|
}
|
|
|
|
const userId = await requireAuth(ctx)
|
|
const user = await ctx.db.get(userId)
|
|
if (!user) {
|
|
throw new ConvexError("User not found")
|
|
}
|
|
|
|
const toAdd = orderSongsForInsert(songIds, user.shuffleEnabled ?? false)
|
|
const queue = user.songQueue ?? []
|
|
|
|
if (queue.length === 0) {
|
|
await setQueueState(ctx, userId, { songQueue: toAdd })
|
|
return
|
|
}
|
|
|
|
const [current, ...rest] = queue
|
|
await setQueueState(ctx, userId, {
|
|
songQueue: [current, ...toAdd, ...rest],
|
|
})
|
|
},
|
|
})
|
|
|
|
export const addToQueueLast = mutation({
|
|
args: { songIds: v.array(v.id("songs")) },
|
|
handler: async (ctx, { songIds }) => {
|
|
if (songIds.length === 0) {
|
|
return
|
|
}
|
|
|
|
const userId = await requireAuth(ctx)
|
|
const user = await ctx.db.get(userId)
|
|
if (!user) {
|
|
throw new ConvexError("User not found")
|
|
}
|
|
|
|
const toAdd = orderSongsForInsert(songIds, user.shuffleEnabled ?? false)
|
|
const queue = user.songQueue ?? []
|
|
|
|
await setQueueState(ctx, userId, {
|
|
songQueue: queue.length === 0 ? toAdd : [...queue, ...toAdd],
|
|
})
|
|
},
|
|
})
|
|
|
|
export const playFromSong = mutation({
|
|
args: {
|
|
songId: v.id("songs"),
|
|
songIds: v.array(v.id("songs")),
|
|
},
|
|
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 index = songIds.indexOf(songId)
|
|
const rest = index === -1 ? [] : songIds.slice(index + 1)
|
|
const queueRest = user.shuffleEnabled ? shuffleArray(rest) : rest
|
|
|
|
await setQueueState(ctx, userId, {
|
|
songQueue: [songId, ...queueRest],
|
|
resetHistory: true,
|
|
})
|
|
await recordRecentlyPlayedFromSong(ctx, userId, songId)
|
|
},
|
|
})
|
|
|
|
export const playFromLibrarySong = mutation({
|
|
args: {
|
|
songId: v.id("songs"),
|
|
sortKey: songsSortKeyValidator,
|
|
sortDirection: songsSortDirectionValidator,
|
|
},
|
|
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 songIds = await getSortedLibrarySongIds(ctx, sortKey, sortDirection)
|
|
const index = songIds.indexOf(songId)
|
|
const rest = index === -1 ? [] : songIds.slice(index + 1)
|
|
const queueRest = user.shuffleEnabled ? shuffleArray(rest) : rest
|
|
|
|
await setQueueState(ctx, userId, {
|
|
songQueue: [songId, ...queueRest],
|
|
resetHistory: true,
|
|
})
|
|
await recordRecentlyPlayedFromSong(ctx, userId, songId)
|
|
},
|
|
})
|
|
|
|
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 shuffleEnabled = !(user.shuffleEnabled ?? false)
|
|
const queue = user.songQueue ?? []
|
|
|
|
if (shuffleEnabled && queue.length > 1) {
|
|
const [current, ...upNext] = queue
|
|
await ctx.db.patch(userId, {
|
|
shuffleEnabled: true,
|
|
songQueue: [current, ...shuffleArray(upNext)],
|
|
})
|
|
return
|
|
}
|
|
|
|
await ctx.db.patch(userId, { shuffleEnabled })
|
|
},
|
|
})
|
|
|
|
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 current = user.repeatEnabled ?? "none"
|
|
const next =
|
|
current === "none" ? "once" : current === "once" ? "always" : "none"
|
|
|
|
await ctx.db.patch(userId, { repeatEnabled: next })
|
|
},
|
|
})
|
|
|
|
export const clearQueue = mutation({
|
|
args: {},
|
|
handler: async (ctx) => {
|
|
const userId = await requireAuth(ctx)
|
|
await ctx.db.patch(userId, {
|
|
songQueue: [],
|
|
queueHistory: [],
|
|
currentSongProgress: 0,
|
|
})
|
|
},
|
|
})
|
|
|
|
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 queue = user.songQueue ?? []
|
|
const currentSongChanged =
|
|
songIds.length > 0 && songIds[0] !== queue[0]
|
|
const history =
|
|
currentSongChanged && queue.length > 0
|
|
? appendToQueueHistory(user.queueHistory ?? [], queue[0])
|
|
: (user.queueHistory ?? [])
|
|
|
|
await ctx.db.patch(userId, {
|
|
songQueue: songIds,
|
|
queueHistory: history,
|
|
...(currentSongChanged ? { currentSongProgress: 0 } : {}),
|
|
})
|
|
},
|
|
})
|
|
|
|
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 queue = user.songQueue ?? []
|
|
if (index < 0 || index >= queue.length || index === 0) {
|
|
return
|
|
}
|
|
|
|
const skipped = queue.slice(0, index)
|
|
const history = appendManyToQueueHistory(user.queueHistory ?? [], skipped)
|
|
|
|
await ctx.db.patch(userId, {
|
|
songQueue: queue.slice(index),
|
|
queueHistory: history,
|
|
currentSongProgress: 0,
|
|
})
|
|
},
|
|
})
|
|
|
|
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 queue = user.songQueue ?? []
|
|
if (queue.length === 0) {
|
|
return
|
|
}
|
|
|
|
const repeat = user.repeatEnabled ?? "none"
|
|
|
|
if (repeat === "once") {
|
|
await ctx.db.patch(userId, { currentSongProgress: 0 })
|
|
return
|
|
}
|
|
|
|
const [current, ...rest] = queue
|
|
|
|
if (repeat === "always") {
|
|
await ctx.db.patch(userId, {
|
|
songQueue: [...rest, current],
|
|
currentSongProgress: 0,
|
|
})
|
|
return
|
|
}
|
|
|
|
const history = appendToQueueHistory(user.queueHistory ?? [], current)
|
|
|
|
if (rest.length === 0) {
|
|
await ctx.db.patch(userId, {
|
|
songQueue: [],
|
|
queueHistory: history,
|
|
currentSongProgress: 0,
|
|
})
|
|
return
|
|
}
|
|
|
|
await ctx.db.patch(userId, {
|
|
songQueue: rest,
|
|
queueHistory: history,
|
|
currentSongProgress: 0,
|
|
})
|
|
},
|
|
})
|
|
|
|
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 queue = user.songQueue ?? []
|
|
const history = user.queueHistory ?? []
|
|
|
|
if (queue.length === 0) {
|
|
return
|
|
}
|
|
|
|
if (history.length === 0) {
|
|
await ctx.db.patch(userId, { currentSongProgress: 0 })
|
|
return
|
|
}
|
|
|
|
const [current, ...rest] = queue
|
|
const previous = history[history.length - 1]
|
|
const newHistory = history.slice(0, -1)
|
|
|
|
await ctx.db.patch(userId, {
|
|
songQueue: [previous, current, ...rest],
|
|
queueHistory: newHistory,
|
|
currentSongProgress: 0,
|
|
})
|
|
},
|
|
})
|
|
|
|
export const getSongProgress = query({
|
|
args: {},
|
|
handler: async (ctx) => {
|
|
const userId = await getAuthUserId(ctx)
|
|
if (userId === null) {
|
|
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
|
|
},
|
|
})
|
|
|
|
export const updateSongProgress = mutation({
|
|
args: { progressSeconds: v.number() },
|
|
handler: async (ctx, args) => {
|
|
const userId = await requireAuth(ctx)
|
|
const user = await ctx.db.get(userId)
|
|
if (!user) {
|
|
throw new ConvexError("User not found")
|
|
}
|
|
|
|
await ctx.db.patch(userId, { currentSongProgress: args.progressSeconds })
|
|
},
|
|
})
|