From b7ead7a316a688a6f1756cc08bda0c8f71750e2f Mon Sep 17 00:00:00 2001 From: mikiher Date: Thu, 3 Dec 2026 05:28:17 +0200 Subject: [PATCH 1/8] Fetch podcast episodes in a separate query in LibraryItem.findAllExpandedWhere --- server/models/LibraryItem.js | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/server/models/LibraryItem.js b/server/models/LibraryItem.js index 4876d52e6..7dcbb7ef9 100644 --- a/server/models/LibraryItem.js +++ b/server/models/LibraryItem.js @@ -148,7 +148,7 @@ class LibraryItem extends Model { * @returns {Promise} */ static async findAllExpandedWhere(where = null) { - return this.findAll({ + const libraryItems = await this.findAll({ where, include: [ { @@ -169,10 +169,7 @@ class LibraryItem extends Model { ] }, { - model: this.sequelize.models.podcast, - include: { - model: this.sequelize.models.podcastEpisode - } + model: this.sequelize.models.podcast } ], order: [ @@ -181,6 +178,31 @@ class LibraryItem extends Model { [this.sequelize.models.book, this.sequelize.models.series, 'bookSeries', 'createdAt', 'ASC'] ] }) + + // Fetch podcast episodes separately to avoid repeating libraryItem.libraryFiles on every episode row in SQLite + const podcasts = libraryItems.filter((li) => li.mediaType === 'podcast' && li.media).map((li) => li.media) + if (podcasts.length) { + const podcastIds = podcasts.map((p) => p.id) + const episodes = await this.sequelize.models.podcastEpisode.findAll({ + where: { podcastId: podcastIds } + }) + const episodesByPodcastId = new Map() + for (const episode of episodes) { + let list = episodesByPodcastId.get(episode.podcastId) + if (!list) { + list = [] + episodesByPodcastId.set(episode.podcastId, list) + } + list.push(episode) + } + for (const podcast of podcasts) { + const podcastEpisodes = episodesByPodcastId.get(podcast.id) || [] + podcast.podcastEpisodes = podcastEpisodes + podcast.dataValues.podcastEpisodes = podcastEpisodes + } + } + + return libraryItems } /** From 938fd36b1d415a34ee03e94087eb8499c718478d Mon Sep 17 00:00:00 2001 From: mikiher Date: Thu, 3 Dec 2026 05:28:49 +0200 Subject: [PATCH 2/8] Skip urlencoded body parsing for internal-api routes --- server/Server.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/server/Server.js b/server/Server.js index 0b2a0dd66..eeb737d07 100644 --- a/server/Server.js +++ b/server/Server.js @@ -337,10 +337,8 @@ class Server { this.server = http.createServer(app) - router.use(express.urlencoded({ extended: true, limit: '5mb' })) - - // Skip JSON parsing for internal-api routes - router.use(/^(?!\/internal-api).*/, express.json({ limit: '10mb' })) + // Skip body parsing for internal-api routes so Next.js receives the unread request stream + router.use(/^(?!\/internal-api).*/, express.urlencoded({ extended: true, limit: '5mb' }), express.json({ limit: '10mb' })) router.use('/api', this.auth.ifAuthNeeded(this.authMiddleware.bind(this)), this.apiRouter.router) router.use('/hls', this.hlsRouter.router) From 5ba7a3fee5a5553e74a5ca56e88fd0da1e9ba406 Mon Sep 17 00:00:00 2001 From: mikiher Date: Thu, 3 Dec 2026 05:29:22 +0200 Subject: [PATCH 3/8] Support custom entry names and abort on disconnect in zipDirectoriesPipe --- server/utils/zipHelpers.js | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/server/utils/zipHelpers.js b/server/utils/zipHelpers.js index 421ca73cd..b9acedca7 100644 --- a/server/utils/zipHelpers.js +++ b/server/utils/zipHelpers.js @@ -54,9 +54,9 @@ module.exports.zipDirectoryPipe = (path, filename, res) => { } /** - * Creates a zip archive containing multiple directories and streams it to the response. + * Creates a zip archive containing multiple directories or files and streams it to the response. * - * @param {{ path: string, isFile: boolean }[]} pathObjects + * @param {{ path: string, isFile: boolean, name?: string }[]} pathObjects * @param {string} filename - Name of the zip file to be sent as attachment. * @param {Response} res - Response object to pipe the archive data to. * @returns {Promise} - Promise that resolves when the zip operation completes. @@ -73,6 +73,9 @@ module.exports.zipDirectoriesPipe = (pathObjects, filename, res) => { // listen for all archive data to be written // 'close' event is fired only when a file descriptor is involved res.on('close', () => { + if (!res.writableEnded) { + archive.abort() + } Logger.info(archive.pointer() + ' total bytes') Logger.debug('archiver has been finalized and the output file descriptor has closed.') resolve() @@ -105,13 +108,14 @@ module.exports.zipDirectoriesPipe = (pathObjects, filename, res) => { // pipe archive data to the file archive.pipe(res) - // Add each path as a directory in the zip + // Add each path as a directory or file in the zip pathObjects.forEach((pathObject) => { + const entryName = pathObject.name || Path.basename(pathObject.path) if (!pathObject.isFile) { // Add the directory to the archive with its name as the root folder - archive.directory(pathObject.path, Path.basename(pathObject.path)) + archive.directory(pathObject.path, entryName) } else { - archive.file(pathObject.path, { name: Path.basename(pathObject.path) }) + archive.file(pathObject.path, { name: entryName }) } }) From 0f213c2b4e368d41f0f54ca93d43eadbe1f67aac Mon Sep 17 00:00:00 2001 From: mikiher Date: Thu, 3 Dec 2026 05:30:03 +0200 Subject: [PATCH 4/8] Add podcast episode batch get, update, and download endpoints --- server/controllers/PodcastController.js | 386 +++++++++++-- server/routers/ApiRouter.js | 3 + .../controllers/PodcastController.test.js | 515 ++++++++++++++++++ 3 files changed, 867 insertions(+), 37 deletions(-) create mode 100644 test/server/controllers/PodcastController.test.js diff --git a/server/controllers/PodcastController.js b/server/controllers/PodcastController.js index 5eaa2a64a..ff6bfd4c5 100644 --- a/server/controllers/PodcastController.js +++ b/server/controllers/PodcastController.js @@ -11,6 +11,7 @@ const { getPodcastFeed, findMatchingEpisodes } = require('../utils/podcastUtils' const { getFileTimestampsWithIno, filePathToPOSIX, isSameOrSubPath } = require('../utils/fileUtils') const { validateUrl } = require('../utils/index') const htmlSanitizer = require('../utils/htmlSanitizer') +const zipHelpers = require('../utils/zipHelpers') const Scanner = require('../scanner/Scanner') const CoverManager = require('../managers/CoverManager') @@ -27,6 +28,133 @@ const CoverManager = require('../managers/CoverManager') * @typedef {RequestWithUser & RequestEntityObject} RequestWithLibraryItem */ +const SUPPORTED_EPISODE_STRING_KEYS = ['title', 'subtitle', 'description', 'pubDate', 'episode', 'season', 'episodeType'] +const PODCAST_LIBRARY_ITEM_ATTRIBUTES = ['id', 'libraryId', 'mediaId', 'mediaType', 'path'] +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. + * + * @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 }>} + */ +async function resolveRequestedPodcastEpisodes(requestedEpisodes, user) { + if (!Array.isArray(requestedEpisodes) || !requestedEpisodes.length) { + return { errorStatus: 400, errorMessage: 'Invalid payload' } + } + + const seenKeys = new Set() + 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) { + return { errorStatus: 400, errorMessage: 'Invalid payload' } + } + const key = `${entry.libraryItemId}:${entry.episodeId}` + if (seenKeys.has(key)) { + return { errorStatus: 400, errorMessage: 'Invalid payload' } + } + seenKeys.add(key) + libraryItemIdSet.add(entry.libraryItemId) + 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 + } + ] + }) + + for (const libraryItem of libraryItems) { + if (!user.checkCanAccessLibraryItem(libraryItem)) { + return { errorStatus: 403 } + } + } + + 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 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 }) + } + + return { + resolvedEpisodes, + matchedLibraryItemCount: libraryItems.length + } +} + +/** + * Build a sanitized PodcastEpisode update object from a request body. + * + * @param {Record} body + * @returns {Record} + */ +function buildEpisodeUpdatePayload(body) { + const updatePayload = {} + if (!body || typeof body !== 'object') return updatePayload + + for (const key of Object.keys(body)) { + if (SUPPORTED_EPISODE_STRING_KEYS.includes(key) && typeof body[key] === 'string') { + let value = body[key] + // Sanitize description/subtitle HTML + if ((key === 'description' || key === 'subtitle') && value) { + const sanitized = htmlSanitizer.sanitize(value) + if (sanitized !== value) { + Logger.debug(`[PodcastController] Sanitized ${key} from "${value}" to "${sanitized}"`) + value = sanitized + } + } + updatePayload[key] = value + } else if (key === 'enclosure') { + const enclosure = body.enclosure + if (enclosure === null) { + updatePayload.enclosureURL = null + updatePayload.enclosureSize = null + updatePayload.enclosureType = null + } else if (enclosure && typeof enclosure === 'object' && typeof enclosure.url === 'string') { + const rawSize = enclosure.length + const parsedSize = typeof rawSize === 'number' ? rawSize : typeof rawSize === 'string' && rawSize.trim() !== '' ? Number(rawSize) : null + updatePayload.enclosureURL = enclosure.url + updatePayload.enclosureType = typeof enclosure.type === 'string' ? enclosure.type : null + updatePayload.enclosureSize = parsedSize !== null && Number.isFinite(parsedSize) && parsedSize >= 0 ? Math.trunc(parsedSize) : null + } + } else if (key === 'chapters' && Array.isArray(body[key]) && body[key].every((ch) => ch && typeof ch === 'object' && typeof ch.title === 'string' && ch.title && typeof ch.start === 'number' && Number.isFinite(ch.start))) { + updatePayload[key] = body[key] + } else if (key === 'publishedAt' && Number.isFinite(body[key])) { + updatePayload[key] = body[key] + } + } + + return updatePayload +} + class PodcastController { /** * POST /api/podcasts @@ -404,6 +532,225 @@ class PodcastController { }) } + /** + * POST: /api/podcasts/episodes/batch/get + * Fetch specific expanded podcast episodes without loading full podcast episode lists. + * + * Request body: + * `{ episodes: Array<{ libraryItemId: string, episodeId: string }> }` (non-empty; `(libraryItemId, episodeId)` pairs must be unique) + * + * Responses: + * - `200`: `{ episodes: PodcastEpisodeExpanded[] }` + * (preserves request order; missing episodes or non-podcast items are omitted) + * - `400`: Missing/empty `episodes` array, malformed entry, or duplicate `(libraryItemId, episodeId)` pair + * - `403`: User lacks access to one or more referenced podcasts + * - `500`: Failed to fetch episodes + * + * @param {RequestWithUser} req + * @param {Response} res + */ + 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) + } + + res.json({ + episodes: resolved.resolvedEpisodes.map(({ libraryItem, episode }) => episode.toOldJSONExpanded(libraryItem.id)) + }) + } catch (error) { + Logger.error(`[PodcastController] Failed to batch get episodes`, error) + return res.status(500).send('Failed to get episodes') + } + } + + /** + * POST: /api/podcasts/episodes/batch/update + * Batch-update metadata for multiple podcast episodes in a single transaction. + * Emits one `item_updated` socket event per modified podcast. Requires `user.canUpdate`. + * + * Request body: + * `Array<{ libraryItemId: string, episodeId: string, payload: EpisodeUpdatePayload }>` + * (non-empty; `(libraryItemId, episodeId)` pairs must be unique; `payload` fields match `PATCH /api/podcasts/:id/episode/:episodeId`) + * + * 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 + * - `403`: User lacks `canUpdate` or access to one or more referenced podcasts + * - `404`: One or more referenced `libraryItemId`s were not found + * + * @param {RequestWithUser} req + * @param {Response} res + */ + async batchUpdateEpisodes(req, res) { + if (!req.user.canUpdate) { + Logger.warn(`[PodcastController] User "${req.user.username}" attempted to batch update episodes without permission`) + 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) + } + + const libraryItemIds = [...libraryItemIdSet] + const libraryItems = await Database.libraryItemModel.findAllExpandedWhere({ + id: libraryItemIds + }) + if (libraryItems.length !== libraryItemIds.length) { + Logger.error(`[PodcastController] Batch episode update failed. Not all podcasts found`) + return res.sendStatus(404) + } + + 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) + } + } + + 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 + + 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)) + episodesUpdated++ + } + } + }) + + for (const libraryItem of updatedLibraryItems) { + Logger.info(`[PodcastController] Batch updated episodes for podcast "${libraryItem.media.title}"`) + SocketAuthority.libraryItemEmitter('item_updated', libraryItem) + } + + res.json({ + success: true, + updates: episodesUpdated + }) + } + + /** + * POST: /api/podcasts/episodes/batch/download + * Streams selected podcast episode audio files as an uncompressed zip archive. + * Requires `user.canDownload`. When episodes span multiple podcasts, files are grouped into + * `/` subfolders; duplicate zip paths are disambiguated with ` (2)`, etc. + * + * Request body: + * `{ episodes: Array<{ libraryItemId: string, episodeId: string }> }` (non-empty; `(libraryItemId, episodeId)` pairs must be unique) + * + * Responses: + * - `200`: Streaming zip attachment (`PodcastEpisodes-.zip`, `Content-Disposition: attachment`) + * - `400`: Missing/empty `episodes` array, malformed entry, or duplicate `(libraryItemId, episodeId)` pair + * - `403`: User lacks `canDownload` or access to one or more referenced podcasts + * - `404`: No downloadable episode audio files found for the requested IDs (or source file missing on disk) + * - `500`: Archive streaming failed before headers were sent + * + * @param {RequestWithUser} req + * @param {Response} res + */ + async batchDownloadEpisodes(req, res) { + if (!req.user.canDownload) { + Logger.warn(`[PodcastController] User "${req.user.username}" attempted to download episodes without permission`) + return res.sendStatus(403) + } + + let resolved + try { + resolved = await resolveRequestedPodcastEpisodes(req.body?.episodes, req.user) + } catch (error) { + Logger.error(`[PodcastController] Failed to resolve episodes for download`, error) + 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 (!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') + } + + const filename = `PodcastEpisodes-${Date.now()}.zip` + Logger.info(`[PodcastController] User "${req.user.username}" requested zip download for ${fileEntries.length} episode(s) "${filename}"`) + + try { + await zipHelpers.zipDirectoriesPipe(fileEntries, filename, res) + Logger.info(`[PodcastController] Downloaded ${fileEntries.length} episode(s) "${filename}"`) + } catch (error) { + Logger.error(`[PodcastController] Episode zip download failed for "${filename}"`, error) + zipHelpers.handleDownloadError(error, res) + } + } + /** * PATCH: /api/podcasts/:id/episode/:episodeId * @@ -417,43 +764,7 @@ class PodcastController { return res.status(404).send('Episode not found') } - const updatePayload = {} - const supportedStringKeys = ['title', 'subtitle', 'description', 'pubDate', 'episode', 'season', 'episodeType'] - for (const key in req.body) { - if (supportedStringKeys.includes(key) && typeof req.body[key] === 'string') { - // Sanitize description HTML - if (key === 'description' && req.body[key]) { - const sanitizedDescription = htmlSanitizer.sanitize(req.body[key]) - if (sanitizedDescription !== req.body[key]) { - Logger.debug(`[PodcastController] Sanitized description from "${req.body[key]}" to "${sanitizedDescription}"`) - req.body[key] = sanitizedDescription - } - } else if (key === 'subtitle' && req.body[key]) { - const sanitizedSubtitle = htmlSanitizer.sanitize(req.body[key]) - if (sanitizedSubtitle !== req.body[key]) { - Logger.debug(`[PodcastController] Sanitized subtitle from "${req.body[key]}" to "${sanitizedSubtitle}"`) - req.body[key] = sanitizedSubtitle - } - } - - updatePayload[key] = req.body[key] - } else if (key === 'enclosure') { - const enclosure = req.body.enclosure - if (enclosure === null) { - updatePayload.enclosureURL = null - updatePayload.enclosureSize = null - updatePayload.enclosureType = null - } else if (typeof enclosure === 'object' && typeof enclosure.url === 'string') { - updatePayload.enclosureURL = enclosure.url - updatePayload.enclosureType = typeof enclosure.type === 'string' ? enclosure.type : null - updatePayload.enclosureSize = enclosure.length !== undefined && enclosure.length !== null ? enclosure.length : null - } - } else if (key === 'chapters' && Array.isArray(req.body[key]) && req.body[key].every((ch) => typeof ch === 'object' && ch.title && ch.start)) { - updatePayload[key] = req.body[key] - } else if (key === 'publishedAt' && typeof req.body[key] === 'number') { - updatePayload[key] = req.body[key] - } - } + const updatePayload = buildEpisodeUpdatePayload(req.body) if (Object.keys(updatePayload).length) { episode.set(updatePayload) @@ -583,3 +894,4 @@ class PodcastController { } } module.exports = new PodcastController() +module.exports.buildEpisodeUpdatePayload = buildEpisodeUpdatePayload diff --git a/server/routers/ApiRouter.js b/server/routers/ApiRouter.js index 392465ea8..daaf79a02 100644 --- a/server/routers/ApiRouter.js +++ b/server/routers/ApiRouter.js @@ -250,6 +250,9 @@ class ApiRouter { this.router.post('/podcasts/feed', PodcastController.getPodcastFeed.bind(this)) this.router.post('/podcasts/opml/parse', PodcastController.getFeedsFromOPMLText.bind(this)) this.router.post('/podcasts/opml/create', PodcastController.bulkCreatePodcastsFromOpmlFeedUrls.bind(this)) + this.router.post('/podcasts/episodes/batch/get', PodcastController.batchGetEpisodes.bind(this)) + this.router.post('/podcasts/episodes/batch/update', PodcastController.batchUpdateEpisodes.bind(this)) + this.router.post('/podcasts/episodes/batch/download', PodcastController.batchDownloadEpisodes.bind(this)) this.router.get('/podcasts/:id/checknew', PodcastController.middleware.bind(this), PodcastController.checkNewEpisodes.bind(this)) this.router.get('/podcasts/:id/downloads', PodcastController.middleware.bind(this), PodcastController.getEpisodeDownloads.bind(this)) this.router.get('/podcasts/:id/clear-queue', PodcastController.middleware.bind(this), PodcastController.clearEpisodeDownloadQueue.bind(this)) diff --git a/test/server/controllers/PodcastController.test.js b/test/server/controllers/PodcastController.test.js new file mode 100644 index 000000000..c7d9c1d59 --- /dev/null +++ b/test/server/controllers/PodcastController.test.js @@ -0,0 +1,515 @@ +const { expect } = require('chai') +const { Sequelize } = require('sequelize') +const sinon = require('sinon') + +const Database = require('../../../server/Database') +const PodcastController = require('../../../server/controllers/PodcastController') +const Logger = require('../../../server/Logger') +const zipHelpers = require('../../../server/utils/zipHelpers') + +const { buildEpisodeUpdatePayload } = PodcastController + +describe('PodcastController.buildEpisodeUpdatePayload', () => { + beforeEach(() => { + sinon.stub(Logger, 'debug') + }) + + afterEach(() => { + sinon.restore() + }) + + it('returns an empty object for null, undefined, or non-object input', () => { + expect(buildEpisodeUpdatePayload(null)).to.deep.equal({}) + expect(buildEpisodeUpdatePayload(undefined)).to.deep.equal({}) + expect(buildEpisodeUpdatePayload('invalid')).to.deep.equal({}) + }) + + it('copies supported string fields and ignores unknown or non-string fields', () => { + const result = buildEpisodeUpdatePayload({ + title: 'Episode 1', + pubDate: 'Mon, 01 Jan 2024 00:00:00 GMT', + episode: '1', + season: '2', + episodeType: 'full', + // ignored + id: 'override-id', + podcastId: 'override-podcast', + audioFile: { path: '/etc/passwd' }, + seasonNumber: 2, + title2: 'ignored', + episode2: 123 + }) + + expect(result).to.deep.equal({ + title: 'Episode 1', + pubDate: 'Mon, 01 Jan 2024 00:00:00 GMT', + episode: '1', + season: '2', + episodeType: 'full' + }) + }) + + it('ignores non-string values for supported string fields', () => { + expect(buildEpisodeUpdatePayload({ title: 123, season: null, description: {} })).to.deep.equal({}) + }) + + it('sanitizes HTML in description and subtitle while keeping allowed tags and links', () => { + const result = buildEpisodeUpdatePayload({ + description: '

Hello

okbad', + subtitle: 'Sub' + }) + + expect(result.description).to.equal('

Hello

okbad') + expect(result.subtitle).to.equal('Sub') + }) + + it('clears enclosure columns when enclosure is null', () => { + expect(buildEpisodeUpdatePayload({ enclosure: null })).to.deep.equal({ + enclosureURL: null, + enclosureSize: null, + enclosureType: null + }) + }) + + it('maps valid enclosure fields and normalizes enclosureSize', () => { + expect( + buildEpisodeUpdatePayload({ + enclosure: { url: 'https://example.com/ep.mp3', type: 'audio/mpeg', length: '123456' } + }) + ).to.deep.equal({ + enclosureURL: 'https://example.com/ep.mp3', + enclosureType: 'audio/mpeg', + enclosureSize: 123456 + }) + + expect( + buildEpisodeUpdatePayload({ + enclosure: { url: 'https://example.com/ep.mp3', length: 987.9 } + }) + ).to.deep.equal({ + enclosureURL: 'https://example.com/ep.mp3', + enclosureType: null, + enclosureSize: 987 + }) + + expect( + buildEpisodeUpdatePayload({ + enclosure: { url: 'https://example.com/ep.mp3', length: -5 } + }) + ).to.deep.equal({ + enclosureURL: 'https://example.com/ep.mp3', + enclosureType: null, + enclosureSize: null + }) + + expect( + buildEpisodeUpdatePayload({ + enclosure: { url: 'https://example.com/ep.mp3', length: { bad: true } } + }) + ).to.deep.equal({ + enclosureURL: 'https://example.com/ep.mp3', + enclosureType: null, + enclosureSize: null + }) + + expect(buildEpisodeUpdatePayload({ enclosure: { type: 'audio/mpeg' } })).to.deep.equal({}) + }) + + it('accepts chapters starting at 0 and rejects invalid chapter arrays', () => { + const validChapters = [ + { id: 0, start: 0, end: 60, title: 'Intro' }, + { id: 1, start: 60, end: 180, title: 'Main' } + ] + expect(buildEpisodeUpdatePayload({ chapters: validChapters })).to.deep.equal({ chapters: validChapters }) + + expect(buildEpisodeUpdatePayload({ chapters: [null] })).to.deep.equal({}) + expect(buildEpisodeUpdatePayload({ chapters: [{ start: 0, title: '' }] })).to.deep.equal({}) + expect(buildEpisodeUpdatePayload({ chapters: [{ start: '0', title: 'Intro' }] })).to.deep.equal({}) + expect(buildEpisodeUpdatePayload({ chapters: [{ start: Number.NaN, title: 'Intro' }] })).to.deep.equal({}) + }) + + it('accepts finite publishedAt timestamps and rejects NaN, Infinity, or non-numbers', () => { + expect(buildEpisodeUpdatePayload({ publishedAt: 1700000000000 })).to.deep.equal({ publishedAt: 1700000000000 }) + expect(buildEpisodeUpdatePayload({ publishedAt: 0 })).to.deep.equal({ publishedAt: 0 }) + expect(buildEpisodeUpdatePayload({ publishedAt: Number.NaN })).to.deep.equal({}) + expect(buildEpisodeUpdatePayload({ publishedAt: Number.POSITIVE_INFINITY })).to.deep.equal({}) + expect(buildEpisodeUpdatePayload({ publishedAt: '1700000000000' })).to.deep.equal({}) + }) +}) + +describe('PodcastController batch episode endpoints', () => { + let library + let libraryFolder + let podcastItem1 + let podcastItem2 + let episode1 + let episode2 + let episode3 + let user + + function createFakeRes() { + return { + status: sinon.stub().returnsThis(), + send: sinon.spy(), + sendStatus: sinon.spy(), + json: sinon.spy() + } + } + + function createAudioFile(filename, filePath, ino = '1') { + return { + ino, + duration: 120, + metadata: { + filename, + path: filePath, + size: 1024 + } + } + } + + beforeEach(async () => { + global.ServerSettings = {} + Database.sequelize = new Sequelize({ dialect: 'sqlite', storage: ':memory:', logging: false }) + Database.sequelize.uppercaseFirst = (str) => (str ? `${str[0].toUpperCase()}${str.substr(1)}` : '') + await Database.buildModels() + + sinon.stub(Logger, 'info') + sinon.stub(Logger, 'debug') + sinon.stub(Logger, 'warn') + sinon.stub(Logger, 'error') + + library = await Database.libraryModel.create({ name: 'Podcasts', mediaType: 'podcast' }) + libraryFolder = await Database.libraryFolderModel.create({ path: '/podcasts', libraryId: library.id }) + + const podcast1 = await Database.podcastModel.create({ + title: 'Podcast One', + explicit: false, + tags: ['tech'], + genres: [] + }) + podcastItem1 = await Database.libraryItemModel.create({ + path: '/podcasts/podcast-one', + libraryFiles: [{ ino: 'huge-blob-sentinel' }], + mediaId: podcast1.id, + mediaType: 'podcast', + libraryId: library.id, + libraryFolderId: libraryFolder.id + }) + + const podcast2 = await Database.podcastModel.create({ + title: '', + explicit: true, + tags: ['restricted'], + genres: [] + }) + podcastItem2 = await Database.libraryItemModel.create({ + path: '/podcasts/podcast-two', + libraryFiles: [], + mediaId: podcast2.id, + mediaType: 'podcast', + libraryId: library.id, + libraryFolderId: libraryFolder.id + }) + + episode1 = await Database.podcastEpisodeModel.create({ + title: 'Ep 1', + podcastId: podcast1.id, + audioFile: createAudioFile('ep1.mp3', '/podcasts/podcast-one/ep1.mp3', '101'), + chapters: [], + extraData: {} + }) + episode2 = await Database.podcastEpisodeModel.create({ + title: 'Ep 2', + podcastId: podcast1.id, + audioFile: createAudioFile('ep2.mp3', '/podcasts/podcast-one/ep2.mp3', '102'), + chapters: [], + extraData: {} + }) + episode3 = await Database.podcastEpisodeModel.create({ + title: 'Ep 3', + podcastId: podcast2.id, + audioFile: createAudioFile('ep1.mp3', '/podcasts/podcast-two/ep1.mp3', '103'), + chapters: [], + extraData: {} + }) + + user = await Database.userModel.create({ + username: 'tester', + type: 'user', + isActive: true, + permissions: { + download: true, + update: true, + delete: false, + upload: false, + accessAllLibraries: true, + accessAllTags: true, + accessExplicitContent: true + } + }) + }) + + afterEach(async () => { + sinon.restore() + await Database.sequelize.sync({ force: true }) + }) + + describe('batchGetEpisodes', () => { + it('returns 400 when episodes payload is missing, empty, contains any malformed entry, or has duplicate pairs', async () => { + const findSpy = sinon.spy(Database.libraryItemModel, 'findAll') + + for (const body of [ + {}, + { episodes: [] }, + { episodes: [{ libraryItemId: podcastItem1.id }, { episodeId: episode1.id }] }, + { episodes: [{ libraryItemId: 123, episodeId: episode1.id }] }, + { episodes: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }, { libraryItemId: podcastItem1.id }] }, + { + episodes: [ + { libraryItemId: podcastItem1.id, episodeId: episode1.id }, + { libraryItemId: podcastItem1.id, episodeId: episode1.id } + ] + } + ]) { + const res = createFakeRes() + await PodcastController.batchGetEpisodes({ body, user }, res) + expect(res.status.calledOnceWith(400)).to.be.true + expect(res.send.calledOnceWith('Invalid payload')).to.be.true + } + + expect(findSpy.called).to.be.false + }) + + it('preserves request order, omits missing/non-podcast entries, and returns expanded episodes', async () => { + const book = await Database.bookModel.create({ title: 'A Book', audioFiles: [], tags: [], narrators: [], genres: [], chapters: [] }) + const bookItem = await Database.libraryItemModel.create({ + libraryFiles: [], + mediaId: book.id, + mediaType: 'book', + libraryId: library.id, + libraryFolderId: libraryFolder.id + }) + + const res = createFakeRes() + await PodcastController.batchGetEpisodes( + { + user, + body: { + episodes: [ + { libraryItemId: podcastItem2.id, episodeId: episode3.id }, + { libraryItemId: podcastItem1.id, episodeId: episode2.id }, + { libraryItemId: podcastItem1.id, episodeId: 'missing-episode' }, + { libraryItemId: bookItem.id, episodeId: episode1.id }, + { libraryItemId: podcastItem1.id, episodeId: episode1.id } + ] + } + }, + res + ) + + expect(res.json.calledOnce).to.be.true + const { episodes } = res.json.firstCall.args[0] + expect(episodes.map((e) => `${e.libraryItemId}:${e.id}`)).to.deep.equal([`${podcastItem2.id}:${episode3.id}`, `${podcastItem1.id}:${episode2.id}`, `${podcastItem1.id}:${episode1.id}`]) + expect(episodes[1].audioTrack.contentUrl).to.equal(`/api/items/${podcastItem1.id}/file/102`) + expect(episodes[1].duration).to.equal(120) + }) + + it('omits cross-podcast mismatched (libraryItemId, episodeId) pairs', async () => { + const res = createFakeRes() + await PodcastController.batchGetEpisodes( + { + user, + body: { + episodes: [ + { libraryItemId: podcastItem1.id, episodeId: episode3.id }, + { libraryItemId: podcastItem2.id, episodeId: episode1.id } + ] + } + }, + res + ) + + expect(res.json.calledOnce).to.be.true + expect(res.json.firstCall.args[0]).to.deep.equal({ episodes: [] }) + }) + + it('returns 403 when user lacks access to a referenced podcast', async () => { + user.permissions = { + ...user.permissions, + accessExplicitContent: false + } + + const res = createFakeRes() + await PodcastController.batchGetEpisodes( + { + user, + body: { + episodes: [ + { libraryItemId: podcastItem1.id, episodeId: episode1.id }, + { libraryItemId: podcastItem2.id, episodeId: episode3.id } + ] + } + }, + res + ) + + expect(res.sendStatus.calledOnceWith(403)).to.be.true + expect(res.json.called).to.be.false + }) + + it('excludes orphaned podcast library items with missing media without crashing access checks', async () => { + const orphanedItem = await Database.libraryItemModel.create({ + libraryFiles: [], + mediaId: '00000000-0000-4000-8000-000000000999', + mediaType: 'podcast', + libraryId: library.id, + libraryFolderId: libraryFolder.id + }) + + const res = createFakeRes() + await PodcastController.batchGetEpisodes( + { + user, + body: { + episodes: [ + { libraryItemId: orphanedItem.id, episodeId: episode1.id }, + { libraryItemId: podcastItem1.id, episodeId: episode1.id } + ] + } + }, + res + ) + + expect(res.json.calledOnce).to.be.true + expect(res.json.firstCall.args[0].episodes).to.have.lengthOf(1) + expect(res.json.firstCall.args[0].episodes[0].id).to.equal(episode1.id) + }) + + it('projects only required libraryItem and podcast attributes and uses required inner join', async () => { + const findSpy = sinon.spy(Database.libraryItemModel, 'findAll') + + const res = createFakeRes() + await PodcastController.batchGetEpisodes( + { + user, + body: { + episodes: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }] + } + }, + res + ) + + expect(findSpy.calledOnce).to.be.true + const queryOptions = findSpy.firstCall.args[0] + expect(queryOptions.attributes).to.deep.equal(['id', 'libraryId', 'mediaId', 'mediaType', 'path']) + expect(queryOptions.attributes).to.not.include('libraryFiles') + expect(queryOptions.include[0].required).to.be.true + expect(queryOptions.include[0].attributes).to.deep.equal(['id', 'explicit', 'tags']) + }) + + it('returns 500 when a database query throws unexpectedly', async () => { + sinon.stub(Database.libraryItemModel, 'findAll').rejects(new Error('SQLITE_BUSY')) + + const res = createFakeRes() + await PodcastController.batchGetEpisodes( + { + user, + body: { + episodes: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }] + } + }, + res + ) + + expect(res.status.calledOnceWith(500)).to.be.true + expect(res.send.calledOnceWith('Failed to get episodes')).to.be.true + expect(Logger.error.calledOnce).to.be.true + }) + }) + + describe('batchDownloadEpisodes', () => { + it('returns 400 for mismatched partial entries without querying DB', async () => { + const findSpy = sinon.spy(Database.libraryItemModel, 'findAll') + const res = createFakeRes() + + await PodcastController.batchDownloadEpisodes( + { + user, + body: { + episodes: [{ libraryItemId: podcastItem1.id }, { episodeId: episode1.id }] + } + }, + res + ) + + expect(res.status.calledOnceWith(400)).to.be.true + expect(findSpy.called).to.be.false + }) + + it('returns 400 for duplicate pairs without querying DB', async () => { + const findSpy = sinon.spy(Database.libraryItemModel, 'findAll') + const res = createFakeRes() + + await PodcastController.batchDownloadEpisodes( + { + user, + body: { + episodes: [ + { libraryItemId: podcastItem1.id, episodeId: episode1.id }, + { libraryItemId: podcastItem1.id, episodeId: episode1.id } + ] + } + }, + res + ) + + expect(res.status.calledOnceWith(400)).to.be.true + expect(findSpy.called).to.be.false + }) + + it('groups multi-podcast episodes into podcast folders', async () => { + const zipStub = sinon.stub(zipHelpers, 'zipDirectoriesPipe').resolves() + const res = createFakeRes() + + await PodcastController.batchDownloadEpisodes( + { + user, + body: { + episodes: [ + { libraryItemId: podcastItem1.id, episodeId: episode1.id }, + { libraryItemId: podcastItem2.id, episodeId: episode3.id } + ] + } + }, + res + ) + + expect(zipStub.calledOnce).to.be.true + const [fileEntries] = zipStub.firstCall.args + expect(fileEntries).to.deep.equal([ + { path: '/podcasts/podcast-one/ep1.mp3', isFile: true, name: 'podcast-one/ep1.mp3' }, + { path: '/podcasts/podcast-two/ep1.mp3', isFile: true, name: 'podcast-two/ep1.mp3' } + ]) + }) + + it('returns 500 when episode resolution fails unexpectedly', async () => { + sinon.stub(Database.libraryItemModel, 'findAll').rejects(new Error('SQLITE_BUSY')) + const res = createFakeRes() + + await PodcastController.batchDownloadEpisodes( + { + user, + body: { + episodes: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }] + } + }, + res + ) + + expect(res.status.calledOnceWith(500)).to.be.true + expect(res.send.calledOnceWith('Download failed')).to.be.true + expect(Logger.error.calledOnce).to.be.true + }) + }) +}) From df5522b56959ccd5e77851ab5a881f7b24162073 Mon Sep 17 00:00:00 2001 From: mikiher Date: Thu, 3 Dec 2026 05:48:24 +0200 Subject: [PATCH 5/8] Add podcast episode batch delete endpoint --- server/controllers/PodcastController.js | 243 +++++++++++++++++++----- server/routers/ApiRouter.js | 1 + 2 files changed, 200 insertions(+), 44 deletions(-) diff --git a/server/controllers/PodcastController.js b/server/controllers/PodcastController.js index ff6bfd4c5..7d16be73c 100644 --- a/server/controllers/PodcastController.js +++ b/server/controllers/PodcastController.js @@ -12,6 +12,7 @@ const { getFileTimestampsWithIno, filePathToPOSIX, isSameOrSubPath } = require(' const { validateUrl } = require('../utils/index') const htmlSanitizer = require('../utils/htmlSanitizer') const zipHelpers = require('../utils/zipHelpers') +const libraryItemsPodcastFilters = require('../utils/queries/libraryItemsPodcastFilters') const Scanner = require('../scanner/Scanner') const CoverManager = require('../managers/CoverManager') @@ -579,6 +580,7 @@ class PodcastController { * - `400`: Empty/malformed array, duplicate `(libraryItemId, episodeId)` entry, or a referenced item is not a podcast * - `403`: User lacks `canUpdate` or access to one or more referenced podcasts * - `404`: One or more referenced `libraryItemId`s were not found + * - `500`: Unexpected server/database error while updating episodes * * @param {RequestWithUser} req * @param {Response} res @@ -611,57 +613,210 @@ class PodcastController { libraryItemIdSet.add(entry.libraryItemId) } - const libraryItemIds = [...libraryItemIdSet] - const libraryItems = await Database.libraryItemModel.findAllExpandedWhere({ - id: libraryItemIds - }) - if (libraryItems.length !== libraryItemIds.length) { - Logger.error(`[PodcastController] Batch episode update failed. Not all podcasts found`) - return res.sendStatus(404) - } - - 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) + try { + const libraryItemIds = [...libraryItemIdSet] + const libraryItems = await Database.libraryItemModel.findAllExpandedWhere({ + id: libraryItemIds + }) + if (libraryItems.length !== libraryItemIds.length) { + Logger.error(`[PodcastController] Batch episode update failed. Not all podcasts found`) + return res.sendStatus(404) } - if (!req.user.checkCanAccessLibraryItem(libraryItem)) { - return res.sendStatus(403) - } - } - 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 - - 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)) - episodesUpdated++ + 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) } } - }) - for (const libraryItem of updatedLibraryItems) { - Logger.info(`[PodcastController] Batch updated episodes for podcast "${libraryItem.media.title}"`) - SocketAuthority.libraryItemEmitter('item_updated', libraryItem) + 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 + + 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)) + episodesUpdated++ + } + } + }) + + for (const libraryItem of updatedLibraryItems) { + Logger.info(`[PodcastController] Batch updated episodes for podcast "${libraryItem.media.title}"`) + SocketAuthority.libraryItemEmitter('item_updated', libraryItem) + } + + 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') + } + } + + /** + * POST: /api/podcasts/episodes/batch/delete?hard=1 + * Batch-delete multiple podcast episodes, cleaning up playlists, media progress, and library files. + * Emits one `item_updated` socket event per modified podcast. Requires `user.canDelete`. + * + * Query params: + * - `hard`: `'1'` to also delete episode audio files from disk + * + * Request body: + * `{ episodes: Array<{ libraryItemId: string, episodeId: string }> }` (non-empty; duplicate pairs are deduplicated) + * + * Responses: + * - `200`: `{ success: true, removed: number }` + * - `400`: Missing/empty `episodes` array or no valid IDs + * - `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 + * + * @param {RequestWithUser} req + * @param {Response} res + */ + async batchDeleteEpisodes(req, res) { + if (!req.user.canDelete) { + Logger.warn(`[PodcastController] User "${req.user.username}" attempted to batch delete episodes without permission`) + return res.sendStatus(403) } - res.json({ - success: true, - updates: episodesUpdated - }) + 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 + }) + + for (const libraryItem of libraryItems) { + if (!req.user.checkCanAccessLibraryItem(libraryItem)) { + return res.sendStatus(403) + } + } + + 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 + + let list = matchedByLibraryItem.get(libraryItem) + if (!list) { + list = [] + matchedByLibraryItem.set(libraryItem, list) + } + list.push(episode) + 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) + }) + } + } + + 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 }) + } + }) + + libraryItemsPodcastFilters.clearCountCache('podcastEpisode', 'afterDestroy') + + for (const [libraryItem, episodesToRemove] of matchedByLibraryItem) { + Logger.info(`[PodcastController] Batch deleted ${episodesToRemove.length} episode(s) from podcast "${libraryItem.media.title}"`) + SocketAuthority.libraryItemEmitter('item_updated', libraryItem) + } + + 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') + } } /** diff --git a/server/routers/ApiRouter.js b/server/routers/ApiRouter.js index daaf79a02..8afa652a8 100644 --- a/server/routers/ApiRouter.js +++ b/server/routers/ApiRouter.js @@ -252,6 +252,7 @@ class ApiRouter { this.router.post('/podcasts/opml/create', PodcastController.bulkCreatePodcastsFromOpmlFeedUrls.bind(this)) this.router.post('/podcasts/episodes/batch/get', PodcastController.batchGetEpisodes.bind(this)) this.router.post('/podcasts/episodes/batch/update', PodcastController.batchUpdateEpisodes.bind(this)) + this.router.post('/podcasts/episodes/batch/delete', PodcastController.batchDeleteEpisodes.bind(this)) this.router.post('/podcasts/episodes/batch/download', PodcastController.batchDownloadEpisodes.bind(this)) this.router.get('/podcasts/:id/checknew', PodcastController.middleware.bind(this), PodcastController.checkNewEpisodes.bind(this)) this.router.get('/podcasts/:id/downloads', PodcastController.middleware.bind(this), PodcastController.getEpisodeDownloads.bind(this)) From b7c0e039c84165c8dc7d6ffc2e03c03850496803 Mon Sep 17 00:00:00 2001 From: mikiher Date: Thu, 3 Dec 2026 07:03:10 +0200 Subject: [PATCH 6/8] Refactor podcast episode batch handlers to share validation and resolution helpers --- server/controllers/PodcastController.js | 402 +++++++++++------------- 1 file changed, 185 insertions(+), 217 deletions(-) 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 From 177b945c601de15d0b4a5e15c987687b77134e07 Mon Sep 17 00:00:00 2001 From: mikiher Date: Thu, 3 Dec 2026 07:03:37 +0200 Subject: [PATCH 7/8] Add unit tests for podcast episode batch update, delete, download, and validation --- .../controllers/PodcastController.test.js | 532 ++++++++++++++++-- 1 file changed, 496 insertions(+), 36 deletions(-) diff --git a/test/server/controllers/PodcastController.test.js b/test/server/controllers/PodcastController.test.js index c7d9c1d59..4e1a4c3ef 100644 --- a/test/server/controllers/PodcastController.test.js +++ b/test/server/controllers/PodcastController.test.js @@ -5,9 +5,12 @@ const sinon = require('sinon') const Database = require('../../../server/Database') const PodcastController = require('../../../server/controllers/PodcastController') const Logger = require('../../../server/Logger') +const SocketAuthority = require('../../../server/SocketAuthority') +const fs = require('../../../server/libs/fsExtra') +const libraryItemsPodcastFilters = require('../../../server/utils/queries/libraryItemsPodcastFilters') const zipHelpers = require('../../../server/utils/zipHelpers') -const { buildEpisodeUpdatePayload } = PodcastController +const { buildEpisodeUpdatePayload, validateEpisodeBatchEntries } = PodcastController describe('PodcastController.buildEpisodeUpdatePayload', () => { beforeEach(() => { @@ -137,6 +140,56 @@ describe('PodcastController.buildEpisodeUpdatePayload', () => { }) }) +describe('PodcastController.validateEpisodeBatchEntries', () => { + it('returns 400 when entries are missing, empty, malformed, or contain duplicate pairs', () => { + for (const entries of [ + undefined, + null, + 'invalid', + [], + [{ libraryItemId: 'li1' }, { episodeId: 'ep1' }], + [{ libraryItemId: 123, episodeId: 'ep1' }], + [{ libraryItemId: 'li1', episodeId: 'ep1' }, { libraryItemId: 'li1' }], + [ + { libraryItemId: 'li1', episodeId: 'ep1' }, + { libraryItemId: 'li1', episodeId: 'ep1' } + ] + ]) { + expect(validateEpisodeBatchEntries(entries)).to.deep.equal({ errorStatus: 400, errorMessage: 'Invalid payload' }) + } + }) + + it('requires a non-null payload object on every entry when requirePayload is true', () => { + for (const entries of [ + [{ libraryItemId: 'li1', episodeId: 'ep1' }], + [{ libraryItemId: 'li1', episodeId: 'ep1', payload: null }], + [{ libraryItemId: 'li1', episodeId: 'ep1', payload: 'bad' }] + ]) { + expect(validateEpisodeBatchEntries(entries, { requirePayload: true })).to.deep.equal({ + errorStatus: 400, + errorMessage: 'Invalid payload' + }) + } + + expect( + validateEpisodeBatchEntries([{ libraryItemId: 'li1', episodeId: 'ep1', payload: { title: 'A' } }], { requirePayload: true }) + ).to.deep.equal({ libraryItemIds: ['li1'], episodeIds: ['ep1'] }) + }) + + it('returns deduplicated libraryItemIds and episodeIds for valid entries', () => { + expect( + validateEpisodeBatchEntries([ + { libraryItemId: 'li1', episodeId: 'ep1' }, + { libraryItemId: 'li1', episodeId: 'ep2' }, + { libraryItemId: 'li2', episodeId: 'ep3' } + ]) + ).to.deep.equal({ + libraryItemIds: ['li1', 'li2'], + episodeIds: ['ep1', 'ep2', 'ep3'] + }) + }) +}) + describe('PodcastController batch episode endpoints', () => { let library let libraryFolder @@ -255,32 +308,28 @@ describe('PodcastController batch episode endpoints', () => { await Database.sequelize.sync({ force: true }) }) + it('returns 400 without querying DB when any batch episode endpoint receives an invalid payload', async () => { + user.permissions = { ...user.permissions, delete: true } + const findAllSpy = sinon.spy(Database.libraryItemModel, 'findAll') + const findExpandedSpy = sinon.spy(Database.libraryItemModel, 'findAllExpandedWhere') + + for (const invoke of [ + (res) => PodcastController.batchGetEpisodes({ user, body: { episodes: [] } }, res), + (res) => PodcastController.batchUpdateEpisodes({ user, body: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }] }, res), + (res) => PodcastController.batchDeleteEpisodes({ user, query: {}, body: { episodes: [] } }, res), + (res) => PodcastController.batchDownloadEpisodes({ user, body: { episodes: [] } }, res) + ]) { + const res = createFakeRes() + await invoke(res) + expect(res.status.calledOnceWith(400)).to.be.true + expect(res.send.calledOnceWith('Invalid payload')).to.be.true + } + + expect(findAllSpy.called).to.be.false + expect(findExpandedSpy.called).to.be.false + }) + describe('batchGetEpisodes', () => { - it('returns 400 when episodes payload is missing, empty, contains any malformed entry, or has duplicate pairs', async () => { - const findSpy = sinon.spy(Database.libraryItemModel, 'findAll') - - for (const body of [ - {}, - { episodes: [] }, - { episodes: [{ libraryItemId: podcastItem1.id }, { episodeId: episode1.id }] }, - { episodes: [{ libraryItemId: 123, episodeId: episode1.id }] }, - { episodes: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }, { libraryItemId: podcastItem1.id }] }, - { - episodes: [ - { libraryItemId: podcastItem1.id, episodeId: episode1.id }, - { libraryItemId: podcastItem1.id, episodeId: episode1.id } - ] - } - ]) { - const res = createFakeRes() - await PodcastController.batchGetEpisodes({ body, user }, res) - expect(res.status.calledOnceWith(400)).to.be.true - expect(res.send.calledOnceWith('Invalid payload')).to.be.true - } - - expect(findSpy.called).to.be.false - }) - it('preserves request order, omits missing/non-podcast entries, and returns expanded episodes', async () => { const book = await Database.bookModel.create({ title: 'A Book', audioFiles: [], tags: [], narrators: [], genres: [], chapters: [] }) const bookItem = await Database.libraryItemModel.create({ @@ -428,27 +477,365 @@ describe('PodcastController batch episode endpoints', () => { }) }) + describe('batchUpdateEpisodes', () => { + it('returns 403 when user lacks canUpdate permission without querying DB', async () => { + user.permissions = { ...user.permissions, update: false } + const findSpy = sinon.spy(Database.libraryItemModel, 'findAllExpandedWhere') + const res = createFakeRes() + + await PodcastController.batchUpdateEpisodes( + { + user, + body: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id, payload: { title: 'Updated' } }] + }, + res + ) + + expect(res.sendStatus.calledOnceWith(403)).to.be.true + expect(findSpy.called).to.be.false + }) + + it('returns 403 when user lacks access to a referenced podcast', async () => { + user.permissions = { ...user.permissions, accessExplicitContent: false } + const emitStub = sinon.stub(SocketAuthority, 'libraryItemEmitter') + const res = createFakeRes() + + await PodcastController.batchUpdateEpisodes( + { + user, + body: [ + { libraryItemId: podcastItem1.id, episodeId: episode1.id, payload: { title: 'Should Not Save' } }, + { libraryItemId: podcastItem2.id, episodeId: episode3.id, payload: { title: 'Restricted' } } + ] + }, + res + ) + + expect(res.sendStatus.calledOnceWith(403)).to.be.true + expect(emitStub.called).to.be.false + await episode1.reload() + expect(episode1.title).to.equal('Ep 1') + }) + + it('returns 404 when no requested episodes exist or only non-podcast items match', async () => { + const book = await Database.bookModel.create({ title: 'A Book', audioFiles: [], tags: [], narrators: [], genres: [], chapters: [] }) + const bookItem = await Database.libraryItemModel.create({ + libraryFiles: [], + mediaId: book.id, + mediaType: 'book', + libraryId: library.id, + libraryFolderId: libraryFolder.id + }) + + const res = createFakeRes() + await PodcastController.batchUpdateEpisodes( + { + user, + body: [ + { libraryItemId: podcastItem1.id, episodeId: 'missing-ep', payload: { title: 'Nope' } }, + { libraryItemId: bookItem.id, episodeId: episode1.id, payload: { title: 'Nope' } } + ] + }, + res + ) + + expect(res.status.calledOnceWith(404)).to.be.true + expect(res.send.calledOnceWith('Episodes not found')).to.be.true + }) + + it('updates episodes across podcasts in a transaction, omits missing entries, and emits once per modified podcast', async () => { + const emitStub = sinon.stub(SocketAuthority, 'libraryItemEmitter') + const res = createFakeRes() + + await PodcastController.batchUpdateEpisodes( + { + user, + body: [ + { libraryItemId: podcastItem1.id, episodeId: episode1.id, payload: { title: 'Ep 1 Updated', season: '2' } }, + { libraryItemId: podcastItem1.id, episodeId: episode2.id, payload: { title: 'Ep 2' } }, + { libraryItemId: podcastItem1.id, episodeId: 'missing-ep', payload: { title: 'Ignored' } }, + { libraryItemId: podcastItem2.id, episodeId: episode3.id, payload: { title: 'Ep 3 Updated', description: '

Clean

' } } + ] + }, + res + ) + + expect(res.json.calledOnceWith({ success: true, updates: 2 })).to.be.true + + await episode1.reload() + await episode2.reload() + await episode3.reload() + expect(episode1.title).to.equal('Ep 1 Updated') + expect(episode1.season).to.equal('2') + expect(episode2.title).to.equal('Ep 2') + expect(episode3.title).to.equal('Ep 3 Updated') + expect(episode3.description).to.equal('

Clean

') + + expect(emitStub.callCount).to.equal(2) + expect(emitStub.getCalls().map((c) => [c.args[0], c.args[1].id])).to.deep.equal([ + ['item_updated', podcastItem1.id], + ['item_updated', podcastItem2.id] + ]) + }) + + it('returns updates: 0 and emits no socket events when payloads produce no changes', async () => { + const emitStub = sinon.stub(SocketAuthority, 'libraryItemEmitter') + const res = createFakeRes() + + await PodcastController.batchUpdateEpisodes( + { + user, + body: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id, payload: { title: 'Ep 1', unknownField: 'ignored' } }] + }, + res + ) + + expect(res.json.calledOnceWith({ success: true, updates: 0 })).to.be.true + expect(emitStub.called).to.be.false + }) + + it('rolls back transaction and returns 500 when saving an episode fails mid-batch', async () => { + const emitStub = sinon.stub(SocketAuthority, 'libraryItemEmitter') + const originalSave = Database.podcastEpisodeModel.prototype.save + let saveCalls = 0 + sinon.stub(Database.podcastEpisodeModel.prototype, 'save').callsFake(function (...args) { + saveCalls++ + if (saveCalls === 2) return Promise.reject(new Error('SQLITE_BUSY')) + return originalSave.apply(this, args) + }) + + const res = createFakeRes() + await PodcastController.batchUpdateEpisodes( + { + user, + body: [ + { libraryItemId: podcastItem1.id, episodeId: episode1.id, payload: { title: 'Rolled Back' } }, + { libraryItemId: podcastItem1.id, episodeId: episode2.id, payload: { title: 'Fails Save' } } + ] + }, + res + ) + + expect(res.status.calledOnceWith(500)).to.be.true + expect(res.send.calledOnceWith('Failed to update episodes')).to.be.true + expect(emitStub.called).to.be.false + + await episode1.reload() + expect(episode1.title).to.equal('Ep 1') + }) + }) + + describe('batchDeleteEpisodes', () => { + it('returns 403 when user lacks canDelete permission without querying DB', async () => { + const findSpy = sinon.spy(Database.libraryItemModel, 'findAllExpandedWhere') + const res = createFakeRes() + + await PodcastController.batchDeleteEpisodes( + { + user, + query: {}, + body: { episodes: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }] } + }, + res + ) + + expect(res.sendStatus.calledOnceWith(403)).to.be.true + expect(findSpy.called).to.be.false + }) + + it('returns 403 when user lacks access to a referenced podcast', async () => { + user.permissions = { ...user.permissions, delete: true, accessExplicitContent: false } + const res = createFakeRes() + + await PodcastController.batchDeleteEpisodes( + { + user, + query: {}, + body: { + episodes: [ + { libraryItemId: podcastItem1.id, episodeId: episode1.id }, + { libraryItemId: podcastItem2.id, episodeId: episode3.id } + ] + } + }, + res + ) + + expect(res.sendStatus.calledOnceWith(403)).to.be.true + expect(await Database.podcastEpisodeModel.findByPk(episode1.id)).to.not.be.null + }) + + it('returns 404 when no requested episodes are found', async () => { + user.permissions = { ...user.permissions, delete: true } + const res = createFakeRes() + + await PodcastController.batchDeleteEpisodes( + { + user, + query: {}, + body: { episodes: [{ libraryItemId: podcastItem1.id, episodeId: 'missing-ep' }] } + }, + res + ) + + expect(res.status.calledOnceWith(404)).to.be.true + expect(res.send.calledOnceWith('Episodes not found')).to.be.true + }) + + it('soft-deletes episodes across podcasts, cleans up progress/playlists/libraryFiles/numEpisodes, and emits once per podcast', async () => { + user.permissions = { ...user.permissions, delete: true } + + podcastItem1.libraryFiles = [{ ino: '101' }, { ino: '102' }, { ino: 'keep-1' }] + podcastItem1.changed('libraryFiles', true) + await podcastItem1.save() + + podcastItem2.libraryFiles = [{ ino: '103' }] + podcastItem2.changed('libraryFiles', true) + await podcastItem2.save() + + await Database.mediaProgressModel.create({ + userId: user.id, + mediaItemId: episode1.id, + mediaItemType: 'podcastEpisode', + duration: 120, + currentTime: 30, + isFinished: false + }) + await Database.mediaProgressModel.create({ + userId: user.id, + mediaItemId: episode2.id, + mediaItemType: 'podcastEpisode', + duration: 120, + currentTime: 60, + isFinished: false + }) + + const playlistStub = sinon.stub(Database.playlistModel, 'removeMediaItemsFromPlaylists').resolves() + const cacheStub = sinon.stub(libraryItemsPodcastFilters, 'clearCountCache') + const fsRemoveStub = sinon.stub(fs, 'remove').resolves() + const emitStub = sinon.stub(SocketAuthority, 'libraryItemEmitter') + + const res = createFakeRes() + await PodcastController.batchDeleteEpisodes( + { + user, + query: {}, + body: { + episodes: [ + { libraryItemId: podcastItem1.id, episodeId: episode1.id }, + { libraryItemId: podcastItem1.id, episodeId: 'missing-ep' }, + { libraryItemId: podcastItem2.id, episodeId: episode3.id } + ] + } + }, + res + ) + + expect(res.json.calledOnceWith({ success: true, removed: 2 })).to.be.true + expect(fsRemoveStub.called).to.be.false + expect(playlistStub.calledOnceWith([episode1.id, episode3.id])).to.be.true + expect(cacheStub.calledOnceWith('podcastEpisode', 'afterDestroy')).to.be.true + + expect(await Database.podcastEpisodeModel.findByPk(episode1.id)).to.be.null + expect(await Database.podcastEpisodeModel.findByPk(episode3.id)).to.be.null + expect(await Database.podcastEpisodeModel.findByPk(episode2.id)).to.not.be.null + + expect(await Database.mediaProgressModel.count({ where: { mediaItemId: episode1.id } })).to.equal(0) + expect(await Database.mediaProgressModel.count({ where: { mediaItemId: episode2.id } })).to.equal(1) + + await podcastItem1.reload() + await podcastItem2.reload() + const podcast1 = await Database.podcastModel.findByPk(podcastItem1.mediaId) + const podcast2 = await Database.podcastModel.findByPk(podcastItem2.mediaId) + expect(podcastItem1.libraryFiles.map((f) => f.ino)).to.deep.equal(['102', 'keep-1']) + expect(podcast1.numEpisodes).to.equal(1) + expect(podcastItem2.libraryFiles).to.deep.equal([]) + expect(podcast2.numEpisodes).to.equal(0) + + expect(emitStub.callCount).to.equal(2) + expect(emitStub.getCalls().map((c) => [c.args[0], c.args[1].id])).to.deep.equal([ + ['item_updated', podcastItem1.id], + ['item_updated', podcastItem2.id] + ]) + }) + + it('hard-deletes audio files when hard=1 and continues if one unlink fails', async () => { + user.permissions = { ...user.permissions, delete: true } + sinon.stub(Database.playlistModel, 'removeMediaItemsFromPlaylists').resolves() + sinon.stub(libraryItemsPodcastFilters, 'clearCountCache') + sinon.stub(SocketAuthority, 'libraryItemEmitter') + + const fsRemoveStub = sinon.stub(fs, 'remove') + fsRemoveStub.onFirstCall().rejects(new Error('ENOENT')) + fsRemoveStub.onSecondCall().resolves() + + const res = createFakeRes() + await PodcastController.batchDeleteEpisodes( + { + user, + query: { hard: '1' }, + body: { + episodes: [ + { libraryItemId: podcastItem1.id, episodeId: episode1.id }, + { libraryItemId: podcastItem2.id, episodeId: episode3.id } + ] + } + }, + res + ) + + expect(res.json.calledOnceWith({ success: true, removed: 2 })).to.be.true + expect(fsRemoveStub.callCount).to.equal(2) + expect(fsRemoveStub.firstCall.args[0]).to.equal('/podcasts/podcast-one/ep1.mp3') + expect(fsRemoveStub.secondCall.args[0]).to.equal('/podcasts/podcast-two/ep1.mp3') + expect(Logger.error.calledOnce).to.be.true + expect(await Database.podcastEpisodeModel.findByPk(episode1.id)).to.be.null + expect(await Database.podcastEpisodeModel.findByPk(episode3.id)).to.be.null + }) + + it('returns 500 when deletion fails unexpectedly', async () => { + user.permissions = { ...user.permissions, delete: true } + sinon.stub(Database.playlistModel, 'removeMediaItemsFromPlaylists').resolves() + const emitStub = sinon.stub(SocketAuthority, 'libraryItemEmitter') + sinon.stub(Database.podcastEpisodeModel, 'destroy').rejects(new Error('SQLITE_BUSY')) + + const res = createFakeRes() + await PodcastController.batchDeleteEpisodes( + { + user, + query: {}, + body: { episodes: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }] } + }, + res + ) + + expect(res.status.calledOnceWith(500)).to.be.true + expect(res.send.calledOnceWith('Failed to delete episodes')).to.be.true + expect(emitStub.called).to.be.false + }) + }) + describe('batchDownloadEpisodes', () => { - it('returns 400 for mismatched partial entries without querying DB', async () => { + it('returns 403 when user lacks canDownload permission without querying DB', async () => { + user.permissions = { ...user.permissions, download: false } const findSpy = sinon.spy(Database.libraryItemModel, 'findAll') const res = createFakeRes() await PodcastController.batchDownloadEpisodes( { user, - body: { - episodes: [{ libraryItemId: podcastItem1.id }, { episodeId: episode1.id }] - } + body: { episodes: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }] } }, res ) - expect(res.status.calledOnceWith(400)).to.be.true + expect(res.sendStatus.calledOnceWith(403)).to.be.true expect(findSpy.called).to.be.false }) - it('returns 400 for duplicate pairs without querying DB', async () => { - const findSpy = sinon.spy(Database.libraryItemModel, 'findAll') + it('returns 403 when user lacks access to a referenced podcast', async () => { + user.permissions = { ...user.permissions, accessExplicitContent: false } + const zipStub = sinon.stub(zipHelpers, 'zipDirectoriesPipe').resolves() const res = createFakeRes() await PodcastController.batchDownloadEpisodes( @@ -457,15 +844,15 @@ describe('PodcastController batch episode endpoints', () => { body: { episodes: [ { libraryItemId: podcastItem1.id, episodeId: episode1.id }, - { libraryItemId: podcastItem1.id, episodeId: episode1.id } + { libraryItemId: podcastItem2.id, episodeId: episode3.id } ] } }, res ) - expect(res.status.calledOnceWith(400)).to.be.true - expect(findSpy.called).to.be.false + expect(res.sendStatus.calledOnceWith(403)).to.be.true + expect(zipStub.called).to.be.false }) it('groups multi-podcast episodes into podcast folders', async () => { @@ -493,6 +880,79 @@ describe('PodcastController batch episode endpoints', () => { ]) }) + it('uses flat filenames for single-podcast downloads and disambiguates duplicate names', async () => { + episode2.audioFile = createAudioFile('ep1.mp3', '/podcasts/podcast-one/sub/ep1.mp3', '102') + episode2.changed('audioFile', true) + await episode2.save() + + const zipStub = sinon.stub(zipHelpers, 'zipDirectoriesPipe').resolves() + const res = createFakeRes() + + await PodcastController.batchDownloadEpisodes( + { + user, + body: { + episodes: [ + { libraryItemId: podcastItem1.id, episodeId: episode1.id }, + { libraryItemId: podcastItem1.id, episodeId: episode2.id } + ] + } + }, + res + ) + + expect(zipStub.calledOnce).to.be.true + const [fileEntries] = zipStub.firstCall.args + expect(fileEntries).to.deep.equal([ + { path: '/podcasts/podcast-one/ep1.mp3', isFile: true, name: 'ep1.mp3' }, + { path: '/podcasts/podcast-one/sub/ep1.mp3', isFile: true, name: 'ep1 (2).mp3' } + ]) + }) + + it('returns 404 when no downloadable episode files are found', async () => { + episode1.audioFile = { ino: '101', duration: 120, metadata: {} } + episode1.changed('audioFile', true) + await episode1.save() + + const zipStub = sinon.stub(zipHelpers, 'zipDirectoriesPipe').resolves() + const res = createFakeRes() + + await PodcastController.batchDownloadEpisodes( + { + user, + body: { + episodes: [ + { libraryItemId: podcastItem1.id, episodeId: episode1.id }, + { libraryItemId: podcastItem1.id, episodeId: 'missing-ep' } + ] + } + }, + res + ) + + expect(res.status.calledOnceWith(404)).to.be.true + expect(res.send.calledOnceWith('No downloadable episode files found')).to.be.true + expect(zipStub.called).to.be.false + }) + + it('delegates zip streaming errors to zipHelpers.handleDownloadError', async () => { + const zipError = new Error('ENOENT') + sinon.stub(zipHelpers, 'zipDirectoriesPipe').rejects(zipError) + const handleErrorStub = sinon.stub(zipHelpers, 'handleDownloadError') + const res = createFakeRes() + + await PodcastController.batchDownloadEpisodes( + { + user, + body: { episodes: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }] } + }, + res + ) + + expect(handleErrorStub.calledOnceWith(zipError, res)).to.be.true + expect(Logger.error.calledOnce).to.be.true + }) + it('returns 500 when episode resolution fails unexpectedly', async () => { sinon.stub(Database.libraryItemModel, 'findAll').rejects(new Error('SQLITE_BUSY')) const res = createFakeRes() From dc0afcce79dcfc9eeeb8c245250fd7c1241a34df Mon Sep 17 00:00:00 2001 From: mikiher Date: Fri, 4 Dec 2026 07:45:21 +0200 Subject: [PATCH 8/8] Do no delete if darabase update fails --- server/controllers/PodcastController.js | 8 ++++---- test/server/controllers/PodcastController.test.js | 6 ++++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/server/controllers/PodcastController.js b/server/controllers/PodcastController.js index c6ccc56a5..2c25ab155 100644 --- a/server/controllers/PodcastController.js +++ b/server/controllers/PodcastController.js @@ -799,15 +799,15 @@ class PodcastController { removedEpisodes.push(episode) } - if (hardDelete) { - await removeEpisodeAudioFiles(removedEpisodes) - } - const removedEpisodeIds = removedEpisodes.map((ep) => ep.id) await Database.playlistModel.removeMediaItemsFromPlaylists(removedEpisodeIds) await deleteEpisodesInTransaction(removedEpisodeIds, matchedByLibraryItem) libraryItemsPodcastFilters.clearCountCache('podcastEpisode', 'afterDestroy') + if (hardDelete) { + await removeEpisodeAudioFiles(removedEpisodes) + } + for (const [libraryItem, episodesToRemove] of matchedByLibraryItem) { Logger.info(`[PodcastController] Batch deleted ${episodesToRemove.length} episode(s) from podcast "${libraryItem.media.title}"`) SocketAuthority.libraryItemEmitter('item_updated', libraryItem) diff --git a/test/server/controllers/PodcastController.test.js b/test/server/controllers/PodcastController.test.js index 4e1a4c3ef..6213885eb 100644 --- a/test/server/controllers/PodcastController.test.js +++ b/test/server/controllers/PodcastController.test.js @@ -793,9 +793,10 @@ describe('PodcastController batch episode endpoints', () => { expect(await Database.podcastEpisodeModel.findByPk(episode3.id)).to.be.null }) - it('returns 500 when deletion fails unexpectedly', async () => { + it('returns 500 and does not unlink files when database deletion fails unexpectedly', async () => { user.permissions = { ...user.permissions, delete: true } sinon.stub(Database.playlistModel, 'removeMediaItemsFromPlaylists').resolves() + const fsRemoveStub = sinon.stub(fs, 'remove').resolves() const emitStub = sinon.stub(SocketAuthority, 'libraryItemEmitter') sinon.stub(Database.podcastEpisodeModel, 'destroy').rejects(new Error('SQLITE_BUSY')) @@ -803,7 +804,7 @@ describe('PodcastController batch episode endpoints', () => { await PodcastController.batchDeleteEpisodes( { user, - query: {}, + query: { hard: '1' }, body: { episodes: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }] } }, res @@ -811,6 +812,7 @@ describe('PodcastController batch episode endpoints', () => { expect(res.status.calledOnceWith(500)).to.be.true expect(res.send.calledOnceWith('Failed to delete episodes')).to.be.true + expect(fsRemoveStub.called).to.be.false expect(emitStub.called).to.be.false }) })