audiobookshelf/server/controllers/PlaylistController.js

455 lines
14 KiB
JavaScript
Raw Normal View History

2022-11-26 22:14:45 +01:00
const Logger = require('../Logger')
const SocketAuthority = require('../SocketAuthority')
2023-07-05 01:14:44 +02:00
const Database = require('../Database')
2022-11-26 22:14:45 +01:00
const Playlist = require('../objects/Playlist')
class PlaylistController {
constructor() { }
/**
* POST: /api/playlists
* Create playlist
* @param {*} req
* @param {*} res
*/
2022-11-26 22:14:45 +01:00
async create(req, res) {
const oldPlaylist = new Playlist()
2022-11-26 22:14:45 +01:00
req.body.userId = req.user.id
const success = oldPlaylist.setData(req.body)
2022-11-26 22:14:45 +01:00
if (!success) {
return res.status(400).send('Invalid playlist request data')
}
// Create Playlist record
const newPlaylist = await Database.models.playlist.createFromOld(oldPlaylist)
// Lookup all library items in playlist
const libraryItemIds = oldPlaylist.items.map(i => i.libraryItemId).filter(i => i)
const libraryItemsInPlaylist = await Database.models.libraryItem.findAll({
where: {
id: libraryItemIds
}
})
// Create playlistMediaItem records
const mediaItemsToAdd = []
let order = 1
for (const mediaItemObj of oldPlaylist.items) {
const libraryItem = libraryItemsInPlaylist.find(li => li.id === mediaItemObj.libraryItemId)
if (!libraryItem) continue
mediaItemsToAdd.push({
mediaItemId: mediaItemObj.episodeId || libraryItem.mediaId,
mediaItemType: mediaItemObj.episodeId ? 'podcastEpisode' : 'book',
playlistId: oldPlaylist.id,
order: order++
})
}
if (mediaItemsToAdd.length) {
await Database.createBulkPlaylistMediaItems(mediaItemsToAdd)
}
const jsonExpanded = await newPlaylist.getOldJsonExpanded()
SocketAuthority.clientEmitter(newPlaylist.userId, 'playlist_added', jsonExpanded)
2022-11-26 22:14:45 +01:00
res.json(jsonExpanded)
}
/**
* GET: /api/playlists
* Get all playlists for user
* @param {*} req
* @param {*} res
*/
async findAllForUser(req, res) {
const playlistsForUser = await Database.models.playlist.findAll({
where: {
userId: req.user.id
}
})
const playlists = []
for (const playlist of playlistsForUser) {
const jsonExpanded = await playlist.getOldJsonExpanded()
playlists.push(jsonExpanded)
}
2022-11-26 22:14:45 +01:00
res.json({
playlists
2022-11-26 22:14:45 +01:00
})
}
/**
* GET: /api/playlists/:id
* @param {*} req
* @param {*} res
*/
async findOne(req, res) {
const jsonExpanded = await req.playlist.getOldJsonExpanded()
res.json(jsonExpanded)
2022-11-26 22:14:45 +01:00
}
/**
* PATCH: /api/playlists/:id
* Update playlist
* @param {*} req
* @param {*} res
*/
2022-11-26 22:14:45 +01:00
async update(req, res) {
const updatedPlaylist = req.playlist.set(req.body)
let wasUpdated = false
const changed = updatedPlaylist.changed()
if (changed?.length) {
await req.playlist.save()
Logger.debug(`[PlaylistController] Updated playlist ${req.playlist.id} keys [${changed.join(',')}]`)
wasUpdated = true
}
// If array of items is passed in then update order of playlist media items
const libraryItemIds = req.body.items?.map(i => i.libraryItemId).filter(i => i) || []
if (libraryItemIds.length) {
const libraryItems = await Database.models.libraryItem.findAll({
where: {
id: libraryItemIds
}
})
const existingPlaylistMediaItems = await updatedPlaylist.getPlaylistMediaItems({
order: [['order', 'ASC']]
})
// Set an array of mediaItemId
const newMediaItemIdOrder = []
for (const item of req.body.items) {
const libraryItem = libraryItems.find(li => li.id === item.libraryItemId)
if (!libraryItem) {
continue
}
const mediaItemId = item.episodeId || libraryItem.mediaId
newMediaItemIdOrder.push(mediaItemId)
}
// Sort existing playlist media items into new order
existingPlaylistMediaItems.sort((a, b) => {
const aIndex = newMediaItemIdOrder.findIndex(i => i === a.mediaItemId)
const bIndex = newMediaItemIdOrder.findIndex(i => i === b.mediaItemId)
return aIndex - bIndex
})
// Update order on playlistMediaItem records
let order = 1
for (const playlistMediaItem of existingPlaylistMediaItems) {
if (playlistMediaItem.order !== order) {
await playlistMediaItem.update({
order
})
wasUpdated = true
}
order++
}
}
const jsonExpanded = await updatedPlaylist.getOldJsonExpanded()
2022-11-26 22:14:45 +01:00
if (wasUpdated) {
SocketAuthority.clientEmitter(updatedPlaylist.userId, 'playlist_updated', jsonExpanded)
2022-11-26 22:14:45 +01:00
}
res.json(jsonExpanded)
}
/**
* DELETE: /api/playlists/:id
* Remove playlist
* @param {*} req
* @param {*} res
*/
2022-11-26 22:14:45 +01:00
async delete(req, res) {
const jsonExpanded = await req.playlist.getOldJsonExpanded()
await req.playlist.destroy()
SocketAuthority.clientEmitter(jsonExpanded.userId, 'playlist_removed', jsonExpanded)
2022-11-26 22:14:45 +01:00
res.sendStatus(200)
}
/**
* POST: /api/playlists/:id/item
* Add item to playlist
* @param {*} req
* @param {*} res
*/
2022-11-26 22:14:45 +01:00
async addItem(req, res) {
const oldPlaylist = await Database.models.playlist.getById(req.playlist.id)
2022-11-26 22:14:45 +01:00
const itemToAdd = req.body
if (!itemToAdd.libraryItemId) {
return res.status(400).send('Request body has no libraryItemId')
}
const libraryItem = await Database.models.libraryItem.getOldById(itemToAdd.libraryItemId)
2022-11-26 22:14:45 +01:00
if (!libraryItem) {
return res.status(400).send('Library item not found')
}
if (libraryItem.libraryId !== oldPlaylist.libraryId) {
2022-11-26 22:14:45 +01:00
return res.status(400).send('Library item in different library')
}
if (oldPlaylist.containsItem(itemToAdd)) {
2022-11-26 22:14:45 +01:00
return res.status(400).send('Item already in playlist')
}
if ((itemToAdd.episodeId && !libraryItem.isPodcast) || (libraryItem.isPodcast && !itemToAdd.episodeId)) {
return res.status(400).send('Invalid item to add for this library type')
}
if (itemToAdd.episodeId && !libraryItem.media.checkHasEpisode(itemToAdd.episodeId)) {
return res.status(400).send('Episode not found in library item')
}
2023-07-05 01:14:44 +02:00
const playlistMediaItem = {
playlistId: oldPlaylist.id,
2023-07-05 01:14:44 +02:00
mediaItemId: itemToAdd.episodeId || libraryItem.media.id,
mediaItemType: itemToAdd.episodeId ? 'podcastEpisode' : 'book',
order: oldPlaylist.items.length + 1
2023-07-05 01:14:44 +02:00
}
await Database.createPlaylistMediaItem(playlistMediaItem)
const jsonExpanded = await req.playlist.getOldJsonExpanded()
SocketAuthority.clientEmitter(playlist.userId, 'playlist_updated', jsonExpanded)
2022-11-26 22:14:45 +01:00
res.json(jsonExpanded)
}
/**
* DELETE: /api/playlists/:id/item/:libraryItemId/:episodeId?
* Remove item from playlist
* @param {*} req
* @param {*} res
*/
2022-11-26 22:14:45 +01:00
async removeItem(req, res) {
const oldLibraryItem = await Database.models.libraryItem.getOldById(req.params.libraryItemId)
if (!oldLibraryItem) {
return res.status(404).send('Library item not found')
2022-11-26 22:14:45 +01:00
}
// Get playlist media items
const mediaItemId = req.params.episodeId || oldLibraryItem.media.id
const playlistMediaItems = await req.playlist.getPlaylistMediaItems({
order: [['order', 'ASC']]
})
// Check if media item to delete is in playlist
const mediaItemToRemove = playlistMediaItems.find(pmi => pmi.mediaItemId === mediaItemId)
if (!mediaItemToRemove) {
return res.status(404).send('Media item not found in playlist')
2022-11-26 22:14:45 +01:00
}
// Remove record
await mediaItemToRemove.destroy()
2022-11-26 22:14:45 +01:00
// Update playlist media items order
let order = 1
for (const mediaItem of playlistMediaItems) {
if (mediaItem.mediaItemId === mediaItemId) continue
if (mediaItem.order !== order) {
await mediaItem.update({
order
})
}
order++
}
const jsonExpanded = await req.playlist.getOldJsonExpanded()
// Playlist is removed when there are no items
if (!jsonExpanded.items.length) {
Logger.info(`[PlaylistController] Playlist "${jsonExpanded.name}" has no more items - removing it`)
await req.playlist.destroy()
SocketAuthority.clientEmitter(jsonExpanded.userId, 'playlist_removed', jsonExpanded)
} else {
SocketAuthority.clientEmitter(jsonExpanded.userId, 'playlist_updated', jsonExpanded)
}
res.json(jsonExpanded)
2022-11-26 22:14:45 +01:00
}
/**
* POST: /api/playlists/:id/batch/add
* Batch add playlist items
* @param {*} req
* @param {*} res
*/
2022-11-26 22:14:45 +01:00
async addBatch(req, res) {
if (!req.body.items?.length) {
return res.status(400).send('Invalid request body')
2022-11-26 22:14:45 +01:00
}
const itemsToAdd = req.body.items
2023-07-05 01:14:44 +02:00
const libraryItemIds = itemsToAdd.map(i => i.libraryItemId).filter(i => i)
if (!libraryItemIds.length) {
return res.status(400).send('Invalid request body')
}
2022-11-26 22:14:45 +01:00
// Find all library items
const libraryItems = await Database.models.libraryItem.findAll({
where: {
id: libraryItemIds
2023-07-05 01:14:44 +02:00
}
})
2023-07-05 01:14:44 +02:00
// Get all existing playlist media items
const existingPlaylistMediaItems = await req.playlist.getPlaylistMediaItems({
order: [['order', 'ASC']]
})
const mediaItemsToAdd = []
// Setup array of playlistMediaItem records to add
let order = existingPlaylistMediaItems.length + 1
for (const item of itemsToAdd) {
const libraryItem = libraryItems.find(li => li.id === item.libraryItemId)
if (!libraryItem) {
return res.status(404).send('Item not found with id ' + item.libraryItemId)
} else {
const mediaItemId = item.episodeId || libraryItem.mediaId
if (existingPlaylistMediaItems.some(pmi => pmi.mediaItemId === mediaItemId)) {
// Already exists in playlist
continue
} else {
mediaItemsToAdd.push({
playlistId: req.playlist.id,
mediaItemId,
mediaItemType: item.episodeId ? 'podcastEpisode' : 'book',
order: order++
})
}
2022-11-26 22:14:45 +01:00
}
}
let jsonExpanded = null
if (mediaItemsToAdd.length) {
await Database.createBulkPlaylistMediaItems(mediaItemsToAdd)
jsonExpanded = await req.playlist.getOldJsonExpanded()
SocketAuthority.clientEmitter(req.playlist.userId, 'playlist_updated', jsonExpanded)
} else {
jsonExpanded = await req.playlist.getOldJsonExpanded()
2022-11-26 22:14:45 +01:00
}
res.json(jsonExpanded)
}
/**
* POST: /api/playlists/:id/batch/remove
* Batch remove playlist items
* @param {*} req
* @param {*} res
*/
2022-11-26 22:14:45 +01:00
async removeBatch(req, res) {
if (!req.body.items?.length) {
return res.status(400).send('Invalid request body')
2022-11-26 22:14:45 +01:00
}
2022-11-26 22:14:45 +01:00
const itemsToRemove = req.body.items
const libraryItemIds = itemsToRemove.map(i => i.libraryItemId).filter(i => i)
if (!libraryItemIds.length) {
return res.status(400).send('Invalid request body')
}
2023-07-05 01:14:44 +02:00
// Find all library items
const libraryItems = await Database.models.libraryItem.findAll({
where: {
id: libraryItemIds
2022-11-26 22:14:45 +01:00
}
})
// Get all existing playlist media items for playlist
const existingPlaylistMediaItems = await req.playlist.getPlaylistMediaItems({
order: [['order', 'ASC']]
})
let numMediaItems = existingPlaylistMediaItems.length
// Remove playlist media items
let hasUpdated = false
for (const item of itemsToRemove) {
const libraryItem = libraryItems.find(li => li.id === item.libraryItemId)
if (!libraryItem) continue
const mediaItemId = item.episodeId || libraryItem.mediaId
const existingMediaItem = existingPlaylistMediaItems.find(pmi => pmi.mediaItemId === mediaItemId)
if (!existingMediaItem) continue
await existingMediaItem.destroy()
hasUpdated = true
numMediaItems--
2022-11-26 22:14:45 +01:00
}
const jsonExpanded = await req.playlist.getOldJsonExpanded()
2022-11-26 22:14:45 +01:00
if (hasUpdated) {
// Playlist is removed when there are no items
if (!numMediaItems) {
Logger.info(`[PlaylistController] Playlist "${req.playlist.name}" has no more items - removing it`)
await req.playlist.destroy()
SocketAuthority.clientEmitter(playlist.userId, 'playlist_removed', jsonExpanded)
} else {
SocketAuthority.clientEmitter(playlist.userId, 'playlist_updated', jsonExpanded)
}
2022-11-26 22:14:45 +01:00
}
res.json(jsonExpanded)
}
/**
* POST: /api/playlists/collection/:collectionId
* Create a playlist from a collection
* @param {*} req
* @param {*} res
*/
async createFromCollection(req, res) {
const collection = await Database.models.collection.findByPk(req.params.collectionId)
if (!collection) {
return res.status(404).send('Collection not found')
}
// Expand collection to get library items
const collectionExpanded = await collection.getOldJsonExpanded(req.user)
if (!collectionExpanded) {
// This can happen if the user has no access to all items in collection
return res.status(404).send('Collection not found')
}
// Playlists cannot be empty
if (!collectionExpanded.books.length) {
return res.status(400).send('Collection has no books')
}
const oldPlaylist = new Playlist()
oldPlaylist.setData({
userId: req.user.id,
libraryId: collection.libraryId,
name: collection.name,
description: collection.description || null
})
// Create Playlist record
const newPlaylist = await Database.models.playlist.createFromOld(oldPlaylist)
// Create PlaylistMediaItem records
const mediaItemsToAdd = []
let order = 1
for (const libraryItem of collectionExpanded.books) {
mediaItemsToAdd.push({
playlistId: newPlaylist.id,
mediaItemId: libraryItem.media.id,
mediaItemType: 'book',
order: order++
})
}
await Database.createBulkPlaylistMediaItems(mediaItemsToAdd)
const jsonExpanded = await newPlaylist.getOldJsonExpanded()
SocketAuthority.clientEmitter(newPlaylist.userId, 'playlist_added', jsonExpanded)
res.json(jsonExpanded)
}
async middleware(req, res, next) {
2022-11-26 22:14:45 +01:00
if (req.params.id) {
const playlist = await Database.models.playlist.findByPk(req.params.id)
2022-11-26 22:14:45 +01:00
if (!playlist) {
return res.status(404).send('Playlist not found')
}
if (playlist.userId !== req.user.id) {
Logger.warn(`[PlaylistController] Playlist ${req.params.id} requested by user ${req.user.id} that is not the owner`)
return res.sendStatus(403)
}
req.playlist = playlist
}
next()
}
}
module.exports = new PlaylistController()