Merge pull request #5799 from mikiher/batch-episodes

Add podcast episode batch endpoints and optimize expanded podcast loading
This commit is contained in:
advplyr authored and GitHub committed 2026-12-04 12:25:53 -06:00
commit 8b4a2f2c3a
6 files changed
+1491 -51

No files matched your search

+472 -37
View File
@@ -11,6 +11,8 @@ 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 libraryItemsPodcastFilters = require('../utils/queries/libraryItemsPodcastFilters')
const Scanner = require('../scanner/Scanner')
const CoverManager = require('../managers/CoverManager')
@@ -27,6 +29,254 @@ 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 a non-empty array of `{ libraryItemId, episodeId }` entries (rejecting duplicates).
*
* @param {unknown} entries
* @param {{ requirePayload?: boolean }} [options]
* @returns {{ errorStatus?: number, errorMessage?: string, libraryItemIds?: string[], episodeIds?: string[] }}
*/
function validateEpisodeBatchEntries(entries, { requirePayload = false } = {}) {
if (!Array.isArray(entries) || !entries.length) {
return { errorStatus: 400, errorMessage: 'Invalid payload' }
}
const seenKeys = new Set()
const libraryItemIdSet = new Set()
const episodeIdSet = new Set()
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}`
if (seenKeys.has(key)) {
return { errorStatus: 400, errorMessage: 'Invalid payload' }
}
seenKeys.add(key)
libraryItemIdSet.add(entry.libraryItemId)
episodeIdSet.add(entry.episodeId)
}
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)) {
return { errorStatus: 403 }
}
}
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 resolvedEpisodes = []
for (const entry of requestedEpisodes) {
const libraryItem = libraryItemsById.get(entry.libraryItemId)
if (!libraryItem) continue
const episode = episodesByPodcastAndId.get(`${libraryItem.media.id}:${entry.episodeId}`)
if (!episode) continue
resolvedEpisodes.push({ libraryItem, episode, entry })
}
return {
resolvedEpisodes,
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<import('../models/LibraryItem'), import('../models/PodcastEpisode')[]>} 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.
*
* @param {Record<string, any>} body
* @returns {Record<string, any>}
*/
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 +654,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 sendErrorResult(res, resolved)
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 or duplicate `(libraryItemId, episodeId)` entry
* - `403`: User lacks `canUpdate` or access to one or more referenced podcasts
* - `404`: None of the requested episodes were found
* - `500`: Unexpected server/database error while updating episodes
*
* @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)
}
try {
const resolved = await resolveRequestedPodcastEpisodes(req.body, req.user, {
expanded: true,
requirePayload: true
})
if (resolved.errorStatus) return sendErrorResult(res, resolved)
if (!resolved.resolvedEpisodes.length) {
return res.status(404).send('Episodes not found')
}
const updatedLibraryItems = new Set()
let episodesUpdated = 0
await Database.sequelize.transaction(async (transaction) => {
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(libraryItem)
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; `(libraryItemId, episodeId)` pairs must be unique)
*
* Responses:
* - `200`: `{ success: true, removed: number }`
* - `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
*
* @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)
}
const hardDelete = req.query.hard === '1'
try {
const resolved = await resolveRequestedPodcastEpisodes(req.body?.episodes, req.user, { expanded: true })
if (resolved.errorStatus) return sendErrorResult(res, resolved)
if (!resolved.resolvedEpisodes.length) {
return res.status(404).send('Episodes not found')
}
const matchedByLibraryItem = new Map()
const removedEpisodes = []
for (const { libraryItem, episode } of resolved.resolvedEpisodes) {
let list = matchedByLibraryItem.get(libraryItem)
if (!list) {
list = []
matchedByLibraryItem.set(libraryItem, list)
}
list.push(episode)
removedEpisodes.push(episode)
}
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)
}
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')
}
}
/**
* 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
* `<podcastFolder>/<filename>` 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-<timestamp>.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 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')
}
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 +886,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 +1016,5 @@ class PodcastController {
}
}
module.exports = new PodcastController()
module.exports.buildEpisodeUpdatePayload = buildEpisodeUpdatePayload
module.exports.validateEpisodeBatchEntries = validateEpisodeBatchEntries