mirror of
https://github.com/advplyr/audiobookshelf.git
synced 2026-12-04 22:16:28 +01:00
Add podcast episode batch delete endpoint
This commit is contained in:
1 parent
0f213c2b4e
commit
df5522b569
2 files changed
+200
-44
No files matched your search
@@ -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')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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))
|
||||
|
||||
Reference in new issue
Block a user