mirror of
https://github.com/advplyr/audiobookshelf.git
synced 2025-12-31 11:38:47 -05:00
Compare commits
36 Commits
plugin-imp
...
refactor-l
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e8678f1cc | ||
|
|
12c6f2e9a5 | ||
|
|
5cd14108f9 | ||
|
|
eb853d9f09 | ||
|
|
4787e7fdb5 | ||
|
|
dd0ebdf2d8 | ||
|
|
de8b0abc3a | ||
|
|
08bbe1ba02 | ||
|
|
87bac1e33b | ||
|
|
e9eeab6fb5 | ||
|
|
235d05eff3 | ||
|
|
f9f8c6d751 | ||
|
|
e175a9c533 | ||
|
|
f9130a138e | ||
|
|
ed17dd9b51 | ||
|
|
eb505a0be7 | ||
|
|
f3918a47e1 | ||
|
|
c8a05920dd | ||
|
|
e7f7d1a573 | ||
|
|
5201625d38 | ||
|
|
8c4d0c503b | ||
|
|
d3bda898d4 | ||
|
|
86809dcc62 | ||
|
|
9fa00a1904 | ||
|
|
46247ecf78 | ||
|
|
0444829a9f | ||
|
|
754c121168 | ||
|
|
1c2ee09f18 | ||
|
|
ee310d967e | ||
|
|
25b7f005c6 | ||
|
|
777c59458d | ||
|
|
9785bc02ea | ||
|
|
6780ef9b37 | ||
|
|
88a0e75576 | ||
|
|
476933a144 | ||
|
|
d7830f4bfc |
@@ -374,19 +374,27 @@ export default {
|
||||
return
|
||||
}
|
||||
|
||||
// https://developer.mozilla.org/en-US/docs/Web/API/Media_Session_API
|
||||
if ('mediaSession' in navigator) {
|
||||
var coverImageSrc = this.$store.getters['globals/getLibraryItemCoverSrc'](this.streamLibraryItem, '/Logo.png', true)
|
||||
const artwork = [
|
||||
{
|
||||
src: coverImageSrc
|
||||
}
|
||||
]
|
||||
const chapterInfo = []
|
||||
if (this.chapters.length) {
|
||||
this.chapters.forEach((chapter) => {
|
||||
chapterInfo.push({
|
||||
title: chapter.title,
|
||||
startTime: chapter.start
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
navigator.mediaSession.metadata = new MediaMetadata({
|
||||
title: this.title,
|
||||
artist: this.playerHandler.displayAuthor || this.mediaMetadata.authorName || 'Unknown',
|
||||
album: this.mediaMetadata.seriesName || '',
|
||||
artwork
|
||||
artwork: [
|
||||
{
|
||||
src: this.$store.getters['globals/getLibraryItemCoverSrc'](this.streamLibraryItem, '/Logo.png', true)
|
||||
}
|
||||
]
|
||||
})
|
||||
console.log('Set media session metadata', navigator.mediaSession.metadata)
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<article class="pb-3e" :style="{ minWidth: cardWidth + 'px', maxWidth: cardWidth + 'px' }">
|
||||
<div class="pb-3e" :style="{ minWidth: cardWidth + 'px', maxWidth: cardWidth + 'px' }">
|
||||
<nuxt-link :to="`/author/${author?.id}`">
|
||||
<div cy-id="card" @mouseover="mouseover" @mouseleave="mouseleave">
|
||||
<div cy-id="imageArea" :style="{ height: cardHeight + 'px' }" class="bg-primary box-shadow-book rounded-md relative overflow-hidden">
|
||||
@@ -34,7 +34,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</nuxt-link>
|
||||
</article>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<article ref="card" :id="`book-card-${index}`" tabindex="0" :aria-label="displayTitle" :style="{ minWidth: coverWidth + 'px', maxWidth: coverWidth + 'px' }" class="absolute rounded-sm z-10 cursor-pointer" @mousedown.prevent @mouseup.prevent @mousemove.prevent @mouseover="mouseover" @mouseleave="mouseleave" @click="clickCard">
|
||||
<div ref="card" :id="`book-card-${index}`" tabindex="0" :style="{ minWidth: coverWidth + 'px', maxWidth: coverWidth + 'px' }" class="absolute rounded-sm z-10 cursor-pointer" @mousedown.prevent @mouseup.prevent @mousemove.prevent @mouseover="mouseover" @mouseleave="mouseleave" @click="clickCard">
|
||||
<div :id="`cover-area-${index}`" class="relative w-full top-0 left-0 rounded overflow-hidden z-10 bg-primary box-shadow-book" :style="{ height: coverHeight + 'px ' }">
|
||||
<!-- When cover image does not fill -->
|
||||
<div cy-id="coverBg" v-show="showCoverBg" class="absolute top-0 left-0 w-full h-full overflow-hidden rounded-sm bg-primary">
|
||||
@@ -128,7 +128,7 @@
|
||||
<div cy-id="detailBottom" :id="`description-area-${index}`" v-if="isAlternativeBookshelfView || isAuthorBookshelfView" dir="auto" class="relative mt-2e mb-2e left-0 z-50 w-full">
|
||||
<div :style="{ fontSize: 0.9 + 'em' }">
|
||||
<ui-tooltip v-if="displayTitle" :text="displayTitle" :disabled="!displayTitleTruncated" direction="bottom" :delayOnShow="500" class="flex items-center">
|
||||
<p cy-id="title" ref="displayTitle" aria-hidden="true" class="truncate">{{ displayTitle }}</p>
|
||||
<p cy-id="title" ref="displayTitle" class="truncate">{{ displayTitle }}</p>
|
||||
<widgets-explicit-indicator cy-id="explicitIndicator" v-if="isExplicit" />
|
||||
</ui-tooltip>
|
||||
</div>
|
||||
@@ -138,7 +138,7 @@
|
||||
<p cy-id="line2" class="truncate text-gray-400" :style="{ fontSize: 0.8 + 'em' }">{{ displayLineTwo || ' ' }}</p>
|
||||
<p cy-id="line3" v-if="displaySortLine" class="truncate text-gray-400" :style="{ fontSize: 0.8 + 'em' }">{{ displaySortLine }}</p>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<article cy-id="card" ref="card" :id="`series-card-${index}`" tabindex="0" :aria-label="displayTitle" :style="{ width: cardWidth + 'px' }" class="absolute rounded-sm z-30 cursor-pointer" @mousedown.prevent @mouseup.prevent @mousemove.prevent @mouseover="mouseover" @mouseleave="mouseleave" @click="clickCard">
|
||||
<div cy-id="card" ref="card" :id="`series-card-${index}`" tabindex="0" :style="{ width: cardWidth + 'px' }" class="absolute rounded-sm z-30 cursor-pointer" @mousedown.prevent @mouseup.prevent @mousemove.prevent @mouseover="mouseover" @mouseleave="mouseleave" @click="clickCard">
|
||||
<div cy-id="covers-area" class="relative" :style="{ height: coverHeight + 'px' }">
|
||||
<div class="absolute top-0 left-0 w-full box-shadow-book shadow-height" />
|
||||
<div class="w-full h-full bg-primary relative rounded overflow-hidden z-0">
|
||||
@@ -21,14 +21,14 @@
|
||||
|
||||
<div cy-id="standardBottomText" v-if="!isAlternativeBookshelfView" class="categoryPlacard absolute z-10 left-0 right-0 mx-auto -bottom-6e h-6e rounded-md text-center" :style="{ width: Math.min(200, cardWidth) + 'px' }">
|
||||
<div class="w-full h-full shinyBlack flex items-center justify-center rounded-sm border" :style="{ padding: `0em 0.5em` }">
|
||||
<p cy-id="standardBottomDisplayTitle" class="truncate" aria-hidden="true" :style="{ fontSize: labelFontSize + 'em' }">{{ displayTitle }}</p>
|
||||
<p cy-id="standardBottomDisplayTitle" class="truncate" :style="{ fontSize: labelFontSize + 'em' }">{{ displayTitle }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div cy-id="detailBottomText" v-else class="relative z-30 left-0 right-0 mx-auto py-1e rounded-md text-center">
|
||||
<p cy-id="detailBottomDisplayTitle" class="truncate" aria-hidden="true" :style="{ fontSize: labelFontSize + 'em' }">{{ displayTitle }}</p>
|
||||
<p cy-id="detailBottomDisplayTitle" class="truncate" :style="{ fontSize: labelFontSize + 'em' }">{{ displayTitle }}</p>
|
||||
<p cy-id="detailBottomSortLine" v-if="displaySortLine" class="truncate text-gray-400" :style="{ fontSize: 0.8 + 'em' }">{{ displaySortLine }}</p>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
|
||||
@@ -138,7 +138,6 @@ export default {
|
||||
.$post(`/api/collections/${collection.id}/batch/remove`, { books: this.selectedBookIds })
|
||||
.then((updatedCollection) => {
|
||||
console.log(`Books removed from collection`, updatedCollection)
|
||||
this.$toast.success(this.$strings.ToastCollectionItemsRemoveSuccess)
|
||||
this.processing = false
|
||||
})
|
||||
.catch((error) => {
|
||||
@@ -152,7 +151,6 @@ export default {
|
||||
.$delete(`/api/collections/${collection.id}/book/${this.selectedLibraryItemId}`)
|
||||
.then((updatedCollection) => {
|
||||
console.log(`Book removed from collection`, updatedCollection)
|
||||
this.$toast.success(this.$strings.ToastCollectionItemsRemoveSuccess)
|
||||
this.processing = false
|
||||
})
|
||||
.catch((error) => {
|
||||
@@ -167,12 +165,11 @@ export default {
|
||||
this.processing = true
|
||||
|
||||
if (this.showBatchCollectionModal) {
|
||||
// BATCH Remove books
|
||||
// BATCH Add books
|
||||
this.$axios
|
||||
.$post(`/api/collections/${collection.id}/batch/add`, { books: this.selectedBookIds })
|
||||
.then((updatedCollection) => {
|
||||
console.log(`Books added to collection`, updatedCollection)
|
||||
this.$toast.success(this.$strings.ToastCollectionItemsAddSuccess)
|
||||
this.processing = false
|
||||
})
|
||||
.catch((error) => {
|
||||
@@ -187,7 +184,6 @@ export default {
|
||||
.$post(`/api/collections/${collection.id}/book`, { id: this.selectedLibraryItemId })
|
||||
.then((updatedCollection) => {
|
||||
console.log(`Book added to collection`, updatedCollection)
|
||||
this.$toast.success(this.$strings.ToastCollectionItemsAddSuccess)
|
||||
this.processing = false
|
||||
})
|
||||
.catch((error) => {
|
||||
@@ -214,7 +210,6 @@ export default {
|
||||
.$post('/api/collections', newCollection)
|
||||
.then((data) => {
|
||||
console.log('New Collection Created', data)
|
||||
this.$toast.success(`Collection "${data.name}" created`)
|
||||
this.processing = false
|
||||
this.newCollectionName = ''
|
||||
})
|
||||
|
||||
@@ -130,7 +130,6 @@ export default {
|
||||
.$post(`/api/playlists/${playlist.id}/batch/remove`, { items: itemObjects })
|
||||
.then((updatedPlaylist) => {
|
||||
console.log(`Items removed from playlist`, updatedPlaylist)
|
||||
this.$toast.success(this.$strings.ToastPlaylistUpdateSuccess)
|
||||
this.processing = false
|
||||
})
|
||||
.catch((error) => {
|
||||
@@ -148,7 +147,6 @@ export default {
|
||||
.$post(`/api/playlists/${playlist.id}/batch/add`, { items: itemObjects })
|
||||
.then((updatedPlaylist) => {
|
||||
console.log(`Items added to playlist`, updatedPlaylist)
|
||||
this.$toast.success(this.$strings.ToastPlaylistUpdateSuccess)
|
||||
this.processing = false
|
||||
})
|
||||
.catch((error) => {
|
||||
@@ -174,7 +172,6 @@ export default {
|
||||
.$post('/api/playlists', newPlaylist)
|
||||
.then((data) => {
|
||||
console.log('New playlist created', data)
|
||||
this.$toast.success(this.$strings.ToastPlaylistCreateSuccess + ': ' + data.name)
|
||||
this.processing = false
|
||||
this.newPlaylistName = ''
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<div id="heatmap" class="w-full">
|
||||
<div class="mx-auto" :style="{ height: innerHeight + 160 + 'px', width: innerWidth + 52 + 'px' }" style="background-color: rgba(13, 17, 23, 0)">
|
||||
<p class="mb-2 px-1 text-sm text-gray-200">{{ $getString('MessageListeningSessionsInTheLastYear', [Object.values(daysListening).length]) }}</p>
|
||||
<p class="mb-2 px-1 text-sm text-gray-200">{{ $getString('MessageDaysListenedInTheLastYear', [daysListenedInTheLastYear]) }}</p>
|
||||
<div class="border border-white border-opacity-25 rounded py-2 w-full" style="background-color: #232323" :style="{ height: innerHeight + 80 + 'px' }">
|
||||
<div :style="{ width: innerWidth + 'px', height: innerHeight + 'px' }" class="ml-10 mt-5 absolute" @mouseover="mouseover" @mouseout="mouseout">
|
||||
<div v-for="dayLabel in dayLabels" :key="dayLabel.label" :style="dayLabel.style" class="absolute top-0 left-0 text-gray-300">{{ dayLabel.label }}</div>
|
||||
@@ -37,6 +37,7 @@ export default {
|
||||
innerHeight: 13 * 7,
|
||||
blockWidth: 13,
|
||||
data: [],
|
||||
daysListenedInTheLastYear: 0,
|
||||
monthLabels: [],
|
||||
tooltipEl: null,
|
||||
tooltipTextEl: null,
|
||||
@@ -193,46 +194,47 @@ export default {
|
||||
buildData() {
|
||||
this.data = []
|
||||
|
||||
var maxValue = 0
|
||||
var minValue = 0
|
||||
Object.values(this.daysListening).forEach((val) => {
|
||||
if (val > maxValue) maxValue = val
|
||||
if (!minValue || val < minValue) minValue = val
|
||||
})
|
||||
const range = maxValue - minValue + 0.01
|
||||
let maxValue = 0
|
||||
let minValue = 0
|
||||
|
||||
const dates = []
|
||||
for (let i = 0; i < this.daysToShow + 1; i++) {
|
||||
const col = Math.floor(i / 7)
|
||||
const row = i % 7
|
||||
|
||||
const date = i === 0 ? this.firstWeekStart : this.$addDaysToDate(this.firstWeekStart, i)
|
||||
const dateString = this.$formatJsDate(date, 'yyyy-MM-dd')
|
||||
const datePretty = this.$formatJsDate(date, 'MMM d, yyyy')
|
||||
const monthString = this.$formatJsDate(date, 'MMM')
|
||||
const value = this.daysListening[dateString] || 0
|
||||
const x = col * 13
|
||||
const y = row * 13
|
||||
const dateObj = {
|
||||
col: Math.floor(i / 7),
|
||||
row: i % 7,
|
||||
date,
|
||||
dateString,
|
||||
datePretty: this.$formatJsDate(date, 'MMM d, yyyy'),
|
||||
monthString: this.$formatJsDate(date, 'MMM'),
|
||||
dayOfMonth: Number(dateString.split('-').pop()),
|
||||
yearString: dateString.split('-').shift(),
|
||||
value: this.daysListening[dateString] || 0
|
||||
}
|
||||
dates.push(dateObj)
|
||||
|
||||
var bgColor = this.bgColors[0]
|
||||
var outlineColor = this.outlineColors[0]
|
||||
if (value) {
|
||||
if (dateObj.value > 0) {
|
||||
this.daysListenedInTheLastYear++
|
||||
if (dateObj.value > maxValue) maxValue = dateObj.value
|
||||
if (!minValue || dateObj.value < minValue) minValue = dateObj.value
|
||||
}
|
||||
}
|
||||
const range = maxValue - minValue + 0.01
|
||||
|
||||
for (const dateObj of dates) {
|
||||
let bgColor = this.bgColors[0]
|
||||
let outlineColor = this.outlineColors[0]
|
||||
if (dateObj.value) {
|
||||
outlineColor = this.outlineColors[1]
|
||||
var percentOfAvg = (value - minValue) / range
|
||||
var bgIndex = Math.floor(percentOfAvg * 4) + 1
|
||||
const percentOfAvg = (dateObj.value - minValue) / range
|
||||
const bgIndex = Math.floor(percentOfAvg * 4) + 1
|
||||
bgColor = this.bgColors[bgIndex] || 'red'
|
||||
}
|
||||
|
||||
this.data.push({
|
||||
date,
|
||||
dateString,
|
||||
datePretty,
|
||||
monthString,
|
||||
dayOfMonth: Number(dateString.split('-').pop()),
|
||||
yearString: dateString.split('-').shift(),
|
||||
value,
|
||||
col,
|
||||
row,
|
||||
style: `transform:translate(${x}px,${y}px);background-color:${bgColor};outline:1px solid ${outlineColor};outline-offset:-1px;`
|
||||
...dateObj,
|
||||
style: `transform:translate(${dateObj.col * 13}px,${dateObj.row * 13}px);background-color:${bgColor};outline:1px solid ${outlineColor};outline-offset:-1px;`
|
||||
})
|
||||
}
|
||||
|
||||
@@ -260,6 +262,7 @@ export default {
|
||||
const heatmapEl = document.getElementById('heatmap')
|
||||
this.contentWidth = heatmapEl.clientWidth
|
||||
this.maxInnerWidth = this.contentWidth - 52
|
||||
this.daysListenedInTheLastYear = 0
|
||||
this.buildData()
|
||||
}
|
||||
},
|
||||
|
||||
@@ -218,7 +218,6 @@ export default {
|
||||
this.$toast.success(this.$strings.ToastPlaylistRemoveSuccess)
|
||||
} else {
|
||||
console.log(`Item removed from playlist`, updatedPlaylist)
|
||||
this.$toast.success(this.$strings.ToastPlaylistUpdateSuccess)
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
|
||||
4
client/package-lock.json
generated
4
client/package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "audiobookshelf-client",
|
||||
"version": "2.17.6",
|
||||
"version": "2.17.7",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "audiobookshelf-client",
|
||||
"version": "2.17.6",
|
||||
"version": "2.17.7",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@nuxtjs/axios": "^5.13.6",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "audiobookshelf-client",
|
||||
"version": "2.17.6",
|
||||
"version": "2.17.7",
|
||||
"buildNumber": 1,
|
||||
"description": "Self-hosted audiobook and podcast client",
|
||||
"main": "index.js",
|
||||
|
||||
@@ -110,6 +110,84 @@ export default {
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
mediaSessionPlay() {
|
||||
console.log('Media session play')
|
||||
this.play()
|
||||
},
|
||||
mediaSessionPause() {
|
||||
console.log('Media session pause')
|
||||
this.pause()
|
||||
},
|
||||
mediaSessionStop() {
|
||||
console.log('Media session stop')
|
||||
this.pause()
|
||||
},
|
||||
mediaSessionSeekBackward() {
|
||||
console.log('Media session seek backward')
|
||||
this.jumpBackward()
|
||||
},
|
||||
mediaSessionSeekForward() {
|
||||
console.log('Media session seek forward')
|
||||
this.jumpForward()
|
||||
},
|
||||
mediaSessionSeekTo(e) {
|
||||
console.log('Media session seek to', e)
|
||||
if (e.seekTime !== null && !isNaN(e.seekTime)) {
|
||||
this.seek(e.seekTime)
|
||||
}
|
||||
},
|
||||
mediaSessionPreviousTrack() {
|
||||
if (this.$refs.audioPlayer) {
|
||||
this.$refs.audioPlayer.prevChapter()
|
||||
}
|
||||
},
|
||||
mediaSessionNextTrack() {
|
||||
if (this.$refs.audioPlayer) {
|
||||
this.$refs.audioPlayer.nextChapter()
|
||||
}
|
||||
},
|
||||
updateMediaSessionPlaybackState() {
|
||||
if ('mediaSession' in navigator) {
|
||||
navigator.mediaSession.playbackState = this.isPlaying ? 'playing' : 'paused'
|
||||
}
|
||||
},
|
||||
setMediaSession() {
|
||||
// https://developer.mozilla.org/en-US/docs/Web/API/Media_Session_API
|
||||
if ('mediaSession' in navigator) {
|
||||
const chapterInfo = []
|
||||
if (this.chapters.length > 0) {
|
||||
this.chapters.forEach((chapter) => {
|
||||
chapterInfo.push({
|
||||
title: chapter.title,
|
||||
startTime: chapter.start
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
navigator.mediaSession.metadata = new MediaMetadata({
|
||||
title: this.mediaItemShare.playbackSession.displayTitle || 'No title',
|
||||
artist: this.mediaItemShare.playbackSession.displayAuthor || 'Unknown',
|
||||
artwork: [
|
||||
{
|
||||
src: this.coverUrl
|
||||
}
|
||||
],
|
||||
chapterInfo
|
||||
})
|
||||
console.log('Set media session metadata', navigator.mediaSession.metadata)
|
||||
|
||||
navigator.mediaSession.setActionHandler('play', this.mediaSessionPlay)
|
||||
navigator.mediaSession.setActionHandler('pause', this.mediaSessionPause)
|
||||
navigator.mediaSession.setActionHandler('stop', this.mediaSessionStop)
|
||||
navigator.mediaSession.setActionHandler('seekbackward', this.mediaSessionSeekBackward)
|
||||
navigator.mediaSession.setActionHandler('seekforward', this.mediaSessionSeekForward)
|
||||
navigator.mediaSession.setActionHandler('seekto', this.mediaSessionSeekTo)
|
||||
navigator.mediaSession.setActionHandler('previoustrack', this.mediaSessionSeekBackward)
|
||||
navigator.mediaSession.setActionHandler('nexttrack', this.mediaSessionSeekForward)
|
||||
} else {
|
||||
console.warn('Media session not available')
|
||||
}
|
||||
},
|
||||
async coverImageLoaded(e) {
|
||||
if (!this.playbackSession.coverPath) return
|
||||
const fac = new FastAverageColor()
|
||||
@@ -126,8 +204,19 @@ export default {
|
||||
})
|
||||
},
|
||||
playPause() {
|
||||
if (this.isPlaying) {
|
||||
this.pause()
|
||||
} else {
|
||||
this.play()
|
||||
}
|
||||
},
|
||||
play() {
|
||||
if (!this.localAudioPlayer || !this.hasLoaded) return
|
||||
this.localAudioPlayer.playPause()
|
||||
this.localAudioPlayer.play()
|
||||
},
|
||||
pause() {
|
||||
if (!this.localAudioPlayer || !this.hasLoaded) return
|
||||
this.localAudioPlayer.pause()
|
||||
},
|
||||
jumpForward() {
|
||||
if (!this.localAudioPlayer || !this.hasLoaded) return
|
||||
@@ -213,6 +302,7 @@ export default {
|
||||
} else {
|
||||
this.stopPlayInterval()
|
||||
}
|
||||
this.updateMediaSessionPlaybackState()
|
||||
},
|
||||
playerTimeUpdate(time) {
|
||||
this.setCurrentTime(time)
|
||||
@@ -276,6 +366,8 @@ export default {
|
||||
this.localAudioPlayer.on('timeupdate', this.playerTimeUpdate.bind(this))
|
||||
this.localAudioPlayer.on('error', this.playerError.bind(this))
|
||||
this.localAudioPlayer.on('finished', this.playerFinished.bind(this))
|
||||
|
||||
this.setMediaSession()
|
||||
},
|
||||
beforeDestroy() {
|
||||
window.removeEventListener('resize', this.resize)
|
||||
|
||||
@@ -629,7 +629,6 @@
|
||||
"MessageItemsSelected": "{0} избрани",
|
||||
"MessageItemsUpdated": "{0} елемента обновени",
|
||||
"MessageJoinUsOn": "Присъединете се към нас",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} слушателски сесии през последната година",
|
||||
"MessageLoading": "Зареждане...",
|
||||
"MessageLoadingFolders": "Зареждане на Папки...",
|
||||
"MessageM4BFailed": "M4B Провалено!",
|
||||
@@ -729,7 +728,6 @@
|
||||
"ToastBookmarkUpdateSuccess": "Отметката е обновена",
|
||||
"ToastChaptersHaveErrors": "Главите имат грешки",
|
||||
"ToastChaptersMustHaveTitles": "Главите трябва да имат заглавия",
|
||||
"ToastCollectionItemsRemoveSuccess": "Елемент(и) премахнати от колекция",
|
||||
"ToastCollectionRemoveSuccess": "Колекцията е премахната",
|
||||
"ToastCollectionUpdateSuccess": "Колекцията е обновена",
|
||||
"ToastItemCoverUpdateSuccess": "Корицата на елемента е обновена",
|
||||
|
||||
@@ -88,6 +88,8 @@
|
||||
"ButtonSaveTracklist": "ট্র্যাকলিস্ট সংরক্ষণ করুন",
|
||||
"ButtonScan": "স্ক্যান",
|
||||
"ButtonScanLibrary": "স্ক্যান লাইব্রেরি",
|
||||
"ButtonScrollLeft": "বাম দিকে স্ক্রল করুন",
|
||||
"ButtonScrollRight": "ডানদিকে স্ক্রল করুন",
|
||||
"ButtonSearch": "অনুসন্ধান",
|
||||
"ButtonSelectFolderPath": "ফোল্ডারের পথ নির্বাচন করুন",
|
||||
"ButtonSeries": "সিরিজ",
|
||||
@@ -190,6 +192,7 @@
|
||||
"HeaderSettingsExperimental": "পরীক্ষামূলক ফিচার",
|
||||
"HeaderSettingsGeneral": "সাধারণ",
|
||||
"HeaderSettingsScanner": "স্ক্যানার",
|
||||
"HeaderSettingsWebClient": "ওয়েব ক্লায়েন্ট",
|
||||
"HeaderSleepTimer": "স্লিপ টাইমার",
|
||||
"HeaderStatsLargestItems": "সবচেয়ে বড় আইটেম",
|
||||
"HeaderStatsLongestItems": "দীর্ঘতম আইটেম (ঘন্টা)",
|
||||
@@ -297,6 +300,7 @@
|
||||
"LabelDiscover": "আবিষ্কার",
|
||||
"LabelDownload": "ডাউনলোড করুন",
|
||||
"LabelDownloadNEpisodes": "{0}টি পর্ব ডাউনলোড করুন",
|
||||
"LabelDownloadable": "ডাউনলোডযোগ্য",
|
||||
"LabelDuration": "সময়কাল",
|
||||
"LabelDurationComparisonExactMatch": "(সঠিক মিল)",
|
||||
"LabelDurationComparisonLonger": "({0} দীর্ঘ)",
|
||||
@@ -542,6 +546,7 @@
|
||||
"LabelServerYearReview": "সার্ভারের বাৎসরিক পর্যালোচনা ({0})",
|
||||
"LabelSetEbookAsPrimary": "প্রাথমিক হিসাবে সেট করুন",
|
||||
"LabelSetEbookAsSupplementary": "পরিপূরক হিসেবে সেট করুন",
|
||||
"LabelSettingsAllowIframe": "আইফ্রেমে এম্বেড করার অনুমতি দিন",
|
||||
"LabelSettingsAudiobooksOnly": "শুধুমাত্র অডিও বই",
|
||||
"LabelSettingsAudiobooksOnlyHelp": "এই সেটিংটি সক্ষম করা ই-বই ফাইলগুলিকে উপেক্ষা করবে যদি না সেগুলি একটি অডিওবই ফোল্ডারের মধ্যে থাকে যে ক্ষেত্রে সেগুলিকে সম্পূরক ই-বই হিসাবে সেট করা হবে",
|
||||
"LabelSettingsBookshelfViewHelp": "কাঠের তাক সহ স্কুমরফিক ডিজাইন",
|
||||
@@ -584,6 +589,7 @@
|
||||
"LabelSettingsStoreMetadataWithItemHelp": "ডিফল্টরূপে মেটাডেটা ফাইলগুলি /মেটাডাটা/আইটেমগুলি -এ সংরক্ষণ করা হয়, এই সেটিংটি সক্ষম করলে মেটাডেটা ফাইলগুলি আপনার লাইব্রেরি আইটেম ফোল্ডারে সংরক্ষণ করা হবে",
|
||||
"LabelSettingsTimeFormat": "সময় বিন্যাস",
|
||||
"LabelShare": "শেয়ার করুন",
|
||||
"LabelShareDownloadableHelp": "শেয়ার লিঙ্ক সহ ব্যবহারকারীদের লাইব্রেরি আইটেমের একটি জিপ ফাইল ডাউনলোড করার অনুমতি দিন।",
|
||||
"LabelShareOpen": "শেয়ার খোলা",
|
||||
"LabelShareURL": "শেয়ার ইউআরএল",
|
||||
"LabelShowAll": "সব দেখান",
|
||||
@@ -592,6 +598,8 @@
|
||||
"LabelSize": "আকার",
|
||||
"LabelSleepTimer": "স্লিপ টাইমার",
|
||||
"LabelSlug": "স্লাগ",
|
||||
"LabelSortAscending": "আরোহী",
|
||||
"LabelSortDescending": "অবরোহী",
|
||||
"LabelStart": "শুরু",
|
||||
"LabelStartTime": "শুরুর সময়",
|
||||
"LabelStarted": "শুরু হয়েছে",
|
||||
@@ -679,6 +687,8 @@
|
||||
"LabelViewPlayerSettings": "প্লেয়ার সেটিংস দেখুন",
|
||||
"LabelViewQueue": "প্লেয়ার সারি দেখুন",
|
||||
"LabelVolume": "ভলিউম",
|
||||
"LabelWebRedirectURLsDescription": "লগইন করার পরে ওয়েব অ্যাপে পুনঃনির্দেশের অনুমতি দেওয়ার জন্য আপনার OAuth প্রদানকারীতে এই URLগুলোকে অনুমোদন করুন:",
|
||||
"LabelWebRedirectURLsSubfolder": "রিডাইরেক্ট URL এর জন্য সাবফোল্ডার",
|
||||
"LabelWeekdaysToRun": "চলতে হবে সপ্তাহের দিন",
|
||||
"LabelXBooks": "{0}টি বই",
|
||||
"LabelXItems": "{0}টি আইটেম",
|
||||
@@ -763,7 +773,6 @@
|
||||
"MessageItemsSelected": "{0}টি আইটেম নির্বাচিত",
|
||||
"MessageItemsUpdated": "{0}টি আইটেম আপডেট করা হয়েছে",
|
||||
"MessageJoinUsOn": "আমাদের সাথে যোগ দিন",
|
||||
"MessageListeningSessionsInTheLastYear": "গত বছরে {0}টি শোনার সেশন",
|
||||
"MessageLoading": "লোড হচ্ছে.।",
|
||||
"MessageLoadingFolders": "ফোল্ডার লোড হচ্ছে...",
|
||||
"MessageLogsDescription": "লগগুলি JSON ফাইল হিসাবে <code>/metadata/logs</code>-এ সংরক্ষণ করা হয়। ক্র্যাশ লগগুলি <code>/metadata/logs/crash_logs.txt</code>-এ সংরক্ষণ করা হয়।",
|
||||
@@ -951,8 +960,6 @@
|
||||
"ToastChaptersRemoved": "অধ্যায়গুলো মুছে ফেলা হয়েছে",
|
||||
"ToastChaptersUpdated": "অধ্যায় আপডেট করা হয়েছে",
|
||||
"ToastCollectionItemsAddFailed": "আইটেম(গুলি) সংগ্রহে যোগ করা ব্যর্থ হয়েছে",
|
||||
"ToastCollectionItemsAddSuccess": "আইটেম(গুলি) সংগ্রহে যোগ করা সফল হয়েছে",
|
||||
"ToastCollectionItemsRemoveSuccess": "আইটেম(গুলি) সংগ্রহ থেকে সরানো হয়েছে",
|
||||
"ToastCollectionRemoveSuccess": "সংগ্রহ সরানো হয়েছে",
|
||||
"ToastCollectionUpdateSuccess": "সংগ্রহ আপডেট করা হয়েছে",
|
||||
"ToastCoverUpdateFailed": "কভার আপডেট ব্যর্থ হয়েছে",
|
||||
|
||||
@@ -904,8 +904,6 @@
|
||||
"ToastChaptersRemoved": "Capítols eliminats",
|
||||
"ToastChaptersUpdated": "Capítols actualitzats",
|
||||
"ToastCollectionItemsAddFailed": "Error en afegir elements a la col·lecció",
|
||||
"ToastCollectionItemsAddSuccess": "Elements afegits a la col·lecció",
|
||||
"ToastCollectionItemsRemoveSuccess": "Elements eliminats de la col·lecció",
|
||||
"ToastCollectionRemoveSuccess": "Col·lecció eliminada",
|
||||
"ToastCollectionUpdateSuccess": "Col·lecció actualitzada",
|
||||
"ToastCoverUpdateFailed": "Error en actualitzar la portada",
|
||||
|
||||
@@ -771,7 +771,6 @@
|
||||
"MessageItemsSelected": "{0} vybraných položek",
|
||||
"MessageItemsUpdated": "{0} položky byly aktualizovány",
|
||||
"MessageJoinUsOn": "Přidejte se k nám",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} poslechových relací za poslední rok",
|
||||
"MessageLoading": "Načítá se...",
|
||||
"MessageLoadingFolders": "Načítám složky...",
|
||||
"MessageLogsDescription": "Protokoly se ukládají do souborů JSON v <code>/metadata/logs</code>. Protokoly o pádech jsou uloženy v <code>/metadata/logs/crash_logs.txt</code>.",
|
||||
@@ -943,7 +942,6 @@
|
||||
"ToastChaptersHaveErrors": "Kapitoly obsahují chyby",
|
||||
"ToastChaptersMustHaveTitles": "Kapitoly musí mít názvy",
|
||||
"ToastChaptersRemoved": "Kapitoly odstraněny",
|
||||
"ToastCollectionItemsRemoveSuccess": "Položky odstraněny z kolekce",
|
||||
"ToastCollectionRemoveSuccess": "Kolekce odstraněna",
|
||||
"ToastCollectionUpdateSuccess": "Kolekce aktualizována",
|
||||
"ToastCoverUpdateFailed": "Aktualizace obálky selhala",
|
||||
|
||||
@@ -539,7 +539,6 @@
|
||||
"MessageItemsSelected": "{0} elementer valgt",
|
||||
"MessageItemsUpdated": "{0} elementer opdateret",
|
||||
"MessageJoinUsOn": "Deltag i os på",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} lyttesessioner i det sidste år",
|
||||
"MessageLoading": "Indlæser...",
|
||||
"MessageLoadingFolders": "Indlæser mapper...",
|
||||
"MessageM4BFailed": "M4B mislykkedes!",
|
||||
@@ -640,7 +639,6 @@
|
||||
"ToastBookmarkUpdateSuccess": "Bogmærke opdateret",
|
||||
"ToastChaptersHaveErrors": "Kapitler har fejl",
|
||||
"ToastChaptersMustHaveTitles": "Kapitler skal have titler",
|
||||
"ToastCollectionItemsRemoveSuccess": "Element(er) fjernet fra samlingen",
|
||||
"ToastCollectionRemoveSuccess": "Samling fjernet",
|
||||
"ToastCollectionUpdateSuccess": "Samling opdateret",
|
||||
"ToastItemCoverUpdateSuccess": "Varens omslag opdateret",
|
||||
|
||||
@@ -771,7 +771,6 @@
|
||||
"MessageItemsSelected": "{0} ausgewählte Medien",
|
||||
"MessageItemsUpdated": "{0} Medien aktualisiert",
|
||||
"MessageJoinUsOn": "Besuche uns auf",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} Ereignisse im letzten Jahr",
|
||||
"MessageLoading": "Wird geladen …",
|
||||
"MessageLoadingFolders": "Lade Ordner...",
|
||||
"MessageLogsDescription": "Die Logs werdern in <code>/metadata/logs</code> als JSON Dateien gespeichert. Crash logs werden in <code>/metadata/logs/crash_logs.txt</code> gespeichert.",
|
||||
@@ -959,8 +958,6 @@
|
||||
"ToastChaptersRemoved": "Kapitel entfernt",
|
||||
"ToastChaptersUpdated": "Kapitel aktualisiert",
|
||||
"ToastCollectionItemsAddFailed": "Das Hinzufügen von Element(en) zur Sammlung ist fehlgeschlagen",
|
||||
"ToastCollectionItemsAddSuccess": "Element(e) erfolgreich zur Sammlung hinzugefügt",
|
||||
"ToastCollectionItemsRemoveSuccess": "Medien aus der Sammlung entfernt",
|
||||
"ToastCollectionRemoveSuccess": "Sammlung entfernt",
|
||||
"ToastCollectionUpdateSuccess": "Sammlung aktualisiert",
|
||||
"ToastCoverUpdateFailed": "Cover-Update fehlgeschlagen",
|
||||
|
||||
@@ -758,6 +758,7 @@
|
||||
"MessageConfirmResetProgress": "Are you sure you want to reset your progress?",
|
||||
"MessageConfirmSendEbookToDevice": "Are you sure you want to send {0} ebook \"{1}\" to device \"{2}\"?",
|
||||
"MessageConfirmUnlinkOpenId": "Are you sure you want to unlink this user from OpenID?",
|
||||
"MessageDaysListenedInTheLastYear": "{0} days listened in the last year",
|
||||
"MessageDownloadingEpisode": "Downloading episode",
|
||||
"MessageDragFilesIntoTrackOrder": "Drag files into correct track order",
|
||||
"MessageEmbedFailed": "Embed Failed!",
|
||||
@@ -773,7 +774,6 @@
|
||||
"MessageItemsSelected": "{0} Items Selected",
|
||||
"MessageItemsUpdated": "{0} Items Updated",
|
||||
"MessageJoinUsOn": "Join us on",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} listening sessions in the last year",
|
||||
"MessageLoading": "Loading...",
|
||||
"MessageLoadingFolders": "Loading folders...",
|
||||
"MessageLogsDescription": "Logs are stored in <code>/metadata/logs</code> as JSON files. Crash logs are stored in <code>/metadata/logs/crash_logs.txt</code>.",
|
||||
@@ -961,8 +961,6 @@
|
||||
"ToastChaptersRemoved": "Chapters removed",
|
||||
"ToastChaptersUpdated": "Chapters updated",
|
||||
"ToastCollectionItemsAddFailed": "Item(s) added to collection failed",
|
||||
"ToastCollectionItemsAddSuccess": "Item(s) added to collection success",
|
||||
"ToastCollectionItemsRemoveSuccess": "Item(s) removed from collection",
|
||||
"ToastCollectionRemoveSuccess": "Collection removed",
|
||||
"ToastCollectionUpdateSuccess": "Collection updated",
|
||||
"ToastCoverUpdateFailed": "Cover update failed",
|
||||
|
||||
@@ -771,7 +771,6 @@
|
||||
"MessageItemsSelected": "{0} Elementos Seleccionados",
|
||||
"MessageItemsUpdated": "{0} Elementos Actualizados",
|
||||
"MessageJoinUsOn": "Únetenos en",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} sesiones de escucha en el último año",
|
||||
"MessageLoading": "Cargando...",
|
||||
"MessageLoadingFolders": "Cargando archivos...",
|
||||
"MessageLogsDescription": "Logs son almacenados en <code>/metadata/logs</code> en archivos bajo formato JSON. Logs de fallos son almacenados en <code>/metadata/logs/crash_logs.txt</code>.",
|
||||
@@ -959,8 +958,6 @@
|
||||
"ToastChaptersRemoved": "Capítulos eliminados",
|
||||
"ToastChaptersUpdated": "Capítulos actualizados",
|
||||
"ToastCollectionItemsAddFailed": "Artículo(s) añadido(s) a la colección fallido(s)",
|
||||
"ToastCollectionItemsAddSuccess": "Artículo(s) añadido(s) a la colección correctamente",
|
||||
"ToastCollectionItemsRemoveSuccess": "Elementos(s) removidos de la colección",
|
||||
"ToastCollectionRemoveSuccess": "Colección removida",
|
||||
"ToastCollectionUpdateSuccess": "Colección actualizada",
|
||||
"ToastCoverUpdateFailed": "Error al actualizar la cubierta",
|
||||
|
||||
@@ -611,7 +611,6 @@
|
||||
"MessageItemsSelected": "{0} Valitud üksust",
|
||||
"MessageItemsUpdated": "{0} Üksust on uuendatud",
|
||||
"MessageJoinUsOn": "Liitu meiega",
|
||||
"MessageListeningSessionsInTheLastYear": "Kuulamissessioone viimase aasta jooksul: {0}",
|
||||
"MessageLoading": "Laadimine...",
|
||||
"MessageLoadingFolders": "Kaustade laadimine...",
|
||||
"MessageM4BFailed": "M4B ebaõnnestus!",
|
||||
@@ -713,7 +712,6 @@
|
||||
"ToastBookmarkUpdateSuccess": "Järjehoidja värskendatud",
|
||||
"ToastChaptersHaveErrors": "Peatükkidel on vigu",
|
||||
"ToastChaptersMustHaveTitles": "Peatükkidel peab olema pealkiri",
|
||||
"ToastCollectionItemsRemoveSuccess": "Üksus(ed) eemaldatud kogumist",
|
||||
"ToastCollectionRemoveSuccess": "Kogum eemaldatud",
|
||||
"ToastCollectionUpdateSuccess": "Kogum värskendatud",
|
||||
"ToastItemCoverUpdateSuccess": "Üksuse kaas värskendatud",
|
||||
|
||||
@@ -765,7 +765,6 @@
|
||||
"MessageItemsSelected": "{0} éléments sélectionnés",
|
||||
"MessageItemsUpdated": "{0} éléments mis à jour",
|
||||
"MessageJoinUsOn": "Rejoignez-nous sur",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} sessions d’écoute l’an dernier",
|
||||
"MessageLoading": "Chargement…",
|
||||
"MessageLoadingFolders": "Chargement des dossiers…",
|
||||
"MessageLogsDescription": "Les journaux sont stockés dans <code>/metadata/logs</code> sous forme de fichiers JSON. Les journaux d’incidents sont stockés dans <code>/metadata/logs/crash_logs.txt</code>.",
|
||||
@@ -953,8 +952,6 @@
|
||||
"ToastChaptersRemoved": "Chapitres supprimés",
|
||||
"ToastChaptersUpdated": "Chapitres mis à jour",
|
||||
"ToastCollectionItemsAddFailed": "Échec de l’ajout de(s) élément(s) à la collection",
|
||||
"ToastCollectionItemsAddSuccess": "Ajout de(s) élément(s) à la collection réussi",
|
||||
"ToastCollectionItemsRemoveSuccess": "Élément(s) supprimé(s) de la collection",
|
||||
"ToastCollectionRemoveSuccess": "Collection supprimée",
|
||||
"ToastCollectionUpdateSuccess": "Collection mise à jour",
|
||||
"ToastCoverUpdateFailed": "Échec de la mise à jour de la couverture",
|
||||
|
||||
@@ -642,7 +642,6 @@
|
||||
"MessageItemsSelected": "{0} פריטים נבחרו",
|
||||
"MessageItemsUpdated": "{0} פריטים עודכנו",
|
||||
"MessageJoinUsOn": "הצטרף אלינו ב-",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} מפגשי האזנה בשנה האחרונה",
|
||||
"MessageLoading": "טוען...",
|
||||
"MessageLoadingFolders": "טוען תיקיות...",
|
||||
"MessageM4BFailed": "M4B נכשל!",
|
||||
@@ -744,7 +743,6 @@
|
||||
"ToastBookmarkUpdateSuccess": "הסימניה עודכנה בהצלחה",
|
||||
"ToastChaptersHaveErrors": "פרקים מכילים שגיאות",
|
||||
"ToastChaptersMustHaveTitles": "פרקים חייבים לכלול כותרות",
|
||||
"ToastCollectionItemsRemoveSuccess": "הפריט(ים) הוסרו מהאוסף בהצלחה",
|
||||
"ToastCollectionRemoveSuccess": "האוסף הוסר בהצלחה",
|
||||
"ToastCollectionUpdateSuccess": "האוסף עודכן בהצלחה",
|
||||
"ToastItemCoverUpdateSuccess": "כריכת הפריט עודכנה בהצלחה",
|
||||
|
||||
@@ -771,7 +771,6 @@
|
||||
"MessageItemsSelected": "{0} odabranih stavki",
|
||||
"MessageItemsUpdated": "{0} stavki ažurirano",
|
||||
"MessageJoinUsOn": "Pridruži nam se na",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} slušanja u prošloj godini",
|
||||
"MessageLoading": "Učitavam...",
|
||||
"MessageLoadingFolders": "Učitavam mape...",
|
||||
"MessageLogsDescription": "Zapisnici se čuvaju u <code>/metadata/logs</code> u obliku JSON datoteka. Zapisnici pada sustava čuvaju se u datoteci <code>/metadata/logs/crash_logs.txt</code>.",
|
||||
@@ -959,8 +958,6 @@
|
||||
"ToastChaptersRemoved": "Poglavlja uklonjena",
|
||||
"ToastChaptersUpdated": "Poglavlja su ažurirana",
|
||||
"ToastCollectionItemsAddFailed": "Neuspješno dodavanje stavki u zbirku",
|
||||
"ToastCollectionItemsAddSuccess": "Uspješno dodavanje stavki u zbirku",
|
||||
"ToastCollectionItemsRemoveSuccess": "Stavke izbrisane iz zbirke",
|
||||
"ToastCollectionRemoveSuccess": "Zbirka izbrisana",
|
||||
"ToastCollectionUpdateSuccess": "Zbirka ažurirana",
|
||||
"ToastCoverUpdateFailed": "Ažuriranje naslovnice nije uspjelo",
|
||||
|
||||
@@ -764,7 +764,6 @@
|
||||
"MessageItemsSelected": "{0} kiválasztott elem",
|
||||
"MessageItemsUpdated": "{0} frissített elem",
|
||||
"MessageJoinUsOn": "Csatlakozzon hozzánk a",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} hallgatási munkamenet az elmúlt évben",
|
||||
"MessageLoading": "Betöltés...",
|
||||
"MessageLoadingFolders": "Mappák betöltése...",
|
||||
"MessageLogsDescription": "A naplók a <code>/metadata/logs</code> mappában JSON-fájlokként tárolódnak. Az összeomlási naplók a <code>/metadata/logs/crash_logs.txt</code> fájlban tárolódnak.",
|
||||
@@ -945,7 +944,6 @@
|
||||
"ToastChaptersMustHaveTitles": "A fejezeteknek címekkel kell rendelkezniük",
|
||||
"ToastChaptersRemoved": "Fejezetek eltávolítva",
|
||||
"ToastChaptersUpdated": "Fejezetek frissítve",
|
||||
"ToastCollectionItemsRemoveSuccess": "Elem(ek) eltávolítva a gyűjteményből",
|
||||
"ToastCollectionRemoveSuccess": "Gyűjtemény eltávolítva",
|
||||
"ToastCollectionUpdateSuccess": "Gyűjtemény frissítve",
|
||||
"ToastCoverUpdateFailed": "A borító frissítése nem sikerült",
|
||||
|
||||
@@ -762,7 +762,6 @@
|
||||
"MessageItemsSelected": "{0} oggetti Selezionati",
|
||||
"MessageItemsUpdated": "{0} Oggetti aggiornati",
|
||||
"MessageJoinUsOn": "Unisciti a noi su",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} sessioni di ascolto nell'ultimo anno",
|
||||
"MessageLoading": "Caricamento…",
|
||||
"MessageLoadingFolders": "Caricamento Cartelle...",
|
||||
"MessageLogsDescription": "I log vengono archiviati nel percorso <code>/metadata/logs</code> as JSON files. I registri degli arresti anomali vengono archiviati nel percorso <code>/metadata/logs/crash_logs.txt</code>.",
|
||||
@@ -950,8 +949,6 @@
|
||||
"ToastChaptersRemoved": "Capitoli rimossi",
|
||||
"ToastChaptersUpdated": "Capitoli aggiornati",
|
||||
"ToastCollectionItemsAddFailed": "l'aggiunta dell'elemento(i) alla raccolta non è riuscito",
|
||||
"ToastCollectionItemsAddSuccess": "L'aggiunta dell'elemento(i) alla raccolta è riuscito",
|
||||
"ToastCollectionItemsRemoveSuccess": "Oggetto(i) rimossi dalla Raccolta",
|
||||
"ToastCollectionRemoveSuccess": "Collezione rimossa",
|
||||
"ToastCollectionUpdateSuccess": "Raccolta aggiornata",
|
||||
"ToastCoverUpdateFailed": "Aggiornamento cover fallito",
|
||||
|
||||
@@ -563,7 +563,6 @@
|
||||
"MessageItemsSelected": "Pasirinkti {0} elementai (-ų)",
|
||||
"MessageItemsUpdated": "Atnaujinti {0} elementai (-ų)",
|
||||
"MessageJoinUsOn": "Prisijunkite prie mūsų",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} klausymo sesijų per paskutinius metus",
|
||||
"MessageLoading": "Kraunama...",
|
||||
"MessageLoadingFolders": "Kraunami aplankai...",
|
||||
"MessageM4BFailed": "M4B Nepavyko!",
|
||||
@@ -666,8 +665,6 @@
|
||||
"ToastChaptersMustHaveTitles": "Skyriai turi turėti pavadinimus",
|
||||
"ToastChaptersRemoved": "Skyriai pašalinti",
|
||||
"ToastCollectionItemsAddFailed": "Nepavyko pridėti į kolekciją",
|
||||
"ToastCollectionItemsAddSuccess": "Pridėta į kolekciją",
|
||||
"ToastCollectionItemsRemoveSuccess": "Elementai pašalinti iš kolekcijos",
|
||||
"ToastCollectionRemoveSuccess": "Kolekcija pašalinta",
|
||||
"ToastCollectionUpdateSuccess": "Kolekcija atnaujinta",
|
||||
"ToastCoverUpdateFailed": "Viršelio atnaujinimas nepavyko",
|
||||
|
||||
@@ -758,7 +758,6 @@
|
||||
"MessageItemsSelected": "{0} onderdelen geselecteerd",
|
||||
"MessageItemsUpdated": "{0} onderdelen bijgewerkt",
|
||||
"MessageJoinUsOn": "Doe mee op",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} luistersessies in het laatste jaar",
|
||||
"MessageLoading": "Aan het laden...",
|
||||
"MessageLoadingFolders": "Mappen aan het laden...",
|
||||
"MessageLogsDescription": "Logs worden opgeslagen in <code>/metadata/logs</code> als JSON-bestanden. Crashlogs worden opgeslagen in <code>/metadata/logs/crash_logs.txt</code>.",
|
||||
@@ -946,8 +945,6 @@
|
||||
"ToastChaptersRemoved": "Hoofdstukken verwijderd",
|
||||
"ToastChaptersUpdated": "Hoofdstukken bijgewerkt",
|
||||
"ToastCollectionItemsAddFailed": "Item(s) toegevoegd aan collectie mislukt",
|
||||
"ToastCollectionItemsAddSuccess": "Item(s) toegevoegd aan collectie gelukt",
|
||||
"ToastCollectionItemsRemoveSuccess": "Onderdeel (of onderdelen) verwijderd uit collectie",
|
||||
"ToastCollectionRemoveSuccess": "Collectie verwijderd",
|
||||
"ToastCollectionUpdateSuccess": "Collectie bijgewerkt",
|
||||
"ToastCoverUpdateFailed": "Cover update mislukt",
|
||||
|
||||
@@ -769,7 +769,6 @@
|
||||
"MessageItemsSelected": "{0} Gjenstander valgt",
|
||||
"MessageItemsUpdated": "{0} Gjenstander oppdatert",
|
||||
"MessageJoinUsOn": "Følg oss nå",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} Lyttesesjoner iløpet av siste året",
|
||||
"MessageLoading": "Laster...",
|
||||
"MessageLoadingFolders": "Laster mapper...",
|
||||
"MessageM4BFailed": "M4B mislykkes!",
|
||||
@@ -882,8 +881,6 @@
|
||||
"ToastChaptersRemoved": "Kapitler fjernet",
|
||||
"ToastChaptersUpdated": "Kapitler oppdatert",
|
||||
"ToastCollectionItemsAddFailed": "Feil med å legge til element(er)",
|
||||
"ToastCollectionItemsAddSuccess": "Element(er) lagt til samlingen",
|
||||
"ToastCollectionItemsRemoveSuccess": "Gjenstand(er) fjernet fra samling",
|
||||
"ToastCollectionRemoveSuccess": "Samling fjernet",
|
||||
"ToastCollectionUpdateSuccess": "samlingupdated",
|
||||
"ToastCoverUpdateFailed": "Oppdatering av bilde feilet",
|
||||
|
||||
@@ -657,7 +657,6 @@
|
||||
"MessageInsertChapterBelow": "Wstaw rozdział poniżej",
|
||||
"MessageItemsSelected": "{0} zaznaczone elementy",
|
||||
"MessageJoinUsOn": "Dołącz do nas na",
|
||||
"MessageListeningSessionsInTheLastYear": "Sesje słuchania w ostatnim roku: {0}",
|
||||
"MessageLoading": "Ładowanie...",
|
||||
"MessageLoadingFolders": "Ładowanie folderów...",
|
||||
"MessageLogsDescription": "Logi zapisane są w <code>/metadata/logs</code> jako pliki JSON. Logi awaryjne są zapisane w <code>/metadata/logs/crash_logs.txt</code>.",
|
||||
@@ -772,7 +771,6 @@
|
||||
"ToastBookmarkCreateSuccess": "Dodano zakładkę",
|
||||
"ToastBookmarkRemoveSuccess": "Zakładka została usunięta",
|
||||
"ToastBookmarkUpdateSuccess": "Zaktualizowano zakładkę",
|
||||
"ToastCollectionItemsRemoveSuccess": "Przedmiot(y) zostały usunięte z kolekcji",
|
||||
"ToastCollectionRemoveSuccess": "Kolekcja usunięta",
|
||||
"ToastCollectionUpdateSuccess": "Zaktualizowano kolekcję",
|
||||
"ToastItemCoverUpdateSuccess": "Zaktualizowano okładkę",
|
||||
|
||||
@@ -630,7 +630,6 @@
|
||||
"MessageItemsSelected": "{0} Itens Selecionados",
|
||||
"MessageItemsUpdated": "{0} Itens Atualizados",
|
||||
"MessageJoinUsOn": "Junte-se a nós",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} sessões de escuta no ano anterior",
|
||||
"MessageLoading": "Carregando...",
|
||||
"MessageLoadingFolders": "Carregando pastas...",
|
||||
"MessageLogsDescription": "Os logs estão armazenados em <code>/metadata/logs</code> como arquivos JSON. Logs de crash estão armazenados em <code>/metadata/logs/crash_logs.txt</code>.",
|
||||
@@ -735,7 +734,6 @@
|
||||
"ToastCachePurgeSuccess": "Cache apagado com sucesso",
|
||||
"ToastChaptersHaveErrors": "Capítulos com erro",
|
||||
"ToastChaptersMustHaveTitles": "Capítulos precisam ter títulos",
|
||||
"ToastCollectionItemsRemoveSuccess": "Item(ns) removidos da coleção",
|
||||
"ToastCollectionRemoveSuccess": "Coleção removida",
|
||||
"ToastCollectionUpdateSuccess": "Coleção atualizada",
|
||||
"ToastDeleteFileFailed": "Falha ao apagar arquivo",
|
||||
|
||||
@@ -300,6 +300,7 @@
|
||||
"LabelDiscover": "Не начато",
|
||||
"LabelDownload": "Скачать",
|
||||
"LabelDownloadNEpisodes": "Скачать {0} эпизодов",
|
||||
"LabelDownloadable": "Загружаемый",
|
||||
"LabelDuration": "Длина",
|
||||
"LabelDurationComparisonExactMatch": "(точное совпадение)",
|
||||
"LabelDurationComparisonLonger": "({0} дольше)",
|
||||
@@ -588,6 +589,7 @@
|
||||
"LabelSettingsStoreMetadataWithItemHelp": "По умолчанию метаинформация сохраняется в папке /metadata/items, при включении этой настройки метаинформация будет храниться в папке элемента",
|
||||
"LabelSettingsTimeFormat": "Формат времени",
|
||||
"LabelShare": "Поделиться",
|
||||
"LabelShareDownloadableHelp": "Позволяет пользователям с помощью ссылки загрузить zip-файл элемента библиотеки.",
|
||||
"LabelShareOpen": "Общедоступно",
|
||||
"LabelShareURL": "Общедоступный URL",
|
||||
"LabelShowAll": "Показать все",
|
||||
@@ -771,7 +773,6 @@
|
||||
"MessageItemsSelected": "{0} Элементов выделено",
|
||||
"MessageItemsUpdated": "{0} Элементов обновлено",
|
||||
"MessageJoinUsOn": "Присоединяйтесь к нам в",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} сеансов прослушивания в прошлом году",
|
||||
"MessageLoading": "Загрузка...",
|
||||
"MessageLoadingFolders": "Загрузка каталогов...",
|
||||
"MessageLogsDescription": "Журналы хранятся в <code>/metadata/logs</code> в виде JSON-файлов. Журналы сбоев хранятся в <code>/metadata/logs/crash_logs.txt</code>.",
|
||||
@@ -959,8 +960,6 @@
|
||||
"ToastChaptersRemoved": "Удалены главы",
|
||||
"ToastChaptersUpdated": "Обновленные главы",
|
||||
"ToastCollectionItemsAddFailed": "Не удалось добавить элемент(ы) в коллекцию",
|
||||
"ToastCollectionItemsAddSuccess": "Элемент(ы) добавлены в коллекцию",
|
||||
"ToastCollectionItemsRemoveSuccess": "Элемент(ы), удалены из коллекции",
|
||||
"ToastCollectionRemoveSuccess": "Коллекция удалена",
|
||||
"ToastCollectionUpdateSuccess": "Коллекция обновлена",
|
||||
"ToastCoverUpdateFailed": "Не удалось обновить обложку",
|
||||
|
||||
@@ -300,6 +300,7 @@
|
||||
"LabelDiscover": "Odkrij",
|
||||
"LabelDownload": "Prenos",
|
||||
"LabelDownloadNEpisodes": "Prenesi {0} epizod",
|
||||
"LabelDownloadable": "Možen prenos",
|
||||
"LabelDuration": "Trajanje",
|
||||
"LabelDurationComparisonExactMatch": "(natančno ujemanje)",
|
||||
"LabelDurationComparisonLonger": "({0} dlje)",
|
||||
@@ -588,6 +589,7 @@
|
||||
"LabelSettingsStoreMetadataWithItemHelp": "Datoteke z metapodatki so privzeto shranjene v /metadata/items, če omogočite to nastavitev, boste datoteke z metapodatki shranili v mape elementov vaše knjižnice",
|
||||
"LabelSettingsTimeFormat": "Oblika časa",
|
||||
"LabelShare": "Deli",
|
||||
"LabelShareDownloadableHelp": "Omogoča uporabnikom s povezavo skupne rabe, da prenesejo zip datoteko elementa knjižnice.",
|
||||
"LabelShareOpen": "Deli odprto",
|
||||
"LabelShareURL": "Deli URL",
|
||||
"LabelShowAll": "Prikaži vse",
|
||||
@@ -771,7 +773,6 @@
|
||||
"MessageItemsSelected": "{0} izbranih elementov",
|
||||
"MessageItemsUpdated": "Št. posodobljenih elementov: {0}",
|
||||
"MessageJoinUsOn": "Pridružite se nam",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} sej poslušanja v zadnjem letu",
|
||||
"MessageLoading": "Nalagam...",
|
||||
"MessageLoadingFolders": "Nalagam mape...",
|
||||
"MessageLogsDescription": "Dnevniki so shranjeni v <code>/metadata/logs</code> kot datoteke JSON. Dnevniki zrušitev so shranjeni v <code>/metadata/logs/crash_logs.txt</code>.",
|
||||
@@ -959,8 +960,6 @@
|
||||
"ToastChaptersRemoved": "Poglavja so odstranjena",
|
||||
"ToastChaptersUpdated": "Poglavja so posodobljena",
|
||||
"ToastCollectionItemsAddFailed": "Dodajanje elementov v zbirko ni uspelo",
|
||||
"ToastCollectionItemsAddSuccess": "Dodajanje elementov v zbirko je bilo uspešno",
|
||||
"ToastCollectionItemsRemoveSuccess": "Elementi so bili odstranjeni iz zbirke",
|
||||
"ToastCollectionRemoveSuccess": "Zbirka je bila odstranjena",
|
||||
"ToastCollectionUpdateSuccess": "Zbirka je bila posodobljena",
|
||||
"ToastCoverUpdateFailed": "Posodobitev naslovnice ni uspela",
|
||||
|
||||
@@ -590,7 +590,6 @@
|
||||
"MessageItemsSelected": "{0} Objekt markerade",
|
||||
"MessageItemsUpdated": "{0} Objekt uppdaterade",
|
||||
"MessageJoinUsOn": "Anslut dig till oss på",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} lyssningssessioner det senaste året",
|
||||
"MessageLoading": "Laddar...",
|
||||
"MessageLoadingFolders": "Laddar mappar...",
|
||||
"MessageM4BFailed": "M4B misslyckades!",
|
||||
@@ -705,7 +704,6 @@
|
||||
"ToastBookmarkUpdateSuccess": "Bokmärket har uppdaterats",
|
||||
"ToastChaptersHaveErrors": "Kapitlen har fel",
|
||||
"ToastChaptersMustHaveTitles": "Kapitel måste ha titlar",
|
||||
"ToastCollectionItemsRemoveSuccess": "Objekt borttagna från samlingen",
|
||||
"ToastCollectionRemoveSuccess": "Samlingen har raderats",
|
||||
"ToastCollectionUpdateSuccess": "Samlingen har uppdaterats",
|
||||
"ToastItemCoverUpdateSuccess": "Objektets omslag uppdaterat",
|
||||
|
||||
@@ -300,6 +300,7 @@
|
||||
"LabelDiscover": "Огляд",
|
||||
"LabelDownload": "Завантажити",
|
||||
"LabelDownloadNEpisodes": "Завантажити епізодів: {0}",
|
||||
"LabelDownloadable": "Можна завантажити",
|
||||
"LabelDuration": "Тривалість",
|
||||
"LabelDurationComparisonExactMatch": "(повний збіг)",
|
||||
"LabelDurationComparisonLonger": "(на {0} довше)",
|
||||
@@ -588,6 +589,7 @@
|
||||
"LabelSettingsStoreMetadataWithItemHelp": "За замовчуванням файли метаданих зберігаються у /metadata/items. Цей параметр увімкне збереження метаданих у теці елемента бібліотеки",
|
||||
"LabelSettingsTimeFormat": "Формат часу",
|
||||
"LabelShare": "Поділитися",
|
||||
"LabelShareDownloadableHelp": "Дозволяє користувачам із посиланням для спільного доступу завантажувати zip-файл елемента бібліотеки.",
|
||||
"LabelShareOpen": "Поділитися відкрито",
|
||||
"LabelShareURL": "Поділитися URL",
|
||||
"LabelShowAll": "Показати все",
|
||||
@@ -771,7 +773,6 @@
|
||||
"MessageItemsSelected": "Обрано елементів: {0}",
|
||||
"MessageItemsUpdated": "Оновлено елементів: {0}",
|
||||
"MessageJoinUsOn": "Приєднуйтесь до",
|
||||
"MessageListeningSessionsInTheLastYear": "Сесій прослуховування минулого року: {0}",
|
||||
"MessageLoading": "Завантаження...",
|
||||
"MessageLoadingFolders": "Завантаження тек...",
|
||||
"MessageLogsDescription": "Журнали зберігаються у <code>/metadata/logs</code> як JSON-файли. Журнали збоїв зберігаються у <code>/metadata/logs/crash_logs.txt</code>.",
|
||||
@@ -959,8 +960,6 @@
|
||||
"ToastChaptersRemoved": "Розділи видалені",
|
||||
"ToastChaptersUpdated": "Розділи оновлені",
|
||||
"ToastCollectionItemsAddFailed": "Не вдалося додати елемент(и) до колекції",
|
||||
"ToastCollectionItemsAddSuccess": "Елемент(и) успішно додано до колекції",
|
||||
"ToastCollectionItemsRemoveSuccess": "Елемент(и) видалено з добірки",
|
||||
"ToastCollectionRemoveSuccess": "Добірку видалено",
|
||||
"ToastCollectionUpdateSuccess": "Добірку оновлено",
|
||||
"ToastCoverUpdateFailed": "Не вдалося оновити обкладинку",
|
||||
|
||||
@@ -581,7 +581,6 @@
|
||||
"MessageItemsSelected": "{0} Mục Đã Chọn",
|
||||
"MessageItemsUpdated": "{0} Mục Đã Cập Nhật",
|
||||
"MessageJoinUsOn": "Tham gia cùng chúng tôi trên",
|
||||
"MessageListeningSessionsInTheLastYear": "{0} phiên nghe trong năm qua",
|
||||
"MessageLoading": "Đang tải...",
|
||||
"MessageLoadingFolders": "Đang tải các thư mục...",
|
||||
"MessageM4BFailed": "M4B thất bại!",
|
||||
@@ -683,7 +682,6 @@
|
||||
"ToastBookmarkUpdateSuccess": "Đánh dấu đã được cập nhật",
|
||||
"ToastChaptersHaveErrors": "Các chương có lỗi",
|
||||
"ToastChaptersMustHaveTitles": "Các chương phải có tiêu đề",
|
||||
"ToastCollectionItemsRemoveSuccess": "Mục đã được xóa khỏi bộ sưu tập",
|
||||
"ToastCollectionRemoveSuccess": "Bộ sưu tập đã được xóa",
|
||||
"ToastCollectionUpdateSuccess": "Bộ sưu tập đã được cập nhật",
|
||||
"ToastItemCoverUpdateSuccess": "Ảnh bìa mục đã được cập nhật",
|
||||
|
||||
@@ -771,7 +771,6 @@
|
||||
"MessageItemsSelected": "已选定 {0} 个项目",
|
||||
"MessageItemsUpdated": "已更新 {0} 个项目",
|
||||
"MessageJoinUsOn": "加入我们",
|
||||
"MessageListeningSessionsInTheLastYear": "去年收听 {0} 个会话",
|
||||
"MessageLoading": "正在加载...",
|
||||
"MessageLoadingFolders": "加载文件夹...",
|
||||
"MessageLogsDescription": "日志以 JSON 文件形式存储在 <code>/metadata/logs</code> 目录中. 崩溃日志存储在 <code>/metadata/logs/crash_logs.txt</code> 目录中.",
|
||||
@@ -959,8 +958,6 @@
|
||||
"ToastChaptersRemoved": "已删除章节",
|
||||
"ToastChaptersUpdated": "章节已更新",
|
||||
"ToastCollectionItemsAddFailed": "项目添加到收藏夹失败",
|
||||
"ToastCollectionItemsAddSuccess": "项目添加到收藏夹成功",
|
||||
"ToastCollectionItemsRemoveSuccess": "项目从收藏夹移除",
|
||||
"ToastCollectionRemoveSuccess": "收藏夹已删除",
|
||||
"ToastCollectionUpdateSuccess": "收藏夹已更新",
|
||||
"ToastCoverUpdateFailed": "封面更新失败",
|
||||
|
||||
@@ -625,7 +625,6 @@
|
||||
"MessageItemsSelected": "已選定 {0} 個項目",
|
||||
"MessageItemsUpdated": "已更新 {0} 個項目",
|
||||
"MessageJoinUsOn": "加入我們",
|
||||
"MessageListeningSessionsInTheLastYear": "去年收聽 {0} 個會話",
|
||||
"MessageLoading": "讀取...",
|
||||
"MessageLoadingFolders": "讀取資料夾...",
|
||||
"MessageM4BFailed": "M4B 失敗!",
|
||||
@@ -727,7 +726,6 @@
|
||||
"ToastBookmarkUpdateSuccess": "書籤已更新",
|
||||
"ToastChaptersHaveErrors": "章節有錯誤",
|
||||
"ToastChaptersMustHaveTitles": "章節必須有標題",
|
||||
"ToastCollectionItemsRemoveSuccess": "項目從收藏夾移除",
|
||||
"ToastCollectionRemoveSuccess": "收藏夾已刪除",
|
||||
"ToastCollectionUpdateSuccess": "收藏夾已更新",
|
||||
"ToastItemCoverUpdateSuccess": "項目封面已更新",
|
||||
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "audiobookshelf",
|
||||
"version": "2.17.6",
|
||||
"version": "2.17.7",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "audiobookshelf",
|
||||
"version": "2.17.6",
|
||||
"version": "2.17.7",
|
||||
"license": "GPL-3.0",
|
||||
"dependencies": {
|
||||
"axios": "^0.27.2",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "audiobookshelf",
|
||||
"version": "2.17.6",
|
||||
"version": "2.17.7",
|
||||
"buildNumber": 1,
|
||||
"description": "Self-hosted audiobook and podcast server",
|
||||
"main": "index.js",
|
||||
|
||||
@@ -406,21 +406,6 @@ class Database {
|
||||
return Promise.all(oldBooks.map((oldBook) => this.models.book.saveFromOld(oldBook)))
|
||||
}
|
||||
|
||||
createBulkCollectionBooks(collectionBooks) {
|
||||
if (!this.sequelize) return false
|
||||
return this.models.collectionBook.bulkCreate(collectionBooks)
|
||||
}
|
||||
|
||||
createPlaylistMediaItem(playlistMediaItem) {
|
||||
if (!this.sequelize) return false
|
||||
return this.models.playlistMediaItem.create(playlistMediaItem)
|
||||
}
|
||||
|
||||
createBulkPlaylistMediaItems(playlistMediaItems) {
|
||||
if (!this.sequelize) return false
|
||||
return this.models.playlistMediaItem.bulkCreate(playlistMediaItems)
|
||||
}
|
||||
|
||||
async createLibraryItem(oldLibraryItem) {
|
||||
if (!this.sequelize) return false
|
||||
await oldLibraryItem.saveMetadata()
|
||||
|
||||
@@ -6,6 +6,7 @@ const util = require('util')
|
||||
const fs = require('./libs/fsExtra')
|
||||
const fileUpload = require('./libs/expressFileupload')
|
||||
const cookieParser = require('cookie-parser')
|
||||
const axios = require('axios')
|
||||
|
||||
const { version } = require('../package.json')
|
||||
|
||||
@@ -54,7 +55,26 @@ class Server {
|
||||
global.XAccel = process.env.USE_X_ACCEL
|
||||
global.AllowCors = process.env.ALLOW_CORS === '1'
|
||||
|
||||
if (process.env.DISABLE_SSRF_REQUEST_FILTER === '1') {
|
||||
if (process.env.EXP_PROXY_SUPPORT === '1') {
|
||||
// https://github.com/advplyr/audiobookshelf/pull/3754
|
||||
Logger.info(`[Server] Experimental Proxy Support Enabled, SSRF Request Filter was Disabled`)
|
||||
global.DisableSsrfRequestFilter = () => true
|
||||
|
||||
axios.defaults.maxRedirects = 0
|
||||
axios.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => {
|
||||
if ([301, 302].includes(error.response?.status)) {
|
||||
return axios({
|
||||
...error.config,
|
||||
url: error.response.headers.location
|
||||
})
|
||||
}
|
||||
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
} else if (process.env.DISABLE_SSRF_REQUEST_FILTER === '1') {
|
||||
Logger.info(`[Server] SSRF Request Filter Disabled`)
|
||||
global.DisableSsrfRequestFilter = () => true
|
||||
} else if (process.env.SSRF_REQUEST_FILTER_WHITELIST?.length) {
|
||||
|
||||
@@ -5,13 +5,17 @@ const SocketAuthority = require('../SocketAuthority')
|
||||
const Database = require('../Database')
|
||||
|
||||
const RssFeedManager = require('../managers/RssFeedManager')
|
||||
const Collection = require('../objects/Collection')
|
||||
|
||||
/**
|
||||
* @typedef RequestUserObject
|
||||
* @property {import('../models/User')} user
|
||||
*
|
||||
* @typedef {Request & RequestUserObject} RequestWithUser
|
||||
*
|
||||
* @typedef RequestEntityObject
|
||||
* @property {import('../models/Collection')} collection
|
||||
*
|
||||
* @typedef {RequestWithUser & RequestEntityObject} CollectionControllerRequest
|
||||
*/
|
||||
|
||||
class CollectionController {
|
||||
@@ -25,36 +29,71 @@ class CollectionController {
|
||||
* @param {Response} res
|
||||
*/
|
||||
async create(req, res) {
|
||||
const newCollection = new Collection()
|
||||
req.body.userId = req.user.id
|
||||
if (!newCollection.setData(req.body)) {
|
||||
const reqBody = req.body || {}
|
||||
|
||||
// Validation
|
||||
if (!reqBody.name || !reqBody.libraryId) {
|
||||
return res.status(400).send('Invalid collection data')
|
||||
}
|
||||
if (reqBody.description && typeof reqBody.description !== 'string') {
|
||||
return res.status(400).send('Invalid collection description')
|
||||
}
|
||||
const libraryItemIds = (reqBody.books || []).filter((b) => !!b && typeof b == 'string')
|
||||
if (!libraryItemIds.length) {
|
||||
return res.status(400).send('Invalid collection data. No books')
|
||||
}
|
||||
|
||||
// Create collection record
|
||||
await Database.collectionModel.createFromOld(newCollection)
|
||||
|
||||
// Get library items in collection
|
||||
const libraryItemsInCollection = await Database.libraryItemModel.getForCollection(newCollection)
|
||||
|
||||
// Create collectionBook records
|
||||
let order = 1
|
||||
const collectionBooksToAdd = []
|
||||
for (const libraryItemId of newCollection.books) {
|
||||
const libraryItem = libraryItemsInCollection.find((li) => li.id === libraryItemId)
|
||||
if (libraryItem) {
|
||||
collectionBooksToAdd.push({
|
||||
collectionId: newCollection.id,
|
||||
bookId: libraryItem.media.id,
|
||||
order: order++
|
||||
})
|
||||
// Load library items
|
||||
const libraryItems = await Database.libraryItemModel.findAll({
|
||||
attributes: ['id', 'mediaId', 'mediaType', 'libraryId'],
|
||||
where: {
|
||||
id: libraryItemIds,
|
||||
libraryId: reqBody.libraryId,
|
||||
mediaType: 'book'
|
||||
}
|
||||
}
|
||||
if (collectionBooksToAdd.length) {
|
||||
await Database.createBulkCollectionBooks(collectionBooksToAdd)
|
||||
})
|
||||
if (libraryItems.length !== libraryItemIds.length) {
|
||||
return res.status(400).send('Invalid collection data. Invalid books')
|
||||
}
|
||||
|
||||
const jsonExpanded = newCollection.toJSONExpanded(libraryItemsInCollection)
|
||||
/** @type {import('../models/Collection')} */
|
||||
let newCollection = null
|
||||
|
||||
const transaction = await Database.sequelize.transaction()
|
||||
try {
|
||||
// Create collection
|
||||
newCollection = await Database.collectionModel.create(
|
||||
{
|
||||
libraryId: reqBody.libraryId,
|
||||
name: reqBody.name,
|
||||
description: reqBody.description || null
|
||||
},
|
||||
{ transaction }
|
||||
)
|
||||
|
||||
// Create collectionBooks
|
||||
const collectionBookPayloads = libraryItemIds.map((llid, index) => {
|
||||
const libraryItem = libraryItems.find((li) => li.id === llid)
|
||||
return {
|
||||
collectionId: newCollection.id,
|
||||
bookId: libraryItem.mediaId,
|
||||
order: index + 1
|
||||
}
|
||||
})
|
||||
await Database.collectionBookModel.bulkCreate(collectionBookPayloads, { transaction })
|
||||
|
||||
await transaction.commit()
|
||||
} catch (error) {
|
||||
await transaction.rollback()
|
||||
Logger.error('[CollectionController] create:', error)
|
||||
return res.status(500).send('Failed to create collection')
|
||||
}
|
||||
|
||||
// Load books expanded
|
||||
newCollection.books = await newCollection.getBooksExpandedWithLibraryItem()
|
||||
|
||||
// Note: The old collection model stores expanded libraryItems in the books property
|
||||
const jsonExpanded = newCollection.toOldJSONExpanded()
|
||||
SocketAuthority.emitter('collection_added', jsonExpanded)
|
||||
res.json(jsonExpanded)
|
||||
}
|
||||
@@ -75,7 +114,7 @@ class CollectionController {
|
||||
/**
|
||||
* GET: /api/collections/:id
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {CollectionControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async findOne(req, res) {
|
||||
@@ -94,7 +133,7 @@ class CollectionController {
|
||||
* PATCH: /api/collections/:id
|
||||
* Update collection
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {CollectionControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async update(req, res) {
|
||||
@@ -158,7 +197,7 @@ class CollectionController {
|
||||
*
|
||||
* @this {import('../routers/ApiRouter')}
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {CollectionControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async delete(req, res) {
|
||||
@@ -178,7 +217,7 @@ class CollectionController {
|
||||
* Add a single book to a collection
|
||||
* Req.body { id: <library item id> }
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {CollectionControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async addBook(req, res) {
|
||||
@@ -212,7 +251,7 @@ class CollectionController {
|
||||
* Remove a single book from a collection. Re-order books
|
||||
* TODO: bookId is actually libraryItemId. Clients need updating to use bookId
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {CollectionControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async removeBook(req, res) {
|
||||
@@ -257,29 +296,31 @@ class CollectionController {
|
||||
* Add multiple books to collection
|
||||
* Req.body { books: <Array of library item ids> }
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {CollectionControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async addBatch(req, res) {
|
||||
// filter out invalid libraryItemIds
|
||||
const bookIdsToAdd = (req.body.books || []).filter((b) => !!b && typeof b == 'string')
|
||||
if (!bookIdsToAdd.length) {
|
||||
return res.status(500).send('Invalid request body')
|
||||
return res.status(400).send('Invalid request body')
|
||||
}
|
||||
|
||||
// Get library items associated with ids
|
||||
const libraryItems = await Database.libraryItemModel.findAll({
|
||||
attributes: ['id', 'mediaId', 'mediaType', 'libraryId'],
|
||||
where: {
|
||||
id: {
|
||||
[Sequelize.Op.in]: bookIdsToAdd
|
||||
}
|
||||
},
|
||||
include: {
|
||||
model: Database.bookModel
|
||||
id: bookIdsToAdd,
|
||||
libraryId: req.collection.libraryId,
|
||||
mediaType: 'book'
|
||||
}
|
||||
})
|
||||
if (!libraryItems.length) {
|
||||
return res.status(400).send('Invalid request body. No valid books')
|
||||
}
|
||||
|
||||
// Get collection books already in collection
|
||||
/** @type {import('../models/CollectionBook')[]} */
|
||||
const collectionBooks = await req.collection.getCollectionBooks()
|
||||
|
||||
let order = collectionBooks.length + 1
|
||||
@@ -288,10 +329,10 @@ class CollectionController {
|
||||
|
||||
// Check and set new collection books to add
|
||||
for (const libraryItem of libraryItems) {
|
||||
if (!collectionBooks.some((cb) => cb.bookId === libraryItem.media.id)) {
|
||||
if (!collectionBooks.some((cb) => cb.bookId === libraryItem.mediaId)) {
|
||||
collectionBooksToAdd.push({
|
||||
collectionId: req.collection.id,
|
||||
bookId: libraryItem.media.id,
|
||||
bookId: libraryItem.mediaId,
|
||||
order: order++
|
||||
})
|
||||
hasUpdated = true
|
||||
@@ -302,7 +343,8 @@ class CollectionController {
|
||||
|
||||
let jsonExpanded = null
|
||||
if (hasUpdated) {
|
||||
await Database.createBulkCollectionBooks(collectionBooksToAdd)
|
||||
await Database.collectionBookModel.bulkCreate(collectionBooksToAdd)
|
||||
|
||||
jsonExpanded = await req.collection.getOldJsonExpanded()
|
||||
SocketAuthority.emitter('collection_updated', jsonExpanded)
|
||||
} else {
|
||||
@@ -316,7 +358,7 @@ class CollectionController {
|
||||
* Remove multiple books from collection
|
||||
* Req.body { books: <Array of library item ids> }
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {CollectionControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async removeBatch(req, res) {
|
||||
@@ -329,9 +371,7 @@ class CollectionController {
|
||||
// Get library items associated with ids
|
||||
const libraryItems = await Database.libraryItemModel.findAll({
|
||||
where: {
|
||||
id: {
|
||||
[Sequelize.Op.in]: bookIdsToRemove
|
||||
}
|
||||
id: bookIdsToRemove
|
||||
},
|
||||
include: {
|
||||
model: Database.bookModel
|
||||
@@ -339,6 +379,7 @@ class CollectionController {
|
||||
})
|
||||
|
||||
// Get collection books already in collection
|
||||
/** @type {import('../models/CollectionBook')[]} */
|
||||
const collectionBooks = await req.collection.getCollectionBooks({
|
||||
order: [['order', 'ASC']]
|
||||
})
|
||||
|
||||
@@ -24,6 +24,16 @@ const ShareManager = require('../managers/ShareManager')
|
||||
* @property {import('../models/User')} user
|
||||
*
|
||||
* @typedef {Request & RequestUserObject} RequestWithUser
|
||||
*
|
||||
* @typedef RequestEntityObject
|
||||
* @property {import('../models/LibraryItem')} libraryItem
|
||||
*
|
||||
* @typedef {RequestWithUser & RequestEntityObject} LibraryItemControllerRequest
|
||||
*
|
||||
* @typedef RequestLibraryFileObject
|
||||
* @property {import('../objects/files/LibraryFile')} libraryFile
|
||||
*
|
||||
* @typedef {RequestWithUser & RequestEntityObject & RequestLibraryFileObject} LibraryItemControllerRequestWithFile
|
||||
*/
|
||||
|
||||
class LibraryItemController {
|
||||
@@ -35,17 +45,17 @@ class LibraryItemController {
|
||||
* ?include=progress,rssfeed,downloads,share
|
||||
* ?expanded=1
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async findOne(req, res) {
|
||||
const includeEntities = (req.query.include || '').split(',')
|
||||
if (req.query.expanded == 1) {
|
||||
var item = req.libraryItem.toJSONExpanded()
|
||||
const item = req.libraryItem.toOldJSONExpanded()
|
||||
|
||||
// Include users media progress
|
||||
if (includeEntities.includes('progress')) {
|
||||
var episodeId = req.query.episode || null
|
||||
const episodeId = req.query.episode || null
|
||||
item.userMediaProgress = req.user.getOldMediaProgress(item.id, episodeId)
|
||||
}
|
||||
|
||||
@@ -68,28 +78,32 @@ class LibraryItemController {
|
||||
|
||||
return res.json(item)
|
||||
}
|
||||
res.json(req.libraryItem)
|
||||
res.json(req.libraryItem.toOldJSON())
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH: /api/items/:id
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @deprecated
|
||||
* Use the updateMedia /api/items/:id/media endpoint instead or updateCover /api/items/:id/cover
|
||||
*
|
||||
* @param {LibraryItemControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async update(req, res) {
|
||||
var libraryItem = req.libraryItem
|
||||
// Item has cover and update is removing cover so purge it from cache
|
||||
if (libraryItem.media.coverPath && req.body.media && (req.body.media.coverPath === '' || req.body.media.coverPath === null)) {
|
||||
await CacheManager.purgeCoverCache(libraryItem.id)
|
||||
if (req.libraryItem.media.coverPath && req.body.media && (req.body.media.coverPath === '' || req.body.media.coverPath === null)) {
|
||||
await CacheManager.purgeCoverCache(req.libraryItem.id)
|
||||
}
|
||||
|
||||
const hasUpdates = libraryItem.update(req.body)
|
||||
const oldLibraryItem = Database.libraryItemModel.getOldLibraryItem(req.libraryItem)
|
||||
const hasUpdates = oldLibraryItem.update(req.body)
|
||||
if (hasUpdates) {
|
||||
Logger.debug(`[LibraryItemController] Updated now saving`)
|
||||
await Database.updateLibraryItem(libraryItem)
|
||||
SocketAuthority.emitter('item_updated', libraryItem.toJSONExpanded())
|
||||
await Database.updateLibraryItem(oldLibraryItem)
|
||||
SocketAuthority.emitter('item_updated', oldLibraryItem.toJSONExpanded())
|
||||
}
|
||||
res.json(libraryItem.toJSON())
|
||||
res.json(oldLibraryItem.toJSON())
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -100,7 +114,7 @@ class LibraryItemController {
|
||||
*
|
||||
* @this {import('../routers/ApiRouter')}
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async delete(req, res) {
|
||||
@@ -111,14 +125,14 @@ class LibraryItemController {
|
||||
const authorIds = []
|
||||
const seriesIds = []
|
||||
if (req.libraryItem.isPodcast) {
|
||||
mediaItemIds.push(...req.libraryItem.media.episodes.map((ep) => ep.id))
|
||||
mediaItemIds.push(...req.libraryItem.media.podcastEpisodes.map((ep) => ep.id))
|
||||
} else {
|
||||
mediaItemIds.push(req.libraryItem.media.id)
|
||||
if (req.libraryItem.media.metadata.authors?.length) {
|
||||
authorIds.push(...req.libraryItem.media.metadata.authors.map((au) => au.id))
|
||||
if (req.libraryItem.media.authors?.length) {
|
||||
authorIds.push(...req.libraryItem.media.authors.map((au) => au.id))
|
||||
}
|
||||
if (req.libraryItem.media.metadata.series?.length) {
|
||||
seriesIds.push(...req.libraryItem.media.metadata.series.map((se) => se.id))
|
||||
if (req.libraryItem.media.series?.length) {
|
||||
seriesIds.push(...req.libraryItem.media.series.map((se) => se.id))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,7 +169,7 @@ class LibraryItemController {
|
||||
* GET: /api/items/:id/download
|
||||
* Download library item. Zip file if multiple files.
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async download(req, res) {
|
||||
@@ -164,7 +178,7 @@ class LibraryItemController {
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
const libraryItemPath = req.libraryItem.path
|
||||
const itemTitle = req.libraryItem.media.metadata.title
|
||||
const itemTitle = req.libraryItem.media.title
|
||||
|
||||
Logger.info(`[LibraryItemController] User "${req.user.username}" requested download for item "${itemTitle}" at "${libraryItemPath}"`)
|
||||
|
||||
@@ -194,11 +208,10 @@ class LibraryItemController {
|
||||
*
|
||||
* @this {import('../routers/ApiRouter')}
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async updateMedia(req, res) {
|
||||
const libraryItem = req.libraryItem
|
||||
const mediaPayload = req.body
|
||||
|
||||
if (mediaPayload.url) {
|
||||
@@ -207,44 +220,41 @@ class LibraryItemController {
|
||||
}
|
||||
|
||||
// Book specific
|
||||
if (libraryItem.isBook) {
|
||||
await this.createAuthorsAndSeriesForItemUpdate(mediaPayload, libraryItem.libraryId)
|
||||
if (req.libraryItem.isBook) {
|
||||
await this.createAuthorsAndSeriesForItemUpdate(mediaPayload, req.libraryItem.libraryId)
|
||||
}
|
||||
|
||||
// Podcast specific
|
||||
let isPodcastAutoDownloadUpdated = false
|
||||
if (libraryItem.isPodcast) {
|
||||
if (mediaPayload.autoDownloadEpisodes !== undefined && libraryItem.media.autoDownloadEpisodes !== mediaPayload.autoDownloadEpisodes) {
|
||||
if (req.libraryItem.isPodcast) {
|
||||
if (mediaPayload.autoDownloadEpisodes !== undefined && req.libraryItem.media.autoDownloadEpisodes !== mediaPayload.autoDownloadEpisodes) {
|
||||
isPodcastAutoDownloadUpdated = true
|
||||
} else if (mediaPayload.autoDownloadSchedule !== undefined && libraryItem.media.autoDownloadSchedule !== mediaPayload.autoDownloadSchedule) {
|
||||
} else if (mediaPayload.autoDownloadSchedule !== undefined && req.libraryItem.media.autoDownloadSchedule !== mediaPayload.autoDownloadSchedule) {
|
||||
isPodcastAutoDownloadUpdated = true
|
||||
}
|
||||
}
|
||||
|
||||
// Book specific - Get all series being removed from this item
|
||||
let seriesRemoved = []
|
||||
if (libraryItem.isBook && mediaPayload.metadata?.series) {
|
||||
if (req.libraryItem.isBook && mediaPayload.metadata?.series) {
|
||||
const seriesIdsInUpdate = mediaPayload.metadata.series?.map((se) => se.id) || []
|
||||
seriesRemoved = libraryItem.media.metadata.series.filter((se) => !seriesIdsInUpdate.includes(se.id))
|
||||
seriesRemoved = req.libraryItem.media.series.filter((se) => !seriesIdsInUpdate.includes(se.id))
|
||||
}
|
||||
|
||||
let authorsRemoved = []
|
||||
if (libraryItem.isBook && mediaPayload.metadata?.authors) {
|
||||
if (req.libraryItem.isBook && mediaPayload.metadata?.authors) {
|
||||
const authorIdsInUpdate = mediaPayload.metadata.authors.map((au) => au.id)
|
||||
authorsRemoved = libraryItem.media.metadata.authors.filter((au) => !authorIdsInUpdate.includes(au.id))
|
||||
authorsRemoved = req.libraryItem.media.authors.filter((au) => !authorIdsInUpdate.includes(au.id))
|
||||
}
|
||||
|
||||
const hasUpdates = libraryItem.media.update(mediaPayload) || mediaPayload.url
|
||||
const hasUpdates = (await req.libraryItem.media.updateFromRequest(mediaPayload)) || mediaPayload.url
|
||||
if (hasUpdates) {
|
||||
libraryItem.updatedAt = Date.now()
|
||||
|
||||
if (isPodcastAutoDownloadUpdated) {
|
||||
this.cronManager.checkUpdatePodcastCron(libraryItem)
|
||||
this.cronManager.checkUpdatePodcastCron(req.libraryItem)
|
||||
}
|
||||
|
||||
Logger.debug(`[LibraryItemController] Updated library item media ${libraryItem.media.metadata.title}`)
|
||||
await Database.updateLibraryItem(libraryItem)
|
||||
SocketAuthority.emitter('item_updated', libraryItem.toJSONExpanded())
|
||||
Logger.debug(`[LibraryItemController] Updated library item media ${req.libraryItem.media.title}`)
|
||||
SocketAuthority.emitter('item_updated', req.libraryItem.toOldJSONExpanded())
|
||||
|
||||
if (authorsRemoved.length) {
|
||||
// Check remove empty authors
|
||||
@@ -259,14 +269,14 @@ class LibraryItemController {
|
||||
}
|
||||
res.json({
|
||||
updated: hasUpdates,
|
||||
libraryItem
|
||||
libraryItem: req.libraryItem.toOldJSON()
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* POST: /api/items/:id/cover
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequest} req
|
||||
* @param {Response} res
|
||||
* @param {boolean} [updateAndReturnJson=true]
|
||||
*/
|
||||
@@ -276,15 +286,13 @@ class LibraryItemController {
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
let libraryItem = req.libraryItem
|
||||
|
||||
let result = null
|
||||
if (req.body?.url) {
|
||||
Logger.debug(`[LibraryItemController] Requesting download cover from url "${req.body.url}"`)
|
||||
result = await CoverManager.downloadCoverFromUrl(libraryItem, req.body.url)
|
||||
result = await CoverManager.downloadCoverFromUrlNew(req.body.url, req.libraryItem.id, req.libraryItem.isFile ? null : req.libraryItem.path)
|
||||
} else if (req.files?.cover) {
|
||||
Logger.debug(`[LibraryItemController] Handling uploaded cover`)
|
||||
result = await CoverManager.uploadCover(libraryItem, req.files.cover)
|
||||
result = await CoverManager.uploadCover(req.libraryItem, req.files.cover)
|
||||
} else {
|
||||
return res.status(400).send('Invalid request no file or url')
|
||||
}
|
||||
@@ -296,8 +304,15 @@ class LibraryItemController {
|
||||
}
|
||||
|
||||
if (updateAndReturnJson) {
|
||||
await Database.updateLibraryItem(libraryItem)
|
||||
SocketAuthority.emitter('item_updated', libraryItem.toJSONExpanded())
|
||||
req.libraryItem.media.coverPath = result.cover
|
||||
req.libraryItem.media.changed('coverPath', true)
|
||||
await req.libraryItem.media.save()
|
||||
|
||||
// client uses updatedAt timestamp in URL to force refresh cover
|
||||
req.libraryItem.changed('updatedAt', true)
|
||||
await req.libraryItem.save()
|
||||
|
||||
SocketAuthority.emitter('item_updated', req.libraryItem.toOldJSONExpanded())
|
||||
res.json({
|
||||
success: true,
|
||||
cover: result.cover
|
||||
@@ -308,22 +323,28 @@ class LibraryItemController {
|
||||
/**
|
||||
* PATCH: /api/items/:id/cover
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async updateCover(req, res) {
|
||||
const libraryItem = req.libraryItem
|
||||
if (!req.body.cover) {
|
||||
return res.status(400).send('Invalid request no cover path')
|
||||
}
|
||||
|
||||
const validationResult = await CoverManager.validateCoverPath(req.body.cover, libraryItem)
|
||||
const validationResult = await CoverManager.validateCoverPath(req.body.cover, req.libraryItem)
|
||||
if (validationResult.error) {
|
||||
return res.status(500).send(validationResult.error)
|
||||
}
|
||||
if (validationResult.updated) {
|
||||
await Database.updateLibraryItem(libraryItem)
|
||||
SocketAuthority.emitter('item_updated', libraryItem.toJSONExpanded())
|
||||
req.libraryItem.media.coverPath = validationResult.cover
|
||||
req.libraryItem.media.changed('coverPath', true)
|
||||
await req.libraryItem.media.save()
|
||||
|
||||
// client uses updatedAt timestamp in URL to force refresh cover
|
||||
req.libraryItem.changed('updatedAt', true)
|
||||
await req.libraryItem.save()
|
||||
|
||||
SocketAuthority.emitter('item_updated', req.libraryItem.toOldJSONExpanded())
|
||||
}
|
||||
res.json({
|
||||
success: true,
|
||||
@@ -334,17 +355,22 @@ class LibraryItemController {
|
||||
/**
|
||||
* DELETE: /api/items/:id/cover
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async removeCover(req, res) {
|
||||
var libraryItem = req.libraryItem
|
||||
if (req.libraryItem.media.coverPath) {
|
||||
req.libraryItem.media.coverPath = null
|
||||
req.libraryItem.media.changed('coverPath', true)
|
||||
await req.libraryItem.media.save()
|
||||
|
||||
if (libraryItem.media.coverPath) {
|
||||
libraryItem.updateMediaCover('')
|
||||
await CacheManager.purgeCoverCache(libraryItem.id)
|
||||
await Database.updateLibraryItem(libraryItem)
|
||||
SocketAuthority.emitter('item_updated', libraryItem.toJSONExpanded())
|
||||
// client uses updatedAt timestamp in URL to force refresh cover
|
||||
req.libraryItem.changed('updatedAt', true)
|
||||
await req.libraryItem.save()
|
||||
|
||||
await CacheManager.purgeCoverCache(req.libraryItem.id)
|
||||
|
||||
SocketAuthority.emitter('item_updated', req.libraryItem.toOldJSONExpanded())
|
||||
}
|
||||
|
||||
res.sendStatus(200)
|
||||
@@ -353,7 +379,7 @@ class LibraryItemController {
|
||||
/**
|
||||
* GET: /api/items/:id/cover
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async getCover(req, res) {
|
||||
@@ -395,11 +421,11 @@ class LibraryItemController {
|
||||
*
|
||||
* @this {import('../routers/ApiRouter')}
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
startPlaybackSession(req, res) {
|
||||
if (!req.libraryItem.media.numTracks) {
|
||||
if (!req.libraryItem.hasAudioTracks) {
|
||||
Logger.error(`[LibraryItemController] startPlaybackSession cannot playback ${req.libraryItem.id}`)
|
||||
return res.sendStatus(404)
|
||||
}
|
||||
@@ -412,18 +438,18 @@ class LibraryItemController {
|
||||
*
|
||||
* @this {import('../routers/ApiRouter')}
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
startEpisodePlaybackSession(req, res) {
|
||||
var libraryItem = req.libraryItem
|
||||
if (!libraryItem.media.numTracks) {
|
||||
Logger.error(`[LibraryItemController] startPlaybackSession cannot playback ${libraryItem.id}`)
|
||||
return res.sendStatus(404)
|
||||
if (!req.libraryItem.isPodcast) {
|
||||
Logger.error(`[LibraryItemController] startEpisodePlaybackSession invalid media type ${req.libraryItem.id}`)
|
||||
return res.sendStatus(400)
|
||||
}
|
||||
var episodeId = req.params.episodeId
|
||||
if (!libraryItem.media.episodes.find((ep) => ep.id === episodeId)) {
|
||||
Logger.error(`[LibraryItemController] startPlaybackSession episode ${episodeId} not found for item ${libraryItem.id}`)
|
||||
|
||||
const episodeId = req.params.episodeId
|
||||
if (!req.libraryItem.media.podcastEpisodes.some((ep) => ep.id === episodeId)) {
|
||||
Logger.error(`[LibraryItemController] startPlaybackSession episode ${episodeId} not found for item ${req.libraryItem.id}`)
|
||||
return res.sendStatus(404)
|
||||
}
|
||||
|
||||
@@ -433,30 +459,55 @@ class LibraryItemController {
|
||||
/**
|
||||
* PATCH: /api/items/:id/tracks
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async updateTracks(req, res) {
|
||||
var libraryItem = req.libraryItem
|
||||
var orderedFileData = req.body.orderedFileData
|
||||
if (!libraryItem.media.updateAudioTracks) {
|
||||
Logger.error(`[LibraryItemController] updateTracks invalid media type ${libraryItem.id}`)
|
||||
return res.sendStatus(500)
|
||||
const orderedFileData = req.body?.orderedFileData
|
||||
|
||||
if (!req.libraryItem.isBook) {
|
||||
Logger.error(`[LibraryItemController] updateTracks invalid media type ${req.libraryItem.id}`)
|
||||
return res.sendStatus(400)
|
||||
}
|
||||
libraryItem.media.updateAudioTracks(orderedFileData)
|
||||
await Database.updateLibraryItem(libraryItem)
|
||||
SocketAuthority.emitter('item_updated', libraryItem.toJSONExpanded())
|
||||
res.json(libraryItem.toJSON())
|
||||
if (!Array.isArray(orderedFileData) || !orderedFileData.length) {
|
||||
Logger.error(`[LibraryItemController] updateTracks invalid orderedFileData ${req.libraryItem.id}`)
|
||||
return res.sendStatus(400)
|
||||
}
|
||||
// Ensure that each orderedFileData has a valid ino and is in the book audioFiles
|
||||
if (orderedFileData.some((fileData) => !fileData?.ino || !req.libraryItem.media.audioFiles.some((af) => af.ino === fileData.ino))) {
|
||||
Logger.error(`[LibraryItemController] updateTracks invalid orderedFileData ${req.libraryItem.id}`)
|
||||
return res.sendStatus(400)
|
||||
}
|
||||
|
||||
let index = 1
|
||||
const updatedAudioFiles = orderedFileData.map((fileData) => {
|
||||
const audioFile = req.libraryItem.media.audioFiles.find((af) => af.ino === fileData.ino)
|
||||
audioFile.manuallyVerified = true
|
||||
audioFile.exclude = !!fileData.exclude
|
||||
if (audioFile.exclude) {
|
||||
audioFile.index = -1
|
||||
} else {
|
||||
audioFile.index = index++
|
||||
}
|
||||
return audioFile
|
||||
})
|
||||
updatedAudioFiles.sort((a, b) => a.index - b.index)
|
||||
|
||||
req.libraryItem.media.audioFiles = updatedAudioFiles
|
||||
req.libraryItem.media.changed('audioFiles', true)
|
||||
await req.libraryItem.media.save()
|
||||
|
||||
SocketAuthority.emitter('item_updated', req.libraryItem.toOldJSONExpanded())
|
||||
res.json(req.libraryItem.toOldJSON())
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/items/:id/match
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async match(req, res) {
|
||||
const libraryItem = req.libraryItem
|
||||
const reqBody = req.body || {}
|
||||
|
||||
const options = {}
|
||||
@@ -473,7 +524,8 @@ class LibraryItemController {
|
||||
options.overrideDetails = !!reqBody.overrideDetails
|
||||
}
|
||||
|
||||
var matchResult = await Scanner.quickMatchLibraryItem(this, libraryItem, options)
|
||||
const oldLibraryItem = Database.libraryItemModel.getOldLibraryItem(req.libraryItem)
|
||||
var matchResult = await Scanner.quickMatchLibraryItem(this, oldLibraryItem, options)
|
||||
res.json(matchResult)
|
||||
}
|
||||
|
||||
@@ -741,7 +793,7 @@ class LibraryItemController {
|
||||
/**
|
||||
* POST: /api/items/:id/scan
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async scan(req, res) {
|
||||
@@ -765,7 +817,7 @@ class LibraryItemController {
|
||||
/**
|
||||
* GET: /api/items/:id/metadata-object
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
getMetadataObject(req, res) {
|
||||
@@ -774,7 +826,7 @@ class LibraryItemController {
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
if (req.libraryItem.isMissing || !req.libraryItem.hasAudioFiles || !req.libraryItem.isBook) {
|
||||
if (req.libraryItem.isMissing || !req.libraryItem.isBook || !req.libraryItem.media.includedAudioFiles.length) {
|
||||
Logger.error(`[LibraryItemController] Invalid library item`)
|
||||
return res.sendStatus(500)
|
||||
}
|
||||
@@ -785,7 +837,7 @@ class LibraryItemController {
|
||||
/**
|
||||
* POST: /api/items/:id/chapters
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async updateMediaChapters(req, res) {
|
||||
@@ -794,26 +846,51 @@ class LibraryItemController {
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
if (req.libraryItem.isMissing || !req.libraryItem.hasAudioFiles || !req.libraryItem.isBook) {
|
||||
if (req.libraryItem.isMissing || !req.libraryItem.isBook || !req.libraryItem.media.hasAudioTracks) {
|
||||
Logger.error(`[LibraryItemController] Invalid library item`)
|
||||
return res.sendStatus(500)
|
||||
}
|
||||
|
||||
if (!req.body.chapters) {
|
||||
if (!Array.isArray(req.body.chapters) || req.body.chapters.some((c) => !c.title || typeof c.title !== 'string' || c.start === undefined || typeof c.start !== 'number' || c.end === undefined || typeof c.end !== 'number')) {
|
||||
Logger.error(`[LibraryItemController] Invalid payload`)
|
||||
return res.sendStatus(400)
|
||||
}
|
||||
|
||||
const chapters = req.body.chapters || []
|
||||
const wasUpdated = req.libraryItem.media.updateChapters(chapters)
|
||||
if (wasUpdated) {
|
||||
await Database.updateLibraryItem(req.libraryItem)
|
||||
SocketAuthority.emitter('item_updated', req.libraryItem.toJSONExpanded())
|
||||
|
||||
let hasUpdates = false
|
||||
if (chapters.length !== req.libraryItem.media.chapters.length) {
|
||||
req.libraryItem.media.chapters = chapters.map((c, index) => {
|
||||
return {
|
||||
id: index,
|
||||
title: c.title,
|
||||
start: c.start,
|
||||
end: c.end
|
||||
}
|
||||
})
|
||||
hasUpdates = true
|
||||
} else {
|
||||
for (const [index, chapter] of chapters.entries()) {
|
||||
const currentChapter = req.libraryItem.media.chapters[index]
|
||||
if (currentChapter.title !== chapter.title || currentChapter.start !== chapter.start || currentChapter.end !== chapter.end) {
|
||||
currentChapter.title = chapter.title
|
||||
currentChapter.start = chapter.start
|
||||
currentChapter.end = chapter.end
|
||||
hasUpdates = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (hasUpdates) {
|
||||
req.libraryItem.media.changed('chapters', true)
|
||||
await req.libraryItem.media.save()
|
||||
|
||||
SocketAuthority.emitter('item_updated', req.libraryItem.toOldJSONExpanded())
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
updated: wasUpdated
|
||||
updated: hasUpdates
|
||||
})
|
||||
}
|
||||
|
||||
@@ -821,7 +898,7 @@ class LibraryItemController {
|
||||
* GET: /api/items/:id/ffprobe/:fileid
|
||||
* FFProbe JSON result from audio file
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async getFFprobeData(req, res) {
|
||||
@@ -829,25 +906,21 @@ class LibraryItemController {
|
||||
Logger.error(`[LibraryItemController] Non-admin user "${req.user.username}" attempted to get ffprobe data`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
if (req.libraryFile.fileType !== 'audio') {
|
||||
Logger.error(`[LibraryItemController] Invalid filetype "${req.libraryFile.fileType}" for fileid "${req.params.fileid}". Expected audio file`)
|
||||
return res.sendStatus(400)
|
||||
}
|
||||
|
||||
const audioFile = req.libraryItem.media.findFileWithInode(req.params.fileid)
|
||||
const audioFile = req.libraryItem.getAudioFileWithIno(req.params.fileid)
|
||||
if (!audioFile) {
|
||||
Logger.error(`[LibraryItemController] Audio file not found with inode value ${req.params.fileid}`)
|
||||
return res.sendStatus(404)
|
||||
}
|
||||
|
||||
const ffprobeData = await AudioFileScanner.probeAudioFile(audioFile)
|
||||
const ffprobeData = await AudioFileScanner.probeAudioFile(audioFile.metadata.path)
|
||||
res.json(ffprobeData)
|
||||
}
|
||||
|
||||
/**
|
||||
* GET api/items/:id/file/:fileid
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequestWithFile} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async getLibraryFile(req, res) {
|
||||
@@ -870,7 +943,7 @@ class LibraryItemController {
|
||||
/**
|
||||
* DELETE api/items/:id/file/:fileid
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequestWithFile} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async deleteLibraryFile(req, res) {
|
||||
@@ -881,17 +954,35 @@ class LibraryItemController {
|
||||
await fs.remove(libraryFile.metadata.path).catch((error) => {
|
||||
Logger.error(`[LibraryItemController] Failed to delete library file at "${libraryFile.metadata.path}"`, error)
|
||||
})
|
||||
req.libraryItem.removeLibraryFile(req.params.fileid)
|
||||
|
||||
if (req.libraryItem.media.removeFileWithInode(req.params.fileid)) {
|
||||
// If book has no more media files then mark it as missing
|
||||
if (req.libraryItem.mediaType === 'book' && !req.libraryItem.media.hasMediaEntities) {
|
||||
req.libraryItem.setMissing()
|
||||
req.libraryItem.libraryFiles = req.libraryItem.libraryFiles.filter((lf) => lf.ino !== req.params.fileid)
|
||||
req.libraryItem.changed('libraryFiles', true)
|
||||
|
||||
if (req.libraryItem.isBook) {
|
||||
if (req.libraryItem.media.audioFiles.some((af) => af.ino === req.params.fileid)) {
|
||||
req.libraryItem.media.audioFiles = req.libraryItem.media.audioFiles.filter((af) => af.ino !== req.params.fileid)
|
||||
req.libraryItem.media.changed('audioFiles', true)
|
||||
} else if (req.libraryItem.media.ebookFile?.ino === req.params.fileid) {
|
||||
req.libraryItem.media.ebookFile = null
|
||||
req.libraryItem.media.changed('ebookFile', true)
|
||||
}
|
||||
if (!req.libraryItem.media.hasMediaFiles) {
|
||||
req.libraryItem.isMissing = true
|
||||
}
|
||||
} else if (req.libraryItem.media.podcastEpisodes.some((ep) => ep.audioFile.ino === req.params.fileid)) {
|
||||
const episodeToRemove = req.libraryItem.media.podcastEpisodes.find((ep) => ep.audioFile.ino === req.params.fileid)
|
||||
await episodeToRemove.destroy()
|
||||
|
||||
req.libraryItem.media.podcastEpisodes = req.libraryItem.media.podcastEpisodes.filter((ep) => ep.audioFile.ino !== req.params.fileid)
|
||||
}
|
||||
req.libraryItem.updatedAt = Date.now()
|
||||
await Database.updateLibraryItem(req.libraryItem)
|
||||
SocketAuthority.emitter('item_updated', req.libraryItem.toJSONExpanded())
|
||||
|
||||
if (req.libraryItem.media.changed()) {
|
||||
await req.libraryItem.media.save()
|
||||
}
|
||||
|
||||
await req.libraryItem.save()
|
||||
|
||||
SocketAuthority.emitter('item_updated', req.libraryItem.toOldJSONExpanded())
|
||||
res.sendStatus(200)
|
||||
}
|
||||
|
||||
@@ -899,7 +990,7 @@ class LibraryItemController {
|
||||
* GET api/items/:id/file/:fileid/download
|
||||
* Same as GET api/items/:id/file/:fileid but allows logging and restricting downloads
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequestWithFile} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async downloadLibraryFile(req, res) {
|
||||
@@ -911,7 +1002,7 @@ class LibraryItemController {
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
Logger.info(`[LibraryItemController] User "${req.user.username}" requested download for item "${req.libraryItem.media.metadata.title}" file at "${libraryFile.metadata.path}"`)
|
||||
Logger.info(`[LibraryItemController] User "${req.user.username}" requested download for item "${req.libraryItem.media.title}" file at "${libraryFile.metadata.path}"`)
|
||||
|
||||
if (global.XAccel) {
|
||||
const encodedURI = encodeUriPath(global.XAccel + libraryFile.metadata.path)
|
||||
@@ -947,13 +1038,13 @@ class LibraryItemController {
|
||||
* fileid is only required when reading a supplementary ebook
|
||||
* when no fileid is passed in the primary ebook will be returned
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async getEBookFile(req, res) {
|
||||
let ebookFile = null
|
||||
if (req.params.fileid) {
|
||||
ebookFile = req.libraryItem.libraryFiles.find((lf) => lf.ino === req.params.fileid)
|
||||
ebookFile = req.libraryItem.getLibraryFileWithIno(req.params.fileid)
|
||||
if (!ebookFile?.isEBookFile) {
|
||||
Logger.error(`[LibraryItemController] Invalid ebook file id "${req.params.fileid}"`)
|
||||
return res.status(400).send('Invalid ebook file id')
|
||||
@@ -963,12 +1054,12 @@ class LibraryItemController {
|
||||
}
|
||||
|
||||
if (!ebookFile) {
|
||||
Logger.error(`[LibraryItemController] No ebookFile for library item "${req.libraryItem.media.metadata.title}"`)
|
||||
Logger.error(`[LibraryItemController] No ebookFile for library item "${req.libraryItem.media.title}"`)
|
||||
return res.sendStatus(404)
|
||||
}
|
||||
const ebookFilePath = ebookFile.metadata.path
|
||||
|
||||
Logger.info(`[LibraryItemController] User "${req.user.username}" requested download for item "${req.libraryItem.media.metadata.title}" ebook at "${ebookFilePath}"`)
|
||||
Logger.info(`[LibraryItemController] User "${req.user.username}" requested download for item "${req.libraryItem.media.title}" ebook at "${ebookFilePath}"`)
|
||||
|
||||
if (global.XAccel) {
|
||||
const encodedURI = encodeUriPath(global.XAccel + ebookFilePath)
|
||||
@@ -991,28 +1082,55 @@ class LibraryItemController {
|
||||
* if an ebook file is the primary ebook, then it will be changed to supplementary
|
||||
* if an ebook file is supplementary, then it will be changed to primary
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {LibraryItemControllerRequestWithFile} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async updateEbookFileStatus(req, res) {
|
||||
const ebookLibraryFile = req.libraryItem.libraryFiles.find((lf) => lf.ino === req.params.fileid)
|
||||
if (!ebookLibraryFile?.isEBookFile) {
|
||||
if (!req.libraryItem.isBook) {
|
||||
Logger.error(`[LibraryItemController] Invalid media type for ebook file status update`)
|
||||
return res.sendStatus(400)
|
||||
}
|
||||
if (!req.libraryFile?.isEBookFile) {
|
||||
Logger.error(`[LibraryItemController] Invalid ebook file id "${req.params.fileid}"`)
|
||||
return res.status(400).send('Invalid ebook file id')
|
||||
}
|
||||
|
||||
const ebookLibraryFile = req.libraryFile
|
||||
let primaryEbookFile = null
|
||||
|
||||
const ebookLibraryFileInos = req.libraryItem
|
||||
.getLibraryFiles()
|
||||
.filter((lf) => lf.isEBookFile)
|
||||
.map((lf) => lf.ino)
|
||||
|
||||
if (ebookLibraryFile.isSupplementary) {
|
||||
Logger.info(`[LibraryItemController] Updating ebook file "${ebookLibraryFile.metadata.filename}" to primary`)
|
||||
req.libraryItem.setPrimaryEbook(ebookLibraryFile)
|
||||
|
||||
primaryEbookFile = ebookLibraryFile.toJSON()
|
||||
delete primaryEbookFile.isSupplementary
|
||||
delete primaryEbookFile.fileType
|
||||
primaryEbookFile.ebookFormat = ebookLibraryFile.metadata.format
|
||||
} else {
|
||||
Logger.info(`[LibraryItemController] Updating ebook file "${ebookLibraryFile.metadata.filename}" to supplementary`)
|
||||
ebookLibraryFile.isSupplementary = true
|
||||
req.libraryItem.setPrimaryEbook(null)
|
||||
}
|
||||
|
||||
req.libraryItem.updatedAt = Date.now()
|
||||
await Database.updateLibraryItem(req.libraryItem)
|
||||
SocketAuthority.emitter('item_updated', req.libraryItem.toJSONExpanded())
|
||||
req.libraryItem.media.ebookFile = primaryEbookFile
|
||||
req.libraryItem.media.changed('ebookFile', true)
|
||||
await req.libraryItem.media.save()
|
||||
|
||||
req.libraryItem.libraryFiles = req.libraryItem.libraryFiles.map((lf) => {
|
||||
if (ebookLibraryFileInos.includes(lf.ino)) {
|
||||
lf.isSupplementary = lf.ino !== primaryEbookFile?.ino
|
||||
}
|
||||
return lf
|
||||
})
|
||||
req.libraryItem.changed('libraryFiles', true)
|
||||
|
||||
req.libraryItem.isMissing = !req.libraryItem.media.hasMediaFiles
|
||||
|
||||
await req.libraryItem.save()
|
||||
|
||||
SocketAuthority.emitter('item_updated', req.libraryItem.toOldJSONExpanded())
|
||||
res.sendStatus(200)
|
||||
}
|
||||
|
||||
@@ -1023,7 +1141,7 @@ class LibraryItemController {
|
||||
* @param {NextFunction} next
|
||||
*/
|
||||
async middleware(req, res, next) {
|
||||
req.libraryItem = await Database.libraryItemModel.getOldById(req.params.id)
|
||||
req.libraryItem = await Database.libraryItemModel.getExpandedById(req.params.id)
|
||||
if (!req.libraryItem?.media) return res.sendStatus(404)
|
||||
|
||||
// Check user can access this library item
|
||||
@@ -1033,7 +1151,7 @@ class LibraryItemController {
|
||||
|
||||
// For library file routes, get the library file
|
||||
if (req.params.fileid) {
|
||||
req.libraryFile = req.libraryItem.libraryFiles.find((lf) => lf.ino === req.params.fileid)
|
||||
req.libraryFile = req.libraryItem.getLibraryFileWithIno(req.params.fileid)
|
||||
if (!req.libraryFile) {
|
||||
Logger.error(`[LibraryItemController] Library file "${req.params.fileid}" does not exist for library item`)
|
||||
return res.sendStatus(404)
|
||||
|
||||
@@ -3,13 +3,16 @@ const Logger = require('../Logger')
|
||||
const SocketAuthority = require('../SocketAuthority')
|
||||
const Database = require('../Database')
|
||||
|
||||
const Playlist = require('../objects/Playlist')
|
||||
|
||||
/**
|
||||
* @typedef RequestUserObject
|
||||
* @property {import('../models/User')} user
|
||||
*
|
||||
* @typedef {Request & RequestUserObject} RequestWithUser
|
||||
*
|
||||
* @typedef RequestEntityObject
|
||||
* @property {import('../models/Playlist')} playlist
|
||||
*
|
||||
* @typedef {RequestWithUser & RequestEntityObject} PlaylistControllerRequest
|
||||
*/
|
||||
|
||||
class PlaylistController {
|
||||
@@ -23,48 +26,103 @@ class PlaylistController {
|
||||
* @param {Response} res
|
||||
*/
|
||||
async create(req, res) {
|
||||
const oldPlaylist = new Playlist()
|
||||
req.body.userId = req.user.id
|
||||
const success = oldPlaylist.setData(req.body)
|
||||
if (!success) {
|
||||
return res.status(400).send('Invalid playlist request data')
|
||||
const reqBody = req.body || {}
|
||||
|
||||
// Validation
|
||||
if (!reqBody.name || !reqBody.libraryId) {
|
||||
return res.status(400).send('Invalid playlist data')
|
||||
}
|
||||
if (reqBody.description && typeof reqBody.description !== 'string') {
|
||||
return res.status(400).send('Invalid playlist description')
|
||||
}
|
||||
const items = reqBody.items || []
|
||||
const isPodcast = items.some((i) => i.episodeId)
|
||||
const libraryItemIds = new Set()
|
||||
for (const item of items) {
|
||||
if (!item.libraryItemId || typeof item.libraryItemId !== 'string') {
|
||||
return res.status(400).send('Invalid playlist item')
|
||||
}
|
||||
if (isPodcast && (!item.episodeId || typeof item.episodeId !== 'string')) {
|
||||
return res.status(400).send('Invalid playlist item episodeId')
|
||||
} else if (!isPodcast && item.episodeId) {
|
||||
return res.status(400).send('Invalid playlist item episodeId')
|
||||
}
|
||||
libraryItemIds.add(item.libraryItemId)
|
||||
}
|
||||
|
||||
// Create Playlist record
|
||||
const newPlaylist = await Database.playlistModel.createFromOld(oldPlaylist)
|
||||
|
||||
// Lookup all library items in playlist
|
||||
const libraryItemIds = oldPlaylist.items.map((i) => i.libraryItemId).filter((i) => i)
|
||||
const libraryItemsInPlaylist = await Database.libraryItemModel.findAll({
|
||||
// Load library items
|
||||
const libraryItems = await Database.libraryItemModel.findAll({
|
||||
attributes: ['id', 'mediaId', 'mediaType', 'libraryId'],
|
||||
where: {
|
||||
id: libraryItemIds
|
||||
id: Array.from(libraryItemIds),
|
||||
libraryId: reqBody.libraryId,
|
||||
mediaType: isPodcast ? 'podcast' : 'book'
|
||||
}
|
||||
})
|
||||
if (libraryItems.length !== libraryItemIds.size) {
|
||||
return res.status(400).send('Invalid playlist data. Invalid items')
|
||||
}
|
||||
|
||||
// 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++
|
||||
// Validate podcast episodes
|
||||
if (isPodcast) {
|
||||
const podcastEpisodeIds = items.map((i) => i.episodeId)
|
||||
const podcastEpisodes = await Database.podcastEpisodeModel.findAll({
|
||||
attributes: ['id'],
|
||||
where: {
|
||||
id: podcastEpisodeIds
|
||||
}
|
||||
})
|
||||
}
|
||||
if (mediaItemsToAdd.length) {
|
||||
await Database.createBulkPlaylistMediaItems(mediaItemsToAdd)
|
||||
if (podcastEpisodes.length !== podcastEpisodeIds.length) {
|
||||
return res.status(400).send('Invalid playlist data. Invalid podcast episodes')
|
||||
}
|
||||
}
|
||||
|
||||
const jsonExpanded = await newPlaylist.getOldJsonExpanded()
|
||||
SocketAuthority.clientEmitter(newPlaylist.userId, 'playlist_added', jsonExpanded)
|
||||
res.json(jsonExpanded)
|
||||
const transaction = await Database.sequelize.transaction()
|
||||
try {
|
||||
// Create playlist
|
||||
const newPlaylist = await Database.playlistModel.create(
|
||||
{
|
||||
libraryId: reqBody.libraryId,
|
||||
userId: req.user.id,
|
||||
name: reqBody.name,
|
||||
description: reqBody.description || null
|
||||
},
|
||||
{ transaction }
|
||||
)
|
||||
|
||||
// Create playlistMediaItems
|
||||
const playlistItemPayloads = []
|
||||
for (const [index, item] of items.entries()) {
|
||||
const libraryItem = libraryItems.find((li) => li.id === item.libraryItemId)
|
||||
playlistItemPayloads.push({
|
||||
playlistId: newPlaylist.id,
|
||||
mediaItemId: item.episodeId || libraryItem.mediaId,
|
||||
mediaItemType: item.episodeId ? 'podcastEpisode' : 'book',
|
||||
order: index + 1
|
||||
})
|
||||
}
|
||||
|
||||
await Database.playlistMediaItemModel.bulkCreate(playlistItemPayloads, { transaction })
|
||||
|
||||
await transaction.commit()
|
||||
|
||||
newPlaylist.playlistMediaItems = await newPlaylist.getMediaItemsExpandedWithLibraryItem()
|
||||
|
||||
const jsonExpanded = newPlaylist.toOldJSONExpanded()
|
||||
SocketAuthority.clientEmitter(newPlaylist.userId, 'playlist_added', jsonExpanded)
|
||||
res.json(jsonExpanded)
|
||||
} catch (error) {
|
||||
await transaction.rollback()
|
||||
Logger.error('[PlaylistController] create:', error)
|
||||
res.status(500).send('Failed to create playlist')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated - Use /api/libraries/:libraryId/playlists
|
||||
* This is not used by Abs web client or mobile apps
|
||||
* TODO: Remove this endpoint or make it the primary
|
||||
*
|
||||
* GET: /api/playlists
|
||||
* Get all playlists for user
|
||||
*
|
||||
@@ -72,68 +130,89 @@ class PlaylistController {
|
||||
* @param {Response} res
|
||||
*/
|
||||
async findAllForUser(req, res) {
|
||||
const playlistsForUser = await Database.playlistModel.findAll({
|
||||
where: {
|
||||
userId: req.user.id
|
||||
}
|
||||
})
|
||||
const playlists = []
|
||||
for (const playlist of playlistsForUser) {
|
||||
const jsonExpanded = await playlist.getOldJsonExpanded()
|
||||
playlists.push(jsonExpanded)
|
||||
}
|
||||
const playlistsForUser = await Database.playlistModel.getOldPlaylistsForUserAndLibrary(req.user.id)
|
||||
res.json({
|
||||
playlists
|
||||
playlists: playlistsForUser
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* GET: /api/playlists/:id
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {PlaylistControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async findOne(req, res) {
|
||||
const jsonExpanded = await req.playlist.getOldJsonExpanded()
|
||||
res.json(jsonExpanded)
|
||||
req.playlist.playlistMediaItems = await req.playlist.getMediaItemsExpandedWithLibraryItem()
|
||||
res.json(req.playlist.toOldJSONExpanded())
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH: /api/playlists/:id
|
||||
* Update playlist
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* Used for updating name and description or reordering items
|
||||
*
|
||||
* @param {PlaylistControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
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
|
||||
// Validation
|
||||
const reqBody = req.body || {}
|
||||
if (reqBody.libraryId || reqBody.userId) {
|
||||
// Could allow support for this if needed with additional validation
|
||||
return res.status(400).send('Invalid playlist data. Cannot update libraryId or userId')
|
||||
}
|
||||
if (reqBody.name && typeof reqBody.name !== 'string') {
|
||||
return res.status(400).send('Invalid playlist name')
|
||||
}
|
||||
if (reqBody.description && typeof reqBody.description !== 'string') {
|
||||
return res.status(400).send('Invalid playlist description')
|
||||
}
|
||||
if (reqBody.items && (!Array.isArray(reqBody.items) || reqBody.items.some((i) => !i.libraryItemId || typeof i.libraryItemId !== 'string' || (i.episodeId && typeof i.episodeId !== 'string')))) {
|
||||
return res.status(400).send('Invalid playlist items')
|
||||
}
|
||||
|
||||
// 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 playlistUpdatePayload = {}
|
||||
if (reqBody.name) playlistUpdatePayload.name = reqBody.name
|
||||
if (reqBody.description) playlistUpdatePayload.description = reqBody.description
|
||||
|
||||
// Update name and description
|
||||
let wasUpdated = false
|
||||
if (Object.keys(playlistUpdatePayload).length) {
|
||||
req.playlist.set(playlistUpdatePayload)
|
||||
const changed = req.playlist.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 set then update order of playlist media items
|
||||
if (reqBody.items?.length) {
|
||||
const libraryItemIds = Array.from(new Set(reqBody.items.map((i) => i.libraryItemId)))
|
||||
const libraryItems = await Database.libraryItemModel.findAll({
|
||||
attributes: ['id', 'mediaId', 'mediaType'],
|
||||
where: {
|
||||
id: libraryItemIds
|
||||
}
|
||||
})
|
||||
const existingPlaylistMediaItems = await updatedPlaylist.getPlaylistMediaItems({
|
||||
if (libraryItems.length !== libraryItemIds.length) {
|
||||
return res.status(400).send('Invalid playlist items. Items not found')
|
||||
}
|
||||
/** @type {import('../models/PlaylistMediaItem')[]} */
|
||||
const existingPlaylistMediaItems = await req.playlist.getPlaylistMediaItems({
|
||||
order: [['order', 'ASC']]
|
||||
})
|
||||
if (existingPlaylistMediaItems.length !== reqBody.items.length) {
|
||||
return res.status(400).send('Invalid playlist items. Length mismatch')
|
||||
}
|
||||
|
||||
// Set an array of mediaItemId
|
||||
const newMediaItemIdOrder = []
|
||||
for (const item of req.body.items) {
|
||||
for (const item of reqBody.items) {
|
||||
const libraryItem = libraryItems.find((li) => li.id === item.libraryItemId)
|
||||
if (!libraryItem) {
|
||||
continue
|
||||
}
|
||||
const mediaItemId = item.episodeId || libraryItem.mediaId
|
||||
newMediaItemIdOrder.push(mediaItemId)
|
||||
}
|
||||
@@ -146,21 +225,21 @@ class PlaylistController {
|
||||
})
|
||||
|
||||
// Update order on playlistMediaItem records
|
||||
let order = 1
|
||||
for (const playlistMediaItem of existingPlaylistMediaItems) {
|
||||
if (playlistMediaItem.order !== order) {
|
||||
for (const [index, playlistMediaItem] of existingPlaylistMediaItems.entries()) {
|
||||
if (playlistMediaItem.order !== index + 1) {
|
||||
await playlistMediaItem.update({
|
||||
order
|
||||
order: index + 1
|
||||
})
|
||||
wasUpdated = true
|
||||
}
|
||||
order++
|
||||
}
|
||||
}
|
||||
|
||||
const jsonExpanded = await updatedPlaylist.getOldJsonExpanded()
|
||||
req.playlist.playlistMediaItems = await req.playlist.getMediaItemsExpandedWithLibraryItem()
|
||||
|
||||
const jsonExpanded = req.playlist.toOldJSONExpanded()
|
||||
if (wasUpdated) {
|
||||
SocketAuthority.clientEmitter(updatedPlaylist.userId, 'playlist_updated', jsonExpanded)
|
||||
SocketAuthority.clientEmitter(req.playlist.userId, 'playlist_updated', jsonExpanded)
|
||||
}
|
||||
res.json(jsonExpanded)
|
||||
}
|
||||
@@ -169,11 +248,13 @@ class PlaylistController {
|
||||
* DELETE: /api/playlists/:id
|
||||
* Remove playlist
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {PlaylistControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async delete(req, res) {
|
||||
const jsonExpanded = await req.playlist.getOldJsonExpanded()
|
||||
req.playlist.playlistMediaItems = await req.playlist.getMediaItemsExpandedWithLibraryItem()
|
||||
const jsonExpanded = req.playlist.toOldJSONExpanded()
|
||||
|
||||
await req.playlist.destroy()
|
||||
SocketAuthority.clientEmitter(jsonExpanded.userId, 'playlist_removed', jsonExpanded)
|
||||
res.sendStatus(200)
|
||||
@@ -183,12 +264,13 @@ class PlaylistController {
|
||||
* POST: /api/playlists/:id/item
|
||||
* Add item to playlist
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* This is not used by Abs web client or mobile apps. Only the batch endpoints are used.
|
||||
*
|
||||
* @param {PlaylistControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async addItem(req, res) {
|
||||
const oldPlaylist = await Database.playlistModel.getById(req.playlist.id)
|
||||
const itemToAdd = req.body
|
||||
const itemToAdd = req.body || {}
|
||||
|
||||
if (!itemToAdd.libraryItemId) {
|
||||
return res.status(400).send('Request body has no libraryItemId')
|
||||
@@ -198,12 +280,9 @@ class PlaylistController {
|
||||
if (!libraryItem) {
|
||||
return res.status(400).send('Library item not found')
|
||||
}
|
||||
if (libraryItem.libraryId !== oldPlaylist.libraryId) {
|
||||
if (libraryItem.libraryId !== req.playlist.libraryId) {
|
||||
return res.status(400).send('Library item in different library')
|
||||
}
|
||||
if (oldPlaylist.containsItem(itemToAdd)) {
|
||||
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')
|
||||
}
|
||||
@@ -211,15 +290,38 @@ class PlaylistController {
|
||||
return res.status(400).send('Episode not found in library item')
|
||||
}
|
||||
|
||||
const playlistMediaItem = {
|
||||
playlistId: oldPlaylist.id,
|
||||
mediaItemId: itemToAdd.episodeId || libraryItem.media.id,
|
||||
mediaItemType: itemToAdd.episodeId ? 'podcastEpisode' : 'book',
|
||||
order: oldPlaylist.items.length + 1
|
||||
req.playlist.playlistMediaItems = await req.playlist.getMediaItemsExpandedWithLibraryItem()
|
||||
|
||||
if (req.playlist.checkHasMediaItem(itemToAdd.libraryItemId, itemToAdd.episodeId)) {
|
||||
return res.status(400).send('Item already in playlist')
|
||||
}
|
||||
|
||||
const jsonExpanded = req.playlist.toOldJSONExpanded()
|
||||
|
||||
const playlistMediaItem = {
|
||||
playlistId: req.playlist.id,
|
||||
mediaItemId: itemToAdd.episodeId || libraryItem.media.id,
|
||||
mediaItemType: itemToAdd.episodeId ? 'podcastEpisode' : 'book',
|
||||
order: req.playlist.playlistMediaItems.length + 1
|
||||
}
|
||||
await Database.playlistMediaItemModel.create(playlistMediaItem)
|
||||
|
||||
// Add the new item to to the old json expanded to prevent having to fully reload the playlist media items
|
||||
if (itemToAdd.episodeId) {
|
||||
const episode = libraryItem.media.episodes.find((ep) => ep.id === itemToAdd.episodeId)
|
||||
jsonExpanded.items.push({
|
||||
episodeId: itemToAdd.episodeId,
|
||||
episode: episode.toJSONExpanded(),
|
||||
libraryItemId: libraryItem.id,
|
||||
libraryItem: libraryItem.toJSONMinified()
|
||||
})
|
||||
} else {
|
||||
jsonExpanded.items.push({
|
||||
libraryItemId: libraryItem.id,
|
||||
libraryItem: libraryItem.toJSONExpanded()
|
||||
})
|
||||
}
|
||||
|
||||
await Database.createPlaylistMediaItem(playlistMediaItem)
|
||||
const jsonExpanded = await req.playlist.getOldJsonExpanded()
|
||||
SocketAuthority.clientEmitter(jsonExpanded.userId, 'playlist_updated', jsonExpanded)
|
||||
res.json(jsonExpanded)
|
||||
}
|
||||
@@ -228,43 +330,36 @@ class PlaylistController {
|
||||
* DELETE: /api/playlists/:id/item/:libraryItemId/:episodeId?
|
||||
* Remove item from playlist
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {PlaylistControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async removeItem(req, res) {
|
||||
const oldLibraryItem = await Database.libraryItemModel.getOldById(req.params.libraryItemId)
|
||||
if (!oldLibraryItem) {
|
||||
return res.status(404).send('Library item not found')
|
||||
req.playlist.playlistMediaItems = await req.playlist.getMediaItemsExpandedWithLibraryItem()
|
||||
|
||||
let playlistMediaItem = null
|
||||
if (req.params.episodeId) {
|
||||
playlistMediaItem = req.playlist.playlistMediaItems.find((pmi) => pmi.mediaItemId === req.params.episodeId)
|
||||
} else {
|
||||
playlistMediaItem = req.playlist.playlistMediaItems.find((pmi) => pmi.mediaItem.libraryItem?.id === req.params.libraryItemId)
|
||||
}
|
||||
|
||||
// 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) {
|
||||
if (!playlistMediaItem) {
|
||||
return res.status(404).send('Media item not found in playlist')
|
||||
}
|
||||
|
||||
// Remove record
|
||||
await mediaItemToRemove.destroy()
|
||||
await playlistMediaItem.destroy()
|
||||
req.playlist.playlistMediaItems = req.playlist.playlistMediaItems.filter((pmi) => pmi.id !== playlistMediaItem.id)
|
||||
|
||||
// Update playlist media items order
|
||||
let order = 1
|
||||
for (const mediaItem of playlistMediaItems) {
|
||||
if (mediaItem.mediaItemId === mediaItemId) continue
|
||||
if (mediaItem.order !== order) {
|
||||
for (const [index, mediaItem] of req.playlist.playlistMediaItems.entries()) {
|
||||
if (mediaItem.order !== index + 1) {
|
||||
await mediaItem.update({
|
||||
order
|
||||
order: index + 1
|
||||
})
|
||||
}
|
||||
order++
|
||||
}
|
||||
|
||||
const jsonExpanded = await req.playlist.getOldJsonExpanded()
|
||||
const jsonExpanded = req.playlist.toOldJSONExpanded()
|
||||
|
||||
// Playlist is removed when there are no items
|
||||
if (!jsonExpanded.items.length) {
|
||||
@@ -282,64 +377,68 @@ class PlaylistController {
|
||||
* POST: /api/playlists/:id/batch/add
|
||||
* Batch add playlist items
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {PlaylistControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async addBatch(req, res) {
|
||||
if (!req.body.items?.length) {
|
||||
return res.status(400).send('Invalid request body')
|
||||
}
|
||||
const itemsToAdd = req.body.items
|
||||
|
||||
const libraryItemIds = itemsToAdd.map((i) => i.libraryItemId).filter((i) => i)
|
||||
if (!libraryItemIds.length) {
|
||||
return res.status(400).send('Invalid request body')
|
||||
if (!req.body.items?.length || !Array.isArray(req.body.items) || req.body.items.some((i) => !i?.libraryItemId || typeof i.libraryItemId !== 'string' || (i.episodeId && typeof i.episodeId !== 'string'))) {
|
||||
return res.status(400).send('Invalid request body items')
|
||||
}
|
||||
|
||||
// Find all library items
|
||||
const libraryItems = await Database.libraryItemModel.findAll({
|
||||
where: {
|
||||
id: libraryItemIds
|
||||
}
|
||||
})
|
||||
const libraryItemIds = new Set(req.body.items.map((i) => i.libraryItemId).filter((i) => i))
|
||||
|
||||
// Get all existing playlist media items
|
||||
const existingPlaylistMediaItems = await req.playlist.getPlaylistMediaItems({
|
||||
order: [['order', 'ASC']]
|
||||
})
|
||||
const oldLibraryItems = await Database.libraryItemModel.getAllOldLibraryItems({ id: Array.from(libraryItemIds) })
|
||||
if (oldLibraryItems.length !== libraryItemIds.size) {
|
||||
return res.status(400).send('Invalid request body items')
|
||||
}
|
||||
|
||||
req.playlist.playlistMediaItems = await req.playlist.getMediaItemsExpandedWithLibraryItem()
|
||||
|
||||
const mediaItemsToAdd = []
|
||||
const jsonExpanded = req.playlist.toOldJSONExpanded()
|
||||
|
||||
// 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)
|
||||
let order = req.playlist.playlistMediaItems.length + 1
|
||||
for (const item of req.body.items) {
|
||||
const libraryItem = oldLibraryItems.find((li) => li.id === item.libraryItemId)
|
||||
|
||||
const mediaItemId = item.episodeId || libraryItem.media.id
|
||||
if (req.playlist.playlistMediaItems.some((pmi) => pmi.mediaItemId === mediaItemId)) {
|
||||
// Already exists in playlist
|
||||
continue
|
||||
} else {
|
||||
const mediaItemId = item.episodeId || libraryItem.mediaId
|
||||
if (existingPlaylistMediaItems.some((pmi) => pmi.mediaItemId === mediaItemId)) {
|
||||
// Already exists in playlist
|
||||
continue
|
||||
mediaItemsToAdd.push({
|
||||
playlistId: req.playlist.id,
|
||||
mediaItemId,
|
||||
mediaItemType: item.episodeId ? 'podcastEpisode' : 'book',
|
||||
order: order++
|
||||
})
|
||||
|
||||
// Add the new item to to the old json expanded to prevent having to fully reload the playlist media items
|
||||
if (item.episodeId) {
|
||||
const episode = libraryItem.media.episodes.find((ep) => ep.id === item.episodeId)
|
||||
jsonExpanded.items.push({
|
||||
episodeId: item.episodeId,
|
||||
episode: episode.toJSONExpanded(),
|
||||
libraryItemId: libraryItem.id,
|
||||
libraryItem: libraryItem.toJSONMinified()
|
||||
})
|
||||
} else {
|
||||
mediaItemsToAdd.push({
|
||||
playlistId: req.playlist.id,
|
||||
mediaItemId,
|
||||
mediaItemType: item.episodeId ? 'podcastEpisode' : 'book',
|
||||
order: order++
|
||||
jsonExpanded.items.push({
|
||||
libraryItemId: libraryItem.id,
|
||||
libraryItem: libraryItem.toJSONExpanded()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let jsonExpanded = null
|
||||
if (mediaItemsToAdd.length) {
|
||||
await Database.createBulkPlaylistMediaItems(mediaItemsToAdd)
|
||||
jsonExpanded = await req.playlist.getOldJsonExpanded()
|
||||
await Database.playlistMediaItemModel.bulkCreate(mediaItemsToAdd)
|
||||
|
||||
SocketAuthority.clientEmitter(req.playlist.userId, 'playlist_updated', jsonExpanded)
|
||||
} else {
|
||||
jsonExpanded = await req.playlist.getOldJsonExpanded()
|
||||
}
|
||||
|
||||
res.json(jsonExpanded)
|
||||
}
|
||||
|
||||
@@ -347,50 +446,40 @@ class PlaylistController {
|
||||
* POST: /api/playlists/:id/batch/remove
|
||||
* Batch remove playlist items
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {PlaylistControllerRequest} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async removeBatch(req, res) {
|
||||
if (!req.body.items?.length) {
|
||||
return res.status(400).send('Invalid request body')
|
||||
if (!req.body.items?.length || !Array.isArray(req.body.items) || req.body.items.some((i) => !i?.libraryItemId || typeof i.libraryItemId !== 'string' || (i.episodeId && typeof i.episodeId !== 'string'))) {
|
||||
return res.status(400).send('Invalid request body items')
|
||||
}
|
||||
|
||||
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')
|
||||
}
|
||||
|
||||
// Find all library items
|
||||
const libraryItems = await Database.libraryItemModel.findAll({
|
||||
where: {
|
||||
id: libraryItemIds
|
||||
}
|
||||
})
|
||||
|
||||
// Get all existing playlist media items for playlist
|
||||
const existingPlaylistMediaItems = await req.playlist.getPlaylistMediaItems({
|
||||
order: [['order', 'ASC']]
|
||||
})
|
||||
let numMediaItems = existingPlaylistMediaItems.length
|
||||
req.playlist.playlistMediaItems = await req.playlist.getMediaItemsExpandedWithLibraryItem()
|
||||
|
||||
// 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()
|
||||
for (const item of req.body.items) {
|
||||
let playlistMediaItem = null
|
||||
if (item.episodeId) {
|
||||
playlistMediaItem = req.playlist.playlistMediaItems.find((pmi) => pmi.mediaItemId === item.episodeId)
|
||||
} else {
|
||||
playlistMediaItem = req.playlist.playlistMediaItems.find((pmi) => pmi.mediaItem.libraryItem?.id === item.libraryItemId)
|
||||
}
|
||||
if (!playlistMediaItem) {
|
||||
Logger.warn(`[PlaylistController] Playlist item not found in playlist ${req.playlist.id}`, item)
|
||||
continue
|
||||
}
|
||||
|
||||
await playlistMediaItem.destroy()
|
||||
req.playlist.playlistMediaItems = req.playlist.playlistMediaItems.filter((pmi) => pmi.id !== playlistMediaItem.id)
|
||||
|
||||
hasUpdated = true
|
||||
numMediaItems--
|
||||
}
|
||||
|
||||
const jsonExpanded = await req.playlist.getOldJsonExpanded()
|
||||
const jsonExpanded = req.playlist.toOldJSONExpanded()
|
||||
if (hasUpdated) {
|
||||
// Playlist is removed when there are no items
|
||||
if (!numMediaItems) {
|
||||
if (!req.playlist.playlistMediaItems.length) {
|
||||
Logger.info(`[PlaylistController] Playlist "${req.playlist.name}" has no more items - removing it`)
|
||||
await req.playlist.destroy()
|
||||
SocketAuthority.clientEmitter(jsonExpanded.userId, 'playlist_removed', jsonExpanded)
|
||||
@@ -425,33 +514,41 @@ class PlaylistController {
|
||||
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
|
||||
})
|
||||
const transaction = await Database.sequelize.transaction()
|
||||
try {
|
||||
const playlist = await Database.playlistModel.create(
|
||||
{
|
||||
userId: req.user.id,
|
||||
libraryId: collection.libraryId,
|
||||
name: collection.name,
|
||||
description: collection.description || null
|
||||
},
|
||||
{ transaction }
|
||||
)
|
||||
|
||||
// Create Playlist record
|
||||
const newPlaylist = await Database.playlistModel.createFromOld(oldPlaylist)
|
||||
const mediaItemsToAdd = []
|
||||
for (const [index, libraryItem] of collectionExpanded.books.entries()) {
|
||||
mediaItemsToAdd.push({
|
||||
playlistId: playlist.id,
|
||||
mediaItemId: libraryItem.media.id,
|
||||
mediaItemType: 'book',
|
||||
order: index + 1
|
||||
})
|
||||
}
|
||||
await Database.playlistMediaItemModel.bulkCreate(mediaItemsToAdd, { transaction })
|
||||
|
||||
// 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 transaction.commit()
|
||||
|
||||
playlist.playlistMediaItems = await playlist.getMediaItemsExpandedWithLibraryItem()
|
||||
|
||||
const jsonExpanded = playlist.toOldJSONExpanded()
|
||||
SocketAuthority.clientEmitter(playlist.userId, 'playlist_added', jsonExpanded)
|
||||
res.json(jsonExpanded)
|
||||
} catch (error) {
|
||||
await transaction.rollback()
|
||||
Logger.error('[PlaylistController] createFromCollection:', error)
|
||||
res.status(500).send('Failed to create playlist')
|
||||
}
|
||||
await Database.createBulkPlaylistMediaItems(mediaItemsToAdd)
|
||||
|
||||
const jsonExpanded = await newPlaylist.getOldJsonExpanded()
|
||||
SocketAuthority.clientEmitter(newPlaylist.userId, 'playlist_added', jsonExpanded)
|
||||
res.json(jsonExpanded)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -34,8 +34,13 @@ class AudioMetadataMangaer {
|
||||
return this.tasksQueued.some((t) => t.data.libraryItemId === libraryItemId) || this.tasksRunning.some((t) => t.data.libraryItemId === libraryItemId)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {import('../models/LibraryItem')} libraryItem
|
||||
* @returns
|
||||
*/
|
||||
getMetadataObjectForApi(libraryItem) {
|
||||
return ffmpegHelpers.getFFMetadataObject(libraryItem, libraryItem.media.includedAudioFiles.length)
|
||||
return ffmpegHelpers.getFFMetadataObject(libraryItem.toOldJSONExpanded(), libraryItem.media.includedAudioFiles.length)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -79,6 +79,12 @@ class CoverManager {
|
||||
return imgType
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {import('../models/LibraryItem')} libraryItem
|
||||
* @param {*} coverFile - file object from req.files
|
||||
* @returns {Promise<{error:string}|{cover:string}>}
|
||||
*/
|
||||
async uploadCover(libraryItem, coverFile) {
|
||||
const extname = Path.extname(coverFile.name.toLowerCase())
|
||||
if (!extname || !globals.SupportedImageTypes.includes(extname.slice(1))) {
|
||||
@@ -110,14 +116,20 @@ class CoverManager {
|
||||
await this.removeOldCovers(coverDirPath, extname)
|
||||
await CacheManager.purgeCoverCache(libraryItem.id)
|
||||
|
||||
Logger.info(`[CoverManager] Uploaded libraryItem cover "${coverFullPath}" for "${libraryItem.media.metadata.title}"`)
|
||||
Logger.info(`[CoverManager] Uploaded libraryItem cover "${coverFullPath}" for "${libraryItem.media.title}"`)
|
||||
|
||||
libraryItem.updateMediaCover(coverFullPath)
|
||||
return {
|
||||
cover: coverFullPath
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Object} libraryItem - old library item
|
||||
* @param {string} url
|
||||
* @param {boolean} [forceLibraryItemFolder=false]
|
||||
* @returns {Promise<{error:string}|{cover:string}>}
|
||||
*/
|
||||
async downloadCoverFromUrl(libraryItem, url, forceLibraryItemFolder = false) {
|
||||
try {
|
||||
// Force save cover with library item is used for adding new podcasts
|
||||
@@ -166,6 +178,12 @@ class CoverManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} coverPath
|
||||
* @param {import('../models/LibraryItem')} libraryItem
|
||||
* @returns {Promise<{error:string}|{cover:string,updated:boolean}>}
|
||||
*/
|
||||
async validateCoverPath(coverPath, libraryItem) {
|
||||
// Invalid cover path
|
||||
if (!coverPath || coverPath.startsWith('http:') || coverPath.startsWith('https:')) {
|
||||
@@ -235,7 +253,6 @@ class CoverManager {
|
||||
|
||||
await CacheManager.purgeCoverCache(libraryItem.id)
|
||||
|
||||
libraryItem.updateMediaCover(coverPath)
|
||||
return {
|
||||
cover: coverPath,
|
||||
updated: true
|
||||
|
||||
@@ -215,6 +215,10 @@ class CronManager {
|
||||
this.podcastCrons = this.podcastCrons.filter((pc) => pc.expression !== podcastCron.expression)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {import('../models/LibraryItem')} libraryItem - this can be the old model
|
||||
*/
|
||||
checkUpdatePodcastCron(libraryItem) {
|
||||
// Remove from old cron by library item id
|
||||
const existingCron = this.podcastCrons.find((pc) => pc.libraryItemIds.includes(libraryItem.id))
|
||||
@@ -230,7 +234,10 @@ class CronManager {
|
||||
const cronMatchingExpression = this.podcastCrons.find((pc) => pc.expression === libraryItem.media.autoDownloadSchedule)
|
||||
if (cronMatchingExpression) {
|
||||
cronMatchingExpression.libraryItemIds.push(libraryItem.id)
|
||||
Logger.info(`[CronManager] Added podcast "${libraryItem.media.metadata.title}" to auto dl episode cron "${cronMatchingExpression.expression}"`)
|
||||
|
||||
// TODO: Update after old model removed
|
||||
const podcastTitle = libraryItem.media.title || libraryItem.media.metadata?.title
|
||||
Logger.info(`[CronManager] Added podcast "${podcastTitle}" to auto dl episode cron "${cronMatchingExpression.expression}"`)
|
||||
} else {
|
||||
this.startPodcastCron(libraryItem.media.autoDownloadSchedule, [libraryItem.id])
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ class PlaybackSessionManager {
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {import('../controllers/SessionController').RequestWithUser} req
|
||||
* @param {import('../controllers/LibraryItemController').LibraryItemControllerRequest} req
|
||||
* @param {Object} [clientDeviceInfo]
|
||||
* @returns {Promise<DeviceInfo>}
|
||||
*/
|
||||
@@ -67,14 +67,14 @@ class PlaybackSessionManager {
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {import('../controllers/SessionController').RequestWithUser} req
|
||||
* @param {import('../controllers/LibraryItemController').LibraryItemControllerRequest} req
|
||||
* @param {import('express').Response} res
|
||||
* @param {string} [episodeId]
|
||||
*/
|
||||
async startSessionRequest(req, res, episodeId) {
|
||||
const deviceInfo = await this.getDeviceInfo(req, req.body?.deviceInfo)
|
||||
Logger.debug(`[PlaybackSessionManager] startSessionRequest for device ${deviceInfo.deviceDescription}`)
|
||||
const { libraryItem, body: options } = req
|
||||
const { oldLibraryItem: libraryItem, body: options } = req
|
||||
const session = await this.startSession(req.user, deviceInfo, libraryItem, episodeId, options)
|
||||
res.json(session.toJSONForClient(libraryItem))
|
||||
}
|
||||
|
||||
@@ -98,11 +98,22 @@ class RssFeedManager {
|
||||
podcastId: feed.entity.mediaId
|
||||
},
|
||||
attributes: ['id', 'updatedAt'],
|
||||
order: [['createdAt', 'DESC']]
|
||||
order: [['updatedAt', 'DESC']]
|
||||
})
|
||||
|
||||
if (mostRecentPodcastEpisode && mostRecentPodcastEpisode.updatedAt > newEntityUpdatedAt) {
|
||||
newEntityUpdatedAt = mostRecentPodcastEpisode.updatedAt
|
||||
}
|
||||
} else {
|
||||
const book = await Database.bookModel.findOne({
|
||||
where: {
|
||||
id: feed.entity.mediaId
|
||||
},
|
||||
attributes: ['id', 'updatedAt']
|
||||
})
|
||||
if (book && book.updatedAt > newEntityUpdatedAt) {
|
||||
newEntityUpdatedAt = book.updatedAt
|
||||
}
|
||||
}
|
||||
|
||||
return newEntityUpdatedAt > feed.entityUpdatedAt
|
||||
@@ -111,7 +122,7 @@ class RssFeedManager {
|
||||
attributes: ['id', 'updatedAt'],
|
||||
include: {
|
||||
model: Database.bookModel,
|
||||
attributes: ['id'],
|
||||
attributes: ['id', 'audioFiles', 'updatedAt'],
|
||||
through: {
|
||||
attributes: []
|
||||
},
|
||||
@@ -122,13 +133,16 @@ class RssFeedManager {
|
||||
}
|
||||
})
|
||||
|
||||
const totalBookTracks = feed.entity.books.reduce((total, book) => total + book.includedAudioFiles.length, 0)
|
||||
if (feed.feedEpisodes.length !== totalBookTracks) {
|
||||
return true
|
||||
}
|
||||
|
||||
let newEntityUpdatedAt = feed.entity.updatedAt
|
||||
|
||||
const mostRecentItemUpdatedAt = feed.entity.books.reduce((mostRecent, book) => {
|
||||
if (book.libraryItem.updatedAt > mostRecent) {
|
||||
return book.libraryItem.updatedAt
|
||||
}
|
||||
return mostRecent
|
||||
let updatedAt = book.libraryItem.updatedAt > book.updatedAt ? book.libraryItem.updatedAt : book.updatedAt
|
||||
return updatedAt > mostRecent ? updatedAt : mostRecent
|
||||
}, 0)
|
||||
|
||||
if (mostRecentItemUpdatedAt > newEntityUpdatedAt) {
|
||||
@@ -151,6 +165,9 @@ class RssFeedManager {
|
||||
let feed = await Database.feedModel.findOne({
|
||||
where: {
|
||||
slug: req.params.slug
|
||||
},
|
||||
include: {
|
||||
model: Database.feedEpisodeModel
|
||||
}
|
||||
})
|
||||
if (!feed) {
|
||||
@@ -163,8 +180,6 @@ class RssFeedManager {
|
||||
if (feedRequiresUpdate) {
|
||||
Logger.info(`[RssFeedManager] Feed "${feed.title}" requires update - updating feed`)
|
||||
feed = await feed.updateFeedForEntity()
|
||||
} else {
|
||||
feed.feedEpisodes = await feed.getFeedEpisodes()
|
||||
}
|
||||
|
||||
const xml = feed.buildXml(req.originalHostPrefix)
|
||||
|
||||
@@ -12,3 +12,4 @@ Please add a record of every database migration that you create to this file. Th
|
||||
| v2.17.4 | v2.17.4-use-subfolder-for-oidc-redirect-uris | Save subfolder to OIDC redirect URIs to support existing installations |
|
||||
| v2.17.5 | v2.17.5-remove-host-from-feed-urls | removes the host (serverAddress) from URL columns in the feeds and feedEpisodes tables |
|
||||
| v2.17.6 | v2.17.6-share-add-isdownloadable | Adds the isDownloadable column to the mediaItemShares table |
|
||||
| v2.17.7 | v2.17.7-add-indices | Adds indices to the libraryItems and books tables to reduce query times |
|
||||
|
||||
83
server/migrations/v2.17.7-add-indices.js
Normal file
83
server/migrations/v2.17.7-add-indices.js
Normal file
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* @typedef MigrationContext
|
||||
* @property {import('sequelize').QueryInterface} queryInterface - a suquelize QueryInterface object.
|
||||
* @property {import('../Logger')} logger - a Logger object.
|
||||
*
|
||||
* @typedef MigrationOptions
|
||||
* @property {MigrationContext} context - an object containing the migration context.
|
||||
*/
|
||||
|
||||
const migrationVersion = '2.17.7'
|
||||
const migrationName = `${migrationVersion}-add-indices`
|
||||
const loggerPrefix = `[${migrationVersion} migration]`
|
||||
|
||||
/**
|
||||
* This upward migration adds some indices to the libraryItems and books tables to improve query performance
|
||||
*
|
||||
* @param {MigrationOptions} options - an object containing the migration context.
|
||||
* @returns {Promise<void>} - A promise that resolves when the migration is complete.
|
||||
*/
|
||||
async function up({ context: { queryInterface, logger } }) {
|
||||
// Upwards migration script
|
||||
logger.info(`${loggerPrefix} UPGRADE BEGIN: ${migrationName}`)
|
||||
|
||||
await addIndex(queryInterface, logger, 'libraryItems', ['libraryId', 'mediaType', 'size'])
|
||||
await addIndex(queryInterface, logger, 'books', ['duration'])
|
||||
|
||||
logger.info(`${loggerPrefix} UPGRADE END: ${migrationName}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* This downward migration script removes the indices added in the upward migration script
|
||||
*
|
||||
* @param {MigrationOptions} options - an object containing the migration context.
|
||||
* @returns {Promise<void>} - A promise that resolves when the migration is complete.
|
||||
*/
|
||||
async function down({ context: { queryInterface, logger } }) {
|
||||
// Downward migration script
|
||||
logger.info(`${loggerPrefix} DOWNGRADE BEGIN: ${migrationName}`)
|
||||
|
||||
await removeIndex(queryInterface, logger, 'libraryItems', ['libraryId', 'mediaType', 'size'])
|
||||
await removeIndex(queryInterface, logger, 'books', ['duration'])
|
||||
|
||||
logger.info(`${loggerPrefix} DOWNGRADE END: ${migrationName}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility function to add an index to a table. If the index already exists, it logs a message and continues.
|
||||
*
|
||||
* @param {import('sequelize').QueryInterface} queryInterface
|
||||
* @param {import ('../Logger')} logger
|
||||
* @param {string} tableName
|
||||
* @param {string[]} columns
|
||||
*/
|
||||
async function addIndex(queryInterface, logger, tableName, columns) {
|
||||
try {
|
||||
logger.info(`${loggerPrefix} adding index [${columns.join(', ')}] to table "${tableName}"`)
|
||||
await queryInterface.addIndex(tableName, columns)
|
||||
logger.info(`${loggerPrefix} added index [${columns.join(', ')}] to table "${tableName}"`)
|
||||
} catch (error) {
|
||||
if (error.name === 'SequelizeDatabaseError' && error.message.includes('already exists')) {
|
||||
logger.info(`${loggerPrefix} index [${columns.join(', ')}] for table "${tableName}" already exists`)
|
||||
} else {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility function to remove an index from a table.
|
||||
* Sequelize implemets it using DROP INDEX IF EXISTS, so it won't throw an error if the index doesn't exist.
|
||||
*
|
||||
* @param {import('sequelize').QueryInterface} queryInterface
|
||||
* @param {import ('../Logger')} logger
|
||||
* @param {string} tableName
|
||||
* @param {string[]} columns
|
||||
*/
|
||||
async function removeIndex(queryInterface, logger, tableName, columns) {
|
||||
logger.info(`${loggerPrefix} removing index [${columns.join(', ')}] from table "${tableName}"`)
|
||||
await queryInterface.removeIndex(tableName, columns)
|
||||
logger.info(`${loggerPrefix} removed index [${columns.join(', ')}] from table "${tableName}"`)
|
||||
}
|
||||
|
||||
module.exports = { up, down }
|
||||
@@ -1,5 +1,7 @@
|
||||
const { DataTypes, Model } = require('sequelize')
|
||||
const Logger = require('../Logger')
|
||||
const { getTitlePrefixAtEnd, getTitleIgnorePrefix } = require('../utils')
|
||||
const parseNameString = require('../utils/parsers/parseNameString')
|
||||
|
||||
/**
|
||||
* @typedef EBookFileObject
|
||||
@@ -113,8 +115,12 @@ class Book extends Model {
|
||||
/** @type {Date} */
|
||||
this.createdAt
|
||||
|
||||
// Expanded properties
|
||||
|
||||
/** @type {import('./Author')[]} - optional if expanded */
|
||||
this.authors
|
||||
/** @type {import('./Series')[]} - optional if expanded */
|
||||
this.series
|
||||
}
|
||||
|
||||
static getOldBook(libraryItemExpanded) {
|
||||
@@ -241,32 +247,6 @@ class Book extends Model {
|
||||
}
|
||||
}
|
||||
|
||||
getAbsMetadataJson() {
|
||||
return {
|
||||
tags: this.tags || [],
|
||||
chapters: this.chapters?.map((c) => ({ ...c })) || [],
|
||||
title: this.title,
|
||||
subtitle: this.subtitle,
|
||||
authors: this.authors.map((a) => a.name),
|
||||
narrators: this.narrators,
|
||||
series: this.series.map((se) => {
|
||||
const sequence = se.bookSeries?.sequence || ''
|
||||
if (!sequence) return se.name
|
||||
return `${se.name} #${sequence}`
|
||||
}),
|
||||
genres: this.genres || [],
|
||||
publishedYear: this.publishedYear,
|
||||
publishedDate: this.publishedDate,
|
||||
publisher: this.publisher,
|
||||
description: this.description,
|
||||
isbn: this.isbn,
|
||||
asin: this.asin,
|
||||
language: this.language,
|
||||
explicit: !!this.explicit,
|
||||
abridged: !!this.abridged
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize model
|
||||
* @param {import('../Database').sequelize} sequelize
|
||||
@@ -321,10 +301,10 @@ class Book extends Model {
|
||||
// },
|
||||
{
|
||||
fields: ['publishedYear']
|
||||
},
|
||||
{
|
||||
fields: ['duration']
|
||||
}
|
||||
// {
|
||||
// fields: ['duration']
|
||||
// }
|
||||
]
|
||||
}
|
||||
)
|
||||
@@ -343,9 +323,50 @@ class Book extends Model {
|
||||
}
|
||||
return this.authors.map((au) => au.name).join(', ')
|
||||
}
|
||||
|
||||
/**
|
||||
* Comma separated array of author names in Last, First format
|
||||
* Requires authors to be loaded
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
get authorNameLF() {
|
||||
if (this.authors === undefined) {
|
||||
Logger.error(`[Book] authorNameLF: Cannot get authorNameLF because authors are not loaded`)
|
||||
return ''
|
||||
}
|
||||
|
||||
// Last, First
|
||||
if (!this.authors.length) return ''
|
||||
return this.authors.map((au) => parseNameString.nameToLastFirst(au.name)).join(', ')
|
||||
}
|
||||
|
||||
/**
|
||||
* Comma separated array of series with sequence
|
||||
* Requires series to be loaded
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
get seriesName() {
|
||||
if (this.series === undefined) {
|
||||
Logger.error(`[Book] seriesName: Cannot get seriesName because series are not loaded`)
|
||||
return ''
|
||||
}
|
||||
|
||||
if (!this.series.length) return ''
|
||||
return this.series
|
||||
.map((se) => {
|
||||
const sequence = se.bookSeries?.sequence || ''
|
||||
if (!sequence) return se.name
|
||||
return `${se.name} #${sequence}`
|
||||
})
|
||||
.join(', ')
|
||||
}
|
||||
|
||||
get includedAudioFiles() {
|
||||
return this.audioFiles.filter((af) => !af.exclude)
|
||||
}
|
||||
|
||||
get trackList() {
|
||||
let startOffset = 0
|
||||
return this.includedAudioFiles.map((af) => {
|
||||
@@ -355,6 +376,299 @@ class Book extends Model {
|
||||
return track
|
||||
})
|
||||
}
|
||||
|
||||
get hasMediaFiles() {
|
||||
return !!this.hasAudioTracks || !!this.ebookFile
|
||||
}
|
||||
|
||||
get hasAudioTracks() {
|
||||
return !!this.includedAudioFiles.length
|
||||
}
|
||||
|
||||
/**
|
||||
* Total file size of all audio files and ebook file
|
||||
*
|
||||
* @returns {number}
|
||||
*/
|
||||
get size() {
|
||||
let total = 0
|
||||
this.audioFiles.forEach((af) => (total += af.metadata.size))
|
||||
if (this.ebookFile) {
|
||||
total += this.ebookFile.metadata.size
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
getAbsMetadataJson() {
|
||||
return {
|
||||
tags: this.tags || [],
|
||||
chapters: this.chapters?.map((c) => ({ ...c })) || [],
|
||||
title: this.title,
|
||||
subtitle: this.subtitle,
|
||||
authors: this.authors.map((a) => a.name),
|
||||
narrators: this.narrators,
|
||||
series: this.series.map((se) => {
|
||||
const sequence = se.bookSeries?.sequence || ''
|
||||
if (!sequence) return se.name
|
||||
return `${se.name} #${sequence}`
|
||||
}),
|
||||
genres: this.genres || [],
|
||||
publishedYear: this.publishedYear,
|
||||
publishedDate: this.publishedDate,
|
||||
publisher: this.publisher,
|
||||
description: this.description,
|
||||
isbn: this.isbn,
|
||||
asin: this.asin,
|
||||
language: this.language,
|
||||
explicit: !!this.explicit,
|
||||
abridged: !!this.abridged
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Object} payload - old book object
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async updateFromRequest(payload) {
|
||||
if (!payload) return false
|
||||
|
||||
let hasUpdates = false
|
||||
|
||||
if (payload.metadata) {
|
||||
const metadataStringKeys = ['title', 'subtitle', 'publishedYear', 'publishedDate', 'publisher', 'description', 'isbn', 'asin', 'language']
|
||||
metadataStringKeys.forEach((key) => {
|
||||
if (typeof payload.metadata[key] === 'string' && this[key] !== payload.metadata[key]) {
|
||||
this[key] = payload.metadata[key] || null
|
||||
|
||||
if (key === 'title') {
|
||||
this.titleIgnorePrefix = getTitleIgnorePrefix(this.title)
|
||||
}
|
||||
|
||||
hasUpdates = true
|
||||
}
|
||||
})
|
||||
if (payload.metadata.explicit !== undefined && this.explicit !== !!payload.metadata.explicit) {
|
||||
this.explicit = !!payload.metadata.explicit
|
||||
hasUpdates = true
|
||||
}
|
||||
if (payload.metadata.abridged !== undefined && this.abridged !== !!payload.metadata.abridged) {
|
||||
this.abridged = !!payload.metadata.abridged
|
||||
hasUpdates = true
|
||||
}
|
||||
const arrayOfStringsKeys = ['narrators', 'genres']
|
||||
arrayOfStringsKeys.forEach((key) => {
|
||||
if (Array.isArray(payload.metadata[key]) && !payload.metadata[key].some((item) => typeof item !== 'string') && JSON.stringify(this[key]) !== JSON.stringify(payload.metadata[key])) {
|
||||
this[key] = payload.metadata[key]
|
||||
this.changed(key, true)
|
||||
hasUpdates = true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (Array.isArray(payload.tags) && !payload.tags.some((tag) => typeof tag !== 'string') && JSON.stringify(this.tags) !== JSON.stringify(payload.tags)) {
|
||||
this.tags = payload.tags
|
||||
this.changed('tags', true)
|
||||
hasUpdates = true
|
||||
}
|
||||
|
||||
// TODO: Remove support for updating audioFiles, chapters and ebookFile here
|
||||
const arrayOfObjectsKeys = ['audioFiles', 'chapters']
|
||||
arrayOfObjectsKeys.forEach((key) => {
|
||||
if (Array.isArray(payload[key]) && !payload[key].some((item) => typeof item !== 'object') && JSON.stringify(this[key]) !== JSON.stringify(payload[key])) {
|
||||
this[key] = payload[key]
|
||||
this.changed(key, true)
|
||||
hasUpdates = true
|
||||
}
|
||||
})
|
||||
if (payload.ebookFile && JSON.stringify(this.ebookFile) !== JSON.stringify(payload.ebookFile)) {
|
||||
this.ebookFile = payload.ebookFile
|
||||
this.changed('ebookFile', true)
|
||||
hasUpdates = true
|
||||
}
|
||||
|
||||
if (hasUpdates) {
|
||||
Logger.debug(`[Book] "${this.title}" changed keys:`, this.changed())
|
||||
await this.save()
|
||||
}
|
||||
|
||||
if (Array.isArray(payload.metadata?.authors)) {
|
||||
const authorsRemoved = this.authors.filter((au) => !payload.metadata.authors.some((a) => a.id === au.id))
|
||||
const newAuthors = payload.metadata.authors.filter((a) => !this.authors.some((au) => au.id === a.id))
|
||||
|
||||
for (const author of authorsRemoved) {
|
||||
await this.sequelize.models.bookAuthor.removeByIds(author.id, this.id)
|
||||
Logger.debug(`[Book] "${this.title}" Removed author ${author.id}`)
|
||||
hasUpdates = true
|
||||
}
|
||||
for (const author of newAuthors) {
|
||||
await this.sequelize.models.bookAuthor.create({ bookId: this.id, authorId: author.id })
|
||||
Logger.debug(`[Book] "${this.title}" Added author ${author.id}`)
|
||||
hasUpdates = true
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(payload.metadata?.series)) {
|
||||
const seriesRemoved = this.series.filter((se) => !payload.metadata.series.some((s) => s.id === se.id))
|
||||
const newSeries = payload.metadata.series.filter((s) => !this.series.some((se) => se.id === s.id))
|
||||
|
||||
for (const series of seriesRemoved) {
|
||||
await this.sequelize.models.bookSeries.removeByIds(series.id, this.id)
|
||||
Logger.debug(`[Book] "${this.title}" Removed series ${series.id}`)
|
||||
hasUpdates = true
|
||||
}
|
||||
for (const series of newSeries) {
|
||||
await this.sequelize.models.bookSeries.create({ bookId: this.id, seriesId: series.id, sequence: series.sequence })
|
||||
Logger.debug(`[Book] "${this.title}" Added series ${series.id}`)
|
||||
hasUpdates = true
|
||||
}
|
||||
for (const series of payload.metadata.series) {
|
||||
const existingSeries = this.series.find((se) => se.id === series.id)
|
||||
if (existingSeries && existingSeries.bookSeries.sequence !== series.sequence) {
|
||||
await existingSeries.bookSeries.update({ sequence: series.sequence })
|
||||
Logger.debug(`[Book] "${this.title}" Updated series ${series.id} sequence ${series.sequence}`)
|
||||
hasUpdates = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return hasUpdates
|
||||
}
|
||||
|
||||
/**
|
||||
* Old model kept metadata in a separate object
|
||||
*/
|
||||
oldMetadataToJSON() {
|
||||
const authors = this.authors.map((au) => ({ id: au.id, name: au.name }))
|
||||
const series = this.series.map((se) => ({ id: se.id, name: se.name, sequence: se.bookSeries.sequence }))
|
||||
return {
|
||||
title: this.title,
|
||||
subtitle: this.subtitle,
|
||||
authors,
|
||||
narrators: [...(this.narrators || [])],
|
||||
series,
|
||||
genres: [...(this.genres || [])],
|
||||
publishedYear: this.publishedYear,
|
||||
publishedDate: this.publishedDate,
|
||||
publisher: this.publisher,
|
||||
description: this.description,
|
||||
isbn: this.isbn,
|
||||
asin: this.asin,
|
||||
language: this.language,
|
||||
explicit: this.explicit,
|
||||
abridged: this.abridged
|
||||
}
|
||||
}
|
||||
|
||||
oldMetadataToJSONMinified() {
|
||||
return {
|
||||
title: this.title,
|
||||
titleIgnorePrefix: getTitlePrefixAtEnd(this.title),
|
||||
subtitle: this.subtitle,
|
||||
authorName: this.authorName,
|
||||
authorNameLF: this.authorNameLF,
|
||||
narratorName: (this.narrators || []).join(', '),
|
||||
seriesName: this.seriesName,
|
||||
genres: [...(this.genres || [])],
|
||||
publishedYear: this.publishedYear,
|
||||
publishedDate: this.publishedDate,
|
||||
publisher: this.publisher,
|
||||
description: this.description,
|
||||
isbn: this.isbn,
|
||||
asin: this.asin,
|
||||
language: this.language,
|
||||
explicit: this.explicit,
|
||||
abridged: this.abridged
|
||||
}
|
||||
}
|
||||
|
||||
oldMetadataToJSONExpanded() {
|
||||
const oldMetadataJSON = this.oldMetadataToJSON()
|
||||
oldMetadataJSON.titleIgnorePrefix = getTitlePrefixAtEnd(this.title)
|
||||
oldMetadataJSON.authorName = this.authorName
|
||||
oldMetadataJSON.authorNameLF = this.authorNameLF
|
||||
oldMetadataJSON.narratorName = (this.narrators || []).join(', ')
|
||||
oldMetadataJSON.seriesName = this.seriesName
|
||||
return oldMetadataJSON
|
||||
}
|
||||
|
||||
/**
|
||||
* The old model stored a minified series and authors array with the book object.
|
||||
* Minified series is { id, name, sequence }
|
||||
* Minified author is { id, name }
|
||||
*
|
||||
* @param {string} libraryItemId
|
||||
*/
|
||||
toOldJSON(libraryItemId) {
|
||||
if (!libraryItemId) {
|
||||
throw new Error(`[Book] Cannot convert to old JSON because libraryItemId is not provided`)
|
||||
}
|
||||
if (!this.authors) {
|
||||
throw new Error(`[Book] Cannot convert to old JSON because authors are not loaded`)
|
||||
}
|
||||
if (!this.series) {
|
||||
throw new Error(`[Book] Cannot convert to old JSON because series are not loaded`)
|
||||
}
|
||||
|
||||
return {
|
||||
id: this.id,
|
||||
libraryItemId: libraryItemId,
|
||||
metadata: this.oldMetadataToJSON(),
|
||||
coverPath: this.coverPath,
|
||||
tags: [...(this.tags || [])],
|
||||
audioFiles: structuredClone(this.audioFiles),
|
||||
chapters: structuredClone(this.chapters),
|
||||
ebookFile: structuredClone(this.ebookFile)
|
||||
}
|
||||
}
|
||||
|
||||
toOldJSONMinified() {
|
||||
if (!this.authors) {
|
||||
throw new Error(`[Book] Cannot convert to old JSON because authors are not loaded`)
|
||||
}
|
||||
if (!this.series) {
|
||||
throw new Error(`[Book] Cannot convert to old JSON because series are not loaded`)
|
||||
}
|
||||
|
||||
return {
|
||||
id: this.id,
|
||||
metadata: this.oldMetadataToJSONMinified(),
|
||||
coverPath: this.coverPath,
|
||||
tags: [...(this.tags || [])],
|
||||
numTracks: this.trackList.length,
|
||||
numAudioFiles: this.audioFiles?.length || 0,
|
||||
numChapters: this.chapters?.length || 0,
|
||||
duration: this.duration,
|
||||
size: this.size,
|
||||
ebookFormat: this.ebookFile?.ebookFormat
|
||||
}
|
||||
}
|
||||
|
||||
toOldJSONExpanded(libraryItemId) {
|
||||
if (!libraryItemId) {
|
||||
throw new Error(`[Book] Cannot convert to old JSON because libraryItemId is not provided`)
|
||||
}
|
||||
if (!this.authors) {
|
||||
throw new Error(`[Book] Cannot convert to old JSON because authors are not loaded`)
|
||||
}
|
||||
if (!this.series) {
|
||||
throw new Error(`[Book] Cannot convert to old JSON because series are not loaded`)
|
||||
}
|
||||
|
||||
return {
|
||||
id: this.id,
|
||||
libraryItemId: libraryItemId,
|
||||
metadata: this.oldMetadataToJSONExpanded(),
|
||||
coverPath: this.coverPath,
|
||||
tags: [...(this.tags || [])],
|
||||
audioFiles: structuredClone(this.audioFiles),
|
||||
chapters: structuredClone(this.chapters),
|
||||
ebookFile: structuredClone(this.ebookFile),
|
||||
duration: this.duration,
|
||||
size: this.size,
|
||||
tracks: structuredClone(this.trackList)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Book
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
const { DataTypes, Model, Sequelize } = require('sequelize')
|
||||
|
||||
const oldCollection = require('../objects/Collection')
|
||||
|
||||
class Collection extends Model {
|
||||
constructor(values, options) {
|
||||
super(values, options)
|
||||
@@ -26,12 +24,12 @@ class Collection extends Model {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all old collections toJSONExpanded, items filtered for user permissions
|
||||
* Get all toOldJSONExpanded, items filtered for user permissions
|
||||
*
|
||||
* @param {import('./User')} user
|
||||
* @param {string} [libraryId]
|
||||
* @param {string[]} [include]
|
||||
* @returns {Promise<oldCollection[]>} oldCollection.toJSONExpanded
|
||||
* @async
|
||||
*/
|
||||
static async getOldCollectionsJsonExpanded(user, libraryId, include) {
|
||||
let collectionWhere = null
|
||||
@@ -79,8 +77,6 @@ class Collection extends Model {
|
||||
// TODO: Handle user permission restrictions on initial query
|
||||
return collections
|
||||
.map((c) => {
|
||||
const oldCollection = this.getOldCollection(c)
|
||||
|
||||
// Filter books using user permissions
|
||||
const books =
|
||||
c.books?.filter((b) => {
|
||||
@@ -95,20 +91,14 @@ class Collection extends Model {
|
||||
return true
|
||||
}) || []
|
||||
|
||||
// Map to library items
|
||||
const libraryItems = books.map((b) => {
|
||||
const libraryItem = b.libraryItem
|
||||
delete b.libraryItem
|
||||
libraryItem.media = b
|
||||
return this.sequelize.models.libraryItem.getOldLibraryItem(libraryItem)
|
||||
})
|
||||
|
||||
// Users with restricted permissions will not see this collection
|
||||
if (!books.length && oldCollection.books.length) {
|
||||
if (!books.length && c.books.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
const collectionExpanded = oldCollection.toJSONExpanded(libraryItems)
|
||||
this.books = books
|
||||
|
||||
const collectionExpanded = c.toOldJSONExpanded()
|
||||
|
||||
// Map feed if found
|
||||
if (c.feeds?.length) {
|
||||
@@ -153,69 +143,6 @@ class Collection extends Model {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get old collection from Collection
|
||||
* @param {Collection} collectionExpanded
|
||||
* @returns {oldCollection}
|
||||
*/
|
||||
static getOldCollection(collectionExpanded) {
|
||||
const libraryItemIds = collectionExpanded.books?.map((b) => b.libraryItem?.id || null).filter((lid) => lid) || []
|
||||
return new oldCollection({
|
||||
id: collectionExpanded.id,
|
||||
libraryId: collectionExpanded.libraryId,
|
||||
name: collectionExpanded.name,
|
||||
description: collectionExpanded.description,
|
||||
books: libraryItemIds,
|
||||
lastUpdate: collectionExpanded.updatedAt.valueOf(),
|
||||
createdAt: collectionExpanded.createdAt.valueOf()
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {oldCollection} oldCollection
|
||||
* @returns {Promise<Collection>}
|
||||
*/
|
||||
static createFromOld(oldCollection) {
|
||||
const collection = this.getFromOld(oldCollection)
|
||||
return this.create(collection)
|
||||
}
|
||||
|
||||
static getFromOld(oldCollection) {
|
||||
return {
|
||||
id: oldCollection.id,
|
||||
name: oldCollection.name,
|
||||
description: oldCollection.description,
|
||||
libraryId: oldCollection.libraryId
|
||||
}
|
||||
}
|
||||
|
||||
static removeById(collectionId) {
|
||||
return this.destroy({
|
||||
where: {
|
||||
id: collectionId
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get old collection by id
|
||||
* @param {string} collectionId
|
||||
* @returns {Promise<oldCollection|null>} returns null if not found
|
||||
*/
|
||||
static async getOldById(collectionId) {
|
||||
if (!collectionId) return null
|
||||
const collection = await this.findByPk(collectionId, {
|
||||
include: {
|
||||
model: this.sequelize.models.book,
|
||||
include: this.sequelize.models.libraryItem
|
||||
},
|
||||
order: [[this.sequelize.models.book, this.sequelize.models.collectionBook, 'order', 'ASC']]
|
||||
})
|
||||
if (!collection) return null
|
||||
return this.getOldCollection(collection)
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all collections belonging to library
|
||||
* @param {string} libraryId
|
||||
@@ -286,64 +213,37 @@ class Collection extends Model {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get old collection toJSONExpanded, items filtered for user permissions
|
||||
* Get toOldJSONExpanded, items filtered for user permissions
|
||||
*
|
||||
* @param {import('./User')|null} user
|
||||
* @param {string[]} [include]
|
||||
* @returns {Promise<oldCollection>} oldCollection.toJSONExpanded
|
||||
* @async
|
||||
*/
|
||||
async getOldJsonExpanded(user, include) {
|
||||
this.books =
|
||||
(await this.getBooks({
|
||||
include: [
|
||||
{
|
||||
model: this.sequelize.models.libraryItem
|
||||
},
|
||||
{
|
||||
model: this.sequelize.models.author,
|
||||
through: {
|
||||
attributes: []
|
||||
}
|
||||
},
|
||||
{
|
||||
model: this.sequelize.models.series,
|
||||
through: {
|
||||
attributes: ['sequence']
|
||||
}
|
||||
}
|
||||
],
|
||||
order: [Sequelize.literal('`collectionBook.order` ASC')]
|
||||
})) || []
|
||||
this.books = await this.getBooksExpandedWithLibraryItem()
|
||||
|
||||
// Filter books using user permissions
|
||||
// TODO: Handle user permission restrictions on initial query
|
||||
const books =
|
||||
this.books?.filter((b) => {
|
||||
if (user) {
|
||||
if (b.tags?.length && !user.checkCanAccessLibraryItemWithTags(b.tags)) {
|
||||
return false
|
||||
}
|
||||
if (b.explicit === true && !user.canAccessExplicitContent) {
|
||||
return false
|
||||
}
|
||||
if (user) {
|
||||
const books = this.books.filter((b) => {
|
||||
if (b.tags?.length && !user.checkCanAccessLibraryItemWithTags(b.tags)) {
|
||||
return false
|
||||
}
|
||||
if (b.explicit === true && !user.canAccessExplicitContent) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}) || []
|
||||
})
|
||||
|
||||
// Map to library items
|
||||
const libraryItems = books.map((b) => {
|
||||
const libraryItem = b.libraryItem
|
||||
delete b.libraryItem
|
||||
libraryItem.media = b
|
||||
return this.sequelize.models.libraryItem.getOldLibraryItem(libraryItem)
|
||||
})
|
||||
// Users with restricted permissions will not see this collection
|
||||
if (!books.length && this.books.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Users with restricted permissions will not see this collection
|
||||
if (!books.length && this.books.length) {
|
||||
return null
|
||||
this.books = books
|
||||
}
|
||||
|
||||
const collectionExpanded = this.toOldJSONExpanded(libraryItems)
|
||||
const collectionExpanded = this.toOldJSONExpanded()
|
||||
|
||||
if (include?.includes('rssfeed')) {
|
||||
const feeds = await this.getFeeds()
|
||||
@@ -357,10 +257,10 @@ class Collection extends Model {
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string[]} libraryItemIds
|
||||
* @param {string[]} [libraryItemIds=[]]
|
||||
* @returns
|
||||
*/
|
||||
toOldJSON(libraryItemIds) {
|
||||
toOldJSON(libraryItemIds = []) {
|
||||
return {
|
||||
id: this.id,
|
||||
libraryId: this.libraryId,
|
||||
@@ -372,19 +272,19 @@ class Collection extends Model {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {import('../objects/LibraryItem')} oldLibraryItems
|
||||
* @returns
|
||||
*/
|
||||
toOldJSONExpanded(oldLibraryItems) {
|
||||
const json = this.toOldJSON(oldLibraryItems.map((li) => li.id))
|
||||
json.books = json.books
|
||||
.map((libraryItemId) => {
|
||||
const book = oldLibraryItems.find((li) => li.id === libraryItemId)
|
||||
return book ? book.toJSONExpanded() : null
|
||||
})
|
||||
.filter((b) => !!b)
|
||||
toOldJSONExpanded() {
|
||||
if (!this.books) {
|
||||
throw new Error('Books are required to expand Collection')
|
||||
}
|
||||
|
||||
const json = this.toOldJSON()
|
||||
json.books = this.books.map((book) => {
|
||||
const libraryItem = book.libraryItem
|
||||
delete book.libraryItem
|
||||
libraryItem.media = book
|
||||
return this.sequelize.models.libraryItem.getOldLibraryItem(libraryItem).toJSONExpanded()
|
||||
})
|
||||
|
||||
return json
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,15 +16,6 @@ class CollectionBook extends Model {
|
||||
this.createdAt
|
||||
}
|
||||
|
||||
static removeByIds(collectionId, bookId) {
|
||||
return this.destroy({
|
||||
where: {
|
||||
bookId,
|
||||
collectionId
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
static init(sequelize) {
|
||||
super.init(
|
||||
{
|
||||
|
||||
@@ -107,6 +107,9 @@ class Feed extends Model {
|
||||
entityUpdatedAt = libraryItem.media.podcastEpisodes.reduce((mostRecent, episode) => {
|
||||
return episode.updatedAt > mostRecent ? episode.updatedAt : mostRecent
|
||||
}, entityUpdatedAt)
|
||||
} else if (libraryItem.media.updatedAt > entityUpdatedAt) {
|
||||
// Book feeds will use Book.updatedAt if more recent
|
||||
entityUpdatedAt = libraryItem.media.updatedAt
|
||||
}
|
||||
|
||||
const feedObj = {
|
||||
@@ -187,7 +190,8 @@ class Feed extends Model {
|
||||
const booksWithTracks = collectionExpanded.books.filter((book) => book.includedAudioFiles.length)
|
||||
|
||||
const entityUpdatedAt = booksWithTracks.reduce((mostRecent, book) => {
|
||||
return book.libraryItem.updatedAt > mostRecent ? book.libraryItem.updatedAt : mostRecent
|
||||
const updatedAt = book.libraryItem.updatedAt > book.updatedAt ? book.libraryItem.updatedAt : book.updatedAt
|
||||
return updatedAt > mostRecent ? updatedAt : mostRecent
|
||||
}, collectionExpanded.updatedAt)
|
||||
|
||||
const firstBookWithCover = booksWithTracks.find((book) => book.coverPath)
|
||||
@@ -275,7 +279,8 @@ class Feed extends Model {
|
||||
static getFeedObjForSeries(userId, seriesExpanded, slug, serverAddress, feedOptions = null) {
|
||||
const booksWithTracks = seriesExpanded.books.filter((book) => book.includedAudioFiles.length)
|
||||
const entityUpdatedAt = booksWithTracks.reduce((mostRecent, book) => {
|
||||
return book.libraryItem.updatedAt > mostRecent ? book.libraryItem.updatedAt : mostRecent
|
||||
const updatedAt = book.libraryItem.updatedAt > book.updatedAt ? book.libraryItem.updatedAt : book.updatedAt
|
||||
return updatedAt > mostRecent ? updatedAt : mostRecent
|
||||
}, seriesExpanded.updatedAt)
|
||||
|
||||
const firstBookWithCover = booksWithTracks.find((book) => book.coverPath)
|
||||
@@ -516,17 +521,24 @@ class Feed extends Model {
|
||||
try {
|
||||
const updatedFeed = await this.update(feedObj, { transaction })
|
||||
|
||||
// Remove existing feed episodes
|
||||
await feedEpisodeModel.destroy({
|
||||
where: {
|
||||
feedId: this.id
|
||||
},
|
||||
transaction
|
||||
})
|
||||
const existingFeedEpisodeIds = this.feedEpisodes.map((ep) => ep.id)
|
||||
|
||||
// Create new feed episodes
|
||||
updatedFeed.feedEpisodes = await feedEpisodeCreateFunc(feedEpisodeCreateFuncEntity, updatedFeed, this.slug, transaction)
|
||||
|
||||
const newFeedEpisodeIds = updatedFeed.feedEpisodes.map((ep) => ep.id)
|
||||
const feedEpisodeIdsToRemove = existingFeedEpisodeIds.filter((epid) => !newFeedEpisodeIds.includes(epid))
|
||||
|
||||
if (feedEpisodeIdsToRemove.length) {
|
||||
Logger.info(`[Feed] Removing ${feedEpisodeIdsToRemove.length} episodes from feed ${this.id}`)
|
||||
await feedEpisodeModel.destroy({
|
||||
where: {
|
||||
id: feedEpisodeIdsToRemove
|
||||
},
|
||||
transaction
|
||||
})
|
||||
}
|
||||
|
||||
await transaction.commit()
|
||||
|
||||
return updatedFeed
|
||||
|
||||
@@ -53,9 +53,10 @@ class FeedEpisode extends Model {
|
||||
* @param {import('./Feed')} feed
|
||||
* @param {string} slug
|
||||
* @param {import('./PodcastEpisode')} episode
|
||||
* @param {string} [existingEpisodeId]
|
||||
*/
|
||||
static getFeedEpisodeObjFromPodcastEpisode(libraryItemExpanded, feed, slug, episode) {
|
||||
const episodeId = uuidv4()
|
||||
static getFeedEpisodeObjFromPodcastEpisode(libraryItemExpanded, feed, slug, episode, existingEpisodeId = null) {
|
||||
const episodeId = existingEpisodeId || uuidv4()
|
||||
return {
|
||||
id: episodeId,
|
||||
title: episode.title,
|
||||
@@ -94,11 +95,18 @@ class FeedEpisode extends Model {
|
||||
libraryItemExpanded.media.podcastEpisodes.sort((a, b) => new Date(a.pubDate) - new Date(b.pubDate))
|
||||
}
|
||||
|
||||
let numExisting = 0
|
||||
for (const episode of libraryItemExpanded.media.podcastEpisodes) {
|
||||
feedEpisodeObjs.push(this.getFeedEpisodeObjFromPodcastEpisode(libraryItemExpanded, feed, slug, episode))
|
||||
// Check for existing episode by filepath
|
||||
const existingEpisode = feed.feedEpisodes?.find((feedEpisode) => {
|
||||
return feedEpisode.filePath === episode.audioFile.metadata.path
|
||||
})
|
||||
numExisting = existingEpisode ? numExisting + 1 : numExisting
|
||||
|
||||
feedEpisodeObjs.push(this.getFeedEpisodeObjFromPodcastEpisode(libraryItemExpanded, feed, slug, episode, existingEpisode?.id))
|
||||
}
|
||||
Logger.info(`[FeedEpisode] Creating ${feedEpisodeObjs.length} episodes for feed ${feed.id}`)
|
||||
return this.bulkCreate(feedEpisodeObjs, { transaction })
|
||||
Logger.info(`[FeedEpisode] Upserting ${feedEpisodeObjs.length} episodes for feed ${feed.id} (${numExisting} existing)`)
|
||||
return this.bulkCreate(feedEpisodeObjs, { transaction, updateOnDuplicate: ['title', 'author', 'description', 'siteURL', 'enclosureURL', 'enclosureType', 'enclosureSize', 'pubDate', 'season', 'episode', 'episodeType', 'duration', 'filePath', 'explicit'] })
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -127,11 +135,12 @@ class FeedEpisode extends Model {
|
||||
* @param {string} slug
|
||||
* @param {import('./Book').AudioFileObject} audioTrack
|
||||
* @param {boolean} useChapterTitles
|
||||
* @param {string} [existingEpisodeId]
|
||||
*/
|
||||
static getFeedEpisodeObjFromAudiobookTrack(book, pubDateStart, feed, slug, audioTrack, useChapterTitles) {
|
||||
static getFeedEpisodeObjFromAudiobookTrack(book, pubDateStart, feed, slug, audioTrack, useChapterTitles, existingEpisodeId = null) {
|
||||
// Example: <pubDate>Fri, 04 Feb 2015 00:00:00 GMT</pubDate>
|
||||
let timeOffset = isNaN(audioTrack.index) ? 0 : Number(audioTrack.index) * 1000 // Offset pubdate to ensure correct order
|
||||
let episodeId = uuidv4()
|
||||
let episodeId = existingEpisodeId || uuidv4()
|
||||
|
||||
// e.g. Track 1 will have a pub date before Track 2
|
||||
const audiobookPubDate = date.format(new Date(pubDateStart.valueOf() + timeOffset), 'ddd, DD MMM YYYY HH:mm:ss [GMT]')
|
||||
@@ -179,11 +188,18 @@ class FeedEpisode extends Model {
|
||||
const useChapterTitles = this.checkUseChapterTitlesForEpisodes(libraryItemExpanded.media)
|
||||
|
||||
const feedEpisodeObjs = []
|
||||
let numExisting = 0
|
||||
for (const track of libraryItemExpanded.media.trackList) {
|
||||
feedEpisodeObjs.push(this.getFeedEpisodeObjFromAudiobookTrack(libraryItemExpanded.media, libraryItemExpanded.createdAt, feed, slug, track, useChapterTitles))
|
||||
// Check for existing episode by filepath
|
||||
const existingEpisode = feed.feedEpisodes?.find((episode) => {
|
||||
return episode.filePath === track.metadata.path
|
||||
})
|
||||
numExisting = existingEpisode ? numExisting + 1 : numExisting
|
||||
|
||||
feedEpisodeObjs.push(this.getFeedEpisodeObjFromAudiobookTrack(libraryItemExpanded.media, libraryItemExpanded.createdAt, feed, slug, track, useChapterTitles, existingEpisode?.id))
|
||||
}
|
||||
Logger.info(`[FeedEpisode] Creating ${feedEpisodeObjs.length} episodes for feed ${feed.id}`)
|
||||
return this.bulkCreate(feedEpisodeObjs, { transaction })
|
||||
Logger.info(`[FeedEpisode] Upserting ${feedEpisodeObjs.length} episodes for feed ${feed.id} (${numExisting} existing)`)
|
||||
return this.bulkCreate(feedEpisodeObjs, { transaction, updateOnDuplicate: ['title', 'author', 'description', 'siteURL', 'enclosureURL', 'enclosureType', 'enclosureSize', 'pubDate', 'season', 'episode', 'episodeType', 'duration', 'filePath', 'explicit'] })
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -200,14 +216,21 @@ class FeedEpisode extends Model {
|
||||
}).libraryItem.createdAt
|
||||
|
||||
const feedEpisodeObjs = []
|
||||
let numExisting = 0
|
||||
for (const book of books) {
|
||||
const useChapterTitles = this.checkUseChapterTitlesForEpisodes(book)
|
||||
for (const track of book.trackList) {
|
||||
feedEpisodeObjs.push(this.getFeedEpisodeObjFromAudiobookTrack(book, earliestLibraryItemCreatedAt, feed, slug, track, useChapterTitles))
|
||||
// Check for existing episode by filepath
|
||||
const existingEpisode = feed.feedEpisodes?.find((episode) => {
|
||||
return episode.filePath === track.metadata.path
|
||||
})
|
||||
numExisting = existingEpisode ? numExisting + 1 : numExisting
|
||||
|
||||
feedEpisodeObjs.push(this.getFeedEpisodeObjFromAudiobookTrack(book, earliestLibraryItemCreatedAt, feed, slug, track, useChapterTitles, existingEpisode?.id))
|
||||
}
|
||||
}
|
||||
Logger.info(`[FeedEpisode] Creating ${feedEpisodeObjs.length} episodes for feed ${feed.id}`)
|
||||
return this.bulkCreate(feedEpisodeObjs, { transaction })
|
||||
Logger.info(`[FeedEpisode] Upserting ${feedEpisodeObjs.length} episodes for feed ${feed.id} (${numExisting} existing)`)
|
||||
return this.bulkCreate(feedEpisodeObjs, { transaction, updateOnDuplicate: ['title', 'author', 'description', 'siteURL', 'enclosureURL', 'enclosureType', 'enclosureSize', 'pubDate', 'season', 'episode', 'episodeType', 'duration', 'filePath', 'explicit'] })
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -123,7 +123,7 @@ class LibraryItem extends Model {
|
||||
}
|
||||
|
||||
/**
|
||||
* Currently unused because this is too slow and uses too much mem
|
||||
*
|
||||
* @param {import('sequelize').WhereOptions} [where]
|
||||
* @returns {Array<objects.LibraryItem>} old library items
|
||||
*/
|
||||
@@ -865,54 +865,6 @@ class LibraryItem extends Model {
|
||||
return libraryItem.media.coverPath
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {import('sequelize').FindOptions} options
|
||||
* @returns {Promise<Book|Podcast>}
|
||||
*/
|
||||
getMedia(options) {
|
||||
if (!this.mediaType) return Promise.resolve(null)
|
||||
const mixinMethodName = `get${this.sequelize.uppercaseFirst(this.mediaType)}`
|
||||
return this[mixinMethodName](options)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns {Promise<Book|Podcast>}
|
||||
*/
|
||||
getMediaExpanded() {
|
||||
if (this.mediaType === 'podcast') {
|
||||
return this.getMedia({
|
||||
include: [
|
||||
{
|
||||
model: this.sequelize.models.podcastEpisode
|
||||
}
|
||||
]
|
||||
})
|
||||
} else {
|
||||
return this.getMedia({
|
||||
include: [
|
||||
{
|
||||
model: this.sequelize.models.author,
|
||||
through: {
|
||||
attributes: []
|
||||
}
|
||||
},
|
||||
{
|
||||
model: this.sequelize.models.series,
|
||||
through: {
|
||||
attributes: ['sequence']
|
||||
}
|
||||
}
|
||||
],
|
||||
order: [
|
||||
[this.sequelize.models.author, this.sequelize.models.bookAuthor, 'createdAt', 'ASC'],
|
||||
[this.sequelize.models.series, 'bookSeries', 'createdAt', 'ASC']
|
||||
]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns {Promise}
|
||||
@@ -1061,6 +1013,9 @@ class LibraryItem extends Model {
|
||||
{
|
||||
fields: ['libraryId', 'mediaType']
|
||||
},
|
||||
{
|
||||
fields: ['libraryId', 'mediaType', 'size']
|
||||
},
|
||||
{
|
||||
fields: ['libraryId', 'mediaId', 'mediaType']
|
||||
},
|
||||
@@ -1128,6 +1083,64 @@ class LibraryItem extends Model {
|
||||
})
|
||||
}
|
||||
|
||||
get isBook() {
|
||||
return this.mediaType === 'book'
|
||||
}
|
||||
get isPodcast() {
|
||||
return this.mediaType === 'podcast'
|
||||
}
|
||||
get hasAudioTracks() {
|
||||
return this.media.hasAudioTracks()
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {import('sequelize').FindOptions} options
|
||||
* @returns {Promise<Book|Podcast>}
|
||||
*/
|
||||
getMedia(options) {
|
||||
if (!this.mediaType) return Promise.resolve(null)
|
||||
const mixinMethodName = `get${this.sequelize.uppercaseFirst(this.mediaType)}`
|
||||
return this[mixinMethodName](options)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns {Promise<Book|Podcast>}
|
||||
*/
|
||||
getMediaExpanded() {
|
||||
if (this.mediaType === 'podcast') {
|
||||
return this.getMedia({
|
||||
include: [
|
||||
{
|
||||
model: this.sequelize.models.podcastEpisode
|
||||
}
|
||||
]
|
||||
})
|
||||
} else {
|
||||
return this.getMedia({
|
||||
include: [
|
||||
{
|
||||
model: this.sequelize.models.author,
|
||||
through: {
|
||||
attributes: []
|
||||
}
|
||||
},
|
||||
{
|
||||
model: this.sequelize.models.series,
|
||||
through: {
|
||||
attributes: ['sequence']
|
||||
}
|
||||
}
|
||||
],
|
||||
order: [
|
||||
[this.sequelize.models.author, this.sequelize.models.bookAuthor, 'createdAt', 'ASC'],
|
||||
[this.sequelize.models.series, 'bookSeries', 'createdAt', 'ASC']
|
||||
]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if book or podcast library item has audio tracks
|
||||
* Requires expanded library item
|
||||
@@ -1139,12 +1152,133 @@ class LibraryItem extends Model {
|
||||
Logger.error(`[LibraryItem] hasAudioTracks: Library item "${this.id}" does not have media`)
|
||||
return false
|
||||
}
|
||||
if (this.mediaType === 'book') {
|
||||
if (this.isBook) {
|
||||
return this.media.audioFiles?.length > 0
|
||||
} else {
|
||||
return this.media.podcastEpisodes?.length > 0
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} ino
|
||||
* @returns {import('./Book').AudioFileObject}
|
||||
*/
|
||||
getAudioFileWithIno(ino) {
|
||||
if (!this.media) {
|
||||
Logger.error(`[LibraryItem] getAudioFileWithIno: Library item "${this.id}" does not have media`)
|
||||
return null
|
||||
}
|
||||
if (this.isBook) {
|
||||
return this.media.audioFiles.find((af) => af.ino === ino)
|
||||
} else {
|
||||
return this.media.podcastEpisodes.find((pe) => pe.audioFile?.ino === ino)?.audioFile
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} ino
|
||||
* @returns {LibraryFile}
|
||||
*/
|
||||
getLibraryFileWithIno(ino) {
|
||||
const libraryFile = this.libraryFiles.find((lf) => lf.ino === ino)
|
||||
if (!libraryFile) return null
|
||||
return new LibraryFile(libraryFile)
|
||||
}
|
||||
|
||||
getLibraryFiles() {
|
||||
return this.libraryFiles.map((lf) => new LibraryFile(lf))
|
||||
}
|
||||
|
||||
getLibraryFilesJson() {
|
||||
return this.libraryFiles.map((lf) => new LibraryFile(lf).toJSON())
|
||||
}
|
||||
|
||||
toOldJSON() {
|
||||
if (!this.media) {
|
||||
throw new Error(`[LibraryItem] Cannot convert to old JSON without media for library item "${this.id}"`)
|
||||
}
|
||||
|
||||
return {
|
||||
id: this.id,
|
||||
ino: this.ino,
|
||||
oldLibraryItemId: this.extraData?.oldLibraryItemId || null,
|
||||
libraryId: this.libraryId,
|
||||
folderId: this.libraryFolderId,
|
||||
path: this.path,
|
||||
relPath: this.relPath,
|
||||
isFile: this.isFile,
|
||||
mtimeMs: this.mtime?.valueOf(),
|
||||
ctimeMs: this.ctime?.valueOf(),
|
||||
birthtimeMs: this.birthtime?.valueOf(),
|
||||
addedAt: this.createdAt.valueOf(),
|
||||
updatedAt: this.updatedAt.valueOf(),
|
||||
lastScan: this.lastScan?.valueOf(),
|
||||
scanVersion: this.lastScanVersion,
|
||||
isMissing: !!this.isMissing,
|
||||
isInvalid: !!this.isInvalid,
|
||||
mediaType: this.mediaType,
|
||||
media: this.media.toOldJSON(this.id),
|
||||
// LibraryFile JSON includes a fileType property that may not be saved in libraryFiles column in the database
|
||||
libraryFiles: this.getLibraryFilesJson()
|
||||
}
|
||||
}
|
||||
|
||||
toOldJSONMinified() {
|
||||
if (!this.media) {
|
||||
throw new Error(`[LibraryItem] Cannot convert to old JSON without media for library item "${this.id}"`)
|
||||
}
|
||||
|
||||
return {
|
||||
id: this.id,
|
||||
ino: this.ino,
|
||||
oldLibraryItemId: this.extraData?.oldLibraryItemId || null,
|
||||
libraryId: this.libraryId,
|
||||
folderId: this.libraryFolderId,
|
||||
path: this.path,
|
||||
relPath: this.relPath,
|
||||
isFile: this.isFile,
|
||||
mtimeMs: this.mtime?.valueOf(),
|
||||
ctimeMs: this.ctime?.valueOf(),
|
||||
birthtimeMs: this.birthtime?.valueOf(),
|
||||
addedAt: this.createdAt.valueOf(),
|
||||
updatedAt: this.updatedAt.valueOf(),
|
||||
isMissing: !!this.isMissing,
|
||||
isInvalid: !!this.isInvalid,
|
||||
mediaType: this.mediaType,
|
||||
media: this.media.toOldJSONMinified(),
|
||||
numFiles: this.libraryFiles.length,
|
||||
size: this.size
|
||||
}
|
||||
}
|
||||
|
||||
toOldJSONExpanded() {
|
||||
return {
|
||||
id: this.id,
|
||||
ino: this.ino,
|
||||
oldLibraryItemId: this.extraData?.oldLibraryItemId || null,
|
||||
libraryId: this.libraryId,
|
||||
folderId: this.libraryFolderId,
|
||||
path: this.path,
|
||||
relPath: this.relPath,
|
||||
isFile: this.isFile,
|
||||
mtimeMs: this.mtime?.valueOf(),
|
||||
ctimeMs: this.ctime?.valueOf(),
|
||||
birthtimeMs: this.birthtime?.valueOf(),
|
||||
addedAt: this.createdAt.valueOf(),
|
||||
updatedAt: this.updatedAt.valueOf(),
|
||||
lastScan: this.lastScan?.valueOf(),
|
||||
scanVersion: this.lastScanVersion,
|
||||
isMissing: !!this.isMissing,
|
||||
isInvalid: !!this.isInvalid,
|
||||
mediaType: this.mediaType,
|
||||
media: this.media.toOldJSONExpanded(this.id),
|
||||
// LibraryFile JSON includes a fileType property that may not be saved in libraryFiles column in the database
|
||||
libraryFiles: this.getLibraryFilesJson(),
|
||||
size: this.size
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = LibraryItem
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
const { DataTypes, Model, Op, literal } = require('sequelize')
|
||||
const { DataTypes, Model, Op } = require('sequelize')
|
||||
const Logger = require('../Logger')
|
||||
|
||||
const oldPlaylist = require('../objects/Playlist')
|
||||
|
||||
class Playlist extends Model {
|
||||
constructor(values, options) {
|
||||
super(values, options)
|
||||
@@ -21,134 +19,23 @@ class Playlist extends Model {
|
||||
this.createdAt
|
||||
/** @type {Date} */
|
||||
this.updatedAt
|
||||
}
|
||||
|
||||
static getOldPlaylist(playlistExpanded) {
|
||||
const items = playlistExpanded.playlistMediaItems
|
||||
.map((pmi) => {
|
||||
const mediaItem = pmi.mediaItem || pmi.dataValues?.mediaItem
|
||||
const libraryItemId = mediaItem?.podcast?.libraryItem?.id || mediaItem?.libraryItem?.id || null
|
||||
if (!libraryItemId) {
|
||||
Logger.error(`[Playlist] Invalid playlist media item - No library item id found`, JSON.stringify(pmi, null, 2))
|
||||
return null
|
||||
}
|
||||
return {
|
||||
episodeId: pmi.mediaItemType === 'podcastEpisode' ? pmi.mediaItemId : '',
|
||||
libraryItemId
|
||||
}
|
||||
})
|
||||
.filter((pmi) => pmi)
|
||||
// Expanded properties
|
||||
|
||||
return new oldPlaylist({
|
||||
id: playlistExpanded.id,
|
||||
libraryId: playlistExpanded.libraryId,
|
||||
userId: playlistExpanded.userId,
|
||||
name: playlistExpanded.name,
|
||||
description: playlistExpanded.description,
|
||||
items,
|
||||
lastUpdate: playlistExpanded.updatedAt.valueOf(),
|
||||
createdAt: playlistExpanded.createdAt.valueOf()
|
||||
})
|
||||
/** @type {import('./PlaylistMediaItem')[]} - only set when expanded */
|
||||
this.playlistMediaItems
|
||||
}
|
||||
|
||||
/**
|
||||
* Get old playlist toJSONExpanded
|
||||
* @param {string[]} [include]
|
||||
* @returns {Promise<oldPlaylist>} oldPlaylist.toJSONExpanded
|
||||
*/
|
||||
async getOldJsonExpanded(include) {
|
||||
this.playlistMediaItems =
|
||||
(await this.getPlaylistMediaItems({
|
||||
include: [
|
||||
{
|
||||
model: this.sequelize.models.book,
|
||||
include: this.sequelize.models.libraryItem
|
||||
},
|
||||
{
|
||||
model: this.sequelize.models.podcastEpisode,
|
||||
include: {
|
||||
model: this.sequelize.models.podcast,
|
||||
include: this.sequelize.models.libraryItem
|
||||
}
|
||||
}
|
||||
],
|
||||
order: [['order', 'ASC']]
|
||||
})) || []
|
||||
|
||||
const oldPlaylist = this.sequelize.models.playlist.getOldPlaylist(this)
|
||||
const libraryItemIds = oldPlaylist.items.map((i) => i.libraryItemId)
|
||||
|
||||
let libraryItems = await this.sequelize.models.libraryItem.getAllOldLibraryItems({
|
||||
id: libraryItemIds
|
||||
})
|
||||
|
||||
const playlistExpanded = oldPlaylist.toJSONExpanded(libraryItems)
|
||||
|
||||
return playlistExpanded
|
||||
}
|
||||
|
||||
static createFromOld(oldPlaylist) {
|
||||
const playlist = this.getFromOld(oldPlaylist)
|
||||
return this.create(playlist)
|
||||
}
|
||||
|
||||
static getFromOld(oldPlaylist) {
|
||||
return {
|
||||
id: oldPlaylist.id,
|
||||
name: oldPlaylist.name,
|
||||
description: oldPlaylist.description,
|
||||
userId: oldPlaylist.userId,
|
||||
libraryId: oldPlaylist.libraryId
|
||||
}
|
||||
}
|
||||
|
||||
static removeById(playlistId) {
|
||||
return this.destroy({
|
||||
where: {
|
||||
id: playlistId
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get playlist by id
|
||||
* @param {string} playlistId
|
||||
* @returns {Promise<oldPlaylist|null>} returns null if not found
|
||||
*/
|
||||
static async getById(playlistId) {
|
||||
if (!playlistId) return null
|
||||
const playlist = await this.findByPk(playlistId, {
|
||||
include: {
|
||||
model: this.sequelize.models.playlistMediaItem,
|
||||
include: [
|
||||
{
|
||||
model: this.sequelize.models.book,
|
||||
include: this.sequelize.models.libraryItem
|
||||
},
|
||||
{
|
||||
model: this.sequelize.models.podcastEpisode,
|
||||
include: {
|
||||
model: this.sequelize.models.podcast,
|
||||
include: this.sequelize.models.libraryItem
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
order: [['playlistMediaItems', 'order', 'ASC']]
|
||||
})
|
||||
if (!playlist) return null
|
||||
return this.getOldPlaylist(playlist)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get old playlists for user and optionally for library
|
||||
* Get old playlists for user and library
|
||||
*
|
||||
* @param {string} userId
|
||||
* @param {string} [libraryId]
|
||||
* @returns {Promise<oldPlaylist[]>}
|
||||
* @param {string} libraryId
|
||||
* @async
|
||||
*/
|
||||
static async getOldPlaylistsForUserAndLibrary(userId, libraryId = null) {
|
||||
static async getOldPlaylistsForUserAndLibrary(userId, libraryId) {
|
||||
if (!userId && !libraryId) return []
|
||||
|
||||
const whereQuery = {}
|
||||
if (userId) {
|
||||
whereQuery.userId = userId
|
||||
@@ -163,7 +50,23 @@ class Playlist extends Model {
|
||||
include: [
|
||||
{
|
||||
model: this.sequelize.models.book,
|
||||
include: this.sequelize.models.libraryItem
|
||||
include: [
|
||||
{
|
||||
model: this.sequelize.models.libraryItem
|
||||
},
|
||||
{
|
||||
model: this.sequelize.models.author,
|
||||
through: {
|
||||
attributes: []
|
||||
}
|
||||
},
|
||||
{
|
||||
model: this.sequelize.models.series,
|
||||
through: {
|
||||
attributes: ['sequence']
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
model: this.sequelize.models.podcastEpisode,
|
||||
@@ -174,42 +77,13 @@ class Playlist extends Model {
|
||||
}
|
||||
]
|
||||
},
|
||||
order: [
|
||||
[literal('name COLLATE NOCASE'), 'ASC'],
|
||||
['playlistMediaItems', 'order', 'ASC']
|
||||
]
|
||||
order: [['playlistMediaItems', 'order', 'ASC']]
|
||||
})
|
||||
|
||||
const oldPlaylists = []
|
||||
for (const playlistExpanded of playlistsExpanded) {
|
||||
const oldPlaylist = this.getOldPlaylist(playlistExpanded)
|
||||
const libraryItems = []
|
||||
for (const pmi of playlistExpanded.playlistMediaItems) {
|
||||
let mediaItem = pmi.mediaItem || pmi.dataValues.mediaItem
|
||||
// Sort by name asc
|
||||
playlistsExpanded.sort((a, b) => a.name.localeCompare(b.name))
|
||||
|
||||
if (!mediaItem) {
|
||||
Logger.error(`[Playlist] Invalid playlist media item - No media item found`, JSON.stringify(mediaItem, null, 2))
|
||||
continue
|
||||
}
|
||||
let libraryItem = mediaItem.libraryItem || mediaItem.podcast?.libraryItem
|
||||
|
||||
if (mediaItem.podcast) {
|
||||
libraryItem.media = mediaItem.podcast
|
||||
libraryItem.media.podcastEpisodes = [mediaItem]
|
||||
delete mediaItem.podcast.libraryItem
|
||||
} else {
|
||||
libraryItem.media = mediaItem
|
||||
delete mediaItem.libraryItem
|
||||
}
|
||||
|
||||
const oldLibraryItem = this.sequelize.models.libraryItem.getOldLibraryItem(libraryItem)
|
||||
libraryItems.push(oldLibraryItem)
|
||||
}
|
||||
const oldPlaylistJson = oldPlaylist.toJSONExpanded(libraryItems)
|
||||
oldPlaylists.push(oldPlaylistJson)
|
||||
}
|
||||
|
||||
return oldPlaylists
|
||||
return playlistsExpanded.map((playlist) => playlist.toOldJSONExpanded())
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -345,6 +219,117 @@ class Playlist extends Model {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all media items in playlist expanded with library item
|
||||
*
|
||||
* @returns {Promise<import('./PlaylistMediaItem')[]>}
|
||||
*/
|
||||
getMediaItemsExpandedWithLibraryItem() {
|
||||
return this.getPlaylistMediaItems({
|
||||
include: [
|
||||
{
|
||||
model: this.sequelize.models.book,
|
||||
include: [
|
||||
{
|
||||
model: this.sequelize.models.libraryItem
|
||||
},
|
||||
{
|
||||
model: this.sequelize.models.author,
|
||||
through: {
|
||||
attributes: []
|
||||
}
|
||||
},
|
||||
{
|
||||
model: this.sequelize.models.series,
|
||||
through: {
|
||||
attributes: ['sequence']
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
model: this.sequelize.models.podcastEpisode,
|
||||
include: [
|
||||
{
|
||||
model: this.sequelize.models.podcast,
|
||||
include: this.sequelize.models.libraryItem
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
order: [['order', 'ASC']]
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get playlists toOldJSONExpanded
|
||||
*
|
||||
* @async
|
||||
*/
|
||||
async getOldJsonExpanded() {
|
||||
this.playlistMediaItems = await this.getMediaItemsExpandedWithLibraryItem()
|
||||
return this.toOldJSONExpanded()
|
||||
}
|
||||
|
||||
/**
|
||||
* Old model used libraryItemId instead of bookId
|
||||
*
|
||||
* @param {string} libraryItemId
|
||||
* @param {string} [episodeId]
|
||||
*/
|
||||
checkHasMediaItem(libraryItemId, episodeId) {
|
||||
if (!this.playlistMediaItems) {
|
||||
throw new Error('playlistMediaItems are required to check Playlist')
|
||||
}
|
||||
if (episodeId) {
|
||||
return this.playlistMediaItems.some((pmi) => pmi.mediaItemId === episodeId)
|
||||
}
|
||||
return this.playlistMediaItems.some((pmi) => pmi.mediaItem.libraryItem.id === libraryItemId)
|
||||
}
|
||||
|
||||
toOldJSON() {
|
||||
return {
|
||||
id: this.id,
|
||||
name: this.name,
|
||||
libraryId: this.libraryId,
|
||||
userId: this.userId,
|
||||
description: this.description,
|
||||
lastUpdate: this.updatedAt.valueOf(),
|
||||
createdAt: this.createdAt.valueOf()
|
||||
}
|
||||
}
|
||||
|
||||
toOldJSONExpanded() {
|
||||
if (!this.playlistMediaItems) {
|
||||
throw new Error('playlistMediaItems are required to expand Playlist')
|
||||
}
|
||||
|
||||
const json = this.toOldJSON()
|
||||
json.items = this.playlistMediaItems.map((pmi) => {
|
||||
if (pmi.mediaItemType === 'book') {
|
||||
const libraryItem = pmi.mediaItem.libraryItem
|
||||
delete pmi.mediaItem.libraryItem
|
||||
libraryItem.media = pmi.mediaItem
|
||||
return {
|
||||
libraryItemId: libraryItem.id,
|
||||
libraryItem: this.sequelize.models.libraryItem.getOldLibraryItem(libraryItem).toJSONExpanded()
|
||||
}
|
||||
}
|
||||
|
||||
const libraryItem = pmi.mediaItem.podcast.libraryItem
|
||||
delete pmi.mediaItem.podcast.libraryItem
|
||||
libraryItem.media = pmi.mediaItem.podcast
|
||||
return {
|
||||
episodeId: pmi.mediaItemId,
|
||||
episode: pmi.mediaItem.toOldJSONExpanded(libraryItem.id),
|
||||
libraryItemId: libraryItem.id,
|
||||
libraryItem: this.sequelize.models.libraryItem.getOldLibraryItem(libraryItem).toJSONMinified()
|
||||
}
|
||||
})
|
||||
|
||||
return json
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Playlist
|
||||
|
||||
@@ -16,15 +16,11 @@ class PlaylistMediaItem extends Model {
|
||||
this.playlistId
|
||||
/** @type {Date} */
|
||||
this.createdAt
|
||||
}
|
||||
|
||||
static removeByIds(playlistId, mediaItemId) {
|
||||
return this.destroy({
|
||||
where: {
|
||||
playlistId,
|
||||
mediaItemId
|
||||
}
|
||||
})
|
||||
// Expanded properties
|
||||
|
||||
/** @type {import('./Book')|import('./PodcastEpisode')} - only set when expanded */
|
||||
this.mediaItem
|
||||
}
|
||||
|
||||
getMediaItem(options) {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
const { DataTypes, Model } = require('sequelize')
|
||||
const { getTitlePrefixAtEnd, getTitleIgnorePrefix } = require('../utils')
|
||||
const Logger = require('../Logger')
|
||||
|
||||
/**
|
||||
* @typedef PodcastExpandedProperties
|
||||
@@ -47,6 +49,8 @@ class Podcast extends Model {
|
||||
this.lastEpisodeCheck
|
||||
/** @type {number} */
|
||||
this.maxEpisodesToKeep
|
||||
/** @type {number} */
|
||||
this.maxNewEpisodesToDownload
|
||||
/** @type {string} */
|
||||
this.coverPath
|
||||
/** @type {string[]} */
|
||||
@@ -57,6 +61,9 @@ class Podcast extends Model {
|
||||
this.createdAt
|
||||
/** @type {Date} */
|
||||
this.updatedAt
|
||||
|
||||
/** @type {import('./PodcastEpisode')[]} */
|
||||
this.podcastEpisodes
|
||||
}
|
||||
|
||||
static getOldPodcast(libraryItemExpanded) {
|
||||
@@ -119,25 +126,6 @@ class Podcast extends Model {
|
||||
}
|
||||
}
|
||||
|
||||
getAbsMetadataJson() {
|
||||
return {
|
||||
tags: this.tags || [],
|
||||
title: this.title,
|
||||
author: this.author,
|
||||
description: this.description,
|
||||
releaseDate: this.releaseDate,
|
||||
genres: this.genres || [],
|
||||
feedURL: this.feedURL,
|
||||
imageURL: this.imageURL,
|
||||
itunesPageURL: this.itunesPageURL,
|
||||
itunesId: this.itunesId,
|
||||
itunesArtistId: this.itunesArtistId,
|
||||
language: this.language,
|
||||
explicit: !!this.explicit,
|
||||
podcastType: this.podcastType
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize model
|
||||
* @param {import('../Database').sequelize} sequelize
|
||||
@@ -179,6 +167,210 @@ class Podcast extends Model {
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
get hasMediaFiles() {
|
||||
return !!this.podcastEpisodes?.length
|
||||
}
|
||||
|
||||
get hasAudioTracks() {
|
||||
return this.hasMediaFiles
|
||||
}
|
||||
|
||||
get size() {
|
||||
if (!this.podcastEpisodes?.length) return 0
|
||||
return this.podcastEpisodes.reduce((total, episode) => total + episode.size, 0)
|
||||
}
|
||||
|
||||
getAbsMetadataJson() {
|
||||
return {
|
||||
tags: this.tags || [],
|
||||
title: this.title,
|
||||
author: this.author,
|
||||
description: this.description,
|
||||
releaseDate: this.releaseDate,
|
||||
genres: this.genres || [],
|
||||
feedURL: this.feedURL,
|
||||
imageURL: this.imageURL,
|
||||
itunesPageURL: this.itunesPageURL,
|
||||
itunesId: this.itunesId,
|
||||
itunesArtistId: this.itunesArtistId,
|
||||
language: this.language,
|
||||
explicit: !!this.explicit,
|
||||
podcastType: this.podcastType
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Object} payload - Old podcast object
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async updateFromRequest(payload) {
|
||||
if (!payload) return false
|
||||
|
||||
let hasUpdates = false
|
||||
|
||||
if (payload.metadata) {
|
||||
const stringKeys = ['title', 'author', 'releaseDate', 'feedUrl', 'imageUrl', 'description', 'itunesPageUrl', 'itunesId', 'itunesArtistId', 'language', 'type']
|
||||
stringKeys.forEach((key) => {
|
||||
let newKey = key
|
||||
if (key === 'type') {
|
||||
newKey = 'podcastType'
|
||||
} else if (key === 'feedUrl') {
|
||||
newKey = 'feedURL'
|
||||
} else if (key === 'imageUrl') {
|
||||
newKey = 'imageURL'
|
||||
} else if (key === 'itunesPageUrl') {
|
||||
newKey = 'itunesPageURL'
|
||||
}
|
||||
if (typeof payload.metadata[key] === 'string' && payload.metadata[key] !== this[newKey]) {
|
||||
this[newKey] = payload.metadata[key]
|
||||
if (key === 'title') {
|
||||
this.titleIgnorePrefix = getTitleIgnorePrefix(this.title)
|
||||
}
|
||||
|
||||
hasUpdates = true
|
||||
}
|
||||
})
|
||||
|
||||
if (payload.metadata.explicit !== undefined && payload.metadata.explicit !== this.explicit) {
|
||||
this.explicit = !!payload.metadata.explicit
|
||||
hasUpdates = true
|
||||
}
|
||||
|
||||
if (Array.isArray(payload.metadata.genres) && !payload.metadata.genres.some((item) => typeof item !== 'string') && JSON.stringify(this.genres) !== JSON.stringify(payload.metadata.genres)) {
|
||||
this.genres = payload.metadata.genres
|
||||
this.changed('genres', true)
|
||||
hasUpdates = true
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(payload.tags) && !payload.tags.some((item) => typeof item !== 'string') && JSON.stringify(this.tags) !== JSON.stringify(payload.tags)) {
|
||||
this.tags = payload.tags
|
||||
this.changed('tags', true)
|
||||
hasUpdates = true
|
||||
}
|
||||
|
||||
if (payload.autoDownloadEpisodes !== undefined && payload.autoDownloadEpisodes !== this.autoDownloadEpisodes) {
|
||||
this.autoDownloadEpisodes = !!payload.autoDownloadEpisodes
|
||||
hasUpdates = true
|
||||
}
|
||||
if (typeof payload.autoDownloadSchedule === 'string' && payload.autoDownloadSchedule !== this.autoDownloadSchedule) {
|
||||
this.autoDownloadSchedule = payload.autoDownloadSchedule
|
||||
hasUpdates = true
|
||||
}
|
||||
|
||||
const numberKeys = ['maxEpisodesToKeep', 'maxNewEpisodesToDownload']
|
||||
numberKeys.forEach((key) => {
|
||||
if (typeof payload[key] === 'number' && payload[key] !== this[key]) {
|
||||
this[key] = payload[key]
|
||||
hasUpdates = true
|
||||
}
|
||||
})
|
||||
|
||||
if (hasUpdates) {
|
||||
Logger.debug(`[Podcast] changed keys:`, this.changed())
|
||||
await this.save()
|
||||
}
|
||||
|
||||
return hasUpdates
|
||||
}
|
||||
|
||||
/**
|
||||
* Old model kept metadata in a separate object
|
||||
*/
|
||||
oldMetadataToJSON() {
|
||||
return {
|
||||
title: this.title,
|
||||
author: this.author,
|
||||
description: this.description,
|
||||
releaseDate: this.releaseDate,
|
||||
genres: [...(this.genres || [])],
|
||||
feedUrl: this.feedURL,
|
||||
imageUrl: this.imageURL,
|
||||
itunesPageUrl: this.itunesPageURL,
|
||||
itunesId: this.itunesId,
|
||||
itunesArtistId: this.itunesArtistId,
|
||||
explicit: this.explicit,
|
||||
language: this.language,
|
||||
type: this.podcastType
|
||||
}
|
||||
}
|
||||
|
||||
oldMetadataToJSONExpanded() {
|
||||
const oldMetadataJSON = this.oldMetadataToJSON()
|
||||
oldMetadataJSON.titleIgnorePrefix = getTitlePrefixAtEnd(this.title)
|
||||
return oldMetadataJSON
|
||||
}
|
||||
|
||||
/**
|
||||
* The old model stored episodes with the podcast object
|
||||
*
|
||||
* @param {string} libraryItemId
|
||||
*/
|
||||
toOldJSON(libraryItemId) {
|
||||
if (!libraryItemId) {
|
||||
throw new Error(`[Podcast] Cannot convert to old JSON because libraryItemId is not provided`)
|
||||
}
|
||||
if (!this.podcastEpisodes) {
|
||||
throw new Error(`[Podcast] Cannot convert to old JSON because episodes are not provided`)
|
||||
}
|
||||
|
||||
return {
|
||||
id: this.id,
|
||||
libraryItemId: libraryItemId,
|
||||
metadata: this.oldMetadataToJSON(),
|
||||
coverPath: this.coverPath,
|
||||
tags: [...(this.tags || [])],
|
||||
episodes: this.podcastEpisodes.map((episode) => episode.toOldJSON(libraryItemId)),
|
||||
autoDownloadEpisodes: this.autoDownloadEpisodes,
|
||||
autoDownloadSchedule: this.autoDownloadSchedule,
|
||||
lastEpisodeCheck: this.lastEpisodeCheck?.valueOf() || null,
|
||||
maxEpisodesToKeep: this.maxEpisodesToKeep,
|
||||
maxNewEpisodesToDownload: this.maxNewEpisodesToDownload
|
||||
}
|
||||
}
|
||||
|
||||
toOldJSONMinified() {
|
||||
return {
|
||||
id: this.id,
|
||||
// Minified metadata and expanded metadata are the same
|
||||
metadata: this.oldMetadataToJSONExpanded(),
|
||||
coverPath: this.coverPath,
|
||||
tags: [...(this.tags || [])],
|
||||
numEpisodes: this.podcastEpisodes?.length || 0,
|
||||
autoDownloadEpisodes: this.autoDownloadEpisodes,
|
||||
autoDownloadSchedule: this.autoDownloadSchedule,
|
||||
lastEpisodeCheck: this.lastEpisodeCheck?.valueOf() || null,
|
||||
maxEpisodesToKeep: this.maxEpisodesToKeep,
|
||||
maxNewEpisodesToDownload: this.maxNewEpisodesToDownload,
|
||||
size: this.size
|
||||
}
|
||||
}
|
||||
|
||||
toOldJSONExpanded(libraryItemId) {
|
||||
if (!libraryItemId) {
|
||||
throw new Error(`[Podcast] Cannot convert to old JSON because libraryItemId is not provided`)
|
||||
}
|
||||
if (!this.podcastEpisodes) {
|
||||
throw new Error(`[Podcast] Cannot convert to old JSON because episodes are not provided`)
|
||||
}
|
||||
|
||||
return {
|
||||
id: this.id,
|
||||
libraryItemId: libraryItemId,
|
||||
metadata: this.oldMetadataToJSONExpanded(),
|
||||
coverPath: this.coverPath,
|
||||
tags: [...(this.tags || [])],
|
||||
episodes: this.podcastEpisodes.map((e) => e.toOldJSONExpanded(libraryItemId)),
|
||||
autoDownloadEpisodes: this.autoDownloadEpisodes,
|
||||
autoDownloadSchedule: this.autoDownloadSchedule,
|
||||
lastEpisodeCheck: this.lastEpisodeCheck?.valueOf() || null,
|
||||
maxEpisodesToKeep: this.maxEpisodesToKeep,
|
||||
maxNewEpisodesToDownload: this.maxNewEpisodesToDownload,
|
||||
size: this.size
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Podcast
|
||||
|
||||
@@ -53,42 +53,6 @@ class PodcastEpisode extends Model {
|
||||
this.updatedAt
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} libraryItemId
|
||||
* @returns {oldPodcastEpisode}
|
||||
*/
|
||||
getOldPodcastEpisode(libraryItemId = null) {
|
||||
let enclosure = null
|
||||
if (this.enclosureURL) {
|
||||
enclosure = {
|
||||
url: this.enclosureURL,
|
||||
type: this.enclosureType,
|
||||
length: this.enclosureSize !== null ? String(this.enclosureSize) : null
|
||||
}
|
||||
}
|
||||
return new oldPodcastEpisode({
|
||||
libraryItemId: libraryItemId || null,
|
||||
podcastId: this.podcastId,
|
||||
id: this.id,
|
||||
oldEpisodeId: this.extraData?.oldEpisodeId || null,
|
||||
index: this.index,
|
||||
season: this.season,
|
||||
episode: this.episode,
|
||||
episodeType: this.episodeType,
|
||||
title: this.title,
|
||||
subtitle: this.subtitle,
|
||||
description: this.description,
|
||||
enclosure,
|
||||
guid: this.extraData?.guid || null,
|
||||
pubDate: this.pubDate,
|
||||
chapters: this.chapters,
|
||||
audioFile: this.audioFile,
|
||||
publishedAt: this.publishedAt?.valueOf() || null,
|
||||
addedAt: this.createdAt.valueOf(),
|
||||
updatedAt: this.updatedAt.valueOf()
|
||||
})
|
||||
}
|
||||
|
||||
static createFromOld(oldEpisode) {
|
||||
const podcastEpisode = this.getFromOld(oldEpisode)
|
||||
return this.create(podcastEpisode)
|
||||
@@ -170,6 +134,106 @@ class PodcastEpisode extends Model {
|
||||
})
|
||||
PodcastEpisode.belongsTo(podcast)
|
||||
}
|
||||
|
||||
/**
|
||||
* AudioTrack object used in old model
|
||||
*
|
||||
* @returns {import('./Book').AudioFileObject|null}
|
||||
*/
|
||||
get track() {
|
||||
if (!this.audioFile) return null
|
||||
const track = structuredClone(this.audioFile)
|
||||
track.startOffset = 0
|
||||
track.title = this.audioFile.metadata.title
|
||||
return track
|
||||
}
|
||||
|
||||
get size() {
|
||||
return this.audioFile?.metadata.size || 0
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} libraryItemId
|
||||
* @returns {oldPodcastEpisode}
|
||||
*/
|
||||
getOldPodcastEpisode(libraryItemId = null) {
|
||||
let enclosure = null
|
||||
if (this.enclosureURL) {
|
||||
enclosure = {
|
||||
url: this.enclosureURL,
|
||||
type: this.enclosureType,
|
||||
length: this.enclosureSize !== null ? String(this.enclosureSize) : null
|
||||
}
|
||||
}
|
||||
return new oldPodcastEpisode({
|
||||
libraryItemId: libraryItemId || null,
|
||||
podcastId: this.podcastId,
|
||||
id: this.id,
|
||||
oldEpisodeId: this.extraData?.oldEpisodeId || null,
|
||||
index: this.index,
|
||||
season: this.season,
|
||||
episode: this.episode,
|
||||
episodeType: this.episodeType,
|
||||
title: this.title,
|
||||
subtitle: this.subtitle,
|
||||
description: this.description,
|
||||
enclosure,
|
||||
guid: this.extraData?.guid || null,
|
||||
pubDate: this.pubDate,
|
||||
chapters: this.chapters,
|
||||
audioFile: this.audioFile,
|
||||
publishedAt: this.publishedAt?.valueOf() || null,
|
||||
addedAt: this.createdAt.valueOf(),
|
||||
updatedAt: this.updatedAt.valueOf()
|
||||
})
|
||||
}
|
||||
|
||||
toOldJSON(libraryItemId) {
|
||||
if (!libraryItemId) {
|
||||
throw new Error(`[PodcastEpisode] Cannot convert to old JSON because libraryItemId is not provided`)
|
||||
}
|
||||
|
||||
let enclosure = null
|
||||
if (this.enclosureURL) {
|
||||
enclosure = {
|
||||
url: this.enclosureURL,
|
||||
type: this.enclosureType,
|
||||
length: this.enclosureSize !== null ? String(this.enclosureSize) : null
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
libraryItemId: libraryItemId,
|
||||
podcastId: this.podcastId,
|
||||
id: this.id,
|
||||
oldEpisodeId: this.extraData?.oldEpisodeId || null,
|
||||
index: this.index,
|
||||
season: this.season,
|
||||
episode: this.episode,
|
||||
episodeType: this.episodeType,
|
||||
title: this.title,
|
||||
subtitle: this.subtitle,
|
||||
description: this.description,
|
||||
enclosure,
|
||||
guid: this.extraData?.guid || null,
|
||||
pubDate: this.pubDate,
|
||||
chapters: structuredClone(this.chapters),
|
||||
audioFile: structuredClone(this.audioFile),
|
||||
publishedAt: this.publishedAt?.valueOf() || null,
|
||||
addedAt: this.createdAt.valueOf(),
|
||||
updatedAt: this.updatedAt.valueOf()
|
||||
}
|
||||
}
|
||||
|
||||
toOldJSONExpanded(libraryItemId) {
|
||||
const json = this.toOldJSON(libraryItemId)
|
||||
|
||||
json.audioTrack = this.track
|
||||
json.size = this.size
|
||||
json.duration = this.audioFile?.duration || 0
|
||||
|
||||
return json
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PodcastEpisode
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
const uuidv4 = require("uuid").v4
|
||||
|
||||
class Collection {
|
||||
constructor(collection) {
|
||||
this.id = null
|
||||
this.libraryId = null
|
||||
|
||||
this.name = null
|
||||
this.description = null
|
||||
|
||||
this.cover = null
|
||||
this.coverFullPath = null
|
||||
this.books = []
|
||||
|
||||
this.lastUpdate = null
|
||||
this.createdAt = null
|
||||
|
||||
if (collection) {
|
||||
this.construct(collection)
|
||||
}
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return {
|
||||
id: this.id,
|
||||
libraryId: this.libraryId,
|
||||
name: this.name,
|
||||
description: this.description,
|
||||
cover: this.cover,
|
||||
coverFullPath: this.coverFullPath,
|
||||
books: [...this.books],
|
||||
lastUpdate: this.lastUpdate,
|
||||
createdAt: this.createdAt
|
||||
}
|
||||
}
|
||||
|
||||
toJSONExpanded(libraryItems, minifiedBooks = false) {
|
||||
const json = this.toJSON()
|
||||
json.books = json.books.map(bookId => {
|
||||
const book = libraryItems.find(li => li.id === bookId)
|
||||
return book ? minifiedBooks ? book.toJSONMinified() : book.toJSONExpanded() : null
|
||||
}).filter(b => !!b)
|
||||
return json
|
||||
}
|
||||
|
||||
// Expanded and filtered out items not accessible to user
|
||||
toJSONExpandedForUser(user, libraryItems) {
|
||||
const json = this.toJSON()
|
||||
json.books = json.books.map(libraryItemId => {
|
||||
const libraryItem = libraryItems.find(li => li.id === libraryItemId)
|
||||
return libraryItem ? libraryItem.toJSONExpanded() : null
|
||||
}).filter(li => {
|
||||
return li && user.checkCanAccessLibraryItem(li)
|
||||
})
|
||||
return json
|
||||
}
|
||||
|
||||
construct(collection) {
|
||||
this.id = collection.id
|
||||
this.libraryId = collection.libraryId
|
||||
this.name = collection.name
|
||||
this.description = collection.description || null
|
||||
this.cover = collection.cover || null
|
||||
this.coverFullPath = collection.coverFullPath || null
|
||||
this.books = collection.books ? [...collection.books] : []
|
||||
this.lastUpdate = collection.lastUpdate || null
|
||||
this.createdAt = collection.createdAt || null
|
||||
}
|
||||
|
||||
setData(data) {
|
||||
if (!data.libraryId || !data.name) {
|
||||
return false
|
||||
}
|
||||
this.id = uuidv4()
|
||||
this.libraryId = data.libraryId
|
||||
this.name = data.name
|
||||
this.description = data.description || null
|
||||
this.cover = data.cover || null
|
||||
this.coverFullPath = data.coverFullPath || null
|
||||
this.books = data.books ? [...data.books] : []
|
||||
this.lastUpdate = Date.now()
|
||||
this.createdAt = Date.now()
|
||||
return true
|
||||
}
|
||||
|
||||
addBook(bookId) {
|
||||
this.books.push(bookId)
|
||||
this.lastUpdate = Date.now()
|
||||
}
|
||||
|
||||
removeBook(bookId) {
|
||||
this.books = this.books.filter(bid => bid !== bookId)
|
||||
this.lastUpdate = Date.now()
|
||||
}
|
||||
|
||||
update(payload) {
|
||||
let hasUpdates = false
|
||||
for (const key in payload) {
|
||||
if (key === 'books') {
|
||||
if (payload.books && this.books.join(',') !== payload.books.join(',')) {
|
||||
this.books = [...payload.books]
|
||||
hasUpdates = true
|
||||
}
|
||||
} else if (this[key] !== undefined && this[key] !== payload[key]) {
|
||||
hasUpdates = true
|
||||
this[key] = payload[key]
|
||||
}
|
||||
}
|
||||
if (hasUpdates) {
|
||||
this.lastUpdate = Date.now()
|
||||
}
|
||||
return hasUpdates
|
||||
}
|
||||
}
|
||||
module.exports = Collection
|
||||
@@ -177,9 +177,6 @@ class LibraryItem {
|
||||
get hasAudioFiles() {
|
||||
return this.libraryFiles.some((lf) => lf.fileType === 'audio')
|
||||
}
|
||||
get hasMediaEntities() {
|
||||
return this.media.hasMediaEntities
|
||||
}
|
||||
|
||||
// Data comes from scandir library item data
|
||||
// TODO: Remove this function. Only used when creating a new podcast now
|
||||
@@ -327,20 +324,5 @@ class LibraryItem {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the EBookFile from a LibraryFile
|
||||
* If null then ebookFile will be removed from the book
|
||||
* all ebook library files that are not primary are marked as supplementary
|
||||
*
|
||||
* @param {LibraryFile} [libraryFile]
|
||||
*/
|
||||
setPrimaryEbook(ebookLibraryFile = null) {
|
||||
const ebookLibraryFiles = this.libraryFiles.filter((lf) => lf.isEBookFile)
|
||||
for (const libraryFile of ebookLibraryFiles) {
|
||||
libraryFile.isSupplementary = ebookLibraryFile?.ino !== libraryFile.ino
|
||||
}
|
||||
this.media.setEbookFile(ebookLibraryFile)
|
||||
}
|
||||
}
|
||||
module.exports = LibraryItem
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
const uuidv4 = require("uuid").v4
|
||||
|
||||
class Playlist {
|
||||
constructor(playlist) {
|
||||
this.id = null
|
||||
this.libraryId = null
|
||||
this.userId = null
|
||||
|
||||
this.name = null
|
||||
this.description = null
|
||||
|
||||
this.coverPath = null
|
||||
|
||||
// Array of objects like { libraryItemId: "", episodeId: "" } (episodeId optional)
|
||||
this.items = []
|
||||
|
||||
this.lastUpdate = null
|
||||
this.createdAt = null
|
||||
|
||||
if (playlist) {
|
||||
this.construct(playlist)
|
||||
}
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return {
|
||||
id: this.id,
|
||||
libraryId: this.libraryId,
|
||||
userId: this.userId,
|
||||
name: this.name,
|
||||
description: this.description,
|
||||
coverPath: this.coverPath,
|
||||
items: [...this.items],
|
||||
lastUpdate: this.lastUpdate,
|
||||
createdAt: this.createdAt
|
||||
}
|
||||
}
|
||||
|
||||
// Expands the items array
|
||||
toJSONExpanded(libraryItems) {
|
||||
var json = this.toJSON()
|
||||
json.items = json.items.map(item => {
|
||||
const libraryItem = libraryItems.find(li => li.id === item.libraryItemId)
|
||||
if (!libraryItem) {
|
||||
// Not found
|
||||
return null
|
||||
}
|
||||
if (item.episodeId) {
|
||||
if (!libraryItem.isPodcast) {
|
||||
// Invalid
|
||||
return null
|
||||
}
|
||||
const episode = libraryItem.media.episodes.find(ep => ep.id === item.episodeId)
|
||||
if (!episode) {
|
||||
// Not found
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
...item,
|
||||
episode: episode.toJSONExpanded(),
|
||||
libraryItem: libraryItem.toJSONMinified()
|
||||
}
|
||||
} else {
|
||||
return {
|
||||
...item,
|
||||
libraryItem: libraryItem.toJSONExpanded()
|
||||
}
|
||||
}
|
||||
}).filter(i => i)
|
||||
return json
|
||||
}
|
||||
|
||||
construct(playlist) {
|
||||
this.id = playlist.id
|
||||
this.libraryId = playlist.libraryId
|
||||
this.userId = playlist.userId
|
||||
this.name = playlist.name
|
||||
this.description = playlist.description || null
|
||||
this.coverPath = playlist.coverPath || null
|
||||
this.items = playlist.items ? playlist.items.map(i => ({ ...i })) : []
|
||||
this.lastUpdate = playlist.lastUpdate || null
|
||||
this.createdAt = playlist.createdAt || null
|
||||
}
|
||||
|
||||
setData(data) {
|
||||
if (!data.userId || !data.libraryId || !data.name) {
|
||||
return false
|
||||
}
|
||||
this.id = uuidv4()
|
||||
this.userId = data.userId
|
||||
this.libraryId = data.libraryId
|
||||
this.name = data.name
|
||||
this.description = data.description || null
|
||||
this.coverPath = data.coverPath || null
|
||||
this.items = data.items ? data.items.map(i => ({ ...i })) : []
|
||||
this.lastUpdate = Date.now()
|
||||
this.createdAt = Date.now()
|
||||
return true
|
||||
}
|
||||
|
||||
addItem(libraryItemId, episodeId = null) {
|
||||
this.items.push({
|
||||
libraryItemId,
|
||||
episodeId: episodeId || null
|
||||
})
|
||||
this.lastUpdate = Date.now()
|
||||
}
|
||||
|
||||
removeItem(libraryItemId, episodeId = null) {
|
||||
if (episodeId) this.items = this.items.filter(i => i.libraryItemId !== libraryItemId || i.episodeId !== episodeId)
|
||||
else this.items = this.items.filter(i => i.libraryItemId !== libraryItemId)
|
||||
this.lastUpdate = Date.now()
|
||||
}
|
||||
|
||||
update(payload) {
|
||||
let hasUpdates = false
|
||||
for (const key in payload) {
|
||||
if (key === 'items') {
|
||||
if (payload.items && JSON.stringify(payload.items) !== JSON.stringify(this.items)) {
|
||||
this.items = payload.items.map(i => ({ ...i }))
|
||||
hasUpdates = true
|
||||
}
|
||||
} else if (this[key] !== undefined && this[key] !== payload[key]) {
|
||||
hasUpdates = true
|
||||
this[key] = payload[key]
|
||||
}
|
||||
}
|
||||
if (hasUpdates) {
|
||||
this.lastUpdate = Date.now()
|
||||
}
|
||||
return hasUpdates
|
||||
}
|
||||
|
||||
containsItem(item) {
|
||||
if (item.episodeId) return this.items.some(i => i.libraryItemId === item.libraryItemId && i.episodeId === item.episodeId)
|
||||
return this.items.some(i => i.libraryItemId === item.libraryItemId)
|
||||
}
|
||||
|
||||
hasItemsForLibraryItem(libraryItemId) {
|
||||
return this.items.some(i => i.libraryItemId === libraryItemId)
|
||||
}
|
||||
|
||||
removeItemsForLibraryItem(libraryItemId) {
|
||||
this.items = this.items.filter(i => i.libraryItemId !== libraryItemId)
|
||||
}
|
||||
}
|
||||
module.exports = Playlist
|
||||
@@ -33,8 +33,8 @@ class Book {
|
||||
this.metadata = new BookMetadata(book.metadata)
|
||||
this.coverPath = book.coverPath
|
||||
this.tags = [...book.tags]
|
||||
this.audioFiles = book.audioFiles.map(f => new AudioFile(f))
|
||||
this.chapters = book.chapters.map(c => ({ ...c }))
|
||||
this.audioFiles = book.audioFiles.map((f) => new AudioFile(f))
|
||||
this.chapters = book.chapters.map((c) => ({ ...c }))
|
||||
this.ebookFile = book.ebookFile ? new EBookFile(book.ebookFile) : null
|
||||
this.lastCoverSearch = book.lastCoverSearch || null
|
||||
this.lastCoverSearchQuery = book.lastCoverSearchQuery || null
|
||||
@@ -47,8 +47,8 @@ class Book {
|
||||
metadata: this.metadata.toJSON(),
|
||||
coverPath: this.coverPath,
|
||||
tags: [...this.tags],
|
||||
audioFiles: this.audioFiles.map(f => f.toJSON()),
|
||||
chapters: this.chapters.map(c => ({ ...c })),
|
||||
audioFiles: this.audioFiles.map((f) => f.toJSON()),
|
||||
chapters: this.chapters.map((c) => ({ ...c })),
|
||||
ebookFile: this.ebookFile ? this.ebookFile.toJSON() : null
|
||||
}
|
||||
}
|
||||
@@ -75,11 +75,11 @@ class Book {
|
||||
metadata: this.metadata.toJSONExpanded(),
|
||||
coverPath: this.coverPath,
|
||||
tags: [...this.tags],
|
||||
audioFiles: this.audioFiles.map(f => f.toJSON()),
|
||||
chapters: this.chapters.map(c => ({ ...c })),
|
||||
audioFiles: this.audioFiles.map((f) => f.toJSON()),
|
||||
chapters: this.chapters.map((c) => ({ ...c })),
|
||||
duration: this.duration,
|
||||
size: this.size,
|
||||
tracks: this.tracks.map(t => t.toJSON()),
|
||||
tracks: this.tracks.map((t) => t.toJSON()),
|
||||
ebookFile: this.ebookFile?.toJSON() || null
|
||||
}
|
||||
}
|
||||
@@ -87,24 +87,21 @@ class Book {
|
||||
toJSONForMetadataFile() {
|
||||
return {
|
||||
tags: [...this.tags],
|
||||
chapters: this.chapters.map(c => ({ ...c })),
|
||||
chapters: this.chapters.map((c) => ({ ...c })),
|
||||
...this.metadata.toJSONForMetadataFile()
|
||||
}
|
||||
}
|
||||
|
||||
get size() {
|
||||
var total = 0
|
||||
this.audioFiles.forEach((af) => total += af.metadata.size)
|
||||
this.audioFiles.forEach((af) => (total += af.metadata.size))
|
||||
if (this.ebookFile) {
|
||||
total += this.ebookFile.metadata.size
|
||||
}
|
||||
return total
|
||||
}
|
||||
get hasMediaEntities() {
|
||||
return !!this.tracks.length || this.ebookFile
|
||||
}
|
||||
get includedAudioFiles() {
|
||||
return this.audioFiles.filter(af => !af.exclude)
|
||||
return this.audioFiles.filter((af) => !af.exclude)
|
||||
}
|
||||
get tracks() {
|
||||
let startOffset = 0
|
||||
@@ -117,7 +114,7 @@ class Book {
|
||||
}
|
||||
get duration() {
|
||||
let total = 0
|
||||
this.tracks.forEach((track) => total += track.duration)
|
||||
this.tracks.forEach((track) => (total += track.duration))
|
||||
return total
|
||||
}
|
||||
get numTracks() {
|
||||
@@ -129,8 +126,6 @@ class Book {
|
||||
|
||||
update(payload) {
|
||||
const json = this.toJSON()
|
||||
delete json.audiobooks // do not update media entities here
|
||||
delete json.ebooks
|
||||
|
||||
let hasUpdates = false
|
||||
for (const key in json) {
|
||||
@@ -149,30 +144,6 @@ class Book {
|
||||
return hasUpdates
|
||||
}
|
||||
|
||||
updateChapters(chapters) {
|
||||
var hasUpdates = this.chapters.length !== chapters.length
|
||||
if (hasUpdates) {
|
||||
this.chapters = chapters.map(ch => ({
|
||||
id: ch.id,
|
||||
start: ch.start,
|
||||
end: ch.end,
|
||||
title: ch.title
|
||||
}))
|
||||
} else {
|
||||
for (let i = 0; i < this.chapters.length; i++) {
|
||||
const currChapter = this.chapters[i]
|
||||
const newChapter = chapters[i]
|
||||
if (!hasUpdates && (currChapter.title !== newChapter.title || currChapter.start !== newChapter.start || currChapter.end !== newChapter.end)) {
|
||||
hasUpdates = true
|
||||
}
|
||||
this.chapters[i].title = newChapter.title
|
||||
this.chapters[i].start = newChapter.start
|
||||
this.chapters[i].end = newChapter.end
|
||||
}
|
||||
}
|
||||
return hasUpdates
|
||||
}
|
||||
|
||||
updateCover(coverPath) {
|
||||
coverPath = filePathToPOSIX(coverPath)
|
||||
if (this.coverPath === coverPath) return false
|
||||
@@ -180,75 +151,6 @@ class Book {
|
||||
return true
|
||||
}
|
||||
|
||||
removeFileWithInode(inode) {
|
||||
if (this.audioFiles.some(af => af.ino === inode)) {
|
||||
this.audioFiles = this.audioFiles.filter(af => af.ino !== inode)
|
||||
return true
|
||||
}
|
||||
if (this.ebookFile && this.ebookFile.ino === inode) {
|
||||
this.ebookFile = null
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Get audio file or ebook file from inode
|
||||
* @param {string} inode
|
||||
* @returns {(AudioFile|EBookFile|null)}
|
||||
*/
|
||||
findFileWithInode(inode) {
|
||||
const audioFile = this.audioFiles.find(af => af.ino === inode)
|
||||
if (audioFile) return audioFile
|
||||
if (this.ebookFile && this.ebookFile.ino === inode) return this.ebookFile
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the EBookFile from a LibraryFile
|
||||
* If null then ebookFile will be removed from the book
|
||||
*
|
||||
* @param {LibraryFile} [libraryFile]
|
||||
*/
|
||||
setEbookFile(libraryFile = null) {
|
||||
if (!libraryFile) {
|
||||
this.ebookFile = null
|
||||
} else {
|
||||
const ebookFile = new EBookFile()
|
||||
ebookFile.setData(libraryFile)
|
||||
this.ebookFile = ebookFile
|
||||
}
|
||||
}
|
||||
|
||||
addAudioFile(audioFile) {
|
||||
this.audioFiles.push(audioFile)
|
||||
}
|
||||
|
||||
updateAudioTracks(orderedFileData) {
|
||||
let index = 1
|
||||
this.audioFiles = orderedFileData.map((fileData) => {
|
||||
const audioFile = this.audioFiles.find(af => af.ino === fileData.ino)
|
||||
audioFile.manuallyVerified = true
|
||||
audioFile.error = null
|
||||
if (fileData.exclude !== undefined) {
|
||||
audioFile.exclude = !!fileData.exclude
|
||||
}
|
||||
if (audioFile.exclude) {
|
||||
audioFile.index = -1
|
||||
} else {
|
||||
audioFile.index = index++
|
||||
}
|
||||
return audioFile
|
||||
})
|
||||
|
||||
this.rebuildTracks()
|
||||
}
|
||||
|
||||
rebuildTracks() {
|
||||
Logger.debug(`[Book] Tracks being rebuilt...!`)
|
||||
this.audioFiles.sort((a, b) => a.index - b.index)
|
||||
}
|
||||
|
||||
// Only checks container format
|
||||
checkCanDirectPlay(payload) {
|
||||
var supportedMimeTypes = payload.supportedMimeTypes || []
|
||||
@@ -268,7 +170,7 @@ class Book {
|
||||
}
|
||||
|
||||
getChapters() {
|
||||
return this.chapters?.map(ch => ({ ...ch })) || []
|
||||
return this.chapters?.map((ch) => ({ ...ch })) || []
|
||||
}
|
||||
}
|
||||
module.exports = Book
|
||||
|
||||
@@ -124,9 +124,6 @@ class Podcast {
|
||||
this.episodes.forEach((ep) => (total += ep.size))
|
||||
return total
|
||||
}
|
||||
get hasMediaEntities() {
|
||||
return !!this.episodes.length
|
||||
}
|
||||
get duration() {
|
||||
let total = 0
|
||||
this.episodes.forEach((ep) => (total += ep.duration))
|
||||
@@ -181,20 +178,6 @@ class Podcast {
|
||||
return true
|
||||
}
|
||||
|
||||
removeFileWithInode(inode) {
|
||||
const hasEpisode = this.episodes.some((ep) => ep.audioFile.ino === inode)
|
||||
if (hasEpisode) {
|
||||
this.episodes = this.episodes.filter((ep) => ep.audioFile.ino !== inode)
|
||||
}
|
||||
return hasEpisode
|
||||
}
|
||||
|
||||
findFileWithInode(inode) {
|
||||
var episode = this.episodes.find((ep) => ep.audioFile.ino === inode)
|
||||
if (episode) return episode.audioFile
|
||||
return null
|
||||
}
|
||||
|
||||
setData(mediaData) {
|
||||
this.metadata = new PodcastMetadata()
|
||||
if (mediaData.metadata) {
|
||||
|
||||
@@ -202,12 +202,12 @@ class AudioFileScanner {
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {AudioFile} audioFile
|
||||
* @param {string} audioFilePath
|
||||
* @returns {object}
|
||||
*/
|
||||
probeAudioFile(audioFile) {
|
||||
Logger.debug(`[AudioFileScanner] Running ffprobe for audio file at "${audioFile.metadata.path}"`)
|
||||
return prober.rawProbe(audioFile.metadata.path)
|
||||
probeAudioFile(audioFilePath) {
|
||||
Logger.debug(`[AudioFileScanner] Running ffprobe for audio file at "${audioFilePath}"`)
|
||||
return prober.rawProbe(audioFilePath)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -82,11 +82,11 @@ describe('LibraryItemController', () => {
|
||||
})
|
||||
|
||||
it('should remove authors and series with no books on library item delete', async () => {
|
||||
const oldLibraryItem = await Database.libraryItemModel.getOldById(libraryItem1Id)
|
||||
const libraryItem = await Database.libraryItemModel.getExpandedById(libraryItem1Id)
|
||||
|
||||
const fakeReq = {
|
||||
query: {},
|
||||
libraryItem: oldLibraryItem
|
||||
libraryItem
|
||||
}
|
||||
const fakeRes = {
|
||||
sendStatus: sinon.spy()
|
||||
@@ -156,7 +156,7 @@ describe('LibraryItemController', () => {
|
||||
})
|
||||
|
||||
it('should remove authors and series with no books on library item update media', async () => {
|
||||
const oldLibraryItem = await Database.libraryItemModel.getOldById(libraryItem1Id)
|
||||
const libraryItem = await Database.libraryItemModel.getExpandedById(libraryItem1Id)
|
||||
|
||||
// Update library item 1 remove all authors and series
|
||||
const fakeReq = {
|
||||
@@ -167,7 +167,7 @@ describe('LibraryItemController', () => {
|
||||
series: []
|
||||
}
|
||||
},
|
||||
libraryItem: oldLibraryItem
|
||||
libraryItem
|
||||
}
|
||||
const fakeRes = {
|
||||
json: sinon.spy()
|
||||
|
||||
Reference in New Issue
Block a user