mirror of
https://github.com/advplyr/audiobookshelf.git
synced 2026-12-04 22:16:28 +01:00
1053 lines
39 KiB
JavaScript
1053 lines
39 KiB
JavaScript
const Path = require('path')
|
|
const { Request, Response, NextFunction } = require('express')
|
|
const Logger = require('../Logger')
|
|
const SocketAuthority = require('../SocketAuthority')
|
|
const Database = require('../Database')
|
|
|
|
const fs = require('../libs/fsExtra')
|
|
const cron = require('../libs/nodeCron')
|
|
|
|
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')
|
|
|
|
/**
|
|
* @typedef RequestUserObject
|
|
* @property {import('../models/User')} user
|
|
*
|
|
* @typedef {Request & RequestUserObject} RequestWithUser
|
|
*
|
|
* @typedef RequestEntityObject
|
|
* @property {import('../models/LibraryItem')} libraryItem
|
|
*
|
|
* @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<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
|
|
* Create podcast
|
|
*
|
|
* @this import('../routers/ApiRouter')
|
|
*
|
|
* @param {RequestWithUser} req
|
|
* @param {Response} res
|
|
*/
|
|
async create(req, res) {
|
|
if (!req.user.isAdminOrUp) {
|
|
Logger.error(`[PodcastController] Non-admin user "${req.user.username}" attempted to create podcast`)
|
|
return res.sendStatus(403)
|
|
}
|
|
const payload = req.body
|
|
if (!payload.media || !payload.media.metadata) {
|
|
return res.status(400).send('Invalid request body. "media" and "media.metadata" are required')
|
|
}
|
|
|
|
if (payload.media.autoDownloadSchedule && !cron.validate(payload.media.autoDownloadSchedule)) {
|
|
Logger.error(`[PodcastController] Invalid auto download schedule cron expression "${payload.media.autoDownloadSchedule}"`)
|
|
return res.status(400).send('Invalid auto download schedule cron expression')
|
|
}
|
|
|
|
const library = await Database.libraryModel.findByIdWithFolders(payload.libraryId)
|
|
if (!library) {
|
|
Logger.error(`[PodcastController] Create: Library not found "${payload.libraryId}"`)
|
|
return res.status(404).send('Library not found')
|
|
}
|
|
|
|
const folder = library.libraryFolders.find((fold) => fold.id === payload.folderId)
|
|
if (!folder) {
|
|
Logger.error(`[PodcastController] Create: Folder not found "${payload.folderId}"`)
|
|
return res.status(404).send('Folder not found')
|
|
}
|
|
|
|
if (typeof payload.path !== 'string' || !payload.path.trim()) {
|
|
return res.status(400).send('Invalid request body. "path" must be a non-empty string')
|
|
}
|
|
|
|
const libraryFolderPath = filePathToPOSIX(folder.path)
|
|
const podcastPath = filePathToPOSIX(payload.path)
|
|
|
|
if (!isSameOrSubPath(libraryFolderPath, podcastPath)) {
|
|
Logger.error(`[PodcastController] Create: Podcast path is outside library folder "${libraryFolderPath}": "${podcastPath}"`)
|
|
return res.status(400).send('Podcast path must be inside the selected library folder')
|
|
}
|
|
|
|
// Check if a library item with this podcast folder exists already
|
|
const existingLibraryItem =
|
|
(await Database.libraryItemModel.count({
|
|
where: {
|
|
path: podcastPath
|
|
}
|
|
})) > 0
|
|
if (existingLibraryItem) {
|
|
Logger.error(`[PodcastController] Podcast already exists at path "${podcastPath}"`)
|
|
return res.status(400).send('Podcast already exists')
|
|
}
|
|
|
|
const success = await fs
|
|
.ensureDir(podcastPath)
|
|
.then(() => true)
|
|
.catch((error) => {
|
|
Logger.error(`[PodcastController] Failed to ensure podcast dir "${podcastPath}"`, error)
|
|
return false
|
|
})
|
|
if (!success) return res.status(400).send('Invalid podcast path')
|
|
|
|
const libraryItemFolderStats = await getFileTimestampsWithIno(podcastPath)
|
|
|
|
let relPath = podcastPath.replace(libraryFolderPath, '')
|
|
if (relPath.startsWith('/')) relPath = relPath.slice(1)
|
|
|
|
let newLibraryItem = null
|
|
const transaction = await Database.sequelize.transaction()
|
|
try {
|
|
const podcast = await Database.podcastModel.createFromRequest(payload.media, transaction)
|
|
|
|
newLibraryItem = await Database.libraryItemModel.create(
|
|
{
|
|
ino: libraryItemFolderStats.ino,
|
|
path: podcastPath,
|
|
relPath,
|
|
mediaId: podcast.id,
|
|
mediaType: 'podcast',
|
|
isFile: false,
|
|
isMissing: false,
|
|
isInvalid: false,
|
|
mtime: libraryItemFolderStats.mtimeMs || 0,
|
|
ctime: libraryItemFolderStats.ctimeMs || 0,
|
|
birthtime: libraryItemFolderStats.birthtimeMs || 0,
|
|
size: 0,
|
|
libraryFiles: [],
|
|
extraData: {},
|
|
libraryId: library.id,
|
|
libraryFolderId: folder.id,
|
|
title: podcast.title,
|
|
titleIgnorePrefix: podcast.titleIgnorePrefix
|
|
},
|
|
{ transaction }
|
|
)
|
|
|
|
await transaction.commit()
|
|
} catch (error) {
|
|
Logger.error(`[PodcastController] Failed to create podcast: ${error}`)
|
|
await transaction.rollback()
|
|
return res.status(500).send('Failed to create podcast')
|
|
}
|
|
|
|
newLibraryItem.media = await newLibraryItem.getMediaExpanded()
|
|
|
|
// Download and save cover image
|
|
if (typeof payload.media.metadata.imageUrl === 'string' && payload.media.metadata.imageUrl.startsWith('http')) {
|
|
// Podcast cover will always go into library item folder
|
|
const coverResponse = await CoverManager.downloadCoverFromUrlNew(payload.media.metadata.imageUrl, newLibraryItem.id, newLibraryItem.path, true)
|
|
if (coverResponse.error) {
|
|
Logger.error(`[PodcastController] Download cover error from "${payload.media.metadata.imageUrl}": ${coverResponse.error}`)
|
|
} else if (coverResponse.cover) {
|
|
const coverImageFileStats = await getFileTimestampsWithIno(coverResponse.cover)
|
|
if (!coverImageFileStats) {
|
|
Logger.error(`[PodcastController] Failed to get cover image stats for "${coverResponse.cover}"`)
|
|
} else {
|
|
// Add libraryFile to libraryItem and coverPath to podcast
|
|
const newLibraryFile = {
|
|
ino: coverImageFileStats.ino,
|
|
fileType: 'image',
|
|
addedAt: Date.now(),
|
|
updatedAt: Date.now(),
|
|
metadata: {
|
|
filename: Path.basename(coverResponse.cover),
|
|
ext: Path.extname(coverResponse.cover).slice(1),
|
|
path: coverResponse.cover,
|
|
relPath: Path.basename(coverResponse.cover),
|
|
size: coverImageFileStats.size,
|
|
mtimeMs: coverImageFileStats.mtimeMs || 0,
|
|
ctimeMs: coverImageFileStats.ctimeMs || 0,
|
|
birthtimeMs: coverImageFileStats.birthtimeMs || 0
|
|
}
|
|
}
|
|
newLibraryItem.libraryFiles.push(newLibraryFile)
|
|
newLibraryItem.changed('libraryFiles', true)
|
|
await newLibraryItem.save()
|
|
|
|
newLibraryItem.media.coverPath = coverResponse.cover
|
|
await newLibraryItem.media.save()
|
|
}
|
|
}
|
|
}
|
|
|
|
SocketAuthority.libraryItemEmitter('item_added', newLibraryItem)
|
|
|
|
res.json(newLibraryItem.toOldJSONExpanded())
|
|
|
|
// Turn on podcast auto download cron if not already on
|
|
if (newLibraryItem.media.autoDownloadEpisodes) {
|
|
this.cronManager.checkUpdatePodcastCron(newLibraryItem)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* POST: /api/podcasts/feed
|
|
*
|
|
* @typedef getPodcastFeedReqBody
|
|
* @property {string} rssFeed
|
|
*
|
|
* @param {Request<{}, {}, getPodcastFeedReqBody, {}> & RequestUserObject} req
|
|
* @param {Response} res
|
|
*/
|
|
async getPodcastFeed(req, res) {
|
|
if (!req.user.isAdminOrUp) {
|
|
Logger.error(`[PodcastController] Non-admin user "${req.user.username}" attempted to get podcast feed`)
|
|
return res.sendStatus(403)
|
|
}
|
|
|
|
const url = validateUrl(req.body.rssFeed)
|
|
if (!url) {
|
|
return res.status(400).send('Invalid request body. "rssFeed" must be a valid URL')
|
|
}
|
|
|
|
const podcast = await getPodcastFeed(url)
|
|
if (!podcast) {
|
|
return res.status(404).send('Podcast RSS feed request failed or invalid response data')
|
|
}
|
|
res.json({ podcast })
|
|
}
|
|
|
|
/**
|
|
* POST: /api/podcasts/opml
|
|
*
|
|
* @this import('../routers/ApiRouter')
|
|
*
|
|
* @param {RequestWithUser} req
|
|
* @param {Response} res
|
|
*/
|
|
async getFeedsFromOPMLText(req, res) {
|
|
if (!req.user.isAdminOrUp) {
|
|
Logger.error(`[PodcastController] Non-admin user "${req.user.username}" attempted to get feeds from opml`)
|
|
return res.sendStatus(403)
|
|
}
|
|
|
|
if (!req.body.opmlText) {
|
|
return res.sendStatus(400)
|
|
}
|
|
|
|
res.json({
|
|
feeds: this.podcastManager.getParsedOPMLFileFeeds(req.body.opmlText)
|
|
})
|
|
}
|
|
|
|
/**
|
|
* POST: /api/podcasts/opml/create
|
|
*
|
|
* @this import('../routers/ApiRouter')
|
|
*
|
|
* @param {RequestWithUser} req
|
|
* @param {Response} res
|
|
*/
|
|
async bulkCreatePodcastsFromOpmlFeedUrls(req, res) {
|
|
if (!req.user.isAdminOrUp) {
|
|
Logger.error(`[PodcastController] Non-admin user "${req.user.username}" attempted to bulk create podcasts`)
|
|
return res.sendStatus(403)
|
|
}
|
|
|
|
const rssFeeds = req.body.feeds
|
|
if (!Array.isArray(rssFeeds) || !rssFeeds.length || rssFeeds.some((feed) => !validateUrl(feed))) {
|
|
return res.status(400).send('Invalid request body. "feeds" must be an array of RSS feed URLs')
|
|
}
|
|
|
|
const libraryId = req.body.libraryId
|
|
const folderId = req.body.folderId
|
|
if (!libraryId || !folderId) {
|
|
return res.status(400).send('Invalid request body. "libraryId" and "folderId" are required')
|
|
}
|
|
|
|
const folder = await Database.libraryFolderModel.findByPk(folderId)
|
|
if (!folder || folder.libraryId !== libraryId) {
|
|
return res.status(404).send('Folder not found')
|
|
}
|
|
const autoDownloadEpisodes = !!req.body.autoDownloadEpisodes
|
|
this.podcastManager.createPodcastsFromFeedUrls(rssFeeds, folder, autoDownloadEpisodes, this.cronManager)
|
|
|
|
res.sendStatus(200)
|
|
}
|
|
|
|
/**
|
|
* GET: /api/podcasts/:id/checknew
|
|
*
|
|
* @this import('../routers/ApiRouter')
|
|
*
|
|
* @param {RequestWithLibraryItem} req
|
|
* @param {Response} res
|
|
*/
|
|
async checkNewEpisodes(req, res) {
|
|
if (!req.user.isAdminOrUp) {
|
|
Logger.error(`[PodcastController] Non-admin user "${req.user.username}" attempted to check/download episodes`)
|
|
return res.sendStatus(403)
|
|
}
|
|
|
|
if (!req.libraryItem.media.feedURL) {
|
|
Logger.error(`[PodcastController] checkNewEpisodes no feed url for item ${req.libraryItem.id}`)
|
|
return res.status(400).send('Podcast has no rss feed url')
|
|
}
|
|
|
|
const maxEpisodesToDownload = !isNaN(req.query.limit) ? Number(req.query.limit) : 3
|
|
|
|
const newEpisodes = await this.podcastManager.checkAndDownloadNewEpisodes(req.libraryItem, maxEpisodesToDownload)
|
|
res.json({
|
|
episodes: newEpisodes || []
|
|
})
|
|
}
|
|
|
|
/**
|
|
* GET: /api/podcasts/:id/clear-queue
|
|
*
|
|
* @this {import('../routers/ApiRouter')}
|
|
*
|
|
* @param {RequestWithUser} req
|
|
* @param {Response} res
|
|
*/
|
|
clearEpisodeDownloadQueue(req, res) {
|
|
if (!req.user.isAdminOrUp) {
|
|
Logger.error(`[PodcastController] Non-admin user "${req.user.username}" attempting to clear download queue`)
|
|
return res.sendStatus(403)
|
|
}
|
|
this.podcastManager.clearDownloadQueue(req.params.id)
|
|
res.sendStatus(200)
|
|
}
|
|
|
|
/**
|
|
* GET: /api/podcasts/:id/downloads
|
|
*
|
|
* @this {import('../routers/ApiRouter')}
|
|
*
|
|
* @param {RequestWithLibraryItem} req
|
|
* @param {Response} res
|
|
*/
|
|
getEpisodeDownloads(req, res) {
|
|
const downloadsInQueue = this.podcastManager.getEpisodeDownloadsInQueue(req.libraryItem.id)
|
|
res.json({
|
|
downloads: downloadsInQueue.map((d) => d.toJSONForClient())
|
|
})
|
|
}
|
|
|
|
/**
|
|
* GET: /api/podcasts/:id/search-episode
|
|
* Search for an episode in a podcast
|
|
*
|
|
* @param {RequestWithLibraryItem} req
|
|
* @param {Response} res
|
|
*/
|
|
async findEpisode(req, res) {
|
|
const rssFeedUrl = req.libraryItem.media.feedURL
|
|
if (!rssFeedUrl) {
|
|
Logger.error(`[PodcastController] findEpisode: Podcast has no feed url`)
|
|
return res.status(400).send('Podcast does not have an RSS feed URL')
|
|
}
|
|
|
|
const searchTitle = req.query.title
|
|
if (!searchTitle || typeof searchTitle !== 'string') {
|
|
return res.sendStatus(500)
|
|
}
|
|
const episodes = await findMatchingEpisodes(rssFeedUrl, searchTitle)
|
|
res.json({
|
|
episodes: episodes || []
|
|
})
|
|
}
|
|
|
|
/**
|
|
* POST: /api/podcasts/:id/download-episodes
|
|
*
|
|
* @this {import('../routers/ApiRouter')}
|
|
*
|
|
* @param {RequestWithLibraryItem} req
|
|
* @param {Response} res
|
|
*/
|
|
async downloadEpisodes(req, res) {
|
|
if (!req.user.isAdminOrUp) {
|
|
Logger.error(`[PodcastController] Non-admin user "${req.user.username}" attempted to download episodes`)
|
|
return res.sendStatus(403)
|
|
}
|
|
|
|
const episodes = req.body
|
|
if (!Array.isArray(episodes) || !episodes.length) {
|
|
return res.sendStatus(400)
|
|
}
|
|
|
|
this.podcastManager.downloadPodcastEpisodes(req.libraryItem, episodes)
|
|
res.sendStatus(200)
|
|
}
|
|
|
|
/**
|
|
* POST: /api/podcasts/:id/match-episodes
|
|
*
|
|
* @this {import('../routers/ApiRouter')}
|
|
*
|
|
* @param {RequestWithLibraryItem} req
|
|
* @param {Response} res
|
|
*/
|
|
async quickMatchEpisodes(req, res) {
|
|
if (!req.user.isAdminOrUp) {
|
|
Logger.error(`[PodcastController] Non-admin user "${req.user.username}" attempted to download episodes`)
|
|
return res.sendStatus(403)
|
|
}
|
|
|
|
const overrideDetails = req.query.override === '1'
|
|
const episodesUpdated = await Scanner.quickMatchPodcastEpisodes(req.libraryItem, { overrideDetails })
|
|
if (episodesUpdated) {
|
|
SocketAuthority.libraryItemEmitter('item_updated', req.libraryItem)
|
|
}
|
|
|
|
res.json({
|
|
numEpisodesUpdated: episodesUpdated
|
|
})
|
|
}
|
|
|
|
/**
|
|
* 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
|
|
* - `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)
|
|
}
|
|
|
|
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
|
|
})
|
|
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
|
|
})
|
|
} 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)
|
|
}
|
|
|
|
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')
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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 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
|
|
*
|
|
* @param {RequestWithLibraryItem} req
|
|
* @param {Response} res
|
|
*/
|
|
async updateEpisode(req, res) {
|
|
/** @type {import('../models/PodcastEpisode')} */
|
|
const episode = req.libraryItem.media.podcastEpisodes.find((ep) => ep.id === req.params.episodeId)
|
|
if (!episode) {
|
|
return res.status(404).send('Episode not found')
|
|
}
|
|
|
|
const updatePayload = buildEpisodeUpdatePayload(req.body)
|
|
|
|
if (Object.keys(updatePayload).length) {
|
|
episode.set(updatePayload)
|
|
if (episode.changed()) {
|
|
Logger.info(`[PodcastController] Updated episode "${episode.title}" keys`, episode.changed())
|
|
await episode.save()
|
|
|
|
SocketAuthority.libraryItemEmitter('item_updated', req.libraryItem)
|
|
} else {
|
|
Logger.info(`[PodcastController] No changes to episode "${episode.title}"`)
|
|
}
|
|
}
|
|
|
|
res.json(req.libraryItem.toOldJSONExpanded())
|
|
}
|
|
|
|
/**
|
|
* GET: /api/podcasts/:id/episode/:episodeId
|
|
*
|
|
* @param {RequestWithLibraryItem} req
|
|
* @param {Response} res
|
|
*/
|
|
async getEpisode(req, res) {
|
|
const episodeId = req.params.episodeId
|
|
|
|
/** @type {import('../models/PodcastEpisode')} */
|
|
const episode = req.libraryItem.media.podcastEpisodes.find((ep) => ep.id === episodeId)
|
|
if (!episode) {
|
|
Logger.error(`[PodcastController] getEpisode episode ${episodeId} not found for item ${req.libraryItem.id}`)
|
|
return res.sendStatus(404)
|
|
}
|
|
|
|
res.json(episode.toOldJSON(req.libraryItem.id))
|
|
}
|
|
|
|
/**
|
|
* DELETE: /api/podcasts/:id/episode/:episodeId
|
|
*
|
|
* @param {RequestWithLibraryItem} req
|
|
* @param {Response} res
|
|
*/
|
|
async removeEpisode(req, res) {
|
|
const episodeId = req.params.episodeId
|
|
const hardDelete = req.query.hard === '1'
|
|
|
|
/** @type {import('../models/PodcastEpisode')} */
|
|
const episode = req.libraryItem.media.podcastEpisodes.find((ep) => ep.id === episodeId)
|
|
if (!episode) {
|
|
Logger.error(`[PodcastController] removeEpisode episode ${episodeId} not found for item ${req.libraryItem.id}`)
|
|
return res.sendStatus(404)
|
|
}
|
|
|
|
// Remove it from the podcastEpisodes array
|
|
req.libraryItem.media.podcastEpisodes = req.libraryItem.media.podcastEpisodes.filter((ep) => ep.id !== episodeId)
|
|
|
|
if (hardDelete) {
|
|
const audioFile = episode.audioFile
|
|
// TODO: this will trigger the watcher. should maybe handle this gracefully
|
|
await fs
|
|
.remove(audioFile.metadata.path)
|
|
.then(() => {
|
|
Logger.info(`[PodcastController] Hard deleted episode file at "${audioFile.metadata.path}"`)
|
|
})
|
|
.catch((error) => {
|
|
Logger.error(`[PodcastController] Failed to hard delete episode file at "${audioFile.metadata.path}"`, error)
|
|
})
|
|
}
|
|
|
|
// Remove episode from playlists
|
|
await Database.playlistModel.removeMediaItemsFromPlaylists([episodeId])
|
|
|
|
// Remove media progress for this episode
|
|
const mediaProgressRemoved = await Database.mediaProgressModel.destroy({
|
|
where: {
|
|
mediaItemId: episode.id
|
|
}
|
|
})
|
|
if (mediaProgressRemoved) {
|
|
Logger.info(`[PodcastController] Removed ${mediaProgressRemoved} media progress for episode ${episode.id}`)
|
|
}
|
|
|
|
// Remove episode
|
|
await episode.destroy()
|
|
|
|
// Remove library file
|
|
req.libraryItem.libraryFiles = req.libraryItem.libraryFiles.filter((file) => file.ino !== episode.audioFile.ino)
|
|
req.libraryItem.changed('libraryFiles', true)
|
|
await req.libraryItem.save()
|
|
|
|
// update number of episodes
|
|
req.libraryItem.media.numEpisodes = req.libraryItem.media.podcastEpisodes.length
|
|
await req.libraryItem.media.save()
|
|
|
|
SocketAuthority.libraryItemEmitter('item_updated', req.libraryItem)
|
|
res.json(req.libraryItem.toOldJSON())
|
|
}
|
|
|
|
/**
|
|
*
|
|
* @param {RequestWithUser} req
|
|
* @param {Response} res
|
|
* @param {NextFunction} next
|
|
*/
|
|
async middleware(req, res, next) {
|
|
const libraryItem = await Database.libraryItemModel.getExpandedById(req.params.id)
|
|
if (!libraryItem?.media) return res.sendStatus(404)
|
|
|
|
if (!libraryItem.isPodcast) {
|
|
return res.sendStatus(500)
|
|
}
|
|
|
|
// Check user can access this library item
|
|
if (!req.user.checkCanAccessLibraryItem(libraryItem)) {
|
|
return res.sendStatus(403)
|
|
}
|
|
|
|
if (req.method == 'DELETE' && !req.user.canDelete) {
|
|
Logger.warn(`[PodcastController] User "${req.user.username}" attempted to delete without permission`)
|
|
return res.sendStatus(403)
|
|
} else if ((req.method == 'PATCH' || req.method == 'POST') && !req.user.canUpdate) {
|
|
Logger.warn(`[PodcastController] User "${req.user.username}" attempted to update without permission`)
|
|
return res.sendStatus(403)
|
|
}
|
|
|
|
req.libraryItem = libraryItem
|
|
next()
|
|
}
|
|
}
|
|
module.exports = new PodcastController()
|
|
module.exports.buildEpisodeUpdatePayload = buildEpisodeUpdatePayload
|