mirror of
https://github.com/advplyr/audiobookshelf.git
synced 2026-01-01 04:00:45 -05:00
Compare commits
17 Commits
feed-episo
...
plugin-imp
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3cae110360 | ||
|
|
c60d74774a | ||
|
|
7557f3e2b9 | ||
|
|
5f680d7277 | ||
|
|
cbbdb0ec29 | ||
|
|
c8682c8456 | ||
|
|
e7e0056288 | ||
|
|
50e84fc2d5 | ||
|
|
a762e6ca03 | ||
|
|
fe4d3c0852 | ||
|
|
048790b33a | ||
|
|
fc17a74865 | ||
|
|
cfe3deff3b | ||
|
|
5a96d8aeb3 | ||
|
|
23b480b11a | ||
|
|
ad89fb2eac | ||
|
|
62bd7e73f4 |
@@ -112,6 +112,14 @@ export default {
|
||||
}
|
||||
]
|
||||
|
||||
if (this.$store.state.pluginsEnabled) {
|
||||
configRoutes.push({
|
||||
id: 'config-plugins',
|
||||
title: 'Plugins',
|
||||
path: '/config/plugins'
|
||||
})
|
||||
}
|
||||
|
||||
if (this.currentLibraryId) {
|
||||
configRoutes.push({
|
||||
id: 'library-stats',
|
||||
|
||||
@@ -374,27 +374,19 @@ export default {
|
||||
return
|
||||
}
|
||||
|
||||
// https://developer.mozilla.org/en-US/docs/Web/API/Media_Session_API
|
||||
if ('mediaSession' in navigator) {
|
||||
const chapterInfo = []
|
||||
if (this.chapters.length) {
|
||||
this.chapters.forEach((chapter) => {
|
||||
chapterInfo.push({
|
||||
title: chapter.title,
|
||||
startTime: chapter.start
|
||||
})
|
||||
})
|
||||
}
|
||||
var coverImageSrc = this.$store.getters['globals/getLibraryItemCoverSrc'](this.streamLibraryItem, '/Logo.png', true)
|
||||
const artwork = [
|
||||
{
|
||||
src: coverImageSrc
|
||||
}
|
||||
]
|
||||
|
||||
navigator.mediaSession.metadata = new MediaMetadata({
|
||||
title: this.title,
|
||||
artist: this.playerHandler.displayAuthor || this.mediaMetadata.authorName || 'Unknown',
|
||||
album: this.mediaMetadata.seriesName || '',
|
||||
artwork: [
|
||||
{
|
||||
src: this.$store.getters['globals/getLibraryItemCoverSrc'](this.streamLibraryItem, '/Logo.png', true)
|
||||
}
|
||||
]
|
||||
artwork
|
||||
})
|
||||
console.log('Set media session metadata', navigator.mediaSession.metadata)
|
||||
|
||||
|
||||
@@ -138,6 +138,7 @@ 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) => {
|
||||
@@ -151,6 +152,7 @@ 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) => {
|
||||
@@ -165,11 +167,12 @@ export default {
|
||||
this.processing = true
|
||||
|
||||
if (this.showBatchCollectionModal) {
|
||||
// BATCH Add books
|
||||
// BATCH Remove 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) => {
|
||||
@@ -184,6 +187,7 @@ 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) => {
|
||||
@@ -210,6 +214,7 @@ 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,6 +130,7 @@ 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) => {
|
||||
@@ -147,6 +148,7 @@ 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) => {
|
||||
@@ -172,6 +174,7 @@ 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 = ''
|
||||
})
|
||||
|
||||
@@ -7,6 +7,14 @@
|
||||
|
||||
<ui-checkbox v-if="checkboxLabel" v-model="checkboxValue" checkbox-bg="bg" :label="checkboxLabel" label-class="pl-2 text-base" class="mb-6 px-1" />
|
||||
|
||||
<div v-if="formFields.length" class="mb-6 space-y-2">
|
||||
<template v-for="field in formFields">
|
||||
<ui-select-input v-if="field.type === 'select'" :key="field.name" v-model="formData[field.name]" :label="field.label" :items="field.options" class="px-1" />
|
||||
<ui-textarea-with-label v-else-if="field.type === 'textarea'" :key="field.name" v-model="formData[field.name]" :label="field.label" class="px-1" />
|
||||
<ui-text-input-with-label v-else-if="field.type === 'text'" :key="field.name" v-model="formData[field.name]" :label="field.label" class="px-1" />
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div class="flex px-1 items-center">
|
||||
<ui-btn v-if="isYesNo" color="primary" @click="nevermind">{{ $strings.ButtonCancel }}</ui-btn>
|
||||
<div class="flex-grow" />
|
||||
@@ -25,7 +33,8 @@ export default {
|
||||
return {
|
||||
el: null,
|
||||
content: null,
|
||||
checkboxValue: false
|
||||
checkboxValue: false,
|
||||
formData: {}
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
@@ -61,6 +70,9 @@ export default {
|
||||
persistent() {
|
||||
return !!this.confirmPromptOptions.persistent
|
||||
},
|
||||
formFields() {
|
||||
return this.confirmPromptOptions.formFields || []
|
||||
},
|
||||
checkboxLabel() {
|
||||
return this.confirmPromptOptions.checkboxLabel
|
||||
},
|
||||
@@ -100,11 +112,31 @@ export default {
|
||||
this.show = false
|
||||
},
|
||||
confirm() {
|
||||
if (this.callback) this.callback(true, this.checkboxValue)
|
||||
if (this.callback) {
|
||||
if (this.formFields.length) {
|
||||
const formFieldData = {
|
||||
...this.formData
|
||||
}
|
||||
|
||||
this.callback(true, formFieldData)
|
||||
} else {
|
||||
this.callback(true, this.checkboxValue)
|
||||
}
|
||||
}
|
||||
this.show = false
|
||||
},
|
||||
setShow() {
|
||||
this.checkboxValue = this.checkboxDefaultValue
|
||||
|
||||
if (this.formFields.length) {
|
||||
this.formFields.forEach((field) => {
|
||||
let defaultValue = ''
|
||||
if (field.type === 'boolean') defaultValue = false
|
||||
if (field.type === 'select') defaultValue = field.options[0].value
|
||||
this.$set(this.formData, field.name, defaultValue)
|
||||
})
|
||||
}
|
||||
|
||||
this.$eventBus.$emit('showing-prompt', true)
|
||||
document.body.appendChild(this.el)
|
||||
setTimeout(() => {
|
||||
|
||||
@@ -193,46 +193,46 @@ export default {
|
||||
buildData() {
|
||||
this.data = []
|
||||
|
||||
let maxValue = 0
|
||||
let minValue = 0
|
||||
|
||||
const dates = []
|
||||
for (let i = 0; i < this.daysToShow + 1; i++) {
|
||||
const date = i === 0 ? this.firstWeekStart : this.$addDaysToDate(this.firstWeekStart, i)
|
||||
const dateString = this.$formatJsDate(date, 'yyyy-MM-dd')
|
||||
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)
|
||||
|
||||
if (dateObj.value) {
|
||||
if (dateObj.value > maxValue) maxValue = dateObj.value
|
||||
if (!minValue || dateObj.value < minValue) minValue = dateObj.value
|
||||
}
|
||||
}
|
||||
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
|
||||
|
||||
for (const dateObj of dates) {
|
||||
let bgColor = this.bgColors[0]
|
||||
let outlineColor = this.outlineColors[0]
|
||||
if (dateObj.value) {
|
||||
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
|
||||
|
||||
var bgColor = this.bgColors[0]
|
||||
var outlineColor = this.outlineColors[0]
|
||||
if (value) {
|
||||
outlineColor = this.outlineColors[1]
|
||||
const percentOfAvg = (dateObj.value - minValue) / range
|
||||
const bgIndex = Math.floor(percentOfAvg * 4) + 1
|
||||
var percentOfAvg = (value - minValue) / range
|
||||
var bgIndex = Math.floor(percentOfAvg * 4) + 1
|
||||
bgColor = this.bgColors[bgIndex] || 'red'
|
||||
}
|
||||
|
||||
this.data.push({
|
||||
...dateObj,
|
||||
style: `transform:translate(${dateObj.col * 13}px,${dateObj.row * 13}px);background-color:${bgColor};outline:1px solid ${outlineColor};outline-offset:-1px;`
|
||||
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;`
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -218,6 +218,7 @@ export default {
|
||||
this.$toast.success(this.$strings.ToastPlaylistRemoveSuccess)
|
||||
} else {
|
||||
console.log(`Item removed from playlist`, updatedPlaylist)
|
||||
this.$toast.success(this.$strings.ToastPlaylistUpdateSuccess)
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
</div>
|
||||
</template>
|
||||
<button v-else :key="index" role="menuitem" class="flex items-center px-2 py-1.5 hover:bg-white/5 text-white text-xs cursor-pointer w-full" @click.stop="clickAction(item.action)">
|
||||
<span v-if="item.icon" class="material-symbols text-base mr-1">{{ item.icon }}</span>
|
||||
<p class="text-left">{{ item.text }}</p>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
154
client/pages/config/plugins/_id.vue
Normal file
154
client/pages/config/plugins/_id.vue
Normal file
@@ -0,0 +1,154 @@
|
||||
<template>
|
||||
<div>
|
||||
<app-settings-content :header-text="`Plugin: ${pluginManifest.name}`">
|
||||
<template #header-prefix>
|
||||
<nuxt-link to="/config/plugins" class="w-8 h-8 flex items-center justify-center rounded-full cursor-pointer hover:bg-white hover:bg-opacity-10 text-center mr-2">
|
||||
<span class="material-symbols text-2xl">arrow_back</span>
|
||||
</nuxt-link>
|
||||
</template>
|
||||
<template #header-items>
|
||||
<ui-tooltip v-if="pluginManifest.documentationUrl" :text="$strings.LabelClickForMoreInfo" class="inline-flex ml-2">
|
||||
<a :href="pluginManifest.documentationUrl" target="_blank" class="inline-flex">
|
||||
<span class="material-symbols text-xl w-5 text-gray-200">help_outline</span>
|
||||
</a>
|
||||
</ui-tooltip>
|
||||
|
||||
<div class="flex-grow" />
|
||||
|
||||
<a v-if="repositoryUrl" :href="repositoryUrl" target="_blank" class="abs-btn outline-none rounded-md shadow-md relative border border-gray-600 text-center bg-primary text-white px-4 py-1 text-sm inline-flex items-center space-x-2"><span>Source</span><span class="material-symbols text-base">open_in_new</span> </a>
|
||||
</template>
|
||||
|
||||
<div class="py-4">
|
||||
<p v-if="configDescription" class="mb-4">{{ configDescription }}</p>
|
||||
|
||||
<form v-if="configFormFields.length" @submit.prevent="handleFormSubmit">
|
||||
<template v-for="field in configFormFields">
|
||||
<div :key="field.name" class="flex items-center mb-4">
|
||||
<label :for="field.name" class="w-1/3 text-gray-200">{{ field.label }}</label>
|
||||
<div class="w-2/3">
|
||||
<input :id="field.name" :type="field.type" :placeholder="field.placeholder" class="w-full bg-bg border border-white border-opacity-20 rounded-md p-2 text-gray-200" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="flex justify-end">
|
||||
<ui-btn class="bg-primary bg-opacity-70 text-white rounded-md p-2" :loading="processing" type="submit">{{ $strings.ButtonSave }}</ui-btn>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</app-settings-content>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
async asyncData({ store, redirect, params, app }) {
|
||||
if (!store.getters['user/getIsAdminOrUp']) {
|
||||
redirect('/')
|
||||
}
|
||||
const pluginConfigData = await app.$axios.$get(`/api/plugins/${params.id}/config`).catch((error) => {
|
||||
console.error('Failed to get plugin config', error)
|
||||
return null
|
||||
})
|
||||
if (!pluginConfigData) {
|
||||
redirect('/config/plugins')
|
||||
}
|
||||
const pluginManifest = store.state.plugins.find((plugin) => plugin.id === params.id)
|
||||
if (!pluginManifest) {
|
||||
redirect('/config/plugins')
|
||||
}
|
||||
return {
|
||||
pluginManifest,
|
||||
pluginConfig: pluginConfigData.config
|
||||
}
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
processing: false
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
pluginManifestConfig() {
|
||||
return this.pluginManifest.config
|
||||
},
|
||||
pluginLocalization() {
|
||||
return this.pluginManifest.localization || {}
|
||||
},
|
||||
localizedStrings() {
|
||||
const localeKey = this.$languageCodes.current
|
||||
if (!localeKey) return {}
|
||||
return this.pluginLocalization[localeKey] || {}
|
||||
},
|
||||
configDescription() {
|
||||
if (this.pluginManifestConfig.descriptionKey && this.localizedStrings[this.pluginManifestConfig.descriptionKey]) {
|
||||
return this.localizedStrings[this.pluginManifestConfig.descriptionKey]
|
||||
}
|
||||
|
||||
return this.pluginManifestConfig.description
|
||||
},
|
||||
configFormFields() {
|
||||
return this.pluginManifestConfig.formFields || []
|
||||
},
|
||||
repositoryUrl() {
|
||||
return this.pluginManifest.repositoryUrl
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
getFormData() {
|
||||
const formData = {}
|
||||
this.configFormFields.forEach((field) => {
|
||||
if (field.type === 'checkbox') {
|
||||
formData[field.name] = document.getElementById(field.name).checked
|
||||
} else {
|
||||
formData[field.name] = document.getElementById(field.name).value
|
||||
}
|
||||
})
|
||||
return formData
|
||||
},
|
||||
handleFormSubmit() {
|
||||
const formData = this.getFormData()
|
||||
console.log('Form data', formData)
|
||||
|
||||
const payload = {
|
||||
config: formData
|
||||
}
|
||||
|
||||
this.processing = true
|
||||
|
||||
this.$axios
|
||||
.$post(`/api/plugins/${this.pluginManifest.id}/config`, payload)
|
||||
.then(() => {
|
||||
console.log('Plugin configuration saved')
|
||||
})
|
||||
.catch((error) => {
|
||||
const errorMsg = error.response?.data || 'Error saving plugin configuration'
|
||||
console.error('Failed to save config:', error)
|
||||
this.$toast.error(errorMsg)
|
||||
})
|
||||
.finally(() => {
|
||||
this.processing = false
|
||||
})
|
||||
},
|
||||
initializeForm() {
|
||||
if (!this.pluginConfig) return
|
||||
this.configFormFields.forEach((field) => {
|
||||
if (this.pluginConfig[field.name] === undefined) {
|
||||
return
|
||||
}
|
||||
|
||||
const value = this.pluginConfig[field.name]
|
||||
if (field.type === 'checkbox') {
|
||||
document.getElementById(field.name).checked = value
|
||||
} else {
|
||||
document.getElementById(field.name).value = value
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
console.log('Plugin manifest', this.pluginManifest, 'config', this.pluginConfig)
|
||||
this.initializeForm()
|
||||
},
|
||||
beforeDestroy() {}
|
||||
}
|
||||
</script>
|
||||
48
client/pages/config/plugins/index.vue
Normal file
48
client/pages/config/plugins/index.vue
Normal file
@@ -0,0 +1,48 @@
|
||||
<template>
|
||||
<div>
|
||||
<app-settings-content :header-text="'Plugins'">
|
||||
<template #header-items>
|
||||
<ui-tooltip :text="$strings.LabelClickForMoreInfo" class="inline-flex ml-2">
|
||||
<a href="https://www.audiobookshelf.org/guides" target="_blank" class="inline-flex">
|
||||
<span class="material-symbols text-xl w-5 text-gray-200">help_outline</span>
|
||||
</a>
|
||||
</ui-tooltip>
|
||||
</template>
|
||||
<div class="py-4">
|
||||
<p v-if="!plugins.length" class="text-gray-300">No plugins installed</p>
|
||||
|
||||
<template v-for="plugin in plugins">
|
||||
<nuxt-link :key="plugin.id" :to="`/config/plugins/${plugin.id}`" class="block w-full rounded bg-primary/40 hover:bg-primary/60 text-gray-300 hover:text-white p-4 my-2">
|
||||
<div class="flex items-center space-x-4">
|
||||
<p class="text-lg">{{ plugin.name }}</p>
|
||||
<p class="text-sm text-gray-300">{{ plugin.description }}</p>
|
||||
<div class="flex-grow" />
|
||||
<span class="material-symbols">arrow_forward</span>
|
||||
</div>
|
||||
</nuxt-link>
|
||||
</template>
|
||||
</div>
|
||||
</app-settings-content>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
asyncData({ store, redirect }) {
|
||||
if (!store.getters['user/getIsAdminOrUp']) {
|
||||
redirect('/')
|
||||
}
|
||||
},
|
||||
data() {
|
||||
return {}
|
||||
},
|
||||
computed: {
|
||||
plugins() {
|
||||
return this.$store.state.plugins
|
||||
}
|
||||
},
|
||||
methods: {},
|
||||
mounted() {},
|
||||
beforeDestroy() {}
|
||||
}
|
||||
</script>
|
||||
@@ -364,6 +364,9 @@ export default {
|
||||
showCollectionsButton() {
|
||||
return this.isBook && this.userCanUpdate
|
||||
},
|
||||
pluginExtensions() {
|
||||
return this.$store.getters['getPluginExtensions']('item.detail.actions')
|
||||
},
|
||||
contextMenuItems() {
|
||||
const items = []
|
||||
|
||||
@@ -429,6 +432,18 @@ export default {
|
||||
})
|
||||
}
|
||||
|
||||
if (this.pluginExtensions.length) {
|
||||
this.pluginExtensions.forEach((plugin) => {
|
||||
plugin.extensions.forEach((pext) => {
|
||||
items.push({
|
||||
text: pext.label,
|
||||
action: `plugin-${plugin.id}-action-${pext.name}`,
|
||||
icon: 'extension'
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
return items
|
||||
}
|
||||
},
|
||||
@@ -763,7 +778,54 @@ export default {
|
||||
} else if (action === 'share') {
|
||||
this.$store.commit('setSelectedLibraryItem', this.libraryItem)
|
||||
this.$store.commit('globals/setShareModal', this.mediaItemShare)
|
||||
} else if (action.startsWith('plugin-')) {
|
||||
const actionStrSplit = action.replace('plugin-', '').split('-action-')
|
||||
const pluginId = actionStrSplit[0]
|
||||
const pluginAction = actionStrSplit[1]
|
||||
this.onPluginAction(pluginId, pluginAction)
|
||||
}
|
||||
},
|
||||
onPluginAction(pluginId, pluginAction) {
|
||||
const plugin = this.pluginExtensions.find((p) => p.id === pluginId)
|
||||
const extension = plugin.extensions.find((ext) => ext.name === pluginAction)
|
||||
|
||||
if (extension.prompt) {
|
||||
const payload = {
|
||||
message: extension.prompt.message,
|
||||
formFields: extension.prompt.formFields || [],
|
||||
yesButtonText: this.$strings.ButtonSubmit,
|
||||
callback: (confirmed, promptData) => {
|
||||
if (confirmed) {
|
||||
this.sendPluginAction(pluginId, pluginAction, promptData)
|
||||
}
|
||||
},
|
||||
type: 'yesNo'
|
||||
}
|
||||
this.$store.commit('globals/setConfirmPrompt', payload)
|
||||
} else {
|
||||
this.sendPluginAction(pluginId, pluginAction)
|
||||
}
|
||||
},
|
||||
sendPluginAction(pluginId, pluginAction, promptData = null) {
|
||||
this.$axios
|
||||
.$post(`/api/plugins/${pluginId}/action`, {
|
||||
pluginAction,
|
||||
target: 'item.detail.actions',
|
||||
data: {
|
||||
entityId: this.libraryItemId,
|
||||
entityType: 'libraryItem',
|
||||
userId: this.$store.state.user.user.id,
|
||||
promptData
|
||||
}
|
||||
})
|
||||
.then((data) => {
|
||||
console.log('Plugin action response', data)
|
||||
})
|
||||
.catch((error) => {
|
||||
const errorMsg = error.response?.data || 'Plugin action failed'
|
||||
console.error('Plugin action failed:', error)
|
||||
this.$toast.error(errorMsg)
|
||||
})
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
|
||||
@@ -166,10 +166,14 @@ export default {
|
||||
|
||||
location.reload()
|
||||
},
|
||||
setUser({ user, userDefaultLibraryId, serverSettings, Source, ereaderDevices }) {
|
||||
setUser({ user, userDefaultLibraryId, serverSettings, Source, ereaderDevices, plugins }) {
|
||||
this.$store.commit('setServerSettings', serverSettings)
|
||||
this.$store.commit('setSource', Source)
|
||||
this.$store.commit('libraries/setEReaderDevices', ereaderDevices)
|
||||
if (plugins !== undefined) {
|
||||
this.$store.commit('setPlugins', plugins)
|
||||
}
|
||||
|
||||
this.$setServerLanguageCode(serverSettings.language)
|
||||
|
||||
if (serverSettings.chromecastEnabled) {
|
||||
|
||||
@@ -110,84 +110,6 @@ 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()
|
||||
@@ -204,19 +126,8 @@ export default {
|
||||
})
|
||||
},
|
||||
playPause() {
|
||||
if (this.isPlaying) {
|
||||
this.pause()
|
||||
} else {
|
||||
this.play()
|
||||
}
|
||||
},
|
||||
play() {
|
||||
if (!this.localAudioPlayer || !this.hasLoaded) return
|
||||
this.localAudioPlayer.play()
|
||||
},
|
||||
pause() {
|
||||
if (!this.localAudioPlayer || !this.hasLoaded) return
|
||||
this.localAudioPlayer.pause()
|
||||
this.localAudioPlayer.playPause()
|
||||
},
|
||||
jumpForward() {
|
||||
if (!this.localAudioPlayer || !this.hasLoaded) return
|
||||
@@ -302,7 +213,6 @@ export default {
|
||||
} else {
|
||||
this.stopPlayInterval()
|
||||
}
|
||||
this.updateMediaSessionPlaybackState()
|
||||
},
|
||||
playerTimeUpdate(time) {
|
||||
this.setCurrentTime(time)
|
||||
@@ -366,8 +276,6 @@ 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)
|
||||
|
||||
@@ -28,7 +28,9 @@ export const state = () => ({
|
||||
openModal: null,
|
||||
innerModalOpen: false,
|
||||
lastBookshelfScrollData: {},
|
||||
routerBasePath: '/'
|
||||
routerBasePath: '/',
|
||||
plugins: [],
|
||||
pluginsEnabled: false
|
||||
})
|
||||
|
||||
export const getters = {
|
||||
@@ -61,6 +63,20 @@ export const getters = {
|
||||
getHomeBookshelfView: (state) => {
|
||||
if (!state.serverSettings || isNaN(state.serverSettings.homeBookshelfView)) return Constants.BookshelfView.STANDARD
|
||||
return state.serverSettings.homeBookshelfView
|
||||
},
|
||||
getPluginExtensions: (state) => (target) => {
|
||||
if (!state.pluginsEnabled) return []
|
||||
return state.plugins
|
||||
.map((pext) => {
|
||||
const extensionsMatchingTarget = pext.extensions?.filter((ext) => ext.target === target) || []
|
||||
if (!extensionsMatchingTarget.length) return null
|
||||
return {
|
||||
id: pext.id,
|
||||
name: pext.name,
|
||||
extensions: extensionsMatchingTarget
|
||||
}
|
||||
})
|
||||
.filter(Boolean)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,5 +255,9 @@ export const mutations = {
|
||||
},
|
||||
setInnerModalOpen(state, val) {
|
||||
state.innerModalOpen = val
|
||||
},
|
||||
setPlugins(state, val) {
|
||||
state.plugins = val
|
||||
state.pluginsEnabled = true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -729,6 +729,7 @@
|
||||
"ToastBookmarkUpdateSuccess": "Отметката е обновена",
|
||||
"ToastChaptersHaveErrors": "Главите имат грешки",
|
||||
"ToastChaptersMustHaveTitles": "Главите трябва да имат заглавия",
|
||||
"ToastCollectionItemsRemoveSuccess": "Елемент(и) премахнати от колекция",
|
||||
"ToastCollectionRemoveSuccess": "Колекцията е премахната",
|
||||
"ToastCollectionUpdateSuccess": "Колекцията е обновена",
|
||||
"ToastItemCoverUpdateSuccess": "Корицата на елемента е обновена",
|
||||
|
||||
@@ -951,6 +951,8 @@
|
||||
"ToastChaptersRemoved": "অধ্যায়গুলো মুছে ফেলা হয়েছে",
|
||||
"ToastChaptersUpdated": "অধ্যায় আপডেট করা হয়েছে",
|
||||
"ToastCollectionItemsAddFailed": "আইটেম(গুলি) সংগ্রহে যোগ করা ব্যর্থ হয়েছে",
|
||||
"ToastCollectionItemsAddSuccess": "আইটেম(গুলি) সংগ্রহে যোগ করা সফল হয়েছে",
|
||||
"ToastCollectionItemsRemoveSuccess": "আইটেম(গুলি) সংগ্রহ থেকে সরানো হয়েছে",
|
||||
"ToastCollectionRemoveSuccess": "সংগ্রহ সরানো হয়েছে",
|
||||
"ToastCollectionUpdateSuccess": "সংগ্রহ আপডেট করা হয়েছে",
|
||||
"ToastCoverUpdateFailed": "কভার আপডেট ব্যর্থ হয়েছে",
|
||||
|
||||
@@ -904,6 +904,8 @@
|
||||
"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",
|
||||
|
||||
@@ -943,6 +943,7 @@
|
||||
"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",
|
||||
|
||||
@@ -640,6 +640,7 @@
|
||||
"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",
|
||||
|
||||
@@ -959,6 +959,8 @@
|
||||
"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",
|
||||
|
||||
@@ -961,6 +961,8 @@
|
||||
"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",
|
||||
|
||||
@@ -959,6 +959,8 @@
|
||||
"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",
|
||||
|
||||
@@ -713,6 +713,7 @@
|
||||
"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",
|
||||
|
||||
@@ -953,6 +953,8 @@
|
||||
"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",
|
||||
|
||||
@@ -744,6 +744,7 @@
|
||||
"ToastBookmarkUpdateSuccess": "הסימניה עודכנה בהצלחה",
|
||||
"ToastChaptersHaveErrors": "פרקים מכילים שגיאות",
|
||||
"ToastChaptersMustHaveTitles": "פרקים חייבים לכלול כותרות",
|
||||
"ToastCollectionItemsRemoveSuccess": "הפריט(ים) הוסרו מהאוסף בהצלחה",
|
||||
"ToastCollectionRemoveSuccess": "האוסף הוסר בהצלחה",
|
||||
"ToastCollectionUpdateSuccess": "האוסף עודכן בהצלחה",
|
||||
"ToastItemCoverUpdateSuccess": "כריכת הפריט עודכנה בהצלחה",
|
||||
|
||||
@@ -959,6 +959,8 @@
|
||||
"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",
|
||||
|
||||
@@ -945,6 +945,7 @@
|
||||
"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",
|
||||
|
||||
@@ -950,6 +950,8 @@
|
||||
"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",
|
||||
|
||||
@@ -666,6 +666,8 @@
|
||||
"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",
|
||||
|
||||
@@ -946,6 +946,8 @@
|
||||
"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",
|
||||
|
||||
@@ -882,6 +882,8 @@
|
||||
"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",
|
||||
|
||||
@@ -772,6 +772,7 @@
|
||||
"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ę",
|
||||
|
||||
@@ -735,6 +735,7 @@
|
||||
"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",
|
||||
|
||||
@@ -959,6 +959,8 @@
|
||||
"ToastChaptersRemoved": "Удалены главы",
|
||||
"ToastChaptersUpdated": "Обновленные главы",
|
||||
"ToastCollectionItemsAddFailed": "Не удалось добавить элемент(ы) в коллекцию",
|
||||
"ToastCollectionItemsAddSuccess": "Элемент(ы) добавлены в коллекцию",
|
||||
"ToastCollectionItemsRemoveSuccess": "Элемент(ы), удалены из коллекции",
|
||||
"ToastCollectionRemoveSuccess": "Коллекция удалена",
|
||||
"ToastCollectionUpdateSuccess": "Коллекция обновлена",
|
||||
"ToastCoverUpdateFailed": "Не удалось обновить обложку",
|
||||
|
||||
@@ -959,6 +959,8 @@
|
||||
"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",
|
||||
|
||||
@@ -705,6 +705,7 @@
|
||||
"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",
|
||||
|
||||
@@ -959,6 +959,8 @@
|
||||
"ToastChaptersRemoved": "Розділи видалені",
|
||||
"ToastChaptersUpdated": "Розділи оновлені",
|
||||
"ToastCollectionItemsAddFailed": "Не вдалося додати елемент(и) до колекції",
|
||||
"ToastCollectionItemsAddSuccess": "Елемент(и) успішно додано до колекції",
|
||||
"ToastCollectionItemsRemoveSuccess": "Елемент(и) видалено з добірки",
|
||||
"ToastCollectionRemoveSuccess": "Добірку видалено",
|
||||
"ToastCollectionUpdateSuccess": "Добірку оновлено",
|
||||
"ToastCoverUpdateFailed": "Не вдалося оновити обкладинку",
|
||||
|
||||
@@ -683,6 +683,7 @@
|
||||
"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",
|
||||
|
||||
@@ -959,6 +959,8 @@
|
||||
"ToastChaptersRemoved": "已删除章节",
|
||||
"ToastChaptersUpdated": "章节已更新",
|
||||
"ToastCollectionItemsAddFailed": "项目添加到收藏夹失败",
|
||||
"ToastCollectionItemsAddSuccess": "项目添加到收藏夹成功",
|
||||
"ToastCollectionItemsRemoveSuccess": "项目从收藏夹移除",
|
||||
"ToastCollectionRemoveSuccess": "收藏夹已删除",
|
||||
"ToastCollectionUpdateSuccess": "收藏夹已更新",
|
||||
"ToastCoverUpdateFailed": "封面更新失败",
|
||||
|
||||
@@ -727,6 +727,7 @@
|
||||
"ToastBookmarkUpdateSuccess": "書籤已更新",
|
||||
"ToastChaptersHaveErrors": "章節有錯誤",
|
||||
"ToastChaptersMustHaveTitles": "章節必須有標題",
|
||||
"ToastCollectionItemsRemoveSuccess": "項目從收藏夾移除",
|
||||
"ToastCollectionRemoveSuccess": "收藏夾已刪除",
|
||||
"ToastCollectionUpdateSuccess": "收藏夾已更新",
|
||||
"ToastItemCoverUpdateSuccess": "項目封面已更新",
|
||||
|
||||
2
index.js
2
index.js
@@ -13,6 +13,8 @@ if (isDev) {
|
||||
if (devEnv.SkipBinariesCheck) process.env.SKIP_BINARIES_CHECK = '1'
|
||||
if (devEnv.AllowIframe) process.env.ALLOW_IFRAME = '1'
|
||||
if (devEnv.BackupPath) process.env.BACKUP_PATH = devEnv.BackupPath
|
||||
if (devEnv.AllowPlugins) process.env.ALLOW_PLUGINS = '1'
|
||||
if (devEnv.DevPluginsPath) process.env.DEV_PLUGINS_PATH = devEnv.DevPluginsPath
|
||||
process.env.SOURCE = 'local'
|
||||
process.env.ROUTER_BASE_PATH = devEnv.RouterBasePath || ''
|
||||
}
|
||||
|
||||
4
prod.js
4
prod.js
@@ -16,8 +16,8 @@ const server = require('./server/Server')
|
||||
|
||||
global.appRoot = __dirname
|
||||
|
||||
var inputConfig = options.config ? Path.resolve(options.config) : null
|
||||
var inputMetadata = options.metadata ? Path.resolve(options.metadata) : null
|
||||
const inputConfig = options.config ? Path.resolve(options.config) : null
|
||||
const inputMetadata = options.metadata ? Path.resolve(options.metadata) : null
|
||||
|
||||
const PORT = options.port || process.env.PORT || 3333
|
||||
const HOST = options.host || process.env.HOST
|
||||
|
||||
@@ -16,6 +16,8 @@ const Logger = require('./Logger')
|
||||
*/
|
||||
class Auth {
|
||||
constructor() {
|
||||
this.pluginManifests = []
|
||||
|
||||
// Map of openId sessions indexed by oauth2 state-variable
|
||||
this.openIdAuthSession = new Map()
|
||||
this.ignorePatterns = [/\/api\/items\/[^/]+\/cover/, /\/api\/authors\/[^/]+\/image/]
|
||||
@@ -933,11 +935,28 @@ class Auth {
|
||||
*/
|
||||
async getUserLoginResponsePayload(user) {
|
||||
const libraryIds = await Database.libraryModel.getAllLibraryIds()
|
||||
|
||||
let plugins = undefined
|
||||
if (process.env.ALLOW_PLUGINS === '1') {
|
||||
// TODO: Should be better handled by the PluginManager
|
||||
// restrict plugin extensions that are not allowed for the user type
|
||||
plugins = this.pluginManifests.map((manifest) => {
|
||||
const manifestExtensions = (manifest.extensions || []).filter((ext) => {
|
||||
if (ext.restrictToAccountTypes?.length) {
|
||||
return ext.restrictToAccountTypes.includes(user.type)
|
||||
}
|
||||
return true
|
||||
})
|
||||
return { ...manifest, extensions: manifestExtensions }
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
user: user.toOldJSONForBrowser(),
|
||||
userDefaultLibraryId: user.getDefaultLibraryId(libraryIds),
|
||||
serverSettings: Database.serverSettings.toJSONForBrowser(),
|
||||
ereaderDevices: Database.emailSettings.getEReaderDevices(user),
|
||||
plugins,
|
||||
Source: global.Source
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,6 +152,11 @@ class Database {
|
||||
return this.models.device
|
||||
}
|
||||
|
||||
/** @type {typeof import('./models/Plugin')} */
|
||||
get pluginModel() {
|
||||
return this.models.plugin
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if db file exists
|
||||
* @returns {boolean}
|
||||
@@ -305,6 +310,7 @@ class Database {
|
||||
require('./models/Setting').init(this.sequelize)
|
||||
require('./models/CustomMetadataProvider').init(this.sequelize)
|
||||
require('./models/MediaItemShare').init(this.sequelize)
|
||||
require('./models/Plugin').init(this.sequelize)
|
||||
|
||||
return this.sequelize.sync({ force, alter: false })
|
||||
}
|
||||
@@ -406,6 +412,21 @@ 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()
|
||||
|
||||
@@ -28,7 +28,6 @@ const AbMergeManager = require('./managers/AbMergeManager')
|
||||
const CacheManager = require('./managers/CacheManager')
|
||||
const BackupManager = require('./managers/BackupManager')
|
||||
const PlaybackSessionManager = require('./managers/PlaybackSessionManager')
|
||||
const PodcastManager = require('./managers/PodcastManager')
|
||||
const AudioMetadataMangaer = require('./managers/AudioMetadataManager')
|
||||
const RssFeedManager = require('./managers/RssFeedManager')
|
||||
const CronManager = require('./managers/CronManager')
|
||||
@@ -36,6 +35,7 @@ const ApiCacheManager = require('./managers/ApiCacheManager')
|
||||
const BinaryManager = require('./managers/BinaryManager')
|
||||
const ShareManager = require('./managers/ShareManager')
|
||||
const LibraryScanner = require('./scanner/LibraryScanner')
|
||||
const PluginManager = require('./managers/PluginManager')
|
||||
|
||||
//Import the main Passport and Express-Session library
|
||||
const passport = require('passport')
|
||||
@@ -79,9 +79,8 @@ class Server {
|
||||
this.backupManager = new BackupManager()
|
||||
this.abMergeManager = new AbMergeManager()
|
||||
this.playbackSessionManager = new PlaybackSessionManager()
|
||||
this.podcastManager = new PodcastManager()
|
||||
this.audioMetadataManager = new AudioMetadataMangaer()
|
||||
this.cronManager = new CronManager(this.podcastManager, this.playbackSessionManager)
|
||||
this.cronManager = new CronManager(this.playbackSessionManager)
|
||||
this.apiCacheManager = new ApiCacheManager()
|
||||
this.binaryManager = new BinaryManager()
|
||||
|
||||
@@ -161,6 +160,15 @@ class Server {
|
||||
LibraryScanner.scanFilesChanged(pendingFileUpdates, pendingTask)
|
||||
})
|
||||
}
|
||||
|
||||
if (process.env.ALLOW_PLUGINS === '1') {
|
||||
Logger.info(`[Server] Experimental plugin support enabled`)
|
||||
|
||||
// Initialize plugins
|
||||
await PluginManager.init()
|
||||
// TODO: Prevents circular dependency for SocketAuthority
|
||||
this.auth.pluginManifests = PluginManager.pluginManifests
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,17 +5,13 @@ 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 {
|
||||
@@ -29,71 +25,36 @@ class CollectionController {
|
||||
* @param {Response} res
|
||||
*/
|
||||
async create(req, res) {
|
||||
const reqBody = req.body || {}
|
||||
|
||||
// Validation
|
||||
if (!reqBody.name || !reqBody.libraryId) {
|
||||
const newCollection = new Collection()
|
||||
req.body.userId = req.user.id
|
||||
if (!newCollection.setData(req.body)) {
|
||||
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')
|
||||
}
|
||||
|
||||
// Load library items
|
||||
const libraryItems = await Database.libraryItemModel.findAll({
|
||||
attributes: ['id', 'mediaId', 'mediaType', 'libraryId'],
|
||||
where: {
|
||||
id: libraryItemIds,
|
||||
libraryId: reqBody.libraryId,
|
||||
mediaType: 'book'
|
||||
}
|
||||
})
|
||||
if (libraryItems.length !== libraryItemIds.length) {
|
||||
return res.status(400).send('Invalid collection data. Invalid books')
|
||||
}
|
||||
// Create collection record
|
||||
await Database.collectionModel.createFromOld(newCollection)
|
||||
|
||||
/** @type {import('../models/Collection')} */
|
||||
let newCollection = null
|
||||
// Get library items in collection
|
||||
const libraryItemsInCollection = await Database.libraryItemModel.getForCollection(newCollection)
|
||||
|
||||
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 {
|
||||
// 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.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')
|
||||
bookId: libraryItem.media.id,
|
||||
order: order++
|
||||
})
|
||||
}
|
||||
}
|
||||
if (collectionBooksToAdd.length) {
|
||||
await Database.createBulkCollectionBooks(collectionBooksToAdd)
|
||||
}
|
||||
|
||||
// Load books expanded
|
||||
newCollection.books = await newCollection.getBooksExpandedWithLibraryItem()
|
||||
|
||||
// Note: The old collection model stores expanded libraryItems in the books property
|
||||
const jsonExpanded = newCollection.toOldJSONExpanded()
|
||||
const jsonExpanded = newCollection.toJSONExpanded(libraryItemsInCollection)
|
||||
SocketAuthority.emitter('collection_added', jsonExpanded)
|
||||
res.json(jsonExpanded)
|
||||
}
|
||||
@@ -114,7 +75,7 @@ class CollectionController {
|
||||
/**
|
||||
* GET: /api/collections/:id
|
||||
*
|
||||
* @param {CollectionControllerRequest} req
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async findOne(req, res) {
|
||||
@@ -133,7 +94,7 @@ class CollectionController {
|
||||
* PATCH: /api/collections/:id
|
||||
* Update collection
|
||||
*
|
||||
* @param {CollectionControllerRequest} req
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async update(req, res) {
|
||||
@@ -197,7 +158,7 @@ class CollectionController {
|
||||
*
|
||||
* @this {import('../routers/ApiRouter')}
|
||||
*
|
||||
* @param {CollectionControllerRequest} req
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async delete(req, res) {
|
||||
@@ -217,7 +178,7 @@ class CollectionController {
|
||||
* Add a single book to a collection
|
||||
* Req.body { id: <library item id> }
|
||||
*
|
||||
* @param {CollectionControllerRequest} req
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async addBook(req, res) {
|
||||
@@ -251,7 +212,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 {CollectionControllerRequest} req
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async removeBook(req, res) {
|
||||
@@ -296,31 +257,29 @@ class CollectionController {
|
||||
* Add multiple books to collection
|
||||
* Req.body { books: <Array of library item ids> }
|
||||
*
|
||||
* @param {CollectionControllerRequest} req
|
||||
* @param {RequestWithUser} 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(400).send('Invalid request body')
|
||||
return res.status(500).send('Invalid request body')
|
||||
}
|
||||
|
||||
// Get library items associated with ids
|
||||
const libraryItems = await Database.libraryItemModel.findAll({
|
||||
attributes: ['id', 'mediaId', 'mediaType', 'libraryId'],
|
||||
where: {
|
||||
id: bookIdsToAdd,
|
||||
libraryId: req.collection.libraryId,
|
||||
mediaType: 'book'
|
||||
id: {
|
||||
[Sequelize.Op.in]: bookIdsToAdd
|
||||
}
|
||||
},
|
||||
include: {
|
||||
model: Database.bookModel
|
||||
}
|
||||
})
|
||||
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
|
||||
@@ -329,10 +288,10 @@ class CollectionController {
|
||||
|
||||
// Check and set new collection books to add
|
||||
for (const libraryItem of libraryItems) {
|
||||
if (!collectionBooks.some((cb) => cb.bookId === libraryItem.mediaId)) {
|
||||
if (!collectionBooks.some((cb) => cb.bookId === libraryItem.media.id)) {
|
||||
collectionBooksToAdd.push({
|
||||
collectionId: req.collection.id,
|
||||
bookId: libraryItem.mediaId,
|
||||
bookId: libraryItem.media.id,
|
||||
order: order++
|
||||
})
|
||||
hasUpdated = true
|
||||
@@ -343,8 +302,7 @@ class CollectionController {
|
||||
|
||||
let jsonExpanded = null
|
||||
if (hasUpdated) {
|
||||
await Database.collectionBookModel.bulkCreate(collectionBooksToAdd)
|
||||
|
||||
await Database.createBulkCollectionBooks(collectionBooksToAdd)
|
||||
jsonExpanded = await req.collection.getOldJsonExpanded()
|
||||
SocketAuthority.emitter('collection_updated', jsonExpanded)
|
||||
} else {
|
||||
@@ -358,7 +316,7 @@ class CollectionController {
|
||||
* Remove multiple books from collection
|
||||
* Req.body { books: <Array of library item ids> }
|
||||
*
|
||||
* @param {CollectionControllerRequest} req
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async removeBatch(req, res) {
|
||||
@@ -371,7 +329,9 @@ class CollectionController {
|
||||
// Get library items associated with ids
|
||||
const libraryItems = await Database.libraryItemModel.findAll({
|
||||
where: {
|
||||
id: bookIdsToRemove
|
||||
id: {
|
||||
[Sequelize.Op.in]: bookIdsToRemove
|
||||
}
|
||||
},
|
||||
include: {
|
||||
model: Database.bookModel
|
||||
@@ -379,7 +339,6 @@ class CollectionController {
|
||||
})
|
||||
|
||||
// Get collection books already in collection
|
||||
/** @type {import('../models/CollectionBook')[]} */
|
||||
const collectionBooks = await req.collection.getCollectionBooks({
|
||||
order: [['order', 'ASC']]
|
||||
})
|
||||
|
||||
@@ -19,6 +19,7 @@ const Scanner = require('../scanner/Scanner')
|
||||
const Database = require('../Database')
|
||||
const Watcher = require('../Watcher')
|
||||
const RssFeedManager = require('../managers/RssFeedManager')
|
||||
const PodcastManager = require('../managers/PodcastManager')
|
||||
|
||||
const libraryFilters = require('../utils/queries/libraryFilters')
|
||||
const libraryItemsPodcastFilters = require('../utils/queries/libraryItemsPodcastFilters')
|
||||
@@ -219,7 +220,7 @@ class LibraryController {
|
||||
* @param {Response} res
|
||||
*/
|
||||
async getEpisodeDownloadQueue(req, res) {
|
||||
const libraryDownloadQueueDetails = this.podcastManager.getDownloadQueueDetails(req.library.id)
|
||||
const libraryDownloadQueueDetails = PodcastManager.getDownloadQueueDetails(req.library.id)
|
||||
res.json(libraryDownloadQueueDetails)
|
||||
}
|
||||
|
||||
@@ -1288,7 +1289,7 @@ class LibraryController {
|
||||
}
|
||||
})
|
||||
|
||||
const opmlText = this.podcastManager.generateOPMLFileText(podcasts)
|
||||
const opmlText = PodcastManager.generateOPMLFileText(podcasts)
|
||||
res.type('application/xml')
|
||||
res.send(opmlText)
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ const RssFeedManager = require('../managers/RssFeedManager')
|
||||
const CacheManager = require('../managers/CacheManager')
|
||||
const CoverManager = require('../managers/CoverManager')
|
||||
const ShareManager = require('../managers/ShareManager')
|
||||
const PodcastManager = require('../managers/PodcastManager')
|
||||
|
||||
/**
|
||||
* @typedef RequestUserObject
|
||||
@@ -59,10 +60,10 @@ class LibraryItemController {
|
||||
}
|
||||
|
||||
if (item.mediaType === 'podcast' && includeEntities.includes('downloads')) {
|
||||
const downloadsInQueue = this.podcastManager.getEpisodeDownloadsInQueue(req.libraryItem.id)
|
||||
const downloadsInQueue = PodcastManager.getEpisodeDownloadsInQueue(req.libraryItem.id)
|
||||
item.episodeDownloadsQueued = downloadsInQueue.map((d) => d.toJSONForClient())
|
||||
if (this.podcastManager.currentDownload?.libraryItemId === req.libraryItem.id) {
|
||||
item.episodesDownloading = [this.podcastManager.currentDownload.toJSONForClient()]
|
||||
if (PodcastManager.currentDownload?.libraryItemId === req.libraryItem.id) {
|
||||
item.episodesDownloading = [PodcastManager.currentDownload.toJSONForClient()]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,16 +3,13 @@ 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 {
|
||||
@@ -26,103 +23,48 @@ class PlaylistController {
|
||||
* @param {Response} res
|
||||
*/
|
||||
async create(req, res) {
|
||||
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)
|
||||
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')
|
||||
}
|
||||
|
||||
// Load library items
|
||||
const libraryItems = await Database.libraryItemModel.findAll({
|
||||
attributes: ['id', 'mediaId', 'mediaType', 'libraryId'],
|
||||
// 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({
|
||||
where: {
|
||||
id: Array.from(libraryItemIds),
|
||||
libraryId: reqBody.libraryId,
|
||||
mediaType: isPodcast ? 'podcast' : 'book'
|
||||
id: libraryItemIds
|
||||
}
|
||||
})
|
||||
if (libraryItems.length !== libraryItemIds.size) {
|
||||
return res.status(400).send('Invalid playlist data. Invalid items')
|
||||
}
|
||||
|
||||
// Validate podcast episodes
|
||||
if (isPodcast) {
|
||||
const podcastEpisodeIds = items.map((i) => i.episodeId)
|
||||
const podcastEpisodes = await Database.podcastEpisodeModel.findAll({
|
||||
attributes: ['id'],
|
||||
where: {
|
||||
id: podcastEpisodeIds
|
||||
}
|
||||
// Create playlistMediaItem records
|
||||
const mediaItemsToAdd = []
|
||||
let order = 1
|
||||
for (const mediaItemObj of oldPlaylist.items) {
|
||||
const libraryItem = libraryItemsInPlaylist.find((li) => li.id === mediaItemObj.libraryItemId)
|
||||
if (!libraryItem) continue
|
||||
|
||||
mediaItemsToAdd.push({
|
||||
mediaItemId: mediaItemObj.episodeId || libraryItem.mediaId,
|
||||
mediaItemType: mediaItemObj.episodeId ? 'podcastEpisode' : 'book',
|
||||
playlistId: oldPlaylist.id,
|
||||
order: order++
|
||||
})
|
||||
if (podcastEpisodes.length !== podcastEpisodeIds.length) {
|
||||
return res.status(400).send('Invalid playlist data. Invalid podcast episodes')
|
||||
}
|
||||
}
|
||||
if (mediaItemsToAdd.length) {
|
||||
await Database.createBulkPlaylistMediaItems(mediaItemsToAdd)
|
||||
}
|
||||
|
||||
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')
|
||||
}
|
||||
const jsonExpanded = await newPlaylist.getOldJsonExpanded()
|
||||
SocketAuthority.clientEmitter(newPlaylist.userId, 'playlist_added', jsonExpanded)
|
||||
res.json(jsonExpanded)
|
||||
}
|
||||
|
||||
/**
|
||||
* @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
|
||||
*
|
||||
@@ -130,89 +72,68 @@ class PlaylistController {
|
||||
* @param {Response} res
|
||||
*/
|
||||
async findAllForUser(req, res) {
|
||||
const playlistsForUser = await Database.playlistModel.getOldPlaylistsForUserAndLibrary(req.user.id)
|
||||
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)
|
||||
}
|
||||
res.json({
|
||||
playlists: playlistsForUser
|
||||
playlists
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* GET: /api/playlists/:id
|
||||
*
|
||||
* @param {PlaylistControllerRequest} req
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async findOne(req, res) {
|
||||
req.playlist.playlistMediaItems = await req.playlist.getMediaItemsExpandedWithLibraryItem()
|
||||
res.json(req.playlist.toOldJSONExpanded())
|
||||
const jsonExpanded = await req.playlist.getOldJsonExpanded()
|
||||
res.json(jsonExpanded)
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH: /api/playlists/:id
|
||||
* Update playlist
|
||||
*
|
||||
* Used for updating name and description or reordering items
|
||||
*
|
||||
* @param {PlaylistControllerRequest} req
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async update(req, res) {
|
||||
// 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')
|
||||
}
|
||||
|
||||
const playlistUpdatePayload = {}
|
||||
if (reqBody.name) playlistUpdatePayload.name = reqBody.name
|
||||
if (reqBody.description) playlistUpdatePayload.description = reqBody.description
|
||||
|
||||
// Update name and description
|
||||
const updatedPlaylist = req.playlist.set(req.body)
|
||||
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
|
||||
}
|
||||
const changed = updatedPlaylist.changed()
|
||||
if (changed?.length) {
|
||||
await req.playlist.save()
|
||||
Logger.debug(`[PlaylistController] Updated playlist ${req.playlist.id} keys [${changed.join(',')}]`)
|
||||
wasUpdated = true
|
||||
}
|
||||
|
||||
// If array of items is set then update order of playlist media items
|
||||
if (reqBody.items?.length) {
|
||||
const libraryItemIds = Array.from(new Set(reqBody.items.map((i) => i.libraryItemId)))
|
||||
// If array of items is passed in then update order of playlist media items
|
||||
const libraryItemIds = req.body.items?.map((i) => i.libraryItemId).filter((i) => i) || []
|
||||
if (libraryItemIds.length) {
|
||||
const libraryItems = await Database.libraryItemModel.findAll({
|
||||
attributes: ['id', 'mediaId', 'mediaType'],
|
||||
where: {
|
||||
id: libraryItemIds
|
||||
}
|
||||
})
|
||||
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({
|
||||
const existingPlaylistMediaItems = await updatedPlaylist.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 reqBody.items) {
|
||||
for (const item of req.body.items) {
|
||||
const libraryItem = libraryItems.find((li) => li.id === item.libraryItemId)
|
||||
if (!libraryItem) {
|
||||
continue
|
||||
}
|
||||
const mediaItemId = item.episodeId || libraryItem.mediaId
|
||||
newMediaItemIdOrder.push(mediaItemId)
|
||||
}
|
||||
@@ -225,21 +146,21 @@ class PlaylistController {
|
||||
})
|
||||
|
||||
// Update order on playlistMediaItem records
|
||||
for (const [index, playlistMediaItem] of existingPlaylistMediaItems.entries()) {
|
||||
if (playlistMediaItem.order !== index + 1) {
|
||||
let order = 1
|
||||
for (const playlistMediaItem of existingPlaylistMediaItems) {
|
||||
if (playlistMediaItem.order !== order) {
|
||||
await playlistMediaItem.update({
|
||||
order: index + 1
|
||||
order
|
||||
})
|
||||
wasUpdated = true
|
||||
}
|
||||
order++
|
||||
}
|
||||
}
|
||||
|
||||
req.playlist.playlistMediaItems = await req.playlist.getMediaItemsExpandedWithLibraryItem()
|
||||
|
||||
const jsonExpanded = req.playlist.toOldJSONExpanded()
|
||||
const jsonExpanded = await updatedPlaylist.getOldJsonExpanded()
|
||||
if (wasUpdated) {
|
||||
SocketAuthority.clientEmitter(req.playlist.userId, 'playlist_updated', jsonExpanded)
|
||||
SocketAuthority.clientEmitter(updatedPlaylist.userId, 'playlist_updated', jsonExpanded)
|
||||
}
|
||||
res.json(jsonExpanded)
|
||||
}
|
||||
@@ -248,13 +169,11 @@ class PlaylistController {
|
||||
* DELETE: /api/playlists/:id
|
||||
* Remove playlist
|
||||
*
|
||||
* @param {PlaylistControllerRequest} req
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async delete(req, res) {
|
||||
req.playlist.playlistMediaItems = await req.playlist.getMediaItemsExpandedWithLibraryItem()
|
||||
const jsonExpanded = req.playlist.toOldJSONExpanded()
|
||||
|
||||
const jsonExpanded = await req.playlist.getOldJsonExpanded()
|
||||
await req.playlist.destroy()
|
||||
SocketAuthority.clientEmitter(jsonExpanded.userId, 'playlist_removed', jsonExpanded)
|
||||
res.sendStatus(200)
|
||||
@@ -264,13 +183,12 @@ class PlaylistController {
|
||||
* POST: /api/playlists/:id/item
|
||||
* Add item to playlist
|
||||
*
|
||||
* This is not used by Abs web client or mobile apps. Only the batch endpoints are used.
|
||||
*
|
||||
* @param {PlaylistControllerRequest} req
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async addItem(req, res) {
|
||||
const itemToAdd = req.body || {}
|
||||
const oldPlaylist = await Database.playlistModel.getById(req.playlist.id)
|
||||
const itemToAdd = req.body
|
||||
|
||||
if (!itemToAdd.libraryItemId) {
|
||||
return res.status(400).send('Request body has no libraryItemId')
|
||||
@@ -280,9 +198,12 @@ class PlaylistController {
|
||||
if (!libraryItem) {
|
||||
return res.status(400).send('Library item not found')
|
||||
}
|
||||
if (libraryItem.libraryId !== req.playlist.libraryId) {
|
||||
if (libraryItem.libraryId !== oldPlaylist.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')
|
||||
}
|
||||
@@ -290,38 +211,15 @@ class PlaylistController {
|
||||
return res.status(400).send('Episode not found in library item')
|
||||
}
|
||||
|
||||
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,
|
||||
playlistId: oldPlaylist.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()
|
||||
})
|
||||
order: oldPlaylist.items.length + 1
|
||||
}
|
||||
|
||||
await Database.createPlaylistMediaItem(playlistMediaItem)
|
||||
const jsonExpanded = await req.playlist.getOldJsonExpanded()
|
||||
SocketAuthority.clientEmitter(jsonExpanded.userId, 'playlist_updated', jsonExpanded)
|
||||
res.json(jsonExpanded)
|
||||
}
|
||||
@@ -330,36 +228,43 @@ class PlaylistController {
|
||||
* DELETE: /api/playlists/:id/item/:libraryItemId/:episodeId?
|
||||
* Remove item from playlist
|
||||
*
|
||||
* @param {PlaylistControllerRequest} req
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async removeItem(req, res) {
|
||||
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)
|
||||
const oldLibraryItem = await Database.libraryItemModel.getOldById(req.params.libraryItemId)
|
||||
if (!oldLibraryItem) {
|
||||
return res.status(404).send('Library item not found')
|
||||
}
|
||||
if (!playlistMediaItem) {
|
||||
|
||||
// Get playlist media items
|
||||
const mediaItemId = req.params.episodeId || oldLibraryItem.media.id
|
||||
const playlistMediaItems = await req.playlist.getPlaylistMediaItems({
|
||||
order: [['order', 'ASC']]
|
||||
})
|
||||
|
||||
// Check if media item to delete is in playlist
|
||||
const mediaItemToRemove = playlistMediaItems.find((pmi) => pmi.mediaItemId === mediaItemId)
|
||||
if (!mediaItemToRemove) {
|
||||
return res.status(404).send('Media item not found in playlist')
|
||||
}
|
||||
|
||||
// Remove record
|
||||
await playlistMediaItem.destroy()
|
||||
req.playlist.playlistMediaItems = req.playlist.playlistMediaItems.filter((pmi) => pmi.id !== playlistMediaItem.id)
|
||||
await mediaItemToRemove.destroy()
|
||||
|
||||
// Update playlist media items order
|
||||
for (const [index, mediaItem] of req.playlist.playlistMediaItems.entries()) {
|
||||
if (mediaItem.order !== index + 1) {
|
||||
let order = 1
|
||||
for (const mediaItem of playlistMediaItems) {
|
||||
if (mediaItem.mediaItemId === mediaItemId) continue
|
||||
if (mediaItem.order !== order) {
|
||||
await mediaItem.update({
|
||||
order: index + 1
|
||||
order
|
||||
})
|
||||
}
|
||||
order++
|
||||
}
|
||||
|
||||
const jsonExpanded = req.playlist.toOldJSONExpanded()
|
||||
const jsonExpanded = await req.playlist.getOldJsonExpanded()
|
||||
|
||||
// Playlist is removed when there are no items
|
||||
if (!jsonExpanded.items.length) {
|
||||
@@ -377,68 +282,64 @@ class PlaylistController {
|
||||
* POST: /api/playlists/:id/batch/add
|
||||
* Batch add playlist items
|
||||
*
|
||||
* @param {PlaylistControllerRequest} req
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async addBatch(req, res) {
|
||||
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')
|
||||
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')
|
||||
}
|
||||
|
||||
// Find all library items
|
||||
const libraryItemIds = new Set(req.body.items.map((i) => i.libraryItemId).filter((i) => i))
|
||||
const libraryItems = await Database.libraryItemModel.findAll({
|
||||
where: {
|
||||
id: libraryItemIds
|
||||
}
|
||||
})
|
||||
|
||||
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()
|
||||
// Get all existing playlist media items
|
||||
const existingPlaylistMediaItems = await req.playlist.getPlaylistMediaItems({
|
||||
order: [['order', 'ASC']]
|
||||
})
|
||||
|
||||
const mediaItemsToAdd = []
|
||||
const jsonExpanded = req.playlist.toOldJSONExpanded()
|
||||
|
||||
// Setup array of playlistMediaItem records to add
|
||||
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
|
||||
let order = existingPlaylistMediaItems.length + 1
|
||||
for (const item of itemsToAdd) {
|
||||
const libraryItem = libraryItems.find((li) => li.id === item.libraryItemId)
|
||||
if (!libraryItem) {
|
||||
return res.status(404).send('Item not found with id ' + item.libraryItemId)
|
||||
} else {
|
||||
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()
|
||||
})
|
||||
const mediaItemId = item.episodeId || libraryItem.mediaId
|
||||
if (existingPlaylistMediaItems.some((pmi) => pmi.mediaItemId === mediaItemId)) {
|
||||
// Already exists in playlist
|
||||
continue
|
||||
} else {
|
||||
jsonExpanded.items.push({
|
||||
libraryItemId: libraryItem.id,
|
||||
libraryItem: libraryItem.toJSONExpanded()
|
||||
mediaItemsToAdd.push({
|
||||
playlistId: req.playlist.id,
|
||||
mediaItemId,
|
||||
mediaItemType: item.episodeId ? 'podcastEpisode' : 'book',
|
||||
order: order++
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let jsonExpanded = null
|
||||
if (mediaItemsToAdd.length) {
|
||||
await Database.playlistMediaItemModel.bulkCreate(mediaItemsToAdd)
|
||||
|
||||
await Database.createBulkPlaylistMediaItems(mediaItemsToAdd)
|
||||
jsonExpanded = await req.playlist.getOldJsonExpanded()
|
||||
SocketAuthority.clientEmitter(req.playlist.userId, 'playlist_updated', jsonExpanded)
|
||||
} else {
|
||||
jsonExpanded = await req.playlist.getOldJsonExpanded()
|
||||
}
|
||||
|
||||
res.json(jsonExpanded)
|
||||
}
|
||||
|
||||
@@ -446,40 +347,50 @@ class PlaylistController {
|
||||
* POST: /api/playlists/:id/batch/remove
|
||||
* Batch remove playlist items
|
||||
*
|
||||
* @param {PlaylistControllerRequest} req
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async removeBatch(req, res) {
|
||||
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')
|
||||
if (!req.body.items?.length) {
|
||||
return res.status(400).send('Invalid request body')
|
||||
}
|
||||
|
||||
req.playlist.playlistMediaItems = await req.playlist.getMediaItemsExpandedWithLibraryItem()
|
||||
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
|
||||
|
||||
// Remove playlist media items
|
||||
let hasUpdated = false
|
||||
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)
|
||||
|
||||
for (const item of itemsToRemove) {
|
||||
const libraryItem = libraryItems.find((li) => li.id === item.libraryItemId)
|
||||
if (!libraryItem) continue
|
||||
const mediaItemId = item.episodeId || libraryItem.mediaId
|
||||
const existingMediaItem = existingPlaylistMediaItems.find((pmi) => pmi.mediaItemId === mediaItemId)
|
||||
if (!existingMediaItem) continue
|
||||
await existingMediaItem.destroy()
|
||||
hasUpdated = true
|
||||
numMediaItems--
|
||||
}
|
||||
|
||||
const jsonExpanded = req.playlist.toOldJSONExpanded()
|
||||
const jsonExpanded = await req.playlist.getOldJsonExpanded()
|
||||
if (hasUpdated) {
|
||||
// Playlist is removed when there are no items
|
||||
if (!req.playlist.playlistMediaItems.length) {
|
||||
if (!numMediaItems) {
|
||||
Logger.info(`[PlaylistController] Playlist "${req.playlist.name}" has no more items - removing it`)
|
||||
await req.playlist.destroy()
|
||||
SocketAuthority.clientEmitter(jsonExpanded.userId, 'playlist_removed', jsonExpanded)
|
||||
@@ -514,41 +425,33 @@ class PlaylistController {
|
||||
return res.status(400).send('Collection has no books')
|
||||
}
|
||||
|
||||
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 }
|
||||
)
|
||||
const oldPlaylist = new Playlist()
|
||||
oldPlaylist.setData({
|
||||
userId: req.user.id,
|
||||
libraryId: collection.libraryId,
|
||||
name: collection.name,
|
||||
description: collection.description || null
|
||||
})
|
||||
|
||||
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 Playlist record
|
||||
const newPlaylist = await Database.playlistModel.createFromOld(oldPlaylist)
|
||||
|
||||
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')
|
||||
// Create PlaylistMediaItem records
|
||||
const mediaItemsToAdd = []
|
||||
let order = 1
|
||||
for (const libraryItem of collectionExpanded.books) {
|
||||
mediaItemsToAdd.push({
|
||||
playlistId: newPlaylist.id,
|
||||
mediaItemId: libraryItem.media.id,
|
||||
mediaItemType: 'book',
|
||||
order: order++
|
||||
})
|
||||
}
|
||||
await Database.createBulkPlaylistMediaItems(mediaItemsToAdd)
|
||||
|
||||
const jsonExpanded = await newPlaylist.getOldJsonExpanded()
|
||||
SocketAuthority.clientEmitter(newPlaylist.userId, 'playlist_added', jsonExpanded)
|
||||
res.json(jsonExpanded)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
82
server/controllers/PluginController.js
Normal file
82
server/controllers/PluginController.js
Normal file
@@ -0,0 +1,82 @@
|
||||
const { Request, Response, NextFunction } = require('express')
|
||||
const PluginManager = require('../managers/PluginManager')
|
||||
const Logger = require('../Logger')
|
||||
|
||||
class PluginController {
|
||||
constructor() {}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
getConfig(req, res) {
|
||||
if (!req.user.isAdminOrUp) {
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
res.json({
|
||||
config: req.pluginData.instance.config
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* POST: /api/plugins/:id/action
|
||||
*
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async handleAction(req, res) {
|
||||
const actionName = req.body.pluginAction
|
||||
const target = req.body.target
|
||||
const data = req.body.data
|
||||
Logger.info(`[PluginController] Handle plugin "${req.pluginData.manifest.name}" action ${actionName} ${target}`, data)
|
||||
const actionData = await PluginManager.onAction(req.pluginData, actionName, target, data)
|
||||
if (!actionData || actionData.error) {
|
||||
return res.status(400).send(actionData?.error || 'Error performing action')
|
||||
}
|
||||
res.sendStatus(200)
|
||||
}
|
||||
|
||||
/**
|
||||
* POST: /api/plugins/:id/config
|
||||
*
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async handleConfigSave(req, res) {
|
||||
if (!req.user.isAdminOrUp) {
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
if (!req.body.config || typeof req.body.config !== 'object') {
|
||||
return res.status(400).send('Invalid config')
|
||||
}
|
||||
|
||||
const config = req.body.config
|
||||
Logger.info(`[PluginController] Handle save config for plugin ${req.pluginData.manifest.name}`, config)
|
||||
const saveData = await PluginManager.onConfigSave(req.pluginData, config)
|
||||
if (!saveData || saveData.error) {
|
||||
return res.status(400).send(saveData?.error || 'Error saving config')
|
||||
}
|
||||
res.sendStatus(200)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
*/
|
||||
async middleware(req, res, next) {
|
||||
if (req.params.id) {
|
||||
const pluginData = PluginManager.getPluginDataById(req.params.id)
|
||||
if (!pluginData) {
|
||||
return res.sendStatus(404)
|
||||
}
|
||||
await pluginData.instance.reload()
|
||||
req.pluginData = pluginData
|
||||
}
|
||||
next()
|
||||
}
|
||||
}
|
||||
module.exports = new PluginController()
|
||||
@@ -11,6 +11,7 @@ const { validateUrl } = require('../utils/index')
|
||||
|
||||
const Scanner = require('../scanner/Scanner')
|
||||
const CoverManager = require('../managers/CoverManager')
|
||||
const PodcastManager = require('../managers/PodcastManager')
|
||||
|
||||
const LibraryItem = require('../objects/LibraryItem')
|
||||
|
||||
@@ -114,7 +115,7 @@ class PodcastController {
|
||||
|
||||
if (payload.episodesToDownload?.length) {
|
||||
Logger.info(`[PodcastController] Podcast created now starting ${payload.episodesToDownload.length} episode downloads`)
|
||||
this.podcastManager.downloadPodcastEpisodes(libraryItem, payload.episodesToDownload)
|
||||
PodcastManager.downloadPodcastEpisodes(libraryItem, payload.episodesToDownload)
|
||||
}
|
||||
|
||||
// Turn on podcast auto download cron if not already on
|
||||
@@ -169,7 +170,7 @@ class PodcastController {
|
||||
}
|
||||
|
||||
res.json({
|
||||
feeds: this.podcastManager.getParsedOPMLFileFeeds(req.body.opmlText)
|
||||
feeds: PodcastManager.getParsedOPMLFileFeeds(req.body.opmlText)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -203,7 +204,7 @@ class PodcastController {
|
||||
return res.status(404).send('Folder not found')
|
||||
}
|
||||
const autoDownloadEpisodes = !!req.body.autoDownloadEpisodes
|
||||
this.podcastManager.createPodcastsFromFeedUrls(rssFeeds, folder, autoDownloadEpisodes, this.cronManager)
|
||||
PodcastManager.createPodcastsFromFeedUrls(rssFeeds, folder, autoDownloadEpisodes, this.cronManager)
|
||||
|
||||
res.sendStatus(200)
|
||||
}
|
||||
@@ -230,7 +231,7 @@ class PodcastController {
|
||||
|
||||
const maxEpisodesToDownload = !isNaN(req.query.limit) ? Number(req.query.limit) : 3
|
||||
|
||||
var newEpisodes = await this.podcastManager.checkAndDownloadNewEpisodes(libraryItem, maxEpisodesToDownload)
|
||||
var newEpisodes = await PodcastManager.checkAndDownloadNewEpisodes(libraryItem, maxEpisodesToDownload)
|
||||
res.json({
|
||||
episodes: newEpisodes || []
|
||||
})
|
||||
@@ -239,8 +240,6 @@ class PodcastController {
|
||||
/**
|
||||
* GET: /api/podcasts/:id/clear-queue
|
||||
*
|
||||
* @this {import('../routers/ApiRouter')}
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
@@ -249,22 +248,20 @@ class PodcastController {
|
||||
Logger.error(`[PodcastController] Non-admin user "${req.user.username}" attempting to clear download queue`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
this.podcastManager.clearDownloadQueue(req.params.id)
|
||||
PodcastManager.clearDownloadQueue(req.params.id)
|
||||
res.sendStatus(200)
|
||||
}
|
||||
|
||||
/**
|
||||
* GET: /api/podcasts/:id/downloads
|
||||
*
|
||||
* @this {import('../routers/ApiRouter')}
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
getEpisodeDownloads(req, res) {
|
||||
var libraryItem = req.libraryItem
|
||||
|
||||
var downloadsInQueue = this.podcastManager.getEpisodeDownloadsInQueue(libraryItem.id)
|
||||
var downloadsInQueue = PodcastManager.getEpisodeDownloadsInQueue(libraryItem.id)
|
||||
res.json({
|
||||
downloads: downloadsInQueue.map((d) => d.toJSONForClient())
|
||||
})
|
||||
@@ -290,8 +287,6 @@ class PodcastController {
|
||||
/**
|
||||
* POST: /api/podcasts/:id/download-episodes
|
||||
*
|
||||
* @this {import('../routers/ApiRouter')}
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
@@ -306,7 +301,7 @@ class PodcastController {
|
||||
return res.sendStatus(400)
|
||||
}
|
||||
|
||||
this.podcastManager.downloadPodcastEpisodes(libraryItem, episodes)
|
||||
PodcastManager.downloadPodcastEpisodes(libraryItem, episodes)
|
||||
res.sendStatus(200)
|
||||
}
|
||||
|
||||
|
||||
@@ -5,11 +5,10 @@ const Database = require('../Database')
|
||||
const LibraryScanner = require('../scanner/LibraryScanner')
|
||||
|
||||
const ShareManager = require('./ShareManager')
|
||||
const PodcastManager = require('./PodcastManager')
|
||||
|
||||
class CronManager {
|
||||
constructor(podcastManager, playbackSessionManager) {
|
||||
/** @type {import('./PodcastManager')} */
|
||||
this.podcastManager = podcastManager
|
||||
constructor(playbackSessionManager) {
|
||||
/** @type {import('./PlaybackSessionManager')} */
|
||||
this.playbackSessionManager = playbackSessionManager
|
||||
|
||||
@@ -163,7 +162,7 @@ class CronManager {
|
||||
task
|
||||
})
|
||||
} catch (error) {
|
||||
Logger.error(`[PodcastManager] Failed to schedule podcast cron ${this.serverSettings.podcastEpisodeSchedule}`, error)
|
||||
Logger.error(`[CronManager] Failed to schedule podcast cron ${this.serverSettings.podcastEpisodeSchedule}`, error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,7 +191,7 @@ class CronManager {
|
||||
|
||||
// Run episode checks
|
||||
for (const libraryItem of libraryItems) {
|
||||
const keepAutoDownloading = await this.podcastManager.runEpisodeCheck(libraryItem)
|
||||
const keepAutoDownloading = await PodcastManager.runEpisodeCheck(libraryItem)
|
||||
if (!keepAutoDownloading) {
|
||||
// auto download was disabled
|
||||
podcastCron.libraryItemIds = podcastCron.libraryItemIds.filter((lid) => lid !== libraryItem.id) // Filter it out
|
||||
|
||||
274
server/managers/PluginManager.js
Normal file
274
server/managers/PluginManager.js
Normal file
@@ -0,0 +1,274 @@
|
||||
const Path = require('path')
|
||||
const Logger = require('../Logger')
|
||||
const Database = require('../Database')
|
||||
const SocketAuthority = require('../SocketAuthority')
|
||||
const TaskManager = require('../managers/TaskManager')
|
||||
const ShareManager = require('../managers/ShareManager')
|
||||
const RssFeedManager = require('../managers/RssFeedManager')
|
||||
const PodcastManager = require('../managers/PodcastManager')
|
||||
const fsExtra = require('../libs/fsExtra')
|
||||
const { isUUID, parseSemverStrict } = require('../utils')
|
||||
|
||||
/**
|
||||
* @typedef PluginContext
|
||||
* @property {import('../Logger')} Logger
|
||||
* @property {import('../Database')} Database
|
||||
* @property {import('../SocketAuthority')} SocketAuthority
|
||||
* @property {import('../managers/TaskManager')} TaskManager
|
||||
* @property {import('../models/Plugin')} pluginInstance
|
||||
* @property {import('../managers/ShareManager')} ShareManager
|
||||
* @property {import('../managers/RssFeedManager')} RssFeedManager
|
||||
* @property {import('../managers/PodcastManager')} PodcastManager
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef PluginData
|
||||
* @property {string} id
|
||||
* @property {Object} manifest
|
||||
* @property {import('../models/Plugin')} instance
|
||||
* @property {Function} init
|
||||
* @property {Function} onAction
|
||||
* @property {Function} onConfigSave
|
||||
*/
|
||||
|
||||
class PluginManager {
|
||||
constructor() {
|
||||
/** @type {PluginData[]} */
|
||||
this.plugins = []
|
||||
}
|
||||
|
||||
get pluginMetadataPath() {
|
||||
return Path.posix.join(global.MetadataPath, 'plugins')
|
||||
}
|
||||
|
||||
get pluginManifests() {
|
||||
return this.plugins.map((plugin) => plugin.manifest)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {import('../models/Plugin')} pluginInstance
|
||||
* @returns {PluginContext}
|
||||
*/
|
||||
getPluginContext(pluginInstance) {
|
||||
return {
|
||||
Logger,
|
||||
Database,
|
||||
SocketAuthority,
|
||||
TaskManager,
|
||||
pluginInstance,
|
||||
ShareManager,
|
||||
RssFeedManager,
|
||||
PodcastManager
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} id
|
||||
* @returns {PluginData}
|
||||
*/
|
||||
getPluginDataById(id) {
|
||||
return this.plugins.find((plugin) => plugin.manifest.id === id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate and load a plugin from a directory
|
||||
* TODO: Validatation
|
||||
*
|
||||
* @param {string} dirname
|
||||
* @param {string} pluginPath
|
||||
* @returns {Promise<PluginData>}
|
||||
*/
|
||||
async loadPlugin(dirname, pluginPath) {
|
||||
const pluginFiles = await fsExtra.readdir(pluginPath, { withFileTypes: true }).then((files) => files.filter((file) => !file.isDirectory()))
|
||||
|
||||
if (!pluginFiles.length) {
|
||||
Logger.error(`No files found in plugin ${pluginPath}`)
|
||||
return null
|
||||
}
|
||||
const manifestFile = pluginFiles.find((file) => file.name === 'manifest.json')
|
||||
if (!manifestFile) {
|
||||
Logger.error(`No manifest found for plugin ${pluginPath}`)
|
||||
return null
|
||||
}
|
||||
const indexFile = pluginFiles.find((file) => file.name === 'index.js')
|
||||
if (!indexFile) {
|
||||
Logger.error(`No index file found for plugin ${pluginPath}`)
|
||||
return null
|
||||
}
|
||||
|
||||
let manifestJson = null
|
||||
try {
|
||||
manifestJson = await fsExtra.readFile(Path.join(pluginPath, manifestFile.name), 'utf8').then((data) => JSON.parse(data))
|
||||
} catch (error) {
|
||||
Logger.error(`Error parsing manifest file for plugin ${pluginPath}`, error)
|
||||
return null
|
||||
}
|
||||
|
||||
// TODO: Validate manifest json
|
||||
if (!isUUID(manifestJson.id)) {
|
||||
Logger.error(`Invalid plugin ID in manifest for plugin ${pluginPath}`)
|
||||
return null
|
||||
}
|
||||
if (!parseSemverStrict(manifestJson.version)) {
|
||||
Logger.error(`Invalid plugin version in manifest for plugin ${pluginPath}`)
|
||||
return null
|
||||
}
|
||||
// TODO: Enforcing plugin name to be the same as the directory name? Ensures plugins are identifiable in the file system. May have issues with unicode characters.
|
||||
if (dirname !== manifestJson.name) {
|
||||
Logger.error(`Plugin directory name "${dirname}" does not match manifest name "${manifestJson.name}"`)
|
||||
return null
|
||||
}
|
||||
|
||||
let pluginContents = null
|
||||
try {
|
||||
pluginContents = require(Path.join(pluginPath, indexFile.name))
|
||||
} catch (error) {
|
||||
Logger.error(`Error loading plugin ${pluginPath}`, error)
|
||||
return null
|
||||
}
|
||||
|
||||
if (typeof pluginContents.init !== 'function') {
|
||||
Logger.error(`Plugin ${pluginPath} does not have an init function`)
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
id: manifestJson.id,
|
||||
manifest: manifestJson,
|
||||
init: pluginContents.init,
|
||||
onAction: pluginContents.onAction,
|
||||
onConfigSave: pluginContents.onConfigSave
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all plugins from the /metadata/plugins directory
|
||||
*/
|
||||
async getPluginsFromDirPath(pluginsPath) {
|
||||
// Get all directories in the plugins directory
|
||||
const pluginDirs = await fsExtra.readdir(pluginsPath, { withFileTypes: true }).then((files) => files.filter((file) => file.isDirectory()))
|
||||
|
||||
const pluginsFound = []
|
||||
for (const pluginDir of pluginDirs) {
|
||||
Logger.debug(`[PluginManager] Checking if directory "${pluginDir.name}" is a plugin`)
|
||||
const plugin = await this.loadPlugin(pluginDir.name, Path.join(pluginsPath, pluginDir.name))
|
||||
if (plugin) {
|
||||
Logger.debug(`[PluginManager] Found plugin "${plugin.manifest.name}"`)
|
||||
pluginsFound.push(plugin)
|
||||
}
|
||||
}
|
||||
|
||||
return pluginsFound
|
||||
}
|
||||
|
||||
/**
|
||||
* Load plugins from the /metadata/plugins directory and update the database
|
||||
*/
|
||||
async loadPlugins() {
|
||||
await fsExtra.ensureDir(this.pluginMetadataPath)
|
||||
|
||||
const pluginsFound = await this.getPluginsFromDirPath(this.pluginMetadataPath)
|
||||
|
||||
if (process.env.DEV_PLUGINS_PATH) {
|
||||
const devPluginsFound = await this.getPluginsFromDirPath(process.env.DEV_PLUGINS_PATH)
|
||||
if (!devPluginsFound.length) {
|
||||
Logger.warn(`[PluginManager] No plugins found in DEV_PLUGINS_PATH: ${process.env.DEV_PLUGINS_PATH}`)
|
||||
} else {
|
||||
pluginsFound.push(...devPluginsFound)
|
||||
}
|
||||
}
|
||||
|
||||
const existingPlugins = await Database.pluginModel.findAll()
|
||||
|
||||
// Add new plugins or update existing plugins
|
||||
for (const plugin of pluginsFound) {
|
||||
const existingPlugin = existingPlugins.find((p) => p.id === plugin.manifest.id)
|
||||
if (existingPlugin) {
|
||||
// TODO: Should automatically update?
|
||||
if (existingPlugin.version !== plugin.manifest.version) {
|
||||
Logger.info(`[PluginManager] Updating plugin "${plugin.manifest.name}" version from "${existingPlugin.version}" to version "${plugin.manifest.version}"`)
|
||||
await existingPlugin.update({ version: plugin.manifest.version, isMissing: false })
|
||||
} else if (existingPlugin.isMissing) {
|
||||
Logger.info(`[PluginManager] Plugin "${plugin.manifest.name}" was missing but is now found`)
|
||||
await existingPlugin.update({ isMissing: false })
|
||||
} else {
|
||||
Logger.debug(`[PluginManager] Plugin "${plugin.manifest.name}" already exists in the database with version "${plugin.manifest.version}"`)
|
||||
}
|
||||
plugin.instance = existingPlugin
|
||||
} else {
|
||||
plugin.instance = await Database.pluginModel.create({
|
||||
id: plugin.manifest.id,
|
||||
name: plugin.manifest.name,
|
||||
version: plugin.manifest.version
|
||||
})
|
||||
Logger.info(`[PluginManager] Added plugin "${plugin.manifest.name}" to the database`)
|
||||
}
|
||||
}
|
||||
|
||||
// Mark missing plugins
|
||||
for (const plugin of existingPlugins) {
|
||||
const foundPlugin = pluginsFound.find((p) => p.manifest.id === plugin.id)
|
||||
if (!foundPlugin && !plugin.isMissing) {
|
||||
Logger.info(`[PluginManager] Plugin "${plugin.name}" not found or invalid - marking as missing`)
|
||||
await plugin.update({ isMissing: true })
|
||||
}
|
||||
}
|
||||
|
||||
this.plugins = pluginsFound
|
||||
}
|
||||
|
||||
/**
|
||||
* Load and initialize all plugins
|
||||
*/
|
||||
async init() {
|
||||
await this.loadPlugins()
|
||||
|
||||
for (const plugin of this.plugins) {
|
||||
Logger.info(`[PluginManager] Initializing plugin ${plugin.manifest.name}`)
|
||||
plugin.init(this.getPluginContext(plugin.instance))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {PluginData} plugin
|
||||
* @param {string} actionName
|
||||
* @param {string} target
|
||||
* @param {Object} data
|
||||
* @returns {Promise<boolean|{error:string}>}
|
||||
*/
|
||||
onAction(plugin, actionName, target, data) {
|
||||
if (!plugin.onAction) {
|
||||
Logger.error(`[PluginManager] onAction not implemented for plugin ${plugin.manifest.name}`)
|
||||
return false
|
||||
}
|
||||
|
||||
const pluginExtension = plugin.manifest.extensions.find((extension) => extension.name === actionName)
|
||||
if (!pluginExtension) {
|
||||
Logger.error(`[PluginManager] Extension ${actionName} not found for plugin ${plugin.manifest.name}`)
|
||||
return false
|
||||
}
|
||||
|
||||
Logger.info(`[PluginManager] Calling onAction for plugin ${plugin.manifest.name}`)
|
||||
return plugin.onAction(this.getPluginContext(plugin.instance), actionName, target, data)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {PluginData} plugin
|
||||
* @param {Object} config
|
||||
* @returns {Promise<boolean|{error:string}>}
|
||||
*/
|
||||
onConfigSave(plugin, config) {
|
||||
if (!plugin.onConfigSave) {
|
||||
Logger.error(`[PluginManager] onConfigSave not implemented for plugin ${plugin.manifest.name}`)
|
||||
return false
|
||||
}
|
||||
|
||||
Logger.info(`[PluginManager] Calling onConfigSave for plugin ${plugin.manifest.name}`)
|
||||
return plugin.onConfigSave(this.getPluginContext(plugin.instance), config)
|
||||
}
|
||||
}
|
||||
module.exports = new PluginManager()
|
||||
@@ -586,4 +586,4 @@ class PodcastManager {
|
||||
Logger.info(`[PodcastManager] createPodcastsFromFeedUrls: Finished OPML import. Created ${numPodcastsAdded} podcasts out of ${rssFeedUrls.length} RSS feed URLs`)
|
||||
}
|
||||
}
|
||||
module.exports = PodcastManager
|
||||
module.exports = new PodcastManager()
|
||||
|
||||
@@ -98,22 +98,11 @@ class RssFeedManager {
|
||||
podcastId: feed.entity.mediaId
|
||||
},
|
||||
attributes: ['id', 'updatedAt'],
|
||||
order: [['updatedAt', 'DESC']]
|
||||
order: [['createdAt', '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
|
||||
@@ -122,7 +111,7 @@ class RssFeedManager {
|
||||
attributes: ['id', 'updatedAt'],
|
||||
include: {
|
||||
model: Database.bookModel,
|
||||
attributes: ['id', 'audioFiles', 'updatedAt'],
|
||||
attributes: ['id'],
|
||||
through: {
|
||||
attributes: []
|
||||
},
|
||||
@@ -133,16 +122,13 @@ 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) => {
|
||||
let updatedAt = book.libraryItem.updatedAt > book.updatedAt ? book.libraryItem.updatedAt : book.updatedAt
|
||||
return updatedAt > mostRecent ? updatedAt : mostRecent
|
||||
if (book.libraryItem.updatedAt > mostRecent) {
|
||||
return book.libraryItem.updatedAt
|
||||
}
|
||||
return mostRecent
|
||||
}, 0)
|
||||
|
||||
if (mostRecentItemUpdatedAt > newEntityUpdatedAt) {
|
||||
@@ -165,9 +151,6 @@ class RssFeedManager {
|
||||
let feed = await Database.feedModel.findOne({
|
||||
where: {
|
||||
slug: req.params.slug
|
||||
},
|
||||
include: {
|
||||
model: Database.feedEpisodeModel
|
||||
}
|
||||
})
|
||||
if (!feed) {
|
||||
@@ -180,6 +163,8 @@ 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,4 +12,3 @@ 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 |
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
/**
|
||||
* @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 }
|
||||
68
server/migrations/v2.18.0-add-plugins-table.js
Normal file
68
server/migrations/v2.18.0-add-plugins-table.js
Normal file
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* @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.18.0'
|
||||
const migrationName = `${migrationVersion}-add-plugins-table`
|
||||
const loggerPrefix = `[${migrationVersion} migration]`
|
||||
|
||||
/**
|
||||
* This upward migration creates the plugins table if it does not exist.
|
||||
*
|
||||
* @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}`)
|
||||
|
||||
if (!(await queryInterface.tableExists('plugins'))) {
|
||||
const DataTypes = queryInterface.sequelize.Sequelize.DataTypes
|
||||
await queryInterface.createTable('plugins', {
|
||||
id: {
|
||||
type: DataTypes.UUID,
|
||||
defaultValue: DataTypes.UUIDV4,
|
||||
primaryKey: true
|
||||
},
|
||||
name: DataTypes.STRING,
|
||||
version: DataTypes.STRING,
|
||||
isMissing: DataTypes.BOOLEAN,
|
||||
config: DataTypes.JSON,
|
||||
extraData: DataTypes.JSON,
|
||||
createdAt: DataTypes.DATE,
|
||||
updatedAt: DataTypes.DATE
|
||||
})
|
||||
logger.info(`${loggerPrefix} Table 'plugins' created`)
|
||||
} else {
|
||||
logger.info(`${loggerPrefix} Table 'plugins' already exists`)
|
||||
}
|
||||
|
||||
logger.info(`${loggerPrefix} UPGRADE END: ${migrationName}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* This downward migration script drops the plugins table if it exists.
|
||||
*
|
||||
* @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}`)
|
||||
|
||||
if (await queryInterface.tableExists('plugins')) {
|
||||
await queryInterface.dropTable('plugins')
|
||||
logger.info(`${loggerPrefix} Table 'plugins' dropped`)
|
||||
} else {
|
||||
logger.info(`${loggerPrefix} Table 'plugins' does not exist`)
|
||||
}
|
||||
|
||||
logger.info(`${loggerPrefix} DOWNGRADE END: ${migrationName}`)
|
||||
}
|
||||
|
||||
module.exports = { up, down }
|
||||
@@ -321,10 +321,10 @@ class Book extends Model {
|
||||
// },
|
||||
{
|
||||
fields: ['publishedYear']
|
||||
},
|
||||
{
|
||||
fields: ['duration']
|
||||
}
|
||||
// {
|
||||
// fields: ['duration']
|
||||
// }
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
const { DataTypes, Model, Sequelize } = require('sequelize')
|
||||
|
||||
const oldCollection = require('../objects/Collection')
|
||||
|
||||
class Collection extends Model {
|
||||
constructor(values, options) {
|
||||
super(values, options)
|
||||
@@ -24,12 +26,12 @@ class Collection extends Model {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all toOldJSONExpanded, items filtered for user permissions
|
||||
* Get all old collections toJSONExpanded, items filtered for user permissions
|
||||
*
|
||||
* @param {import('./User')} user
|
||||
* @param {string} [libraryId]
|
||||
* @param {string[]} [include]
|
||||
* @async
|
||||
* @returns {Promise<oldCollection[]>} oldCollection.toJSONExpanded
|
||||
*/
|
||||
static async getOldCollectionsJsonExpanded(user, libraryId, include) {
|
||||
let collectionWhere = null
|
||||
@@ -77,6 +79,8 @@ 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) => {
|
||||
@@ -91,14 +95,20 @@ 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 && c.books.length) {
|
||||
if (!books.length && oldCollection.books.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
this.books = books
|
||||
|
||||
const collectionExpanded = c.toOldJSONExpanded()
|
||||
const collectionExpanded = oldCollection.toJSONExpanded(libraryItems)
|
||||
|
||||
// Map feed if found
|
||||
if (c.feeds?.length) {
|
||||
@@ -143,6 +153,69 @@ 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
|
||||
@@ -213,37 +286,64 @@ class Collection extends Model {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get toOldJSONExpanded, items filtered for user permissions
|
||||
* Get old collection toJSONExpanded, items filtered for user permissions
|
||||
*
|
||||
* @param {import('./User')|null} user
|
||||
* @param {string[]} [include]
|
||||
* @async
|
||||
* @returns {Promise<oldCollection>} oldCollection.toJSONExpanded
|
||||
*/
|
||||
async getOldJsonExpanded(user, include) {
|
||||
this.books = await this.getBooksExpandedWithLibraryItem()
|
||||
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')]
|
||||
})) || []
|
||||
|
||||
// Filter books using user permissions
|
||||
// TODO: Handle user permission restrictions on initial query
|
||||
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
|
||||
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
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}) || []
|
||||
|
||||
// Users with restricted permissions will not see this collection
|
||||
if (!books.length && this.books.length) {
|
||||
return null
|
||||
}
|
||||
// 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)
|
||||
})
|
||||
|
||||
this.books = books
|
||||
// Users with restricted permissions will not see this collection
|
||||
if (!books.length && this.books.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
const collectionExpanded = this.toOldJSONExpanded()
|
||||
const collectionExpanded = this.toOldJSONExpanded(libraryItems)
|
||||
|
||||
if (include?.includes('rssfeed')) {
|
||||
const feeds = await this.getFeeds()
|
||||
@@ -257,10 +357,10 @@ class Collection extends Model {
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string[]} [libraryItemIds=[]]
|
||||
* @param {string[]} libraryItemIds
|
||||
* @returns
|
||||
*/
|
||||
toOldJSON(libraryItemIds = []) {
|
||||
toOldJSON(libraryItemIds) {
|
||||
return {
|
||||
id: this.id,
|
||||
libraryId: this.libraryId,
|
||||
@@ -272,19 +372,19 @@ class Collection extends Model {
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
})
|
||||
|
||||
/**
|
||||
*
|
||||
* @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)
|
||||
return json
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,15 @@ class CollectionBook extends Model {
|
||||
this.createdAt
|
||||
}
|
||||
|
||||
static removeByIds(collectionId, bookId) {
|
||||
return this.destroy({
|
||||
where: {
|
||||
bookId,
|
||||
collectionId
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
static init(sequelize) {
|
||||
super.init(
|
||||
{
|
||||
|
||||
@@ -107,9 +107,6 @@ 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 = {
|
||||
@@ -190,8 +187,7 @@ class Feed extends Model {
|
||||
const booksWithTracks = collectionExpanded.books.filter((book) => book.includedAudioFiles.length)
|
||||
|
||||
const entityUpdatedAt = booksWithTracks.reduce((mostRecent, book) => {
|
||||
const updatedAt = book.libraryItem.updatedAt > book.updatedAt ? book.libraryItem.updatedAt : book.updatedAt
|
||||
return updatedAt > mostRecent ? updatedAt : mostRecent
|
||||
return book.libraryItem.updatedAt > mostRecent ? book.libraryItem.updatedAt : mostRecent
|
||||
}, collectionExpanded.updatedAt)
|
||||
|
||||
const firstBookWithCover = booksWithTracks.find((book) => book.coverPath)
|
||||
@@ -279,8 +275,7 @@ 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) => {
|
||||
const updatedAt = book.libraryItem.updatedAt > book.updatedAt ? book.libraryItem.updatedAt : book.updatedAt
|
||||
return updatedAt > mostRecent ? updatedAt : mostRecent
|
||||
return book.libraryItem.updatedAt > mostRecent ? book.libraryItem.updatedAt : mostRecent
|
||||
}, seriesExpanded.updatedAt)
|
||||
|
||||
const firstBookWithCover = booksWithTracks.find((book) => book.coverPath)
|
||||
@@ -521,24 +516,17 @@ class Feed extends Model {
|
||||
try {
|
||||
const updatedFeed = await this.update(feedObj, { transaction })
|
||||
|
||||
const existingFeedEpisodeIds = this.feedEpisodes.map((ep) => ep.id)
|
||||
// Remove existing feed episodes
|
||||
await feedEpisodeModel.destroy({
|
||||
where: {
|
||||
feedId: this.id
|
||||
},
|
||||
transaction
|
||||
})
|
||||
|
||||
// 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,10 +53,9 @@ class FeedEpisode extends Model {
|
||||
* @param {import('./Feed')} feed
|
||||
* @param {string} slug
|
||||
* @param {import('./PodcastEpisode')} episode
|
||||
* @param {string} [existingEpisodeId]
|
||||
*/
|
||||
static getFeedEpisodeObjFromPodcastEpisode(libraryItemExpanded, feed, slug, episode, existingEpisodeId = null) {
|
||||
const episodeId = existingEpisodeId || uuidv4()
|
||||
static getFeedEpisodeObjFromPodcastEpisode(libraryItemExpanded, feed, slug, episode) {
|
||||
const episodeId = uuidv4()
|
||||
return {
|
||||
id: episodeId,
|
||||
title: episode.title,
|
||||
@@ -95,18 +94,11 @@ 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) {
|
||||
// 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))
|
||||
feedEpisodeObjs.push(this.getFeedEpisodeObjFromPodcastEpisode(libraryItemExpanded, feed, slug, episode))
|
||||
}
|
||||
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'] })
|
||||
Logger.info(`[FeedEpisode] Creating ${feedEpisodeObjs.length} episodes for feed ${feed.id}`)
|
||||
return this.bulkCreate(feedEpisodeObjs, { transaction })
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -135,12 +127,11 @@ 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, existingEpisodeId = null) {
|
||||
static getFeedEpisodeObjFromAudiobookTrack(book, pubDateStart, feed, slug, audioTrack, useChapterTitles) {
|
||||
// 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 = existingEpisodeId || uuidv4()
|
||||
let episodeId = 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]')
|
||||
@@ -188,18 +179,11 @@ class FeedEpisode extends Model {
|
||||
const useChapterTitles = this.checkUseChapterTitlesForEpisodes(libraryItemExpanded.media)
|
||||
|
||||
const feedEpisodeObjs = []
|
||||
let numExisting = 0
|
||||
for (const track of libraryItemExpanded.media.trackList) {
|
||||
// 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))
|
||||
feedEpisodeObjs.push(this.getFeedEpisodeObjFromAudiobookTrack(libraryItemExpanded.media, libraryItemExpanded.createdAt, feed, slug, track, useChapterTitles))
|
||||
}
|
||||
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'] })
|
||||
Logger.info(`[FeedEpisode] Creating ${feedEpisodeObjs.length} episodes for feed ${feed.id}`)
|
||||
return this.bulkCreate(feedEpisodeObjs, { transaction })
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -216,21 +200,14 @@ 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) {
|
||||
// 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))
|
||||
feedEpisodeObjs.push(this.getFeedEpisodeObjFromAudiobookTrack(book, earliestLibraryItemCreatedAt, feed, slug, track, useChapterTitles))
|
||||
}
|
||||
}
|
||||
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'] })
|
||||
Logger.info(`[FeedEpisode] Creating ${feedEpisodeObjs.length} episodes for feed ${feed.id}`)
|
||||
return this.bulkCreate(feedEpisodeObjs, { transaction })
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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
|
||||
*/
|
||||
@@ -1061,9 +1061,6 @@ class LibraryItem extends Model {
|
||||
{
|
||||
fields: ['libraryId', 'mediaType']
|
||||
},
|
||||
{
|
||||
fields: ['libraryId', 'mediaType', 'size']
|
||||
},
|
||||
{
|
||||
fields: ['libraryId', 'mediaId', 'mediaType']
|
||||
},
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
const { DataTypes, Model, Op } = require('sequelize')
|
||||
const { DataTypes, Model, Op, literal } = require('sequelize')
|
||||
const Logger = require('../Logger')
|
||||
|
||||
const oldPlaylist = require('../objects/Playlist')
|
||||
|
||||
class Playlist extends Model {
|
||||
constructor(values, options) {
|
||||
super(values, options)
|
||||
@@ -19,23 +21,134 @@ class Playlist extends Model {
|
||||
this.createdAt
|
||||
/** @type {Date} */
|
||||
this.updatedAt
|
||||
}
|
||||
|
||||
// Expanded properties
|
||||
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)
|
||||
|
||||
/** @type {import('./PlaylistMediaItem')[]} - only set when expanded */
|
||||
this.playlistMediaItems
|
||||
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()
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get old playlists for user and library
|
||||
* 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
|
||||
*
|
||||
* @param {string} userId
|
||||
* @param {string} libraryId
|
||||
* @async
|
||||
* @param {string} [libraryId]
|
||||
* @returns {Promise<oldPlaylist[]>}
|
||||
*/
|
||||
static async getOldPlaylistsForUserAndLibrary(userId, libraryId) {
|
||||
static async getOldPlaylistsForUserAndLibrary(userId, libraryId = null) {
|
||||
if (!userId && !libraryId) return []
|
||||
|
||||
const whereQuery = {}
|
||||
if (userId) {
|
||||
whereQuery.userId = userId
|
||||
@@ -50,23 +163,7 @@ class Playlist extends Model {
|
||||
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']
|
||||
}
|
||||
}
|
||||
]
|
||||
include: this.sequelize.models.libraryItem
|
||||
},
|
||||
{
|
||||
model: this.sequelize.models.podcastEpisode,
|
||||
@@ -77,13 +174,42 @@ class Playlist extends Model {
|
||||
}
|
||||
]
|
||||
},
|
||||
order: [['playlistMediaItems', 'order', 'ASC']]
|
||||
order: [
|
||||
[literal('name COLLATE NOCASE'), 'ASC'],
|
||||
['playlistMediaItems', 'order', 'ASC']
|
||||
]
|
||||
})
|
||||
|
||||
// Sort by name asc
|
||||
playlistsExpanded.sort((a, b) => a.name.localeCompare(b.name))
|
||||
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
|
||||
|
||||
return playlistsExpanded.map((playlist) => playlist.toOldJSONExpanded())
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -219,117 +345,6 @@ 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,11 +16,15 @@ class PlaylistMediaItem extends Model {
|
||||
this.playlistId
|
||||
/** @type {Date} */
|
||||
this.createdAt
|
||||
}
|
||||
|
||||
// Expanded properties
|
||||
|
||||
/** @type {import('./Book')|import('./PodcastEpisode')} - only set when expanded */
|
||||
this.mediaItem
|
||||
static removeByIds(playlistId, mediaItemId) {
|
||||
return this.destroy({
|
||||
where: {
|
||||
playlistId,
|
||||
mediaItemId
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
getMediaItem(options) {
|
||||
|
||||
54
server/models/Plugin.js
Normal file
54
server/models/Plugin.js
Normal file
@@ -0,0 +1,54 @@
|
||||
const { DataTypes, Model } = require('sequelize')
|
||||
|
||||
class Plugin extends Model {
|
||||
constructor(values, options) {
|
||||
super(values, options)
|
||||
|
||||
/** @type {UUIDV4} */
|
||||
this.id
|
||||
/** @type {string} */
|
||||
this.name
|
||||
/** @type {string} */
|
||||
this.version
|
||||
/** @type {boolean} */
|
||||
this.isMissing
|
||||
/** @type {Object} */
|
||||
this.config
|
||||
/** @type {Object} */
|
||||
this.extraData
|
||||
/** @type {Date} */
|
||||
this.createdAt
|
||||
/** @type {Date} */
|
||||
this.updatedAt
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize model
|
||||
* @param {import('../Database').sequelize} sequelize
|
||||
*/
|
||||
static init(sequelize) {
|
||||
super.init(
|
||||
{
|
||||
id: {
|
||||
type: DataTypes.UUID,
|
||||
defaultValue: DataTypes.UUIDV4,
|
||||
primaryKey: true
|
||||
},
|
||||
name: DataTypes.STRING,
|
||||
version: DataTypes.STRING,
|
||||
isMissing: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
defaultValue: false
|
||||
},
|
||||
config: DataTypes.JSON,
|
||||
extraData: DataTypes.JSON
|
||||
},
|
||||
{
|
||||
sequelize,
|
||||
modelName: 'plugin'
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Plugin
|
||||
@@ -170,62 +170,6 @@ 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
|
||||
}
|
||||
|
||||
toOldJSON(libraryItemId) {
|
||||
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: this.chapters?.map((ch) => ({ ...ch })) || [],
|
||||
audioFile: this.audioFile || null,
|
||||
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.audioFile?.metadata.size || 0
|
||||
json.duration = this.audioFile?.duration || 0
|
||||
|
||||
return json
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PodcastEpisode
|
||||
|
||||
115
server/objects/Collection.js
Normal file
115
server/objects/Collection.js
Normal file
@@ -0,0 +1,115 @@
|
||||
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
|
||||
148
server/objects/Playlist.js
Normal file
148
server/objects/Playlist.js
Normal file
@@ -0,0 +1,148 @@
|
||||
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,6 +33,7 @@ const RSSFeedController = require('../controllers/RSSFeedController')
|
||||
const CustomMetadataProviderController = require('../controllers/CustomMetadataProviderController')
|
||||
const MiscController = require('../controllers/MiscController')
|
||||
const ShareController = require('../controllers/ShareController')
|
||||
const PluginController = require('../controllers/PluginController')
|
||||
|
||||
const { getTitleIgnorePrefix } = require('../utils/index')
|
||||
|
||||
@@ -46,8 +47,6 @@ class ApiRouter {
|
||||
this.abMergeManager = Server.abMergeManager
|
||||
/** @type {import('../managers/BackupManager')} */
|
||||
this.backupManager = Server.backupManager
|
||||
/** @type {import('../managers/PodcastManager')} */
|
||||
this.podcastManager = Server.podcastManager
|
||||
/** @type {import('../managers/AudioMetadataManager')} */
|
||||
this.audioMetadataManager = Server.audioMetadataManager
|
||||
/** @type {import('../managers/CronManager')} */
|
||||
@@ -320,6 +319,13 @@ class ApiRouter {
|
||||
this.router.post('/share/mediaitem', ShareController.createMediaItemShare.bind(this))
|
||||
this.router.delete('/share/mediaitem/:id', ShareController.deleteMediaItemShare.bind(this))
|
||||
|
||||
//
|
||||
// Plugin routes
|
||||
//
|
||||
this.router.get('/plugins/:id/config', PluginController.middleware.bind(this), PluginController.getConfig.bind(this))
|
||||
this.router.post('/plugins/:id/action', PluginController.middleware.bind(this), PluginController.handleAction.bind(this))
|
||||
this.router.post('/plugins/:id/config', PluginController.middleware.bind(this), PluginController.handleConfigSave.bind(this))
|
||||
|
||||
//
|
||||
// Misc Routes
|
||||
//
|
||||
|
||||
@@ -243,3 +243,21 @@ module.exports.isValidASIN = (str) => {
|
||||
if (!str || typeof str !== 'string') return false
|
||||
return /^[A-Z0-9]{10}$/.test(str)
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse semver string that must be in format "major.minor.patch" all numbers
|
||||
*
|
||||
* @param {string} version
|
||||
* @returns {{major: number, minor: number, patch: number} | null}
|
||||
*/
|
||||
module.exports.parseSemverStrict = (version) => {
|
||||
if (typeof version !== 'string') {
|
||||
return null
|
||||
}
|
||||
const [major, minor, patch] = version.split('.').map(Number)
|
||||
|
||||
if (isNaN(major) || isNaN(minor) || isNaN(patch)) {
|
||||
return null
|
||||
}
|
||||
return { major, minor, patch }
|
||||
}
|
||||
|
||||
5
test/server/managers/PluginManager.test.js
Normal file
5
test/server/managers/PluginManager.test.js
Normal file
@@ -0,0 +1,5 @@
|
||||
describe('PluginManager', () => {
|
||||
it('should register a plugin', () => {
|
||||
// Test implementation
|
||||
})
|
||||
})
|
||||
152
test/server/managers/plugins/Example/index.js
Normal file
152
test/server/managers/plugins/Example/index.js
Normal file
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* Called on initialization of the plugin
|
||||
*
|
||||
* @param {import('../../../server/managers/PluginManager').PluginContext} context
|
||||
*/
|
||||
module.exports.init = async (context) => {
|
||||
// Set default config on first init
|
||||
if (!context.pluginInstance.config) {
|
||||
context.Logger.info('[ExamplePlugin] First init. Setting default config')
|
||||
context.pluginInstance.config = {
|
||||
requestAddress: '',
|
||||
enable: false
|
||||
}
|
||||
await context.pluginInstance.save()
|
||||
}
|
||||
|
||||
context.Database.mediaProgressModel.addHook('afterSave', (instance, options) => {
|
||||
context.Logger.debug(`[ExamplePlugin] mediaProgressModel afterSave hook for mediaProgress ${instance.id}`)
|
||||
handleMediaProgressUpdate(context, instance)
|
||||
})
|
||||
|
||||
context.Logger.info('[ExamplePlugin] Example plugin initialized')
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when an extension action is triggered
|
||||
*
|
||||
* @param {import('../../../server/managers/PluginManager').PluginContext} context
|
||||
* @param {string} actionName
|
||||
* @param {string} target
|
||||
* @param {*} data
|
||||
* @returns {Promise<boolean|{error: string}>}
|
||||
*/
|
||||
module.exports.onAction = async (context, actionName, target, data) => {
|
||||
context.Logger.info('[ExamplePlugin] Example plugin onAction', actionName, target, data)
|
||||
|
||||
createTask(context)
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the plugin config page is saved
|
||||
*
|
||||
* @param {import('../../../server/managers/PluginManager').PluginContext} context
|
||||
* @param {*} config
|
||||
* @returns {Promise<boolean|{error: string}>}
|
||||
*/
|
||||
module.exports.onConfigSave = async (context, config) => {
|
||||
context.Logger.info('[ExamplePlugin] Example plugin onConfigSave', config)
|
||||
|
||||
if (!config.requestAddress || typeof config.requestAddress !== 'string') {
|
||||
context.Logger.error('[ExamplePlugin] Invalid request address')
|
||||
return {
|
||||
error: 'Invalid request address'
|
||||
}
|
||||
}
|
||||
if (typeof config.enable !== 'boolean') {
|
||||
context.Logger.error('[ExamplePlugin] Invalid enable value')
|
||||
return {
|
||||
error: 'Invalid enable value'
|
||||
}
|
||||
}
|
||||
|
||||
// Config would need to be validated
|
||||
const updatedConfig = {
|
||||
requestAddress: config.requestAddress,
|
||||
enable: config.enable
|
||||
}
|
||||
context.pluginInstance.config = updatedConfig
|
||||
await context.pluginInstance.save()
|
||||
context.Logger.info('[ExamplePlugin] Example plugin config saved', updatedConfig)
|
||||
return true
|
||||
}
|
||||
|
||||
//
|
||||
// Helper functions
|
||||
//
|
||||
let numProgressSyncs = 0
|
||||
|
||||
/**
|
||||
* Send media progress update to external requestAddress defined in config
|
||||
*
|
||||
* @param {import('../../../server/managers/PluginManager').PluginContext} context
|
||||
* @param {import('../../../server/models/MediaProgress')} mediaProgress
|
||||
*/
|
||||
async function handleMediaProgressUpdate(context, mediaProgress) {
|
||||
// Need to reload the model instance since it was passed in during init and may have values changed
|
||||
await context.pluginInstance.reload()
|
||||
|
||||
if (!context.pluginInstance.config?.enable) {
|
||||
return
|
||||
}
|
||||
const requestAddress = context.pluginInstance.config.requestAddress
|
||||
if (!requestAddress) {
|
||||
context.Logger.error('[ExamplePlugin] Request address not set')
|
||||
return
|
||||
}
|
||||
|
||||
const mediaItem = await mediaProgress.getMediaItem()
|
||||
if (!mediaItem) {
|
||||
context.Logger.error(`[ExamplePlugin] Media item not found for mediaProgress ${mediaProgress.id}`)
|
||||
} else {
|
||||
const mediaProgressDuration = mediaProgress.duration
|
||||
const progressPercent = mediaProgressDuration > 0 ? (mediaProgress.currentTime / mediaProgressDuration) * 100 : 0
|
||||
context.Logger.info(`[ExamplePlugin] Media progress update for "${mediaItem.title}" ${Math.round(progressPercent)}% (total numProgressSyncs: ${numProgressSyncs})`)
|
||||
|
||||
fetch(requestAddress, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
title: mediaItem.title,
|
||||
progress: progressPercent
|
||||
})
|
||||
})
|
||||
.then(() => {
|
||||
context.Logger.info(`[ExamplePlugin] Media progress update sent for "${mediaItem.title}" ${Math.round(progressPercent)}%`)
|
||||
numProgressSyncs++
|
||||
sendAdminMessageToast(context, `Synced "${mediaItem.title}" (total syncs: ${numProgressSyncs})`)
|
||||
})
|
||||
.catch((error) => {
|
||||
context.Logger.error(`[ExamplePlugin] Error sending media progress update: ${error.message}`)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test socket authority
|
||||
*
|
||||
* @param {import('../../../server/managers/PluginManager').PluginContext} context
|
||||
* @param {string} message
|
||||
*/
|
||||
async function sendAdminMessageToast(context, message) {
|
||||
context.SocketAuthority.adminEmitter('admin_message', message)
|
||||
}
|
||||
|
||||
/**
|
||||
* Test task manager
|
||||
*
|
||||
* @param {import('../../../server/managers/PluginManager').PluginContext} context
|
||||
*/
|
||||
async function createTask(context) {
|
||||
const task = context.TaskManager.createAndAddTask('example_action', { text: 'Example Task' }, { text: 'This is an example task' }, true)
|
||||
const pluginConfigEnabled = !!context.pluginInstance.config.enable
|
||||
|
||||
setTimeout(() => {
|
||||
task.setFinished({ text: `Plugin is ${pluginConfigEnabled ? 'enabled' : 'disabled'}` })
|
||||
context.TaskManager.taskFinished(task)
|
||||
}, 5000)
|
||||
}
|
||||
53
test/server/managers/plugins/Example/manifest.json
Normal file
53
test/server/managers/plugins/Example/manifest.json
Normal file
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"id": "e6205690-916c-4add-9a2b-2548266996ef",
|
||||
"name": "Example",
|
||||
"version": "1.0.0",
|
||||
"owner": "advplyr",
|
||||
"repositoryUrl": "https://github.com/example/example-plugin",
|
||||
"documentationUrl": "https://example.com",
|
||||
"description": "This is an example plugin",
|
||||
"descriptionKey": "ExamplePluginDescription",
|
||||
"extensions": [
|
||||
{
|
||||
"target": "item.detail.actions",
|
||||
"name": "itemActionExample",
|
||||
"label": "Item Example Action",
|
||||
"labelKey": "ItemExampleAction"
|
||||
}
|
||||
],
|
||||
"config": {
|
||||
"description": "This is a description on how to configure the plugin",
|
||||
"descriptionKey": "ExamplePluginConfigurationDescription",
|
||||
"formFields": [
|
||||
{
|
||||
"name": "requestAddress",
|
||||
"label": "Request Address",
|
||||
"labelKey": "LabelRequestAddress",
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"name": "enable",
|
||||
"label": "Enable",
|
||||
"labelKey": "LabelEnable",
|
||||
"type": "checkbox"
|
||||
}
|
||||
]
|
||||
},
|
||||
"localization": {
|
||||
"de": {
|
||||
"ExamplePluginDescription": "Dies ist ein Beispiel-Plugin",
|
||||
"ItemExampleAction": "Item Example Action",
|
||||
"LabelEnable": "Enable",
|
||||
"ExamplePluginConfigurationDescription": "This is a description on how to configure the plugin",
|
||||
"LabelRequestAddress": "Request Address"
|
||||
}
|
||||
},
|
||||
"releases": [
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"changelog": "Initial release",
|
||||
"timestamp": "2022-01-01T00:00:00Z",
|
||||
"downloadUrl": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
36
test/server/managers/plugins/Template/index.js
Normal file
36
test/server/managers/plugins/Template/index.js
Normal file
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Called on initialization of the plugin
|
||||
*
|
||||
* @param {import('../../../server/managers/PluginManager').PluginContext} context
|
||||
*/
|
||||
module.exports.init = async (context) => {
|
||||
context.Logger.info('[TemplatePlugin] plugin initialized')
|
||||
// Can be used to initialize plugin config and/or setup Database hooks
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when an extension action is triggered
|
||||
*
|
||||
* @param {import('../../../server/managers/PluginManager').PluginContext} context
|
||||
* @param {string} actionName
|
||||
* @param {string} target
|
||||
* @param {Object} data
|
||||
* @returns {Promise<boolean|{error: string}>}
|
||||
*/
|
||||
module.exports.onAction = async (context, actionName, target, data) => {
|
||||
context.Logger.info('[TemplatePlugin] plugin onAction', actionName, target, data)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the plugin config page is saved
|
||||
*
|
||||
* @param {import('../../../server/managers/PluginManager').PluginContext} context
|
||||
* @param {Object} config
|
||||
* @returns {Promise<boolean|{error: string}>}
|
||||
*/
|
||||
module.exports.onConfigSave = async (context, config) => {
|
||||
context.Logger.info('[TemplatePlugin] plugin onConfigSave', config)
|
||||
// Maintener is responsible for validating and saving the config to their `pluginInstance`
|
||||
return true
|
||||
}
|
||||
20
test/server/managers/plugins/Template/manifest.json
Normal file
20
test/server/managers/plugins/Template/manifest.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"id": "e6205690-916c-4add-9a2b-2548266996eg",
|
||||
"name": "Template",
|
||||
"version": "1.0.0",
|
||||
"owner": "advplyr",
|
||||
"repositoryUrl": "https://github.com/advplr/abs-report-for-review-plugin",
|
||||
"documentationUrl": "https://audiobookshelf.org/guides",
|
||||
"description": "This is a minimal template for an abs plugin",
|
||||
"extensions": [],
|
||||
"config": {},
|
||||
"localization": {},
|
||||
"releases": [
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"changelog": "Initial release",
|
||||
"timestamp": "2022-01-01T00:00:00Z",
|
||||
"downloadUrl": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
0
test/server/managers/plugins/readme.md
Normal file
0
test/server/managers/plugins/readme.md
Normal file
Reference in New Issue
Block a user