diff --git a/server/controllers/PodcastController.js b/server/controllers/PodcastController.js index 7d16be73c..c6ccc56a5 100644 --- a/server/controllers/PodcastController.js +++ b/server/controllers/PodcastController.js @@ -34,15 +34,14 @@ const PODCAST_LIBRARY_ITEM_ATTRIBUTES = ['id', 'libraryId', 'mediaId', 'mediaTyp const PODCAST_ACCESS_ATTRIBUTES = ['id', 'explicit', 'tags'] /** - * Validate, authorize, and resolve requested `(libraryItemId, episodeId)` pairs in request order. - * Missing episodes and non-podcast items are omitted. + * Validate a non-empty array of `{ libraryItemId, episodeId }` entries (rejecting duplicates). * - * @param {unknown} requestedEpisodes - * @param {import('../models/User')} user - * @returns {Promise<{ errorStatus?: number, errorMessage?: string, resolvedEpisodes?: Array<{ libraryItem: import('../models/LibraryItem'), episode: import('../models/PodcastEpisode') }>, matchedLibraryItemCount?: number }>} + * @param {unknown} entries + * @param {{ requirePayload?: boolean }} [options] + * @returns {{ errorStatus?: number, errorMessage?: string, libraryItemIds?: string[], episodeIds?: string[] }} */ -async function resolveRequestedPodcastEpisodes(requestedEpisodes, user) { - if (!Array.isArray(requestedEpisodes) || !requestedEpisodes.length) { +function validateEpisodeBatchEntries(entries, { requirePayload = false } = {}) { + if (!Array.isArray(entries) || !entries.length) { return { errorStatus: 400, errorMessage: 'Invalid payload' } } @@ -50,8 +49,10 @@ async function resolveRequestedPodcastEpisodes(requestedEpisodes, user) { const libraryItemIdSet = new Set() const episodeIdSet = new Set() - for (const entry of requestedEpisodes) { - if (!entry || typeof entry.libraryItemId !== 'string' || !entry.libraryItemId || typeof entry.episodeId !== 'string' || !entry.episodeId) { + for (const entry of entries) { + const hasIds = entry && typeof entry.libraryItemId === 'string' && entry.libraryItemId && typeof entry.episodeId === 'string' && entry.episodeId + const hasValidPayload = !requirePayload || (entry?.payload && typeof entry.payload === 'object') + if (!hasIds || !hasValidPayload) { return { errorStatus: 400, errorMessage: 'Invalid payload' } } const key = `${entry.libraryItemId}:${entry.episodeId}` @@ -63,20 +64,44 @@ async function resolveRequestedPodcastEpisodes(requestedEpisodes, user) { episodeIdSet.add(entry.episodeId) } - const libraryItems = await Database.libraryItemModel.findAll({ - where: { - id: [...libraryItemIdSet], - mediaType: 'podcast' - }, - attributes: PODCAST_LIBRARY_ITEM_ATTRIBUTES, - include: [ - { - model: Database.podcastModel, - attributes: PODCAST_ACCESS_ATTRIBUTES, - required: true - } - ] - }) + return { + libraryItemIds: [...libraryItemIdSet], + episodeIds: [...episodeIdSet] + } +} + +/** + * Send an error result returned by a batch validation/resolution helper. + * + * @param {Response} res + * @param {{ errorStatus?: number, errorMessage?: string }} result + */ +function sendErrorResult(res, result) { + return result.errorMessage ? res.status(result.errorStatus).send(result.errorMessage) : res.sendStatus(result.errorStatus) +} + +/** + * Validate, authorize, and resolve requested `(libraryItemId, episodeId)` pairs in request order. + * + * @param {unknown} requestedEpisodes + * @param {import('../models/User')} user + * @param {object} [options] + * @param {boolean} [options.expanded=false] - Load full expanded `LibraryItem`s (including `libraryFiles` and all `podcastEpisodes`) for mutations / socket broadcasts; otherwise query minimal attributes and only the requested episodes. + * @param {boolean} [options.requirePayload=false] - Require every entry to include a non-null `payload` object (returns `400` otherwise). + * @returns {Promise<{ errorStatus?: number, errorMessage?: string, resolvedEpisodes?: Array<{ libraryItem: import('../models/LibraryItem'), episode: import('../models/PodcastEpisode'), entry: any }>, matchedLibraryItemCount?: number }>} + */ +async function resolveRequestedPodcastEpisodes(requestedEpisodes, user, { expanded = false, requirePayload = false } = {}) { + const validated = validateEpisodeBatchEntries(requestedEpisodes, { requirePayload }) + if (validated.errorStatus) return validated + + const { libraryItemIds, episodeIds } = validated + const libraryItems = expanded + ? await Database.libraryItemModel.findAllExpandedWhere({ id: libraryItemIds, mediaType: 'podcast' }) + : await Database.libraryItemModel.findAll({ + where: { id: libraryItemIds, mediaType: 'podcast' }, + attributes: PODCAST_LIBRARY_ITEM_ATTRIBUTES, + include: [{ model: Database.podcastModel, attributes: PODCAST_ACCESS_ATTRIBUTES, required: true }] + }) for (const libraryItem of libraryItems) { if (!user.checkCanAccessLibraryItem(libraryItem)) { @@ -84,33 +109,129 @@ async function resolveRequestedPodcastEpisodes(requestedEpisodes, user) { } } - const libraryItemsById = new Map(libraryItems.map((li) => [li.id, li])) - const podcastIds = libraryItems.map((li) => li.media.id) - const episodes = podcastIds.length - ? await Database.podcastEpisodeModel.findAll({ - where: { - id: [...episodeIdSet], - podcastId: podcastIds - } - }) - : [] + const podcastItems = libraryItems.filter((li) => li.isPodcast && li.media) + const libraryItemsById = new Map(podcastItems.map((li) => [li.id, li])) + + let episodesByPodcastAndId + if (expanded) { + episodesByPodcastAndId = new Map() + for (const li of podcastItems) { + for (const ep of li.media.podcastEpisodes || []) { + episodesByPodcastAndId.set(`${li.media.id}:${ep.id}`, ep) + } + } + } else { + const podcastIds = podcastItems.map((li) => li.media.id) + const episodes = podcastIds.length ? await Database.podcastEpisodeModel.findAll({ where: { id: episodeIds, podcastId: podcastIds } }) : [] + episodesByPodcastAndId = new Map(episodes.map((ep) => [`${ep.podcastId}:${ep.id}`, ep])) + } - const episodesById = new Map(episodes.map((ep) => [ep.id, ep])) const resolvedEpisodes = [] - for (const entry of requestedEpisodes) { const libraryItem = libraryItemsById.get(entry.libraryItemId) - const episode = episodesById.get(entry.episodeId) - if (!libraryItem || !episode || episode.podcastId !== libraryItem.media.id) continue - resolvedEpisodes.push({ libraryItem, episode }) + if (!libraryItem) continue + const episode = episodesByPodcastAndId.get(`${libraryItem.media.id}:${entry.episodeId}`) + if (!episode) continue + resolvedEpisodes.push({ libraryItem, episode, entry }) } return { resolvedEpisodes, - matchedLibraryItemCount: libraryItems.length + matchedLibraryItemCount: podcastItems.length } } +/** + * Build zip archive file entries with deduplicated entry names. + * + * @param {Array<{ libraryItem: import('../models/LibraryItem'), episode: import('../models/PodcastEpisode') }>} resolvedEpisodes + * @param {boolean} includePodcastFolder + * @returns {Array<{ path: string, isFile: true, name: string }>} + */ +function buildEpisodeZipFileEntries(resolvedEpisodes, includePodcastFolder) { + const usedZipNames = new Set() + const fileEntries = [] + + const uniqueZipName = (desiredName) => { + if (!usedZipNames.has(desiredName)) { + usedZipNames.add(desiredName) + return desiredName + } + const ext = Path.extname(desiredName) + const base = ext ? desiredName.slice(0, -ext.length) : desiredName + let counter = 2 + while (usedZipNames.has(`${base} (${counter})${ext}`)) counter++ + const candidate = `${base} (${counter})${ext}` + usedZipNames.add(candidate) + return candidate + } + + for (const { libraryItem, episode } of resolvedEpisodes) { + const filePath = episode.audioFile?.metadata?.path + if (!filePath) continue + const basename = episode.audioFile.metadata.filename || Path.basename(filePath) + const rawZipName = includePodcastFolder ? `${Path.basename(libraryItem.path)}/${basename}` : basename + fileEntries.push({ path: filePath, isFile: true, name: uniqueZipName(rawZipName) }) + } + + return fileEntries +} + +/** + * Hard-delete audio files for the given episodes from disk, logging any failures. + * + * @param {import('../models/PodcastEpisode')[]} episodes + */ +async function removeEpisodeAudioFiles(episodes) { + for (const episode of episodes) { + const filePath = episode.audioFile?.metadata?.path + if (!filePath) continue + await fs + .remove(filePath) + .then(() => Logger.info(`[PodcastController] Hard deleted episode file at "${filePath}"`)) + .catch((error) => Logger.error(`[PodcastController] Failed to hard delete episode file at "${filePath}"`, error)) + } +} + +/** + * Delete episodes, their media progress, and update each affected podcast's libraryFiles and numEpisodes in one transaction. + * + * @param {string[]} removedEpisodeIds + * @param {Map} matchedByLibraryItem + */ +async function deleteEpisodesInTransaction(removedEpisodeIds, matchedByLibraryItem) { + await Database.sequelize.transaction(async (transaction) => { + const mediaProgressRemoved = await Database.mediaProgressModel.destroy({ + where: { mediaItemId: removedEpisodeIds }, + transaction + }) + if (mediaProgressRemoved) { + Logger.info(`[PodcastController] Removed ${mediaProgressRemoved} media progress entries for ${removedEpisodeIds.length} episodes`) + } + + await Database.podcastEpisodeModel.destroy({ + where: { id: removedEpisodeIds }, + transaction + }) + + for (const [libraryItem, episodesToRemove] of matchedByLibraryItem) { + const removedIdSet = new Set(episodesToRemove.map((ep) => ep.id)) + const removedInoSet = new Set(episodesToRemove.map((ep) => ep.audioFile?.ino).filter(Boolean)) + + const remainingEpisodes = (libraryItem.media.podcastEpisodes || []).filter((ep) => !removedIdSet.has(ep.id)) + libraryItem.media.podcastEpisodes = remainingEpisodes + libraryItem.media.dataValues.podcastEpisodes = remainingEpisodes + + libraryItem.libraryFiles = (libraryItem.libraryFiles || []).filter((file) => !removedInoSet.has(file.ino)) + libraryItem.changed('libraryFiles', true) + await libraryItem.save({ transaction }) + + libraryItem.media.numEpisodes = remainingEpisodes.length + await libraryItem.media.save({ transaction }) + } + }) +} + /** * Build a sanitized PodcastEpisode update object from a request body. * @@ -553,9 +674,7 @@ class PodcastController { async batchGetEpisodes(req, res) { try { const resolved = await resolveRequestedPodcastEpisodes(req.body?.episodes, req.user) - if (resolved.errorStatus) { - return resolved.errorMessage ? res.status(resolved.errorStatus).send(resolved.errorMessage) : res.sendStatus(resolved.errorStatus) - } + if (resolved.errorStatus) return sendErrorResult(res, resolved) res.json({ episodes: resolved.resolvedEpisodes.map(({ libraryItem, episode }) => episode.toOldJSONExpanded(libraryItem.id)) @@ -577,9 +696,9 @@ class PodcastController { * * Responses: * - `200`: `{ success: true, updates: number }` (count of episodes that had actual changes) - * - `400`: Empty/malformed array, duplicate `(libraryItemId, episodeId)` entry, or a referenced item is not a podcast + * - `400`: Empty/malformed array or duplicate `(libraryItemId, episodeId)` entry * - `403`: User lacks `canUpdate` or access to one or more referenced podcasts - * - `404`: One or more referenced `libraryItemId`s were not found + * - `404`: None of the requested episodes were found * - `500`: Unexpected server/database error while updating episodes * * @param {RequestWithUser} req @@ -591,66 +710,29 @@ class PodcastController { return res.sendStatus(403) } - const updatePayloads = req.body - if (!Array.isArray(updatePayloads) || !updatePayloads.length) { - Logger.error(`[PodcastController] Batch episode update failed. Invalid payload`) - return res.sendStatus(400) - } - - const seenKeys = new Set() - const libraryItemIdSet = new Set() - for (const entry of updatePayloads) { - if (!entry || typeof entry.libraryItemId !== 'string' || !entry.libraryItemId || typeof entry.episodeId !== 'string' || !entry.episodeId || !entry.payload || typeof entry.payload !== 'object') { - Logger.error(`[PodcastController] Batch episode update failed. Each entry must include libraryItemId, episodeId, and payload`) - return res.sendStatus(400) - } - const key = `${entry.libraryItemId}:${entry.episodeId}` - if (seenKeys.has(key)) { - Logger.error(`[PodcastController] Batch episode update failed. Duplicate episode entry "${key}"`) - return res.sendStatus(400) - } - seenKeys.add(key) - libraryItemIdSet.add(entry.libraryItemId) - } - try { - const libraryItemIds = [...libraryItemIdSet] - const libraryItems = await Database.libraryItemModel.findAllExpandedWhere({ - id: libraryItemIds + const resolved = await resolveRequestedPodcastEpisodes(req.body, req.user, { + expanded: true, + requirePayload: true }) - if (libraryItems.length !== libraryItemIds.length) { - Logger.error(`[PodcastController] Batch episode update failed. Not all podcasts found`) - return res.sendStatus(404) - } + if (resolved.errorStatus) return sendErrorResult(res, resolved) - for (const libraryItem of libraryItems) { - if (!libraryItem.isPodcast) { - Logger.error(`[PodcastController] Batch episode update failed. Library item "${libraryItem.id}" is not a podcast`) - return res.sendStatus(400) - } - if (!req.user.checkCanAccessLibraryItem(libraryItem)) { - return res.sendStatus(403) - } + if (!resolved.resolvedEpisodes.length) { + return res.status(404).send('Episodes not found') } - const libraryItemsById = new Map(libraryItems.map((li) => [li.id, li])) - const episodesByItemId = new Map(libraryItems.map((li) => [li.id, new Map((li.media?.podcastEpisodes || []).map((ep) => [ep.id, ep]))])) - const updatedLibraryItems = new Set() let episodesUpdated = 0 await Database.sequelize.transaction(async (transaction) => { - for (const entry of updatePayloads) { - const episode = episodesByItemId.get(entry.libraryItemId)?.get(entry.episodeId) - if (!episode) continue - + for (const { libraryItem, episode, entry } of resolved.resolvedEpisodes) { const updatePayload = buildEpisodeUpdatePayload(entry.payload) if (!Object.keys(updatePayload).length) continue episode.set(updatePayload) if (episode.changed()) { await episode.save({ transaction }) - updatedLibraryItems.add(libraryItemsById.get(entry.libraryItemId)) + updatedLibraryItems.add(libraryItem) episodesUpdated++ } } @@ -661,10 +743,7 @@ class PodcastController { SocketAuthority.libraryItemEmitter('item_updated', libraryItem) } - res.json({ - success: true, - updates: episodesUpdated - }) + res.json({ success: true, updates: episodesUpdated }) } catch (error) { Logger.error(`[PodcastController] Failed to batch update episodes`, error) return res.status(500).send('Failed to update episodes') @@ -680,11 +759,11 @@ class PodcastController { * - `hard`: `'1'` to also delete episode audio files from disk * * Request body: - * `{ episodes: Array<{ libraryItemId: string, episodeId: string }> }` (non-empty; duplicate pairs are deduplicated) + * `{ episodes: Array<{ libraryItemId: string, episodeId: string }> }` (non-empty; `(libraryItemId, episodeId)` pairs must be unique) * * Responses: * - `200`: `{ success: true, removed: number }` - * - `400`: Missing/empty `episodes` array or no valid IDs + * - `400`: Missing/empty `episodes` array, malformed entry, or duplicate `(libraryItemId, episodeId)` pair * - `403`: User lacks `canDelete` or access to one or more referenced podcasts * - `404`: None of the requested episodes were found * - `500`: Unexpected server/database error while deleting episodes @@ -699,47 +778,18 @@ class PodcastController { } const hardDelete = req.query.hard === '1' - const requestedEpisodes = req.body?.episodes - if (!Array.isArray(requestedEpisodes) || !requestedEpisodes.length) { - return res.status(400).send('Invalid payload. episodes must be a non-empty array') - } - - const libraryItemIds = [...new Set(requestedEpisodes.map((entry) => entry?.libraryItemId).filter((id) => typeof id === 'string' && id))] - const episodeIds = [...new Set(requestedEpisodes.map((entry) => entry?.episodeId).filter((id) => typeof id === 'string' && id))] - if (!libraryItemIds.length || !episodeIds.length) { - return res.status(400).send('Invalid payload. Each episode must include libraryItemId and episodeId') - } try { - const libraryItems = await Database.libraryItemModel.findAllExpandedWhere({ - id: libraryItemIds - }) + const resolved = await resolveRequestedPodcastEpisodes(req.body?.episodes, req.user, { expanded: true }) + if (resolved.errorStatus) return sendErrorResult(res, resolved) - for (const libraryItem of libraryItems) { - if (!req.user.checkCanAccessLibraryItem(libraryItem)) { - return res.sendStatus(403) - } + if (!resolved.resolvedEpisodes.length) { + return res.status(404).send('Episodes not found') } - const libraryItemsById = new Map(libraryItems.filter((li) => li.isPodcast && li.media).map((li) => [li.id, li])) - const episodesByItemId = new Map( - Array.from(libraryItemsById.values()).map((li) => [li.id, new Map((li.media.podcastEpisodes || []).map((ep) => [ep.id, ep]))]) - ) - - const seenKeys = new Set() const matchedByLibraryItem = new Map() const removedEpisodes = [] - - for (const entry of requestedEpisodes) { - if (!entry?.libraryItemId || !entry?.episodeId) continue - const key = `${entry.libraryItemId}:${entry.episodeId}` - if (seenKeys.has(key)) continue - seenKeys.add(key) - - const libraryItem = libraryItemsById.get(entry.libraryItemId) - const episode = episodesByItemId.get(entry.libraryItemId)?.get(entry.episodeId) - if (!libraryItem || !episode) continue - + for (const { libraryItem, episode } of resolved.resolvedEpisodes) { let list = matchedByLibraryItem.get(libraryItem) if (!list) { list = [] @@ -749,59 +799,13 @@ class PodcastController { removedEpisodes.push(episode) } - if (!removedEpisodes.length) { - return res.status(404).send('Episodes not found') - } - if (hardDelete) { - for (const episode of removedEpisodes) { - const filePath = episode.audioFile?.metadata?.path - if (!filePath) continue - await fs - .remove(filePath) - .then(() => { - Logger.info(`[PodcastController] Hard deleted episode file at "${filePath}"`) - }) - .catch((error) => { - Logger.error(`[PodcastController] Failed to hard delete episode file at "${filePath}"`, error) - }) - } + await removeEpisodeAudioFiles(removedEpisodes) } const removedEpisodeIds = removedEpisodes.map((ep) => ep.id) await Database.playlistModel.removeMediaItemsFromPlaylists(removedEpisodeIds) - - await Database.sequelize.transaction(async (transaction) => { - const mediaProgressRemoved = await Database.mediaProgressModel.destroy({ - where: { mediaItemId: removedEpisodeIds }, - transaction - }) - if (mediaProgressRemoved) { - Logger.info(`[PodcastController] Removed ${mediaProgressRemoved} media progress entries for ${removedEpisodeIds.length} episodes`) - } - - await Database.podcastEpisodeModel.destroy({ - where: { id: removedEpisodeIds }, - transaction - }) - - for (const [libraryItem, episodesToRemove] of matchedByLibraryItem) { - const removedIdSet = new Set(episodesToRemove.map((ep) => ep.id)) - const removedInoSet = new Set(episodesToRemove.map((ep) => ep.audioFile?.ino).filter(Boolean)) - - const remainingEpisodes = (libraryItem.media.podcastEpisodes || []).filter((ep) => !removedIdSet.has(ep.id)) - libraryItem.media.podcastEpisodes = remainingEpisodes - libraryItem.media.dataValues.podcastEpisodes = remainingEpisodes - - libraryItem.libraryFiles = (libraryItem.libraryFiles || []).filter((file) => !removedInoSet.has(file.ino)) - libraryItem.changed('libraryFiles', true) - await libraryItem.save({ transaction }) - - libraryItem.media.numEpisodes = remainingEpisodes.length - await libraryItem.media.save({ transaction }) - } - }) - + await deleteEpisodesInTransaction(removedEpisodeIds, matchedByLibraryItem) libraryItemsPodcastFilters.clearCountCache('podcastEpisode', 'afterDestroy') for (const [libraryItem, episodesToRemove] of matchedByLibraryItem) { @@ -809,10 +813,7 @@ class PodcastController { SocketAuthority.libraryItemEmitter('item_updated', libraryItem) } - res.json({ - success: true, - removed: removedEpisodeIds.length - }) + res.json({ success: true, removed: removedEpisodeIds.length }) } catch (error) { Logger.error(`[PodcastController] Failed to batch delete episodes`, error) return res.status(500).send('Failed to delete episodes') @@ -852,43 +853,9 @@ class PodcastController { return res.status(500).send('Download failed') } - if (resolved.errorStatus) { - return resolved.errorMessage ? res.status(resolved.errorStatus).send(resolved.errorMessage) : res.sendStatus(resolved.errorStatus) - } - - const includePodcastFolder = resolved.matchedLibraryItemCount > 1 - const usedZipNames = new Set() - const fileEntries = [] - - const uniqueZipName = (desiredName) => { - if (!usedZipNames.has(desiredName)) { - usedZipNames.add(desiredName) - return desiredName - } - const ext = Path.extname(desiredName) - const base = ext ? desiredName.slice(0, -ext.length) : desiredName - let counter = 2 - while (usedZipNames.has(`${base} (${counter})${ext}`)) { - counter++ - } - const candidate = `${base} (${counter})${ext}` - usedZipNames.add(candidate) - return candidate - } - - for (const { libraryItem, episode } of resolved.resolvedEpisodes) { - const filePath = episode.audioFile?.metadata?.path - if (!filePath) continue - - const basename = episode.audioFile.metadata.filename || Path.basename(filePath) - const rawZipName = includePodcastFolder ? `${Path.basename(libraryItem.path)}/${basename}` : basename - fileEntries.push({ - path: filePath, - isFile: true, - name: uniqueZipName(rawZipName) - }) - } + if (resolved.errorStatus) return sendErrorResult(res, resolved) + const fileEntries = buildEpisodeZipFileEntries(resolved.resolvedEpisodes, resolved.matchedLibraryItemCount > 1) if (!fileEntries.length) { Logger.warn(`[PodcastController] No downloadable episode files found for user "${req.user.username}"`) return res.status(404).send('No downloadable episode files found') @@ -1050,3 +1017,4 @@ class PodcastController { } module.exports = new PodcastController() module.exports.buildEpisodeUpdatePayload = buildEpisodeUpdatePayload +module.exports.validateEpisodeBatchEntries = validateEpisodeBatchEntries