2022-03-14 15:56:24 +01:00
|
|
|
const Path = require('path')
|
2022-07-06 02:53:01 +02:00
|
|
|
const fs = require('../libs/fsExtra')
|
2022-03-14 15:56:24 +01:00
|
|
|
const filePerms = require('../utils/filePerms')
|
2021-11-22 03:00:40 +01:00
|
|
|
const Logger = require('../Logger')
|
2022-11-24 22:53:58 +01:00
|
|
|
const SocketAuthority = require('../SocketAuthority')
|
2021-11-22 03:00:40 +01:00
|
|
|
const Library = require('../objects/Library')
|
2021-12-01 03:02:40 +01:00
|
|
|
const libraryHelpers = require('../utils/libraryHelpers')
|
2022-06-08 03:22:23 +02:00
|
|
|
const { sort, createNewSortInstance } = require('../libs/fastSort')
|
2021-12-26 23:17:10 +01:00
|
|
|
const naturalSort = createNewSortInstance({
|
|
|
|
comparer: new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }).compare
|
|
|
|
})
|
2023-07-05 01:14:44 +02:00
|
|
|
|
|
|
|
const Database = require('../Database')
|
|
|
|
|
2021-11-22 03:00:40 +01:00
|
|
|
class LibraryController {
|
|
|
|
constructor() { }
|
|
|
|
|
|
|
|
async create(req, res) {
|
2022-12-01 00:32:59 +01:00
|
|
|
const newLibraryPayload = {
|
2021-11-22 03:00:40 +01:00
|
|
|
...req.body
|
|
|
|
}
|
|
|
|
if (!newLibraryPayload.name || !newLibraryPayload.folders || !newLibraryPayload.folders.length) {
|
|
|
|
return res.status(500).send('Invalid request')
|
|
|
|
}
|
|
|
|
|
2022-03-19 12:41:54 +01:00
|
|
|
// Validate folder paths exist or can be created & resolve rel paths
|
|
|
|
// returns 400 if a folder fails to access
|
|
|
|
newLibraryPayload.folders = newLibraryPayload.folders.map(f => {
|
|
|
|
f.fullPath = Path.resolve(f.fullPath)
|
|
|
|
return f
|
|
|
|
})
|
2022-12-01 00:32:59 +01:00
|
|
|
for (const folder of newLibraryPayload.folders) {
|
2022-04-21 00:49:34 +02:00
|
|
|
try {
|
2022-12-01 00:32:59 +01:00
|
|
|
const direxists = await fs.pathExists(folder.fullPath)
|
2022-04-21 00:49:34 +02:00
|
|
|
if (!direxists) { // If folder does not exist try to make it and set file permissions/owner
|
|
|
|
await fs.mkdir(folder.fullPath)
|
|
|
|
await filePerms.setDefault(folder.fullPath)
|
|
|
|
}
|
|
|
|
} catch (error) {
|
2022-03-19 12:41:54 +01:00
|
|
|
Logger.error(`[LibraryController] Failed to ensure folder dir "${folder.fullPath}"`, error)
|
|
|
|
return res.status(400).send(`Invalid folder directory "${folder.fullPath}"`)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-01 00:32:59 +01:00
|
|
|
const library = new Library()
|
2023-07-09 18:39:15 +02:00
|
|
|
|
2023-07-22 21:25:20 +02:00
|
|
|
let currentLargestDisplayOrder = await Database.models.library.getMaxDisplayOrder()
|
|
|
|
if (isNaN(currentLargestDisplayOrder)) currentLargestDisplayOrder = 0
|
|
|
|
newLibraryPayload.displayOrder = currentLargestDisplayOrder + 1
|
2021-11-22 03:00:40 +01:00
|
|
|
library.setData(newLibraryPayload)
|
2023-07-05 01:14:44 +02:00
|
|
|
await Database.createLibrary(library)
|
2022-12-01 00:32:59 +01:00
|
|
|
|
|
|
|
// Only emit to users with access to library
|
|
|
|
const userFilter = (user) => {
|
2023-07-05 01:14:44 +02:00
|
|
|
return user.checkCanAccessLibrary?.(library.id)
|
2022-12-01 00:32:59 +01:00
|
|
|
}
|
|
|
|
SocketAuthority.emitter('library_added', library.toJSON(), userFilter)
|
2021-11-22 03:00:40 +01:00
|
|
|
|
|
|
|
// Add library watcher
|
|
|
|
this.watcher.addLibrary(library)
|
|
|
|
|
|
|
|
res.json(library)
|
|
|
|
}
|
|
|
|
|
2023-07-22 21:25:20 +02:00
|
|
|
async findAll(req, res) {
|
|
|
|
const libraries = await Database.models.library.getAllOldLibraries()
|
|
|
|
|
2022-12-01 00:32:59 +01:00
|
|
|
const librariesAccessible = req.user.librariesAccessible || []
|
2023-07-05 01:14:44 +02:00
|
|
|
if (librariesAccessible.length) {
|
2022-12-20 00:46:32 +01:00
|
|
|
return res.json({
|
2023-07-22 21:25:20 +02:00
|
|
|
libraries: libraries.filter(lib => librariesAccessible.includes(lib.id)).map(lib => lib.toJSON())
|
2022-12-20 00:46:32 +01:00
|
|
|
})
|
2022-01-16 18:17:09 +01:00
|
|
|
}
|
|
|
|
|
2022-11-29 18:30:25 +01:00
|
|
|
res.json({
|
2023-07-22 21:25:20 +02:00
|
|
|
libraries: libraries.map(lib => lib.toJSON())
|
2022-11-29 18:30:25 +01:00
|
|
|
})
|
2021-11-22 03:00:40 +01:00
|
|
|
}
|
|
|
|
|
2021-12-01 03:02:40 +01:00
|
|
|
async findOne(req, res) {
|
2022-11-27 21:34:27 +01:00
|
|
|
const includeArray = (req.query.include || '').split(',')
|
|
|
|
if (includeArray.includes('filterdata')) {
|
2021-12-01 03:02:40 +01:00
|
|
|
return res.json({
|
2022-03-11 01:45:02 +01:00
|
|
|
filterdata: libraryHelpers.getDistinctFilterDataNew(req.libraryItems),
|
2022-03-18 18:37:47 +01:00
|
|
|
issues: req.libraryItems.filter(li => li.hasIssues).length,
|
2023-07-05 01:14:44 +02:00
|
|
|
numUserPlaylists: Database.playlists.filter(p => p.userId === req.user.id && p.libraryId === req.library.id).length,
|
2021-12-01 03:02:40 +01:00
|
|
|
library: req.library
|
|
|
|
})
|
2021-11-22 03:00:40 +01:00
|
|
|
}
|
2021-12-01 03:02:40 +01:00
|
|
|
return res.json(req.library)
|
2021-11-22 03:00:40 +01:00
|
|
|
}
|
|
|
|
|
2023-03-05 17:35:34 +01:00
|
|
|
async getEpisodeDownloadQueue(req, res) {
|
|
|
|
const libraryDownloadQueueDetails = this.podcastManager.getDownloadQueueDetails(req.library.id)
|
|
|
|
return res.json(libraryDownloadQueueDetails)
|
2023-02-27 03:56:07 +01:00
|
|
|
}
|
|
|
|
|
2021-11-22 03:00:40 +01:00
|
|
|
async update(req, res) {
|
2022-12-01 00:32:59 +01:00
|
|
|
const library = req.library
|
2022-02-03 23:39:05 +01:00
|
|
|
|
2022-03-14 15:56:24 +01:00
|
|
|
// Validate new folder paths exist or can be created & resolve rel paths
|
|
|
|
// returns 400 if a new folder fails to access
|
|
|
|
if (req.body.folders) {
|
2022-12-01 00:32:59 +01:00
|
|
|
const newFolderPaths = []
|
2022-03-14 15:56:24 +01:00
|
|
|
req.body.folders = req.body.folders.map(f => {
|
|
|
|
if (!f.id) {
|
|
|
|
f.fullPath = Path.resolve(f.fullPath)
|
|
|
|
newFolderPaths.push(f.fullPath)
|
|
|
|
}
|
|
|
|
return f
|
|
|
|
})
|
2022-12-01 00:32:59 +01:00
|
|
|
for (const path of newFolderPaths) {
|
|
|
|
const pathExists = await fs.pathExists(path)
|
2022-05-20 02:00:34 +02:00
|
|
|
if (!pathExists) {
|
|
|
|
// Ensure dir will recursively create directories which might be preferred over mkdir
|
2022-12-01 00:32:59 +01:00
|
|
|
const success = await fs.ensureDir(path).then(() => true).catch((error) => {
|
2022-05-20 02:00:34 +02:00
|
|
|
Logger.error(`[LibraryController] Failed to ensure folder dir "${path}"`, error)
|
|
|
|
return false
|
|
|
|
})
|
|
|
|
if (!success) {
|
|
|
|
return res.status(400).send(`Invalid folder directory "${path}"`)
|
|
|
|
}
|
|
|
|
// Set permissions on newly created path
|
2022-03-14 15:56:24 +01:00
|
|
|
await filePerms.setDefault(path)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-01 00:32:59 +01:00
|
|
|
const hasUpdates = library.update(req.body)
|
2022-02-03 23:39:05 +01:00
|
|
|
// TODO: Should check if this is an update to folder paths or name only
|
2021-11-22 03:00:40 +01:00
|
|
|
if (hasUpdates) {
|
|
|
|
// Update watcher
|
|
|
|
this.watcher.updateLibrary(library)
|
|
|
|
|
2022-08-18 01:44:21 +02:00
|
|
|
// Update auto scan cron
|
|
|
|
this.cronManager.updateLibraryScanCron(library)
|
|
|
|
|
2022-03-13 00:45:32 +01:00
|
|
|
// Remove libraryItems no longer in library
|
2023-07-05 01:14:44 +02:00
|
|
|
const itemsToRemove = Database.libraryItems.filter(li => li.libraryId === library.id && !library.checkFullPathInLibrary(li.path))
|
2022-03-13 00:45:32 +01:00
|
|
|
if (itemsToRemove.length) {
|
|
|
|
Logger.info(`[Scanner] Updating library, removing ${itemsToRemove.length} items`)
|
|
|
|
for (let i = 0; i < itemsToRemove.length; i++) {
|
|
|
|
await this.handleDeleteLibraryItem(itemsToRemove[i])
|
2021-11-22 03:00:40 +01:00
|
|
|
}
|
|
|
|
}
|
2023-07-05 01:14:44 +02:00
|
|
|
await Database.updateLibrary(library)
|
2022-12-01 00:32:59 +01:00
|
|
|
|
|
|
|
// Only emit to users with access to library
|
|
|
|
const userFilter = (user) => {
|
|
|
|
return user.checkCanAccessLibrary && user.checkCanAccessLibrary(library.id)
|
|
|
|
}
|
|
|
|
SocketAuthority.emitter('library_updated', library.toJSON(), userFilter)
|
2021-11-22 03:00:40 +01:00
|
|
|
}
|
|
|
|
return res.json(library.toJSON())
|
|
|
|
}
|
|
|
|
|
2023-07-22 21:25:20 +02:00
|
|
|
/**
|
|
|
|
* DELETE: /api/libraries/:id
|
|
|
|
* Delete a library
|
|
|
|
* @param {*} req
|
|
|
|
* @param {*} res
|
|
|
|
*/
|
2021-11-22 03:00:40 +01:00
|
|
|
async delete(req, res) {
|
2022-12-01 00:32:59 +01:00
|
|
|
const library = req.library
|
2021-11-22 03:00:40 +01:00
|
|
|
|
|
|
|
// Remove library watcher
|
|
|
|
this.watcher.removeLibrary(library)
|
|
|
|
|
2022-11-12 00:44:19 +01:00
|
|
|
// Remove collections for library
|
2023-07-22 23:18:55 +02:00
|
|
|
const numCollectionsRemoved = await Database.models.collection.removeAllForLibrary(library.id)
|
|
|
|
if (numCollectionsRemoved) {
|
|
|
|
Logger.info(`[Server] Removed ${numCollectionsRemoved} collections for library "${library.name}"`)
|
2022-11-12 00:44:19 +01:00
|
|
|
}
|
|
|
|
|
2022-03-13 00:45:32 +01:00
|
|
|
// Remove items in this library
|
2023-07-05 01:14:44 +02:00
|
|
|
const libraryItems = Database.libraryItems.filter(li => li.libraryId === library.id)
|
2022-03-13 00:45:32 +01:00
|
|
|
Logger.info(`[Server] deleting library "${library.name}" with ${libraryItems.length} items"`)
|
|
|
|
for (let i = 0; i < libraryItems.length; i++) {
|
|
|
|
await this.handleDeleteLibraryItem(libraryItems[i])
|
2021-11-22 03:00:40 +01:00
|
|
|
}
|
|
|
|
|
2022-12-01 00:32:59 +01:00
|
|
|
const libraryJson = library.toJSON()
|
2023-07-05 01:14:44 +02:00
|
|
|
await Database.removeLibrary(library.id)
|
2023-07-22 21:25:20 +02:00
|
|
|
|
|
|
|
// Re-order libraries
|
|
|
|
await Database.models.library.resetDisplayOrder()
|
|
|
|
|
2022-11-24 22:53:58 +01:00
|
|
|
SocketAuthority.emitter('library_removed', libraryJson)
|
2021-11-22 03:00:40 +01:00
|
|
|
return res.json(libraryJson)
|
|
|
|
}
|
|
|
|
|
2022-03-11 01:45:02 +01:00
|
|
|
// api/libraries/:id/items
|
2022-03-13 00:45:32 +01:00
|
|
|
// TODO: Optimize this method, items are iterated through several times but can be combined
|
2023-07-17 23:48:46 +02:00
|
|
|
async getLibraryItems(req, res) {
|
2022-12-31 17:59:12 +01:00
|
|
|
let libraryItems = req.libraryItems
|
|
|
|
|
|
|
|
const include = (req.query.include || '').split(',').map(v => v.trim().toLowerCase()).filter(v => !!v)
|
|
|
|
|
|
|
|
const payload = {
|
2022-03-11 01:45:02 +01:00
|
|
|
results: [],
|
|
|
|
total: libraryItems.length,
|
|
|
|
limit: req.query.limit && !isNaN(req.query.limit) ? Number(req.query.limit) : 0,
|
|
|
|
page: req.query.page && !isNaN(req.query.page) ? Number(req.query.page) : 0,
|
|
|
|
sortBy: req.query.sort,
|
|
|
|
sortDesc: req.query.desc === '1',
|
|
|
|
filterBy: req.query.filter,
|
2022-03-26 17:59:34 +01:00
|
|
|
mediaType: req.library.mediaType,
|
2022-03-11 01:45:02 +01:00
|
|
|
minified: req.query.minified === '1',
|
2022-12-31 17:59:12 +01:00
|
|
|
collapseseries: req.query.collapseseries === '1',
|
|
|
|
include: include.join(',')
|
2022-03-11 01:45:02 +01:00
|
|
|
}
|
2022-12-01 00:32:59 +01:00
|
|
|
const mediaIsBook = payload.mediaType === 'book'
|
2023-07-15 21:45:08 +02:00
|
|
|
const mediaIsPodcast = payload.mediaType === 'podcast'
|
2021-11-29 02:36:44 +01:00
|
|
|
|
2022-10-30 16:38:00 +01:00
|
|
|
// Step 1 - Filter the retrieved library items
|
2022-12-01 00:32:59 +01:00
|
|
|
let filterSeries = null
|
2022-03-11 01:45:02 +01:00
|
|
|
if (payload.filterBy) {
|
2023-07-17 23:48:46 +02:00
|
|
|
libraryItems = await libraryHelpers.getFilteredLibraryItems(libraryItems, payload.filterBy, req.user)
|
2022-03-11 01:45:02 +01:00
|
|
|
payload.total = libraryItems.length
|
2022-10-30 16:38:00 +01:00
|
|
|
|
|
|
|
// Determining if we are filtering titles by a series, and if so, which series
|
|
|
|
filterSeries = (mediaIsBook && payload.filterBy.startsWith('series.')) ? libraryHelpers.decode(payload.filterBy.replace('series.', '')) : null
|
2022-11-28 00:54:40 +01:00
|
|
|
if (filterSeries === 'no-series') filterSeries = null
|
2021-11-29 02:36:44 +01:00
|
|
|
}
|
2021-11-22 03:00:40 +01:00
|
|
|
|
2022-10-30 16:38:00 +01:00
|
|
|
// Step 2 - If selected, collapse library items by the series they belong to.
|
|
|
|
// If also filtering by series, will not collapse the filtered series as this would lead
|
|
|
|
// to series having a collapsed series that is just that series.
|
2022-10-30 15:21:12 +01:00
|
|
|
if (payload.collapseseries) {
|
2023-07-05 01:14:44 +02:00
|
|
|
let collapsedItems = libraryHelpers.collapseBookSeries(libraryItems, Database.series, filterSeries, req.library.settings.hideSingleBookSeries)
|
2022-10-30 15:21:12 +01:00
|
|
|
|
2022-10-30 16:38:00 +01:00
|
|
|
if (!(collapsedItems.length == 1 && collapsedItems[0].collapsedSeries)) {
|
|
|
|
libraryItems = collapsedItems
|
2022-11-13 20:25:20 +01:00
|
|
|
|
|
|
|
// Get accurate total entities
|
2022-11-13 23:46:43 +01:00
|
|
|
// let uniqueEntities = new Set()
|
|
|
|
// libraryItems.forEach((item) => {
|
|
|
|
// if (item.collapsedSeries) {
|
|
|
|
// item.collapsedSeries.books.forEach(book => uniqueEntities.add(book.id))
|
|
|
|
// } else {
|
|
|
|
// uniqueEntities.add(item.id)
|
|
|
|
// }
|
|
|
|
// })
|
|
|
|
payload.total = libraryItems.length
|
2022-10-30 16:38:00 +01:00
|
|
|
}
|
|
|
|
}
|
2022-10-30 15:21:12 +01:00
|
|
|
|
2022-10-30 16:38:00 +01:00
|
|
|
// Step 3 - Sort the retrieved library items.
|
2022-12-31 17:59:12 +01:00
|
|
|
const sortArray = []
|
2022-10-30 16:38:00 +01:00
|
|
|
|
|
|
|
// When on the series page, sort by sequence only
|
|
|
|
if (filterSeries && !payload.sortBy) {
|
2022-10-30 15:21:12 +01:00
|
|
|
sortArray.push({ asc: (li) => li.media.metadata.getSeries(filterSeries).sequence })
|
2023-03-05 21:48:20 +01:00
|
|
|
// If no series sequence then fallback to sorting by title (or collapsed series name for sub-series)
|
|
|
|
sortArray.push({
|
|
|
|
asc: (li) => {
|
2023-07-05 01:14:44 +02:00
|
|
|
if (Database.serverSettings.sortingIgnorePrefix) {
|
2023-03-05 21:48:20 +01:00
|
|
|
return li.collapsedSeries?.nameIgnorePrefix || li.media.metadata.titleIgnorePrefix
|
|
|
|
} else {
|
|
|
|
return li.collapsedSeries?.name || li.media.metadata.title
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
2022-10-30 15:21:12 +01:00
|
|
|
}
|
|
|
|
|
2022-03-11 01:45:02 +01:00
|
|
|
if (payload.sortBy) {
|
2022-12-01 00:32:59 +01:00
|
|
|
let sortKey = payload.sortBy
|
2022-03-11 01:45:02 +01:00
|
|
|
|
|
|
|
// Handle server setting sortingIgnorePrefix
|
2022-07-15 02:00:52 +02:00
|
|
|
const sortByTitle = sortKey === 'media.metadata.title'
|
2023-07-05 01:14:44 +02:00
|
|
|
if (sortByTitle && Database.serverSettings.sortingIgnorePrefix) {
|
2022-03-11 01:45:02 +01:00
|
|
|
// BookMetadata.js has titleIgnorePrefix getter
|
|
|
|
sortKey += 'IgnorePrefix'
|
|
|
|
}
|
|
|
|
|
2022-11-03 14:11:33 +01:00
|
|
|
// If series are collapsed and not sorting by title or sequence,
|
|
|
|
// sort all collapsed series to the end in alphabetical order
|
|
|
|
const sortBySequence = filterSeries && (sortKey === 'sequence')
|
|
|
|
if (payload.collapseseries && !(sortByTitle || sortBySequence)) {
|
2022-10-30 15:21:12 +01:00
|
|
|
sortArray.push({
|
|
|
|
asc: (li) => {
|
|
|
|
if (li.collapsedSeries) {
|
2023-07-05 01:14:44 +02:00
|
|
|
return Database.serverSettings.sortingIgnorePrefix ?
|
2022-10-30 15:21:12 +01:00
|
|
|
li.collapsedSeries.nameIgnorePrefix :
|
|
|
|
li.collapsedSeries.name
|
|
|
|
} else {
|
|
|
|
return ''
|
2022-07-15 02:00:52 +02:00
|
|
|
}
|
2022-10-30 15:21:12 +01:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2022-07-15 02:00:52 +02:00
|
|
|
|
2022-11-03 14:11:33 +01:00
|
|
|
// Sort series based on the sortBy attribute
|
2022-12-01 00:32:59 +01:00
|
|
|
const direction = payload.sortDesc ? 'desc' : 'asc'
|
2022-10-30 15:21:12 +01:00
|
|
|
sortArray.push({
|
|
|
|
[direction]: (li) => {
|
2022-11-03 14:11:33 +01:00
|
|
|
if (mediaIsBook && sortBySequence) {
|
|
|
|
return li.media.metadata.getSeries(filterSeries).sequence
|
|
|
|
} else if (mediaIsBook && sortByTitle && li.collapsedSeries) {
|
2023-07-05 01:14:44 +02:00
|
|
|
return Database.serverSettings.sortingIgnorePrefix ?
|
2022-10-30 15:21:12 +01:00
|
|
|
li.collapsedSeries.nameIgnorePrefix :
|
|
|
|
li.collapsedSeries.name
|
|
|
|
} else {
|
2022-04-23 00:11:03 +02:00
|
|
|
// Supports dot notation strings i.e. "media.metadata.title"
|
|
|
|
return sortKey.split('.').reduce((a, b) => a[b], li)
|
|
|
|
}
|
|
|
|
}
|
2022-10-30 15:21:12 +01:00
|
|
|
})
|
2022-04-23 00:11:03 +02:00
|
|
|
|
|
|
|
// Secondary sort when sorting by book author use series sort title
|
2022-10-30 15:21:12 +01:00
|
|
|
if (mediaIsBook && payload.sortBy.includes('author')) {
|
2022-04-23 00:11:03 +02:00
|
|
|
sortArray.push({
|
|
|
|
asc: (li) => {
|
|
|
|
if (li.media.metadata.series && li.media.metadata.series.length) {
|
|
|
|
return li.media.metadata.getSeriesSortTitle(li.media.metadata.series[0])
|
|
|
|
}
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2021-11-29 02:36:44 +01:00
|
|
|
}
|
|
|
|
|
2022-10-30 15:21:12 +01:00
|
|
|
if (sortArray.length) {
|
|
|
|
libraryItems = naturalSort(libraryItems).by(sortArray)
|
2022-04-10 02:44:46 +02:00
|
|
|
}
|
2022-03-11 01:45:02 +01:00
|
|
|
|
2022-11-13 20:25:20 +01:00
|
|
|
// Step 3.5: Limit items
|
|
|
|
if (payload.limit) {
|
2022-12-31 17:59:12 +01:00
|
|
|
const startIndex = payload.page * payload.limit
|
2022-11-13 20:25:20 +01:00
|
|
|
libraryItems = libraryItems.slice(startIndex, startIndex + payload.limit)
|
|
|
|
}
|
|
|
|
|
2022-10-30 16:38:00 +01:00
|
|
|
// Step 4 - Transform the items to pass to the client side
|
2023-07-17 23:48:46 +02:00
|
|
|
payload.results = await Promise.all(libraryItems.map(async li => {
|
2022-12-31 17:59:12 +01:00
|
|
|
const json = payload.minified ? li.toJSONMinified() : li.toJSON()
|
2022-10-30 15:21:12 +01:00
|
|
|
|
|
|
|
if (li.collapsedSeries) {
|
|
|
|
json.collapsedSeries = {
|
|
|
|
id: li.collapsedSeries.id,
|
|
|
|
name: li.collapsedSeries.name,
|
|
|
|
nameIgnorePrefix: li.collapsedSeries.nameIgnorePrefix,
|
|
|
|
libraryItemIds: li.collapsedSeries.books.map(b => b.id),
|
|
|
|
numBooks: li.collapsedSeries.books.length
|
|
|
|
}
|
2022-10-30 16:38:00 +01:00
|
|
|
|
|
|
|
// If collapsing by series and filtering by a series, generate the list of sequences the collapsed
|
|
|
|
// series represents in the filtered series
|
|
|
|
if (filterSeries) {
|
2022-11-03 14:11:33 +01:00
|
|
|
json.collapsedSeries.seriesSequenceList =
|
2023-01-31 22:53:04 +01:00
|
|
|
naturalSort(li.collapsedSeries.books.filter(b => b.filterSeriesSequence).map(b => b.filterSeriesSequence)).asc()
|
2022-11-03 14:11:33 +01:00
|
|
|
.reduce((ranges, currentSequence) => {
|
|
|
|
let lastRange = ranges.at(-1)
|
|
|
|
let isNumber = /^(\d+|\d+\.\d*|\d*\.\d+)$/.test(currentSequence)
|
|
|
|
if (isNumber) currentSequence = parseFloat(currentSequence)
|
|
|
|
|
|
|
|
if (lastRange && isNumber && lastRange.isNumber && ((lastRange.end + 1) == currentSequence)) {
|
|
|
|
lastRange.end = currentSequence
|
|
|
|
}
|
|
|
|
else {
|
2022-11-07 15:24:48 +01:00
|
|
|
ranges.push({ start: currentSequence, end: currentSequence, isNumber: isNumber })
|
2022-11-03 14:11:33 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return ranges
|
|
|
|
}, [])
|
|
|
|
.map(r => r.start == r.end ? r.start : `${r.start}-${r.end}`)
|
|
|
|
.join(', ')
|
2022-10-30 16:38:00 +01:00
|
|
|
}
|
2022-12-31 17:59:12 +01:00
|
|
|
} else {
|
|
|
|
// add rssFeed object if "include=rssfeed" was put in query string (only for non-collapsed series)
|
|
|
|
if (include.includes('rssfeed')) {
|
2023-07-17 23:48:46 +02:00
|
|
|
const feedData = await this.rssFeedManager.findFeedForEntityId(json.id)
|
2022-12-31 21:31:38 +01:00
|
|
|
json.rssFeed = feedData ? feedData.toJSONMinified() : null
|
2022-12-31 17:59:12 +01:00
|
|
|
}
|
|
|
|
|
2023-07-15 21:45:08 +02:00
|
|
|
// add numEpisodesIncomplete if "include=numEpisodesIncomplete" was put in query string (only for podcasts)
|
|
|
|
if (mediaIsPodcast && include.includes('numepisodesincomplete')) {
|
|
|
|
json.numEpisodesIncomplete = req.user.getNumEpisodesIncompleteForPodcast(li)
|
|
|
|
}
|
|
|
|
|
2022-12-31 17:59:12 +01:00
|
|
|
if (filterSeries) {
|
|
|
|
// If filtering by series, make sure to include the series metadata
|
|
|
|
json.media.metadata.series = li.media.metadata.getSeries(filterSeries)
|
|
|
|
}
|
2022-10-30 15:21:12 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return json
|
2023-07-17 23:48:46 +02:00
|
|
|
}))
|
2022-10-30 15:21:12 +01:00
|
|
|
|
2022-03-11 01:45:02 +01:00
|
|
|
res.json(payload)
|
2021-11-22 03:00:40 +01:00
|
|
|
}
|
|
|
|
|
2022-04-25 01:25:33 +02:00
|
|
|
async removeLibraryItemsWithIssues(req, res) {
|
2022-12-01 00:32:59 +01:00
|
|
|
const libraryItemsWithIssues = req.libraryItems.filter(li => li.hasIssues)
|
2022-04-25 01:25:33 +02:00
|
|
|
if (!libraryItemsWithIssues.length) {
|
|
|
|
Logger.warn(`[LibraryController] No library items have issues`)
|
|
|
|
return res.sendStatus(200)
|
|
|
|
}
|
|
|
|
|
|
|
|
Logger.info(`[LibraryController] Removing ${libraryItemsWithIssues.length} items with issues`)
|
|
|
|
for (const libraryItem of libraryItemsWithIssues) {
|
|
|
|
Logger.info(`[LibraryController] Removing library item "${libraryItem.media.metadata.title}"`)
|
|
|
|
await this.handleDeleteLibraryItem(libraryItem)
|
|
|
|
}
|
|
|
|
|
|
|
|
res.sendStatus(200)
|
|
|
|
}
|
|
|
|
|
2023-07-08 00:59:17 +02:00
|
|
|
/**
|
|
|
|
* api/libraries/:id/series
|
|
|
|
* Optional query string: `?include=rssfeed` that adds `rssFeed` to series if a feed is open
|
|
|
|
*
|
|
|
|
* @param {*} req
|
|
|
|
* @param {*} res
|
|
|
|
*/
|
2021-12-02 02:07:03 +01:00
|
|
|
async getAllSeriesForLibrary(req, res) {
|
2022-12-01 00:32:59 +01:00
|
|
|
const libraryItems = req.libraryItems
|
2022-12-31 23:58:19 +01:00
|
|
|
|
|
|
|
const include = (req.query.include || '').split(',').map(v => v.trim().toLowerCase()).filter(v => !!v)
|
|
|
|
|
2022-12-01 00:32:59 +01:00
|
|
|
const payload = {
|
2021-12-01 03:02:40 +01:00
|
|
|
results: [],
|
|
|
|
total: 0,
|
|
|
|
limit: req.query.limit && !isNaN(req.query.limit) ? Number(req.query.limit) : 0,
|
|
|
|
page: req.query.page && !isNaN(req.query.page) ? Number(req.query.page) : 0,
|
|
|
|
sortBy: req.query.sort,
|
|
|
|
sortDesc: req.query.desc === '1',
|
2021-12-24 23:37:57 +01:00
|
|
|
filterBy: req.query.filter,
|
2022-12-31 23:58:19 +01:00
|
|
|
minified: req.query.minified === '1',
|
|
|
|
include: include.join(',')
|
2021-12-01 03:02:40 +01:00
|
|
|
}
|
|
|
|
|
2023-07-05 01:14:44 +02:00
|
|
|
let series = libraryHelpers.getSeriesFromBooks(libraryItems, Database.series, null, payload.filterBy, req.user, payload.minified, req.library.settings.hideSingleBookSeries)
|
2022-10-29 22:33:38 +02:00
|
|
|
|
2022-10-29 18:17:51 +02:00
|
|
|
const direction = payload.sortDesc ? 'desc' : 'asc'
|
|
|
|
series = naturalSort(series).by([
|
|
|
|
{
|
|
|
|
[direction]: (se) => {
|
|
|
|
if (payload.sortBy === 'numBooks') {
|
|
|
|
return se.books.length
|
|
|
|
} else if (payload.sortBy === 'totalDuration') {
|
|
|
|
return se.totalDuration
|
|
|
|
} else if (payload.sortBy === 'addedAt') {
|
|
|
|
return se.addedAt
|
2023-04-12 05:18:25 +02:00
|
|
|
} else if (payload.sortBy === 'lastBookUpdated') {
|
|
|
|
return Math.max(...(se.books).map(x => x.updatedAt), 0)
|
|
|
|
} else if (payload.sortBy === 'lastBookAdded') {
|
|
|
|
return Math.max(...(se.books).map(x => x.addedAt), 0)
|
2022-10-29 18:17:51 +02:00
|
|
|
} else { // sort by name
|
2023-07-05 01:14:44 +02:00
|
|
|
return Database.serverSettings.sortingIgnorePrefix ? se.nameIgnorePrefixSort : se.name
|
2022-10-29 18:17:51 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
])
|
|
|
|
|
2021-12-01 03:02:40 +01:00
|
|
|
payload.total = series.length
|
|
|
|
|
|
|
|
if (payload.limit) {
|
2022-12-31 23:58:19 +01:00
|
|
|
const startIndex = payload.page * payload.limit
|
2021-12-01 03:02:40 +01:00
|
|
|
series = series.slice(startIndex, startIndex + payload.limit)
|
|
|
|
}
|
|
|
|
|
2022-12-31 23:58:19 +01:00
|
|
|
// add rssFeed when "include=rssfeed" is in query string
|
|
|
|
if (include.includes('rssfeed')) {
|
2023-07-17 23:48:46 +02:00
|
|
|
series = await Promise.all(series.map(async (se) => {
|
|
|
|
const feedData = await this.rssFeedManager.findFeedForEntityId(se.id)
|
2022-12-31 23:58:19 +01:00
|
|
|
se.rssFeed = feedData?.toJSONMinified() || null
|
|
|
|
return se
|
2023-07-17 23:48:46 +02:00
|
|
|
}))
|
2022-12-31 23:58:19 +01:00
|
|
|
}
|
|
|
|
|
2022-01-08 00:26:12 +01:00
|
|
|
payload.results = series
|
2021-12-01 03:02:40 +01:00
|
|
|
res.json(payload)
|
|
|
|
}
|
|
|
|
|
2023-07-08 00:59:17 +02:00
|
|
|
/**
|
|
|
|
* api/libraries/:id/series/:seriesId
|
|
|
|
*
|
|
|
|
* Optional includes (e.g. `?include=rssfeed,progress`)
|
|
|
|
* rssfeed: adds `rssFeed` to series object if a feed is open
|
|
|
|
* progress: adds `progress` to series object with { libraryItemIds:Array<llid>, libraryItemIdsFinished:Array<llid>, isFinished:boolean }
|
|
|
|
*
|
|
|
|
* @param {*} req
|
|
|
|
* @param {*} res - Series
|
|
|
|
*/
|
|
|
|
async getSeriesForLibrary(req, res) {
|
|
|
|
const include = (req.query.include || '').split(',').map(v => v.trim().toLowerCase()).filter(v => !!v)
|
|
|
|
|
2023-07-08 15:25:33 +02:00
|
|
|
const series = Database.series.find(se => se.id === req.params.seriesId)
|
2023-07-08 00:59:17 +02:00
|
|
|
if (!series) return res.sendStatus(404)
|
|
|
|
|
|
|
|
const libraryItemsInSeries = req.libraryItems.filter(li => li.media.metadata.hasSeries?.(series.id))
|
|
|
|
|
|
|
|
const seriesJson = series.toJSON()
|
|
|
|
if (include.includes('progress')) {
|
|
|
|
const libraryItemsFinished = libraryItemsInSeries.filter(li => !!req.user.getMediaProgress(li.id)?.isFinished)
|
|
|
|
seriesJson.progress = {
|
|
|
|
libraryItemIds: libraryItemsInSeries.map(li => li.id),
|
|
|
|
libraryItemIdsFinished: libraryItemsFinished.map(li => li.id),
|
|
|
|
isFinished: libraryItemsFinished.length >= libraryItemsInSeries.length
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (include.includes('rssfeed')) {
|
2023-07-17 23:48:46 +02:00
|
|
|
const feedObj = await this.rssFeedManager.findFeedForEntityId(seriesJson.id)
|
2023-07-08 00:59:17 +02:00
|
|
|
seriesJson.rssFeed = feedObj?.toJSONMinified() || null
|
|
|
|
}
|
|
|
|
|
|
|
|
res.json(seriesJson)
|
|
|
|
}
|
|
|
|
|
2022-03-13 01:50:31 +01:00
|
|
|
// api/libraries/:id/collections
|
2021-12-01 03:02:40 +01:00
|
|
|
async getCollectionsForLibrary(req, res) {
|
2022-12-31 17:33:38 +01:00
|
|
|
const libraryItems = req.libraryItems
|
2021-12-01 03:02:40 +01:00
|
|
|
|
2022-12-31 17:33:38 +01:00
|
|
|
const include = (req.query.include || '').split(',').map(v => v.trim().toLowerCase()).filter(v => !!v)
|
|
|
|
|
|
|
|
const payload = {
|
2021-12-01 03:02:40 +01:00
|
|
|
results: [],
|
|
|
|
total: 0,
|
|
|
|
limit: req.query.limit && !isNaN(req.query.limit) ? Number(req.query.limit) : 0,
|
|
|
|
page: req.query.page && !isNaN(req.query.page) ? Number(req.query.page) : 0,
|
|
|
|
sortBy: req.query.sort,
|
|
|
|
sortDesc: req.query.desc === '1',
|
2021-12-24 23:37:57 +01:00
|
|
|
filterBy: req.query.filter,
|
2022-12-31 17:33:38 +01:00
|
|
|
minified: req.query.minified === '1',
|
|
|
|
include: include.join(',')
|
2021-12-01 03:02:40 +01:00
|
|
|
}
|
|
|
|
|
2023-07-22 23:18:55 +02:00
|
|
|
const collectionsForLibrary = await Database.models.collection.getAllForLibrary(req.library.id)
|
|
|
|
|
|
|
|
let collections = await Promise.all(collectionsForLibrary.map(async c => {
|
2022-12-31 17:33:38 +01:00
|
|
|
const expanded = c.toJSONExpanded(libraryItems, payload.minified)
|
|
|
|
|
2022-04-22 02:29:15 +02:00
|
|
|
// If all books restricted to user in this collection then hide this collection
|
|
|
|
if (!expanded.books.length && c.books.length) return null
|
2022-12-31 17:33:38 +01:00
|
|
|
|
|
|
|
if (include.includes('rssfeed')) {
|
2023-07-17 23:48:46 +02:00
|
|
|
const feedData = await this.rssFeedManager.findFeedForEntityId(c.id)
|
2022-12-31 23:58:19 +01:00
|
|
|
expanded.rssFeed = feedData?.toJSONMinified() || null
|
2022-12-31 17:33:38 +01:00
|
|
|
}
|
|
|
|
|
2022-04-22 02:29:15 +02:00
|
|
|
return expanded
|
2023-07-17 23:48:46 +02:00
|
|
|
}))
|
|
|
|
|
|
|
|
collections = collections.filter(c => !!c)
|
2022-04-22 02:29:15 +02:00
|
|
|
|
2021-12-01 03:02:40 +01:00
|
|
|
payload.total = collections.length
|
|
|
|
|
|
|
|
if (payload.limit) {
|
2022-12-31 17:33:38 +01:00
|
|
|
const startIndex = payload.page * payload.limit
|
2021-12-01 03:02:40 +01:00
|
|
|
collections = collections.slice(startIndex, startIndex + payload.limit)
|
|
|
|
}
|
|
|
|
|
|
|
|
payload.results = collections
|
|
|
|
res.json(payload)
|
|
|
|
}
|
|
|
|
|
2022-11-27 00:24:46 +01:00
|
|
|
// api/libraries/:id/playlists
|
|
|
|
async getUserPlaylistsForLibrary(req, res) {
|
2023-07-05 01:14:44 +02:00
|
|
|
let playlistsForUser = Database.playlists.filter(p => p.userId === req.user.id && p.libraryId === req.library.id).map(p => p.toJSONExpanded(Database.libraryItems))
|
2022-11-27 00:24:46 +01:00
|
|
|
|
|
|
|
const payload = {
|
|
|
|
results: [],
|
|
|
|
total: playlistsForUser.length,
|
|
|
|
limit: req.query.limit && !isNaN(req.query.limit) ? Number(req.query.limit) : 0,
|
|
|
|
page: req.query.page && !isNaN(req.query.page) ? Number(req.query.page) : 0
|
|
|
|
}
|
|
|
|
|
|
|
|
if (payload.limit) {
|
|
|
|
const startIndex = payload.page * payload.limit
|
|
|
|
playlistsForUser = playlistsForUser.slice(startIndex, startIndex + payload.limit)
|
|
|
|
}
|
|
|
|
|
|
|
|
payload.results = playlistsForUser
|
|
|
|
res.json(payload)
|
|
|
|
}
|
|
|
|
|
2023-01-03 01:02:04 +01:00
|
|
|
// api/libraries/:id/albums
|
|
|
|
async getAlbumsForLibrary(req, res) {
|
|
|
|
if (!req.library.isMusic) {
|
|
|
|
return res.status(400).send('Invalid library media type')
|
|
|
|
}
|
|
|
|
|
2023-07-05 01:14:44 +02:00
|
|
|
let libraryItems = Database.libraryItems.filter(li => li.libraryId === req.library.id)
|
2023-01-03 01:02:04 +01:00
|
|
|
let albums = libraryHelpers.groupMusicLibraryItemsIntoAlbums(libraryItems)
|
|
|
|
albums = naturalSort(albums).asc(a => a.title) // Alphabetical by album title
|
|
|
|
|
|
|
|
const payload = {
|
|
|
|
results: [],
|
|
|
|
total: albums.length,
|
|
|
|
limit: req.query.limit && !isNaN(req.query.limit) ? Number(req.query.limit) : 0,
|
|
|
|
page: req.query.page && !isNaN(req.query.page) ? Number(req.query.page) : 0
|
|
|
|
}
|
|
|
|
|
|
|
|
if (payload.limit) {
|
|
|
|
const startIndex = payload.page * payload.limit
|
|
|
|
albums = albums.slice(startIndex, startIndex + payload.limit)
|
|
|
|
}
|
|
|
|
|
|
|
|
payload.results = albums
|
|
|
|
res.json(payload)
|
|
|
|
}
|
|
|
|
|
2022-03-11 01:45:02 +01:00
|
|
|
async getLibraryFilterData(req, res) {
|
|
|
|
res.json(libraryHelpers.getDistinctFilterDataNew(req.libraryItems))
|
|
|
|
}
|
|
|
|
|
2022-03-14 01:34:31 +01:00
|
|
|
// api/libraries/:id/personalized
|
2022-04-24 23:56:30 +02:00
|
|
|
// New and improved personalized call only loops through library items once
|
|
|
|
async getLibraryUserPersonalizedOptimal(req, res) {
|
2022-12-31 21:31:38 +01:00
|
|
|
const limitPerShelf = req.query.limit && !isNaN(req.query.limit) ? Number(req.query.limit) || 10 : 10
|
|
|
|
const include = (req.query.include || '').split(',').map(v => v.trim().toLowerCase()).filter(v => !!v)
|
2022-04-24 23:56:30 +02:00
|
|
|
|
2023-07-17 23:48:46 +02:00
|
|
|
const categories = await libraryHelpers.buildPersonalizedShelves(this, req.user, req.libraryItems, req.library, limitPerShelf, include)
|
2022-12-13 00:29:56 +01:00
|
|
|
res.json(categories)
|
2022-04-24 23:56:30 +02:00
|
|
|
}
|
2021-12-01 03:02:40 +01:00
|
|
|
|
2023-07-22 21:25:20 +02:00
|
|
|
/**
|
|
|
|
* POST: /api/libraries/order
|
|
|
|
* Change the display order of libraries
|
|
|
|
* @param {*} req
|
|
|
|
* @param {*} res
|
|
|
|
*/
|
2021-11-22 03:00:40 +01:00
|
|
|
async reorder(req, res) {
|
2022-05-04 02:16:16 +02:00
|
|
|
if (!req.user.isAdminOrUp) {
|
2022-03-18 01:10:47 +01:00
|
|
|
Logger.error('[LibraryController] ReorderLibraries invalid user', req.user)
|
2022-02-15 23:36:22 +01:00
|
|
|
return res.sendStatus(403)
|
2021-11-22 03:00:40 +01:00
|
|
|
}
|
2023-07-22 21:25:20 +02:00
|
|
|
const libraries = await Database.models.library.getAllOldLibraries()
|
2021-11-22 03:00:40 +01:00
|
|
|
|
2023-07-22 21:25:20 +02:00
|
|
|
const orderdata = req.body
|
|
|
|
let hasUpdates = false
|
2021-11-22 03:00:40 +01:00
|
|
|
for (let i = 0; i < orderdata.length; i++) {
|
2023-07-22 21:25:20 +02:00
|
|
|
const library = libraries.find(lib => lib.id === orderdata[i].id)
|
2021-11-22 03:00:40 +01:00
|
|
|
if (!library) {
|
2022-03-18 01:10:47 +01:00
|
|
|
Logger.error(`[LibraryController] Invalid library not found in reorder ${orderdata[i].id}`)
|
2021-11-22 03:00:40 +01:00
|
|
|
return res.sendStatus(500)
|
|
|
|
}
|
|
|
|
if (library.update({ displayOrder: orderdata[i].newOrder })) {
|
|
|
|
hasUpdates = true
|
2023-07-05 01:14:44 +02:00
|
|
|
await Database.updateLibrary(library)
|
2021-11-22 03:00:40 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (hasUpdates) {
|
2023-07-22 21:25:20 +02:00
|
|
|
libraries.sort((a, b) => a.displayOrder - b.displayOrder)
|
2022-03-27 16:45:28 +02:00
|
|
|
Logger.debug(`[LibraryController] Updated library display orders`)
|
2021-11-22 03:00:40 +01:00
|
|
|
} else {
|
2022-03-27 16:45:28 +02:00
|
|
|
Logger.debug(`[LibraryController] Library orders were up to date`)
|
2021-11-22 03:00:40 +01:00
|
|
|
}
|
|
|
|
|
2022-11-29 18:30:25 +01:00
|
|
|
res.json({
|
2023-07-22 21:25:20 +02:00
|
|
|
libraries: libraries.map(lib => lib.toJSON())
|
2022-11-29 18:30:25 +01:00
|
|
|
})
|
2021-11-22 03:00:40 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// GET: Global library search
|
|
|
|
search(req, res) {
|
|
|
|
if (!req.query.q) {
|
|
|
|
return res.status(400).send('No query string')
|
|
|
|
}
|
2023-01-05 00:43:15 +01:00
|
|
|
const libraryItems = req.libraryItems
|
|
|
|
const maxResults = req.query.limit && !isNaN(req.query.limit) ? Number(req.query.limit) : 12
|
2021-11-22 03:00:40 +01:00
|
|
|
|
2023-01-05 00:43:15 +01:00
|
|
|
const itemMatches = []
|
|
|
|
const authorMatches = {}
|
2023-04-25 01:25:30 +02:00
|
|
|
const narratorMatches = {}
|
2023-01-05 00:43:15 +01:00
|
|
|
const seriesMatches = {}
|
|
|
|
const tagMatches = {}
|
2021-11-22 03:00:40 +01:00
|
|
|
|
2022-03-13 18:39:12 +01:00
|
|
|
libraryItems.forEach((li) => {
|
2023-01-05 00:43:15 +01:00
|
|
|
const queryResult = li.searchQuery(req.query.q)
|
2022-03-13 18:39:12 +01:00
|
|
|
if (queryResult.matchKey) {
|
|
|
|
itemMatches.push({
|
2022-04-12 23:54:52 +02:00
|
|
|
libraryItem: li.toJSONExpanded(),
|
2022-03-13 18:39:12 +01:00
|
|
|
matchKey: queryResult.matchKey,
|
|
|
|
matchText: queryResult.matchText
|
|
|
|
})
|
2021-11-22 03:00:40 +01:00
|
|
|
}
|
2023-04-25 01:25:30 +02:00
|
|
|
if (queryResult.series?.length) {
|
2022-03-13 18:39:12 +01:00
|
|
|
queryResult.series.forEach((se) => {
|
|
|
|
if (!seriesMatches[se.id]) {
|
2023-07-05 01:14:44 +02:00
|
|
|
const _series = Database.series.find(_se => _se.id === se.id)
|
2022-03-13 18:39:12 +01:00
|
|
|
if (_series) seriesMatches[se.id] = { series: _series.toJSON(), books: [li.toJSON()] }
|
2021-12-03 02:02:38 +01:00
|
|
|
} else {
|
2022-03-13 18:39:12 +01:00
|
|
|
seriesMatches[se.id].books.push(li.toJSON())
|
2021-11-22 03:00:40 +01:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2023-04-25 01:25:30 +02:00
|
|
|
if (queryResult.authors?.length) {
|
2022-03-13 18:39:12 +01:00
|
|
|
queryResult.authors.forEach((au) => {
|
|
|
|
if (!authorMatches[au.id]) {
|
2023-07-05 01:14:44 +02:00
|
|
|
const _author = Database.authors.find(_au => _au.id === au.id)
|
2022-03-13 18:39:12 +01:00
|
|
|
if (_author) {
|
|
|
|
authorMatches[au.id] = _author.toJSON()
|
|
|
|
authorMatches[au.id].numBooks = 1
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
authorMatches[au.id].numBooks++
|
2021-11-22 03:00:40 +01:00
|
|
|
}
|
2022-03-13 18:39:12 +01:00
|
|
|
})
|
2021-11-22 03:00:40 +01:00
|
|
|
}
|
2023-04-25 01:25:30 +02:00
|
|
|
if (queryResult.tags?.length) {
|
2021-11-22 03:00:40 +01:00
|
|
|
queryResult.tags.forEach((tag) => {
|
|
|
|
if (!tagMatches[tag]) {
|
2022-03-13 18:39:12 +01:00
|
|
|
tagMatches[tag] = { name: tag, books: [li.toJSON()] }
|
2021-11-22 03:00:40 +01:00
|
|
|
} else {
|
2022-03-13 18:39:12 +01:00
|
|
|
tagMatches[tag].books.push(li.toJSON())
|
2021-11-22 03:00:40 +01:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2023-04-25 01:25:30 +02:00
|
|
|
if (queryResult.narrators?.length) {
|
|
|
|
queryResult.narrators.forEach((narrator) => {
|
|
|
|
if (!narratorMatches[narrator]) {
|
|
|
|
narratorMatches[narrator] = { name: narrator, books: [li.toJSON()] }
|
|
|
|
} else {
|
|
|
|
narratorMatches[narrator].books.push(li.toJSON())
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2021-11-22 03:00:40 +01:00
|
|
|
})
|
2023-01-05 00:43:15 +01:00
|
|
|
const itemKey = req.library.mediaType
|
|
|
|
const results = {
|
2022-03-13 18:39:12 +01:00
|
|
|
[itemKey]: itemMatches.slice(0, maxResults),
|
2021-11-22 03:00:40 +01:00
|
|
|
tags: Object.values(tagMatches).slice(0, maxResults),
|
|
|
|
authors: Object.values(authorMatches).slice(0, maxResults),
|
2023-04-25 01:25:30 +02:00
|
|
|
series: Object.values(seriesMatches).slice(0, maxResults),
|
|
|
|
narrators: Object.values(narratorMatches).slice(0, maxResults)
|
2021-12-02 02:07:03 +01:00
|
|
|
}
|
|
|
|
res.json(results)
|
|
|
|
}
|
|
|
|
|
|
|
|
async stats(req, res) {
|
2022-03-13 23:33:50 +01:00
|
|
|
var libraryItems = req.libraryItems
|
|
|
|
var authorsWithCount = libraryHelpers.getAuthorsWithCount(libraryItems)
|
|
|
|
var genresWithCount = libraryHelpers.getGenresWithCount(libraryItems)
|
|
|
|
var durationStats = libraryHelpers.getItemDurationStats(libraryItems)
|
2023-02-19 22:39:28 +01:00
|
|
|
var sizeStats = libraryHelpers.getItemSizeStats(libraryItems)
|
2021-12-02 02:07:03 +01:00
|
|
|
var stats = {
|
2022-03-13 23:33:50 +01:00
|
|
|
totalItems: libraryItems.length,
|
2021-12-02 02:07:03 +01:00
|
|
|
totalAuthors: Object.keys(authorsWithCount).length,
|
|
|
|
totalGenres: Object.keys(genresWithCount).length,
|
2022-03-13 23:33:50 +01:00
|
|
|
totalDuration: durationStats.totalDuration,
|
|
|
|
longestItems: durationStats.longestItems,
|
|
|
|
numAudioTracks: durationStats.numAudioTracks,
|
|
|
|
totalSize: libraryHelpers.getLibraryItemsTotalSize(libraryItems),
|
2023-02-19 22:39:28 +01:00
|
|
|
largestItems: sizeStats.largestItems,
|
2021-12-02 02:07:03 +01:00
|
|
|
authorsWithCount,
|
|
|
|
genresWithCount
|
|
|
|
}
|
|
|
|
res.json(stats)
|
2021-11-22 03:00:40 +01:00
|
|
|
}
|
2021-12-01 03:02:40 +01:00
|
|
|
|
2021-12-03 02:02:38 +01:00
|
|
|
async getAuthors(req, res) {
|
2023-04-30 21:11:54 +02:00
|
|
|
const authors = {}
|
|
|
|
req.libraryItems.forEach((li) => {
|
2022-03-13 01:50:31 +01:00
|
|
|
if (li.media.metadata.authors && li.media.metadata.authors.length) {
|
|
|
|
li.media.metadata.authors.forEach((au) => {
|
|
|
|
if (!authors[au.id]) {
|
2023-07-05 01:14:44 +02:00
|
|
|
const _author = Database.authors.find(_au => _au.id === au.id)
|
2022-03-13 01:50:31 +01:00
|
|
|
if (_author) {
|
|
|
|
authors[au.id] = _author.toJSON()
|
|
|
|
authors[au.id].numBooks = 1
|
2021-12-03 02:02:38 +01:00
|
|
|
}
|
|
|
|
} else {
|
2022-03-13 01:50:31 +01:00
|
|
|
authors[au.id].numBooks++
|
2021-12-03 02:02:38 +01:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
})
|
2022-04-25 00:15:41 +02:00
|
|
|
|
2022-11-29 18:30:25 +01:00
|
|
|
res.json({
|
|
|
|
authors: naturalSort(Object.values(authors)).asc(au => au.name)
|
|
|
|
})
|
2021-12-03 02:02:38 +01:00
|
|
|
}
|
|
|
|
|
2023-04-30 21:11:54 +02:00
|
|
|
async getNarrators(req, res) {
|
|
|
|
const narrators = {}
|
|
|
|
req.libraryItems.forEach((li) => {
|
2023-05-13 01:22:09 +02:00
|
|
|
if (li.media.metadata.narrators?.length) {
|
2023-04-30 21:11:54 +02:00
|
|
|
li.media.metadata.narrators.forEach((n) => {
|
2023-05-13 01:22:09 +02:00
|
|
|
if (typeof n !== 'string') {
|
|
|
|
Logger.error(`[LibraryController] getNarrators: Invalid narrator "${n}" on book "${li.media.metadata.title}"`)
|
|
|
|
} else if (!narrators[n]) {
|
2023-04-30 21:11:54 +02:00
|
|
|
narrators[n] = {
|
|
|
|
id: encodeURIComponent(Buffer.from(n).toString('base64')),
|
|
|
|
name: n,
|
|
|
|
numBooks: 1
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
narrators[n].numBooks++
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
res.json({
|
|
|
|
narrators: naturalSort(Object.values(narrators)).asc(n => n.name)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
async updateNarrator(req, res) {
|
|
|
|
if (!req.user.canUpdate) {
|
|
|
|
Logger.error(`[LibraryController] Unauthorized user "${req.user.username}" attempted to update narrator`)
|
|
|
|
return res.sendStatus(403)
|
|
|
|
}
|
|
|
|
|
|
|
|
const narratorName = libraryHelpers.decode(req.params.narratorId)
|
|
|
|
const updatedName = req.body.name
|
|
|
|
if (!updatedName) {
|
|
|
|
return res.status(400).send('Invalid request payload. Name not specified.')
|
|
|
|
}
|
|
|
|
|
|
|
|
const itemsUpdated = []
|
|
|
|
for (const libraryItem of req.libraryItems) {
|
|
|
|
if (libraryItem.media.metadata.updateNarrator(narratorName, updatedName)) {
|
|
|
|
itemsUpdated.push(libraryItem)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (itemsUpdated.length) {
|
2023-07-05 01:14:44 +02:00
|
|
|
await Database.updateBulkBooks(itemsUpdated.map(i => i.media))
|
2023-04-30 21:11:54 +02:00
|
|
|
SocketAuthority.emitter('items_updated', itemsUpdated.map(li => li.toJSONExpanded()))
|
|
|
|
}
|
|
|
|
|
|
|
|
res.json({
|
|
|
|
updated: itemsUpdated.length
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
async removeNarrator(req, res) {
|
|
|
|
if (!req.user.canUpdate) {
|
|
|
|
Logger.error(`[LibraryController] Unauthorized user "${req.user.username}" attempted to remove narrator`)
|
|
|
|
return res.sendStatus(403)
|
|
|
|
}
|
|
|
|
|
|
|
|
const narratorName = libraryHelpers.decode(req.params.narratorId)
|
|
|
|
|
|
|
|
const itemsUpdated = []
|
|
|
|
for (const libraryItem of req.libraryItems) {
|
|
|
|
if (libraryItem.media.metadata.removeNarrator(narratorName)) {
|
|
|
|
itemsUpdated.push(libraryItem)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (itemsUpdated.length) {
|
2023-07-05 01:14:44 +02:00
|
|
|
await Database.updateBulkBooks(itemsUpdated.map(i => i.media))
|
2023-04-30 21:11:54 +02:00
|
|
|
SocketAuthority.emitter('items_updated', itemsUpdated.map(li => li.toJSONExpanded()))
|
|
|
|
}
|
|
|
|
|
|
|
|
res.json({
|
|
|
|
updated: itemsUpdated.length
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-04-21 01:05:09 +02:00
|
|
|
async matchAll(req, res) {
|
2022-05-04 02:16:16 +02:00
|
|
|
if (!req.user.isAdminOrUp) {
|
2022-04-21 01:05:09 +02:00
|
|
|
Logger.error(`[LibraryController] Non-root user attempted to match library items`, req.user)
|
2022-02-15 23:36:22 +01:00
|
|
|
return res.sendStatus(403)
|
|
|
|
}
|
2022-04-21 01:05:09 +02:00
|
|
|
this.scanner.matchLibraryItems(req.library)
|
2022-02-15 23:36:22 +01:00
|
|
|
res.sendStatus(200)
|
|
|
|
}
|
|
|
|
|
2023-02-04 00:50:42 +01:00
|
|
|
// POST: api/libraries/:id/scan
|
2022-03-18 17:51:55 +01:00
|
|
|
async scan(req, res) {
|
2022-05-04 02:16:16 +02:00
|
|
|
if (!req.user.isAdminOrUp) {
|
2022-03-18 17:51:55 +01:00
|
|
|
Logger.error(`[LibraryController] Non-root user attempted to scan library`, req.user)
|
|
|
|
return res.sendStatus(403)
|
|
|
|
}
|
2023-02-04 00:50:42 +01:00
|
|
|
const options = {
|
2022-03-18 17:51:55 +01:00
|
|
|
forceRescan: req.query.force == 1
|
|
|
|
}
|
|
|
|
res.sendStatus(200)
|
|
|
|
await this.scanner.scan(req.library, options)
|
|
|
|
Logger.info('[LibraryController] Scan complete')
|
|
|
|
}
|
|
|
|
|
2022-09-16 23:59:16 +02:00
|
|
|
// GET: api/libraries/:id/recent-episode
|
|
|
|
async getRecentEpisodes(req, res) {
|
|
|
|
if (!req.library.isPodcast) {
|
|
|
|
return res.sendStatus(404)
|
|
|
|
}
|
|
|
|
|
|
|
|
const payload = {
|
|
|
|
episodes: [],
|
|
|
|
total: 0,
|
|
|
|
limit: req.query.limit && !isNaN(req.query.limit) ? Number(req.query.limit) : 0,
|
|
|
|
page: req.query.page && !isNaN(req.query.page) ? Number(req.query.page) : 0,
|
|
|
|
}
|
|
|
|
|
|
|
|
var allUnfinishedEpisodes = []
|
|
|
|
for (const libraryItem of req.libraryItems) {
|
|
|
|
const unfinishedEpisodes = libraryItem.media.episodes.filter(ep => {
|
|
|
|
const userProgress = req.user.getMediaProgress(libraryItem.id, ep.id)
|
|
|
|
return !userProgress || !userProgress.isFinished
|
2022-09-17 22:23:33 +02:00
|
|
|
}).map(_ep => {
|
|
|
|
const ep = _ep.toJSONExpanded()
|
|
|
|
ep.podcast = libraryItem.media.toJSONMinified()
|
|
|
|
ep.libraryItemId = libraryItem.id
|
2022-11-12 22:41:41 +01:00
|
|
|
ep.libraryId = libraryItem.libraryId
|
2022-09-17 22:23:33 +02:00
|
|
|
return ep
|
2022-09-16 23:59:16 +02:00
|
|
|
})
|
|
|
|
allUnfinishedEpisodes.push(...unfinishedEpisodes)
|
|
|
|
}
|
|
|
|
|
|
|
|
payload.total = allUnfinishedEpisodes.length
|
|
|
|
|
|
|
|
allUnfinishedEpisodes = sort(allUnfinishedEpisodes).desc(ep => ep.publishedAt)
|
|
|
|
|
|
|
|
if (payload.limit) {
|
|
|
|
var startIndex = payload.page * payload.limit
|
|
|
|
allUnfinishedEpisodes = allUnfinishedEpisodes.slice(startIndex, startIndex + payload.limit)
|
|
|
|
}
|
|
|
|
payload.episodes = allUnfinishedEpisodes
|
|
|
|
res.json(payload)
|
|
|
|
}
|
|
|
|
|
2023-05-28 22:10:34 +02:00
|
|
|
getOPMLFile(req, res) {
|
|
|
|
const opmlText = this.podcastManager.generateOPMLFileText(req.libraryItems)
|
|
|
|
res.type('application/xml')
|
|
|
|
res.send(opmlText)
|
|
|
|
}
|
|
|
|
|
2023-07-22 21:25:20 +02:00
|
|
|
async middleware(req, res, next) {
|
2022-05-28 23:53:03 +02:00
|
|
|
if (!req.user.checkCanAccessLibrary(req.params.id)) {
|
2022-01-16 21:10:46 +01:00
|
|
|
Logger.warn(`[LibraryController] Library ${req.params.id} not accessible to user ${req.user.username}`)
|
2023-07-08 00:59:17 +02:00
|
|
|
return res.sendStatus(403)
|
2022-01-16 21:10:46 +01:00
|
|
|
}
|
|
|
|
|
2023-07-22 21:25:20 +02:00
|
|
|
const library = await Database.models.library.getOldById(req.params.id)
|
2021-12-01 03:02:40 +01:00
|
|
|
if (!library) {
|
|
|
|
return res.status(404).send('Library not found')
|
|
|
|
}
|
|
|
|
req.library = library
|
2023-07-05 01:14:44 +02:00
|
|
|
req.libraryItems = Database.libraryItems.filter(li => {
|
2022-05-28 23:53:03 +02:00
|
|
|
return li.libraryId === library.id && req.user.checkCanAccessLibraryItem(li)
|
2022-03-20 12:29:08 +01:00
|
|
|
})
|
2021-12-01 03:02:40 +01:00
|
|
|
next()
|
|
|
|
}
|
2021-11-22 03:00:40 +01:00
|
|
|
}
|
2023-02-19 22:39:28 +01:00
|
|
|
module.exports = new LibraryController()
|