mirror of
https://github.com/advplyr/audiobookshelf.git
synced 2026-12-04 22:16:28 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8b4a2f2c3a | ||
|
|
dc0afcce79 | ||
|
|
625b854236 | ||
|
|
177b945c60 | ||
|
|
b7c0e039c8 | ||
|
|
df5522b569 | ||
|
|
0f213c2b4e | ||
|
|
5ba7a3fee5 | ||
|
|
938fd36b1d | ||
|
|
b7ead7a316 | ||
|
|
f5a40b1ece | ||
|
|
69fa8d08d4 | ||
|
|
86af083e1d | ||
|
|
ebd03c9086 | ||
|
|
1c082182b8 | ||
|
|
508516e1df | ||
|
|
2730a0c838 | ||
|
|
acaf0d3949 | ||
|
|
de5f80e0ff | ||
|
|
47bdd3d2dc | ||
|
|
0afb582f09 | ||
|
|
03cca94403 | ||
|
|
9e3176e76e | ||
|
|
5de038dafd | ||
|
|
a5540d07c6 | ||
|
|
1e0921100b | ||
|
|
54f1f5c7a4 | ||
|
|
fc11bb4947 | ||
|
|
0776e8079e | ||
|
|
bf1c5688b9 | ||
|
|
1430c9fc64 | ||
|
|
84a7061cb4 | ||
|
|
9a7f331ab5 | ||
|
|
23eff31a2d | ||
|
|
3ebd8c0068 | ||
|
|
cefa357c87 | ||
|
|
f78811882b | ||
|
|
cc0675d27c | ||
|
|
9301910b2f | ||
|
|
8f04237659 | ||
|
|
26028a3619 | ||
|
|
c68798d66c | ||
|
|
125774083c | ||
|
|
6ee1618b8a | ||
|
|
0bff6c02cb | ||
|
|
870e3e313c | ||
|
|
38b6e6d92c | ||
|
|
c5c9e6c844 | ||
|
|
8f69ca0f78 | ||
|
|
2a14f96b53 | ||
|
|
25a82ae964 | ||
|
|
d875332b86 | ||
|
|
3c622c89e0 | ||
|
|
1eb5b9f1bc | ||
|
|
c5e6e463e4 | ||
|
|
75d85e971b | ||
|
|
3e0333877b | ||
|
|
2dde0bf1c7 | ||
|
|
e9ff70e522 | ||
|
|
83dce682e8 | ||
|
|
f88fdf1321 | ||
|
|
20fd0cd700 | ||
|
|
9b055f80a6 | ||
|
|
04acd53667 | ||
|
|
8af3448ac0 | ||
|
|
cf1f162aba | ||
|
|
49c0ef6c07 | ||
|
|
420c2b28ed | ||
|
|
f35f40929d | ||
|
|
f57ca09f6e | ||
|
|
149bae7d73 | ||
|
|
d6d0cf6b8f | ||
|
|
087099faa3 | ||
|
|
ce41ce489c | ||
|
|
b31af26837 | ||
|
|
4072054e00 | ||
|
|
f1f57d6595 | ||
|
|
7aaa734d3e | ||
|
|
48d9309eb2 | ||
|
|
616c8ba152 |
No files matched your search
@@ -0,0 +1,102 @@
|
||||
# Builds the v3 test image
|
||||
#
|
||||
# Moves the :v3 tag on Docker Hub and GHCR, the same way master
|
||||
# moves :edge. Using the server's v3 branch and react-client master.
|
||||
#
|
||||
# repository_dispatch (build-v3) is for triggering a build on updates to react-client
|
||||
|
||||
name: Build and Push v3 Docker Image
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [v3]
|
||||
repository_dispatch:
|
||||
types: [build-v3]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
if: ${{ github.repository == 'advplyr/audiobookshelf' && (github.event_name != 'push' || !contains(github.event.head_commit.message, 'skip ci')) }}
|
||||
runs-on: ubuntu-24.04
|
||||
|
||||
steps:
|
||||
- name: Check out server
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event_name == 'repository_dispatch' && 'v3' || github.sha }}
|
||||
|
||||
- name: Check out React client
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: audiobookshelf/audiobookshelf-client-react
|
||||
ref: master
|
||||
path: client-react
|
||||
|
||||
- name: Server sha
|
||||
id: server-sha
|
||||
run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Client sha
|
||||
id: client-sha
|
||||
working-directory: client-react
|
||||
run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: advplyr/audiobookshelf,ghcr.io/${{ github.repository_owner }}/audiobookshelf
|
||||
flavor: |
|
||||
latest=false
|
||||
tags: |
|
||||
type=raw,value=v3
|
||||
labels: |
|
||||
audiobookshelf.server.sha=${{ steps.server-sha.outputs.sha }}
|
||||
audiobookshelf.client.sha=${{ steps.client-sha.outputs.sha }}
|
||||
|
||||
- name: Setup QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Cache Docker layers
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: /tmp/.buildx-cache
|
||||
key: ${{ runner.os }}-buildx-v3-${{ github.sha }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-buildx-v3-
|
||||
|
||||
- name: Login to Dockerhub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_PASSWORD }}
|
||||
|
||||
- name: Login to ghcr
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.GHCR_PASSWORD }}
|
||||
|
||||
- name: Build image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
file: client-react/Dockerfile
|
||||
context: .
|
||||
build-contexts: |
|
||||
abs-client=client-react
|
||||
abs-server=.
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
cache-from: type=local,src=/tmp/.buildx-cache
|
||||
cache-to: type=local,dest=/tmp/.buildx-cache-new,mode=max
|
||||
|
||||
- name: Move cache
|
||||
run: |
|
||||
rm -rf /tmp/.buildx-cache
|
||||
mv /tmp/.buildx-cache-new /tmp/.buildx-cache
|
||||
@@ -34,6 +34,13 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Install libnusqlite3
|
||||
run: |
|
||||
curl -fsSL -o /tmp/libnusqlite3.zip "https://github.com/mikiher/nunicode-sqlite/releases/download/v1.2/libnusqlite3-linux-x64.zip"
|
||||
unzip -o /tmp/libnusqlite3.zip -d /tmp/nusqlite3
|
||||
echo "NUSQLITE3_PATH=/tmp/nusqlite3/libnusqlite3.so" >> "$GITHUB_ENV"
|
||||
rm /tmp/libnusqlite3.zip
|
||||
|
||||
- name: Run lint
|
||||
run: npm run lint
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# Security
|
||||
|
||||
Report security issues through GitHub private vulnerability reporting.
|
||||
|
||||
Failed logins (`POST /login`) share one server-wide limit. Failed password changes (`PATCH /api/me/password`) are limited per user. Neither limit uses the client IP. Set `RATE_LIMIT_AUTH_MAX=0` to disable both.
|
||||
|
||||
Anything beyond those two limits is the server operator's responsibility. Add a rate limiter in front of the server if you want one. A missing limiter on any other route is out of scope unless the report shows a guessable secret or a resource that grows without a bound.
|
||||
@@ -42,7 +42,7 @@
|
||||
<div v-if="userCanUpdate" class="mx-1" :class="isHovering ? '' : 'ml-6'">
|
||||
<ui-icon-btn icon="edit" borderless @click="clickEdit" />
|
||||
</div>
|
||||
<div v-if="userCanDelete" class="mx-1">
|
||||
<div v-if="userCanUpdate" class="mx-1">
|
||||
<ui-icon-btn icon="close" borderless @click="removeClick" />
|
||||
</div>
|
||||
</div>
|
||||
@@ -79,8 +79,7 @@ export default {
|
||||
},
|
||||
computed: {
|
||||
translateDistance() {
|
||||
if (!this.userCanUpdate && !this.userCanDelete) return 'translate-x-0'
|
||||
else if (!this.userCanUpdate || !this.userCanDelete) return '-translate-x-12'
|
||||
if (!this.userCanUpdate) return 'translate-x-0'
|
||||
return '-translate-x-24'
|
||||
},
|
||||
media() {
|
||||
@@ -144,9 +143,6 @@ export default {
|
||||
},
|
||||
userCanUpdate() {
|
||||
return this.$store.getters['user/getUserCanUpdate']
|
||||
},
|
||||
userCanDelete() {
|
||||
return this.$store.getters['user/getUserCanDelete']
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "audiobookshelf-client",
|
||||
"version": "2.37.2",
|
||||
"version": "2.38.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "audiobookshelf-client",
|
||||
"version": "2.37.2",
|
||||
"version": "2.38.0",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@nuxtjs/axios": "^5.13.6",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "audiobookshelf-client",
|
||||
"version": "2.37.2",
|
||||
"version": "2.38.0",
|
||||
"buildNumber": 1,
|
||||
"description": "Self-hosted audiobook and podcast client",
|
||||
"main": "index.js",
|
||||
|
||||
@@ -1030,8 +1030,8 @@
|
||||
"ToastCollectionItemsAddFailed": "Přidávání položek do kolekce selhalo",
|
||||
"ToastCollectionRemoveSuccess": "Kolekce odstraněna",
|
||||
"ToastCollectionUpdateSuccess": "Kolekce aktualizována",
|
||||
"ToastConnectionNotAvailable": "Připojení není k dispozici. Zkuste to prosím znovu později",
|
||||
"ToastCoverSearchFailed": "Hledání obálky se nezdařilo",
|
||||
"ToastConnectionNotAvailable": "Připojení není k dispozici. Prosím zkuste to později.",
|
||||
"ToastCoverSearchFailed": "Vyhledání obalu selhalo",
|
||||
"ToastCoverUpdateFailed": "Aktualizace obálky selhala",
|
||||
"ToastDateTimeInvalidOrIncomplete": "Datum a čas jsou chybné nebo nekompletní",
|
||||
"ToastDeleteFileFailed": "Nepodařilo se smazat soubor",
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
"ButtonEditChapters": "Rediger kapitler",
|
||||
"ButtonEditPodcast": "Rediger podcast",
|
||||
"ButtonEnable": "Aktivér",
|
||||
"ButtonFireAndFail": "Affyring Og Fejl",
|
||||
"ButtonFireAndFail": "Affyring og Fejl",
|
||||
"ButtonFireOnTest": "Udløs onTest-hændelse",
|
||||
"ButtonForceReScan": "Tving genskanning",
|
||||
"ButtonFullPath": "Fuld sti",
|
||||
@@ -46,6 +46,7 @@
|
||||
"ButtonLatest": "Seneste",
|
||||
"ButtonLibrary": "Bibliotek",
|
||||
"ButtonLogout": "Log ud",
|
||||
"ButtonLogoutAllDevices": "Log ud af alle enheder",
|
||||
"ButtonLookup": "Slå op",
|
||||
"ButtonManageTracks": "Administrer spor",
|
||||
"ButtonMapChapterTitles": "Kortlæg kapiteloverskrifter",
|
||||
@@ -194,6 +195,7 @@
|
||||
"HeaderScheduleEpisodeDownloads": "Planlæg automatisk hentning af afsnit",
|
||||
"HeaderScheduleLibraryScans": "Planlæg automatisk biblioteksskanning",
|
||||
"HeaderSession": "Session",
|
||||
"HeaderSessions": "Sessioner",
|
||||
"HeaderSetBackupSchedule": "Indstil tidsplan for sikkerhedskopiering",
|
||||
"HeaderSettings": "Indstillinger",
|
||||
"HeaderSettingsDisplay": "Visning",
|
||||
@@ -415,6 +417,7 @@
|
||||
"LabelIntervalEveryHour": "Hver time",
|
||||
"LabelIntervalEveryMinute": "Hvert minut",
|
||||
"LabelInvert": "Omvendt begrænsning",
|
||||
"LabelIpAddress": "IP Adresse",
|
||||
"LabelItem": "Element",
|
||||
"LabelJumpBackwardAmount": "Tilbagespolingstid",
|
||||
"LabelJumpForwardAmount": "Fremadspolingstid",
|
||||
@@ -774,6 +777,7 @@
|
||||
"MessageConfirmDeleteSession": "Er du sikker på, at du vil slette denne session?",
|
||||
"MessageConfirmEmbedMetadataInAudioFiles": "Er du sikker på at du vil indlejre metadata i {0} lydbogsfiler?",
|
||||
"MessageConfirmForceReScan": "Er du sikker på, at du vil tvinge en genindlæsning?",
|
||||
"MessageConfirmLogoutDevice": "Er du sikker på, at du vil logge ud af \"{0}\"?",
|
||||
"MessageConfirmMarkAllEpisodesFinished": "Er du sikker på, at du vil markere alle episoder som afsluttet?",
|
||||
"MessageConfirmMarkAllEpisodesNotFinished": "Er du sikker på, at du vil markere alle episoder som ikke afsluttet?",
|
||||
"MessageConfirmMarkItemFinished": "Er du sikker på at du vil markere \"{0}\" som færdig?",
|
||||
|
||||
@@ -403,7 +403,7 @@
|
||||
"LabelHours": "Stunden",
|
||||
"LabelIcon": "Symbol",
|
||||
"LabelImageURLFromTheWeb": "Bild-URL vom Internet",
|
||||
"LabelInProgress": "In Bearbeitung",
|
||||
"LabelInProgress": "Begonnen",
|
||||
"LabelIncludeInTracklist": "In die Titelliste aufnehmen",
|
||||
"LabelIncomplete": "Unvollständig",
|
||||
"LabelInterval": "Intervall",
|
||||
|
||||
@@ -463,7 +463,7 @@
|
||||
"LabelSettingsHomePageBookshelfView": "Avalehel kasuta raamaturiiulivaadet",
|
||||
"LabelSettingsLibraryBookshelfView": "Raamatukogus kasuta raamaturiiulivaadet",
|
||||
"LabelSettingsParseSubtitles": "Lugege subtiitreid",
|
||||
"LabelSettingsParseSubtitlesHelp": "Eraldage subtiitrid heliraamatu kaustade nimedest.<br>Subtiitrid peavad olema eraldatud kasutades \" - \".<br>Näiteks: \"Raamatu pealkiri - Siin on alapealkiri\" alapealkiri on \"Siin on alapealkiri\"",
|
||||
"LabelSettingsParseSubtitlesHelp": "Eraldage subtiitrid heliraamatu kaustade nimedest.<br>Subtiitrid peavad olema eraldatud kasutades \" - \".<br>Näiteks: \"Raamatu pealkiri - Siin on alapealkiri\" alapealkiri on \"Siin on alapealkiri\"",
|
||||
"LabelSettingsPreferMatchedMetadata": "Eelista sobitatud metaandmeid",
|
||||
"LabelSettingsPreferMatchedMetadataHelp": "Sobitatud andmed kirjutavad Kiir Sobitamise kasutamisel üle üksikasjad.",
|
||||
"LabelSettingsSkipMatchingBooksWithASIN": "Jätke ASIN-iga sobituvad raamatud vahele",
|
||||
|
||||
+41
-1
@@ -1 +1,41 @@
|
||||
{}
|
||||
{
|
||||
"ButtonAdd": "Gehitu",
|
||||
"ButtonAddApiKey": "Gehitu API Gakoa",
|
||||
"ButtonAddChapters": "Kapituluak gehitu",
|
||||
"ButtonAddDevice": "Gailu gehitu",
|
||||
"ButtonAddPodcasts": "Podcastak gehitu",
|
||||
"ButtonAddUser": "Erabiltzailea gehitu",
|
||||
"ButtonApply": "Aplikatu",
|
||||
"ButtonApplyChapters": "Kapituluak aplikatu",
|
||||
"ButtonAuthors": "Egileak",
|
||||
"ButtonBack": "Atzera",
|
||||
"ButtonCancel": "Utzi",
|
||||
"ButtonCheckAndDownloadNewEpisodes": "Atal berriak aztertu eta deskargatu",
|
||||
"ButtonChooseAFolder": "Karpeta bat aukeratu",
|
||||
"ButtonChooseFiles": "Karpetak aukeratu",
|
||||
"ButtonClearFilter": "Iragazkiak garbitu",
|
||||
"ButtonClose": "Itxi",
|
||||
"ButtonCloseFeed": "Feed itxi",
|
||||
"ButtonCollections": "Bildumak",
|
||||
"ButtonCreate": "Sortu",
|
||||
"ButtonCreateBackup": "Babeskopia sortu",
|
||||
"ButtonDelete": "Ezabatu",
|
||||
"ButtonDownloadQueue": "Ilarra",
|
||||
"ButtonEdit": "Editatu",
|
||||
"ButtonEditChapters": "Kapituluak editatu",
|
||||
"ButtonEditPodcast": "Podcasta editatu",
|
||||
"ButtonEnable": "Aktibatu",
|
||||
"ButtonHide": "Ezkutatu",
|
||||
"ButtonHome": "Etxea",
|
||||
"ButtonIssues": "Arazoak",
|
||||
"ButtonLogout": "Saioa itxi",
|
||||
"ButtonLogoutAllDevices": "Gailu guztietan saioa itxi",
|
||||
"ButtonNevermind": "Ez du axola",
|
||||
"ButtonNext": "Ondorengoa",
|
||||
"ButtonNextChapter": "Hurrengo kapitulua",
|
||||
"ButtonOk": "Ados",
|
||||
"ButtonPause": "Pausa",
|
||||
"ButtonPlaylists": "Erreprodukzio-zerrendak",
|
||||
"ButtonQueueAddItem": "Ilarara gehitu",
|
||||
"ButtonQueueRemoveItem": "Ilaratik kendu"
|
||||
}
|
||||
+11
-1
@@ -24,5 +24,15 @@
|
||||
"ButtonSave": "ذخیره",
|
||||
"ButtonSearch": "جستجو",
|
||||
"ButtonSeries": "مجموعه",
|
||||
"ButtonSubmit": "ثبت"
|
||||
"ButtonSubmit": "ثبت",
|
||||
"ButtonYes": "بله",
|
||||
"HeaderAccount": "حساب کاربری",
|
||||
"HeaderAdvanced": "پیشرفته",
|
||||
"HeaderChapters": "قسمتها",
|
||||
"HeaderCollection": "مجموعه",
|
||||
"HeaderDetails": "جزئیات",
|
||||
"HeaderEpisodes": "قسمتها",
|
||||
"HeaderEreaderSettings": "تنظیمات Ereader",
|
||||
"HeaderLatestEpisodes": "آخرین قسمتها",
|
||||
"HeaderLibraries": "مجموعهها"
|
||||
}
|
||||
@@ -34,54 +34,78 @@
|
||||
"ButtonEditChapters": "अध्याय संपादित करें",
|
||||
"ButtonEditPodcast": "पॉडकास्ट संपादित करें",
|
||||
"ButtonEnable": "सक्षम करें",
|
||||
"ButtonFireAndFail": "भेजें और विफल हों",
|
||||
"ButtonFireOnTest": "फायर ऑनटेस्ट इवेंट",
|
||||
"ButtonForceReScan": "बलपूर्वक पुन: स्कैन करें",
|
||||
"ButtonFullPath": "पूर्ण पथ",
|
||||
"ButtonHide": "छुपाएं",
|
||||
"ButtonHome": "घर",
|
||||
"ButtonIssues": "समस्याएं",
|
||||
"ButtonJumpBackward": "पीछे जाएं",
|
||||
"ButtonJumpForward": "आगे जाएं",
|
||||
"ButtonLatest": "नवीनतम",
|
||||
"ButtonLibrary": "पुस्तकालय",
|
||||
"ButtonLogout": "लॉग आउट",
|
||||
"ButtonLogoutAllDevices": "सभी डिवाइस से लॉगआउट करें",
|
||||
"ButtonLookup": "तलाश करें",
|
||||
"ButtonManageTracks": "ट्रैक्स मैनेज करें",
|
||||
"ButtonMapChapterTitles": "अध्यायों का मिलान करें",
|
||||
"ButtonMatchAllAuthors": "सभी लेखकों को तलाश करें",
|
||||
"ButtonMatchBooks": "संबंधित पुस्तकों का मिलान करें",
|
||||
"ButtonNevermind": "कोई बात नहीं",
|
||||
"ButtonNext": "अगला",
|
||||
"ButtonNextChapter": "अगला चैप्टर",
|
||||
"ButtonNextItemInQueue": "कतार में अगला आइटम",
|
||||
"ButtonOk": "ठीक है",
|
||||
"ButtonOpenFeed": "फ़ीड खोलें",
|
||||
"ButtonOpenManager": "मैनेजर खोलें",
|
||||
"ButtonPause": "पॉज़ करें",
|
||||
"ButtonPlay": "चलाएँ",
|
||||
"ButtonPlayAll": "सभी प्ले करें",
|
||||
"ButtonPlaying": "चल रही है",
|
||||
"ButtonPlaylists": "प्लेलिस्ट्स",
|
||||
"ButtonPrevious": "पिछला",
|
||||
"ButtonPreviousChapter": "पिछला चैप्टर",
|
||||
"ButtonProbeAudioFile": "ऑडियो फ़ाइल की जांच करें",
|
||||
"ButtonPurgeAllCache": "सभी Cache मिटाएं",
|
||||
"ButtonPurgeItemsCache": "आइटम Cache मिटाएं",
|
||||
"ButtonQueueAddItem": "क़तार में जोड़ें",
|
||||
"ButtonQueueRemoveItem": "कतार से हटाएं",
|
||||
"ButtonQuickEmbed": "तुरंत एम्बेड करें",
|
||||
"ButtonQuickEmbedMetadata": "मेटाडेटा तुरंत एम्बेड करें",
|
||||
"ButtonQuickMatch": "जल्दी से समानता की तलाश करें",
|
||||
"ButtonReScan": "पुन: स्कैन करें",
|
||||
"ButtonRead": "पढ़ लिया",
|
||||
"ButtonReadLess": "कम पढ़ें",
|
||||
"ButtonRefresh": "रिफ्रेश करें",
|
||||
"ButtonRemove": "हटाएं",
|
||||
"ButtonRemoveAll": "सभी हटाएं",
|
||||
"ButtonRemoveAllLibraryItems": "पुस्तकालय की सभी आइटम हटाएं",
|
||||
"ButtonRemoveFromContinueListening": "सुनना जारी रखें से हटाएं",
|
||||
"ButtonRemoveFromContinueReading": "'पढ़ना जारी रखें' से हटाएं",
|
||||
"ButtonRemoveSeriesFromContinueSeries": "इस सीरीज को कंटिन्यू सीरीज से हटा दें",
|
||||
"ButtonReset": "रीसेट करें",
|
||||
"ButtonResetToDefault": "डिफ़ॉल्ट पर रीसेट करें",
|
||||
"ButtonRestore": "पुनर्स्थापित करें",
|
||||
"ButtonSave": "सहेजें",
|
||||
"ButtonSaveAndClose": "सहेजें और बंद करें",
|
||||
"ButtonSaveTracklist": "ट्रैक सूची सहेजें",
|
||||
"ButtonScan": "स्कैन करें",
|
||||
"ButtonScanLibrary": "पुस्तकालय स्कैन करें",
|
||||
"ButtonScrollRight": "बाईं ओर स्क्रॉल करें",
|
||||
"ButtonSearch": "खोजें",
|
||||
"ButtonSelectFolderPath": "फ़ोल्डर का पथ चुनें",
|
||||
"ButtonSeries": "सीरीज",
|
||||
"ButtonSetChaptersFromTracks": "ट्रैक्स से अध्याय बनाएं",
|
||||
"ButtonShare": "शेयर करें",
|
||||
"ButtonShiftTimes": "समय खिसकाए",
|
||||
"ButtonShow": "दिखाएं",
|
||||
"ButtonStartM4BEncode": "M4B एन्कोडिंग शुरू करें",
|
||||
"ButtonStartMetadataEmbed": "मेटाडेटा एम्बेडिंग शुरू करें",
|
||||
"ButtonStats": "आँकड़े",
|
||||
"ButtonSubmit": "जमा करें",
|
||||
"ButtonTest": "टेस्ट करें",
|
||||
"ButtonUnlinkOpenId": "OpenID अनलिंक करें",
|
||||
"ButtonUpload": "अपलोड करें",
|
||||
"ButtonUploadBackup": "बैकअप अपलोड करें",
|
||||
"ButtonUploadCover": "कवर अपलोड करें",
|
||||
@@ -90,9 +114,37 @@
|
||||
"ButtonUserEdit": "उपयोगकर्ता {0} को संपादित करें",
|
||||
"ButtonViewAll": "सभी को देखें",
|
||||
"ButtonYes": "हाँ",
|
||||
"ErrorUploadFetchMetadataAPI": "मेटाडेटा लाने में त्रुटि हुई",
|
||||
"ErrorUploadFetchMetadataNoResults": "मेटाडेटा लाने में असमर्थ - कृपया शीर्षक और/या लेखक का नाम अपडेट करके पुनः प्रयास करें",
|
||||
"ErrorUploadLacksTitle": "शीर्षक होना अनिवार्य है",
|
||||
"HeaderAccount": "खाता",
|
||||
"HeaderAddCustomMetadataProvider": "कस्टम मेटाडेटा प्रोवाइडर जोड़ें",
|
||||
"HeaderAdvanced": "विकसित",
|
||||
"HeaderApiKeys": "एपीआई कुंजियाँ (API Keys)",
|
||||
"HeaderAppriseNotificationSettings": "Apprise अधिसूचना सेटिंग्स",
|
||||
"HeaderAudioTracks": "ऑडियो ट्रैक्स",
|
||||
"HeaderAudiobookTools": "ऑडियोबुक फ़ाइल प्रबंधन उपकरण",
|
||||
"HeaderAuthentication": "ऑथेंटिकेशन",
|
||||
"HeaderBackups": "बैकअप",
|
||||
"HeaderBulkChapterModal": "एक साथ कई चैप्टर जोड़ें",
|
||||
"HeaderChangePassword": "पासवर्ड बदलें",
|
||||
"HeaderChapters": "चैप्टर्स",
|
||||
"HeaderChooseAFolder": "फ़ोल्डर चुनें",
|
||||
"HeaderCollection": "कलेक्शन",
|
||||
"HeaderCollectionItems": "कलेक्शन आइटम्स",
|
||||
"HeaderCover": "कवर",
|
||||
"HeaderCurrentDownloads": "मौजूदा डाउनलोड",
|
||||
"HeaderCustomMessageOnLogin": "लॉगिन पर कस्टम संदेश",
|
||||
"HeaderCustomMetadataProviders": "कस्टम मेटाडेटा प्रोवाइडर्स",
|
||||
"HeaderDetails": "विवरण",
|
||||
"HeaderDownloadQueue": "डाउनलोड कतार",
|
||||
"HeaderEbookFiles": "ई-बुक फ़ाइलें",
|
||||
"HeaderEmail": "ईमेल",
|
||||
"HeaderEmailSettings": "ईमेल सेटिंग",
|
||||
"HeaderEpisodes": "एपिसोड",
|
||||
"HeaderEreaderDevices": "ई-रीडर डिवाइस",
|
||||
"HeaderEreaderSettings": "ई-रीडर सेटिंग्स",
|
||||
"HeaderFiles": "फ़ाइलें",
|
||||
"LabelBackupsMaxBackupSize": "Maximum backup size (in GB)",
|
||||
"LabelFontFamily": "फुहारा परिवार",
|
||||
"LabelPodcastSearchRegion": "पॉडकास्ट खोज क्षेत्र",
|
||||
|
||||
@@ -145,7 +145,7 @@
|
||||
"HeaderEmailSettings": "E-mail beállítások",
|
||||
"HeaderEpisodes": "Epizódok",
|
||||
"HeaderEreaderDevices": "E-olvasó eszközök",
|
||||
"HeaderEreaderSettings": "E-olvasó beállítások",
|
||||
"HeaderEreaderSettings": "E-olvasó beállításai",
|
||||
"HeaderFiles": "Fájlok",
|
||||
"HeaderFindChapters": "Fejezetek keresése",
|
||||
"HeaderIgnoredFiles": "Figyelmen kívül hagyott fájlok",
|
||||
@@ -486,7 +486,7 @@
|
||||
"LabelNoCustomMetadataProviders": "Nincsenek egyedi metaadat szolgáltatók",
|
||||
"LabelNoEpisodesSelected": "Nincsenek kiválasztott epizódok",
|
||||
"LabelNotFinished": "Nem befejezett",
|
||||
"LabelNotStarted": "Nem indult el",
|
||||
"LabelNotStarted": "Nem kezdődött el",
|
||||
"LabelNotes": "Megjegyzések",
|
||||
"LabelNotificationAppriseURL": "Apprise URL(ek)",
|
||||
"LabelNotificationAvailableVariables": "Elérhető változók",
|
||||
@@ -868,7 +868,7 @@
|
||||
"MessageNoSeries": "Nincsenek sorozatok",
|
||||
"MessageNoTags": "Nincsenek címkék",
|
||||
"MessageNoTasksRunning": "Nincsenek futó feladatok",
|
||||
"MessageNoUpdatesWereNecessary": "Nem volt szükség frissítésekre",
|
||||
"MessageNoUpdatesWereNecessary": "Nincs szükség frissítésre",
|
||||
"MessageNoUserPlaylists": "Nincsenek felhasználói lejátszási listák",
|
||||
"MessageNoUserPlaylistsHelp": "A lejátszási listák személyesek. Csak az a felhasználó láthatja őket, aki létrehozta őket.",
|
||||
"MessageNotYetImplemented": "Még nem implementált",
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
"ButtonJumpBackward": "Salta indietro",
|
||||
"ButtonJumpForward": "Salta Avanti",
|
||||
"ButtonLatest": "Ultimi",
|
||||
"ButtonLibrary": "Biblioteca",
|
||||
"ButtonLibrary": "Libreria",
|
||||
"ButtonLogout": "Disconnetti",
|
||||
"ButtonLogoutAllDevices": "Disconnetti su tutti i dispositivi",
|
||||
"ButtonLookup": "Consulta",
|
||||
@@ -311,7 +311,7 @@
|
||||
"LabelDeleteFromFileSystemCheckbox": "Elimina dal file system (despunta per rimuoverla solo dal database)",
|
||||
"LabelDescription": "Descrizione",
|
||||
"LabelDeselectAll": "Deseleziona Tutto",
|
||||
"LabelDetectedPattern": "Trovato pattern:",
|
||||
"LabelDetectedPattern": "Pattern rilevato:",
|
||||
"LabelDevice": "Dispositivo",
|
||||
"LabelDeviceInfo": "Info dispositivo",
|
||||
"LabelDeviceIsAvailableTo": "Il dispositivo e disponibile su…",
|
||||
@@ -439,8 +439,8 @@
|
||||
"LabelLibraryFilterSublistEmpty": "Nessuno {0}",
|
||||
"LabelLibraryItem": "Elementi della biblioteca",
|
||||
"LabelLibraryName": "Nome della biblioteca",
|
||||
"LabelLibrarySortByProgress": "Progresso: ultimo aggiornamento",
|
||||
"LabelLibrarySortByProgressFinished": "Progresso: finito",
|
||||
"LabelLibrarySortByProgress": "Progresso: Ultimo Aggiornamento",
|
||||
"LabelLibrarySortByProgressFinished": "Progresso: Finito",
|
||||
"LabelLibrarySortByProgressStarted": "Progresso: iniziato",
|
||||
"LabelLimit": "Limiti",
|
||||
"LabelLineSpacing": "Interlinea",
|
||||
@@ -641,7 +641,7 @@
|
||||
"LabelStartTime": "Tempo di inizio",
|
||||
"LabelStarted": "Iniziato",
|
||||
"LabelStartedAt": "Iniziato al",
|
||||
"LabelStartedDate": "Iniziati {0}",
|
||||
"LabelStartedDate": "Iniziato {0}",
|
||||
"LabelStatsAudioTracks": "Tracce Audio",
|
||||
"LabelStatsAuthors": "Autori",
|
||||
"LabelStatsBestDay": "Giorno migliore",
|
||||
|
||||
@@ -275,7 +275,7 @@
|
||||
"LabelBonus": "ボーナス",
|
||||
"LabelBooks": "本",
|
||||
"LabelButtonText": "ボタンテキスト",
|
||||
"LabelByAuthor": "by {0}",
|
||||
"LabelByAuthor": "作者:{0}",
|
||||
"LabelChangePassword": "パスワードを変更",
|
||||
"LabelChannels": "チャンネル",
|
||||
"LabelChapterCount": "{0}チャプター",
|
||||
|
||||
+30
-1
@@ -1 +1,30 @@
|
||||
{}
|
||||
{
|
||||
"ButtonAdd": "Pievienot",
|
||||
"ButtonAuthors": "Autori",
|
||||
"ButtonBack": "Atpakaļ",
|
||||
"ButtonCancel": "Atcelt",
|
||||
"ButtonClearFilter": "Notīrīt filtru",
|
||||
"ButtonCloseFeed": "Aizvērt plūsmu",
|
||||
"ButtonCollections": "Kolekcijas",
|
||||
"ButtonCreate": "Izveidot",
|
||||
"ButtonDelete": "Dzēst",
|
||||
"ButtonHome": "Mājas",
|
||||
"ButtonIssues": "Problēmas",
|
||||
"ButtonLatest": "Pēdējais",
|
||||
"ButtonLibrary": "Bibliotēka",
|
||||
"ButtonOk": "Labi",
|
||||
"ButtonOpenFeed": "Atvērt barotni",
|
||||
"ButtonPause": "Pauzēt",
|
||||
"ButtonPlay": "Atskaņot",
|
||||
"ButtonPlaylists": "Atskaņošanas saraksti",
|
||||
"ButtonRead": "Lasīt",
|
||||
"ButtonReadLess": "Lasīt mazāk",
|
||||
"ButtonReadMore": "Lasīt vairāk",
|
||||
"ButtonRemove": "Noņemt",
|
||||
"ButtonSave": "Saglabāt",
|
||||
"ButtonSearch": "Meklēt",
|
||||
"ButtonSeries": "Sērijas",
|
||||
"ButtonSubmit": "Iesniegt",
|
||||
"ButtonYes": "Jā",
|
||||
"HeaderAccount": "Konts"
|
||||
}
|
||||
@@ -333,7 +333,7 @@
|
||||
"LabelEmail": "Epost",
|
||||
"LabelEmailSettingsFromAddress": "Fra Adresse",
|
||||
"LabelEmailSettingsRejectUnauthorized": "Avvis uautoriserte sertifikat",
|
||||
"LabelEmailSettingsRejectUnauthorizedHelp": "Ved å deaktivere sjekk av SSL sertifikat eksponerer man tilkoblingen for sikkerhetsrisiko, som for eksempel mann-i-midten-angrep. Slå av kun om du forstår implikasjonene og stoler på e-post-serveren du kobler til!",
|
||||
"LabelEmailSettingsRejectUnauthorizedHelp": "Ved å deaktivere sjekk av SSL sertifikat eksponerer man tilkoblingen for sikkerhetsrisiko, som for eksempel mann-i-midten-angrep. Slå av kun om du forstår implikasjonene og stoler på e-post-serveren du kobler til.",
|
||||
"LabelEmailSettingsSecure": "Sikker",
|
||||
"LabelEmailSettingsSecureHelp": "Hvis aktivert, vil tilkoblingen bruke TLS under tilkobling til tjeneren. Ellers vil TLS bli brukt hvis tjeneren støtter STARTTLS utvidelsen. I de fleste tilfeller aktiver valget hvis du kobler til med port 465. Med port 587 eller 25 deaktiver valget. (fra nodemailer.com/smtp/#authentication)",
|
||||
"LabelEmailSettingsTestAddress": "Test Adresse",
|
||||
@@ -577,7 +577,7 @@
|
||||
"LabelSelectUsers": "Velg brukere",
|
||||
"LabelSendEbookToDevice": "Send Ebok til...",
|
||||
"LabelSequence": "Sekvens",
|
||||
"LabelSerial": "Serienr.",
|
||||
"LabelSerial": "Seriell",
|
||||
"LabelSeries": "Serier",
|
||||
"LabelSeriesName": "Serier Navn",
|
||||
"LabelSeriesProgress": "Serier fremgang",
|
||||
@@ -610,7 +610,7 @@
|
||||
"LabelSettingsOnlyShowLaterBooksInContinueSeries": "Hopp over tidligere bøker i \"Fortsett serien\"",
|
||||
"LabelSettingsOnlyShowLaterBooksInContinueSeriesHelp": "\"Fortsett serie\"-siden viser første bok som ikke er påbegynt i serier der en bok er lest og ingen bøker leses nå. Ved å slå på denne innstillingen så vil man fortsette på serien etter siste leste bok, fremfor første bok som ikke er startet på i en serie.",
|
||||
"LabelSettingsParseSubtitles": "Analyser undertitler",
|
||||
"LabelSettingsParseSubtitlesHelp": "Hent undertittel fra lydbokens mappenavn.<br>Undertittel må være separert med \" - \"<br>f.eks. \"Boktittel - En lengre tittel\" har undertittel \"En lengre tittel\".",
|
||||
"LabelSettingsParseSubtitlesHelp": "Hent undertittel fra lydbokens mappenavn.<br>Undertittel må være separert med \" - \"<br>f.eks. \"Boktittel - En lengre tittel\" har undertittel \"En lengre tittel\"",
|
||||
"LabelSettingsPreferMatchedMetadata": "Foretrekk funnet metadata",
|
||||
"LabelSettingsPreferMatchedMetadataHelp": "Funnet data vil overskrive enhetens detaljene når man bruker Kjapt søk. Som standard vil Kjapt søk kun fylle inn manglende detaljer.",
|
||||
"LabelSettingsSkipMatchingBooksWithASIN": "Hopp over bøker som allerede har ASIN",
|
||||
@@ -744,7 +744,7 @@
|
||||
"MessageAuthenticationOIDCChangesRestart": "Etter å ha lagret, start serveren din på nytt for at OIDC-endringene skal tre i kraft.",
|
||||
"MessageAuthenticationSecurityMessage": "Autentisering er forbedret av sikkerhetshensyn. Alle brukere må logge inn på nytt.",
|
||||
"MessageBackupsDescription": "Sikkerhetskopier inkluderer, brukerfremgang, detaljer om bibliotekgjenstander, tjener instillinger og bilder lagret under <code>/metadata/items</code> og <code>/metadata/authors</code>. Sikkerhetskopier <strong>vil ikke</strong> inkludere filer som er lagret i bibliotek mappene.",
|
||||
"MessageBackupsLocationEditNote": "Viktig: Endring av mappen for sikkerhetskopi hverken endrer eller flytter eksisterende sikkerhetskopier!",
|
||||
"MessageBackupsLocationEditNote": "Viktig: Endring av mappen for sikkerhetskopi hverken endrer eller flytter eksisterende sikkerhetskopier",
|
||||
"MessageBackupsLocationNoEditNote": "Viktig: Mappen for sikkerhetskopi satt i en miljøvariabel og kan ikke endres her.",
|
||||
"MessageBackupsLocationPathEmpty": "Mappen for sikkerhetskopiering må angis",
|
||||
"MessageBatchEditPopulateMapDetailsAllHelp": "Fyll aktiverte felt med data fra alle elementer. Felt med flere verdier blir slått sammen",
|
||||
|
||||
@@ -456,7 +456,7 @@
|
||||
"LabelMaxEpisodesToDownload": "Maksymalna liczba odcinków do pobrania. Użyj 0, aby uzyskać nieograniczoną liczbę.",
|
||||
"LabelMaxEpisodesToDownloadPerCheck": "Maksymalna liczba nowych odcinków do pobrania na jedno sprawdzenie",
|
||||
"LabelMaxEpisodesToKeep": "Maksymalna liczba odcinków do zachowania",
|
||||
"LabelMaxEpisodesToKeepHelp": "Wartość 0 wyłącza maksymalny limit. Po automatycznym pobraniu nowego odcinka, najstarszy odcinek zostanie usunięty, jeśli masz ich więcej niż X. Spowoduje to usunięcie tylko 1 odcinka na nowe pobieranie.",
|
||||
"LabelMaxEpisodesToKeepHelp": "Wartość 0 nie ustawia maksymalnego limitu. Po automatycznym pobraniu nowego odcinka, najstarszy odcinek zostanie usunięty, jeśli masz ich więcej niż X. Spowoduje to usunięcie tylko 1 odcinka na nowe pobranie.",
|
||||
"LabelMediaPlayer": "Odtwarzacz",
|
||||
"LabelMediaType": "Typ mediów",
|
||||
"LabelMetaTag": "Tag",
|
||||
@@ -633,7 +633,7 @@
|
||||
"LabelShowSubtitles": "Pokaż Napisy",
|
||||
"LabelSize": "Rozmiar",
|
||||
"LabelSleepTimer": "Wyłącznik czasowy",
|
||||
"LabelSlug": "slug (części URL która identyfikuje konkretny zasób)",
|
||||
"LabelSlug": "Slug (części URL która identyfikuje konkretny zasób)",
|
||||
"LabelSortAscending": "Rosnąco",
|
||||
"LabelSortDescending": "Malejąco",
|
||||
"LabelSortPubDate": "Sortuj według daty publikacji",
|
||||
@@ -1038,7 +1038,7 @@
|
||||
"ToastDeleteFileSuccess": "Plik został usunięty",
|
||||
"ToastDeviceAddFailed": "Nieudana próba dodania urządzenia",
|
||||
"ToastDeviceNameAlreadyExists": "Czytnik z taką nazwą już istnieje",
|
||||
"ToastDeviceTestEmailFailed": "NIeudana próba wysłania testowego maila",
|
||||
"ToastDeviceTestEmailFailed": "Nieudana próba wysłania testowego maila",
|
||||
"ToastDeviceTestEmailSuccess": "Testowy email został wysłany",
|
||||
"ToastEmailSettingsUpdateSuccess": "Ustawienia email zaktualizowane",
|
||||
"ToastEncodeCancelFailed": "Nie udało się anulować kodowania",
|
||||
@@ -1046,7 +1046,7 @@
|
||||
"ToastEpisodeDownloadQueueClearFailed": "Nie udało się wyczyścić kolejki",
|
||||
"ToastEpisodeDownloadQueueClearSuccess": "Wyczyszczono kolejkę epizodów do ściągnięcia",
|
||||
"ToastEpisodeUpdateSuccess": "Zaktualizowano {0} odcinków",
|
||||
"ToastErrorCannotShare": "Nie można udostępniać natywnie na tym urządzeniu.",
|
||||
"ToastErrorCannotShare": "Nie można udostępniać natywnie na tym urządzeniu",
|
||||
"ToastFailedToCreate": "Nie udało się utworzyć",
|
||||
"ToastFailedToDelete": "Nie udało się usunąć",
|
||||
"ToastFailedToLoadData": "Nie udało się załadować danych",
|
||||
@@ -1143,7 +1143,7 @@
|
||||
"ToastSlugRequired": "Slug jest wymagany",
|
||||
"ToastSocketConnected": "Nawiązano połączenie z serwerem",
|
||||
"ToastSocketDisconnected": "Połączenie z serwerem zostało zamknięte",
|
||||
"ToastSocketFailedToConnect": "Poączenie z serwerem nie powiodło się",
|
||||
"ToastSocketFailedToConnect": "Połączenie z serwerem nie powiodło się",
|
||||
"ToastSortingPrefixesEmptyError": "Musi mieć co najmniej 1 prefiks sortowania",
|
||||
"ToastSortingPrefixesUpdateSuccess": "Zaktualizowano prefiksy sortowania ({0} elementów)",
|
||||
"ToastTitleRequired": "Tytuł jest wymagany",
|
||||
|
||||
+122
-118
@@ -21,15 +21,15 @@
|
||||
"ButtonChooseAFolder": "Vyberte priečinok",
|
||||
"ButtonChooseFiles": "Vyberte súbory",
|
||||
"ButtonClearFilter": "Zrušiť filter",
|
||||
"ButtonClose": "Uzavrieť",
|
||||
"ButtonClose": "Zavrieť",
|
||||
"ButtonCloseFeed": "Zatvoriť zdroj",
|
||||
"ButtonCloseSession": "Ukončiť aktívne relácie",
|
||||
"ButtonCollections": "Kolekcie",
|
||||
"ButtonCollections": "Zbierky",
|
||||
"ButtonConfigureScanner": "Nastaviť skener",
|
||||
"ButtonCreate": "Vytvoriť",
|
||||
"ButtonCreateBackup": "Vytvoriť zálohu",
|
||||
"ButtonDelete": "Zmazať",
|
||||
"ButtonDownloadQueue": "Poradie",
|
||||
"ButtonDownloadQueue": "Fronta",
|
||||
"ButtonEdit": "Upraviť",
|
||||
"ButtonEditChapters": "Upraviť kapitoly",
|
||||
"ButtonEditPodcast": "Upraviť podcast",
|
||||
@@ -46,6 +46,7 @@
|
||||
"ButtonLatest": "Najnovšie",
|
||||
"ButtonLibrary": "Knižnica",
|
||||
"ButtonLogout": "Odhlásenie",
|
||||
"ButtonLogoutAllDevices": "Odhlásiť zo všetkých zariadení",
|
||||
"ButtonLookup": "Vyhľadať",
|
||||
"ButtonManageTracks": "Spravovať stopy",
|
||||
"ButtonMapChapterTitles": "Mapovať názvy kapitol",
|
||||
@@ -54,7 +55,7 @@
|
||||
"ButtonNevermind": "Nevadí",
|
||||
"ButtonNext": "Ďalšie",
|
||||
"ButtonNextChapter": "Ďalšia kapitola",
|
||||
"ButtonNextItemInQueue": "Ďalšia položka v poradí",
|
||||
"ButtonNextItemInQueue": "Ďalšia položka vo fronte",
|
||||
"ButtonOk": "OK",
|
||||
"ButtonOpenFeed": "Otvoriť zdroj",
|
||||
"ButtonOpenManager": "Otvoriť správcu",
|
||||
@@ -65,27 +66,27 @@
|
||||
"ButtonPlaylists": "Playlisty",
|
||||
"ButtonPrevious": "Predchádzajúci",
|
||||
"ButtonPreviousChapter": "Predchádzajúca kapitola",
|
||||
"ButtonProbeAudioFile": "Preskúmaj zvukový súbor",
|
||||
"ButtonPurgeAllCache": "Vymaž celú medzipamäť",
|
||||
"ButtonPurgeItemsCache": "Vymaž medzipamäť položiek",
|
||||
"ButtonQueueAddItem": "Pridať do poradia",
|
||||
"ButtonQueueRemoveItem": "Vymazať z poradia",
|
||||
"ButtonProbeAudioFile": "Preskúmať zvukový súbor",
|
||||
"ButtonPurgeAllCache": "Vyčistiť celú vyrovnávaciu pamäť",
|
||||
"ButtonPurgeItemsCache": "Vyčistiť vyrovnávaciu pamäť položiek",
|
||||
"ButtonQueueAddItem": "Pridať do fronty",
|
||||
"ButtonQueueRemoveItem": "Odstrániť z fronty",
|
||||
"ButtonQuickEmbed": "Rýchle vloženie",
|
||||
"ButtonQuickEmbedMetadata": "Rýchle vloženie metadát",
|
||||
"ButtonQuickMatch": "Rýchle vyhľadanie",
|
||||
"ButtonReScan": "Preskenovať",
|
||||
"ButtonRead": "Načítať",
|
||||
"ButtonReadLess": "Načítať menej",
|
||||
"ButtonReadMore": "Načítať viac",
|
||||
"ButtonRead": "Čítať",
|
||||
"ButtonReadLess": "Čítať menej",
|
||||
"ButtonReadMore": "Čítať viac",
|
||||
"ButtonRefresh": "Obnoviť",
|
||||
"ButtonRemove": "Odstrániť",
|
||||
"ButtonRemoveAll": "Odstrániť všetko",
|
||||
"ButtonRemoveAllLibraryItems": "Odstrániť všetky položky knižnice",
|
||||
"ButtonRemoveFromContinueListening": "Odstrániť z nedokončených podcastov",
|
||||
"ButtonRemoveFromContinueReading": "Odtrániť z nedokončených audiokníh",
|
||||
"ButtonRemoveFromContinueReading": "Odstrániť z nedokončených audiokníh",
|
||||
"ButtonRemoveSeriesFromContinueSeries": "Odstrániť z nedokončených sérií",
|
||||
"ButtonReset": "Resetovať",
|
||||
"ButtonResetToDefault": "Resetovať do predvolené",
|
||||
"ButtonResetToDefault": "Resetovať na predvolené",
|
||||
"ButtonRestore": "Obnoviť zo zálohy",
|
||||
"ButtonSave": "Uložiť",
|
||||
"ButtonSaveAndClose": "Uložiť a zavrieť",
|
||||
@@ -95,7 +96,7 @@
|
||||
"ButtonScrollLeft": "Doľava",
|
||||
"ButtonScrollRight": "Doprava",
|
||||
"ButtonSearch": "Vyhľadať",
|
||||
"ButtonSelectFolderPath": "Vybrať umiestnenie priečinku",
|
||||
"ButtonSelectFolderPath": "Vybrať umiestnenie priečinka",
|
||||
"ButtonSeries": "Série",
|
||||
"ButtonSetChaptersFromTracks": "Nastaviť kapitoly podľa stôp",
|
||||
"ButtonShare": "Zdieľať",
|
||||
@@ -119,7 +120,7 @@
|
||||
"ErrorUploadFetchMetadataNoResults": "Metadáta sa nenašli - skúste upraviť názov a/alebo autora",
|
||||
"ErrorUploadLacksTitle": "Musí mať názov",
|
||||
"HeaderAccount": "Účet",
|
||||
"HeaderAddCustomMetadataProvider": "Pridať vastný zdroj metadát",
|
||||
"HeaderAddCustomMetadataProvider": "Pridať vlastný zdroj metadát",
|
||||
"HeaderAdvanced": "Pokročilé",
|
||||
"HeaderApiKeys": "Kľúče API",
|
||||
"HeaderAppriseNotificationSettings": "Nastavenie Apprise notifikácií",
|
||||
@@ -131,14 +132,14 @@
|
||||
"HeaderChangePassword": "Zmeniť heslo",
|
||||
"HeaderChapters": "Kapitoly",
|
||||
"HeaderChooseAFolder": "Vybrať priečinok",
|
||||
"HeaderCollection": "Zbierky",
|
||||
"HeaderCollection": "Zbierka",
|
||||
"HeaderCollectionItems": "Položky zbierky",
|
||||
"HeaderCover": "Prebal",
|
||||
"HeaderCurrentDownloads": "Aktuálne sťahovanie",
|
||||
"HeaderCustomMessageOnLogin": "Vlastné privítanie pri prihlásení",
|
||||
"HeaderCustomMetadataProviders": "Vlastné zdroje metadát",
|
||||
"HeaderDetails": "Podrobnosti",
|
||||
"HeaderDownloadQueue": "Poradie sťahovania",
|
||||
"HeaderDownloadQueue": "Fronta sťahovania",
|
||||
"HeaderEbookFiles": "Súbory e-kníh",
|
||||
"HeaderEmail": "E-mail",
|
||||
"HeaderEmailSettings": "Nastavenie e-mailu",
|
||||
@@ -177,7 +178,7 @@
|
||||
"HeaderOtherFiles": "Ostatné súbory",
|
||||
"HeaderPasswordAuthentication": "Overenie heslom",
|
||||
"HeaderPermissions": "Povolenia",
|
||||
"HeaderPlayerQueue": "Poradie prehrávania",
|
||||
"HeaderPlayerQueue": "Fronta prehrávania",
|
||||
"HeaderPlayerSettings": "Nastavenia prehrávania",
|
||||
"HeaderPlaylist": "Playlist",
|
||||
"HeaderPlaylistItems": "Položky playlistu",
|
||||
@@ -192,8 +193,9 @@
|
||||
"HeaderSavedMediaProgress": "Stav uložených médií",
|
||||
"HeaderSchedule": "Plán",
|
||||
"HeaderScheduleEpisodeDownloads": "Naplánovať automatické sťahovanie epizód",
|
||||
"HeaderScheduleLibraryScans": "Naplánovanovať automatické skenovanie knižnice",
|
||||
"HeaderScheduleLibraryScans": "Naplánovať automatické skenovanie knižnice",
|
||||
"HeaderSession": "Relácia",
|
||||
"HeaderSessions": "Relácie",
|
||||
"HeaderSetBackupSchedule": "Naplánovať zálohovanie",
|
||||
"HeaderSettings": "Nastavenia",
|
||||
"HeaderSettingsDisplay": "Zobraziť",
|
||||
@@ -216,7 +218,7 @@
|
||||
"HeaderUpdateAuthor": "Aktualizovať autora",
|
||||
"HeaderUpdateDetails": "Aktualizovať detaily",
|
||||
"HeaderUpdateLibrary": "Aktualizovať knižnicu",
|
||||
"HeaderUsers": "Užívatelia",
|
||||
"HeaderUsers": "Používatelia",
|
||||
"HeaderYearReview": "Prehľad roka {0}",
|
||||
"HeaderYourStats": "Vaše štatistiky",
|
||||
"LabelAbridged": "Skrátená verzia",
|
||||
@@ -232,20 +234,20 @@
|
||||
"LabelAddToCollection": "Pridať do zbierky",
|
||||
"LabelAddToCollectionBatch": "Pridať {0} kníh do zbierky",
|
||||
"LabelAddToPlaylist": "Pridať do playlistu",
|
||||
"LabelAddToPlaylistBatch": "Pridať {0} položie do playlistu",
|
||||
"LabelAddToPlaylistBatch": "Pridať {0} položiek do playlistu",
|
||||
"LabelAddedAt": "Pridané",
|
||||
"LabelAddedDate": "Pridané {0}",
|
||||
"LabelAdminUsersOnly": "Iba administrátory",
|
||||
"LabelAdminUsersOnly": "Iba administrátori",
|
||||
"LabelAll": "Všetko",
|
||||
"LabelAllEpisodesDownloaded": "Všetky epizódy stiahnuté",
|
||||
"LabelAllUsers": "Všetci užívatelia",
|
||||
"LabelAllUsersExcludingGuests": "Všetci užívatelia okrem hostí",
|
||||
"LabelAllUsersIncludingGuests": "Všetci užívatelia vrátane hostí",
|
||||
"LabelAlreadyInYourLibrary": "Už v tvojej knižnici",
|
||||
"LabelAllUsers": "Všetci používatelia",
|
||||
"LabelAllUsersExcludingGuests": "Všetci používatelia okrem hostí",
|
||||
"LabelAllUsersIncludingGuests": "Všetci používatelia vrátane hostí",
|
||||
"LabelAlreadyInYourLibrary": "Už vo vašej knižnici",
|
||||
"LabelApiKeyCreated": "Kľúč API \"{0}\" bol úspešne vytvorený.",
|
||||
"LabelApiKeyCreatedDescription": "Skopírujte si kľúč API teraz, neskôr ho už neuvidíte.",
|
||||
"LabelApiKeyUser": "Vykonáva v mene používateľa",
|
||||
"LabelApiKeyUserDescription": "Uvedená API bude mať rovnaké práva ako používateľ, v mene ktorého koná. Rovnako v záznamoch budú jednotlivé krky uvedené, ako keby ich vykonal samotný používateľ.",
|
||||
"LabelApiKeyUserDescription": "Tento kľúč API bude mať rovnaké oprávnenia ako používateľ, v mene ktorého koná. V záznamoch sa bude zobrazovať rovnako, ako keby požiadavku vykonal samotný používateľ.",
|
||||
"LabelApiToken": "API Token",
|
||||
"LabelAppend": "Pridať",
|
||||
"LabelAudioBitrate": "Bitrate audio stopy (napr. 128k)",
|
||||
@@ -257,20 +259,20 @@
|
||||
"LabelAuthors": "Autori",
|
||||
"LabelAutoDownloadEpisodes": "Automaticky sťahovať epizódy",
|
||||
"LabelAutoFetchMetadata": "Automaticky načítať metadáta",
|
||||
"LabelAutoFetchMetadataHelp": "Načíta metadáta pre názov, autra a sériu pre optimalizované nahranie. Dodatočné metadáta môžu byť priradené po nahraní.",
|
||||
"LabelAutoFetchMetadataHelp": "Načíta metadáta pre názov, autora a sériu pre optimalizované nahranie. Dodatočné metadáta môžu byť priradené po nahraní.",
|
||||
"LabelAutoLaunch": "Automaticky spustiť",
|
||||
"LabelAutoLaunchDescription": "Presmerovať na poskytovateľa authentifikácie pri otvorení prihlasovacej stránky (manuálny prepis cesty <code>/login?autoLaunch=0</code>)",
|
||||
"LabelAutoLaunchDescription": "Presmerovať na poskytovateľa autentifikácie pri otvorení prihlasovacej stránky (manuálny prepis cesty <code>/login?autoLaunch=0</code>)",
|
||||
"LabelAutoRegister": "Automatická registrácia",
|
||||
"LabelAutoRegisterDescription": "Automaticky vytvoriť nových užívateľov po prihlásení",
|
||||
"LabelBackToUser": "Späť na užívateľa",
|
||||
"LabelBackupAudioFiles": "Zálohovať audio súbory",
|
||||
"LabelBackupLocation": "Zálohovať lokáciu",
|
||||
"LabelBackupLocation": "Umiestnenie zálohy",
|
||||
"LabelBackupsEnableAutomaticBackups": "Automatické zálohy",
|
||||
"LabelBackupsEnableAutomaticBackupsHelp": "Zálohy uložené v /metadata/backups",
|
||||
"LabelBackupsMaxBackupSize": "Maximálna veľkosť zálohy (v GB) (0 pre neobmedzenú)",
|
||||
"LabelBackupsMaxBackupSizeHelp": "Ako poistka proti miskonfigurácii, zálohy zlyhajú ak prekročia konfigurovanú veľkosť.",
|
||||
"LabelBackupsMaxBackupSizeHelp": "Ako poistka proti nesprávnej konfigurácii zálohy zlyhajú, ak prekročia nastavenú veľkosť.",
|
||||
"LabelBackupsNumberToKeep": "Počet uložených záloh",
|
||||
"LabelBackupsNumberToKeepHelp": "Týmto spôsobom odstránite vždy iba jednu zálohu. V prípade, ak chcete odtrániť viacero záloh, mali by ste ich odstrániť manuálne.",
|
||||
"LabelBackupsNumberToKeepHelp": "Týmto spôsobom odstránite vždy iba jednu zálohu. V prípade, ak chcete odstrániť viacero záloh, mali by ste ich odstrániť manuálne.",
|
||||
"LabelBitrate": "Bitrate",
|
||||
"LabelBonus": "Bonus",
|
||||
"LabelBooks": "Knihy",
|
||||
@@ -282,8 +284,8 @@
|
||||
"LabelChapterTitle": "Názov kapitoly",
|
||||
"LabelChapters": "Kapitoly",
|
||||
"LabelChaptersFound": "nájdených kapitol",
|
||||
"LabelClickForMoreInfo": "Klikni pre viac informácií",
|
||||
"LabelClickToUseCurrentValue": "Klikni pre použitie aktuálnej hodnoty",
|
||||
"LabelClickForMoreInfo": "Kliknite pre viac informácií",
|
||||
"LabelClickToUseCurrentValue": "Kliknite pre použitie aktuálnej hodnoty",
|
||||
"LabelClosePlayer": "Zavrieť prehrávač",
|
||||
"LabelCodec": "Kodek",
|
||||
"LabelCollapseSeries": "Zbaliť série",
|
||||
@@ -306,7 +308,7 @@
|
||||
"LabelCustomCronExpression": "Vlastný Cron príkaz:",
|
||||
"LabelDatetime": "Dátum a čas",
|
||||
"LabelDays": "Dni",
|
||||
"LabelDeleteFromFileSystemCheckbox": "Zmazať zo systému (odškrtni len pre odstránenie z databázy)",
|
||||
"LabelDeleteFromFileSystemCheckbox": "Zmazať zo súborového systému (odškrtnite pre odstránenie len z databázy)",
|
||||
"LabelDescription": "Popis",
|
||||
"LabelDeselectAll": "Odznačiť všetko",
|
||||
"LabelDetectedPattern": "Identifikovaný vzor:",
|
||||
@@ -324,16 +326,16 @@
|
||||
"LabelDurationComparisonExactMatch": "(presná zhoda)",
|
||||
"LabelDurationComparisonLonger": "({0} dlhšie)",
|
||||
"LabelDurationComparisonShorter": "({0} kratšie)",
|
||||
"LabelDurationFound": "Nájdená dlžka:",
|
||||
"LabelDurationFound": "Nájdená dĺžka:",
|
||||
"LabelEbook": "E-kniha",
|
||||
"LabelEbooks": "E-knihy",
|
||||
"LabelEdit": "Upraviť",
|
||||
"LabelEmail": "E-mail",
|
||||
"LabelEmailSettingsFromAddress": "Z e-mailu",
|
||||
"LabelEmailSettingsRejectUnauthorized": "Odmietnuť neautorizované certifikáty",
|
||||
"LabelEmailSettingsRejectUnauthorizedHelp": "Vypnutie validácie SSL certifikátu môže tvoje pripojenie vystaviť bezpečnostným rizikám, ako napríklad MitM útokom. Vypni túto možnosť len v prípade, že rozumieš dôsledkom a dôveruješ e-mailovému serveru, ku ktorému sa pripájaš.",
|
||||
"LabelEmailSettingsRejectUnauthorizedHelp": "Vypnutie validácie SSL certifikátu môže vaše pripojenie vystaviť bezpečnostným rizikám, ako napríklad MitM útokom. Túto možnosť vypnite len v prípade, že rozumiete dôsledkom a dôverujete e-mailovému serveru, ku ktorému sa pripájate.",
|
||||
"LabelEmailSettingsSecure": "Bezpečné",
|
||||
"LabelEmailSettingsSecureHelp": "Pri povolení bude na pripojenie k serveru použité TLS. V opačnom prípade je TLS použité iba v prípade, ak server podporuje rozšírenie STARTTLS. Vo väčšine prípadov povoľte túto možnosť, ak sa pripájate cez port 465. V prípadoch, ak používate port 587 alebo 25, túto voľbu nepovoľujte. (prevzaté z nodemailer.com/smtp/#authentification)",
|
||||
"LabelEmailSettingsSecureHelp": "Pri povolení bude na pripojenie k serveru použité TLS. V opačnom prípade je TLS použité iba v prípade, ak server podporuje rozšírenie STARTTLS. Vo väčšine prípadov povoľte túto možnosť, ak sa pripájate cez port 465. V prípadoch, ak používate port 587 alebo 25, túto voľbu nepovoľujte. (prevzaté z nodemailer.com/smtp/#authentication)",
|
||||
"LabelEmailSettingsTestAddress": "Testovacia adresa",
|
||||
"LabelEmbeddedCover": "Vložený prebal",
|
||||
"LabelEnable": "Povoliť",
|
||||
@@ -346,7 +348,7 @@
|
||||
"LabelEncodingTimeWarning": "Prekódovanie môže trvať aj 30 minút.",
|
||||
"LabelEncodingWarningAdvancedSettings": "Pozor: Nemeňte uvedené nastavenia, pokiaľ nie ste dostatočne oboznámený s nastaveniami ffmpeg prekódovania.",
|
||||
"LabelEncodingWatcherDisabled": "V prípade, ak nemáte povolené automatické sledovanie zmien, bude na konci potrebné audioknihu opätovne preskenovať.",
|
||||
"LabelEnd": "Ukončiť",
|
||||
"LabelEnd": "Koniec",
|
||||
"LabelEndOfChapter": "Koniec kapitoly",
|
||||
"LabelEpisode": "Epizóda",
|
||||
"LabelEpisodeNotLinkedToRssFeed": "Epizóda bez RSS zdroja",
|
||||
@@ -365,7 +367,7 @@
|
||||
"LabelExpiresNever": "Nikdy",
|
||||
"LabelExplicit": "Explicitný obsah",
|
||||
"LabelExplicitChecked": "Explicitné (zaškrtnuté)",
|
||||
"LabelExplicitUnchecked": "Ne-explicitné (nezaškrtnuté)",
|
||||
"LabelExplicitUnchecked": "Neexplicitné (nezaškrtnuté)",
|
||||
"LabelExportOPML": "Exportovať OPML",
|
||||
"LabelFeedURL": "URL zdroja",
|
||||
"LabelFetchingMetadata": "Sťahovanie metadát",
|
||||
@@ -383,7 +385,7 @@
|
||||
"LabelFolders": "Priečinky",
|
||||
"LabelFontBold": "Tučné",
|
||||
"LabelFontBoldness": "Hrúbka písma",
|
||||
"LabelFontFamily": "písmo",
|
||||
"LabelFontFamily": "Písmo",
|
||||
"LabelFontItalic": "Kurzíva",
|
||||
"LabelFontScale": "Veľkosť písma",
|
||||
"LabelFontStrikethrough": "Preškrtnuté",
|
||||
@@ -394,7 +396,7 @@
|
||||
"LabelHardDeleteFile": "Nezvratné zmazanie súborov",
|
||||
"LabelHasEbook": "Má e-knihu",
|
||||
"LabelHasSupplementaryEbook": "Má doplnkovú e-knihu",
|
||||
"LabelHideSubtitles": "Skryť titulky",
|
||||
"LabelHideSubtitles": "Skryť podnázvy",
|
||||
"LabelHighestPriority": "Najvyššia priorita",
|
||||
"LabelHost": "Host",
|
||||
"LabelHour": "Hodina",
|
||||
@@ -414,17 +416,18 @@
|
||||
"LabelIntervalEveryDay": "Denne",
|
||||
"LabelIntervalEveryHour": "Každú hodinu",
|
||||
"LabelIntervalEveryMinute": "Každú minútu",
|
||||
"LabelInvert": "Invertne",
|
||||
"LabelInvert": "Invertovať",
|
||||
"LabelIpAddress": "IP adresa",
|
||||
"LabelItem": "Položka",
|
||||
"LabelJumpBackwardAmount": "Posunúť vpred o",
|
||||
"LabelJumpForwardAmount": "Posunúť dozadu o",
|
||||
"LabelJumpBackwardAmount": "Posunúť dozadu o",
|
||||
"LabelJumpForwardAmount": "Posunúť vpred o",
|
||||
"LabelLanguage": "Jazyk",
|
||||
"LabelLanguageDefaultServer": "Prednastavený jazyk servera",
|
||||
"LabelLanguages": "Jazyky",
|
||||
"LabelLastBookAdded": "Posledná pridaná kniha",
|
||||
"LabelLastBookUpdated": "Posledná aktualizovaná kniha",
|
||||
"LabelLastProgressDate": "Posledný pokrok: {0}",
|
||||
"LabelLastSeen": "Posledne videné",
|
||||
"LabelLastSeen": "Naposledy videné",
|
||||
"LabelLastTime": "Posledný čas",
|
||||
"LabelLastUpdate": "Posledná aktualizácia",
|
||||
"LabelLayout": "Rozloženie",
|
||||
@@ -448,8 +451,8 @@
|
||||
"LabelLookForNewEpisodesAfterDate": "Hľadať nové epizódy od uvedeného dátumu",
|
||||
"LabelLowestPriority": "Najnižšia priorita",
|
||||
"LabelMatchConfidence": "Istota",
|
||||
"LabelMatchExistingUsersBy": "Vyhľadaj vytvorených užívateľov podľa",
|
||||
"LabelMatchExistingUsersByDescription": "Používané na pripájanie vytvorených užívateľov. Po pripojení budú užívatelia vyhľadaní na základe jedinečného id poskytnutého Vaším poskytovateľom SSO",
|
||||
"LabelMatchExistingUsersBy": "Vyhľadať vytvorených používateľov podľa",
|
||||
"LabelMatchExistingUsersByDescription": "Používané na pripájanie vytvorených užívateľov. Po pripojení budú používatelia vyhľadaní na základe jedinečného id poskytnutého Vaším poskytovateľom SSO",
|
||||
"LabelMaxEpisodesToDownload": "Stiahnuť maximálne # epizód. Pre neobmedzené sťahovanie zadajte 0.",
|
||||
"LabelMaxEpisodesToDownloadPerCheck": "Pri kontrole stiahnuť maximálne # epizód",
|
||||
"LabelMaxEpisodesToKeep": "Uchovávať maximálne # epizód",
|
||||
@@ -488,19 +491,19 @@
|
||||
"LabelNotificationAppriseURL": "URL odkaz(-y) Apprise",
|
||||
"LabelNotificationAvailableVariables": "Dostupné premenné",
|
||||
"LabelNotificationBodyTemplate": "Šablóna obsahu",
|
||||
"LabelNotificationEvent": "Udalosť oznámení",
|
||||
"LabelNotificationEvent": "Udalosť notifikácie",
|
||||
"LabelNotificationTitleTemplate": "Šablóna názvu",
|
||||
"LabelNotificationsMaxFailedAttempts": "Maximálny počet neúspešných pokusov",
|
||||
"LabelNotificationsMaxFailedAttemptsHelp": "Notifikácie sa automaticky vypnú, ak ich odoslanie zlyhá nasledovný počet krát",
|
||||
"LabelNotificationsMaxQueueSize": "Maximálna dĺžka fronty oznámení",
|
||||
"LabelNotificationsMaxQueueSizeHelp": "Odosielanie udalostí je ohraničené na jedno oznámenie za sekundu. Novovzniknuté udalosti budú ignorované, ak bude fronta oznámení naplnená. Toto nastavenie zabraňuje nevyžiadanému zahlteniu oznámeniami.",
|
||||
"LabelNotificationsMaxQueueSize": "Maximálna dĺžka fronty notifikácií",
|
||||
"LabelNotificationsMaxQueueSizeHelp": "Odosielanie udalostí je ohraničené na jednu notifikáciu za sekundu. Novovzniknuté udalosti budú ignorované, ak bude fronta notifikácií naplnená. Toto nastavenie zabraňuje nevyžiadanému zahlteniu notifikáciami.",
|
||||
"LabelNumberOfBooks": "Počet kníh",
|
||||
"LabelNumberOfChapters": "Počet kapitol:",
|
||||
"LabelNumberOfEpisodes": "# z epizód",
|
||||
"LabelOpenIDAdvancedPermsClaimDescription": "Názov OpenID predpokladá prítomnosť pokročilých povolení pre užívateľské akcie v rámci aplikácie, ktoré sú aplikovateľné na ne-administrátorské role (<b>ak sú nakonfigurované</b>). Ak potvrdenie takýchto pokročilých povolení nie je v odozve prítomné, prístup do ABS bude automaticky zamietnutý. Ak v odozve chýba len niektoré z očakávaných nastavení, tak bude jeho hodnota automaticky nastavená na <code>false</code>. Uistite sa prosím, že forma odozvy poskytovateľa identity má nasledovnú štruktúru:",
|
||||
"LabelNumberOfEpisodes": "Počet epizód",
|
||||
"LabelOpenIDAdvancedPermsClaimDescription": "Názov OpenID claimu, ktorý obsahuje rozšírené oprávnenia pre akcie používateľov v rámci aplikácie a ktorý sa uplatní na roly iné ako administrátorské (<b>ak je nakonfigurovaný</b>). Ak claim v odpovedi chýba, prístup do ABS bude zamietnutý. Ak chýba jedna z možností, bude sa považovať za <code>false</code>. Uistite sa, že claim od poskytovateľa identity zodpovedá očakávanej štruktúre:",
|
||||
"LabelOpenIDClaims": "Ak ponecháte nasledujúce nastavenia prázdne, pokročilé nastavenia skupín a povolení nebudú aktivované a automaticky bude nastavená skupina 'Užívateľ'.",
|
||||
"LabelOpenIDGroupClaimDescription": "Pri názve požiadavky OpenID sa predpokladá, že obsahuje zoznam užívateľských skupín. Bežne označovaný ako <code>groups</code>. <b>Ak je správne nakonfigurovaný</b>, aplikácia automaticky pridelí role podľa príslušnosti k užívateľským skupinám pod podmienkou, že sú tieto skupiny v požiadavke nazvané (bez ohľadu na veľkosť písmen) ako 'admin', 'user' alebo 'guest'. Požiadavka musí obsahovať zoznam skupín a ak užívateľ patrí do viacerých skupín, aplikácia mu priradí rolu, ktorá zodpovedá skupine s najvyššími prístupovými právami. Ak sa žiadna z poskytnutých skupín nezhoduje, prístup bude zamietnutý.",
|
||||
"LabelOpenRSSFeed": "Otvor RSS zdroj",
|
||||
"LabelOpenIDGroupClaimDescription": "Názov OpenID claimu, ktorý obsahuje zoznam skupín používateľa. Bežne sa označuje ako <code>groups</code>. <b>Ak je nakonfigurovaný</b>, aplikácia automaticky pridelí roly podľa členstva používateľa v skupinách, pokiaľ sú tieto skupiny v claime pomenované (bez rozlišovania veľkosti písmen) 'admin', 'user' alebo 'guest'. Claim má obsahovať zoznam a ak používateľ patrí do viacerých skupín, aplikácia mu priradí rolu zodpovedajúcu najvyššej úrovni prístupu. Ak sa nezhoduje žiadna skupina, prístup bude zamietnutý.",
|
||||
"LabelOpenRSSFeed": "Otvoriť RSS zdroj",
|
||||
"LabelOverwrite": "Prepísať",
|
||||
"LabelPaginationPageXOfY": "Stránka {0} z {1}",
|
||||
"LabelPassword": "Heslo",
|
||||
@@ -517,17 +520,17 @@
|
||||
"LabelPersonalYearReview": "Váš rok v prehľade ({0})",
|
||||
"LabelPhotoPathURL": "Cesta/URL fotky",
|
||||
"LabelPlayMethod": "Metóda prehrávania",
|
||||
"LabelPlaybackRateIncrementDecrement": "Veľkosť kroku zrýchlenia/spomalenia rýchlosti prehávania",
|
||||
"LabelPlaybackRateIncrementDecrement": "Veľkosť kroku zrýchlenia/spomalenia rýchlosti prehrávania",
|
||||
"LabelPlayerChapterNumberMarker": "{0} z {1}",
|
||||
"LabelPlaylists": "Playlisty",
|
||||
"LabelPodcast": "Podcast",
|
||||
"LabelPodcastSearchRegion": "Región vyhľadávania podcastu",
|
||||
"LabelPodcastType": "Typ podcastu",
|
||||
"LabelPodcasts": "Podcasty",
|
||||
"LabelPort": "Prístav",
|
||||
"LabelPort": "Port",
|
||||
"LabelPrefixesToIgnore": "Ignorované predpony (bez ohľadu na veľkosť písmen)",
|
||||
"LabelPreventIndexing": "Zabráni indexácii vašich zdrojov službami iTunes a Google podcast directories",
|
||||
"LabelPrimaryEbook": "Primárny e-book",
|
||||
"LabelPrimaryEbook": "Primárna e-kniha",
|
||||
"LabelProgress": "Aktuálny stav",
|
||||
"LabelProvider": "Poskytovateľ",
|
||||
"LabelProviderAuthorizationValue": "Obsah hlavičky autorizácie",
|
||||
@@ -546,7 +549,7 @@
|
||||
"LabelRSSFeedURL": "URL RSS zdroja",
|
||||
"LabelRandomly": "Náhodne",
|
||||
"LabelReAddSeriesToContinueListening": "Znova pridať série do pokračujúceho počúvania",
|
||||
"LabelRead": "Načítať",
|
||||
"LabelRead": "Čítať",
|
||||
"LabelReadAgain": "Čítať znova",
|
||||
"LabelReadEbookWithoutProgress": "Čítať e-knihu bez zmeny stavu",
|
||||
"LabelRecentSeries": "Posledné série",
|
||||
@@ -562,9 +565,9 @@
|
||||
"LabelRemoveMetadataFile": "Odstrániť súbory metadát z priečinkov položiek v knižnici",
|
||||
"LabelRemoveMetadataFileHelp": "Odstrániť všetky súbory metadata.json a metadata.abs vo Vašich {0} priečinkoch.",
|
||||
"LabelRowsPerPage": "Počet riadkov na stránku",
|
||||
"LabelSearchTerm": "Hľadaj výraz",
|
||||
"LabelSearchTitle": "Hľadaj názov",
|
||||
"LabelSearchTitleOrASIN": "Hľadaj názov alebo ASIN",
|
||||
"LabelSearchTerm": "Hľadať výraz",
|
||||
"LabelSearchTitle": "Hľadať názov",
|
||||
"LabelSearchTitleOrASIN": "Hľadať názov alebo ASIN",
|
||||
"LabelSeason": "Sezóna",
|
||||
"LabelSeasonNumber": "Sezóna #{0}",
|
||||
"LabelSelectAll": "Vybrať všetko",
|
||||
@@ -595,7 +598,7 @@
|
||||
"LabelSettingsEpubsAllowScriptedContentHelp": "Povoliť e-knihám spúšťanie skriptov. Odporúča sa túto voľbu nepovolovať, pokiaľ plne nedôverujete zdrojom súborov e-kníh.",
|
||||
"LabelSettingsExperimentalFeatures": "Experimentálne funkcie",
|
||||
"LabelSettingsExperimentalFeaturesHelp": "Funkcie vo vývoji, ktoré ocenia Vašu spätnú väzbu a pomoc s testovaním. Kliknite pre otvorenie diskusie na GitHub-e.",
|
||||
"LabelSettingsFindCovers": "Nájdi prebaly",
|
||||
"LabelSettingsFindCovers": "Hľadať prebaly",
|
||||
"LabelSettingsFindCoversHelp": "Ak Vaša audiokniha neobsahuje vložený prebal alebo jeho obrázok v priečinku audioknihy, skener sa ho pokúsi automaticky vyhľadať.<br>Poznámka: Táto voľba predĺži čas skenovania",
|
||||
"LabelSettingsHideSingleBookSeries": "Skryť série obsahujúce len jednu knihu",
|
||||
"LabelSettingsHideSingleBookSeriesHelp": "Série obsahujúce len jednu knihu budú skryté na stránke sérií a na poličkách domácej stránky.",
|
||||
@@ -606,17 +609,17 @@
|
||||
"LabelSettingsLibraryMarkAsFinishedWhen": "Označiť položku média ako dokončenú",
|
||||
"LabelSettingsOnlyShowLaterBooksInContinueSeries": "Preskočiť predchádzajúce knihy v pokračujúcej sérii",
|
||||
"LabelSettingsOnlyShowLaterBooksInContinueSeriesHelp": "Polička pokračujúcich sérií na domácej stránke zobrazuje prvú nezačatú knihu série, ktorá má dokončenú aspoň jednu z kníh série a žiadne započaté knihy. Povolením tohto nastavenia bude pokračujúca séria začínať poslednou ukončenou knihou miesto prvej nepočúvanej.",
|
||||
"LabelSettingsParseSubtitles": "Parsovať podtituly",
|
||||
"LabelSettingsParseSubtitlesHelp": "Extrahovať podtituly z názvov priečinkov audiokníh.<br>Podtitul musí byť oddelený \" - \"<br>tj. \"Názov knihy - Podtitul knihy\" má podtitul \"Podtitul knihy\"",
|
||||
"LabelSettingsParseSubtitles": "Rozpoznávať podnázvy",
|
||||
"LabelSettingsParseSubtitlesHelp": "Extrahovať podnázvy z názvov priečinkov audiokníh.<br>Podnázov musí byť oddelený \" - \"<br>t. j. \"Názov knihy - Podnázov knihy\" má podnázov \"Podnázov knihy\"",
|
||||
"LabelSettingsPreferMatchedMetadata": "Preferovať vyhľadané metadáta",
|
||||
"LabelSettingsPreferMatchedMetadataHelp": "Pri použití funkcie Rýchle vyhľadávanie, vyhľadané údaje prepíšu príslušné údaje položky. Defaultne funkcia Rýchle vyhľadávanie vyplní iba chýbajúce údaje.",
|
||||
"LabelSettingsSkipMatchingBooksWithASIN": "Preskočiť vyhľadané knihy, ktoré už majú vyplnené ASIN",
|
||||
"LabelSettingsSkipMatchingBooksWithISBN": "Preskočiť vyhľadané knihy, ktoré už majú vyplnené ISBN",
|
||||
"LabelSettingsSortingIgnorePrefixes": "Pri triedení ignorovať prefixy",
|
||||
"LabelSettingsSortingIgnorePrefixesHelp": "tj. v prípade prefixu \"the\" bude názov knihy \"The Book Title\" usporiadaný podľa \"Book Title, The\"",
|
||||
"LabelSettingsSortingIgnorePrefixes": "Pri triedení ignorovať predpony",
|
||||
"LabelSettingsSortingIgnorePrefixesHelp": "t. j. v prípade predpony \"the\" bude názov knihy \"The Book Title\" usporiadaný podľa \"Book Title, The\"",
|
||||
"LabelSettingsSquareBookCovers": "Použiť štvorcové prebaly kníh",
|
||||
"LabelSettingsSquareBookCoversHelp": "Preferovať štvorcové prebaly pred štandardnými prebalmi kníh formátu 1.6:1",
|
||||
"LabelSettingsStoreCoversWithItem": "Okladať prebaly k položkám",
|
||||
"LabelSettingsStoreCoversWithItem": "Ukladať prebaly k položkám",
|
||||
"LabelSettingsStoreCoversWithItemHelp": "Defaultne sú prebaly uložené v priečinku /metadata/items, povolením tejto voľby budú prebaly umiestnené do priečinkov jednotlivých položiek Vašej knižnice, pričom bude vždy použitý len jeden súbor s názvom \"cover\"",
|
||||
"LabelSettingsStoreMetadataWithItem": "Uložiť metadáta spolu s položkou",
|
||||
"LabelSettingsStoreMetadataWithItemHelp": "Defaultne sú súbory metadát ukladané do priečinka /metadata/items, pri povolení tejto voľby budú súbory metadát uložené do priečinkov položiek Vašej knižnice",
|
||||
@@ -674,14 +677,14 @@
|
||||
"LabelTimeDurationXMinutes": "{0} minút",
|
||||
"LabelTimeDurationXSeconds": "{0} sekúnd",
|
||||
"LabelTimeInMinutes": "Čas v minútach",
|
||||
"LabelTimeLeft": "{0} ponechaných",
|
||||
"LabelTimeLeft": "Zostáva {0}",
|
||||
"LabelTimeListened": "Čas počúvania",
|
||||
"LabelTimeListenedToday": "Dnešný čas počúvania",
|
||||
"LabelTimeRemaining": "Zostáva {0}",
|
||||
"LabelTimeToShift": "Čas posunutia v sekundách",
|
||||
"LabelTitle": "Názov",
|
||||
"LabelToolsEmbedMetadata": "Vlož metadáta",
|
||||
"LabelToolsEmbedMetadataDescription": "Vloždo zvukových súborov metadáta obsahujúce obrázok prebalu a kapitoly.",
|
||||
"LabelToolsEmbedMetadata": "Vložiť metadáta",
|
||||
"LabelToolsEmbedMetadataDescription": "Vložiť do zvukových súborov metadáta obsahujúce obrázok prebalu a kapitoly.",
|
||||
"LabelToolsM4bEncoder": "M4B Encoder",
|
||||
"LabelToolsMakeM4b": "Vytvoriť M4B súbor audioknihy",
|
||||
"LabelToolsMakeM4bDescription": "Generovať .M4B súbor audioknihy obsahujúci vložené metadáta, obrázok prebalu a kapitoly.",
|
||||
@@ -690,7 +693,7 @@
|
||||
"LabelTotalDuration": "Celkové trvanie",
|
||||
"LabelTotalTimeListened": "Celkový čas počúvania",
|
||||
"LabelTrackFromFilename": "Stopa podľa názvu súboru",
|
||||
"LabelTrackFromMetadata": "Stopa podľ metadát",
|
||||
"LabelTrackFromMetadata": "Stopa podľa metadát",
|
||||
"LabelTracks": "Stopy",
|
||||
"LabelTracksMultiTrack": "Viacstopová",
|
||||
"LabelTracksNone": "Žiadne stopy",
|
||||
@@ -706,14 +709,14 @@
|
||||
"LabelUpdateDetails": "Aktualizovať detaily",
|
||||
"LabelUpdateDetailsHelp": "Povoliť nahradenie existujúcich detailov pre vybrané knihy, ak bolo vyhľadanie úspešné",
|
||||
"LabelUpdatedAt": "Aktualizované",
|
||||
"LabelUploaderDragAndDrop": "Potiahni a vlož súbory alebo priečinky",
|
||||
"LabelUploaderDragAndDropFilesOnly": "Potiahni a vlož súbory",
|
||||
"LabelUploaderDropFiles": "Vlož súbory",
|
||||
"LabelUploaderDragAndDrop": "Potiahnite a pustite súbory alebo priečinky",
|
||||
"LabelUploaderDragAndDropFilesOnly": "Potiahnite a pustite súbory",
|
||||
"LabelUploaderDropFiles": "Pustite súbory",
|
||||
"LabelUploaderItemFetchMetadataHelp": "Automaticky vyhľadá názov, autora a sériu",
|
||||
"LabelUseAdvancedOptions": "Použiť pokročilé nastavenia",
|
||||
"LabelUseChapterTrack": "Použiť stopu kapitoly",
|
||||
"LabelUseFullTrack": "Použiť celú stopu",
|
||||
"LabelUseZeroForUnlimited": "Použito 0 pre neobmedzené",
|
||||
"LabelUseZeroForUnlimited": "Použite 0 pre neobmedzené",
|
||||
"LabelUser": "Používateľ",
|
||||
"LabelUsername": "Prihlasovacie meno",
|
||||
"LabelValue": "Hodnota",
|
||||
@@ -721,7 +724,7 @@
|
||||
"LabelViewBookmarks": "Zobraziť záložky",
|
||||
"LabelViewChapters": "Zobraziť kapitoly",
|
||||
"LabelViewPlayerSettings": "Zobraziť nastavenie prehrávania",
|
||||
"LabelViewQueue": "Zobraziť zoznam na prehratie",
|
||||
"LabelViewQueue": "Zobraziť frontu prehrávania",
|
||||
"LabelVolume": "Hlasitosť",
|
||||
"LabelWebRedirectURLsDescription": "Autorizovať nasledovné URL linky pomocou Vášho OAuth poskytovateľa a povoliť presmerovanie späť na webovú aplikáciu po prihlásení:",
|
||||
"LabelWebRedirectURLsSubfolder": "Podpriečinok pre presmerované URL",
|
||||
@@ -734,15 +737,15 @@
|
||||
"LabelYourBookmarks": "Vaše záložky",
|
||||
"LabelYourPlaylists": "Vaše playlisty",
|
||||
"LabelYourProgress": "Váš aktuálny stav",
|
||||
"MessageAddToPlayerQueue": "Pridať do zoznamu prehrávania",
|
||||
"MessageAppriseDescription": "Aby ste mohli používať túto funkciumusíte mať k dispozícii inštanciu <a href=\"https://github.com/caronc/apprise-api\" target=\"_blank\">Apprise API</a> alebo inú, ktorá dokáže spracovávať rovnaké požiadavky/requesty.<br/>Apprise URL musí byť úplná URL určená na zasielanie notifikácií, tj. ak napr. vaša APi beží na <code>http://192.168.1.1:8337</code>, vložte do daného poľa <code>http://192.168.1.1:8337/notify</code>.",
|
||||
"MessageAddToPlayerQueue": "Pridať do fronty prehrávania",
|
||||
"MessageAppriseDescription": "Aby ste mohli používať túto funkciu musíte mať k dispozícii inštanciu <a href=\"https://github.com/caronc/apprise-api\" target=\"_blank\">Apprise API</a> alebo inú, ktorá dokáže spracovávať rovnaké požiadavky/requesty.<br/>Apprise URL musí byť úplná URL určená na zasielanie notifikácií, t. j. ak napr. vaša API beží na <code>http://192.168.1.1:8337</code>, vložte do daného poľa <code>http://192.168.1.1:8337/notify</code>.",
|
||||
"MessageAsinCheck": "Uistite sa, že používate ASIN zo správneho regiónu Audible, nie Amazonu.",
|
||||
"MessageAuthenticationLegacyTokenWarning": "Zastaralé API toleny budú v budúcnosti odstránené. Použite miesto nich <a href=\"/config/api-keys\">API kľúče</a>.",
|
||||
"MessageAuthenticationLegacyTokenWarning": "Zastaralé API tokeny budú v budúcnosti odstránené. Použite namiesto nich <a href=\"/config/api-keys\">API kľúče</a>.",
|
||||
"MessageAuthenticationOIDCChangesRestart": "Reštartujte svoj server po uložení, aby mohli byť použité zmeny OIDC.",
|
||||
"MessageAuthenticationSecurityMessage": "Overovanie bolo kvôli bezpečnosti vylepšené. Všetci používatelia sa musia znova prihlásiť.",
|
||||
"MessageBackupsDescription": "Zálohy pokrývajú používateľov, ich aktuálne stavy počúvania, detaily položiek knižnice, nastavenia servera a obrázky uložené v <code>/metadata/items</code> a <code>/metadata/authors</code>. Zálohy <strong>neobsahujú</strong> súbory v priečinkoch vašich knižníc.",
|
||||
"MessageBackupsLocationEditNote": "Poznámka: Zmena umiestnenia záloh nepresunie ani nezmení existujúce zálohy",
|
||||
"MessageBackupsLocationNoEditNote": "Poznámka: Umietnenie záloh je nastavené prostredníctvom premennej prostredia a nie je ho možné zmeniť z tohto miesta.",
|
||||
"MessageBackupsLocationNoEditNote": "Poznámka: Umiestnenie záloh je nastavené prostredníctvom premennej prostredia a nie je ho možné zmeniť z tohto miesta.",
|
||||
"MessageBackupsLocationPathEmpty": "Cesta umiestnenia záloh nemôže byť prázdna",
|
||||
"MessageBatchEditPopulateMapDetailsAllHelp": "Vyplniť povolené polia dátami zo všetkých položiek. Viacpočetné hodnoty v poliach budú zlúčené",
|
||||
"MessageBatchEditPopulateMapDetailsItemHelp": "Vyplniť polia povolených detailov z údajov tejto položky",
|
||||
@@ -774,8 +777,9 @@
|
||||
"MessageConfirmDeleteSession": "Ste si istý, že chcete zmazať túto reláciu?",
|
||||
"MessageConfirmEmbedMetadataInAudioFiles": "Ste si istý, že chcete vložiť metadáta do {0} zvukových súborov?",
|
||||
"MessageConfirmForceReScan": "Ste si istý, že chcete spustiť vynútený re-sken?",
|
||||
"MessageConfirmLogoutDevice": "Ste si istý, že sa chcete odhlásiť zo zariadenia \"{0}\"?",
|
||||
"MessageConfirmMarkAllEpisodesFinished": "Chcete označiť všetky epizódy ako dokončené?",
|
||||
"MessageConfirmMarkAllEpisodesNotFinished": "Checte označiť všetky epizódy ako nedokončené?",
|
||||
"MessageConfirmMarkAllEpisodesNotFinished": "Chcete označiť všetky epizódy ako nedokončené?",
|
||||
"MessageConfirmMarkItemFinished": "Chcete označiť \"{0}\" ako dokončené?",
|
||||
"MessageConfirmMarkItemNotFinished": "Chcete označiť \"{0}\" ako nedokončené?",
|
||||
"MessageConfirmMarkSeriesFinished": "Ste si istý, že chcete označiť všetky knihy v tejto sérii ako dokončené?",
|
||||
@@ -796,7 +800,7 @@
|
||||
"MessageConfirmRemoveMetadataFiles": "Ste si istý, že chcete odstrániť všetky súbory metadata.{0} z priečinkov položiek vašej knižnice?",
|
||||
"MessageConfirmRemoveNarrator": "Ste si istý, že chcete odstrániť interpreta \"{0}\"?",
|
||||
"MessageConfirmRemovePlaylist": "Ste si istý, že chcete odstrániť váš playlist \"{0}\"?",
|
||||
"MessageConfirmRenameGenre": "Ste si istý, že chcete nahradiť žáner \"{0}\" vo všetkých položkách žánrom \"{0}\"?",
|
||||
"MessageConfirmRenameGenre": "Ste si istý, že chcete nahradiť žáner \"{0}\" žánrom \"{1}\" vo všetkých položkách?",
|
||||
"MessageConfirmRenameGenreMergeNote": "Poznámka: Tento žáner už existuje a preto bude zlúčený.",
|
||||
"MessageConfirmRenameGenreWarning": "Varovanie! Podobný žáner len s odlišným zápisom už existuje \"{0}\".",
|
||||
"MessageConfirmRenameTag": "Ste si istý, že chcete zmeniť štítok \"{0}\" za \"{1}\" vo všetkých položkách?",
|
||||
@@ -805,18 +809,18 @@
|
||||
"MessageConfirmResetProgress": "Ste si istý, že chcete resetnúť váš aktuálny stav počúvania?",
|
||||
"MessageConfirmSendEbookToDevice": "Ste si istý, že chcete poslať {0} e-knihu \"{1}\" do zariadenia \"{2}\"?",
|
||||
"MessageConfirmUnlinkOpenId": "Ste si istý, že chcete odstrániť prepojenie tohto používateľa na OpenID?",
|
||||
"MessageDaysListenedInTheLastYear": "{0} dní počúvania počas posledného roku",
|
||||
"MessageDaysListenedInTheLastYear": "{0} dní počúvania počas posledného roka",
|
||||
"MessageDownloadingEpisode": "Sťahovanie epizódy",
|
||||
"MessageDragFilesIntoTrackOrder": "Presuňte súbory do správneho poradia prehrávania",
|
||||
"MessageEmbedFailed": "Vloženie zlyhalo!",
|
||||
"MessageEmbedFinished": "Vloženie skončené!",
|
||||
"MessageEmbedQueue": "Zaradené do fronty na vloženie metadát ({0} v zozname)",
|
||||
"MessageEpisodesQueuedForDownload": "{0} epizód(a) v zozname na sťahovanie",
|
||||
"MessageEmbedQueue": "Zaradené do fronty na vloženie metadát ({0} vo fronte)",
|
||||
"MessageEpisodesQueuedForDownload": "{0} epizód(a) vo fronte na sťahovanie",
|
||||
"MessageEreaderDevices": "Na zaistenie dodania e-kníh môže byť nutné zadanie vyššie uvedenej e-mailovej adresy ako overeného odosielateľa v každom z nižšie vypísaných zariadení.",
|
||||
"MessageFeedURLWillBe": "URL zdroja bude {0}",
|
||||
"MessageFetching": "Získavam...",
|
||||
"MessageForceReScanDescription": "preskenuje všetky súbory ako pri prvom skenovaní. ID3 štítky zvukových súborov, OPF súbory a textové súbory budú nanovo naskenované.",
|
||||
"MessageHeatmapListeningTimeTooltip": "<strong>{0} počúvajúcich</strong> na {1}",
|
||||
"MessageHeatmapListeningTimeTooltip": "<strong>{0} počúvania</strong> dňa {1}",
|
||||
"MessageHeatmapNoListeningSessions": "Žiadne relácie počúvania na {0}",
|
||||
"MessageImportantNotice": "Dôležité upozornenie!",
|
||||
"MessageInsertChapterBelow": "Vložte kapitolu nižšie",
|
||||
@@ -845,9 +849,9 @@
|
||||
"MessageNoDescription": "Žiadny popis",
|
||||
"MessageNoDevices": "Žiadne zariadenia",
|
||||
"MessageNoDownloadsInProgress": "Aktuálne neprebieha žiadne sťahovanie",
|
||||
"MessageNoDownloadsQueued": "Žiadne sťahovania v poradí",
|
||||
"MessageNoDownloadsQueued": "Žiadne sťahovania vo fronte",
|
||||
"MessageNoEpisodeMatchesFound": "Neboli spárované žiadne epizódy",
|
||||
"MessageNoEpisodes": "Žiadne eizódy",
|
||||
"MessageNoEpisodes": "Žiadne epizódy",
|
||||
"MessageNoFoldersAvailable": "Žiadne priečinky nie sú dostupné",
|
||||
"MessageNoGenres": "Žiadne žánre",
|
||||
"MessageNoIssues": "Žiadne problémy",
|
||||
@@ -856,7 +860,7 @@
|
||||
"MessageNoListeningSessions": "Žiadne relácie",
|
||||
"MessageNoLogs": "Žiadne záznamy udalostí",
|
||||
"MessageNoMediaProgress": "Žiadny stav médií",
|
||||
"MessageNoNotifications": "Žiadne upozornenia",
|
||||
"MessageNoNotifications": "Žiadne notifikácie",
|
||||
"MessageNoPodcastFeed": "Chybný podcast: Žiadny zdroj",
|
||||
"MessageNoPodcastsFound": "Žiadne podcasty neboli nájdené",
|
||||
"MessageNoResults": "Žiadne výsledky",
|
||||
@@ -877,19 +881,19 @@
|
||||
"MessagePodcastHasNoRSSFeedForMatching": "Podcast nemá žiadnu URL RSS zdroja na spárovanie",
|
||||
"MessagePodcastSearchField": "Zadajte hľadaný výraz alebo URL RSS zdroja",
|
||||
"MessageQuickEmbedInProgress": "Prebieha rýchle vkladanie",
|
||||
"MessageQuickEmbedQueue": "Zadané na rýchle vloženie ({0} v rade)",
|
||||
"MessageQuickEmbedQueue": "Zaradené do fronty na rýchle vloženie ({0} vo fronte)",
|
||||
"MessageQuickMatchAllEpisodes": "Rýchle vyhľadanie všetkých epizód",
|
||||
"MessageQuickMatchDescription": "Doplní všetky nevyplnené údaje a chýbajúci prebal z prvého výsledku vyhľdávania '{0}'. Neprepíše už existujúce údaje, vykoná tak iba v prípade, ak je zaškrtnutá voľba 'Preferovať vyhľadané metadáta'.",
|
||||
"MessageQuickMatchDescription": "Doplní všetky nevyplnené údaje a chýbajúci prebal z prvého výsledku vyhľadávania '{0}'. Neprepíše už existujúce údaje, vykoná tak iba v prípade, ak je zaškrtnutá voľba 'Preferovať vyhľadané metadáta'.",
|
||||
"MessageRemoveChapter": "Odstrániť kapitolu",
|
||||
"MessageRemoveEpisodes": "Odstrániť {0} epizódu(-y)",
|
||||
"MessageRemoveFromPlayerQueue": "Odstrániť zo zoznamu prehrávania",
|
||||
"MessageRemoveUserWarning": "Ste si istí, že chcete trvalo odstrániť užívateľa \"{0}\"?",
|
||||
"MessageRemoveFromPlayerQueue": "Odstrániť z fronty prehrávania",
|
||||
"MessageRemoveUserWarning": "Ste si istý, že chcete trvalo odstrániť užívateľa \"{0}\"?",
|
||||
"MessageReportBugsAndContribute": "Nahlásiť chyby, požiadavky na funkcie, a prispievať na",
|
||||
"MessageResetChaptersConfirm": "Ste si istý, že chcete resetnúť kapitoly a zahodiť zmeny, ktoré ste vykonali?",
|
||||
"MessageRestoreBackupConfirm": "Ste si istí, že chcete obnoviť zálohu vytvorenú",
|
||||
"MessageRestoreBackupWarning": "Obnovenie zálohy spôsobí kompletný prepis databázy umiestnenej v /config a obrázkov prebalov a autorov v /metadata/items a /metadata/authors.<br /><br />Zálohy nemenia žiadne súbory v priečinkoch vašej knižnice. Ak ste povolili v nastaveniach servera ukladanie obrázkov prebalov a metadát v priečinkoch knižnice, tieto nie sú zálohované a teda ani prepisované.<br /><br />Všetky klienti používajúci váš server budú automaticky obnovené.",
|
||||
"MessageRestoreBackupConfirm": "Ste si istý, že chcete obnoviť zálohu vytvorenú",
|
||||
"MessageRestoreBackupWarning": "Obnovenie zálohy spôsobí kompletný prepis databázy umiestnenej v /config a obrázkov prebalov a autorov v /metadata/items a /metadata/authors.<br /><br />Zálohy nemenia žiadne súbory v priečinkoch vašej knižnice. Ak ste povolili v nastaveniach servera ukladanie obrázkov prebalov a metadát v priečinkoch knižnice, tieto nie sú zálohované a teda ani prepisované.<br /><br />Všetci klienti používajúci váš server budú automaticky obnovené.",
|
||||
"MessageScheduleLibraryScanNote": "Pre väčšinu používateľov sa odporúča nechať túto funkciu vypnutú a ponechať zapnuté nastavenie „Automatické sledovanie zmien v knižnici“ – táto funkcia automaticky zistí zmeny vo vašich priečinkoch knižnice. Túto funkciu zapnite, ak „Automatické sledovanie zmien v knižnici“ nefunguje vo vašom súborovom systéme (napr. NFS).",
|
||||
"MessageScheduleRunEveryWeekdayAtTime": "Spustiť každú {0} o {1}",
|
||||
"MessageScheduleRunEveryWeekdayAtTime": "Spustiť každý týždeň: {0} o {1}",
|
||||
"MessageSearchResultsFor": "Výsledky vyhľadávania pre",
|
||||
"MessageSelected": "{0} vybrané",
|
||||
"MessageSeriesSequenceCannotContainSpaces": "Poradie série nemôže obsahovať medzery",
|
||||
@@ -897,25 +901,25 @@
|
||||
"MessageSetChaptersFromTracksDescription": "Nastaviť jednotlivé zvukové súbory ako kapitoly a názvy zvukových súborov ako názvy týchto kapitol",
|
||||
"MessageShareExpirationWillBe": "Expiruje <strong>{0}</strong>",
|
||||
"MessageShareExpiresIn": "Uplynie za {0}",
|
||||
"MessageShareURLWillBe": "URL na zdielanie bude <strong>{0}</strong>",
|
||||
"MessageShareURLWillBe": "URL na zdieľanie bude <strong>{0}</strong>",
|
||||
"MessageStartPlaybackAtTime": "Spustiť prehrávanie \"{0}\" o {1}?",
|
||||
"MessageTaskAudioFileNotWritable": "Do súboru \"{0}\" sa nedá zapisovať",
|
||||
"MessageTaskCanceledByUser": "Úloha zrušená používateľom",
|
||||
"MessageTaskDownloadingEpisodeDescription": "Sťahuje sa diel \"{0}\"",
|
||||
"MessageTaskDownloadingEpisodeDescription": "Sťahuje sa epizóda \"{0}\"",
|
||||
"MessageTaskEmbeddingMetadata": "Vkladanie metadát",
|
||||
"MessageTaskEmbeddingMetadataDescription": "Vkladanie metadát v audioknihe \"{0}\"",
|
||||
"MessageTaskEncodingM4b": "Kódovanie M4B",
|
||||
"MessageTaskEncodingM4bDescription": "Konverzia audioknihy \"{0}\" do jedného m4b súboru",
|
||||
"MessageTaskFailed": "Zlyhané",
|
||||
"MessageTaskFailedToBackupAudioFile": "Nepodarilo sa zazálohovať audio súbor \"{0}\"",
|
||||
"MessageTaskFailedToCreateCacheDirectory": "Nepodarilo sa vytvoriť adresár na cache",
|
||||
"MessageTaskFailedToCreateCacheDirectory": "Nepodarilo sa vytvoriť priečinok vyrovnávacej pamäte",
|
||||
"MessageTaskFailedToEmbedMetadataInFile": "Vloženie metadát do \"{0}\" zlyhalo",
|
||||
"MessageTaskFailedToMergeAudioFiles": "Nepodarilo sa pospájať audio súbory",
|
||||
"MessageTaskFailedToMoveM4bFile": "Nepodarilo sa presunúť m4b súbor",
|
||||
"MessageTaskFailedToWriteMetadataFile": "Nepodarilo sa zapísať súbor s metadátami",
|
||||
"MessageTaskMatchingBooksInLibrary": "Spárované knihy v knižnici \"{0}\"",
|
||||
"MessageTaskNoFilesToScan": "Žiadne súbory k skenu",
|
||||
"MessageTaskOpmlImport": "OMPL import",
|
||||
"MessageTaskOpmlImport": "OPML import",
|
||||
"MessageTaskOpmlImportDescription": "Vytvorenie podcastov z {0} RSS zdrojov",
|
||||
"MessageTaskOpmlImportFeed": "Importný zdroj OPML",
|
||||
"MessageTaskOpmlImportFeedDescription": "Import RSS zdroja \"{0}\"",
|
||||
@@ -937,7 +941,7 @@
|
||||
"MessageThinking": "Premýšľam...",
|
||||
"MessageUploaderItemFailed": "Nahratie zlyhalo",
|
||||
"MessageUploaderItemSuccess": "Úspešne nahrané!",
|
||||
"MessageUploading": "Nahrávanie zmien...",
|
||||
"MessageUploading": "Nahrávanie...",
|
||||
"MessageValidCronExpression": "Platný cron výraz",
|
||||
"MessageWatcherIsDisabledGlobally": "Funkcia sledovania zmien je globálne vypnutá v nastaveniach servera",
|
||||
"MessageXLibraryIsEmpty": "Knižnica {0} je prázdna!",
|
||||
@@ -947,7 +951,7 @@
|
||||
"NoteChapterEditorTimes": "Poznámka: Prvá kapitola musí vždy začínať v 0:00 a začiatok poslednej kapitoly nemôže prekročiť trvanie tejto audioknihy.",
|
||||
"NoteFolderPicker": "Poznámka: Priečinky, ktoré už boli priradené, sa ďalej nezobrazujú",
|
||||
"NoteRSSFeedPodcastAppsHttps": "Varovanie: Väčšina podcastových aplikácií požaduje URL RSS zdroja s HTTPS",
|
||||
"NoteRSSFeedPodcastAppsPubDate": "Varovanie: 1 alebo viac vašich epizód neobsahuje infomáciu o dátum vydania. Niektoré podcastové ju vyžadujú.",
|
||||
"NoteRSSFeedPodcastAppsPubDate": "Varovanie: 1 alebo viac vašich epizód neobsahuje informáciu o dátume vydania. Niektoré podcastové aplikácie ju vyžadujú.",
|
||||
"NoteUploaderFoldersWithMediaFiles": "Priečinky obsahujúce súbory médií budú považované za samostatné položky knižnice.",
|
||||
"NoteUploaderOnlyAudioFiles": "Ak budú nahraté iba zvukové súbory, každý zvukový súbor bude považovaný za samostatnú audioknihu.",
|
||||
"NoteUploaderUnsupportedFiles": "Nepodporované súbory budú ignorované. Pri výbere alebo prenesení priečinka, budú všetky súbory, ktoré nie sú v priečinku niektorej z položiek, ignorované.",
|
||||
@@ -963,13 +967,13 @@
|
||||
"PlaceholderNewPlaylist": "Názov nového playlistu",
|
||||
"PlaceholderSearch": "Vyhľadávanie..",
|
||||
"PlaceholderSearchEpisode": "Vyhľadať epizódu..",
|
||||
"StatsAuthorsAdded": "autorov pridaných",
|
||||
"StatsBooksAdded": "kníh pridaných",
|
||||
"StatsAuthorsAdded": "pridaných autorov",
|
||||
"StatsBooksAdded": "pridaných kníh",
|
||||
"StatsBooksAdditional": "Niektoré prílohy zahŕňajú…",
|
||||
"StatsBooksFinished": "dokončených kníh",
|
||||
"StatsBooksFinishedThisYear": "Niektoré knihy dokončené tento rok…",
|
||||
"StatsBooksListenedTo": "vypočutých kníh",
|
||||
"StatsCollectionGrewTo": "Vaša knižná zbierka sa blíži k…",
|
||||
"StatsCollectionGrewTo": "Vaša knižná zbierka narástla na…",
|
||||
"StatsSessions": "relácie",
|
||||
"StatsSpentListening": "strávených počúvaním",
|
||||
"StatsTopAuthor": "TOP AUTOR",
|
||||
@@ -1001,7 +1005,7 @@
|
||||
"ToastBackupRestoreFailed": "Obnovenie zo zálohy zlyhalo",
|
||||
"ToastBackupUploadFailed": "Nahratie zálohy zlyhalo",
|
||||
"ToastBackupUploadSuccess": "Záloha bola nahratá",
|
||||
"ToastBatchApplyDetailsToItemsSuccess": "Dotknuté údaje položiek",
|
||||
"ToastBatchApplyDetailsToItemsSuccess": "Údaje boli použité na vybrané položky",
|
||||
"ToastBatchDeleteFailed": "Hromadné odstránenie zlyhalo",
|
||||
"ToastBatchDeleteSuccess": "Hromadné odstránenie bolo úspešné",
|
||||
"ToastBatchQuickMatchFailed": "Hromadné rýchle vyhľadanie zlyhalo!",
|
||||
@@ -1037,12 +1041,12 @@
|
||||
"ToastDeviceTestEmailFailed": "Odoslanie testovacieho e-mailu zlyhalo",
|
||||
"ToastDeviceTestEmailSuccess": "Testovací e-mail bol odoslaný",
|
||||
"ToastEmailSettingsUpdateSuccess": "Nastavenia e-mailu boli aktualizované",
|
||||
"ToastEncodeCancelFailed": "Zrušenie znakového kódovania zlyhalo",
|
||||
"ToastEncodeCancelSucces": "Znakové kódovanie bolo zrušené",
|
||||
"ToastEpisodeDownloadQueueClearFailed": "Vyčistenie poradia zlyhalo",
|
||||
"ToastEpisodeDownloadQueueClearSuccess": "Poradie sťahovania bolo vyčistené",
|
||||
"ToastEncodeCancelFailed": "Zrušenie kódovania zlyhalo",
|
||||
"ToastEncodeCancelSucces": "Kódovanie bolo zrušené",
|
||||
"ToastEpisodeDownloadQueueClearFailed": "Vyčistenie fronty zlyhalo",
|
||||
"ToastEpisodeDownloadQueueClearSuccess": "Fronta sťahovania bola vyčistená",
|
||||
"ToastEpisodeUpdateSuccess": "{0} epizód bolo aktualizovaných",
|
||||
"ToastErrorCannotShare": "Na tomto zariadení nie je možné zdielať vybraným spôsobom",
|
||||
"ToastErrorCannotShare": "Na tomto zariadení nie je možné zdieľať vybraným spôsobom",
|
||||
"ToastFailedToCreate": "Vytvorenie zlyhalo",
|
||||
"ToastFailedToDelete": "Zmazanie zlyhalo",
|
||||
"ToastFailedToLoadData": "Načítanie údajov zlyhalo",
|
||||
@@ -1052,7 +1056,7 @@
|
||||
"ToastInvalidImageUrl": "Neplatná URL obrázku",
|
||||
"ToastInvalidMaxEpisodesToDownload": "Neplatný maximálny počet epizód na stiahnutie",
|
||||
"ToastInvalidUrl": "Neplatná URL",
|
||||
"ToastInvalidUrls": "Jedna alebo viac URL liniek sú neplatné",
|
||||
"ToastInvalidUrls": "Jedna alebo viac URL adries je neplatných",
|
||||
"ToastItemCoverUpdateSuccess": "Prebal položky bol aktualizovaný",
|
||||
"ToastItemDeletedFailed": "Odstránenie položky zlyhalo",
|
||||
"ToastItemDeletedSuccess": "Položka bola odstránená",
|
||||
@@ -1087,11 +1091,11 @@
|
||||
"ToastNewUserUsernameError": "Zadajte používateľské meno",
|
||||
"ToastNoNewEpisodesFound": "Žiadne nové epizódy neboli nájdené",
|
||||
"ToastNoRSSFeed": "Podcast nemá RSS zdroj",
|
||||
"ToastNoUpdatesNecessary": "Žiadne aktualizácie nie nutné",
|
||||
"ToastNoUpdatesNecessary": "Žiadne aktualizácie nie sú potrebné",
|
||||
"ToastNotificationCreateFailed": "Vytvorenie notifikácie zlyhalo",
|
||||
"ToastNotificationDeleteFailed": "Odstránenie notifikácie zlyhalo",
|
||||
"ToastNotificationFailedMaximum": "Maximálny počet chybných pokusov musí byť >= 0",
|
||||
"ToastNotificationQueueMaximum": "Maximálny počet notifikácií v poradí musí byť >= 0",
|
||||
"ToastNotificationQueueMaximum": "Maximálny počet notifikácií vo fronte musí byť >= 0",
|
||||
"ToastNotificationSettingsUpdateSuccess": "Nastavenia notifikácií boli aktualizované",
|
||||
"ToastNotificationTestTriggerFailed": "Spustenie testovacej notifikácie zlyhalo",
|
||||
"ToastNotificationTestTriggerSuccess": "Testovacia notifikácia bola spustená",
|
||||
@@ -1134,8 +1138,8 @@
|
||||
"ToastSessionCloseFailed": "Ukončenie relácie zlyhalo",
|
||||
"ToastSessionDeleteFailed": "Odstránenie relácie zlyhalo",
|
||||
"ToastSessionDeleteSuccess": "Relácia odstránená",
|
||||
"ToastSleepTimerDone": "Časovač spánku bol spustený... zZzzZz",
|
||||
"ToastSlugMustChange": "Slug obsahuje naplatné znaky",
|
||||
"ToastSleepTimerDone": "Časovač spánku skončil... zZzzZz",
|
||||
"ToastSlugMustChange": "Slug obsahuje neplatné znaky",
|
||||
"ToastSlugRequired": "Slug je povinný",
|
||||
"ToastSocketConnected": "Socket je pripojený",
|
||||
"ToastSocketDisconnected": "Socket je odpojený",
|
||||
|
||||
@@ -951,7 +951,7 @@
|
||||
"NoteChapterEditorTimes": "OBS: Starttiden för första kapitlet måste vara 0:00 och starttiden för det sista kapitlet får inte överstiga ljudbokens totala längd.",
|
||||
"NoteFolderPicker": "OBS: Mappar som redan är kopplade kommer inte att visas",
|
||||
"NoteRSSFeedPodcastAppsHttps": "VARNING: De flesta poddappar kräver att RSS-flödets URL använder HTTPS",
|
||||
"NoteRSSFeedPodcastAppsPubDate": "VARNING: Ett eller flera avsnitt saknar publiceringsdatum. Vissa poddappar kräver ett sådant datum.",
|
||||
"NoteRSSFeedPodcastAppsPubDate": "Varning: Ett eller flera avsnitt saknar publiceringsdatum. Vissa poddappar kräver ett sådant datum.",
|
||||
"NoteUploaderFoldersWithMediaFiles": "Mappar som innehåller mediefiler hanteras som separata objekt i biblioteket.",
|
||||
"NoteUploaderOnlyAudioFiles": "Om du bara laddar upp ljudfiler kommer varje ljudfil att hanteras som en separat ljudbok.",
|
||||
"NoteUploaderUnsupportedFiles": "Filtyper som inte stöds ignoreras. När du väljer eller släpper en mapp ignoreras filer som inte tillhör ett biblioteksobjekt.",
|
||||
|
||||
@@ -399,7 +399,7 @@
|
||||
"LabelPodcasts": "Podcasts",
|
||||
"LabelPort": "Cổng",
|
||||
"LabelPrefixesToIgnore": "Tiền tố để bỏ qua (không phân biệt chữ hoa/chữ thường)",
|
||||
"LabelPreventIndexing": "Ngăn Chặn Feed của bạn bị truy xuất bởi thư mục iTunes và Google podcast",
|
||||
"LabelPreventIndexing": "Ngăn Chặn Feed của bạn bị truy xuất bởi thư mục iTunes và Google podcast",
|
||||
"LabelPrimaryEbook": "Ebook chính",
|
||||
"LabelProgress": "Tiến độ",
|
||||
"LabelProvider": "Nhà cung cấp",
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "audiobookshelf",
|
||||
"version": "2.37.2",
|
||||
"version": "2.38.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "audiobookshelf",
|
||||
"version": "2.37.2",
|
||||
"version": "2.38.0",
|
||||
"license": "GPL-3.0",
|
||||
"dependencies": {
|
||||
"axios": "^0.27.2",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "audiobookshelf",
|
||||
"version": "2.37.2",
|
||||
"version": "2.38.0",
|
||||
"buildNumber": 1,
|
||||
"description": "Self-hosted audiobook and podcast server",
|
||||
"main": "dist-server/index.js",
|
||||
|
||||
+5
-5
@@ -22,6 +22,7 @@ class Auth {
|
||||
|
||||
/** @type {import('express-rate-limit').RateLimitRequestHandler} */
|
||||
this.authRateLimiter = RateLimiterFactory.getAuthRateLimiter()
|
||||
this.passwordChangeRateLimiter = RateLimiterFactory.getPasswordChangeRateLimiter()
|
||||
|
||||
this.tokenManager = new TokenManager()
|
||||
this.localAuthStrategy = new LocalAuthStrategy()
|
||||
@@ -328,7 +329,7 @@ class Auth {
|
||||
})
|
||||
|
||||
// Refresh token route
|
||||
router.post('/auth/refresh', this.authRateLimiter, async (req, res) => {
|
||||
router.post('/auth/refresh', async (req, res) => {
|
||||
let refreshToken = req.cookies.refresh_token
|
||||
|
||||
// If x-refresh-token header is present, use it instead of the cookie
|
||||
@@ -359,7 +360,7 @@ class Auth {
|
||||
})
|
||||
|
||||
// openid strategy login route (this redirects to the configured openid login provider)
|
||||
router.get('/auth/openid', this.authRateLimiter, (req, res) => {
|
||||
router.get('/auth/openid', (req, res) => {
|
||||
const authorizationUrlResponse = this.oidcAuthStrategy.getAuthorizationUrl(req)
|
||||
|
||||
if (authorizationUrlResponse.error) {
|
||||
@@ -377,12 +378,11 @@ class Auth {
|
||||
|
||||
// This will be the oauth2 callback route for mobile clients
|
||||
// It will redirect to an app-link like audiobookshelf://oauth
|
||||
router.get('/auth/openid/mobile-redirect', this.authRateLimiter, (req, res) => this.oidcAuthStrategy.handleMobileRedirect(req, res))
|
||||
router.get('/auth/openid/mobile-redirect', (req, res) => this.oidcAuthStrategy.handleMobileRedirect(req, res))
|
||||
|
||||
// openid strategy callback route (this receives the token from the configured openid login provider)
|
||||
router.get(
|
||||
'/auth/openid/callback',
|
||||
this.authRateLimiter,
|
||||
(req, res, next) => {
|
||||
const sessionKey = this.oidcAuthStrategy.getStrategy()._key
|
||||
|
||||
@@ -461,7 +461,7 @@ class Auth {
|
||||
*
|
||||
* @example /auth/openid/config?issuer=http://192.168.1.66:9000/application/o/audiobookshelf/
|
||||
*/
|
||||
router.get('/auth/openid/config', this.authRateLimiter, this.isAuthenticated, async (req, res) => {
|
||||
router.get('/auth/openid/config', this.isAuthenticated, async (req, res) => {
|
||||
if (!req.user.isAdminOrUp) {
|
||||
Logger.error(`[Auth] Non-admin user "${req.user.username}" attempted to get issuer config`)
|
||||
return res.sendStatus(403)
|
||||
|
||||
+4
-15
@@ -4,7 +4,6 @@ const express = require('express')
|
||||
const http = require('http')
|
||||
const util = require('util')
|
||||
const fs = require('./libs/fsExtra')
|
||||
const fileUpload = require('./libs/expressFileupload')
|
||||
const cookieParser = require('cookie-parser')
|
||||
const axios = require('axios')
|
||||
|
||||
@@ -13,6 +12,7 @@ const { version } = require('../package.json')
|
||||
// Utils
|
||||
const is = require('./libs/requestIp/isJs')
|
||||
const fileUtils = require('./utils/fileUtils')
|
||||
const { sweepUploadTempFiles } = require('./utils/fileUploadMiddleware')
|
||||
const { toNumber } = require('./utils/index')
|
||||
const { getRequestOrigin } = require('./utils/requestUtils')
|
||||
const Logger = require('./Logger')
|
||||
@@ -199,6 +199,7 @@ class Server {
|
||||
|
||||
await this.cleanUserData() // Remove invalid user item progress
|
||||
await CacheManager.ensureCachePaths()
|
||||
await sweepUploadTempFiles()
|
||||
|
||||
await ShareManager.init()
|
||||
await this.backupManager.init()
|
||||
@@ -336,20 +337,8 @@ class Server {
|
||||
|
||||
this.server = http.createServer(app)
|
||||
|
||||
// Skip file upload parsing for internal-api routes (Next.js proxies read multipart bodies).
|
||||
router.use(
|
||||
/^(?!\/internal-api).*/,
|
||||
fileUpload({
|
||||
defCharset: 'utf8',
|
||||
defParamCharset: 'utf8',
|
||||
useTempFiles: true,
|
||||
tempFileDir: Path.join(global.MetadataPath, 'tmp')
|
||||
})
|
||||
)
|
||||
router.use(express.urlencoded({ extended: true, limit: '5mb' }))
|
||||
|
||||
// Skip JSON parsing for internal-api routes
|
||||
router.use(/^(?!\/internal-api).*/, express.json({ limit: '10mb' }))
|
||||
// Skip body parsing for internal-api routes so Next.js receives the unread request stream
|
||||
router.use(/^(?!\/internal-api).*/, express.urlencoded({ extended: true, limit: '5mb' }), express.json({ limit: '10mb' }))
|
||||
|
||||
router.use('/api', this.auth.ifAuthNeeded(this.authMiddleware.bind(this)), this.apiRouter.router)
|
||||
router.use('/hls', this.hlsRouter.router)
|
||||
|
||||
@@ -194,7 +194,11 @@ class SocketAuthority {
|
||||
})
|
||||
|
||||
// Cover search streaming
|
||||
socket.on('search_covers', (payload) => this.handleCoverSearch(socket, payload))
|
||||
socket.on('search_covers', (payload) => {
|
||||
this.handleCoverSearch(socket, payload).catch((error) => {
|
||||
Logger.error('[SocketAuthority] search_covers failed', error)
|
||||
})
|
||||
})
|
||||
socket.on('cancel_cover_search', (requestId) => this.handleCancelCoverSearch(socket, requestId))
|
||||
|
||||
// Logs
|
||||
@@ -372,6 +376,10 @@ class SocketAuthority {
|
||||
* @param {Object} payload
|
||||
*/
|
||||
async handleCoverSearch(socket, payload) {
|
||||
if (!payload || typeof payload !== 'object') {
|
||||
payload = {}
|
||||
}
|
||||
|
||||
const client = this.clients[socket.id]
|
||||
if (!client?.user) {
|
||||
Logger.error('[SocketAuthority] Unauthorized cover search request')
|
||||
|
||||
@@ -49,6 +49,12 @@ class LocalAuthStrategy {
|
||||
* @param {Function} done - Passport callback
|
||||
*/
|
||||
async verifyCredentials(req, username, password, done) {
|
||||
if (typeof username !== 'string' || typeof password !== 'string') {
|
||||
this.logFailedLoginAttempt(req, typeof username === 'string' ? username : '[non-string]', 'Invalid username or password')
|
||||
done(null, null)
|
||||
return
|
||||
}
|
||||
|
||||
// Load the user given it's username
|
||||
const user = await Database.userModel.getUserByUsername(username.toLowerCase())
|
||||
|
||||
|
||||
@@ -393,7 +393,15 @@ class OidcAuthStrategy {
|
||||
* @returns {string|null}
|
||||
*/
|
||||
getEndSessionUrl(req, idToken, authMethod) {
|
||||
const client = this.getClient()
|
||||
// Logout trusts the auth_method cookie. getClient() throws when OpenID is not
|
||||
// configured, and that throw is outside the request promise, so it exits the process.
|
||||
let client
|
||||
try {
|
||||
client = this.getClient()
|
||||
} catch (error) {
|
||||
Logger.error(`[OidcAuth] Cannot build end session URL - ${error.message}`)
|
||||
return null
|
||||
}
|
||||
|
||||
if (client.issuer.end_session_endpoint && client.issuer.end_session_endpoint.length > 0) {
|
||||
let postLogoutRedirectUri = null
|
||||
|
||||
@@ -11,11 +11,24 @@ const CoverManager = require('../managers/CoverManager')
|
||||
const AuthorFinder = require('../finders/AuthorFinder')
|
||||
|
||||
const { reqSupportsWebp, isValidASIN, clampPositiveInt } = require('../utils/index')
|
||||
const htmlSanitizer = require('../utils/htmlSanitizer')
|
||||
|
||||
const naturalSort = createNewSortInstance({
|
||||
comparer: new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }).compare
|
||||
})
|
||||
|
||||
/**
|
||||
* @param {string} description
|
||||
* @returns {string|null}
|
||||
*/
|
||||
function sanitizeAuthorDescription(description) {
|
||||
const sanitizedDescription = htmlSanitizer.sanitize(description)
|
||||
if (sanitizedDescription !== description) {
|
||||
Logger.debug(`[AuthorController] Sanitized description from "${description}" to "${sanitizedDescription}"`)
|
||||
}
|
||||
return sanitizedDescription || null
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef RequestUserObject
|
||||
* @property {import('../models/User')} user
|
||||
@@ -101,6 +114,10 @@ class AuthorController {
|
||||
payload[key] = req.body[key]
|
||||
}
|
||||
}
|
||||
if (payload.description) {
|
||||
payload.description = sanitizeAuthorDescription(payload.description)
|
||||
}
|
||||
|
||||
if (!Object.keys(payload).length) {
|
||||
Logger.error(`[AuthorController] Invalid request payload. No valid keys found`, req.body)
|
||||
return res.status(400).send('Invalid request payload. No valid keys found')
|
||||
@@ -364,9 +381,12 @@ class AuthorController {
|
||||
}
|
||||
}
|
||||
|
||||
if (authorData.description && req.author.description !== authorData.description) {
|
||||
req.author.description = authorData.description
|
||||
hasUpdates = true
|
||||
if (authorData.description) {
|
||||
const description = sanitizeAuthorDescription(authorData.description)
|
||||
if (req.author.description !== description) {
|
||||
req.author.description = description
|
||||
hasUpdates = true
|
||||
}
|
||||
}
|
||||
|
||||
if (hasUpdates) {
|
||||
|
||||
@@ -96,12 +96,8 @@ class CollectionController {
|
||||
return res.status(500).send('Failed to create collection')
|
||||
}
|
||||
|
||||
// Load books expanded
|
||||
newCollection.books = await newCollection.getBooksExpandedWithLibraryItem()
|
||||
|
||||
// Note: The old collection model stores expanded libraryItems in the books property
|
||||
const jsonExpanded = newCollection.toOldJSONExpanded()
|
||||
SocketAuthority.emitter('collection_added', jsonExpanded)
|
||||
const jsonExpanded = await newCollection.getOldJsonExpanded(req.user)
|
||||
if (jsonExpanded) SocketAuthority.clientEmitter(req.user.id, 'collection_added', jsonExpanded)
|
||||
res.json(jsonExpanded)
|
||||
}
|
||||
|
||||
@@ -196,9 +192,9 @@ class CollectionController {
|
||||
}
|
||||
}
|
||||
|
||||
const jsonExpanded = await req.collection.getOldJsonExpanded()
|
||||
if (wasUpdated) {
|
||||
SocketAuthority.emitter('collection_updated', jsonExpanded)
|
||||
const jsonExpanded = await req.collection.getOldJsonExpanded(req.user)
|
||||
if (wasUpdated && jsonExpanded) {
|
||||
SocketAuthority.clientEmitter(req.user.id, 'collection_updated', jsonExpanded)
|
||||
}
|
||||
res.json(jsonExpanded)
|
||||
}
|
||||
@@ -212,14 +208,17 @@ class CollectionController {
|
||||
* @param {Response} res
|
||||
*/
|
||||
async delete(req, res) {
|
||||
const jsonExpanded = await req.collection.getOldJsonExpanded()
|
||||
const jsonExpanded = await req.collection.getOldJsonExpanded(req.user)
|
||||
|
||||
// Close rss feed - remove from db and emit socket event
|
||||
await RssFeedManager.closeFeedForEntityId(req.collection.id)
|
||||
|
||||
if (jsonExpanded) {
|
||||
SocketAuthority.clientEmitter(req.user.id, 'collection_removed', jsonExpanded)
|
||||
}
|
||||
|
||||
await req.collection.destroy()
|
||||
|
||||
SocketAuthority.emitter('collection_removed', jsonExpanded)
|
||||
res.sendStatus(200)
|
||||
}
|
||||
|
||||
@@ -248,14 +247,19 @@ class CollectionController {
|
||||
return res.status(400).send('Book already in collection')
|
||||
}
|
||||
|
||||
// Create collectionBook record
|
||||
await Database.collectionBookModel.create({
|
||||
collectionId: req.collection.id,
|
||||
bookId: libraryItem.mediaId,
|
||||
order: collectionBooks.length + 1
|
||||
})
|
||||
const jsonExpanded = await req.collection.getOldJsonExpanded()
|
||||
SocketAuthority.emitter('collection_updated', jsonExpanded)
|
||||
// Create collectionBook record. A second add can pass the check above and hit the unique pair.
|
||||
try {
|
||||
await Database.collectionBookModel.create({
|
||||
collectionId: req.collection.id,
|
||||
bookId: libraryItem.mediaId,
|
||||
order: collectionBooks.length + 1
|
||||
})
|
||||
} catch (error) {
|
||||
if (error.name !== 'SequelizeUniqueConstraintError') throw error
|
||||
return res.status(400).send('Book already in collection')
|
||||
}
|
||||
const jsonExpanded = await req.collection.getOldJsonExpanded(req.user)
|
||||
if (jsonExpanded) SocketAuthority.clientEmitter(req.user.id, 'collection_updated', jsonExpanded)
|
||||
res.json(jsonExpanded)
|
||||
}
|
||||
|
||||
@@ -299,10 +303,10 @@ class CollectionController {
|
||||
order++
|
||||
}
|
||||
|
||||
jsonExpanded = await req.collection.getOldJsonExpanded()
|
||||
SocketAuthority.emitter('collection_updated', jsonExpanded)
|
||||
jsonExpanded = await req.collection.getOldJsonExpanded(req.user)
|
||||
if (jsonExpanded) SocketAuthority.clientEmitter(req.user.id, 'collection_updated', jsonExpanded)
|
||||
} else {
|
||||
jsonExpanded = await req.collection.getOldJsonExpanded()
|
||||
jsonExpanded = await req.collection.getOldJsonExpanded(req.user)
|
||||
}
|
||||
res.json(jsonExpanded)
|
||||
}
|
||||
@@ -359,12 +363,12 @@ class CollectionController {
|
||||
|
||||
let jsonExpanded = null
|
||||
if (hasUpdated) {
|
||||
await Database.collectionBookModel.bulkCreate(collectionBooksToAdd)
|
||||
await Database.collectionBookModel.bulkCreate(collectionBooksToAdd, { ignoreDuplicates: true })
|
||||
|
||||
jsonExpanded = await req.collection.getOldJsonExpanded()
|
||||
SocketAuthority.emitter('collection_updated', jsonExpanded)
|
||||
jsonExpanded = await req.collection.getOldJsonExpanded(req.user)
|
||||
if (jsonExpanded) SocketAuthority.clientEmitter(req.user.id, 'collection_updated', jsonExpanded)
|
||||
} else {
|
||||
jsonExpanded = await req.collection.getOldJsonExpanded()
|
||||
jsonExpanded = await req.collection.getOldJsonExpanded(req.user)
|
||||
}
|
||||
res.json(jsonExpanded)
|
||||
}
|
||||
@@ -417,9 +421,9 @@ class CollectionController {
|
||||
order++
|
||||
}
|
||||
|
||||
let jsonExpanded = await req.collection.getOldJsonExpanded()
|
||||
if (hasUpdated) {
|
||||
SocketAuthority.emitter('collection_updated', jsonExpanded)
|
||||
let jsonExpanded = await req.collection.getOldJsonExpanded(req.user)
|
||||
if (hasUpdated && jsonExpanded) {
|
||||
SocketAuthority.clientEmitter(req.user.id, 'collection_updated', jsonExpanded)
|
||||
}
|
||||
res.json(jsonExpanded)
|
||||
}
|
||||
@@ -447,7 +451,7 @@ class CollectionController {
|
||||
if (req.method == 'DELETE' && !req.params.bookId && !req.user.canDelete) {
|
||||
Logger.warn(`[CollectionController] User "${req.user.username}" attempted to delete without permission`)
|
||||
return res.sendStatus(403)
|
||||
} else if ((req.method == 'PATCH' || req.method == 'POST') && !req.user.canUpdate) {
|
||||
} else if ((req.method == 'PATCH' || req.method == 'POST' || (req.method == 'DELETE' && req.params.bookId)) && !req.user.canUpdate) {
|
||||
Logger.warn(`[CollectionController] User "${req.user.username}" attempted to update without permission`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ const Logger = require('../Logger')
|
||||
const fs = require('../libs/fsExtra')
|
||||
const { toNumber } = require('../utils/index')
|
||||
const fileUtils = require('../utils/fileUtils')
|
||||
const uploadPath = require('../utils/uploadPath')
|
||||
const Database = require('../Database')
|
||||
|
||||
/**
|
||||
@@ -96,67 +97,44 @@ class FileSystemController {
|
||||
})
|
||||
}
|
||||
|
||||
// Check that library folder exists
|
||||
const libraryFolder = await Database.libraryFolderModel.findOne({
|
||||
where: {
|
||||
path: folderPath
|
||||
}
|
||||
})
|
||||
|
||||
if (!libraryFolder) {
|
||||
Logger.error(`[FileSystemController] Library folder not found: ${folderPath}`)
|
||||
return res.sendStatus(404)
|
||||
}
|
||||
|
||||
if (!req.user.checkCanAccessLibrary(libraryFolder.libraryId)) {
|
||||
Logger.error(`[FileSystemController] User "${req.user.username}" attempting to check path exists for library "${libraryFolder.libraryId}" without access`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
let filepath = Path.join(libraryFolder.path, directory)
|
||||
filepath = fileUtils.filePathToPOSIX(filepath)
|
||||
|
||||
// Ensure filepath is inside library folder (prevents directory traversal)
|
||||
if (!fileUtils.isSameOrSubPath(libraryFolder.path, filepath)) {
|
||||
Logger.error(`[FileSystemController] Filepath is not inside library folder: ${filepath}`)
|
||||
return res.sendStatus(400)
|
||||
}
|
||||
|
||||
if (await fs.pathExists(filepath)) {
|
||||
return res.json({
|
||||
exists: true
|
||||
})
|
||||
}
|
||||
|
||||
// Check if a library item exists in a subdirectory
|
||||
// See: https://github.com/advplyr/audiobookshelf/issues/4146
|
||||
const cleanedDirectory = directory.split('/').filter(Boolean).join('/')
|
||||
if (cleanedDirectory.includes('/')) {
|
||||
// Can only be 2 levels deep
|
||||
const possiblePaths = []
|
||||
const subdir = Path.dirname(directory)
|
||||
possiblePaths.push(fileUtils.filePathToPOSIX(Path.join(folderPath, subdir)))
|
||||
if (subdir.includes('/')) {
|
||||
possiblePaths.push(fileUtils.filePathToPOSIX(Path.join(folderPath, Path.dirname(subdir))))
|
||||
}
|
||||
|
||||
const libraryItem = await Database.libraryItemModel.findOne({
|
||||
// Check that library folder exists. The lookup is inside the try: Express 4 does not answer a rejected async route.
|
||||
try {
|
||||
const libraryFolder = await Database.libraryFolderModel.findOne({
|
||||
where: {
|
||||
path: possiblePaths
|
||||
path: folderPath
|
||||
}
|
||||
})
|
||||
|
||||
if (libraryItem) {
|
||||
if (!libraryFolder) {
|
||||
Logger.error(`[FileSystemController] Library folder not found: ${folderPath}`)
|
||||
return res.sendStatus(404)
|
||||
}
|
||||
|
||||
if (!req.user.checkCanAccessLibrary(libraryFolder.libraryId)) {
|
||||
Logger.error(`[FileSystemController] User "${req.user.username}" attempting to check path exists for library "${libraryFolder.libraryId}" without access`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
// Same rules as POST /api/upload: the directory itself, then a library item in a parent folder.
|
||||
// See: https://github.com/advplyr/audiobookshelf/issues/4146
|
||||
const existing = await uploadPath.checkUploadDirectory(libraryFolder.path, directory)
|
||||
if ('libraryItemTitle' in existing) {
|
||||
return res.json({
|
||||
exists: true,
|
||||
libraryItemTitle: libraryItem.title
|
||||
libraryItemTitle: existing.libraryItemTitle
|
||||
})
|
||||
}
|
||||
return res.json({
|
||||
exists: existing.exists
|
||||
})
|
||||
} catch (error) {
|
||||
if (error instanceof uploadPath.UploadError) {
|
||||
Logger.error(`[FileSystemController] Filepath is not inside library folder: ${directory}`)
|
||||
return res.sendStatus(error.statusCode)
|
||||
}
|
||||
Logger.error('[FileSystemController] Failed to check if path exists', directory, error)
|
||||
return res.sendStatus(500)
|
||||
}
|
||||
|
||||
return res.json({
|
||||
exists: false
|
||||
})
|
||||
}
|
||||
}
|
||||
module.exports = new FileSystemController()
|
||||
@@ -188,8 +188,10 @@ class LibraryController {
|
||||
async findAll(req, res) {
|
||||
let libraries = await Database.libraryModel.getAllWithFolders()
|
||||
|
||||
const librariesAccessible = req.user.permissions?.librariesAccessible || []
|
||||
if (librariesAccessible.length) {
|
||||
// accessAllLibraries is stored with an empty librariesAccessible list. An empty list
|
||||
// with access to all libraries turned off means the user can see no libraries.
|
||||
if (!req.user.permissions?.accessAllLibraries) {
|
||||
const librariesAccessible = req.user.permissions?.librariesAccessible || []
|
||||
libraries = libraries.filter((lib) => librariesAccessible.includes(lib.id))
|
||||
}
|
||||
|
||||
@@ -785,6 +787,10 @@ class LibraryController {
|
||||
if (!series || series.libraryId !== req.library.id) return res.sendStatus(404)
|
||||
|
||||
const libraryItemsInSeries = await libraryItemsBookFilters.getLibraryItemsForSeries(series, req.user)
|
||||
if (!libraryItemsInSeries.length) {
|
||||
Logger.warn(`[LibraryController] User "${req.user.username}" attempted to access series "${series.id}" with no accessible books`)
|
||||
return res.sendStatus(404)
|
||||
}
|
||||
|
||||
const seriesJson = series.toOldJSON()
|
||||
if (include.includes('progress')) {
|
||||
|
||||
@@ -495,7 +495,7 @@ class MeController {
|
||||
for (const mediaProgress of mediaProgressesInProgress) {
|
||||
const oldMediaProgress = mediaProgress.getOldMediaProgress()
|
||||
const libraryItem = libraryItems.find((li) => li.id === oldMediaProgress.libraryItemId)
|
||||
if (libraryItem) {
|
||||
if (libraryItem && req.user.checkCanAccessLibraryItem(libraryItem)) {
|
||||
if (oldMediaProgress.episodeId && libraryItem.isPodcast) {
|
||||
const episode = libraryItem.media.podcastEpisodes.find((ep) => ep.id === oldMediaProgress.episodeId)
|
||||
if (episode) {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
const Sequelize = require('sequelize')
|
||||
const Path = require('path')
|
||||
const { Request, Response } = require('express')
|
||||
const fs = require('../libs/fsExtra')
|
||||
const Logger = require('../Logger')
|
||||
const SocketAuthority = require('../SocketAuthority')
|
||||
const Database = require('../Database')
|
||||
@@ -12,6 +11,7 @@ const cron = require('../libs/nodeCron')
|
||||
const { isObject, getTitleIgnorePrefix } = require('../utils/index')
|
||||
const ServerSettings = require('../objects/settings/ServerSettings')
|
||||
const { sanitizeFilename } = require('../utils/fileUtils')
|
||||
const uploadPath = require('../utils/uploadPath')
|
||||
const { sanitize } = require('../utils/htmlSanitizer')
|
||||
|
||||
const TaskManager = require('../managers/TaskManager')
|
||||
@@ -29,7 +29,8 @@ class MiscController {
|
||||
|
||||
/**
|
||||
* POST: /api/upload
|
||||
* Update library item
|
||||
* Upload files for a new library item, or add files to an existing folder with update permission.
|
||||
* Refuses to overwrite existing files unless `overwrite` is true and the user has update and delete permissions.
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
@@ -39,17 +40,22 @@ class MiscController {
|
||||
Logger.warn(`User "${req.user.username}" attempted to upload without permission`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
if (!req.files || !Object.values(req.files).length) {
|
||||
// Flatten first. A field can be present and still hold no files.
|
||||
const files = Object.values(req.files || {}).flat()
|
||||
if (!files.length) {
|
||||
Logger.error('Invalid request, no files')
|
||||
return res.sendStatus(400)
|
||||
}
|
||||
|
||||
const files = Object.values(req.files).flat()
|
||||
let { title, author, series, folder: folderId, library: libraryId } = req.body
|
||||
// Validate request body
|
||||
if (!libraryId || !folderId || typeof libraryId !== 'string' || typeof folderId !== 'string' || !title || typeof title !== 'string') {
|
||||
return res.status(400).send('Invalid request body')
|
||||
}
|
||||
const overwrite = req.body.overwrite === true || req.body.overwrite === 'true' || req.body.overwrite === '1'
|
||||
if (overwrite && (!req.user.canUpdate || !req.user.canDelete)) {
|
||||
Logger.warn(`[MiscController] User "${req.user.username}" attempted to upload with overwrite without permission`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
if (!series || typeof series !== 'string') {
|
||||
series = null
|
||||
}
|
||||
@@ -57,55 +63,92 @@ class MiscController {
|
||||
author = null
|
||||
}
|
||||
|
||||
const library = await Database.libraryModel.findByIdWithFolders(libraryId)
|
||||
if (!library) {
|
||||
return res.status(404).send('Library not found')
|
||||
}
|
||||
const filenames = files.map((file) => sanitizeFilename(file.name))
|
||||
|
||||
if (!req.user.checkCanAccessLibrary(library.id)) {
|
||||
Logger.error(`[MiscController] User "${req.user.username}" attempting to upload to library "${library.id}" without access`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
const folder = library.libraryFolders.find((fold) => fold.id === folderId)
|
||||
if (!folder) {
|
||||
return res.status(404).send('Folder not found')
|
||||
}
|
||||
|
||||
// Podcasts should only be one folder deep
|
||||
const outputDirectoryParts = library.isPodcast ? [title] : [author, series, title]
|
||||
// `.filter(Boolean)` to strip out all the potentially missing details (eg: `author`)
|
||||
// before sanitizing all the directory parts to remove illegal chars and finally prepending
|
||||
// the base folder path
|
||||
const cleanedOutputDirectoryParts = outputDirectoryParts.filter(Boolean).map((part) => sanitizeFilename(part))
|
||||
const outputDirectory = Path.join(...[folder.path, ...cleanedOutputDirectoryParts])
|
||||
|
||||
try {
|
||||
await fs.ensureDir(outputDirectory)
|
||||
} catch (error) {
|
||||
Logger.error('[MiscController] Failed to create upload directory', outputDirectory, error)
|
||||
const respond = (error) => {
|
||||
if (error instanceof uploadPath.UploadError) {
|
||||
Logger.warn(`[MiscController] User "${req.user.username}" upload failed (${error.statusCode}): ${error.message}`)
|
||||
if (error.body) return res.status(error.statusCode).json(error.body)
|
||||
// Send only a known plain-text literal rather than arbitrary exception text.
|
||||
const message = uploadPath.PLAIN_TEXT_UPLOAD_ERRORS.find((known) => known === error.message)
|
||||
res.type('text/plain')
|
||||
return message ? res.status(error.statusCode).send(message) : res.sendStatus(error.statusCode)
|
||||
}
|
||||
return res.sendStatus(500)
|
||||
}
|
||||
|
||||
Logger.info(`Uploading ${files.length} files to`, outputDirectory)
|
||||
// A 409 means a file or parent library item conflict. createUploadDirectory removes only
|
||||
// directories this request created when a later mkdir fails.
|
||||
// The library lookup is inside the try: Express 4 does not answer a rejected async route.
|
||||
let outputDirectory
|
||||
let firstCreated = null
|
||||
let createdOutputDirectory = true
|
||||
let existingFiles = new Set()
|
||||
try {
|
||||
const library = await Database.libraryModel.findByIdWithFolders(libraryId)
|
||||
if (!library) {
|
||||
return res.status(404).send('Library not found')
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
const path = Path.join(outputDirectory, sanitizeFilename(file.name))
|
||||
if (!req.user.checkCanAccessLibrary(library.id)) {
|
||||
Logger.error(`[MiscController] User "${req.user.username}" attempting to upload to library "${library.id}" without access`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
await file
|
||||
.mv(path)
|
||||
.then(() => {
|
||||
return true
|
||||
})
|
||||
.catch((error) => {
|
||||
Logger.error('Failed to move file', path, error)
|
||||
return false
|
||||
})
|
||||
const folder = library.libraryFolders.find((fold) => fold.id === folderId)
|
||||
if (!folder) {
|
||||
return res.status(404).send('Folder not found')
|
||||
}
|
||||
|
||||
// Podcasts should only be one folder deep. A title that sanitizes to an empty name
|
||||
// must not fall through to the author folder or the library folder.
|
||||
const sanitizedTitle = sanitizeFilename(title)
|
||||
if (!sanitizedTitle) {
|
||||
return res.status(400).send('Invalid upload path')
|
||||
}
|
||||
const parentParts = library.isPodcast ? [] : [author, series].map((part) => sanitizeFilename(part)).filter(Boolean)
|
||||
const directoryParts = [...parentParts, sanitizedTitle]
|
||||
outputDirectory = Path.join(folder.path, ...directoryParts)
|
||||
|
||||
const destination = await uploadPath.assertUploadDestination(folder.path, outputDirectory, filenames, req.user, overwrite)
|
||||
createdOutputDirectory = !destination?.directoryExists
|
||||
existingFiles = destination?.existingFiles || new Set()
|
||||
if (createdOutputDirectory) {
|
||||
firstCreated = await uploadPath.createUploadDirectory(outputDirectory)
|
||||
}
|
||||
} catch (error) {
|
||||
if (!(error instanceof uploadPath.UploadError)) {
|
||||
Logger.error('[MiscController] Failed to upload', outputDirectory, error)
|
||||
}
|
||||
return respond(error)
|
||||
}
|
||||
|
||||
res.sendStatus(200)
|
||||
}
|
||||
const createdFiles = []
|
||||
try {
|
||||
Logger.info(`Uploading ${files.length} files to`, outputDirectory)
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const targetPath = Path.join(outputDirectory, filenames[i])
|
||||
if (!overwrite) {
|
||||
await uploadPath.reserveUploadFile(targetPath)
|
||||
createdFiles.push(targetPath)
|
||||
} else if (!existingFiles.has(filenames[i])) {
|
||||
createdFiles.push(targetPath)
|
||||
}
|
||||
await files[i].mv(targetPath)
|
||||
}
|
||||
|
||||
res.sendStatus(200)
|
||||
} catch (error) {
|
||||
if (!(error instanceof uploadPath.UploadError)) {
|
||||
Logger.error('[MiscController] Failed to upload', outputDirectory, error)
|
||||
}
|
||||
await uploadPath.rollbackFailedUpload(outputDirectory, firstCreated, createdOutputDirectory, createdFiles)
|
||||
if (error instanceof uploadPath.UploadError) return respond(error)
|
||||
const notWritable = uploadPath.notWritableUploadError(error)
|
||||
if (notWritable) return respond(notWritable)
|
||||
return res.sendStatus(500)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* GET: /api/tasks
|
||||
* Get tasks for task manager
|
||||
|
||||
@@ -399,7 +399,7 @@ class PlaylistController {
|
||||
// Find all library items
|
||||
const libraryItemIds = new Set(req.body.items.map((i) => i.libraryItemId).filter((i) => i))
|
||||
|
||||
const libraryItems = await Database.libraryItemModel.findAllExpandedWhere({ id: Array.from(libraryItemIds) })
|
||||
const libraryItems = await Database.libraryItemModel.findAllExpandedWhere({ id: Array.from(libraryItemIds), libraryId: req.playlist.libraryId })
|
||||
if (libraryItems.length !== libraryItemIds.size) {
|
||||
return res.status(400).send('Invalid request body items')
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ const { getPodcastFeed, findMatchingEpisodes } = require('../utils/podcastUtils'
|
||||
const { getFileTimestampsWithIno, filePathToPOSIX, isSameOrSubPath } = require('../utils/fileUtils')
|
||||
const { validateUrl } = require('../utils/index')
|
||||
const htmlSanitizer = require('../utils/htmlSanitizer')
|
||||
const zipHelpers = require('../utils/zipHelpers')
|
||||
const libraryItemsPodcastFilters = require('../utils/queries/libraryItemsPodcastFilters')
|
||||
|
||||
const Scanner = require('../scanner/Scanner')
|
||||
const CoverManager = require('../managers/CoverManager')
|
||||
@@ -27,6 +29,254 @@ const CoverManager = require('../managers/CoverManager')
|
||||
* @typedef {RequestWithUser & RequestEntityObject} RequestWithLibraryItem
|
||||
*/
|
||||
|
||||
const SUPPORTED_EPISODE_STRING_KEYS = ['title', 'subtitle', 'description', 'pubDate', 'episode', 'season', 'episodeType']
|
||||
const PODCAST_LIBRARY_ITEM_ATTRIBUTES = ['id', 'libraryId', 'mediaId', 'mediaType', 'path']
|
||||
const PODCAST_ACCESS_ATTRIBUTES = ['id', 'explicit', 'tags']
|
||||
|
||||
/**
|
||||
* Validate a non-empty array of `{ libraryItemId, episodeId }` entries (rejecting duplicates).
|
||||
*
|
||||
* @param {unknown} entries
|
||||
* @param {{ requirePayload?: boolean }} [options]
|
||||
* @returns {{ errorStatus?: number, errorMessage?: string, libraryItemIds?: string[], episodeIds?: string[] }}
|
||||
*/
|
||||
function validateEpisodeBatchEntries(entries, { requirePayload = false } = {}) {
|
||||
if (!Array.isArray(entries) || !entries.length) {
|
||||
return { errorStatus: 400, errorMessage: 'Invalid payload' }
|
||||
}
|
||||
|
||||
const seenKeys = new Set()
|
||||
const libraryItemIdSet = new Set()
|
||||
const episodeIdSet = new Set()
|
||||
|
||||
for (const entry of entries) {
|
||||
const hasIds = entry && typeof entry.libraryItemId === 'string' && entry.libraryItemId && typeof entry.episodeId === 'string' && entry.episodeId
|
||||
const hasValidPayload = !requirePayload || (entry?.payload && typeof entry.payload === 'object')
|
||||
if (!hasIds || !hasValidPayload) {
|
||||
return { errorStatus: 400, errorMessage: 'Invalid payload' }
|
||||
}
|
||||
const key = `${entry.libraryItemId}:${entry.episodeId}`
|
||||
if (seenKeys.has(key)) {
|
||||
return { errorStatus: 400, errorMessage: 'Invalid payload' }
|
||||
}
|
||||
seenKeys.add(key)
|
||||
libraryItemIdSet.add(entry.libraryItemId)
|
||||
episodeIdSet.add(entry.episodeId)
|
||||
}
|
||||
|
||||
return {
|
||||
libraryItemIds: [...libraryItemIdSet],
|
||||
episodeIds: [...episodeIdSet]
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an error result returned by a batch validation/resolution helper.
|
||||
*
|
||||
* @param {Response} res
|
||||
* @param {{ errorStatus?: number, errorMessage?: string }} result
|
||||
*/
|
||||
function sendErrorResult(res, result) {
|
||||
return result.errorMessage ? res.status(result.errorStatus).send(result.errorMessage) : res.sendStatus(result.errorStatus)
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate, authorize, and resolve requested `(libraryItemId, episodeId)` pairs in request order.
|
||||
*
|
||||
* @param {unknown} requestedEpisodes
|
||||
* @param {import('../models/User')} user
|
||||
* @param {object} [options]
|
||||
* @param {boolean} [options.expanded=false] - Load full expanded `LibraryItem`s (including `libraryFiles` and all `podcastEpisodes`) for mutations / socket broadcasts; otherwise query minimal attributes and only the requested episodes.
|
||||
* @param {boolean} [options.requirePayload=false] - Require every entry to include a non-null `payload` object (returns `400` otherwise).
|
||||
* @returns {Promise<{ errorStatus?: number, errorMessage?: string, resolvedEpisodes?: Array<{ libraryItem: import('../models/LibraryItem'), episode: import('../models/PodcastEpisode'), entry: any }>, matchedLibraryItemCount?: number }>}
|
||||
*/
|
||||
async function resolveRequestedPodcastEpisodes(requestedEpisodes, user, { expanded = false, requirePayload = false } = {}) {
|
||||
const validated = validateEpisodeBatchEntries(requestedEpisodes, { requirePayload })
|
||||
if (validated.errorStatus) return validated
|
||||
|
||||
const { libraryItemIds, episodeIds } = validated
|
||||
const libraryItems = expanded
|
||||
? await Database.libraryItemModel.findAllExpandedWhere({ id: libraryItemIds, mediaType: 'podcast' })
|
||||
: await Database.libraryItemModel.findAll({
|
||||
where: { id: libraryItemIds, mediaType: 'podcast' },
|
||||
attributes: PODCAST_LIBRARY_ITEM_ATTRIBUTES,
|
||||
include: [{ model: Database.podcastModel, attributes: PODCAST_ACCESS_ATTRIBUTES, required: true }]
|
||||
})
|
||||
|
||||
for (const libraryItem of libraryItems) {
|
||||
if (!user.checkCanAccessLibraryItem(libraryItem)) {
|
||||
return { errorStatus: 403 }
|
||||
}
|
||||
}
|
||||
|
||||
const podcastItems = libraryItems.filter((li) => li.isPodcast && li.media)
|
||||
const libraryItemsById = new Map(podcastItems.map((li) => [li.id, li]))
|
||||
|
||||
let episodesByPodcastAndId
|
||||
if (expanded) {
|
||||
episodesByPodcastAndId = new Map()
|
||||
for (const li of podcastItems) {
|
||||
for (const ep of li.media.podcastEpisodes || []) {
|
||||
episodesByPodcastAndId.set(`${li.media.id}:${ep.id}`, ep)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const podcastIds = podcastItems.map((li) => li.media.id)
|
||||
const episodes = podcastIds.length ? await Database.podcastEpisodeModel.findAll({ where: { id: episodeIds, podcastId: podcastIds } }) : []
|
||||
episodesByPodcastAndId = new Map(episodes.map((ep) => [`${ep.podcastId}:${ep.id}`, ep]))
|
||||
}
|
||||
|
||||
const resolvedEpisodes = []
|
||||
for (const entry of requestedEpisodes) {
|
||||
const libraryItem = libraryItemsById.get(entry.libraryItemId)
|
||||
if (!libraryItem) continue
|
||||
const episode = episodesByPodcastAndId.get(`${libraryItem.media.id}:${entry.episodeId}`)
|
||||
if (!episode) continue
|
||||
resolvedEpisodes.push({ libraryItem, episode, entry })
|
||||
}
|
||||
|
||||
return {
|
||||
resolvedEpisodes,
|
||||
matchedLibraryItemCount: podcastItems.length
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build zip archive file entries with deduplicated entry names.
|
||||
*
|
||||
* @param {Array<{ libraryItem: import('../models/LibraryItem'), episode: import('../models/PodcastEpisode') }>} resolvedEpisodes
|
||||
* @param {boolean} includePodcastFolder
|
||||
* @returns {Array<{ path: string, isFile: true, name: string }>}
|
||||
*/
|
||||
function buildEpisodeZipFileEntries(resolvedEpisodes, includePodcastFolder) {
|
||||
const usedZipNames = new Set()
|
||||
const fileEntries = []
|
||||
|
||||
const uniqueZipName = (desiredName) => {
|
||||
if (!usedZipNames.has(desiredName)) {
|
||||
usedZipNames.add(desiredName)
|
||||
return desiredName
|
||||
}
|
||||
const ext = Path.extname(desiredName)
|
||||
const base = ext ? desiredName.slice(0, -ext.length) : desiredName
|
||||
let counter = 2
|
||||
while (usedZipNames.has(`${base} (${counter})${ext}`)) counter++
|
||||
const candidate = `${base} (${counter})${ext}`
|
||||
usedZipNames.add(candidate)
|
||||
return candidate
|
||||
}
|
||||
|
||||
for (const { libraryItem, episode } of resolvedEpisodes) {
|
||||
const filePath = episode.audioFile?.metadata?.path
|
||||
if (!filePath) continue
|
||||
const basename = episode.audioFile.metadata.filename || Path.basename(filePath)
|
||||
const rawZipName = includePodcastFolder ? `${Path.basename(libraryItem.path)}/${basename}` : basename
|
||||
fileEntries.push({ path: filePath, isFile: true, name: uniqueZipName(rawZipName) })
|
||||
}
|
||||
|
||||
return fileEntries
|
||||
}
|
||||
|
||||
/**
|
||||
* Hard-delete audio files for the given episodes from disk, logging any failures.
|
||||
*
|
||||
* @param {import('../models/PodcastEpisode')[]} episodes
|
||||
*/
|
||||
async function removeEpisodeAudioFiles(episodes) {
|
||||
for (const episode of episodes) {
|
||||
const filePath = episode.audioFile?.metadata?.path
|
||||
if (!filePath) continue
|
||||
await fs
|
||||
.remove(filePath)
|
||||
.then(() => Logger.info(`[PodcastController] Hard deleted episode file at "${filePath}"`))
|
||||
.catch((error) => Logger.error(`[PodcastController] Failed to hard delete episode file at "${filePath}"`, error))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete episodes, their media progress, and update each affected podcast's libraryFiles and numEpisodes in one transaction.
|
||||
*
|
||||
* @param {string[]} removedEpisodeIds
|
||||
* @param {Map<import('../models/LibraryItem'), import('../models/PodcastEpisode')[]>} matchedByLibraryItem
|
||||
*/
|
||||
async function deleteEpisodesInTransaction(removedEpisodeIds, matchedByLibraryItem) {
|
||||
await Database.sequelize.transaction(async (transaction) => {
|
||||
const mediaProgressRemoved = await Database.mediaProgressModel.destroy({
|
||||
where: { mediaItemId: removedEpisodeIds },
|
||||
transaction
|
||||
})
|
||||
if (mediaProgressRemoved) {
|
||||
Logger.info(`[PodcastController] Removed ${mediaProgressRemoved} media progress entries for ${removedEpisodeIds.length} episodes`)
|
||||
}
|
||||
|
||||
await Database.podcastEpisodeModel.destroy({
|
||||
where: { id: removedEpisodeIds },
|
||||
transaction
|
||||
})
|
||||
|
||||
for (const [libraryItem, episodesToRemove] of matchedByLibraryItem) {
|
||||
const removedIdSet = new Set(episodesToRemove.map((ep) => ep.id))
|
||||
const removedInoSet = new Set(episodesToRemove.map((ep) => ep.audioFile?.ino).filter(Boolean))
|
||||
|
||||
const remainingEpisodes = (libraryItem.media.podcastEpisodes || []).filter((ep) => !removedIdSet.has(ep.id))
|
||||
libraryItem.media.podcastEpisodes = remainingEpisodes
|
||||
libraryItem.media.dataValues.podcastEpisodes = remainingEpisodes
|
||||
|
||||
libraryItem.libraryFiles = (libraryItem.libraryFiles || []).filter((file) => !removedInoSet.has(file.ino))
|
||||
libraryItem.changed('libraryFiles', true)
|
||||
await libraryItem.save({ transaction })
|
||||
|
||||
libraryItem.media.numEpisodes = remainingEpisodes.length
|
||||
await libraryItem.media.save({ transaction })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a sanitized PodcastEpisode update object from a request body.
|
||||
*
|
||||
* @param {Record<string, any>} body
|
||||
* @returns {Record<string, any>}
|
||||
*/
|
||||
function buildEpisodeUpdatePayload(body) {
|
||||
const updatePayload = {}
|
||||
if (!body || typeof body !== 'object') return updatePayload
|
||||
|
||||
for (const key of Object.keys(body)) {
|
||||
if (SUPPORTED_EPISODE_STRING_KEYS.includes(key) && typeof body[key] === 'string') {
|
||||
let value = body[key]
|
||||
// Sanitize description/subtitle HTML
|
||||
if ((key === 'description' || key === 'subtitle') && value) {
|
||||
const sanitized = htmlSanitizer.sanitize(value)
|
||||
if (sanitized !== value) {
|
||||
Logger.debug(`[PodcastController] Sanitized ${key} from "${value}" to "${sanitized}"`)
|
||||
value = sanitized
|
||||
}
|
||||
}
|
||||
updatePayload[key] = value
|
||||
} else if (key === 'enclosure') {
|
||||
const enclosure = body.enclosure
|
||||
if (enclosure === null) {
|
||||
updatePayload.enclosureURL = null
|
||||
updatePayload.enclosureSize = null
|
||||
updatePayload.enclosureType = null
|
||||
} else if (enclosure && typeof enclosure === 'object' && typeof enclosure.url === 'string') {
|
||||
const rawSize = enclosure.length
|
||||
const parsedSize = typeof rawSize === 'number' ? rawSize : typeof rawSize === 'string' && rawSize.trim() !== '' ? Number(rawSize) : null
|
||||
updatePayload.enclosureURL = enclosure.url
|
||||
updatePayload.enclosureType = typeof enclosure.type === 'string' ? enclosure.type : null
|
||||
updatePayload.enclosureSize = parsedSize !== null && Number.isFinite(parsedSize) && parsedSize >= 0 ? Math.trunc(parsedSize) : null
|
||||
}
|
||||
} else if (key === 'chapters' && Array.isArray(body[key]) && body[key].every((ch) => ch && typeof ch === 'object' && typeof ch.title === 'string' && ch.title && typeof ch.start === 'number' && Number.isFinite(ch.start))) {
|
||||
updatePayload[key] = body[key]
|
||||
} else if (key === 'publishedAt' && Number.isFinite(body[key])) {
|
||||
updatePayload[key] = body[key]
|
||||
}
|
||||
}
|
||||
|
||||
return updatePayload
|
||||
}
|
||||
|
||||
class PodcastController {
|
||||
/**
|
||||
* POST /api/podcasts
|
||||
@@ -404,6 +654,225 @@ class PodcastController {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* POST: /api/podcasts/episodes/batch/get
|
||||
* Fetch specific expanded podcast episodes without loading full podcast episode lists.
|
||||
*
|
||||
* Request body:
|
||||
* `{ episodes: Array<{ libraryItemId: string, episodeId: string }> }` (non-empty; `(libraryItemId, episodeId)` pairs must be unique)
|
||||
*
|
||||
* Responses:
|
||||
* - `200`: `{ episodes: PodcastEpisodeExpanded[] }`
|
||||
* (preserves request order; missing episodes or non-podcast items are omitted)
|
||||
* - `400`: Missing/empty `episodes` array, malformed entry, or duplicate `(libraryItemId, episodeId)` pair
|
||||
* - `403`: User lacks access to one or more referenced podcasts
|
||||
* - `500`: Failed to fetch episodes
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async batchGetEpisodes(req, res) {
|
||||
try {
|
||||
const resolved = await resolveRequestedPodcastEpisodes(req.body?.episodes, req.user)
|
||||
if (resolved.errorStatus) return sendErrorResult(res, resolved)
|
||||
|
||||
res.json({
|
||||
episodes: resolved.resolvedEpisodes.map(({ libraryItem, episode }) => episode.toOldJSONExpanded(libraryItem.id))
|
||||
})
|
||||
} catch (error) {
|
||||
Logger.error(`[PodcastController] Failed to batch get episodes`, error)
|
||||
return res.status(500).send('Failed to get episodes')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST: /api/podcasts/episodes/batch/update
|
||||
* Batch-update metadata for multiple podcast episodes in a single transaction.
|
||||
* Emits one `item_updated` socket event per modified podcast. Requires `user.canUpdate`.
|
||||
*
|
||||
* Request body:
|
||||
* `Array<{ libraryItemId: string, episodeId: string, payload: EpisodeUpdatePayload }>`
|
||||
* (non-empty; `(libraryItemId, episodeId)` pairs must be unique; `payload` fields match `PATCH /api/podcasts/:id/episode/:episodeId`)
|
||||
*
|
||||
* Responses:
|
||||
* - `200`: `{ success: true, updates: number }` (count of episodes that had actual changes)
|
||||
* - `400`: Empty/malformed array or duplicate `(libraryItemId, episodeId)` entry
|
||||
* - `403`: User lacks `canUpdate` or access to one or more referenced podcasts
|
||||
* - `404`: None of the requested episodes were found
|
||||
* - `500`: Unexpected server/database error while updating episodes
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async batchUpdateEpisodes(req, res) {
|
||||
if (!req.user.canUpdate) {
|
||||
Logger.warn(`[PodcastController] User "${req.user.username}" attempted to batch update episodes without permission`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
try {
|
||||
const resolved = await resolveRequestedPodcastEpisodes(req.body, req.user, {
|
||||
expanded: true,
|
||||
requirePayload: true
|
||||
})
|
||||
if (resolved.errorStatus) return sendErrorResult(res, resolved)
|
||||
|
||||
if (!resolved.resolvedEpisodes.length) {
|
||||
return res.status(404).send('Episodes not found')
|
||||
}
|
||||
|
||||
const updatedLibraryItems = new Set()
|
||||
let episodesUpdated = 0
|
||||
|
||||
await Database.sequelize.transaction(async (transaction) => {
|
||||
for (const { libraryItem, episode, entry } of resolved.resolvedEpisodes) {
|
||||
const updatePayload = buildEpisodeUpdatePayload(entry.payload)
|
||||
if (!Object.keys(updatePayload).length) continue
|
||||
|
||||
episode.set(updatePayload)
|
||||
if (episode.changed()) {
|
||||
await episode.save({ transaction })
|
||||
updatedLibraryItems.add(libraryItem)
|
||||
episodesUpdated++
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
for (const libraryItem of updatedLibraryItems) {
|
||||
Logger.info(`[PodcastController] Batch updated episodes for podcast "${libraryItem.media.title}"`)
|
||||
SocketAuthority.libraryItemEmitter('item_updated', libraryItem)
|
||||
}
|
||||
|
||||
res.json({ success: true, updates: episodesUpdated })
|
||||
} catch (error) {
|
||||
Logger.error(`[PodcastController] Failed to batch update episodes`, error)
|
||||
return res.status(500).send('Failed to update episodes')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST: /api/podcasts/episodes/batch/delete?hard=1
|
||||
* Batch-delete multiple podcast episodes, cleaning up playlists, media progress, and library files.
|
||||
* Emits one `item_updated` socket event per modified podcast. Requires `user.canDelete`.
|
||||
*
|
||||
* Query params:
|
||||
* - `hard`: `'1'` to also delete episode audio files from disk
|
||||
*
|
||||
* Request body:
|
||||
* `{ episodes: Array<{ libraryItemId: string, episodeId: string }> }` (non-empty; `(libraryItemId, episodeId)` pairs must be unique)
|
||||
*
|
||||
* Responses:
|
||||
* - `200`: `{ success: true, removed: number }`
|
||||
* - `400`: Missing/empty `episodes` array, malformed entry, or duplicate `(libraryItemId, episodeId)` pair
|
||||
* - `403`: User lacks `canDelete` or access to one or more referenced podcasts
|
||||
* - `404`: None of the requested episodes were found
|
||||
* - `500`: Unexpected server/database error while deleting episodes
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async batchDeleteEpisodes(req, res) {
|
||||
if (!req.user.canDelete) {
|
||||
Logger.warn(`[PodcastController] User "${req.user.username}" attempted to batch delete episodes without permission`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
const hardDelete = req.query.hard === '1'
|
||||
|
||||
try {
|
||||
const resolved = await resolveRequestedPodcastEpisodes(req.body?.episodes, req.user, { expanded: true })
|
||||
if (resolved.errorStatus) return sendErrorResult(res, resolved)
|
||||
|
||||
if (!resolved.resolvedEpisodes.length) {
|
||||
return res.status(404).send('Episodes not found')
|
||||
}
|
||||
|
||||
const matchedByLibraryItem = new Map()
|
||||
const removedEpisodes = []
|
||||
for (const { libraryItem, episode } of resolved.resolvedEpisodes) {
|
||||
let list = matchedByLibraryItem.get(libraryItem)
|
||||
if (!list) {
|
||||
list = []
|
||||
matchedByLibraryItem.set(libraryItem, list)
|
||||
}
|
||||
list.push(episode)
|
||||
removedEpisodes.push(episode)
|
||||
}
|
||||
|
||||
const removedEpisodeIds = removedEpisodes.map((ep) => ep.id)
|
||||
await Database.playlistModel.removeMediaItemsFromPlaylists(removedEpisodeIds)
|
||||
await deleteEpisodesInTransaction(removedEpisodeIds, matchedByLibraryItem)
|
||||
libraryItemsPodcastFilters.clearCountCache('podcastEpisode', 'afterDestroy')
|
||||
|
||||
if (hardDelete) {
|
||||
await removeEpisodeAudioFiles(removedEpisodes)
|
||||
}
|
||||
|
||||
for (const [libraryItem, episodesToRemove] of matchedByLibraryItem) {
|
||||
Logger.info(`[PodcastController] Batch deleted ${episodesToRemove.length} episode(s) from podcast "${libraryItem.media.title}"`)
|
||||
SocketAuthority.libraryItemEmitter('item_updated', libraryItem)
|
||||
}
|
||||
|
||||
res.json({ success: true, removed: removedEpisodeIds.length })
|
||||
} catch (error) {
|
||||
Logger.error(`[PodcastController] Failed to batch delete episodes`, error)
|
||||
return res.status(500).send('Failed to delete episodes')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST: /api/podcasts/episodes/batch/download
|
||||
* Streams selected podcast episode audio files as an uncompressed zip archive.
|
||||
* Requires `user.canDownload`. When episodes span multiple podcasts, files are grouped into
|
||||
* `<podcastFolder>/<filename>` subfolders; duplicate zip paths are disambiguated with ` (2)`, etc.
|
||||
*
|
||||
* Request body:
|
||||
* `{ episodes: Array<{ libraryItemId: string, episodeId: string }> }` (non-empty; `(libraryItemId, episodeId)` pairs must be unique)
|
||||
*
|
||||
* Responses:
|
||||
* - `200`: Streaming zip attachment (`PodcastEpisodes-<timestamp>.zip`, `Content-Disposition: attachment`)
|
||||
* - `400`: Missing/empty `episodes` array, malformed entry, or duplicate `(libraryItemId, episodeId)` pair
|
||||
* - `403`: User lacks `canDownload` or access to one or more referenced podcasts
|
||||
* - `404`: No downloadable episode audio files found for the requested IDs (or source file missing on disk)
|
||||
* - `500`: Archive streaming failed before headers were sent
|
||||
*
|
||||
* @param {RequestWithUser} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async batchDownloadEpisodes(req, res) {
|
||||
if (!req.user.canDownload) {
|
||||
Logger.warn(`[PodcastController] User "${req.user.username}" attempted to download episodes without permission`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
let resolved
|
||||
try {
|
||||
resolved = await resolveRequestedPodcastEpisodes(req.body?.episodes, req.user)
|
||||
} catch (error) {
|
||||
Logger.error(`[PodcastController] Failed to resolve episodes for download`, error)
|
||||
return res.status(500).send('Download failed')
|
||||
}
|
||||
|
||||
if (resolved.errorStatus) return sendErrorResult(res, resolved)
|
||||
|
||||
const fileEntries = buildEpisodeZipFileEntries(resolved.resolvedEpisodes, resolved.matchedLibraryItemCount > 1)
|
||||
if (!fileEntries.length) {
|
||||
Logger.warn(`[PodcastController] No downloadable episode files found for user "${req.user.username}"`)
|
||||
return res.status(404).send('No downloadable episode files found')
|
||||
}
|
||||
|
||||
const filename = `PodcastEpisodes-${Date.now()}.zip`
|
||||
Logger.info(`[PodcastController] User "${req.user.username}" requested zip download for ${fileEntries.length} episode(s) "${filename}"`)
|
||||
|
||||
try {
|
||||
await zipHelpers.zipDirectoriesPipe(fileEntries, filename, res)
|
||||
Logger.info(`[PodcastController] Downloaded ${fileEntries.length} episode(s) "${filename}"`)
|
||||
} catch (error) {
|
||||
Logger.error(`[PodcastController] Episode zip download failed for "${filename}"`, error)
|
||||
zipHelpers.handleDownloadError(error, res)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH: /api/podcasts/:id/episode/:episodeId
|
||||
*
|
||||
@@ -417,43 +886,7 @@ class PodcastController {
|
||||
return res.status(404).send('Episode not found')
|
||||
}
|
||||
|
||||
const updatePayload = {}
|
||||
const supportedStringKeys = ['title', 'subtitle', 'description', 'pubDate', 'episode', 'season', 'episodeType']
|
||||
for (const key in req.body) {
|
||||
if (supportedStringKeys.includes(key) && typeof req.body[key] === 'string') {
|
||||
// Sanitize description HTML
|
||||
if (key === 'description' && req.body[key]) {
|
||||
const sanitizedDescription = htmlSanitizer.sanitize(req.body[key])
|
||||
if (sanitizedDescription !== req.body[key]) {
|
||||
Logger.debug(`[PodcastController] Sanitized description from "${req.body[key]}" to "${sanitizedDescription}"`)
|
||||
req.body[key] = sanitizedDescription
|
||||
}
|
||||
} else if (key === 'subtitle' && req.body[key]) {
|
||||
const sanitizedSubtitle = htmlSanitizer.sanitize(req.body[key])
|
||||
if (sanitizedSubtitle !== req.body[key]) {
|
||||
Logger.debug(`[PodcastController] Sanitized subtitle from "${req.body[key]}" to "${sanitizedSubtitle}"`)
|
||||
req.body[key] = sanitizedSubtitle
|
||||
}
|
||||
}
|
||||
|
||||
updatePayload[key] = req.body[key]
|
||||
} else if (key === 'enclosure') {
|
||||
const enclosure = req.body.enclosure
|
||||
if (enclosure === null) {
|
||||
updatePayload.enclosureURL = null
|
||||
updatePayload.enclosureSize = null
|
||||
updatePayload.enclosureType = null
|
||||
} else if (typeof enclosure === 'object' && typeof enclosure.url === 'string') {
|
||||
updatePayload.enclosureURL = enclosure.url
|
||||
updatePayload.enclosureType = typeof enclosure.type === 'string' ? enclosure.type : null
|
||||
updatePayload.enclosureSize = enclosure.length !== undefined && enclosure.length !== null ? enclosure.length : null
|
||||
}
|
||||
} else if (key === 'chapters' && Array.isArray(req.body[key]) && req.body[key].every((ch) => typeof ch === 'object' && ch.title && ch.start)) {
|
||||
updatePayload[key] = req.body[key]
|
||||
} else if (key === 'publishedAt' && typeof req.body[key] === 'number') {
|
||||
updatePayload[key] = req.body[key]
|
||||
}
|
||||
}
|
||||
const updatePayload = buildEpisodeUpdatePayload(req.body)
|
||||
|
||||
if (Object.keys(updatePayload).length) {
|
||||
episode.set(updatePayload)
|
||||
@@ -583,3 +1016,5 @@ class PodcastController {
|
||||
}
|
||||
}
|
||||
module.exports = new PodcastController()
|
||||
module.exports.buildEpisodeUpdatePayload = buildEpisodeUpdatePayload
|
||||
module.exports.validateEpisodeBatchEntries = validateEpisodeBatchEntries
|
||||
@@ -95,6 +95,10 @@ class SeriesController {
|
||||
async middleware(req, res, next) {
|
||||
const series = await Database.seriesModel.findByPk(req.params.id)
|
||||
if (!series) return res.sendStatus(404)
|
||||
if (!req.user.checkCanAccessLibrary(series.libraryId)) {
|
||||
Logger.warn(`[SeriesController] User "${req.user.username}" attempted to access series "${series.id}" without access to the library`)
|
||||
return res.sendStatus(404)
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter out any library items not accessible to user
|
||||
|
||||
@@ -361,6 +361,11 @@ class SessionController {
|
||||
return res.sendStatus(404)
|
||||
}
|
||||
|
||||
if (playbackSession.userId !== req.user.id && !req.user.isAdminOrUp) {
|
||||
Logger.error(`[SessionController] Non-admin user "${req.user.username}" attempted to access session belonging to another user "${req.params.id}"`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
if (req.method == 'DELETE' && !req.user.canDelete) {
|
||||
Logger.warn(`[SessionController] User "${req.user.username}" attempted to delete without permission`)
|
||||
return res.sendStatus(403)
|
||||
|
||||
@@ -26,6 +26,18 @@ const waitFlushProperty = Symbol('wait flush property symbol');
|
||||
*/
|
||||
module.exports = (options, req, res, next) => {
|
||||
req.files = null;
|
||||
const pendingCleanups = [];
|
||||
const runPendingCleanups = () => {
|
||||
while (pendingCleanups.length) {
|
||||
const cleanupFn = pendingCleanups.pop();
|
||||
try {
|
||||
cleanupFn();
|
||||
} catch (err) {
|
||||
debugLog(options, `Temp file cleanup failed: ${err}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
res.once('close', runPendingCleanups);
|
||||
|
||||
// Build busboy options and init busboy instance.
|
||||
const busboyOptions = buildOptions(options, { headers: req.headers });
|
||||
@@ -62,6 +74,7 @@ module.exports = (options, req, res, next) => {
|
||||
} = options.useTempFiles
|
||||
? tempFileHandler(options, field, filename) // Upload into temporary file.
|
||||
: memHandler(options, field, filename); // Upload into RAM.
|
||||
pendingCleanups.push(cleanup);
|
||||
|
||||
const writePromise = options.useTempFiles
|
||||
? getWritePromise().catch(err => {
|
||||
@@ -161,6 +174,7 @@ module.exports = (options, req, res, next) => {
|
||||
|
||||
busboy.on('error', (err) => {
|
||||
debugLog(options, `Busboy error`);
|
||||
runPendingCleanups();
|
||||
next(err);
|
||||
});
|
||||
|
||||
|
||||
@@ -28,6 +28,18 @@ module.exports = (options, fieldname, filename) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
// cleanup() can run from an error path and again on response close.
|
||||
let cleanedUp = false;
|
||||
|
||||
// Windows cannot unlink while the write stream still holds the file.
|
||||
const closeWriteStream = () => new Promise((resolve) => {
|
||||
if (writeStream.destroyed || writeStream.closed) {
|
||||
return resolve();
|
||||
}
|
||||
writeStream.once('close', resolve);
|
||||
writeStream.once('error', resolve);
|
||||
writeStream.end();
|
||||
});
|
||||
|
||||
return {
|
||||
dataHandler: (data) => {
|
||||
@@ -51,13 +63,21 @@ module.exports = (options, fieldname, filename) => {
|
||||
return Buffer.concat([]);
|
||||
},
|
||||
cleanup: () => {
|
||||
if (cleanedUp) return Promise.resolve();
|
||||
cleanedUp = true;
|
||||
completed = true;
|
||||
debugLog(options, `Cleaning up temporary file ${tempFilePath}...`);
|
||||
writeStream.end();
|
||||
deleteFile(tempFilePath, err => (err
|
||||
? debugLog(options, `Cleaning up temporary file ${tempFilePath} failed: ${err}`)
|
||||
: debugLog(options, `Cleaning up temporary file ${tempFilePath} done.`)
|
||||
));
|
||||
return closeWriteStream().then(() => new Promise((resolve) => {
|
||||
// ENOENT: handler already mv()'d the file; that is success.
|
||||
deleteFile(tempFilePath, err => {
|
||||
if (err && err.code !== 'ENOENT') {
|
||||
debugLog(options, `Cleaning up temporary file ${tempFilePath} failed: ${err}`);
|
||||
} else {
|
||||
debugLog(options, `Cleaning up temporary file ${tempFilePath} done.`);
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
}));
|
||||
},
|
||||
getWritePromise: () => writePromise
|
||||
};
|
||||
|
||||
@@ -2,6 +2,10 @@ const { LRUCache } = require('lru-cache')
|
||||
const Logger = require('../Logger')
|
||||
const Database = require('../Database')
|
||||
|
||||
const PERSONALIZED_URL_PATTERN = /^\/libraries\/[^/]+\/personalized/
|
||||
const RECENT_EPISODES_URL_PATTERN = /^\/libraries\/[^/]+\/recent-episodes/
|
||||
const ME_URL_PATTERN = /^\/me(\/|\?|$)/
|
||||
|
||||
class ApiCacheManager {
|
||||
defaultCacheOptions = { max: 1000, maxSize: 10 * 1000 * 1000, sizeCalculation: (item) => item.body.length + JSON.stringify(item.headers).length }
|
||||
defaultTtlOptions = { ttl: 30 * 60 * 1000 }
|
||||
@@ -12,6 +16,9 @@ class ApiCacheManager {
|
||||
constructor(cache = new LRUCache(this.defaultCacheOptions), ttlOptions = this.defaultTtlOptions) {
|
||||
this.cache = cache
|
||||
this.ttlOptions = ttlOptions
|
||||
this.globalVersion = 0
|
||||
this.personalizedVersion = 0
|
||||
this.meVersion = 0
|
||||
}
|
||||
|
||||
init(database = Database) {
|
||||
@@ -20,12 +27,25 @@ class ApiCacheManager {
|
||||
}
|
||||
|
||||
getModelName(model) {
|
||||
if (typeof model?.name === 'string') return model.name
|
||||
if (typeof model?.model?.name === 'string') return model.model.name
|
||||
if (typeof model?.constructor?.name === 'string' && model.constructor.name !== 'Object') return model.constructor.name
|
||||
const target = Array.isArray(model) ? model[0] : model
|
||||
if (typeof target?.constructor?.name === 'string' && target.constructor.name !== 'Object' && target.constructor.name !== 'Function') {
|
||||
return target.constructor.name
|
||||
}
|
||||
if (typeof target?.model?.name === 'string') return target.model.name
|
||||
if (typeof target?.name === 'string') return target.name
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
getCacheVersion(url) {
|
||||
if (PERSONALIZED_URL_PATTERN.test(url) || RECENT_EPISODES_URL_PATTERN.test(url)) {
|
||||
return this.globalVersion + this.personalizedVersion
|
||||
}
|
||||
if (ME_URL_PATTERN.test(url)) {
|
||||
return this.globalVersion + this.meVersion
|
||||
}
|
||||
return this.globalVersion
|
||||
}
|
||||
|
||||
clearByUrlPattern(urlPattern) {
|
||||
let removed = 0
|
||||
for (const key of this.cache.keys()) {
|
||||
@@ -45,10 +65,15 @@ class ApiCacheManager {
|
||||
let removedPersonalized = 0
|
||||
let removedRecentEpisodes = 0
|
||||
if (this.modelsInvalidatingPersonalized.has(modelName)) {
|
||||
removedPersonalized = this.clearByUrlPattern(/^\/libraries\/[^/]+\/personalized/)
|
||||
removedRecentEpisodes = this.clearByUrlPattern(/^\/libraries\/[^/]+\/recent-episodes/)
|
||||
this.personalizedVersion++
|
||||
removedPersonalized = this.clearByUrlPattern(PERSONALIZED_URL_PATTERN)
|
||||
removedRecentEpisodes = this.clearByUrlPattern(RECENT_EPISODES_URL_PATTERN)
|
||||
}
|
||||
let removedMe = 0
|
||||
if (this.modelsInvalidatingMe.has(modelName)) {
|
||||
this.meVersion++
|
||||
removedMe = this.clearByUrlPattern(ME_URL_PATTERN)
|
||||
}
|
||||
const removedMe = this.modelsInvalidatingMe.has(modelName) ? this.clearByUrlPattern(/^\/me(\/|\?|$)/) : 0
|
||||
Logger.debug(`[ApiCacheManager] ${modelName}.${hook}: cleared user-progress cache slices (personalized=${removedPersonalized}, recentEpisodes=${removedRecentEpisodes}, me=${removedMe})`)
|
||||
}
|
||||
|
||||
@@ -60,6 +85,7 @@ class ApiCacheManager {
|
||||
}
|
||||
|
||||
Logger.debug(`[ApiCacheManager] ${modelName}.${hook}: Clearing cache`)
|
||||
this.globalVersion++
|
||||
this.cache.clear()
|
||||
}
|
||||
|
||||
@@ -70,6 +96,7 @@ class ApiCacheManager {
|
||||
Logger.info(`[ApiCacheManager] Resetting cache`)
|
||||
|
||||
this.init()
|
||||
this.globalVersion++
|
||||
this.cache.clear()
|
||||
}
|
||||
|
||||
@@ -96,15 +123,20 @@ class ApiCacheManager {
|
||||
res.send(cached.body)
|
||||
return
|
||||
}
|
||||
const requestCacheVersion = this.getCacheVersion(key.url)
|
||||
res.originalSend = res.send
|
||||
res.send = (body) => {
|
||||
Logger.debug(`[ApiCacheManager] Cache miss: ${stringifiedKey}`)
|
||||
const cached = { body, headers: res.getHeaders(), statusCode: res.statusCode }
|
||||
if (key.url.search(/^\/libraries\/.*?\/personalized/) !== -1) {
|
||||
Logger.debug(`[ApiCacheManager] Caching with ${this.ttlOptions.ttl} ms TTL`)
|
||||
this.cache.set(stringifiedKey, cached, this.ttlOptions)
|
||||
if (this.getCacheVersion(key.url) !== requestCacheVersion) {
|
||||
Logger.debug(`[ApiCacheManager] Skipping cache set for invalidated in-flight request: ${stringifiedKey}`)
|
||||
} else {
|
||||
this.cache.set(stringifiedKey, cached)
|
||||
Logger.debug(`[ApiCacheManager] Cache miss: ${stringifiedKey}`)
|
||||
const cached = { body, headers: res.getHeaders(), statusCode: res.statusCode }
|
||||
if (PERSONALIZED_URL_PATTERN.test(key.url)) {
|
||||
Logger.debug(`[ApiCacheManager] Caching with ${this.ttlOptions.ttl} ms TTL`)
|
||||
this.cache.set(stringifiedKey, cached, this.ttlOptions)
|
||||
} else {
|
||||
this.cache.set(stringifiedKey, cached)
|
||||
}
|
||||
}
|
||||
res.originalSend(body)
|
||||
}
|
||||
|
||||
@@ -172,7 +172,7 @@ class NotificationManager {
|
||||
}
|
||||
|
||||
await Database.updateSetting(Database.notificationSettings)
|
||||
SocketAuthority.emitter('notifications_updated', Database.notificationSettings.toJSON())
|
||||
SocketAuthority.adminEmitter('notifications_updated', Database.notificationSettings.toJSON())
|
||||
|
||||
this.notificationFinished()
|
||||
}
|
||||
|
||||
@@ -299,7 +299,7 @@ class RssFeedManager {
|
||||
const feedExpanded = await Database.feedModel.createFeedForLibraryItem(userId, libraryItem, slug, serverAddress, feedOptions)
|
||||
if (feedExpanded) {
|
||||
Logger.info(`[RssFeedManager] Opened RSS feed "${feedExpanded.feedURL}"`)
|
||||
SocketAuthority.emitter('rss_feed_open', feedExpanded.toOldJSONMinified())
|
||||
SocketAuthority.emitter('rss_feed_open', feedExpanded.toOldJSONMinified(), (user) => user.checkCanAccessLibrary?.(libraryItem.libraryId))
|
||||
}
|
||||
return feedExpanded
|
||||
}
|
||||
@@ -320,7 +320,7 @@ class RssFeedManager {
|
||||
const feedExpanded = await Database.feedModel.createFeedForCollection(userId, collectionExpanded, slug, serverAddress, feedOptions)
|
||||
if (feedExpanded) {
|
||||
Logger.info(`[RssFeedManager] Opened RSS feed "${feedExpanded.feedURL}"`)
|
||||
SocketAuthority.emitter('rss_feed_open', feedExpanded.toOldJSONMinified())
|
||||
SocketAuthority.emitter('rss_feed_open', feedExpanded.toOldJSONMinified(), (user) => user.checkCanAccessLibrary?.(collectionExpanded.libraryId))
|
||||
}
|
||||
return feedExpanded
|
||||
}
|
||||
@@ -341,7 +341,7 @@ class RssFeedManager {
|
||||
const feedExpanded = await Database.feedModel.createFeedForSeries(userId, seriesExpanded, slug, serverAddress, feedOptions)
|
||||
if (feedExpanded) {
|
||||
Logger.info(`[RssFeedManager] Opened RSS feed "${feedExpanded.feedURL}"`)
|
||||
SocketAuthority.emitter('rss_feed_open', feedExpanded.toOldJSONMinified())
|
||||
SocketAuthority.emitter('rss_feed_open', feedExpanded.toOldJSONMinified(), (user) => user.checkCanAccessLibrary?.(seriesExpanded.libraryId))
|
||||
}
|
||||
return feedExpanded
|
||||
}
|
||||
@@ -354,8 +354,11 @@ class RssFeedManager {
|
||||
*/
|
||||
async handleCloseFeed(feed) {
|
||||
if (!feed) return false
|
||||
const entity = await feed.getEntity({ attributes: ['libraryId'] })
|
||||
const wasRemoved = await Database.feedModel.removeById(feed.id)
|
||||
SocketAuthority.emitter('rss_feed_closed', feed.toOldJSONMinified())
|
||||
if (entity?.libraryId) {
|
||||
SocketAuthority.emitter('rss_feed_closed', feed.toOldJSONMinified(), (user) => user.checkCanAccessLibrary?.(entity.libraryId))
|
||||
}
|
||||
Logger.info(`[RssFeedManager] Closed RSS feed "${feed.feedURL}"`)
|
||||
return wasRemoved
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const { DataTypes, Model, where, fn, col } = require('sequelize')
|
||||
const parseNameString = require('../utils/parsers/parseNameString')
|
||||
const htmlSanitizer = require('../utils/htmlSanitizer')
|
||||
|
||||
class Author extends Model {
|
||||
constructor(values, options) {
|
||||
@@ -175,11 +176,16 @@ class Author extends Model {
|
||||
}
|
||||
|
||||
toOldJSON() {
|
||||
let description = this.description
|
||||
if (description) {
|
||||
description = htmlSanitizer.sanitize(description) || null
|
||||
}
|
||||
|
||||
return {
|
||||
id: this.id,
|
||||
asin: this.asin,
|
||||
name: this.name,
|
||||
description: this.description,
|
||||
description,
|
||||
imagePath: this.imagePath,
|
||||
libraryId: this.libraryId,
|
||||
addedAt: this.createdAt.valueOf(),
|
||||
|
||||
+26
-5
@@ -439,6 +439,7 @@ class Book extends Model {
|
||||
*/
|
||||
async updateAuthorsFromRequest(authors, libraryId) {
|
||||
if (!Array.isArray(authors)) return null
|
||||
authors = parseNameString.dedupeNames(authors)
|
||||
|
||||
if (!this.authors) {
|
||||
throw new Error(`[Book] Cannot update authors because authors are not loaded for book ${this.id}`)
|
||||
@@ -466,7 +467,15 @@ class Book extends Model {
|
||||
const authorsAdded = []
|
||||
for (const authorName of newAuthorNames) {
|
||||
const { author, created } = await authorModel.findOrCreateByNameAndLibrary(authorName, libraryId)
|
||||
await bookAuthorModel.create({ bookId: this.id, authorId: author.id })
|
||||
// findOrCreate matches case-insensitively, so a second spelling can resolve to an author just linked
|
||||
if (this.authors.some((au) => au.id === author.id)) continue
|
||||
try {
|
||||
await bookAuthorModel.create({ bookId: this.id, authorId: author.id })
|
||||
} catch (error) {
|
||||
if (error.name !== 'SequelizeUniqueConstraintError') throw error
|
||||
this.authors.push(author)
|
||||
continue
|
||||
}
|
||||
if (created) {
|
||||
SocketAuthority.emitter('author_added', author.toOldJSON())
|
||||
} else {
|
||||
@@ -522,11 +531,23 @@ class Book extends Model {
|
||||
}
|
||||
} else {
|
||||
const series = await seriesModel.findOrCreateByNameAndLibrary(seriesObj.name, libraryId)
|
||||
series.bookSeries = await bookSeriesModel.create({ bookId: this.id, seriesId: series.id, sequence: seriesObjSequence })
|
||||
try {
|
||||
series.bookSeries = await bookSeriesModel.create({ bookId: this.id, seriesId: series.id, sequence: seriesObjSequence })
|
||||
seriesAdded.push(series)
|
||||
hasUpdates = true
|
||||
Logger.debug(`[Book] "${this.title}" Added series "${series.name}"`)
|
||||
} catch (error) {
|
||||
if (error.name !== 'SequelizeUniqueConstraintError') throw error
|
||||
series.bookSeries = await bookSeriesModel.findOne({ where: { bookId: this.id, seriesId: series.id } })
|
||||
if (!series.bookSeries) throw error
|
||||
if (series.bookSeries.sequence !== seriesObjSequence) {
|
||||
series.bookSeries.sequence = seriesObjSequence
|
||||
await series.bookSeries.save()
|
||||
hasUpdates = true
|
||||
Logger.debug(`[Book] "${this.title}" Updated series "${series.name}" sequence ${seriesObjSequence}`)
|
||||
}
|
||||
}
|
||||
this.series.push(series)
|
||||
seriesAdded.push(series)
|
||||
hasUpdates = true
|
||||
Logger.debug(`[Book] "${this.title}" Added series "${series.name}"`)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ class Collection extends Model {
|
||||
return null
|
||||
}
|
||||
|
||||
this.books = books
|
||||
c.books = books
|
||||
|
||||
const collectionExpanded = c.toOldJSONExpanded()
|
||||
|
||||
|
||||
@@ -148,7 +148,7 @@ class LibraryItem extends Model {
|
||||
* @returns {Promise<LibraryItemExpanded[]>}
|
||||
*/
|
||||
static async findAllExpandedWhere(where = null) {
|
||||
return this.findAll({
|
||||
const libraryItems = await this.findAll({
|
||||
where,
|
||||
include: [
|
||||
{
|
||||
@@ -169,10 +169,7 @@ class LibraryItem extends Model {
|
||||
]
|
||||
},
|
||||
{
|
||||
model: this.sequelize.models.podcast,
|
||||
include: {
|
||||
model: this.sequelize.models.podcastEpisode
|
||||
}
|
||||
model: this.sequelize.models.podcast
|
||||
}
|
||||
],
|
||||
order: [
|
||||
@@ -181,6 +178,31 @@ class LibraryItem extends Model {
|
||||
[this.sequelize.models.book, this.sequelize.models.series, 'bookSeries', 'createdAt', 'ASC']
|
||||
]
|
||||
})
|
||||
|
||||
// Fetch podcast episodes separately to avoid repeating libraryItem.libraryFiles on every episode row in SQLite
|
||||
const podcasts = libraryItems.filter((li) => li.mediaType === 'podcast' && li.media).map((li) => li.media)
|
||||
if (podcasts.length) {
|
||||
const podcastIds = podcasts.map((p) => p.id)
|
||||
const episodes = await this.sequelize.models.podcastEpisode.findAll({
|
||||
where: { podcastId: podcastIds }
|
||||
})
|
||||
const episodesByPodcastId = new Map()
|
||||
for (const episode of episodes) {
|
||||
let list = episodesByPodcastId.get(episode.podcastId)
|
||||
if (!list) {
|
||||
list = []
|
||||
episodesByPodcastId.set(episode.podcastId, list)
|
||||
}
|
||||
list.push(episode)
|
||||
}
|
||||
for (const podcast of podcasts) {
|
||||
const podcastEpisodes = episodesByPodcastId.get(podcast.id) || []
|
||||
podcast.podcastEpisodes = podcastEpisodes
|
||||
podcast.dataValues.podcastEpisodes = podcastEpisodes
|
||||
}
|
||||
}
|
||||
|
||||
return libraryItems
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+15
-5
@@ -75,11 +75,21 @@ class Series extends Model {
|
||||
static async findOrCreateByNameAndLibrary(seriesName, libraryId) {
|
||||
const series = await this.getByNameAndLibrary(seriesName, libraryId)
|
||||
if (series) return series
|
||||
return this.create({
|
||||
name: seriesName,
|
||||
nameIgnorePrefix: getTitleIgnorePrefix(seriesName),
|
||||
libraryId
|
||||
})
|
||||
try {
|
||||
return await this.create({
|
||||
name: seriesName,
|
||||
nameIgnorePrefix: getTitleIgnorePrefix(seriesName),
|
||||
libraryId
|
||||
})
|
||||
} catch (error) {
|
||||
if (error.name !== 'SequelizeUniqueConstraintError') throw error
|
||||
// The unique index is on the exact name. lower() can miss that row.
|
||||
const existingSeries = await this.findOne({
|
||||
where: { name: seriesName, libraryId }
|
||||
})
|
||||
if (!existingSeries) throw error
|
||||
return existingSeries
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+33
-4
@@ -743,10 +743,10 @@ class User extends Model {
|
||||
},
|
||||
{
|
||||
model: this.sequelize.models.podcast,
|
||||
attributes: ['id', 'title'],
|
||||
attributes: ['id', 'title', 'explicit', 'tags'],
|
||||
include: {
|
||||
model: this.sequelize.models.libraryItem,
|
||||
attributes: ['id']
|
||||
attributes: ['id', 'libraryId', 'mediaType']
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -758,15 +758,38 @@ class User extends Model {
|
||||
statusCode: 404
|
||||
}
|
||||
}
|
||||
const episodeLibraryItem = podcastEpisode.podcast?.libraryItem
|
||||
if (!episodeLibraryItem) {
|
||||
Logger.error(`[User] createUpdateMediaProgress: library item for episode ${progressPayload.episodeId} not found`)
|
||||
return {
|
||||
error: 'Library item not found',
|
||||
statusCode: 404
|
||||
}
|
||||
}
|
||||
if (progressPayload.libraryItemId && episodeLibraryItem.id !== progressPayload.libraryItemId) {
|
||||
Logger.error(`[User] createUpdateMediaProgress: episode ${progressPayload.episodeId} does not belong to library item ${progressPayload.libraryItemId}`)
|
||||
return {
|
||||
error: 'Episode does not belong to library item',
|
||||
statusCode: 400
|
||||
}
|
||||
}
|
||||
episodeLibraryItem.media = podcastEpisode.podcast
|
||||
if (!this.checkCanAccessLibraryItem(episodeLibraryItem)) {
|
||||
Logger.error(`[User] createUpdateMediaProgress: user "${this.username}" attempted to update progress for inaccessible library item "${episodeLibraryItem.id}"`)
|
||||
return {
|
||||
error: 'User does not have access to this library item',
|
||||
statusCode: 403
|
||||
}
|
||||
}
|
||||
mediaItemId = podcastEpisode.id
|
||||
mediaProgress = podcastEpisode.mediaProgresses?.[0]
|
||||
podcastId = podcastEpisode.podcastId
|
||||
} else {
|
||||
const libraryItem = await this.sequelize.models.libraryItem.findByPk(progressPayload.libraryItemId, {
|
||||
attributes: ['id', 'mediaId', 'mediaType'],
|
||||
attributes: ['id', 'libraryId', 'mediaId', 'mediaType'],
|
||||
include: {
|
||||
model: this.sequelize.models.book,
|
||||
attributes: ['id', 'title'],
|
||||
attributes: ['id', 'title', 'explicit', 'tags'],
|
||||
required: false,
|
||||
include: {
|
||||
model: this.sequelize.models.mediaProgress,
|
||||
@@ -787,6 +810,12 @@ class User extends Model {
|
||||
error: 'Library item is not a book',
|
||||
statusCode: 400
|
||||
}
|
||||
} else if (!this.checkCanAccessLibraryItem(libraryItem)) {
|
||||
Logger.error(`[User] createUpdateMediaProgress: user "${this.username}" attempted to update progress for inaccessible library item "${libraryItem.id}"`)
|
||||
return {
|
||||
error: 'User does not have access to this library item',
|
||||
statusCode: 403
|
||||
}
|
||||
}
|
||||
|
||||
mediaItemId = libraryItem.media.id
|
||||
|
||||
@@ -27,6 +27,55 @@ const htmlSanitizer = require('../utils/htmlSanitizer')
|
||||
* @property {boolean} explicit
|
||||
*/
|
||||
|
||||
/**
|
||||
* Split a list of authors on commas. A piece with no space is a credential and is glued onto the previous name.
|
||||
*
|
||||
* @param {string} text
|
||||
* @returns {string[]}
|
||||
*/
|
||||
function parseAuthorPieces(text) {
|
||||
const authors = []
|
||||
for (const piece of (text || '').split(',')) {
|
||||
const name = piece.trim()
|
||||
if (!name) continue
|
||||
if (!name.includes(' ') && authors.length) {
|
||||
authors[authors.length - 1] = `${authors[authors.length - 1]} ${name}`
|
||||
} else {
|
||||
authors.push(name)
|
||||
}
|
||||
}
|
||||
return authors
|
||||
}
|
||||
|
||||
function stripCommasFromName(name) {
|
||||
return (name || '').replace(/,/g, '').replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
|
||||
/**
|
||||
* Apple lists authors as "Name1, Name2 & Name3", but a comma can also sit inside one name ("Rick Hanson, PhD").
|
||||
* A comma-separated piece with no space is treated as a credential and glued onto the previous name.
|
||||
* The text after the last " & " is a single author, so commas there are removed.
|
||||
* @see https://github.com/advplyr/audiobookshelf/issues/1022
|
||||
* @see https://github.com/advplyr/audiobookshelf/issues/2661
|
||||
*
|
||||
* @param {string} artistName
|
||||
* @returns {string}
|
||||
*/
|
||||
function cleanAuthor(artistName) {
|
||||
const raw = (artistName || '').trim()
|
||||
if (!raw) return ''
|
||||
|
||||
const lastAmpIndex = raw.lastIndexOf(' & ')
|
||||
if (lastAmpIndex === -1) {
|
||||
return stripCommasFromName(raw)
|
||||
}
|
||||
|
||||
const authors = parseAuthorPieces(raw.slice(0, lastAmpIndex))
|
||||
const lastAuthor = stripCommasFromName(raw.slice(lastAmpIndex + 3))
|
||||
if (lastAuthor) authors.push(lastAuthor)
|
||||
return authors.join(', ')
|
||||
}
|
||||
|
||||
class iTunes {
|
||||
#responseTimeout = 10000
|
||||
|
||||
@@ -103,15 +152,11 @@ class iTunes {
|
||||
}
|
||||
|
||||
cleanAudiobook(data) {
|
||||
// artistName can be "Name1, Name2 & Name3" so we refactor this to "Name1, Name2, Name3"
|
||||
// see: https://github.com/advplyr/audiobookshelf/issues/1022
|
||||
const author = (data.artistName || '').split(' & ').join(', ')
|
||||
|
||||
return {
|
||||
id: data.collectionId,
|
||||
artistId: data.artistId,
|
||||
title: data.collectionName,
|
||||
author,
|
||||
author: cleanAuthor(data.artistName),
|
||||
description: data.description || null,
|
||||
publishedYear: data.releaseDate ? data.releaseDate.split('-')[0] : null,
|
||||
genres: data.primaryGenreName ? [data.primaryGenreName] : null,
|
||||
|
||||
@@ -11,6 +11,7 @@ const date = require('../libs/dateAndTime')
|
||||
|
||||
const CacheManager = require('../managers/CacheManager')
|
||||
const RssFeedManager = require('../managers/RssFeedManager')
|
||||
const { fileUploadParser, requireUploadPermission } = require('../utils/fileUploadMiddleware')
|
||||
|
||||
const LibraryController = require('../controllers/LibraryController')
|
||||
const UserController = require('../controllers/UserController')
|
||||
@@ -110,7 +111,7 @@ class ApiRouter {
|
||||
this.router.get('/items/:id/download', LibraryItemController.middleware.bind(this), LibraryItemController.download.bind(this))
|
||||
this.router.patch('/items/:id/media', LibraryItemController.middleware.bind(this), LibraryItemController.updateMedia.bind(this))
|
||||
this.router.get('/items/:id/cover', LibraryItemController.getCover.bind(this))
|
||||
this.router.post('/items/:id/cover', LibraryItemController.middleware.bind(this), LibraryItemController.uploadCover.bind(this))
|
||||
this.router.post('/items/:id/cover', LibraryItemController.middleware.bind(this), requireUploadPermission, fileUploadParser, LibraryItemController.uploadCover.bind(this))
|
||||
this.router.patch('/items/:id/cover', LibraryItemController.middleware.bind(this), LibraryItemController.updateCover.bind(this))
|
||||
this.router.delete('/items/:id/cover', LibraryItemController.middleware.bind(this), LibraryItemController.removeCover.bind(this))
|
||||
this.router.post('/items/:id/match', LibraryItemController.middleware.bind(this), LibraryItemController.match.bind(this))
|
||||
@@ -187,7 +188,7 @@ class ApiRouter {
|
||||
this.router.post('/me/item/:id/bookmark', MeController.createBookmark.bind(this))
|
||||
this.router.patch('/me/item/:id/bookmark', MeController.updateBookmark.bind(this))
|
||||
this.router.delete('/me/item/:id/bookmark/:time', MeController.removeBookmark.bind(this))
|
||||
this.router.patch('/me/password', this.auth.authRateLimiter, MeController.updatePassword.bind(this))
|
||||
this.router.patch('/me/password', this.auth.passwordChangeRateLimiter, MeController.updatePassword.bind(this))
|
||||
this.router.get('/me/items-in-progress', MeController.getAllLibraryItemsInProgress.bind(this))
|
||||
this.router.get('/me/series/:id/remove-from-continue-listening', MeController.removeSeriesFromContinueListening.bind(this))
|
||||
this.router.get('/me/series/:id/readd-to-continue-listening', MeController.readdSeriesFromContinueListening.bind(this))
|
||||
@@ -202,7 +203,7 @@ class ApiRouter {
|
||||
this.router.delete('/backups/:id', BackupController.middleware.bind(this), BackupController.delete.bind(this))
|
||||
this.router.get('/backups/:id/download', BackupController.middleware.bind(this), BackupController.download.bind(this))
|
||||
this.router.get('/backups/:id/apply', BackupController.middleware.bind(this), BackupController.apply.bind(this))
|
||||
this.router.post('/backups/upload', BackupController.middleware.bind(this), BackupController.upload.bind(this))
|
||||
this.router.post('/backups/upload', BackupController.middleware.bind(this), fileUploadParser, BackupController.upload.bind(this))
|
||||
this.router.patch('/backups/path', BackupController.middleware.bind(this), BackupController.updatePath.bind(this))
|
||||
|
||||
//
|
||||
@@ -249,6 +250,10 @@ class ApiRouter {
|
||||
this.router.post('/podcasts/feed', PodcastController.getPodcastFeed.bind(this))
|
||||
this.router.post('/podcasts/opml/parse', PodcastController.getFeedsFromOPMLText.bind(this))
|
||||
this.router.post('/podcasts/opml/create', PodcastController.bulkCreatePodcastsFromOpmlFeedUrls.bind(this))
|
||||
this.router.post('/podcasts/episodes/batch/get', PodcastController.batchGetEpisodes.bind(this))
|
||||
this.router.post('/podcasts/episodes/batch/update', PodcastController.batchUpdateEpisodes.bind(this))
|
||||
this.router.post('/podcasts/episodes/batch/delete', PodcastController.batchDeleteEpisodes.bind(this))
|
||||
this.router.post('/podcasts/episodes/batch/download', PodcastController.batchDownloadEpisodes.bind(this))
|
||||
this.router.get('/podcasts/:id/checknew', PodcastController.middleware.bind(this), PodcastController.checkNewEpisodes.bind(this))
|
||||
this.router.get('/podcasts/:id/downloads', PodcastController.middleware.bind(this), PodcastController.getEpisodeDownloads.bind(this))
|
||||
this.router.get('/podcasts/:id/clear-queue', PodcastController.middleware.bind(this), PodcastController.clearEpisodeDownloadQueue.bind(this))
|
||||
@@ -343,7 +348,7 @@ class ApiRouter {
|
||||
//
|
||||
// Misc Routes
|
||||
//
|
||||
this.router.post('/upload', MiscController.handleUpload.bind(this))
|
||||
this.router.post('/upload', requireUploadPermission, fileUploadParser, MiscController.handleUpload.bind(this))
|
||||
this.router.get('/tasks', MiscController.getTasks.bind(this))
|
||||
this.router.patch('/settings', MiscController.updateServerSettings.bind(this))
|
||||
this.router.patch('/sorting-prefixes', MiscController.updateSortingPrefixes.bind(this))
|
||||
|
||||
@@ -5,6 +5,7 @@ const { LogLevel } = require('../utils/constants')
|
||||
const { parseOverdriveMediaMarkersAsChapters } = require('../utils/parsers/parseOverdriveMediaMarkers')
|
||||
const parseNameString = require('../utils/parsers/parseNameString')
|
||||
const parseSeriesString = require('../utils/parsers/parseSeriesString')
|
||||
const htmlSanitizer = require('../utils/htmlSanitizer')
|
||||
const LibraryItem = require('../models/LibraryItem')
|
||||
const AudioFile = require('../objects/files/AudioFile')
|
||||
|
||||
@@ -461,6 +462,7 @@ class AudioFileScanner {
|
||||
|
||||
if (value && typeof value === 'string') {
|
||||
value = value.trim() // Trim whitespace
|
||||
if (mapping.key === 'description' || mapping.key === 'subtitle') value = htmlSanitizer.sanitize(value)
|
||||
|
||||
if (mapping.key === 'pubDate') {
|
||||
const pubJsDate = new Date(value)
|
||||
|
||||
@@ -224,12 +224,16 @@ class BookScanner {
|
||||
if (!media.authors.some((au) => au.name === authorName)) {
|
||||
const existingAuthorId = await Database.getAuthorIdByName(libraryItemData.libraryId, authorName)
|
||||
if (existingAuthorId) {
|
||||
await Database.bookAuthorModel.create({
|
||||
bookId: media.id,
|
||||
authorId: existingAuthorId
|
||||
})
|
||||
libraryScan.authorsNumBooksChangedIds.add(existingAuthorId)
|
||||
libraryScan.addLog(LogLevel.DEBUG, `Updating book "${bookMetadata.title}" added author "${authorName}"`)
|
||||
try {
|
||||
await Database.bookAuthorModel.create({
|
||||
bookId: media.id,
|
||||
authorId: existingAuthorId
|
||||
})
|
||||
libraryScan.authorsNumBooksChangedIds.add(existingAuthorId)
|
||||
libraryScan.addLog(LogLevel.DEBUG, `Updating book "${bookMetadata.title}" added author "${authorName}"`)
|
||||
} catch (error) {
|
||||
if (error.name !== 'SequelizeUniqueConstraintError') throw error
|
||||
}
|
||||
authorsUpdated = true
|
||||
} else {
|
||||
const newAuthor = await Database.authorModel.create({
|
||||
@@ -262,22 +266,51 @@ class BookScanner {
|
||||
if (!existingBookSeries) {
|
||||
const existingSeriesId = await Database.getSeriesIdByName(libraryItemData.libraryId, seriesObj.name)
|
||||
if (existingSeriesId) {
|
||||
await Database.bookSeriesModel.create({
|
||||
bookId: media.id,
|
||||
seriesId: existingSeriesId,
|
||||
sequence: seriesObj.sequence
|
||||
})
|
||||
libraryScan.addLog(LogLevel.DEBUG, `Updating book "${bookMetadata.title}" added series "${seriesObj.name}"${seriesObj.sequence ? ` with sequence "${seriesObj.sequence}"` : ''}`)
|
||||
try {
|
||||
await Database.bookSeriesModel.create({
|
||||
bookId: media.id,
|
||||
seriesId: existingSeriesId,
|
||||
sequence: seriesObj.sequence
|
||||
})
|
||||
libraryScan.addLog(LogLevel.DEBUG, `Updating book "${bookMetadata.title}" added series "${seriesObj.name}"${seriesObj.sequence ? ` with sequence "${seriesObj.sequence}"` : ''}`)
|
||||
} catch (error) {
|
||||
if (error.name !== 'SequelizeUniqueConstraintError') throw error
|
||||
}
|
||||
seriesUpdated = true
|
||||
} else {
|
||||
const newSeries = await Database.seriesModel.create({
|
||||
name: seriesObj.name,
|
||||
nameIgnorePrefix: getTitleIgnorePrefix(seriesObj.name),
|
||||
libraryId: libraryItemData.libraryId
|
||||
})
|
||||
await media.addSeries(newSeries, { through: { sequence: seriesObj.sequence } })
|
||||
Database.addSeriesToFilterData(libraryItemData.libraryId, newSeries.name, newSeries.id)
|
||||
libraryScan.addLog(LogLevel.DEBUG, `Updating book "${bookMetadata.title}" added new series "${seriesObj.name}"${seriesObj.sequence ? ` with sequence "${seriesObj.sequence}"` : ''}`)
|
||||
let newSeries
|
||||
let seriesCreated = false
|
||||
try {
|
||||
newSeries = await Database.seriesModel.create({
|
||||
name: seriesObj.name,
|
||||
nameIgnorePrefix: getTitleIgnorePrefix(seriesObj.name),
|
||||
libraryId: libraryItemData.libraryId
|
||||
})
|
||||
seriesCreated = true
|
||||
} catch (error) {
|
||||
if (error.name !== 'SequelizeUniqueConstraintError') throw error
|
||||
newSeries = await Database.seriesModel.findOne({
|
||||
where: { name: seriesObj.name, libraryId: libraryItemData.libraryId }
|
||||
})
|
||||
if (!newSeries) throw error
|
||||
}
|
||||
if (seriesCreated) {
|
||||
Database.addSeriesToFilterData(libraryItemData.libraryId, newSeries.name, newSeries.id)
|
||||
}
|
||||
try {
|
||||
await Database.bookSeriesModel.create({
|
||||
bookId: media.id,
|
||||
seriesId: newSeries.id,
|
||||
sequence: seriesObj.sequence
|
||||
})
|
||||
if (seriesCreated) {
|
||||
libraryScan.addLog(LogLevel.DEBUG, `Updating book "${bookMetadata.title}" added new series "${seriesObj.name}"${seriesObj.sequence ? ` with sequence "${seriesObj.sequence}"` : ''}`)
|
||||
} else {
|
||||
libraryScan.addLog(LogLevel.DEBUG, `Updating book "${bookMetadata.title}" added series "${seriesObj.name}"${seriesObj.sequence ? ` with sequence "${seriesObj.sequence}"` : ''}`)
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.name !== 'SequelizeUniqueConstraintError') throw error
|
||||
}
|
||||
seriesUpdated = true
|
||||
}
|
||||
} else if (seriesObj.sequence && existingBookSeries.bookSeries.sequence !== seriesObj.sequence) {
|
||||
@@ -507,24 +540,38 @@ class BookScanner {
|
||||
}
|
||||
}
|
||||
if (bookMetadata.series.length) {
|
||||
const linkedSeriesIds = new Set()
|
||||
for (const seriesObj of bookMetadata.series) {
|
||||
if (!seriesObj.name) continue
|
||||
const matchingSeriesId = await Database.getSeriesIdByName(libraryItemData.libraryId, seriesObj.name)
|
||||
if (matchingSeriesId) {
|
||||
bookObject.bookSeries.push({
|
||||
seriesId: matchingSeriesId,
|
||||
sequence: seriesObj.sequence
|
||||
})
|
||||
} else {
|
||||
bookObject.bookSeries.push({
|
||||
sequence: seriesObj.sequence,
|
||||
series: {
|
||||
let seriesId = await Database.getSeriesIdByName(libraryItemData.libraryId, seriesObj.name)
|
||||
if (!seriesId) {
|
||||
let series
|
||||
let seriesCreated = false
|
||||
try {
|
||||
series = await Database.seriesModel.create({
|
||||
name: seriesObj.name,
|
||||
nameIgnorePrefix: getTitleIgnorePrefix(seriesObj.name),
|
||||
libraryId: libraryItemData.libraryId
|
||||
}
|
||||
})
|
||||
})
|
||||
seriesCreated = true
|
||||
} catch (error) {
|
||||
if (error.name !== 'SequelizeUniqueConstraintError') throw error
|
||||
series = await Database.seriesModel.findOne({
|
||||
where: { name: seriesObj.name, libraryId: libraryItemData.libraryId }
|
||||
})
|
||||
if (!series) throw error
|
||||
}
|
||||
seriesId = series.id
|
||||
if (seriesCreated) {
|
||||
Database.addSeriesToFilterData(libraryItemData.libraryId, series.name, series.id)
|
||||
}
|
||||
}
|
||||
if (linkedSeriesIds.has(seriesId)) continue
|
||||
linkedSeriesIds.add(seriesId)
|
||||
bookObject.bookSeries.push({
|
||||
seriesId,
|
||||
sequence: seriesObj.sequence
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -703,6 +750,15 @@ class BookScanner {
|
||||
bookMetadata.description = htmlSanitizer.sanitize(bookMetadata.description)
|
||||
}
|
||||
|
||||
// One dedupe after every metadata source. A repeated name inserts the same bookAuthor or bookSeries twice and aborts the scan.
|
||||
bookMetadata.authors = parseNameString.dedupeNames(bookMetadata.authors)
|
||||
const seenSeriesNames = new Set()
|
||||
bookMetadata.series = bookMetadata.series.filter((series) => {
|
||||
if (!series?.name || seenSeriesNames.has(series.name)) return false
|
||||
seenSeriesNames.add(series.name)
|
||||
return true
|
||||
})
|
||||
|
||||
return bookMetadata
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,9 @@ class LibraryScan {
|
||||
/** @type {string[]} */
|
||||
this.seriesRemovedFromBooks = []
|
||||
|
||||
/** @type {string} item label while a library item is being scanned, so a thrown error can name it */
|
||||
this.failureItem = null
|
||||
|
||||
this.logs = []
|
||||
}
|
||||
|
||||
|
||||
@@ -116,7 +116,8 @@ class LibraryScanner {
|
||||
} catch (err) {
|
||||
libraryScan.setComplete()
|
||||
|
||||
Logger.error(`[LibraryScanner] Library scan ${libraryScan.id} failed after ${libraryScan.elapsedTimestamp} | ${libraryScan.resultStats}.`, err)
|
||||
const failedItem = libraryScan.failureItem ? ` while scanning ${libraryScan.failureItem}` : ''
|
||||
Logger.error(`[LibraryScanner] Library scan ${libraryScan.id} failed after ${libraryScan.elapsedTimestamp} | ${libraryScan.resultStats}${failedItem}.`, err)
|
||||
|
||||
task.data.scanResults = libraryScan.scanResults
|
||||
const taskFailedString = {
|
||||
@@ -169,6 +170,7 @@ class LibraryScanner {
|
||||
const libraryItemIdsMissing = []
|
||||
let libraryItemsUpdated = []
|
||||
for (const existingLibraryItem of existingLibraryItems) {
|
||||
libraryScan.failureItem = scanItemFailureLabel(existingLibraryItem.title, existingLibraryItem.path)
|
||||
// First try to find matching library item with exact file path
|
||||
let libraryItemData = libraryItemDataFound.find((lid) => lid.path === existingLibraryItem.path)
|
||||
if (!libraryItemData) {
|
||||
@@ -221,6 +223,8 @@ class LibraryScanner {
|
||||
}
|
||||
}
|
||||
|
||||
libraryScan.failureItem = null
|
||||
|
||||
// Emit item updates in chunks of 10 to client
|
||||
if (libraryItemsUpdated.length === 10) {
|
||||
SocketAuthority.libraryItemsEmitter('items_updated', libraryItemsUpdated)
|
||||
@@ -259,12 +263,14 @@ class LibraryScanner {
|
||||
if (libraryItemDataFound.length) {
|
||||
let newLibraryItems = []
|
||||
for (const libraryItemData of libraryItemDataFound) {
|
||||
libraryScan.failureItem = scanItemFailureLabel(libraryItemData.mediaMetadata?.title, libraryItemData.path)
|
||||
const newLibraryItem = await LibraryItemScanner.scanNewLibraryItem(libraryItemData, libraryScan.library.settings, libraryScan)
|
||||
if (newLibraryItem) {
|
||||
newLibraryItems.push(newLibraryItem)
|
||||
|
||||
libraryScan.resultsAdded++
|
||||
}
|
||||
libraryScan.failureItem = null
|
||||
|
||||
// Emit new items in chunks of 10 to client
|
||||
if (newLibraryItems.length === 10) {
|
||||
@@ -597,7 +603,12 @@ class LibraryScanner {
|
||||
}
|
||||
// Scan library item for updates
|
||||
Logger.debug(`[LibraryScanner] Folder update for relative path "${itemDir}" is in library item "${existingLibraryItem.media.title}" with id "${existingLibraryItem.id}" - scan for updates`)
|
||||
itemGroupingResults[itemDir] = await LibraryItemScanner.scanLibraryItem(existingLibraryItem.id, updatedLibraryItemDetails)
|
||||
try {
|
||||
itemGroupingResults[itemDir] = await LibraryItemScanner.scanLibraryItem(existingLibraryItem.id, updatedLibraryItemDetails)
|
||||
} catch (err) {
|
||||
Logger.error(`[LibraryScanner] Failed while scanning ${scanItemFailureLabel(existingLibraryItem.media?.title, existingLibraryItem.path)}`)
|
||||
throw err
|
||||
}
|
||||
continue
|
||||
} else if (library.settings.audiobooksOnly && !hasAudioFiles(fileUpdateGroup, itemDir)) {
|
||||
Logger.debug(`[LibraryScanner] Folder update for relative path "${itemDir}" has no audio files`)
|
||||
@@ -626,7 +637,13 @@ class LibraryScanner {
|
||||
|
||||
Logger.debug(`[LibraryScanner] Folder update group must be a new item "${itemDir}" in library "${library.name}"`)
|
||||
const isSingleMediaItem = isSingleMediaFile(fileUpdateGroup, itemDir)
|
||||
const newLibraryItem = await LibraryItemScanner.scanPotentialNewLibraryItem(fullPath, library, folder, isSingleMediaItem)
|
||||
let newLibraryItem
|
||||
try {
|
||||
newLibraryItem = await LibraryItemScanner.scanPotentialNewLibraryItem(fullPath, library, folder, isSingleMediaItem)
|
||||
} catch (err) {
|
||||
Logger.error(`[LibraryScanner] Failed while scanning ${scanItemFailureLabel(null, fullPath)}`)
|
||||
throw err
|
||||
}
|
||||
if (newLibraryItem) {
|
||||
SocketAuthority.libraryItemEmitter('item_added', newLibraryItem)
|
||||
}
|
||||
@@ -638,6 +655,16 @@ class LibraryScanner {
|
||||
}
|
||||
module.exports = new LibraryScanner()
|
||||
|
||||
/**
|
||||
* @param {string} title
|
||||
* @param {string} path
|
||||
* @returns {string}
|
||||
*/
|
||||
function scanItemFailureLabel(title, path) {
|
||||
if (title && path) return `"${title}" at "${path}"`
|
||||
return `"${path || title || 'unknown item'}"`
|
||||
}
|
||||
|
||||
function ItemToFileInoMatch(libraryItem1, libraryItem2) {
|
||||
return libraryItem1.isFile && libraryItem2.libraryFiles.some((lf) => lf.ino === libraryItem1.ino)
|
||||
}
|
||||
|
||||
+46
-21
@@ -260,16 +260,21 @@ class Scanner {
|
||||
// Update filter data
|
||||
Database.addAuthorToFilterData(libraryItem.libraryId, author.name, author.id)
|
||||
}
|
||||
await Database.bookAuthorModel
|
||||
.create({
|
||||
let bookAuthorCreated = true
|
||||
try {
|
||||
await Database.bookAuthorModel.create({
|
||||
authorId: author.id,
|
||||
bookId: libraryItem.media.id
|
||||
})
|
||||
.then(() => {
|
||||
Logger.info(`[Scanner] quickMatchBookBuildUpdatePayload: Added author "${author.name}" to "${libraryItem.media.title}"`)
|
||||
libraryItem.media.authors.push(author)
|
||||
hasAuthorUpdates = true
|
||||
})
|
||||
} catch (error) {
|
||||
if (error.name !== 'SequelizeUniqueConstraintError') throw error
|
||||
bookAuthorCreated = false
|
||||
}
|
||||
libraryItem.media.authors.push(author)
|
||||
hasAuthorUpdates = true
|
||||
if (bookAuthorCreated) {
|
||||
Logger.info(`[Scanner] quickMatchBookBuildUpdatePayload: Added author "${author.name}" to "${libraryItem.media.title}"`)
|
||||
}
|
||||
}
|
||||
const authorsRemoved = libraryItem.media.authors.filter((a) => !matchData.author.find((ma) => ma.toLowerCase() === a.name.toLowerCase()))
|
||||
if (authorsRemoved.length) {
|
||||
@@ -306,23 +311,43 @@ class Scanner {
|
||||
} else {
|
||||
let seriesItem = await Database.seriesModel.getByNameAndLibrary(seriesMatchItem.series, libraryItem.libraryId)
|
||||
if (!seriesItem) {
|
||||
seriesItem = await Database.seriesModel.create({
|
||||
name: seriesMatchItem.series,
|
||||
nameIgnorePrefix: getTitleIgnorePrefix(seriesMatchItem.series),
|
||||
libraryId: libraryItem.libraryId
|
||||
})
|
||||
// Update filter data
|
||||
Database.addSeriesToFilterData(libraryItem.libraryId, seriesItem.name, seriesItem.id)
|
||||
SocketAuthority.emitter('series_added', seriesItem.toOldJSON())
|
||||
let seriesCreated = false
|
||||
try {
|
||||
seriesItem = await Database.seriesModel.create({
|
||||
name: seriesMatchItem.series,
|
||||
nameIgnorePrefix: getTitleIgnorePrefix(seriesMatchItem.series),
|
||||
libraryId: libraryItem.libraryId
|
||||
})
|
||||
seriesCreated = true
|
||||
} catch (error) {
|
||||
if (error.name !== 'SequelizeUniqueConstraintError') throw error
|
||||
seriesItem = await Database.seriesModel.findOne({
|
||||
where: { name: seriesMatchItem.series, libraryId: libraryItem.libraryId }
|
||||
})
|
||||
if (!seriesItem) throw error
|
||||
}
|
||||
if (seriesCreated) {
|
||||
// Update filter data
|
||||
Database.addSeriesToFilterData(libraryItem.libraryId, seriesItem.name, seriesItem.id)
|
||||
SocketAuthority.emitter('series_added', seriesItem.toOldJSON())
|
||||
}
|
||||
}
|
||||
let bookSeries
|
||||
try {
|
||||
bookSeries = await Database.bookSeriesModel.create({
|
||||
seriesId: seriesItem.id,
|
||||
bookId: libraryItem.media.id,
|
||||
sequence: seriesMatchItem.sequence
|
||||
})
|
||||
Logger.info(`[Scanner] quickMatchBookBuildUpdatePayload: Added series "${seriesItem.name}" to "${libraryItem.media.title}"`)
|
||||
} catch (error) {
|
||||
if (error.name !== 'SequelizeUniqueConstraintError') throw error
|
||||
bookSeries = await Database.bookSeriesModel.findOne({
|
||||
where: { seriesId: seriesItem.id, bookId: libraryItem.media.id }
|
||||
})
|
||||
}
|
||||
const bookSeries = await Database.bookSeriesModel.create({
|
||||
seriesId: seriesItem.id,
|
||||
bookId: libraryItem.media.id,
|
||||
sequence: seriesMatchItem.sequence
|
||||
})
|
||||
seriesItem.bookSeries = bookSeries
|
||||
libraryItem.media.series.push(seriesItem)
|
||||
Logger.info(`[Scanner] quickMatchBookBuildUpdatePayload: Added series "${seriesItem.name}" to "${libraryItem.media.title}"`)
|
||||
hasSeriesUpdates = true
|
||||
}
|
||||
const seriesRemoved = libraryItem.media.series.filter((s) => !matchData.series.find((ms) => ms.series.toLowerCase() === s.name.toLowerCase()))
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
const Path = require('path')
|
||||
const fs = require('../libs/fsExtra')
|
||||
const fileUpload = require('../libs/expressFileupload')
|
||||
const Logger = require('../Logger')
|
||||
|
||||
/**
|
||||
* Multipart parser for the three routes that read req.files.
|
||||
* Reads MetadataPath per request so route registration does not depend on it.
|
||||
*
|
||||
* @param {import('express').Request} req
|
||||
* @param {import('express').Response} res
|
||||
* @param {import('express').NextFunction} next
|
||||
*/
|
||||
function fileUploadParser(req, res, next) {
|
||||
fileUpload({
|
||||
defCharset: 'utf8',
|
||||
defParamCharset: 'utf8',
|
||||
useTempFiles: true,
|
||||
tempFileDir: Path.join(global.MetadataPath, 'tmp')
|
||||
})(req, res, next)
|
||||
}
|
||||
module.exports.fileUploadParser = fileUploadParser
|
||||
|
||||
/**
|
||||
* Reject users without upload permission before the multipart parser writes temp files.
|
||||
*
|
||||
* @param {import('express').Request} req
|
||||
* @param {import('express').Response} res
|
||||
* @param {import('express').NextFunction} next
|
||||
*/
|
||||
function requireUploadPermission(req, res, next) {
|
||||
if (!req.user?.canUpload) {
|
||||
Logger.warn(`User "${req.user?.username || 'unknown'}" attempted to upload without permission`)
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
next()
|
||||
}
|
||||
module.exports.requireUploadPermission = requireUploadPermission
|
||||
|
||||
/**
|
||||
* Remove leftover upload temp files (tmp-*) from metadata/tmp.
|
||||
* Comic extraction uses the same directory with other names; those stay.
|
||||
*
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function sweepUploadTempFiles() {
|
||||
const tmpDir = Path.join(global.MetadataPath, 'tmp')
|
||||
let names
|
||||
try {
|
||||
names = await fs.readdir(tmpDir)
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') return
|
||||
Logger.warn(`[FileUpload] Failed to read upload temp directory "${tmpDir}": ${error.message}`)
|
||||
return
|
||||
}
|
||||
|
||||
let removed = 0
|
||||
for (const name of names) {
|
||||
if (!name.startsWith('tmp-')) continue
|
||||
const fullPath = Path.join(tmpDir, name)
|
||||
try {
|
||||
const stat = await fs.lstat(fullPath)
|
||||
if (!stat.isFile()) continue
|
||||
await fs.unlink(fullPath)
|
||||
removed++
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') continue
|
||||
Logger.warn(`[FileUpload] Failed to remove leftover upload temp file "${fullPath}": ${error.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (removed) {
|
||||
Logger.info(`[FileUpload] Removed ${removed} leftover upload temp file(s) from "${tmpDir}"`)
|
||||
}
|
||||
}
|
||||
module.exports.sweepUploadTempFiles = sweepUploadTempFiles
|
||||
+23
-12
@@ -19,25 +19,36 @@ const filePathToPOSIX = (path) => {
|
||||
}
|
||||
module.exports.filePathToPOSIX = filePathToPOSIX
|
||||
|
||||
/**
|
||||
* Check whether childPath is inside parentPath (or the same directory when allowSame is true).
|
||||
*/
|
||||
function checkSubPath(parentPath, childPath, allowSame) {
|
||||
const pathImpl = global.isWin === undefined ? Path : global.isWin ? Path.win32 : Path.posix
|
||||
parentPath = pathImpl.toNamespacedPath(parentPath)
|
||||
childPath = pathImpl.toNamespacedPath(childPath)
|
||||
if (parentPath === childPath) return allowSame
|
||||
const relativePath = pathImpl.relative(parentPath, childPath)
|
||||
if (relativePath === '') return allowSame // Same path (e.g. parentPath = '/a/b/', childPath = '/a/b')
|
||||
return relativePath !== '..' && !relativePath.startsWith('..' + pathImpl.sep) && !pathImpl.isAbsolute(relativePath)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check path is a child of or equal to another path
|
||||
*
|
||||
* @param {string} parentPath
|
||||
* @param {string} childPath
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isSameOrSubPath(parentPath, childPath) {
|
||||
parentPath = filePathToPOSIX(parentPath)
|
||||
childPath = filePathToPOSIX(childPath)
|
||||
if (parentPath === childPath) return true
|
||||
const relativePath = Path.relative(parentPath, childPath)
|
||||
return (
|
||||
relativePath === '' || // Same path (e.g. parentPath = '/a/b/', childPath = '/a/b')
|
||||
(!relativePath.startsWith('..') && !Path.isAbsolute(relativePath)) // Sub path
|
||||
)
|
||||
return checkSubPath(parentPath, childPath, true)
|
||||
}
|
||||
module.exports.isSameOrSubPath = isSameOrSubPath
|
||||
|
||||
/**
|
||||
* True when childPath is inside parentPath and is not the same directory.
|
||||
* Trailing separators still count as the same directory.
|
||||
*/
|
||||
function isStrictSubPath(parentPath, childPath) {
|
||||
return checkSubPath(parentPath, childPath, false)
|
||||
}
|
||||
module.exports.isStrictSubPath = isStrictSubPath
|
||||
|
||||
function getFileStat(path) {
|
||||
try {
|
||||
return fs.stat(path)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const Logger = require('../../Logger')
|
||||
const parseSeriesString = require('../parsers/parseSeriesString')
|
||||
const { dedupeNames } = require('../parsers/parseNameString')
|
||||
|
||||
const mediaTypeKeys = {
|
||||
book: {
|
||||
@@ -140,8 +141,7 @@ function validateMetadataValue(key, value, expectedType) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const cleanedArray = value.filter((t) => typeof t === 'string')
|
||||
return [...new Set(cleanedArray.map((t) => t.trim()).filter((t) => t))]
|
||||
return dedupeNames(value)
|
||||
}
|
||||
|
||||
Logger.warn(`[abmetadataGenerator] Unknown expected type "${expectedType}" for key "${key}"`)
|
||||
|
||||
@@ -35,6 +35,28 @@ module.exports.nameToLastFirst = (firstLast) => {
|
||||
return `${nameObj.last_name}, ${nameObj.first_name}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Trim names, drop blanks, and drop exact repeats. The first spelling is kept.
|
||||
* Callers that build bookAuthors rows should use this instead of deduping per metadata source.
|
||||
*
|
||||
* @param {string[]} names
|
||||
* @returns {string[]}
|
||||
*/
|
||||
function dedupeNames(names) {
|
||||
if (!Array.isArray(names)) return []
|
||||
const seen = new Set()
|
||||
const deduped = []
|
||||
for (const name of names) {
|
||||
if (typeof name !== 'string') continue
|
||||
const trimmed = name.trim()
|
||||
if (!trimmed || seen.has(trimmed)) continue
|
||||
seen.add(trimmed)
|
||||
deduped.push(trimmed)
|
||||
}
|
||||
return deduped
|
||||
}
|
||||
module.exports.dedupeNames = dedupeNames
|
||||
|
||||
/**
|
||||
* Parses a name string into an array of names
|
||||
*
|
||||
@@ -62,7 +84,7 @@ module.exports.parse = (nameString) => {
|
||||
// If names are in Chinese,Japanese and Korean languages, return as is.
|
||||
if (/[\u4e00-\u9fff\u3040-\u30ff\u31f0-\u31ff]/.test(splitNames[0])) {
|
||||
return {
|
||||
names: splitNames
|
||||
names: dedupeNames(splitNames)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,7 +124,7 @@ module.exports.parse = (nameString) => {
|
||||
names = names.filter((n) => n.first_name || n.last_name)
|
||||
|
||||
// Set name strings and remove duplicates
|
||||
const namesArray = [...new Set(names.map((a) => (a.first_name ? `${a.first_name} ${a.last_name}` : a.last_name)))]
|
||||
const namesArray = dedupeNames(names.map((a) => (a.first_name ? `${a.first_name} ${a.last_name}` : a.last_name)))
|
||||
|
||||
return {
|
||||
names: namesArray // Array of first last
|
||||
|
||||
@@ -242,7 +242,9 @@ module.exports = {
|
||||
if (!user.canAccessExplicitContent) {
|
||||
attrQuery += ' AND b.explicit = 0'
|
||||
}
|
||||
if (!user.permissions?.accessAllTags && user.permissions?.itemTagsSelected?.length) {
|
||||
if (!user.permissions?.accessAllTags && !user.permissions?.selectedTagsNotAccessible && !user.permissions?.itemTagsSelected?.length) {
|
||||
attrQuery += ' AND 0'
|
||||
} else if (!user.permissions?.accessAllTags && user.permissions?.itemTagsSelected?.length) {
|
||||
if (user.permissions.selectedTagsNotAccessible) {
|
||||
attrQuery += ' AND (SELECT count(*) FROM json_each(tags) WHERE json_valid(tags) AND json_each.value IN (:userTagsSelected)) = 0'
|
||||
} else {
|
||||
|
||||
@@ -24,7 +24,10 @@ module.exports = {
|
||||
explicit: false
|
||||
})
|
||||
}
|
||||
if (!user.permissions?.accessAllTags && user.permissions?.itemTagsSelected?.length) {
|
||||
if (!user.permissions?.accessAllTags && !user.permissions?.selectedTagsNotAccessible && !user.permissions?.itemTagsSelected?.length) {
|
||||
// Empty allow-list: the per-item check denies every item. An empty block-list denies nothing.
|
||||
bookWhere.push(Sequelize.where(Sequelize.literal('1'), 0))
|
||||
} else if (!user.permissions?.accessAllTags && user.permissions?.itemTagsSelected?.length) {
|
||||
replacements['userTagsSelected'] = user.permissions.itemTagsSelected
|
||||
if (user.permissions.selectedTagsNotAccessible) {
|
||||
bookWhere.push(Sequelize.where(Sequelize.literal(`(SELECT count(*) FROM json_each(tags) WHERE json_valid(tags) AND json_each.value IN (:userTagsSelected))`), 0))
|
||||
|
||||
@@ -21,7 +21,10 @@ module.exports = {
|
||||
})
|
||||
}
|
||||
|
||||
if (!user.permissions?.accessAllTags && user.permissions?.itemTagsSelected?.length) {
|
||||
if (!user.permissions?.accessAllTags && !user.permissions?.selectedTagsNotAccessible && !user.permissions?.itemTagsSelected?.length) {
|
||||
// Empty allow-list: the per-item check denies every item. An empty block-list denies nothing.
|
||||
podcastWhere.push(Sequelize.where(Sequelize.literal('1'), 0))
|
||||
} else if (!user.permissions?.accessAllTags && user.permissions?.itemTagsSelected?.length) {
|
||||
replacements['userTagsSelected'] = user.permissions.itemTagsSelected
|
||||
if (user.permissions.selectedTagsNotAccessible) {
|
||||
podcastWhere.push(Sequelize.where(Sequelize.literal(`(SELECT count(*) FROM json_each(tags) WHERE json_valid(tags) AND json_each.value IN (:userTagsSelected))`), 0))
|
||||
|
||||
@@ -102,7 +102,9 @@ module.exports = {
|
||||
if (!user.canAccessExplicitContent) {
|
||||
attrQuery += ' AND b.explicit = 0'
|
||||
}
|
||||
if (!user.permissions?.accessAllTags && user.permissions?.itemTagsSelected?.length) {
|
||||
if (!user.permissions?.accessAllTags && !user.permissions?.selectedTagsNotAccessible && !user.permissions?.itemTagsSelected?.length) {
|
||||
attrQuery += ' AND 0'
|
||||
} else if (!user.permissions?.accessAllTags && user.permissions?.itemTagsSelected?.length) {
|
||||
if (user.permissions.selectedTagsNotAccessible) {
|
||||
attrQuery += ' AND (SELECT count(*) FROM json_each(tags) WHERE json_valid(tags) AND json_each.value IN (:userTagsSelected)) = 0'
|
||||
} else {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
const { rateLimit, RateLimitRequestHandler } = require('express-rate-limit')
|
||||
const Logger = require('../Logger')
|
||||
const requestIp = require('../libs/requestIp')
|
||||
|
||||
/**
|
||||
* Factory for creating authentication rate limiters
|
||||
@@ -8,9 +7,96 @@ const requestIp = require('../libs/requestIp')
|
||||
class RateLimiterFactory {
|
||||
static DEFAULT_WINDOW_MS = 10 * 60 * 1000 // 10 minutes
|
||||
static DEFAULT_MAX = 40 // 40 attempts
|
||||
static LOCAL_LOGIN_KEY = 'local-login'
|
||||
static UNKNOWN_USER_KEY = 'unknown-user'
|
||||
|
||||
constructor() {
|
||||
this.authRateLimiter = null
|
||||
this.passwordChangeRateLimiter = null
|
||||
this.disabledLimiter = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared window, max, and message. Null when rate limiting is disabled.
|
||||
* @returns {{ windowMs: number, max: number, message: string } | null}
|
||||
*/
|
||||
getLimiterConfig() {
|
||||
// Disable by setting max to 0
|
||||
if (process.env.RATE_LIMIT_AUTH_MAX === '0') {
|
||||
return null
|
||||
}
|
||||
|
||||
let windowMs = RateLimiterFactory.DEFAULT_WINDOW_MS
|
||||
if (parseInt(process.env.RATE_LIMIT_AUTH_WINDOW) > 0) {
|
||||
windowMs = parseInt(process.env.RATE_LIMIT_AUTH_WINDOW)
|
||||
}
|
||||
|
||||
let max = RateLimiterFactory.DEFAULT_MAX
|
||||
if (parseInt(process.env.RATE_LIMIT_AUTH_MAX) > 0) {
|
||||
max = parseInt(process.env.RATE_LIMIT_AUTH_MAX)
|
||||
}
|
||||
|
||||
let message = 'Too many authentication requests'
|
||||
if (process.env.RATE_LIMIT_AUTH_MESSAGE) {
|
||||
message = process.env.RATE_LIMIT_AUTH_MESSAGE
|
||||
}
|
||||
|
||||
return { windowMs, max, message }
|
||||
}
|
||||
|
||||
/**
|
||||
* Log non-default limiter settings once per process.
|
||||
* @param {{ windowMs: number, max: number }} config
|
||||
*/
|
||||
logCustomLimiterConfig(config) {
|
||||
if (this.loggedCustomConfig) return
|
||||
this.loggedCustomConfig = true
|
||||
|
||||
if (config.windowMs !== RateLimiterFactory.DEFAULT_WINDOW_MS) {
|
||||
Logger.info(`[RateLimiterFactory] Authentication rate limiting window set to ${config.windowMs}ms by ENV variable`)
|
||||
}
|
||||
if (config.max !== RateLimiterFactory.DEFAULT_MAX) {
|
||||
Logger.info(`[RateLimiterFactory] Authentication rate limiting max set to ${config.max} by ENV variable`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {RateLimitRequestHandler}
|
||||
*/
|
||||
getDisabledLimiter() {
|
||||
if (!this.disabledLimiter) {
|
||||
this.disabledLimiter = (req, res, next) => next()
|
||||
}
|
||||
return this.disabledLimiter
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ windowMs: number, max: number, message: string }} config
|
||||
* @param {(req: import('express').Request) => string} keyGenerator
|
||||
* @returns {RateLimitRequestHandler}
|
||||
*/
|
||||
createLimiter(config, keyGenerator) {
|
||||
return rateLimit({
|
||||
windowMs: config.windowMs,
|
||||
max: config.max,
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
keyGenerator,
|
||||
skipSuccessfulRequests: true,
|
||||
handler: (req, res) => {
|
||||
const userAgent = req.get('User-Agent') || 'Unknown'
|
||||
const endpoint = req.path
|
||||
const method = req.method
|
||||
const userId = req.user?.id
|
||||
const userLabel = userId ? `, User: ${userId}` : ''
|
||||
|
||||
Logger.warn(`[RateLimiter] Rate limit exceeded - Endpoint: ${method} ${endpoint}${userLabel}, User-Agent: ${userAgent}`)
|
||||
|
||||
res.status(429).json({
|
||||
error: config.message
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -22,61 +108,49 @@ class RateLimiterFactory {
|
||||
return this.authRateLimiter
|
||||
}
|
||||
|
||||
// Disable by setting max to 0
|
||||
if (process.env.RATE_LIMIT_AUTH_MAX === '0') {
|
||||
this.authRateLimiter = (req, res, next) => next()
|
||||
const config = this.getLimiterConfig()
|
||||
if (!config) {
|
||||
Logger.info(`[RateLimiterFactory] Authentication rate limiting disabled by ENV variable`)
|
||||
this.authRateLimiter = this.getDisabledLimiter()
|
||||
return this.authRateLimiter
|
||||
}
|
||||
|
||||
let windowMs = RateLimiterFactory.DEFAULT_WINDOW_MS
|
||||
if (parseInt(process.env.RATE_LIMIT_AUTH_WINDOW) > 0) {
|
||||
windowMs = parseInt(process.env.RATE_LIMIT_AUTH_WINDOW)
|
||||
if (windowMs !== RateLimiterFactory.DEFAULT_WINDOW_MS) {
|
||||
Logger.info(`[RateLimiterFactory] Authentication rate limiting window set to ${windowMs}ms by ENV variable`)
|
||||
}
|
||||
}
|
||||
this.logCustomLimiterConfig(config)
|
||||
|
||||
let max = RateLimiterFactory.DEFAULT_MAX
|
||||
if (parseInt(process.env.RATE_LIMIT_AUTH_MAX) > 0) {
|
||||
max = parseInt(process.env.RATE_LIMIT_AUTH_MAX)
|
||||
if (max !== RateLimiterFactory.DEFAULT_MAX) {
|
||||
Logger.info(`[RateLimiterFactory] Authentication rate limiting max set to ${max} by ENV variable`)
|
||||
}
|
||||
}
|
||||
// One process-wide bucket of failed local logins. Do not key on client IP headers.
|
||||
this.authRateLimiter = this.createLimiter(config, () => RateLimiterFactory.LOCAL_LOGIN_KEY)
|
||||
|
||||
let message = 'Too many authentication requests'
|
||||
if (process.env.RATE_LIMIT_AUTH_MESSAGE) {
|
||||
message = process.env.RATE_LIMIT_AUTH_MESSAGE
|
||||
}
|
||||
|
||||
this.authRateLimiter = rateLimit({
|
||||
windowMs,
|
||||
max,
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
keyGenerator: (req) => {
|
||||
// Override keyGenerator to handle proxy IPs
|
||||
return requestIp.getClientIp(req) || req.ip
|
||||
},
|
||||
handler: (req, res) => {
|
||||
const userAgent = req.get('User-Agent') || 'Unknown'
|
||||
const endpoint = req.path
|
||||
const method = req.method
|
||||
const ip = requestIp.getClientIp(req) || req.ip
|
||||
|
||||
Logger.warn(`[RateLimiter] Rate limit exceeded - IP: ${ip}, Endpoint: ${method} ${endpoint}, User-Agent: ${userAgent}`)
|
||||
|
||||
res.status(429).json({
|
||||
error: message
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
Logger.debug(`[RateLimiterFactory] Created auth rate limiter: ${max} attempts per ${windowMs / 1000 / 60} minutes`)
|
||||
Logger.debug(`[RateLimiterFactory] Created auth rate limiter: ${config.max} failed attempts per ${config.windowMs / 1000 / 60} minutes`)
|
||||
|
||||
return this.authRateLimiter
|
||||
}
|
||||
|
||||
/**
|
||||
* Failed current-password checks on PATCH /me/password, keyed by the authenticated user.
|
||||
* @returns {RateLimitRequestHandler}
|
||||
*/
|
||||
getPasswordChangeRateLimiter() {
|
||||
if (this.passwordChangeRateLimiter) {
|
||||
return this.passwordChangeRateLimiter
|
||||
}
|
||||
|
||||
const config = this.getLimiterConfig()
|
||||
if (!config) {
|
||||
this.passwordChangeRateLimiter = this.getDisabledLimiter()
|
||||
return this.passwordChangeRateLimiter
|
||||
}
|
||||
|
||||
this.logCustomLimiterConfig(config)
|
||||
|
||||
this.passwordChangeRateLimiter = this.createLimiter(config, (req) => {
|
||||
const userId = req.user?.id
|
||||
return userId ? String(userId) : RateLimiterFactory.UNKNOWN_USER_KEY
|
||||
})
|
||||
|
||||
Logger.debug(`[RateLimiterFactory] Created password change rate limiter: ${config.max} failed attempts per ${config.windowMs / 1000 / 60} minutes`)
|
||||
|
||||
return this.passwordChangeRateLimiter
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new RateLimiterFactory()
|
||||
@@ -0,0 +1,366 @@
|
||||
const Path = require('path')
|
||||
const { Op, where, fn, col } = require('sequelize')
|
||||
const fs = require('../libs/fsExtra')
|
||||
const Database = require('../Database')
|
||||
const Logger = require('../Logger')
|
||||
const { filePathToPOSIX, isSameOrSubPath, isStrictSubPath } = require('./fileUtils')
|
||||
|
||||
/**
|
||||
* Stable codes for new upload failures. `error` stays an English sentence so older clients
|
||||
* can keep displaying the body. Existing plain-text 400/404 responses are unchanged.
|
||||
*/
|
||||
const UPLOAD_ERROR_CODE = {
|
||||
pathExists: 'UPLOAD_PATH_EXISTS',
|
||||
libraryItemExists: 'UPLOAD_LIBRARY_ITEM_EXISTS',
|
||||
duplicateFileName: 'UPLOAD_DUPLICATE_FILENAME',
|
||||
folderNotWritable: 'UPLOAD_FOLDER_NOT_WRITABLE'
|
||||
}
|
||||
const UPLOAD_PATH_EXISTS_MESSAGE = 'File already exists'
|
||||
const UPLOAD_LIBRARY_ITEM_EXISTS_PREFIX = 'Library item exists: '
|
||||
const UPLOAD_DUPLICATE_FILENAME_MESSAGE = 'Duplicate file name in upload'
|
||||
const UPLOAD_FOLDER_NOT_WRITABLE_MESSAGE = 'Cannot write to this library folder'
|
||||
const UPLOAD_INVALID_PATH_MESSAGE = 'Invalid upload path'
|
||||
const UPLOAD_INVALID_FILENAME_MESSAGE = 'Invalid file name'
|
||||
const UPLOAD_FORBIDDEN_MESSAGE = 'Forbidden'
|
||||
const PLAIN_TEXT_UPLOAD_ERRORS = [UPLOAD_INVALID_PATH_MESSAGE, UPLOAD_INVALID_FILENAME_MESSAGE]
|
||||
|
||||
module.exports.UPLOAD_ERROR_CODE = UPLOAD_ERROR_CODE
|
||||
module.exports.UPLOAD_PATH_EXISTS_MESSAGE = UPLOAD_PATH_EXISTS_MESSAGE
|
||||
module.exports.UPLOAD_LIBRARY_ITEM_EXISTS_PREFIX = UPLOAD_LIBRARY_ITEM_EXISTS_PREFIX
|
||||
module.exports.UPLOAD_DUPLICATE_FILENAME_MESSAGE = UPLOAD_DUPLICATE_FILENAME_MESSAGE
|
||||
module.exports.UPLOAD_FOLDER_NOT_WRITABLE_MESSAGE = UPLOAD_FOLDER_NOT_WRITABLE_MESSAGE
|
||||
module.exports.PLAIN_TEXT_UPLOAD_ERRORS = PLAIN_TEXT_UPLOAD_ERRORS
|
||||
|
||||
/**
|
||||
* Paths of library items this upload would be nested inside (issue #4146).
|
||||
* At most two levels above the upload directory, matching the previous pathexists check.
|
||||
*
|
||||
* @param {string} folderPath
|
||||
* @param {string} outputDirectory
|
||||
* @returns {string[]}
|
||||
*/
|
||||
function parentLibraryItemPaths(folderPath, outputDirectory) {
|
||||
const relative = filePathToPOSIX(Path.relative(folderPath, outputDirectory))
|
||||
if (!relative || relative === '.' || relative === '..' || relative.startsWith('../') || !relative.includes('/')) return []
|
||||
|
||||
const parent = Path.posix.dirname(relative)
|
||||
const paths = [filePathToPOSIX(Path.join(folderPath, parent))]
|
||||
if (parent.includes('/')) {
|
||||
paths.push(filePathToPOSIX(Path.join(folderPath, Path.posix.dirname(parent))))
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
/**
|
||||
* Windows and macOS treat paths that differ only by case as the same directory.
|
||||
* A case-sensitive match would miss `Author A/Book B` and write `author a/book b/extra` inside it.
|
||||
*
|
||||
* @param {string[]} paths
|
||||
* @returns {import('sequelize').WhereOptions}
|
||||
*/
|
||||
function libraryItemPathWhere(paths) {
|
||||
if (global.isWin || process.platform === 'darwin') {
|
||||
// Apply SQL lower() on both sides so both match SQLite's active lower() implementation
|
||||
// (Unicode via libnusqlite3 when loaded, or ASCII fallback without breaking exact Unicode matches).
|
||||
return where(fn('lower', col('path')), {
|
||||
[Op.in]: paths.map((libraryItemPath) => fn('lower', libraryItemPath))
|
||||
})
|
||||
}
|
||||
return { path: paths }
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} folderPath
|
||||
* @param {string} outputDirectory
|
||||
* @returns {Promise<import('../models/LibraryItem') | null>}
|
||||
*/
|
||||
async function libraryItemContainingUpload(folderPath, outputDirectory) {
|
||||
const paths = parentLibraryItemPaths(folderPath, outputDirectory)
|
||||
if (!paths.length) return null
|
||||
return Database.libraryItemModel.findOne({
|
||||
where: libraryItemPathWhere(paths)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} outputDirectory
|
||||
* @returns {Promise<import('../models/LibraryItem').LibraryItemExpanded | null>}
|
||||
*/
|
||||
async function libraryItemAtPath(outputDirectory) {
|
||||
return Database.libraryItemModel.findOneExpanded(libraryItemPathWhere([filePathToPOSIX(outputDirectory)]))
|
||||
}
|
||||
|
||||
class UploadError extends Error {
|
||||
/**
|
||||
* A code makes the response JSON `{ code, error, ...details }`. Without one, the response stays the plain message.
|
||||
*
|
||||
* @param {number} statusCode
|
||||
* @param {string} message plain-text response, also used as Error.message and as the JSON `error`
|
||||
* @param {string | null} [code]
|
||||
* @param {object} [details] extra JSON fields, such as libraryItemTitle
|
||||
*/
|
||||
constructor(statusCode, message, code = null, details = {}) {
|
||||
super(message)
|
||||
this.name = 'UploadError'
|
||||
this.statusCode = statusCode
|
||||
this.body = code ? { code, error: message, ...details } : null
|
||||
}
|
||||
}
|
||||
module.exports.UploadError = UploadError
|
||||
|
||||
/**
|
||||
* Shared lookup for the upload handler and POST /api/filesystem/pathexists.
|
||||
* Throws when the path escapes the library folder.
|
||||
*
|
||||
* @param {string} folderPath
|
||||
* @param {string} outputDirectory
|
||||
* @returns {Promise<{ exists: boolean, libraryItemTitle?: string }>}
|
||||
*/
|
||||
async function lookupUploadDirectory(folderPath, outputDirectory) {
|
||||
if (!isSameOrSubPath(folderPath, outputDirectory)) {
|
||||
throw new UploadError(400, UPLOAD_INVALID_PATH_MESSAGE)
|
||||
}
|
||||
if (await fs.pathExists(outputDirectory)) {
|
||||
return { exists: true }
|
||||
}
|
||||
|
||||
const libraryItem = await libraryItemContainingUpload(folderPath, outputDirectory)
|
||||
if (libraryItem) {
|
||||
return { exists: true, libraryItemTitle: libraryItem.title || '' }
|
||||
}
|
||||
return { exists: false }
|
||||
}
|
||||
|
||||
/**
|
||||
* Throw when this upload must not be written.
|
||||
* Allows adding non-conflicting files to an existing directory when the user has update permission
|
||||
* (and access to any matching library item), and overwriting existing regular files only when
|
||||
* `overwrite` is true. Nested uploads inside an existing library item are always refused.
|
||||
*
|
||||
* @param {string} folderPath
|
||||
* @param {string} outputDirectory absolute directory the files would be written into
|
||||
* @param {string[]} filenames sanitized file names
|
||||
* @param {import('../models/User') | null} [user]
|
||||
* @param {boolean} [overwrite]
|
||||
* @returns {Promise<{ directoryExists: boolean, existingFiles: Set<string> }>}
|
||||
*/
|
||||
async function assertUploadDestination(folderPath, outputDirectory, filenames, user = null, overwrite = false) {
|
||||
// The library folder itself is not a valid item directory, even when every name sanitized away.
|
||||
if (!isStrictSubPath(folderPath, outputDirectory)) {
|
||||
throw new UploadError(400, UPLOAD_INVALID_PATH_MESSAGE)
|
||||
}
|
||||
|
||||
const seen = new Set()
|
||||
for (const name of filenames) {
|
||||
if (!name) throw new UploadError(400, UPLOAD_INVALID_FILENAME_MESSAGE)
|
||||
const key = name.toLowerCase()
|
||||
if (seen.has(key)) throw new UploadError(409, UPLOAD_DUPLICATE_FILENAME_MESSAGE, UPLOAD_ERROR_CODE.duplicateFileName)
|
||||
seen.add(key)
|
||||
}
|
||||
|
||||
const parentLibraryItem = await libraryItemContainingUpload(folderPath, outputDirectory)
|
||||
if (parentLibraryItem) {
|
||||
const libraryItemTitle = parentLibraryItem.title || ''
|
||||
const message = `${UPLOAD_LIBRARY_ITEM_EXISTS_PREFIX}${libraryItemTitle}`
|
||||
throw new UploadError(409, message, UPLOAD_ERROR_CODE.libraryItemExists, { libraryItemTitle })
|
||||
}
|
||||
|
||||
let dirStat = null
|
||||
try {
|
||||
dirStat = await fs.lstat(outputDirectory)
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOTDIR') {
|
||||
throw new UploadError(409, UPLOAD_PATH_EXISTS_MESSAGE, UPLOAD_ERROR_CODE.pathExists)
|
||||
}
|
||||
if (error.code !== 'ENOENT') {
|
||||
const notWritable = notWritableUploadError(error)
|
||||
if (notWritable) throw notWritable
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
if (!dirStat) {
|
||||
return { directoryExists: false, existingFiles: new Set() }
|
||||
}
|
||||
|
||||
if (!dirStat.isDirectory()) {
|
||||
throw new UploadError(409, UPLOAD_PATH_EXISTS_MESSAGE, UPLOAD_ERROR_CODE.pathExists)
|
||||
}
|
||||
|
||||
if (!user?.canUpdate) {
|
||||
throw new UploadError(403, UPLOAD_FORBIDDEN_MESSAGE)
|
||||
}
|
||||
|
||||
const existingLibraryItem = await libraryItemAtPath(outputDirectory)
|
||||
if (existingLibraryItem && !user.checkCanAccessLibraryItem(existingLibraryItem)) {
|
||||
throw new UploadError(403, UPLOAD_FORBIDDEN_MESSAGE)
|
||||
}
|
||||
|
||||
const existingFiles = new Set()
|
||||
for (const name of filenames) {
|
||||
const targetPath = Path.join(outputDirectory, name)
|
||||
let targetStat = null
|
||||
try {
|
||||
targetStat = await fs.lstat(targetPath)
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') continue
|
||||
const notWritable = notWritableUploadError(error)
|
||||
if (notWritable) throw notWritable
|
||||
throw error
|
||||
}
|
||||
|
||||
if (targetStat.isDirectory() || targetStat.isSymbolicLink() || !overwrite) {
|
||||
throw new UploadError(409, UPLOAD_PATH_EXISTS_MESSAGE, UPLOAD_ERROR_CODE.pathExists)
|
||||
}
|
||||
existingFiles.add(name)
|
||||
}
|
||||
|
||||
return { directoryExists: true, existingFiles }
|
||||
}
|
||||
module.exports.assertUploadDestination = assertUploadDestination
|
||||
|
||||
/**
|
||||
* POST /api/filesystem/pathexists. `directory` is the client path relative to the library folder.
|
||||
*
|
||||
* @param {string} folderPath
|
||||
* @param {string} directory
|
||||
* @returns {Promise<{ exists: boolean, libraryItemTitle?: string }>}
|
||||
*/
|
||||
async function checkUploadDirectory(folderPath, directory) {
|
||||
return lookupUploadDirectory(folderPath, Path.join(folderPath, directory))
|
||||
}
|
||||
module.exports.checkUploadDirectory = checkUploadDirectory
|
||||
|
||||
const NOT_WRITABLE_CODES = ['EACCES', 'EPERM', 'EROFS']
|
||||
|
||||
/**
|
||||
* Permission errors from mkdir or move. Null for every other failure.
|
||||
*
|
||||
* @param {NodeJS.ErrnoException} error
|
||||
* @returns {UploadError | null}
|
||||
*/
|
||||
function notWritableUploadError(error) {
|
||||
if (!error || !NOT_WRITABLE_CODES.includes(error.code)) return null
|
||||
return new UploadError(403, UPLOAD_FOLDER_NOT_WRITABLE_MESSAGE, UPLOAD_ERROR_CODE.folderNotWritable)
|
||||
}
|
||||
module.exports.notWritableUploadError = notWritableUploadError
|
||||
|
||||
/**
|
||||
* Create the upload directory. Returns the first parent this call created, or null when
|
||||
* every parent already existed. The leaf mkdir is not recursive: an existing directory
|
||||
* would count as success, and a later failure would delete it.
|
||||
*
|
||||
* @param {string} outputDirectory
|
||||
* @returns {Promise<string | null>}
|
||||
*/
|
||||
async function createUploadDirectory(outputDirectory) {
|
||||
let firstCreated = null
|
||||
try {
|
||||
firstCreated = (await fs.mkdir(Path.dirname(outputDirectory), { recursive: true })) || null
|
||||
await fs.mkdir(outputDirectory)
|
||||
} catch (error) {
|
||||
if (firstCreated) await removeEmptyCreatedDirectories(Path.dirname(outputDirectory), firstCreated)
|
||||
// An existing directory is EEXIST. A parent segment that is a file is ENOTDIR on Linux and macOS, and EEXIST on Windows.
|
||||
if (error.code === 'EEXIST' || error.code === 'ENOTDIR') {
|
||||
throw new UploadError(409, UPLOAD_PATH_EXISTS_MESSAGE, UPLOAD_ERROR_CODE.pathExists)
|
||||
}
|
||||
const notWritable = notWritableUploadError(error)
|
||||
if (notWritable) throw notWritable
|
||||
throw error
|
||||
}
|
||||
return firstCreated
|
||||
}
|
||||
module.exports.createUploadDirectory = createUploadDirectory
|
||||
|
||||
/**
|
||||
* Remove empty directories this request created, from deepest up through firstCreated.
|
||||
* Directories that already existed are left alone, including empty ones.
|
||||
*
|
||||
* @param {string} deepest
|
||||
* @param {string} firstCreated
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function removeEmptyCreatedDirectories(deepest, firstCreated) {
|
||||
if (!firstCreated) return
|
||||
let current = deepest
|
||||
while (isSameOrSubPath(firstCreated, current)) {
|
||||
let names
|
||||
try {
|
||||
names = await fs.readdir(current)
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') return
|
||||
Logger.error('[uploadPath] Failed to read upload directory during rollback', current, error)
|
||||
return
|
||||
}
|
||||
if (names.length) return
|
||||
try {
|
||||
await fs.rmdir(current)
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') {
|
||||
Logger.error('[uploadPath] Failed to remove upload directory', current, error)
|
||||
}
|
||||
return
|
||||
}
|
||||
current = Path.dirname(current)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically reserve a destination file path so a concurrent upload cannot overwrite it.
|
||||
*
|
||||
* @param {string} targetPath
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function reserveUploadFile(targetPath) {
|
||||
let fd
|
||||
try {
|
||||
fd = await fs.open(targetPath, 'wx')
|
||||
} catch (error) {
|
||||
if (error.code === 'EEXIST' || error.code === 'EISDIR') {
|
||||
throw new UploadError(409, UPLOAD_PATH_EXISTS_MESSAGE, UPLOAD_ERROR_CODE.pathExists)
|
||||
}
|
||||
const notWritable = notWritableUploadError(error)
|
||||
if (notWritable) throw notWritable
|
||||
throw error
|
||||
}
|
||||
await fs.close(fd)
|
||||
}
|
||||
module.exports.reserveUploadFile = reserveUploadFile
|
||||
|
||||
/**
|
||||
* Roll back a failed upload without touching pre-existing directories or files.
|
||||
* When this request created outputDirectory, remove it and any empty parents this request created.
|
||||
* When outputDirectory already existed, remove only files created by this request.
|
||||
* Unmoved temp files are deleted by the multipart parser when the response closes.
|
||||
*
|
||||
* @param {string} outputDirectory
|
||||
* @param {string | null} firstCreated
|
||||
* @param {boolean} [createdOutputDirectory]
|
||||
* @param {string[]} [createdFiles]
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function rollbackFailedUpload(outputDirectory, firstCreated, createdOutputDirectory = true, createdFiles = []) {
|
||||
if (createdOutputDirectory) {
|
||||
try {
|
||||
await fs.remove(outputDirectory)
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') {
|
||||
Logger.error('[uploadPath] Failed to remove partial upload', outputDirectory, error)
|
||||
}
|
||||
}
|
||||
|
||||
await removeEmptyCreatedDirectories(Path.dirname(outputDirectory), firstCreated)
|
||||
return
|
||||
}
|
||||
|
||||
for (const filePath of createdFiles) {
|
||||
try {
|
||||
await fs.unlink(filePath)
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') {
|
||||
Logger.error('[uploadPath] Failed to remove partial upload file', filePath, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
module.exports.rollbackFailedUpload = rollbackFailedUpload
|
||||
@@ -54,9 +54,9 @@ module.exports.zipDirectoryPipe = (path, filename, res) => {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a zip archive containing multiple directories and streams it to the response.
|
||||
* Creates a zip archive containing multiple directories or files and streams it to the response.
|
||||
*
|
||||
* @param {{ path: string, isFile: boolean }[]} pathObjects
|
||||
* @param {{ path: string, isFile: boolean, name?: string }[]} pathObjects
|
||||
* @param {string} filename - Name of the zip file to be sent as attachment.
|
||||
* @param {Response} res - Response object to pipe the archive data to.
|
||||
* @returns {Promise<void>} - Promise that resolves when the zip operation completes.
|
||||
@@ -73,6 +73,9 @@ module.exports.zipDirectoriesPipe = (pathObjects, filename, res) => {
|
||||
// listen for all archive data to be written
|
||||
// 'close' event is fired only when a file descriptor is involved
|
||||
res.on('close', () => {
|
||||
if (!res.writableEnded) {
|
||||
archive.abort()
|
||||
}
|
||||
Logger.info(archive.pointer() + ' total bytes')
|
||||
Logger.debug('archiver has been finalized and the output file descriptor has closed.')
|
||||
resolve()
|
||||
@@ -105,13 +108,14 @@ module.exports.zipDirectoriesPipe = (pathObjects, filename, res) => {
|
||||
// pipe archive data to the file
|
||||
archive.pipe(res)
|
||||
|
||||
// Add each path as a directory in the zip
|
||||
// Add each path as a directory or file in the zip
|
||||
pathObjects.forEach((pathObject) => {
|
||||
const entryName = pathObject.name || Path.basename(pathObject.path)
|
||||
if (!pathObject.isFile) {
|
||||
// Add the directory to the archive with its name as the root folder
|
||||
archive.directory(pathObject.path, Path.basename(pathObject.path))
|
||||
archive.directory(pathObject.path, entryName)
|
||||
} else {
|
||||
archive.file(pathObject.path, { name: Path.basename(pathObject.path) })
|
||||
archive.file(pathObject.path, { name: entryName })
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
const { expect } = require('chai')
|
||||
const { Sequelize } = require('sequelize')
|
||||
const sinon = require('sinon')
|
||||
|
||||
const Database = require('../../../server/Database')
|
||||
const AuthorController = require('../../../server/controllers/AuthorController')
|
||||
const AuthorFinder = require('../../../server/finders/AuthorFinder')
|
||||
const Logger = require('../../../server/Logger')
|
||||
|
||||
const unsafeDescription = '<p>Hello</p><script>alert(1)</script><img src="x" onerror="alert(document.domain)"><a href="https://example.com">link</a>'
|
||||
const safeDescription = '<p>Hello</p><a href="https://example.com">link</a>'
|
||||
|
||||
describe('AuthorController', () => {
|
||||
beforeEach(async () => {
|
||||
global.ServerSettings = {}
|
||||
Database.sequelize = new Sequelize({ dialect: 'sqlite', storage: ':memory:', logging: false })
|
||||
Database.sequelize.uppercaseFirst = (str) => (str ? `${str[0].toUpperCase()}${str.substr(1)}` : '')
|
||||
await Database.buildModels()
|
||||
|
||||
sinon.stub(Logger, 'info')
|
||||
sinon.stub(Logger, 'debug')
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
sinon.restore()
|
||||
|
||||
// Clear all tables
|
||||
await Database.sequelize.sync({ force: true })
|
||||
})
|
||||
|
||||
/**
|
||||
* @param {string} [description]
|
||||
*/
|
||||
async function createAuthor(description) {
|
||||
const library = await Database.libraryModel.create({ name: 'Test Library', mediaType: 'book' })
|
||||
return Database.authorModel.create({
|
||||
name: 'Test Author',
|
||||
libraryId: library.id,
|
||||
description: description || null
|
||||
})
|
||||
}
|
||||
|
||||
describe('update', () => {
|
||||
it('should store and return a sanitized description', async () => {
|
||||
const author = await createAuthor()
|
||||
const fakeReq = {
|
||||
body: {
|
||||
description: unsafeDescription
|
||||
},
|
||||
author
|
||||
}
|
||||
const fakeRes = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy(),
|
||||
json: sinon.spy()
|
||||
}
|
||||
|
||||
await AuthorController.update(fakeReq, fakeRes)
|
||||
|
||||
expect(fakeRes.json.calledOnce).to.be.true
|
||||
const response = fakeRes.json.firstCall.args[0]
|
||||
expect(response.updated).to.be.true
|
||||
expect(response.author.description).to.equal(safeDescription)
|
||||
expect(response.author.description).to.not.include('script')
|
||||
expect(response.author.description).to.not.include('onerror')
|
||||
|
||||
const stored = await Database.authorModel.findByPk(author.id)
|
||||
expect(stored.description).to.equal(safeDescription)
|
||||
})
|
||||
|
||||
it('should store null when sanitizing leaves an empty description', async () => {
|
||||
const author = await createAuthor('<p>Existing</p>')
|
||||
const fakeReq = {
|
||||
body: {
|
||||
description: '<script>alert(1)</script><img src="x" onerror="alert(1)">'
|
||||
},
|
||||
author
|
||||
}
|
||||
const fakeRes = {
|
||||
json: sinon.spy()
|
||||
}
|
||||
|
||||
await AuthorController.update(fakeReq, fakeRes)
|
||||
|
||||
const response = fakeRes.json.firstCall.args[0]
|
||||
expect(response.author.description).to.equal(null)
|
||||
|
||||
const stored = await Database.authorModel.findByPk(author.id)
|
||||
expect(stored.description).to.equal(null)
|
||||
})
|
||||
})
|
||||
|
||||
describe('toOldJSON', () => {
|
||||
it('should sanitize a stored description without rewriting the row', async () => {
|
||||
const author = await createAuthor(unsafeDescription)
|
||||
|
||||
expect(author.toOldJSON().description).to.equal(safeDescription)
|
||||
expect(author.description).to.equal(unsafeDescription)
|
||||
|
||||
const stored = await Database.authorModel.findByPk(author.id)
|
||||
expect(stored.description).to.equal(unsafeDescription)
|
||||
expect(stored.toOldJSON().description).to.equal(safeDescription)
|
||||
})
|
||||
})
|
||||
|
||||
describe('match', () => {
|
||||
it('should store the sanitized Audnexus description', async () => {
|
||||
const author = await createAuthor()
|
||||
sinon.stub(AuthorFinder, 'findAuthorByASIN').resolves({
|
||||
asin: 'B00TEST000',
|
||||
name: 'Test Author',
|
||||
description: '<p>Bio</p><script>alert(1)</script>',
|
||||
image: null
|
||||
})
|
||||
|
||||
const fakeReq = {
|
||||
body: {
|
||||
asin: 'B00TEST000'
|
||||
},
|
||||
author
|
||||
}
|
||||
const fakeRes = {
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy(),
|
||||
json: sinon.spy()
|
||||
}
|
||||
|
||||
await AuthorController.match(fakeReq, fakeRes)
|
||||
|
||||
expect(fakeRes.json.calledOnce).to.be.true
|
||||
const response = fakeRes.json.firstCall.args[0]
|
||||
expect(response.updated).to.be.true
|
||||
expect(response.author.description).to.equal('<p>Bio</p>')
|
||||
|
||||
const stored = await Database.authorModel.findByPk(author.id)
|
||||
expect(stored.description).to.equal('<p>Bio</p>')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,113 @@
|
||||
const { expect } = require('chai')
|
||||
const { Sequelize } = require('sequelize')
|
||||
const sinon = require('sinon')
|
||||
|
||||
const Database = require('../../../server/Database')
|
||||
const Logger = require('../../../server/Logger')
|
||||
const CollectionController = require('../../../server/controllers/CollectionController')
|
||||
|
||||
describe('CollectionController', () => {
|
||||
/** @type {import('../../../server/models/Collection')} */
|
||||
let collection
|
||||
/** @type {import('../../../server/models/LibraryItem')} */
|
||||
let libraryItem
|
||||
|
||||
beforeEach(async () => {
|
||||
global.ServerSettings = {}
|
||||
Database.sequelize = new Sequelize({ dialect: 'sqlite', storage: ':memory:', logging: false })
|
||||
Database.sequelize.uppercaseFirst = (str) => (str ? `${str[0].toUpperCase()}${str.substr(1)}` : '')
|
||||
await Database.buildModels()
|
||||
|
||||
sinon.stub(Logger, 'info')
|
||||
sinon.stub(Logger, 'debug')
|
||||
sinon.stub(Logger, 'warn')
|
||||
sinon.stub(Logger, 'error')
|
||||
|
||||
const library = await Database.libraryModel.create({ name: 'Test Library', mediaType: 'book' })
|
||||
const libraryFolder = await Database.libraryFolderModel.create({ path: '/test-lib', libraryId: library.id })
|
||||
const book = await Database.bookModel.create({ title: 'Test Book', audioFiles: [], tags: [], narrators: [], genres: [], chapters: [] })
|
||||
libraryItem = await Database.libraryItemModel.create({
|
||||
path: '/test-lib/book',
|
||||
isFile: false,
|
||||
libraryFiles: [],
|
||||
mediaId: book.id,
|
||||
mediaType: 'book',
|
||||
libraryId: library.id,
|
||||
libraryFolderId: libraryFolder.id
|
||||
})
|
||||
collection = await Database.collectionModel.create({ name: 'Test Collection', libraryId: library.id })
|
||||
await Database.collectionBookModel.create({ collectionId: collection.id, bookId: book.id, order: 1 })
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
sinon.restore()
|
||||
await Database.sequelize.sync({ force: true })
|
||||
})
|
||||
|
||||
it('does not throw when the collectionBook link already exists', async () => {
|
||||
sinon.stub(collection, 'getCollectionBooks').resolves([])
|
||||
|
||||
const res = {
|
||||
statusCode: null,
|
||||
body: null,
|
||||
status(code) {
|
||||
this.statusCode = code
|
||||
return this
|
||||
},
|
||||
send(body) {
|
||||
this.body = body
|
||||
return this
|
||||
},
|
||||
json(body) {
|
||||
this.body = body
|
||||
return this
|
||||
}
|
||||
}
|
||||
|
||||
await CollectionController.addBook({ body: { id: libraryItem.id }, collection, user: { id: 'user-id' } }, res)
|
||||
|
||||
expect(res.statusCode).to.equal(400)
|
||||
expect(res.body).to.equal('Book already in collection')
|
||||
const links = await Database.collectionBookModel.findAll({ where: { collectionId: collection.id, bookId: libraryItem.mediaId } })
|
||||
expect(links).to.have.lengthOf(1)
|
||||
})
|
||||
|
||||
it('does not throw when a batch includes a book already in the collection', async () => {
|
||||
const book = await Database.bookModel.create({ title: 'Second Book', audioFiles: [], tags: [], narrators: [], genres: [], chapters: [] })
|
||||
const secondItem = await Database.libraryItemModel.create({
|
||||
path: '/test-lib/book-2',
|
||||
isFile: false,
|
||||
libraryFiles: [],
|
||||
mediaId: book.id,
|
||||
mediaType: 'book',
|
||||
libraryId: libraryItem.libraryId,
|
||||
libraryFolderId: libraryItem.libraryFolderId
|
||||
})
|
||||
sinon.stub(collection, 'getCollectionBooks').resolves([])
|
||||
sinon.stub(collection, 'getOldJsonExpanded').resolves(null)
|
||||
|
||||
const res = {
|
||||
statusCode: null,
|
||||
body: null,
|
||||
status(code) {
|
||||
this.statusCode = code
|
||||
return this
|
||||
},
|
||||
send(body) {
|
||||
this.body = body
|
||||
return this
|
||||
},
|
||||
json(body) {
|
||||
this.body = body
|
||||
return this
|
||||
}
|
||||
}
|
||||
|
||||
await CollectionController.addBatch({ body: { books: [libraryItem.id, secondItem.id] }, collection, user: { id: 'user-id' } }, res)
|
||||
|
||||
const existingLinks = await Database.collectionBookModel.findAll({ where: { collectionId: collection.id, bookId: libraryItem.mediaId } })
|
||||
expect(existingLinks).to.have.lengthOf(1)
|
||||
const newLinks = await Database.collectionBookModel.findAll({ where: { collectionId: collection.id, bookId: secondItem.mediaId } })
|
||||
expect(newLinks).to.have.lengthOf(1)
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,977 @@
|
||||
const { expect } = require('chai')
|
||||
const { Sequelize } = require('sequelize')
|
||||
const sinon = require('sinon')
|
||||
|
||||
const Database = require('../../../server/Database')
|
||||
const PodcastController = require('../../../server/controllers/PodcastController')
|
||||
const Logger = require('../../../server/Logger')
|
||||
const SocketAuthority = require('../../../server/SocketAuthority')
|
||||
const fs = require('../../../server/libs/fsExtra')
|
||||
const libraryItemsPodcastFilters = require('../../../server/utils/queries/libraryItemsPodcastFilters')
|
||||
const zipHelpers = require('../../../server/utils/zipHelpers')
|
||||
|
||||
const { buildEpisodeUpdatePayload, validateEpisodeBatchEntries } = PodcastController
|
||||
|
||||
describe('PodcastController.buildEpisodeUpdatePayload', () => {
|
||||
beforeEach(() => {
|
||||
sinon.stub(Logger, 'debug')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore()
|
||||
})
|
||||
|
||||
it('returns an empty object for null, undefined, or non-object input', () => {
|
||||
expect(buildEpisodeUpdatePayload(null)).to.deep.equal({})
|
||||
expect(buildEpisodeUpdatePayload(undefined)).to.deep.equal({})
|
||||
expect(buildEpisodeUpdatePayload('invalid')).to.deep.equal({})
|
||||
})
|
||||
|
||||
it('copies supported string fields and ignores unknown or non-string fields', () => {
|
||||
const result = buildEpisodeUpdatePayload({
|
||||
title: 'Episode 1',
|
||||
pubDate: 'Mon, 01 Jan 2024 00:00:00 GMT',
|
||||
episode: '1',
|
||||
season: '2',
|
||||
episodeType: 'full',
|
||||
// ignored
|
||||
id: 'override-id',
|
||||
podcastId: 'override-podcast',
|
||||
audioFile: { path: '/etc/passwd' },
|
||||
seasonNumber: 2,
|
||||
title2: 'ignored',
|
||||
episode2: 123
|
||||
})
|
||||
|
||||
expect(result).to.deep.equal({
|
||||
title: 'Episode 1',
|
||||
pubDate: 'Mon, 01 Jan 2024 00:00:00 GMT',
|
||||
episode: '1',
|
||||
season: '2',
|
||||
episodeType: 'full'
|
||||
})
|
||||
})
|
||||
|
||||
it('ignores non-string values for supported string fields', () => {
|
||||
expect(buildEpisodeUpdatePayload({ title: 123, season: null, description: {} })).to.deep.equal({})
|
||||
})
|
||||
|
||||
it('sanitizes HTML in description and subtitle while keeping allowed tags and links', () => {
|
||||
const result = buildEpisodeUpdatePayload({
|
||||
description: '<p>Hello</p><script>alert(1)</script><img src="x" onerror="alert(1)"><a href="https://example.com">ok</a><a href="javascript:alert(1)">bad</a>',
|
||||
subtitle: '<b>Sub</b><script>xss()</script>'
|
||||
})
|
||||
|
||||
expect(result.description).to.equal('<p>Hello</p><a href="https://example.com">ok</a><a>bad</a>')
|
||||
expect(result.subtitle).to.equal('<b>Sub</b>')
|
||||
})
|
||||
|
||||
it('clears enclosure columns when enclosure is null', () => {
|
||||
expect(buildEpisodeUpdatePayload({ enclosure: null })).to.deep.equal({
|
||||
enclosureURL: null,
|
||||
enclosureSize: null,
|
||||
enclosureType: null
|
||||
})
|
||||
})
|
||||
|
||||
it('maps valid enclosure fields and normalizes enclosureSize', () => {
|
||||
expect(
|
||||
buildEpisodeUpdatePayload({
|
||||
enclosure: { url: 'https://example.com/ep.mp3', type: 'audio/mpeg', length: '123456' }
|
||||
})
|
||||
).to.deep.equal({
|
||||
enclosureURL: 'https://example.com/ep.mp3',
|
||||
enclosureType: 'audio/mpeg',
|
||||
enclosureSize: 123456
|
||||
})
|
||||
|
||||
expect(
|
||||
buildEpisodeUpdatePayload({
|
||||
enclosure: { url: 'https://example.com/ep.mp3', length: 987.9 }
|
||||
})
|
||||
).to.deep.equal({
|
||||
enclosureURL: 'https://example.com/ep.mp3',
|
||||
enclosureType: null,
|
||||
enclosureSize: 987
|
||||
})
|
||||
|
||||
expect(
|
||||
buildEpisodeUpdatePayload({
|
||||
enclosure: { url: 'https://example.com/ep.mp3', length: -5 }
|
||||
})
|
||||
).to.deep.equal({
|
||||
enclosureURL: 'https://example.com/ep.mp3',
|
||||
enclosureType: null,
|
||||
enclosureSize: null
|
||||
})
|
||||
|
||||
expect(
|
||||
buildEpisodeUpdatePayload({
|
||||
enclosure: { url: 'https://example.com/ep.mp3', length: { bad: true } }
|
||||
})
|
||||
).to.deep.equal({
|
||||
enclosureURL: 'https://example.com/ep.mp3',
|
||||
enclosureType: null,
|
||||
enclosureSize: null
|
||||
})
|
||||
|
||||
expect(buildEpisodeUpdatePayload({ enclosure: { type: 'audio/mpeg' } })).to.deep.equal({})
|
||||
})
|
||||
|
||||
it('accepts chapters starting at 0 and rejects invalid chapter arrays', () => {
|
||||
const validChapters = [
|
||||
{ id: 0, start: 0, end: 60, title: 'Intro' },
|
||||
{ id: 1, start: 60, end: 180, title: 'Main' }
|
||||
]
|
||||
expect(buildEpisodeUpdatePayload({ chapters: validChapters })).to.deep.equal({ chapters: validChapters })
|
||||
|
||||
expect(buildEpisodeUpdatePayload({ chapters: [null] })).to.deep.equal({})
|
||||
expect(buildEpisodeUpdatePayload({ chapters: [{ start: 0, title: '' }] })).to.deep.equal({})
|
||||
expect(buildEpisodeUpdatePayload({ chapters: [{ start: '0', title: 'Intro' }] })).to.deep.equal({})
|
||||
expect(buildEpisodeUpdatePayload({ chapters: [{ start: Number.NaN, title: 'Intro' }] })).to.deep.equal({})
|
||||
})
|
||||
|
||||
it('accepts finite publishedAt timestamps and rejects NaN, Infinity, or non-numbers', () => {
|
||||
expect(buildEpisodeUpdatePayload({ publishedAt: 1700000000000 })).to.deep.equal({ publishedAt: 1700000000000 })
|
||||
expect(buildEpisodeUpdatePayload({ publishedAt: 0 })).to.deep.equal({ publishedAt: 0 })
|
||||
expect(buildEpisodeUpdatePayload({ publishedAt: Number.NaN })).to.deep.equal({})
|
||||
expect(buildEpisodeUpdatePayload({ publishedAt: Number.POSITIVE_INFINITY })).to.deep.equal({})
|
||||
expect(buildEpisodeUpdatePayload({ publishedAt: '1700000000000' })).to.deep.equal({})
|
||||
})
|
||||
})
|
||||
|
||||
describe('PodcastController.validateEpisodeBatchEntries', () => {
|
||||
it('returns 400 when entries are missing, empty, malformed, or contain duplicate pairs', () => {
|
||||
for (const entries of [
|
||||
undefined,
|
||||
null,
|
||||
'invalid',
|
||||
[],
|
||||
[{ libraryItemId: 'li1' }, { episodeId: 'ep1' }],
|
||||
[{ libraryItemId: 123, episodeId: 'ep1' }],
|
||||
[{ libraryItemId: 'li1', episodeId: 'ep1' }, { libraryItemId: 'li1' }],
|
||||
[
|
||||
{ libraryItemId: 'li1', episodeId: 'ep1' },
|
||||
{ libraryItemId: 'li1', episodeId: 'ep1' }
|
||||
]
|
||||
]) {
|
||||
expect(validateEpisodeBatchEntries(entries)).to.deep.equal({ errorStatus: 400, errorMessage: 'Invalid payload' })
|
||||
}
|
||||
})
|
||||
|
||||
it('requires a non-null payload object on every entry when requirePayload is true', () => {
|
||||
for (const entries of [
|
||||
[{ libraryItemId: 'li1', episodeId: 'ep1' }],
|
||||
[{ libraryItemId: 'li1', episodeId: 'ep1', payload: null }],
|
||||
[{ libraryItemId: 'li1', episodeId: 'ep1', payload: 'bad' }]
|
||||
]) {
|
||||
expect(validateEpisodeBatchEntries(entries, { requirePayload: true })).to.deep.equal({
|
||||
errorStatus: 400,
|
||||
errorMessage: 'Invalid payload'
|
||||
})
|
||||
}
|
||||
|
||||
expect(
|
||||
validateEpisodeBatchEntries([{ libraryItemId: 'li1', episodeId: 'ep1', payload: { title: 'A' } }], { requirePayload: true })
|
||||
).to.deep.equal({ libraryItemIds: ['li1'], episodeIds: ['ep1'] })
|
||||
})
|
||||
|
||||
it('returns deduplicated libraryItemIds and episodeIds for valid entries', () => {
|
||||
expect(
|
||||
validateEpisodeBatchEntries([
|
||||
{ libraryItemId: 'li1', episodeId: 'ep1' },
|
||||
{ libraryItemId: 'li1', episodeId: 'ep2' },
|
||||
{ libraryItemId: 'li2', episodeId: 'ep3' }
|
||||
])
|
||||
).to.deep.equal({
|
||||
libraryItemIds: ['li1', 'li2'],
|
||||
episodeIds: ['ep1', 'ep2', 'ep3']
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('PodcastController batch episode endpoints', () => {
|
||||
let library
|
||||
let libraryFolder
|
||||
let podcastItem1
|
||||
let podcastItem2
|
||||
let episode1
|
||||
let episode2
|
||||
let episode3
|
||||
let user
|
||||
|
||||
function createFakeRes() {
|
||||
return {
|
||||
status: sinon.stub().returnsThis(),
|
||||
send: sinon.spy(),
|
||||
sendStatus: sinon.spy(),
|
||||
json: sinon.spy()
|
||||
}
|
||||
}
|
||||
|
||||
function createAudioFile(filename, filePath, ino = '1') {
|
||||
return {
|
||||
ino,
|
||||
duration: 120,
|
||||
metadata: {
|
||||
filename,
|
||||
path: filePath,
|
||||
size: 1024
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
global.ServerSettings = {}
|
||||
Database.sequelize = new Sequelize({ dialect: 'sqlite', storage: ':memory:', logging: false })
|
||||
Database.sequelize.uppercaseFirst = (str) => (str ? `${str[0].toUpperCase()}${str.substr(1)}` : '')
|
||||
await Database.buildModels()
|
||||
|
||||
sinon.stub(Logger, 'info')
|
||||
sinon.stub(Logger, 'debug')
|
||||
sinon.stub(Logger, 'warn')
|
||||
sinon.stub(Logger, 'error')
|
||||
|
||||
library = await Database.libraryModel.create({ name: 'Podcasts', mediaType: 'podcast' })
|
||||
libraryFolder = await Database.libraryFolderModel.create({ path: '/podcasts', libraryId: library.id })
|
||||
|
||||
const podcast1 = await Database.podcastModel.create({
|
||||
title: 'Podcast One',
|
||||
explicit: false,
|
||||
tags: ['tech'],
|
||||
genres: []
|
||||
})
|
||||
podcastItem1 = await Database.libraryItemModel.create({
|
||||
path: '/podcasts/podcast-one',
|
||||
libraryFiles: [{ ino: 'huge-blob-sentinel' }],
|
||||
mediaId: podcast1.id,
|
||||
mediaType: 'podcast',
|
||||
libraryId: library.id,
|
||||
libraryFolderId: libraryFolder.id
|
||||
})
|
||||
|
||||
const podcast2 = await Database.podcastModel.create({
|
||||
title: '',
|
||||
explicit: true,
|
||||
tags: ['restricted'],
|
||||
genres: []
|
||||
})
|
||||
podcastItem2 = await Database.libraryItemModel.create({
|
||||
path: '/podcasts/podcast-two',
|
||||
libraryFiles: [],
|
||||
mediaId: podcast2.id,
|
||||
mediaType: 'podcast',
|
||||
libraryId: library.id,
|
||||
libraryFolderId: libraryFolder.id
|
||||
})
|
||||
|
||||
episode1 = await Database.podcastEpisodeModel.create({
|
||||
title: 'Ep 1',
|
||||
podcastId: podcast1.id,
|
||||
audioFile: createAudioFile('ep1.mp3', '/podcasts/podcast-one/ep1.mp3', '101'),
|
||||
chapters: [],
|
||||
extraData: {}
|
||||
})
|
||||
episode2 = await Database.podcastEpisodeModel.create({
|
||||
title: 'Ep 2',
|
||||
podcastId: podcast1.id,
|
||||
audioFile: createAudioFile('ep2.mp3', '/podcasts/podcast-one/ep2.mp3', '102'),
|
||||
chapters: [],
|
||||
extraData: {}
|
||||
})
|
||||
episode3 = await Database.podcastEpisodeModel.create({
|
||||
title: 'Ep 3',
|
||||
podcastId: podcast2.id,
|
||||
audioFile: createAudioFile('ep1.mp3', '/podcasts/podcast-two/ep1.mp3', '103'),
|
||||
chapters: [],
|
||||
extraData: {}
|
||||
})
|
||||
|
||||
user = await Database.userModel.create({
|
||||
username: 'tester',
|
||||
type: 'user',
|
||||
isActive: true,
|
||||
permissions: {
|
||||
download: true,
|
||||
update: true,
|
||||
delete: false,
|
||||
upload: false,
|
||||
accessAllLibraries: true,
|
||||
accessAllTags: true,
|
||||
accessExplicitContent: true
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
sinon.restore()
|
||||
await Database.sequelize.sync({ force: true })
|
||||
})
|
||||
|
||||
it('returns 400 without querying DB when any batch episode endpoint receives an invalid payload', async () => {
|
||||
user.permissions = { ...user.permissions, delete: true }
|
||||
const findAllSpy = sinon.spy(Database.libraryItemModel, 'findAll')
|
||||
const findExpandedSpy = sinon.spy(Database.libraryItemModel, 'findAllExpandedWhere')
|
||||
|
||||
for (const invoke of [
|
||||
(res) => PodcastController.batchGetEpisodes({ user, body: { episodes: [] } }, res),
|
||||
(res) => PodcastController.batchUpdateEpisodes({ user, body: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }] }, res),
|
||||
(res) => PodcastController.batchDeleteEpisodes({ user, query: {}, body: { episodes: [] } }, res),
|
||||
(res) => PodcastController.batchDownloadEpisodes({ user, body: { episodes: [] } }, res)
|
||||
]) {
|
||||
const res = createFakeRes()
|
||||
await invoke(res)
|
||||
expect(res.status.calledOnceWith(400)).to.be.true
|
||||
expect(res.send.calledOnceWith('Invalid payload')).to.be.true
|
||||
}
|
||||
|
||||
expect(findAllSpy.called).to.be.false
|
||||
expect(findExpandedSpy.called).to.be.false
|
||||
})
|
||||
|
||||
describe('batchGetEpisodes', () => {
|
||||
it('preserves request order, omits missing/non-podcast entries, and returns expanded episodes', async () => {
|
||||
const book = await Database.bookModel.create({ title: 'A Book', audioFiles: [], tags: [], narrators: [], genres: [], chapters: [] })
|
||||
const bookItem = await Database.libraryItemModel.create({
|
||||
libraryFiles: [],
|
||||
mediaId: book.id,
|
||||
mediaType: 'book',
|
||||
libraryId: library.id,
|
||||
libraryFolderId: libraryFolder.id
|
||||
})
|
||||
|
||||
const res = createFakeRes()
|
||||
await PodcastController.batchGetEpisodes(
|
||||
{
|
||||
user,
|
||||
body: {
|
||||
episodes: [
|
||||
{ libraryItemId: podcastItem2.id, episodeId: episode3.id },
|
||||
{ libraryItemId: podcastItem1.id, episodeId: episode2.id },
|
||||
{ libraryItemId: podcastItem1.id, episodeId: 'missing-episode' },
|
||||
{ libraryItemId: bookItem.id, episodeId: episode1.id },
|
||||
{ libraryItemId: podcastItem1.id, episodeId: episode1.id }
|
||||
]
|
||||
}
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.json.calledOnce).to.be.true
|
||||
const { episodes } = res.json.firstCall.args[0]
|
||||
expect(episodes.map((e) => `${e.libraryItemId}:${e.id}`)).to.deep.equal([`${podcastItem2.id}:${episode3.id}`, `${podcastItem1.id}:${episode2.id}`, `${podcastItem1.id}:${episode1.id}`])
|
||||
expect(episodes[1].audioTrack.contentUrl).to.equal(`/api/items/${podcastItem1.id}/file/102`)
|
||||
expect(episodes[1].duration).to.equal(120)
|
||||
})
|
||||
|
||||
it('omits cross-podcast mismatched (libraryItemId, episodeId) pairs', async () => {
|
||||
const res = createFakeRes()
|
||||
await PodcastController.batchGetEpisodes(
|
||||
{
|
||||
user,
|
||||
body: {
|
||||
episodes: [
|
||||
{ libraryItemId: podcastItem1.id, episodeId: episode3.id },
|
||||
{ libraryItemId: podcastItem2.id, episodeId: episode1.id }
|
||||
]
|
||||
}
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.json.calledOnce).to.be.true
|
||||
expect(res.json.firstCall.args[0]).to.deep.equal({ episodes: [] })
|
||||
})
|
||||
|
||||
it('returns 403 when user lacks access to a referenced podcast', async () => {
|
||||
user.permissions = {
|
||||
...user.permissions,
|
||||
accessExplicitContent: false
|
||||
}
|
||||
|
||||
const res = createFakeRes()
|
||||
await PodcastController.batchGetEpisodes(
|
||||
{
|
||||
user,
|
||||
body: {
|
||||
episodes: [
|
||||
{ libraryItemId: podcastItem1.id, episodeId: episode1.id },
|
||||
{ libraryItemId: podcastItem2.id, episodeId: episode3.id }
|
||||
]
|
||||
}
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.sendStatus.calledOnceWith(403)).to.be.true
|
||||
expect(res.json.called).to.be.false
|
||||
})
|
||||
|
||||
it('excludes orphaned podcast library items with missing media without crashing access checks', async () => {
|
||||
const orphanedItem = await Database.libraryItemModel.create({
|
||||
libraryFiles: [],
|
||||
mediaId: '00000000-0000-4000-8000-000000000999',
|
||||
mediaType: 'podcast',
|
||||
libraryId: library.id,
|
||||
libraryFolderId: libraryFolder.id
|
||||
})
|
||||
|
||||
const res = createFakeRes()
|
||||
await PodcastController.batchGetEpisodes(
|
||||
{
|
||||
user,
|
||||
body: {
|
||||
episodes: [
|
||||
{ libraryItemId: orphanedItem.id, episodeId: episode1.id },
|
||||
{ libraryItemId: podcastItem1.id, episodeId: episode1.id }
|
||||
]
|
||||
}
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.json.calledOnce).to.be.true
|
||||
expect(res.json.firstCall.args[0].episodes).to.have.lengthOf(1)
|
||||
expect(res.json.firstCall.args[0].episodes[0].id).to.equal(episode1.id)
|
||||
})
|
||||
|
||||
it('projects only required libraryItem and podcast attributes and uses required inner join', async () => {
|
||||
const findSpy = sinon.spy(Database.libraryItemModel, 'findAll')
|
||||
|
||||
const res = createFakeRes()
|
||||
await PodcastController.batchGetEpisodes(
|
||||
{
|
||||
user,
|
||||
body: {
|
||||
episodes: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }]
|
||||
}
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(findSpy.calledOnce).to.be.true
|
||||
const queryOptions = findSpy.firstCall.args[0]
|
||||
expect(queryOptions.attributes).to.deep.equal(['id', 'libraryId', 'mediaId', 'mediaType', 'path'])
|
||||
expect(queryOptions.attributes).to.not.include('libraryFiles')
|
||||
expect(queryOptions.include[0].required).to.be.true
|
||||
expect(queryOptions.include[0].attributes).to.deep.equal(['id', 'explicit', 'tags'])
|
||||
})
|
||||
|
||||
it('returns 500 when a database query throws unexpectedly', async () => {
|
||||
sinon.stub(Database.libraryItemModel, 'findAll').rejects(new Error('SQLITE_BUSY'))
|
||||
|
||||
const res = createFakeRes()
|
||||
await PodcastController.batchGetEpisodes(
|
||||
{
|
||||
user,
|
||||
body: {
|
||||
episodes: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }]
|
||||
}
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.status.calledOnceWith(500)).to.be.true
|
||||
expect(res.send.calledOnceWith('Failed to get episodes')).to.be.true
|
||||
expect(Logger.error.calledOnce).to.be.true
|
||||
})
|
||||
})
|
||||
|
||||
describe('batchUpdateEpisodes', () => {
|
||||
it('returns 403 when user lacks canUpdate permission without querying DB', async () => {
|
||||
user.permissions = { ...user.permissions, update: false }
|
||||
const findSpy = sinon.spy(Database.libraryItemModel, 'findAllExpandedWhere')
|
||||
const res = createFakeRes()
|
||||
|
||||
await PodcastController.batchUpdateEpisodes(
|
||||
{
|
||||
user,
|
||||
body: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id, payload: { title: 'Updated' } }]
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.sendStatus.calledOnceWith(403)).to.be.true
|
||||
expect(findSpy.called).to.be.false
|
||||
})
|
||||
|
||||
it('returns 403 when user lacks access to a referenced podcast', async () => {
|
||||
user.permissions = { ...user.permissions, accessExplicitContent: false }
|
||||
const emitStub = sinon.stub(SocketAuthority, 'libraryItemEmitter')
|
||||
const res = createFakeRes()
|
||||
|
||||
await PodcastController.batchUpdateEpisodes(
|
||||
{
|
||||
user,
|
||||
body: [
|
||||
{ libraryItemId: podcastItem1.id, episodeId: episode1.id, payload: { title: 'Should Not Save' } },
|
||||
{ libraryItemId: podcastItem2.id, episodeId: episode3.id, payload: { title: 'Restricted' } }
|
||||
]
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.sendStatus.calledOnceWith(403)).to.be.true
|
||||
expect(emitStub.called).to.be.false
|
||||
await episode1.reload()
|
||||
expect(episode1.title).to.equal('Ep 1')
|
||||
})
|
||||
|
||||
it('returns 404 when no requested episodes exist or only non-podcast items match', async () => {
|
||||
const book = await Database.bookModel.create({ title: 'A Book', audioFiles: [], tags: [], narrators: [], genres: [], chapters: [] })
|
||||
const bookItem = await Database.libraryItemModel.create({
|
||||
libraryFiles: [],
|
||||
mediaId: book.id,
|
||||
mediaType: 'book',
|
||||
libraryId: library.id,
|
||||
libraryFolderId: libraryFolder.id
|
||||
})
|
||||
|
||||
const res = createFakeRes()
|
||||
await PodcastController.batchUpdateEpisodes(
|
||||
{
|
||||
user,
|
||||
body: [
|
||||
{ libraryItemId: podcastItem1.id, episodeId: 'missing-ep', payload: { title: 'Nope' } },
|
||||
{ libraryItemId: bookItem.id, episodeId: episode1.id, payload: { title: 'Nope' } }
|
||||
]
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.status.calledOnceWith(404)).to.be.true
|
||||
expect(res.send.calledOnceWith('Episodes not found')).to.be.true
|
||||
})
|
||||
|
||||
it('updates episodes across podcasts in a transaction, omits missing entries, and emits once per modified podcast', async () => {
|
||||
const emitStub = sinon.stub(SocketAuthority, 'libraryItemEmitter')
|
||||
const res = createFakeRes()
|
||||
|
||||
await PodcastController.batchUpdateEpisodes(
|
||||
{
|
||||
user,
|
||||
body: [
|
||||
{ libraryItemId: podcastItem1.id, episodeId: episode1.id, payload: { title: 'Ep 1 Updated', season: '2' } },
|
||||
{ libraryItemId: podcastItem1.id, episodeId: episode2.id, payload: { title: 'Ep 2' } },
|
||||
{ libraryItemId: podcastItem1.id, episodeId: 'missing-ep', payload: { title: 'Ignored' } },
|
||||
{ libraryItemId: podcastItem2.id, episodeId: episode3.id, payload: { title: 'Ep 3 Updated', description: '<p>Clean</p><script>bad()</script>' } }
|
||||
]
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.json.calledOnceWith({ success: true, updates: 2 })).to.be.true
|
||||
|
||||
await episode1.reload()
|
||||
await episode2.reload()
|
||||
await episode3.reload()
|
||||
expect(episode1.title).to.equal('Ep 1 Updated')
|
||||
expect(episode1.season).to.equal('2')
|
||||
expect(episode2.title).to.equal('Ep 2')
|
||||
expect(episode3.title).to.equal('Ep 3 Updated')
|
||||
expect(episode3.description).to.equal('<p>Clean</p>')
|
||||
|
||||
expect(emitStub.callCount).to.equal(2)
|
||||
expect(emitStub.getCalls().map((c) => [c.args[0], c.args[1].id])).to.deep.equal([
|
||||
['item_updated', podcastItem1.id],
|
||||
['item_updated', podcastItem2.id]
|
||||
])
|
||||
})
|
||||
|
||||
it('returns updates: 0 and emits no socket events when payloads produce no changes', async () => {
|
||||
const emitStub = sinon.stub(SocketAuthority, 'libraryItemEmitter')
|
||||
const res = createFakeRes()
|
||||
|
||||
await PodcastController.batchUpdateEpisodes(
|
||||
{
|
||||
user,
|
||||
body: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id, payload: { title: 'Ep 1', unknownField: 'ignored' } }]
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.json.calledOnceWith({ success: true, updates: 0 })).to.be.true
|
||||
expect(emitStub.called).to.be.false
|
||||
})
|
||||
|
||||
it('rolls back transaction and returns 500 when saving an episode fails mid-batch', async () => {
|
||||
const emitStub = sinon.stub(SocketAuthority, 'libraryItemEmitter')
|
||||
const originalSave = Database.podcastEpisodeModel.prototype.save
|
||||
let saveCalls = 0
|
||||
sinon.stub(Database.podcastEpisodeModel.prototype, 'save').callsFake(function (...args) {
|
||||
saveCalls++
|
||||
if (saveCalls === 2) return Promise.reject(new Error('SQLITE_BUSY'))
|
||||
return originalSave.apply(this, args)
|
||||
})
|
||||
|
||||
const res = createFakeRes()
|
||||
await PodcastController.batchUpdateEpisodes(
|
||||
{
|
||||
user,
|
||||
body: [
|
||||
{ libraryItemId: podcastItem1.id, episodeId: episode1.id, payload: { title: 'Rolled Back' } },
|
||||
{ libraryItemId: podcastItem1.id, episodeId: episode2.id, payload: { title: 'Fails Save' } }
|
||||
]
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.status.calledOnceWith(500)).to.be.true
|
||||
expect(res.send.calledOnceWith('Failed to update episodes')).to.be.true
|
||||
expect(emitStub.called).to.be.false
|
||||
|
||||
await episode1.reload()
|
||||
expect(episode1.title).to.equal('Ep 1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('batchDeleteEpisodes', () => {
|
||||
it('returns 403 when user lacks canDelete permission without querying DB', async () => {
|
||||
const findSpy = sinon.spy(Database.libraryItemModel, 'findAllExpandedWhere')
|
||||
const res = createFakeRes()
|
||||
|
||||
await PodcastController.batchDeleteEpisodes(
|
||||
{
|
||||
user,
|
||||
query: {},
|
||||
body: { episodes: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }] }
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.sendStatus.calledOnceWith(403)).to.be.true
|
||||
expect(findSpy.called).to.be.false
|
||||
})
|
||||
|
||||
it('returns 403 when user lacks access to a referenced podcast', async () => {
|
||||
user.permissions = { ...user.permissions, delete: true, accessExplicitContent: false }
|
||||
const res = createFakeRes()
|
||||
|
||||
await PodcastController.batchDeleteEpisodes(
|
||||
{
|
||||
user,
|
||||
query: {},
|
||||
body: {
|
||||
episodes: [
|
||||
{ libraryItemId: podcastItem1.id, episodeId: episode1.id },
|
||||
{ libraryItemId: podcastItem2.id, episodeId: episode3.id }
|
||||
]
|
||||
}
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.sendStatus.calledOnceWith(403)).to.be.true
|
||||
expect(await Database.podcastEpisodeModel.findByPk(episode1.id)).to.not.be.null
|
||||
})
|
||||
|
||||
it('returns 404 when no requested episodes are found', async () => {
|
||||
user.permissions = { ...user.permissions, delete: true }
|
||||
const res = createFakeRes()
|
||||
|
||||
await PodcastController.batchDeleteEpisodes(
|
||||
{
|
||||
user,
|
||||
query: {},
|
||||
body: { episodes: [{ libraryItemId: podcastItem1.id, episodeId: 'missing-ep' }] }
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.status.calledOnceWith(404)).to.be.true
|
||||
expect(res.send.calledOnceWith('Episodes not found')).to.be.true
|
||||
})
|
||||
|
||||
it('soft-deletes episodes across podcasts, cleans up progress/playlists/libraryFiles/numEpisodes, and emits once per podcast', async () => {
|
||||
user.permissions = { ...user.permissions, delete: true }
|
||||
|
||||
podcastItem1.libraryFiles = [{ ino: '101' }, { ino: '102' }, { ino: 'keep-1' }]
|
||||
podcastItem1.changed('libraryFiles', true)
|
||||
await podcastItem1.save()
|
||||
|
||||
podcastItem2.libraryFiles = [{ ino: '103' }]
|
||||
podcastItem2.changed('libraryFiles', true)
|
||||
await podcastItem2.save()
|
||||
|
||||
await Database.mediaProgressModel.create({
|
||||
userId: user.id,
|
||||
mediaItemId: episode1.id,
|
||||
mediaItemType: 'podcastEpisode',
|
||||
duration: 120,
|
||||
currentTime: 30,
|
||||
isFinished: false
|
||||
})
|
||||
await Database.mediaProgressModel.create({
|
||||
userId: user.id,
|
||||
mediaItemId: episode2.id,
|
||||
mediaItemType: 'podcastEpisode',
|
||||
duration: 120,
|
||||
currentTime: 60,
|
||||
isFinished: false
|
||||
})
|
||||
|
||||
const playlistStub = sinon.stub(Database.playlistModel, 'removeMediaItemsFromPlaylists').resolves()
|
||||
const cacheStub = sinon.stub(libraryItemsPodcastFilters, 'clearCountCache')
|
||||
const fsRemoveStub = sinon.stub(fs, 'remove').resolves()
|
||||
const emitStub = sinon.stub(SocketAuthority, 'libraryItemEmitter')
|
||||
|
||||
const res = createFakeRes()
|
||||
await PodcastController.batchDeleteEpisodes(
|
||||
{
|
||||
user,
|
||||
query: {},
|
||||
body: {
|
||||
episodes: [
|
||||
{ libraryItemId: podcastItem1.id, episodeId: episode1.id },
|
||||
{ libraryItemId: podcastItem1.id, episodeId: 'missing-ep' },
|
||||
{ libraryItemId: podcastItem2.id, episodeId: episode3.id }
|
||||
]
|
||||
}
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.json.calledOnceWith({ success: true, removed: 2 })).to.be.true
|
||||
expect(fsRemoveStub.called).to.be.false
|
||||
expect(playlistStub.calledOnceWith([episode1.id, episode3.id])).to.be.true
|
||||
expect(cacheStub.calledOnceWith('podcastEpisode', 'afterDestroy')).to.be.true
|
||||
|
||||
expect(await Database.podcastEpisodeModel.findByPk(episode1.id)).to.be.null
|
||||
expect(await Database.podcastEpisodeModel.findByPk(episode3.id)).to.be.null
|
||||
expect(await Database.podcastEpisodeModel.findByPk(episode2.id)).to.not.be.null
|
||||
|
||||
expect(await Database.mediaProgressModel.count({ where: { mediaItemId: episode1.id } })).to.equal(0)
|
||||
expect(await Database.mediaProgressModel.count({ where: { mediaItemId: episode2.id } })).to.equal(1)
|
||||
|
||||
await podcastItem1.reload()
|
||||
await podcastItem2.reload()
|
||||
const podcast1 = await Database.podcastModel.findByPk(podcastItem1.mediaId)
|
||||
const podcast2 = await Database.podcastModel.findByPk(podcastItem2.mediaId)
|
||||
expect(podcastItem1.libraryFiles.map((f) => f.ino)).to.deep.equal(['102', 'keep-1'])
|
||||
expect(podcast1.numEpisodes).to.equal(1)
|
||||
expect(podcastItem2.libraryFiles).to.deep.equal([])
|
||||
expect(podcast2.numEpisodes).to.equal(0)
|
||||
|
||||
expect(emitStub.callCount).to.equal(2)
|
||||
expect(emitStub.getCalls().map((c) => [c.args[0], c.args[1].id])).to.deep.equal([
|
||||
['item_updated', podcastItem1.id],
|
||||
['item_updated', podcastItem2.id]
|
||||
])
|
||||
})
|
||||
|
||||
it('hard-deletes audio files when hard=1 and continues if one unlink fails', async () => {
|
||||
user.permissions = { ...user.permissions, delete: true }
|
||||
sinon.stub(Database.playlistModel, 'removeMediaItemsFromPlaylists').resolves()
|
||||
sinon.stub(libraryItemsPodcastFilters, 'clearCountCache')
|
||||
sinon.stub(SocketAuthority, 'libraryItemEmitter')
|
||||
|
||||
const fsRemoveStub = sinon.stub(fs, 'remove')
|
||||
fsRemoveStub.onFirstCall().rejects(new Error('ENOENT'))
|
||||
fsRemoveStub.onSecondCall().resolves()
|
||||
|
||||
const res = createFakeRes()
|
||||
await PodcastController.batchDeleteEpisodes(
|
||||
{
|
||||
user,
|
||||
query: { hard: '1' },
|
||||
body: {
|
||||
episodes: [
|
||||
{ libraryItemId: podcastItem1.id, episodeId: episode1.id },
|
||||
{ libraryItemId: podcastItem2.id, episodeId: episode3.id }
|
||||
]
|
||||
}
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.json.calledOnceWith({ success: true, removed: 2 })).to.be.true
|
||||
expect(fsRemoveStub.callCount).to.equal(2)
|
||||
expect(fsRemoveStub.firstCall.args[0]).to.equal('/podcasts/podcast-one/ep1.mp3')
|
||||
expect(fsRemoveStub.secondCall.args[0]).to.equal('/podcasts/podcast-two/ep1.mp3')
|
||||
expect(Logger.error.calledOnce).to.be.true
|
||||
expect(await Database.podcastEpisodeModel.findByPk(episode1.id)).to.be.null
|
||||
expect(await Database.podcastEpisodeModel.findByPk(episode3.id)).to.be.null
|
||||
})
|
||||
|
||||
it('returns 500 and does not unlink files when database deletion fails unexpectedly', async () => {
|
||||
user.permissions = { ...user.permissions, delete: true }
|
||||
sinon.stub(Database.playlistModel, 'removeMediaItemsFromPlaylists').resolves()
|
||||
const fsRemoveStub = sinon.stub(fs, 'remove').resolves()
|
||||
const emitStub = sinon.stub(SocketAuthority, 'libraryItemEmitter')
|
||||
sinon.stub(Database.podcastEpisodeModel, 'destroy').rejects(new Error('SQLITE_BUSY'))
|
||||
|
||||
const res = createFakeRes()
|
||||
await PodcastController.batchDeleteEpisodes(
|
||||
{
|
||||
user,
|
||||
query: { hard: '1' },
|
||||
body: { episodes: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }] }
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.status.calledOnceWith(500)).to.be.true
|
||||
expect(res.send.calledOnceWith('Failed to delete episodes')).to.be.true
|
||||
expect(fsRemoveStub.called).to.be.false
|
||||
expect(emitStub.called).to.be.false
|
||||
})
|
||||
})
|
||||
|
||||
describe('batchDownloadEpisodes', () => {
|
||||
it('returns 403 when user lacks canDownload permission without querying DB', async () => {
|
||||
user.permissions = { ...user.permissions, download: false }
|
||||
const findSpy = sinon.spy(Database.libraryItemModel, 'findAll')
|
||||
const res = createFakeRes()
|
||||
|
||||
await PodcastController.batchDownloadEpisodes(
|
||||
{
|
||||
user,
|
||||
body: { episodes: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }] }
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.sendStatus.calledOnceWith(403)).to.be.true
|
||||
expect(findSpy.called).to.be.false
|
||||
})
|
||||
|
||||
it('returns 403 when user lacks access to a referenced podcast', async () => {
|
||||
user.permissions = { ...user.permissions, accessExplicitContent: false }
|
||||
const zipStub = sinon.stub(zipHelpers, 'zipDirectoriesPipe').resolves()
|
||||
const res = createFakeRes()
|
||||
|
||||
await PodcastController.batchDownloadEpisodes(
|
||||
{
|
||||
user,
|
||||
body: {
|
||||
episodes: [
|
||||
{ libraryItemId: podcastItem1.id, episodeId: episode1.id },
|
||||
{ libraryItemId: podcastItem2.id, episodeId: episode3.id }
|
||||
]
|
||||
}
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.sendStatus.calledOnceWith(403)).to.be.true
|
||||
expect(zipStub.called).to.be.false
|
||||
})
|
||||
|
||||
it('groups multi-podcast episodes into podcast folders', async () => {
|
||||
const zipStub = sinon.stub(zipHelpers, 'zipDirectoriesPipe').resolves()
|
||||
const res = createFakeRes()
|
||||
|
||||
await PodcastController.batchDownloadEpisodes(
|
||||
{
|
||||
user,
|
||||
body: {
|
||||
episodes: [
|
||||
{ libraryItemId: podcastItem1.id, episodeId: episode1.id },
|
||||
{ libraryItemId: podcastItem2.id, episodeId: episode3.id }
|
||||
]
|
||||
}
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(zipStub.calledOnce).to.be.true
|
||||
const [fileEntries] = zipStub.firstCall.args
|
||||
expect(fileEntries).to.deep.equal([
|
||||
{ path: '/podcasts/podcast-one/ep1.mp3', isFile: true, name: 'podcast-one/ep1.mp3' },
|
||||
{ path: '/podcasts/podcast-two/ep1.mp3', isFile: true, name: 'podcast-two/ep1.mp3' }
|
||||
])
|
||||
})
|
||||
|
||||
it('uses flat filenames for single-podcast downloads and disambiguates duplicate names', async () => {
|
||||
episode2.audioFile = createAudioFile('ep1.mp3', '/podcasts/podcast-one/sub/ep1.mp3', '102')
|
||||
episode2.changed('audioFile', true)
|
||||
await episode2.save()
|
||||
|
||||
const zipStub = sinon.stub(zipHelpers, 'zipDirectoriesPipe').resolves()
|
||||
const res = createFakeRes()
|
||||
|
||||
await PodcastController.batchDownloadEpisodes(
|
||||
{
|
||||
user,
|
||||
body: {
|
||||
episodes: [
|
||||
{ libraryItemId: podcastItem1.id, episodeId: episode1.id },
|
||||
{ libraryItemId: podcastItem1.id, episodeId: episode2.id }
|
||||
]
|
||||
}
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(zipStub.calledOnce).to.be.true
|
||||
const [fileEntries] = zipStub.firstCall.args
|
||||
expect(fileEntries).to.deep.equal([
|
||||
{ path: '/podcasts/podcast-one/ep1.mp3', isFile: true, name: 'ep1.mp3' },
|
||||
{ path: '/podcasts/podcast-one/sub/ep1.mp3', isFile: true, name: 'ep1 (2).mp3' }
|
||||
])
|
||||
})
|
||||
|
||||
it('returns 404 when no downloadable episode files are found', async () => {
|
||||
episode1.audioFile = { ino: '101', duration: 120, metadata: {} }
|
||||
episode1.changed('audioFile', true)
|
||||
await episode1.save()
|
||||
|
||||
const zipStub = sinon.stub(zipHelpers, 'zipDirectoriesPipe').resolves()
|
||||
const res = createFakeRes()
|
||||
|
||||
await PodcastController.batchDownloadEpisodes(
|
||||
{
|
||||
user,
|
||||
body: {
|
||||
episodes: [
|
||||
{ libraryItemId: podcastItem1.id, episodeId: episode1.id },
|
||||
{ libraryItemId: podcastItem1.id, episodeId: 'missing-ep' }
|
||||
]
|
||||
}
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.status.calledOnceWith(404)).to.be.true
|
||||
expect(res.send.calledOnceWith('No downloadable episode files found')).to.be.true
|
||||
expect(zipStub.called).to.be.false
|
||||
})
|
||||
|
||||
it('delegates zip streaming errors to zipHelpers.handleDownloadError', async () => {
|
||||
const zipError = new Error('ENOENT')
|
||||
sinon.stub(zipHelpers, 'zipDirectoriesPipe').rejects(zipError)
|
||||
const handleErrorStub = sinon.stub(zipHelpers, 'handleDownloadError')
|
||||
const res = createFakeRes()
|
||||
|
||||
await PodcastController.batchDownloadEpisodes(
|
||||
{
|
||||
user,
|
||||
body: { episodes: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }] }
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(handleErrorStub.calledOnceWith(zipError, res)).to.be.true
|
||||
expect(Logger.error.calledOnce).to.be.true
|
||||
})
|
||||
|
||||
it('returns 500 when episode resolution fails unexpectedly', async () => {
|
||||
sinon.stub(Database.libraryItemModel, 'findAll').rejects(new Error('SQLITE_BUSY'))
|
||||
const res = createFakeRes()
|
||||
|
||||
await PodcastController.batchDownloadEpisodes(
|
||||
{
|
||||
user,
|
||||
body: {
|
||||
episodes: [{ libraryItemId: podcastItem1.id, episodeId: episode1.id }]
|
||||
}
|
||||
},
|
||||
res
|
||||
)
|
||||
|
||||
expect(res.status.calledOnceWith(500)).to.be.true
|
||||
expect(res.send.calledOnceWith('Download failed')).to.be.true
|
||||
expect(Logger.error.calledOnce).to.be.true
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -108,4 +108,82 @@ describe('ApiCacheManager', () => {
|
||||
expect(cache.get(key)).to.be.undefined
|
||||
})
|
||||
})
|
||||
|
||||
describe('in-flight invalidation', () => {
|
||||
it('should not cache response when full clear happens while request is in flight', () => {
|
||||
const lruCache = new LRUCache({ max: 10 })
|
||||
req.url = '/libraries/abc-123/personalized?include=rssfeed,share'
|
||||
res.getHeaders.returns({ 'content-type': 'application/json' })
|
||||
manager = new ApiCacheManager(lruCache)
|
||||
|
||||
manager.middleware(req, res, next)
|
||||
manager.clear({ name: 'libraryItem' }, 'afterCreate')
|
||||
res.send('stale personalized data')
|
||||
|
||||
const key = JSON.stringify({ user: req.user.username, url: req.url })
|
||||
expect(lruCache.get(key)).to.be.undefined
|
||||
expect(res.originalSend.calledOnceWith('stale personalized data')).to.be.true
|
||||
})
|
||||
|
||||
it('should not cache personalized or recent-episodes response when mediaProgress updates while in flight', () => {
|
||||
const lruCache = new LRUCache({ max: 10 })
|
||||
req.url = '/libraries/abc-123/personalized'
|
||||
res.getHeaders.returns({ 'content-type': 'application/json' })
|
||||
manager = new ApiCacheManager(lruCache)
|
||||
|
||||
manager.middleware(req, res, next)
|
||||
manager.clear({ name: 'mediaProgress' }, 'afterUpdate')
|
||||
res.send('stale personalized data')
|
||||
|
||||
const key = JSON.stringify({ user: req.user.username, url: req.url })
|
||||
expect(lruCache.get(key)).to.be.undefined
|
||||
expect(res.originalSend.calledOnceWith('stale personalized data')).to.be.true
|
||||
})
|
||||
|
||||
it('should still cache unrelated endpoints when a high-churn slice clears while in flight', () => {
|
||||
const lruCache = new LRUCache({ max: 10 })
|
||||
req.url = '/libraries/abc-123/stats'
|
||||
res.getHeaders.returns({ 'content-type': 'application/json' })
|
||||
manager = new ApiCacheManager(lruCache)
|
||||
|
||||
manager.middleware(req, res, next)
|
||||
manager.clear({ name: 'session' }, 'afterCreate')
|
||||
res.send('fresh stats')
|
||||
|
||||
const key = JSON.stringify({ user: req.user.username, url: req.url })
|
||||
expect(lruCache.get(key)).to.deep.equal({
|
||||
body: 'fresh stats',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
statusCode: 200
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('getModelName', () => {
|
||||
it('should prefer instance constructor name over name column value', () => {
|
||||
class author {
|
||||
constructor(name) {
|
||||
this.name = name
|
||||
}
|
||||
}
|
||||
const lruCache = new LRUCache({ max: 10 })
|
||||
const key = JSON.stringify({ user: 'u', url: '/libraries/abc-123/stats' })
|
||||
lruCache.set(key, { body: '{}', headers: {}, statusCode: 200 })
|
||||
manager = new ApiCacheManager(lruCache)
|
||||
|
||||
// An author named "session" must still clear the full cache, not be treated as the high-churn session model
|
||||
const instance = new author('session')
|
||||
expect(manager.getModelName(instance)).to.equal('author')
|
||||
manager.clear(instance, 'afterCreate')
|
||||
expect(lruCache.get(key)).to.be.undefined
|
||||
})
|
||||
|
||||
it('should resolve model name from arrays and bulk hook options', () => {
|
||||
class libraryItem {}
|
||||
manager = new ApiCacheManager(cache)
|
||||
|
||||
expect(manager.getModelName([new libraryItem()])).to.equal('libraryItem')
|
||||
expect(manager.getModelName({ model: { name: 'mediaProgress' } })).to.equal('mediaProgress')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,71 @@
|
||||
const { expect } = require('chai')
|
||||
const { Sequelize } = require('sequelize')
|
||||
const sinon = require('sinon')
|
||||
|
||||
const Database = require('../../../server/Database')
|
||||
const Logger = require('../../../server/Logger')
|
||||
|
||||
describe('Book author and series updates', () => {
|
||||
/** @type {import('../../../server/models/Library')} */
|
||||
let library
|
||||
/** @type {import('../../../server/models/Book')} */
|
||||
let book
|
||||
|
||||
beforeEach(async () => {
|
||||
global.ServerSettings = {}
|
||||
Database.sequelize = new Sequelize({ dialect: 'sqlite', storage: ':memory:', logging: false })
|
||||
Database.sequelize.uppercaseFirst = (str) => (str ? `${str[0].toUpperCase()}${str.substr(1)}` : '')
|
||||
await Database.buildModels()
|
||||
|
||||
sinon.stub(Logger, 'info')
|
||||
sinon.stub(Logger, 'debug')
|
||||
sinon.stub(Logger, 'warn')
|
||||
sinon.stub(Logger, 'error')
|
||||
|
||||
library = await Database.libraryModel.create({ name: 'Test Library', mediaType: 'book' })
|
||||
book = await Database.bookModel.create({ title: 'Test Book', audioFiles: [], tags: [], narrators: [], genres: [], chapters: [] })
|
||||
book.authors = []
|
||||
book.series = []
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
sinon.restore()
|
||||
await Database.sequelize.sync({ force: true })
|
||||
})
|
||||
|
||||
it('does not throw when the bookSeries link already exists', async () => {
|
||||
const series = await Database.seriesModel.create({ name: 'Crescent City', libraryId: library.id })
|
||||
await Database.bookSeriesModel.create({ bookId: book.id, seriesId: series.id, sequence: '3' })
|
||||
|
||||
const result = await book.updateSeriesFromRequest([{ name: 'Crescent City', sequence: '3' }], library.id)
|
||||
|
||||
expect(result.hasUpdates).to.be.false
|
||||
const links = await Database.bookSeriesModel.findAll({ where: { bookId: book.id, seriesId: series.id } })
|
||||
expect(links).to.have.lengthOf(1)
|
||||
})
|
||||
|
||||
it('reuses an existing series when create hits the name unique constraint', async () => {
|
||||
const series = await Database.seriesModel.create({ name: 'Crescent City', libraryId: library.id })
|
||||
sinon.stub(Database.seriesModel, 'getByNameAndLibrary').resolves(null)
|
||||
|
||||
const result = await book.updateSeriesFromRequest([{ name: 'Crescent City', sequence: '3' }], library.id)
|
||||
|
||||
expect(result.seriesAdded).to.have.lengthOf(1)
|
||||
expect(result.seriesAdded[0].id).to.equal(series.id)
|
||||
const seriesRows = await Database.seriesModel.findAll({ where: { libraryId: library.id, name: 'Crescent City' } })
|
||||
expect(seriesRows).to.have.lengthOf(1)
|
||||
const links = await Database.bookSeriesModel.findAll({ where: { bookId: book.id, seriesId: series.id } })
|
||||
expect(links).to.have.lengthOf(1)
|
||||
})
|
||||
|
||||
it('does not throw when the bookAuthor link already exists', async () => {
|
||||
const author = await Database.authorModel.create({ name: 'Sarah Maas', libraryId: library.id })
|
||||
await Database.bookAuthorModel.create({ bookId: book.id, authorId: author.id })
|
||||
|
||||
const result = await book.updateAuthorsFromRequest(['Sarah Maas'], library.id)
|
||||
|
||||
expect(result.authorsAdded).to.have.lengthOf(0)
|
||||
const links = await Database.bookAuthorModel.findAll({ where: { bookId: book.id, authorId: author.id } })
|
||||
expect(links).to.have.lengthOf(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,53 @@
|
||||
const iTunes = require('../../../server/providers/iTunes')
|
||||
const { expect } = require('chai')
|
||||
|
||||
describe('iTunes', () => {
|
||||
let itunes
|
||||
|
||||
beforeEach(() => {
|
||||
itunes = new iTunes()
|
||||
})
|
||||
|
||||
describe('cleanAudiobook', () => {
|
||||
function authorFrom(artistName) {
|
||||
return itunes.cleanAudiobook({ artistName }).author
|
||||
}
|
||||
|
||||
it('should return an empty string if artistName is missing', () => {
|
||||
expect(authorFrom()).to.equal('')
|
||||
expect(authorFrom('')).to.equal('')
|
||||
})
|
||||
|
||||
it('should keep a single author without commas', () => {
|
||||
expect(authorFrom('Joy Fielding')).to.equal('Joy Fielding')
|
||||
})
|
||||
|
||||
it('should strip commas from a single author with a credential', () => {
|
||||
expect(authorFrom('Rick Hanson, PhD')).to.equal('Rick Hanson PhD')
|
||||
})
|
||||
|
||||
it('should split two authors joined by an ampersand', () => {
|
||||
expect(authorFrom('Name1 & Name2')).to.equal('Name1, Name2')
|
||||
})
|
||||
|
||||
it('should split three authors using commas and an ampersand', () => {
|
||||
expect(authorFrom('Keltie Knight, Becca Tobin & Jac Vanek')).to.equal('Keltie Knight, Becca Tobin, Jac Vanek')
|
||||
})
|
||||
|
||||
it('should glue a one-word credential onto the previous author before the ampersand', () => {
|
||||
expect(authorFrom('Rick Hanson, PhD & Jane Doe')).to.equal('Rick Hanson PhD, Jane Doe')
|
||||
})
|
||||
|
||||
it('should glue several one-word credentials in a row', () => {
|
||||
expect(authorFrom('Rick Hanson, PhD, MD & Jane Doe')).to.equal('Rick Hanson PhD MD, Jane Doe')
|
||||
})
|
||||
|
||||
it('should strip commas from the last author', () => {
|
||||
expect(authorFrom('Rick Hanson & Jane Doe, PhD')).to.equal('Rick Hanson, Jane Doe PhD')
|
||||
})
|
||||
|
||||
it('should glue credentials before the ampersand and strip commas from the last author', () => {
|
||||
expect(authorFrom('Rick Hanson, PhD & Jane Doe, PhD')).to.equal('Rick Hanson PhD, Jane Doe PhD')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,123 @@
|
||||
const { expect } = require('chai')
|
||||
const { Sequelize } = require('sequelize')
|
||||
const sinon = require('sinon')
|
||||
|
||||
const Database = require('../../../server/Database')
|
||||
const Logger = require('../../../server/Logger')
|
||||
const BookScanner = require('../../../server/scanner/BookScanner')
|
||||
const LibraryScan = require('../../../server/scanner/LibraryScan')
|
||||
|
||||
describe('BookScanner.rescanExistingBookLibraryItem', () => {
|
||||
/** @type {import('../../../server/models/Library')} */
|
||||
let library
|
||||
/** @type {import('../../../server/models/LibraryItem')} */
|
||||
let libraryItem
|
||||
/** @type {import('../../../server/models/Book')} */
|
||||
let book
|
||||
/** @type {LibraryScan} */
|
||||
let libraryScan
|
||||
|
||||
const librarySettings = { audiobooksOnly: true }
|
||||
|
||||
beforeEach(async () => {
|
||||
global.ServerSettings = {}
|
||||
Database.sequelize = new Sequelize({ dialect: 'sqlite', storage: ':memory:', logging: false })
|
||||
Database.sequelize.uppercaseFirst = (str) => (str ? `${str[0].toUpperCase()}${str.substr(1)}` : '')
|
||||
await Database.buildModels()
|
||||
|
||||
sinon.stub(Logger, 'info')
|
||||
sinon.stub(Logger, 'debug')
|
||||
sinon.stub(Logger, 'warn')
|
||||
sinon.stub(Logger, 'error')
|
||||
|
||||
library = await Database.libraryModel.create({ name: 'Test Library', mediaType: 'book' })
|
||||
const libraryFolder = await Database.libraryFolderModel.create({ path: '/test', libraryId: library.id })
|
||||
book = await Database.bookModel.create({ title: 'Test Book', audioFiles: [], tags: [], narrators: [], genres: [], chapters: [], coverPath: '/cover.jpg' })
|
||||
libraryItem = await Database.libraryItemModel.create({
|
||||
libraryFiles: [],
|
||||
mediaId: book.id,
|
||||
mediaType: 'book',
|
||||
libraryId: library.id,
|
||||
libraryFolderId: libraryFolder.id
|
||||
})
|
||||
libraryItem.isMissing = true
|
||||
libraryItem.isFile = true
|
||||
// Stale associations: the rows exist in the database, but this scan's loaded book does not see them
|
||||
sinon.stub(libraryItem, 'getMedia').callsFake(async () => {
|
||||
book.authors = []
|
||||
book.series = []
|
||||
book.audioFiles = []
|
||||
book.coverPath = '/cover.jpg'
|
||||
return book
|
||||
})
|
||||
|
||||
libraryScan = new LibraryScan()
|
||||
libraryScan.library = library
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
sinon.restore()
|
||||
await Database.sequelize.sync({ force: true })
|
||||
})
|
||||
|
||||
function scanData() {
|
||||
return {
|
||||
hasAudioFileChanges: false,
|
||||
audioLibraryFiles: [],
|
||||
imageLibraryFiles: [],
|
||||
imageLibraryFilesRemoved: [],
|
||||
imageLibraryFilesModified: [],
|
||||
ebookLibraryFiles: [],
|
||||
ebookLibraryFilesModified: [],
|
||||
libraryId: library.id
|
||||
}
|
||||
}
|
||||
|
||||
it('does not throw when the bookSeries link already exists', async () => {
|
||||
const series = await Database.seriesModel.create({ name: 'Crescent City', libraryId: library.id })
|
||||
await Database.bookSeriesModel.create({ bookId: book.id, seriesId: series.id, sequence: '3' })
|
||||
sinon.stub(BookScanner, 'getBookMetadataFromScanData').resolves({
|
||||
title: 'Test Book',
|
||||
authors: [],
|
||||
series: [{ name: 'Crescent City', sequence: '3' }]
|
||||
})
|
||||
|
||||
const result = await BookScanner.rescanExistingBookLibraryItem(libraryItem, scanData(), librarySettings, libraryScan)
|
||||
|
||||
expect(result.wasUpdated).to.be.true
|
||||
const links = await Database.bookSeriesModel.findAll({ where: { bookId: book.id, seriesId: series.id } })
|
||||
expect(links).to.have.lengthOf(1)
|
||||
})
|
||||
|
||||
it('reuses an existing series when create hits the name unique constraint', async () => {
|
||||
const series = await Database.seriesModel.create({ name: 'Crescent City', libraryId: library.id })
|
||||
sinon.stub(Database, 'getSeriesIdByName').resolves(null)
|
||||
sinon.stub(BookScanner, 'getBookMetadataFromScanData').resolves({
|
||||
title: 'Test Book',
|
||||
authors: [],
|
||||
series: [{ name: 'Crescent City', sequence: '3' }]
|
||||
})
|
||||
|
||||
await BookScanner.rescanExistingBookLibraryItem(libraryItem, scanData(), librarySettings, libraryScan)
|
||||
|
||||
const seriesRows = await Database.seriesModel.findAll({ where: { libraryId: library.id, name: 'Crescent City' } })
|
||||
expect(seriesRows).to.have.lengthOf(1)
|
||||
const links = await Database.bookSeriesModel.findAll({ where: { bookId: book.id, seriesId: series.id } })
|
||||
expect(links).to.have.lengthOf(1)
|
||||
})
|
||||
|
||||
it('does not throw when the bookAuthor link already exists', async () => {
|
||||
const author = await Database.authorModel.create({ name: 'Sarah Maas', libraryId: library.id })
|
||||
await Database.bookAuthorModel.create({ bookId: book.id, authorId: author.id })
|
||||
sinon.stub(BookScanner, 'getBookMetadataFromScanData').resolves({
|
||||
title: 'Test Book',
|
||||
authors: ['Sarah Maas'],
|
||||
series: []
|
||||
})
|
||||
|
||||
await BookScanner.rescanExistingBookLibraryItem(libraryItem, scanData(), librarySettings, libraryScan)
|
||||
|
||||
const links = await Database.bookAuthorModel.findAll({ where: { bookId: book.id, authorId: author.id } })
|
||||
expect(links).to.have.lengthOf(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,120 @@
|
||||
const { expect } = require('chai')
|
||||
const { Sequelize } = require('sequelize')
|
||||
const sinon = require('sinon')
|
||||
|
||||
const Database = require('../../../server/Database')
|
||||
const Logger = require('../../../server/Logger')
|
||||
const Scanner = require('../../../server/scanner/Scanner')
|
||||
|
||||
describe('Scanner.quickMatchBookBuildUpdatePayload', () => {
|
||||
/** @type {import('../../../server/models/Library')} */
|
||||
let library
|
||||
/** @type {import('../../../server/models/LibraryItem')} */
|
||||
let libraryItem
|
||||
/** @type {import('../../../server/models/Book')} */
|
||||
let book
|
||||
|
||||
const apiRouterCtx = {
|
||||
checkRemoveAuthorsWithNoBooks: sinon.stub().resolves(),
|
||||
checkRemoveEmptySeries: sinon.stub().resolves()
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
global.ServerSettings = {}
|
||||
Database.sequelize = new Sequelize({ dialect: 'sqlite', storage: ':memory:', logging: false })
|
||||
Database.sequelize.uppercaseFirst = (str) => (str ? `${str[0].toUpperCase()}${str.substr(1)}` : '')
|
||||
await Database.buildModels()
|
||||
|
||||
sinon.stub(Logger, 'info')
|
||||
sinon.stub(Logger, 'debug')
|
||||
sinon.stub(Logger, 'warn')
|
||||
sinon.stub(Logger, 'error')
|
||||
|
||||
library = await Database.libraryModel.create({ name: 'Test Library', mediaType: 'book' })
|
||||
const libraryFolder = await Database.libraryFolderModel.create({ path: '/test', libraryId: library.id })
|
||||
book = await Database.bookModel.create({ title: 'Test Book', audioFiles: [], tags: [], narrators: [], genres: [], chapters: [] })
|
||||
libraryItem = await Database.libraryItemModel.create({
|
||||
libraryFiles: [],
|
||||
mediaId: book.id,
|
||||
mediaType: 'book',
|
||||
libraryId: library.id,
|
||||
libraryFolderId: libraryFolder.id
|
||||
})
|
||||
libraryItem.media = book
|
||||
// Stale in-memory associations: DB may already have links from a concurrent quick match
|
||||
book.authors = []
|
||||
book.series = []
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
sinon.restore()
|
||||
await Database.sequelize.sync({ force: true })
|
||||
})
|
||||
|
||||
it('does not throw when bookSeries link already exists from a concurrent quick match', async () => {
|
||||
const series = await Database.seriesModel.create({ name: 'Crescent City', libraryId: library.id })
|
||||
await Database.bookSeriesModel.create({ bookId: book.id, seriesId: series.id, sequence: '3' })
|
||||
|
||||
const result = await Scanner.quickMatchBookBuildUpdatePayload(
|
||||
apiRouterCtx,
|
||||
libraryItem,
|
||||
{
|
||||
series: [{ series: 'Crescent City', sequence: '3' }]
|
||||
},
|
||||
{}
|
||||
)
|
||||
|
||||
expect(result.hasSeriesUpdates).to.be.true
|
||||
expect(libraryItem.media.series).to.have.lengthOf(1)
|
||||
expect(libraryItem.media.series[0].id).to.equal(series.id)
|
||||
expect(libraryItem.media.series[0].bookSeries).to.exist
|
||||
expect(libraryItem.media.series[0].bookSeries.sequence).to.equal('3')
|
||||
|
||||
const links = await Database.bookSeriesModel.findAll({ where: { bookId: book.id, seriesId: series.id } })
|
||||
expect(links).to.have.lengthOf(1)
|
||||
})
|
||||
|
||||
it('reuses an existing series when create hits the name unique constraint', async () => {
|
||||
const series = await Database.seriesModel.create({ name: 'Crescent City', libraryId: library.id })
|
||||
sinon.stub(Database.seriesModel, 'getByNameAndLibrary').resolves(null)
|
||||
|
||||
const result = await Scanner.quickMatchBookBuildUpdatePayload(
|
||||
apiRouterCtx,
|
||||
libraryItem,
|
||||
{
|
||||
series: [{ series: 'Crescent City', sequence: '3' }]
|
||||
},
|
||||
{}
|
||||
)
|
||||
|
||||
expect(result.hasSeriesUpdates).to.be.true
|
||||
expect(libraryItem.media.series).to.have.lengthOf(1)
|
||||
expect(libraryItem.media.series[0].id).to.equal(series.id)
|
||||
|
||||
const seriesRows = await Database.seriesModel.findAll({ where: { libraryId: library.id, name: 'Crescent City' } })
|
||||
expect(seriesRows).to.have.lengthOf(1)
|
||||
const links = await Database.bookSeriesModel.findAll({ where: { bookId: book.id, seriesId: series.id } })
|
||||
expect(links).to.have.lengthOf(1)
|
||||
})
|
||||
|
||||
it('does not throw when bookAuthor link already exists from a concurrent quick match', async () => {
|
||||
const author = await Database.authorModel.create({ name: 'Sarah Maas', libraryId: library.id })
|
||||
await Database.bookAuthorModel.create({ bookId: book.id, authorId: author.id })
|
||||
|
||||
const result = await Scanner.quickMatchBookBuildUpdatePayload(
|
||||
apiRouterCtx,
|
||||
libraryItem,
|
||||
{
|
||||
author: ['Sarah Maas']
|
||||
},
|
||||
{}
|
||||
)
|
||||
|
||||
expect(result.hasAuthorUpdates).to.be.true
|
||||
expect(libraryItem.media.authors).to.have.lengthOf(1)
|
||||
expect(libraryItem.media.authors[0].id).to.equal(author.id)
|
||||
|
||||
const links = await Database.bookAuthorModel.findAll({ where: { bookId: book.id, authorId: author.id } })
|
||||
expect(links).to.have.lengthOf(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,221 @@
|
||||
const { expect } = require('chai')
|
||||
const express = require('express')
|
||||
const fs = require('fs')
|
||||
const http = require('http')
|
||||
const os = require('os')
|
||||
const path = require('path')
|
||||
const sinon = require('sinon')
|
||||
|
||||
const Logger = require('../../../server/Logger')
|
||||
const { fileUploadParser, requireUploadPermission, sweepUploadTempFiles } = require('../../../server/utils/fileUploadMiddleware')
|
||||
|
||||
function listTmpFiles(dir) {
|
||||
if (!fs.existsSync(dir)) return []
|
||||
return fs.readdirSync(dir).filter((name) => name.startsWith('tmp-'))
|
||||
}
|
||||
|
||||
function sendMultipart(port, urlPath, extraHeaders = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const boundary = '----AbsUploadTestBoundary'
|
||||
const payload = [
|
||||
`--${boundary}`,
|
||||
'Content-Disposition: form-data; name="f"; filename="probe.txt"',
|
||||
'Content-Type: text/plain',
|
||||
'',
|
||||
'probe',
|
||||
`--${boundary}--`,
|
||||
''
|
||||
].join('\r\n')
|
||||
|
||||
const req = http.request(
|
||||
{
|
||||
hostname: '127.0.0.1',
|
||||
port,
|
||||
path: urlPath,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': `multipart/form-data; boundary=${boundary}`,
|
||||
'Content-Length': Buffer.byteLength(payload),
|
||||
...extraHeaders
|
||||
}
|
||||
},
|
||||
(res) => {
|
||||
res.resume()
|
||||
res.on('end', () => resolve(res.statusCode))
|
||||
}
|
||||
)
|
||||
req.on('error', reject)
|
||||
req.write(payload)
|
||||
req.end()
|
||||
})
|
||||
}
|
||||
|
||||
function listen(app) {
|
||||
const server = http.createServer(app)
|
||||
return new Promise((resolve) => {
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
resolve({ server, port: server.address().port })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function closeServer(server) {
|
||||
return new Promise((resolve, reject) => {
|
||||
server.close((err) => (err ? reject(err) : resolve()))
|
||||
})
|
||||
}
|
||||
|
||||
async function waitFor(predicate, timeoutMs = 2000) {
|
||||
const started = Date.now()
|
||||
while (Date.now() - started < timeoutMs) {
|
||||
if (predicate()) return
|
||||
await new Promise((resolve) => setTimeout(resolve, 25))
|
||||
}
|
||||
throw new Error('Timed out waiting for condition')
|
||||
}
|
||||
|
||||
describe('fileUploadMiddleware', () => {
|
||||
let metadataDir
|
||||
let tmpDir
|
||||
let previousMetadataPath
|
||||
|
||||
beforeEach(() => {
|
||||
previousMetadataPath = global.MetadataPath
|
||||
metadataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'abs-upload-meta-'))
|
||||
tmpDir = path.join(metadataDir, 'tmp')
|
||||
global.MetadataPath = metadataDir
|
||||
sinon.stub(Logger, 'info')
|
||||
sinon.stub(Logger, 'warn')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore()
|
||||
global.MetadataPath = previousMetadataPath
|
||||
fs.rmSync(metadataDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
describe('requireUploadPermission', () => {
|
||||
it('returns 403 when the user cannot upload', () => {
|
||||
const req = { user: { canUpload: false, username: 'guest' } }
|
||||
const res = { sendStatus: sinon.stub() }
|
||||
const next = sinon.stub()
|
||||
|
||||
requireUploadPermission(req, res, next)
|
||||
|
||||
expect(res.sendStatus.calledOnceWithExactly(403)).to.equal(true)
|
||||
expect(next.called).to.equal(false)
|
||||
})
|
||||
|
||||
it('calls next when the user can upload', () => {
|
||||
const req = { user: { canUpload: true, username: 'uploader' } }
|
||||
const res = { sendStatus: sinon.stub() }
|
||||
const next = sinon.stub()
|
||||
|
||||
requireUploadPermission(req, res, next)
|
||||
|
||||
expect(next.calledOnce).to.equal(true)
|
||||
expect(res.sendStatus.called).to.equal(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('sweepUploadTempFiles', () => {
|
||||
it('removes leftover tmp-* files and leaves other names', async () => {
|
||||
fs.mkdirSync(tmpDir, { recursive: true })
|
||||
fs.writeFileSync(path.join(tmpDir, 'tmp-1-123'), 'stale')
|
||||
fs.writeFileSync(path.join(tmpDir, 'tmp-2-456'), 'stale')
|
||||
fs.writeFileSync(path.join(tmpDir, 'comic-extract-keep'), 'keep')
|
||||
fs.mkdirSync(path.join(tmpDir, 'tmp-not-a-file'))
|
||||
|
||||
await sweepUploadTempFiles()
|
||||
|
||||
expect(fs.existsSync(path.join(tmpDir, 'tmp-1-123'))).to.equal(false)
|
||||
expect(fs.existsSync(path.join(tmpDir, 'tmp-2-456'))).to.equal(false)
|
||||
expect(fs.existsSync(path.join(tmpDir, 'comic-extract-keep'))).to.equal(true)
|
||||
expect(fs.existsSync(path.join(tmpDir, 'tmp-not-a-file'))).to.equal(true)
|
||||
})
|
||||
|
||||
it('returns when the temp directory does not exist', async () => {
|
||||
await sweepUploadTempFiles()
|
||||
expect(fs.existsSync(tmpDir)).to.equal(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('upload parser mounting', () => {
|
||||
it('does not write tmp-* files for a route without the parser', async () => {
|
||||
const app = express()
|
||||
app.use((req, res) => res.sendStatus(404))
|
||||
const { server, port } = await listen(app)
|
||||
|
||||
try {
|
||||
const status = await sendMultipart(port, '/not-a-route')
|
||||
expect(status).to.equal(404)
|
||||
expect(listTmpFiles(tmpDir)).to.deep.equal([])
|
||||
} finally {
|
||||
await closeServer(server)
|
||||
}
|
||||
})
|
||||
|
||||
it('does not write tmp-* files when permission is rejected before parsing', async () => {
|
||||
const app = express()
|
||||
app.use((req, res, next) => {
|
||||
req.user = { canUpload: false, username: 'guest' }
|
||||
next()
|
||||
})
|
||||
app.post('/upload', requireUploadPermission, fileUploadParser, (req, res) => {
|
||||
res.sendStatus(200)
|
||||
})
|
||||
const { server, port } = await listen(app)
|
||||
|
||||
try {
|
||||
const status = await sendMultipart(port, '/upload')
|
||||
expect(status).to.equal(403)
|
||||
expect(listTmpFiles(tmpDir)).to.deep.equal([])
|
||||
} finally {
|
||||
await closeServer(server)
|
||||
}
|
||||
})
|
||||
|
||||
it('removes the temp file when the handler rejects without moving it', async () => {
|
||||
const app = express()
|
||||
app.use((req, res, next) => {
|
||||
req.user = { canUpload: true, username: 'uploader' }
|
||||
next()
|
||||
})
|
||||
app.post('/upload', requireUploadPermission, fileUploadParser, (req, res) => {
|
||||
res.status(400).send('Invalid request no file or url')
|
||||
})
|
||||
const { server, port } = await listen(app)
|
||||
|
||||
try {
|
||||
const status = await sendMultipart(port, '/upload')
|
||||
expect(status).to.equal(400)
|
||||
await waitFor(() => listTmpFiles(tmpDir).length === 0)
|
||||
} finally {
|
||||
await closeServer(server)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps a moved file and leaves no tmp-* leftover', async () => {
|
||||
const dest = path.join(metadataDir, 'moved.txt')
|
||||
const app = express()
|
||||
app.use((req, res, next) => {
|
||||
req.user = { canUpload: true, username: 'uploader' }
|
||||
next()
|
||||
})
|
||||
app.post('/upload', requireUploadPermission, fileUploadParser, async (req, res) => {
|
||||
await req.files.f.mv(dest)
|
||||
res.sendStatus(200)
|
||||
})
|
||||
const { server, port } = await listen(app)
|
||||
|
||||
try {
|
||||
const status = await sendMultipart(port, '/upload')
|
||||
expect(status).to.equal(200)
|
||||
expect(fs.readFileSync(dest, 'utf8')).to.equal('probe')
|
||||
await waitFor(() => listTmpFiles(tmpDir).length === 0)
|
||||
} finally {
|
||||
await closeServer(server)
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -134,4 +134,60 @@ describe('fileUtils', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('isSameOrSubPath and isStrictSubPath', () => {
|
||||
let prevIsWin
|
||||
|
||||
beforeEach(() => {
|
||||
prevIsWin = global.isWin
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
global.isWin = prevIsWin
|
||||
})
|
||||
|
||||
it('identifies POSIX same paths, subpaths, and paths outside the parent', () => {
|
||||
global.isWin = false
|
||||
|
||||
expect(fileUtils.isSameOrSubPath('/a/b', '/a/b')).to.equal(true)
|
||||
expect(fileUtils.isSameOrSubPath('/a/b/', '/a/b')).to.equal(true)
|
||||
expect(fileUtils.isSameOrSubPath('/a/b', '/a/b/')).to.equal(true)
|
||||
expect(fileUtils.isSameOrSubPath('/a/b', '/a/b/c')).to.equal(true)
|
||||
expect(fileUtils.isSameOrSubPath('/a/b', '/a/b/..foo')).to.equal(true)
|
||||
|
||||
expect(fileUtils.isSameOrSubPath('/a/b', '/a/bc')).to.equal(false)
|
||||
expect(fileUtils.isSameOrSubPath('/a/b', '/a')).to.equal(false)
|
||||
expect(fileUtils.isSameOrSubPath('/a/b', '/a/b/../c')).to.equal(false)
|
||||
|
||||
expect(fileUtils.isStrictSubPath('/a/b', '/a/b')).to.equal(false)
|
||||
expect(fileUtils.isStrictSubPath('/a/b/', '/a/b')).to.equal(false)
|
||||
expect(fileUtils.isStrictSubPath('/a/b', '/a/b/')).to.equal(false)
|
||||
expect(fileUtils.isStrictSubPath('/a/b', '/a/b/c')).to.equal(true)
|
||||
expect(fileUtils.isStrictSubPath('/a/b', '/a/b/..foo')).to.equal(true)
|
||||
expect(fileUtils.isStrictSubPath('/a/b', '/a/bc')).to.equal(false)
|
||||
})
|
||||
|
||||
it('matches standard and Windows namespaced drive and UNC paths', () => {
|
||||
global.isWin = true
|
||||
|
||||
expect(fileUtils.isSameOrSubPath('C:\\lib\\Author', '\\\\?\\C:\\lib\\Author')).to.equal(true)
|
||||
expect(fileUtils.isSameOrSubPath('\\\\?\\C:\\lib\\Author', 'C:\\lib\\Author\\Book')).to.equal(true)
|
||||
expect(fileUtils.isSameOrSubPath('C:/lib', '\\\\?\\C:\\lib\\Author')).to.equal(true)
|
||||
expect(fileUtils.isSameOrSubPath('C:\\lib', 'C:\\lib\\..foo')).to.equal(true)
|
||||
expect(fileUtils.isSameOrSubPath('\\\\server\\share\\lib', '\\\\?\\UNC\\server\\share\\lib\\Author')).to.equal(true)
|
||||
expect(fileUtils.isSameOrSubPath('\\\\server/share/lib', '\\\\?\\UNC\\server\\share\\lib\\Author')).to.equal(true)
|
||||
expect(fileUtils.isSameOrSubPath('\\\\?\\UNC\\server\\share\\lib', '\\\\server\\share\\lib\\Author')).to.equal(true)
|
||||
expect(fileUtils.isSameOrSubPath('\\\\?\\Volume{1234}\\lib', '\\\\?\\Volume{1234}\\lib\\Author')).to.equal(true)
|
||||
|
||||
expect(fileUtils.isSameOrSubPath('C:\\lib', '\\\\?\\D:\\lib\\Author')).to.equal(false)
|
||||
expect(fileUtils.isSameOrSubPath('C:\\lib', 'C:\\lib2\\Author')).to.equal(false)
|
||||
expect(fileUtils.isSameOrSubPath('\\\\server\\share\\lib', '\\\\other\\share\\lib\\Author')).to.equal(false)
|
||||
expect(fileUtils.isSameOrSubPath('\\\\?\\UNC\\server\\share\\lib', '\\\\other\\share\\lib\\Author')).to.equal(false)
|
||||
expect(fileUtils.isSameOrSubPath('\\\\?\\C:\\lib', '\\\\?\\UNC\\server\\share\\lib')).to.equal(false)
|
||||
|
||||
expect(fileUtils.isStrictSubPath('\\\\?\\C:\\lib\\Author', 'C:\\lib\\Author')).to.equal(false)
|
||||
expect(fileUtils.isStrictSubPath('\\\\?\\C:\\lib\\Author', 'C:\\lib\\Author\\Book')).to.equal(true)
|
||||
expect(fileUtils.isStrictSubPath('\\\\server\\share\\lib', '\\\\?\\UNC\\server\\share\\lib\\Author')).to.equal(true)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
const chai = require('chai')
|
||||
const expect = chai.expect
|
||||
const { parse, nameToLastFirst } = require('../../../../server/utils/parsers/parseNameString')
|
||||
const { parse, nameToLastFirst, dedupeNames } = require('../../../../server/utils/parsers/parseNameString')
|
||||
|
||||
describe('parseNameString', () => {
|
||||
describe('parse', () => {
|
||||
@@ -80,6 +80,20 @@ describe('parseNameString', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('dedupeNames', () => {
|
||||
it('trims, drops blanks, and keeps the first spelling of an exact repeat', () => {
|
||||
expect(dedupeNames([' Stephen King ', 'Stephen King', '', ' ', 'stephen king'])).to.deep.equal(['Stephen King', 'stephen king'])
|
||||
})
|
||||
|
||||
it('preserves order and ignores non-strings', () => {
|
||||
expect(dedupeNames(['Amy Yao', null, 'Amy Yao', 3, 'Raymond Chandler'])).to.deep.equal(['Amy Yao', 'Raymond Chandler'])
|
||||
})
|
||||
|
||||
it('returns an empty array for non-arrays', () => {
|
||||
expect(dedupeNames(null)).to.deep.equal([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('nameToLastFirst', () => {
|
||||
it('converts First Last to Last, First format', () => {
|
||||
const result = nameToLastFirst('John Smith')
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
const { expect } = require('chai')
|
||||
const express = require('express')
|
||||
const http = require('http')
|
||||
const sinon = require('sinon')
|
||||
|
||||
const Logger = require('../../../server/Logger')
|
||||
const RateLimiterFactory = require('../../../server/utils/rateLimiterFactory')
|
||||
|
||||
function listen(app) {
|
||||
const server = http.createServer(app)
|
||||
return new Promise((resolve) => {
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
resolve({ server, port: server.address().port })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function closeServer(server) {
|
||||
return new Promise((resolve, reject) => {
|
||||
server.close((err) => (err ? reject(err) : resolve()))
|
||||
})
|
||||
}
|
||||
|
||||
function patchPassword(port, { userId, headers = {} } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const body = JSON.stringify({ password: 'current', newPassword: 'next' })
|
||||
const req = http.request(
|
||||
{
|
||||
hostname: '127.0.0.1',
|
||||
port,
|
||||
path: '/me/password',
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
'User-Agent': 'rate-limiter-test',
|
||||
'x-user-id': userId,
|
||||
...headers
|
||||
}
|
||||
},
|
||||
(res) => {
|
||||
res.resume()
|
||||
res.on('end', () => resolve({ status: res.statusCode }))
|
||||
}
|
||||
)
|
||||
req.on('error', reject)
|
||||
req.write(body)
|
||||
req.end()
|
||||
})
|
||||
}
|
||||
|
||||
function passwordChangeApp(limiter) {
|
||||
const app = express()
|
||||
app.patch(
|
||||
'/me/password',
|
||||
(req, res, next) => {
|
||||
const userId = req.get('x-user-id')
|
||||
if (userId) req.user = { id: userId }
|
||||
next()
|
||||
},
|
||||
limiter,
|
||||
(req, res) => {
|
||||
res.status(400).send('Invalid password')
|
||||
}
|
||||
)
|
||||
return app
|
||||
}
|
||||
|
||||
function postLogin(port, { headers = {} } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const body = JSON.stringify({ username: 'alice', password: 'guess' })
|
||||
const req = http.request(
|
||||
{
|
||||
hostname: '127.0.0.1',
|
||||
port,
|
||||
path: '/login',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
'User-Agent': 'rate-limiter-test',
|
||||
...headers
|
||||
}
|
||||
},
|
||||
(res) => {
|
||||
let data = ''
|
||||
res.on('data', (chunk) => {
|
||||
data += chunk
|
||||
})
|
||||
res.on('end', () => {
|
||||
resolve({ status: res.statusCode, body: data, headers: res.headers })
|
||||
})
|
||||
}
|
||||
)
|
||||
req.on('error', reject)
|
||||
req.write(body)
|
||||
req.end()
|
||||
})
|
||||
}
|
||||
|
||||
describe('rateLimiterFactory', () => {
|
||||
const previousMax = process.env.RATE_LIMIT_AUTH_MAX
|
||||
const previousWindow = process.env.RATE_LIMIT_AUTH_WINDOW
|
||||
const previousMessage = process.env.RATE_LIMIT_AUTH_MESSAGE
|
||||
|
||||
beforeEach(() => {
|
||||
RateLimiterFactory.authRateLimiter = null
|
||||
RateLimiterFactory.passwordChangeRateLimiter = null
|
||||
process.env.RATE_LIMIT_AUTH_MAX = '3'
|
||||
process.env.RATE_LIMIT_AUTH_WINDOW = '60000'
|
||||
delete process.env.RATE_LIMIT_AUTH_MESSAGE
|
||||
sinon.stub(Logger, 'info')
|
||||
sinon.stub(Logger, 'warn')
|
||||
sinon.stub(Logger, 'debug')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
RateLimiterFactory.authRateLimiter = null
|
||||
RateLimiterFactory.passwordChangeRateLimiter = null
|
||||
if (previousMax === undefined) delete process.env.RATE_LIMIT_AUTH_MAX
|
||||
else process.env.RATE_LIMIT_AUTH_MAX = previousMax
|
||||
if (previousWindow === undefined) delete process.env.RATE_LIMIT_AUTH_WINDOW
|
||||
else process.env.RATE_LIMIT_AUTH_WINDOW = previousWindow
|
||||
if (previousMessage === undefined) delete process.env.RATE_LIMIT_AUTH_MESSAGE
|
||||
else process.env.RATE_LIMIT_AUTH_MESSAGE = previousMessage
|
||||
sinon.restore()
|
||||
})
|
||||
|
||||
it('shares one bucket across rotating client IP headers and returns 429 after max failures', async () => {
|
||||
const app = express()
|
||||
const limiter = RateLimiterFactory.getAuthRateLimiter()
|
||||
app.post('/login', limiter, (req, res) => {
|
||||
res.status(401).json({ error: 'Unauthorized' })
|
||||
})
|
||||
|
||||
const { server, port } = await listen(app)
|
||||
try {
|
||||
const statuses = []
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const result = await postLogin(port, {
|
||||
headers: {
|
||||
'X-Client-IP': `10.0.0.${i}`,
|
||||
'X-Forwarded-For': `203.0.113.${i}`
|
||||
}
|
||||
})
|
||||
statuses.push(result.status)
|
||||
}
|
||||
|
||||
expect(statuses).to.deep.equal([401, 401, 401, 429])
|
||||
} finally {
|
||||
await closeServer(server)
|
||||
}
|
||||
})
|
||||
|
||||
it('does not consume a slot for successful logins', async () => {
|
||||
const app = express()
|
||||
const limiter = RateLimiterFactory.getAuthRateLimiter()
|
||||
let attempt = 0
|
||||
app.post('/login', limiter, (req, res) => {
|
||||
attempt += 1
|
||||
if (attempt === 1) {
|
||||
return res.status(200).json({ ok: true })
|
||||
}
|
||||
res.status(401).json({ error: 'Unauthorized' })
|
||||
})
|
||||
|
||||
const { server, port } = await listen(app)
|
||||
try {
|
||||
const success = await postLogin(port)
|
||||
expect(success.status).to.equal(200)
|
||||
|
||||
const statuses = []
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const result = await postLogin(port, {
|
||||
headers: {
|
||||
'X-Client-IP': `10.1.0.${i}`
|
||||
}
|
||||
})
|
||||
statuses.push(result.status)
|
||||
}
|
||||
|
||||
expect(statuses).to.deep.equal([401, 401, 401, 429])
|
||||
} finally {
|
||||
await closeServer(server)
|
||||
}
|
||||
})
|
||||
|
||||
it('limits password changes per user and ignores client IP headers', async () => {
|
||||
const app = passwordChangeApp(RateLimiterFactory.getPasswordChangeRateLimiter())
|
||||
const { server, port } = await listen(app)
|
||||
try {
|
||||
const alice = []
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const result = await patchPassword(port, {
|
||||
userId: 'alice',
|
||||
headers: {
|
||||
'X-Client-IP': `10.2.0.${i}`,
|
||||
'X-Forwarded-For': `198.51.100.${i}`
|
||||
}
|
||||
})
|
||||
alice.push(result.status)
|
||||
}
|
||||
const bob = await patchPassword(port, { userId: 'bob' })
|
||||
|
||||
expect(alice).to.deep.equal([400, 400, 400, 429])
|
||||
expect(bob.status).to.equal(400)
|
||||
expect(Logger.warn.calledWithMatch(/User: alice/)).to.equal(true)
|
||||
} finally {
|
||||
await closeServer(server)
|
||||
}
|
||||
})
|
||||
|
||||
it('does not consume a password-change slot for a successful update', async () => {
|
||||
let attempt = 0
|
||||
const app = express()
|
||||
const limiter = RateLimiterFactory.getPasswordChangeRateLimiter()
|
||||
app.patch(
|
||||
'/me/password',
|
||||
(req, res, next) => {
|
||||
req.user = { id: 'alice' }
|
||||
next()
|
||||
},
|
||||
limiter,
|
||||
(req, res) => {
|
||||
attempt += 1
|
||||
res.status(attempt === 1 ? 200 : 400).send(attempt === 1 ? 'ok' : 'Invalid password')
|
||||
}
|
||||
)
|
||||
|
||||
const { server, port } = await listen(app)
|
||||
try {
|
||||
const success = await patchPassword(port, { userId: 'alice' })
|
||||
expect(success.status).to.equal(200)
|
||||
|
||||
const statuses = []
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const result = await patchPassword(port, { userId: 'alice' })
|
||||
statuses.push(result.status)
|
||||
}
|
||||
expect(statuses).to.deep.equal([400, 400, 400, 429])
|
||||
} finally {
|
||||
await closeServer(server)
|
||||
}
|
||||
})
|
||||
|
||||
it('can be disabled with RATE_LIMIT_AUTH_MAX=0', async () => {
|
||||
RateLimiterFactory.authRateLimiter = null
|
||||
process.env.RATE_LIMIT_AUTH_MAX = '0'
|
||||
|
||||
const app = express()
|
||||
const limiter = RateLimiterFactory.getAuthRateLimiter()
|
||||
app.post('/login', limiter, (req, res) => {
|
||||
res.status(401).json({ error: 'Unauthorized' })
|
||||
})
|
||||
|
||||
const { server, port } = await listen(app)
|
||||
try {
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const result = await postLogin(port)
|
||||
expect(result.status).to.equal(401)
|
||||
}
|
||||
} finally {
|
||||
await closeServer(server)
|
||||
}
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user