Compare commits

...

40 Commits

Author SHA1 Message Date
Luigi311
771b0a7eab Library: Async the SaveImages function (#15718) 2025-12-13 08:43:49 -07:00
renovate[bot]
4db0ab0f40 Update GitHub Artifact Actions (#15783)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2025-12-13 08:42:57 -07:00
dkanada
dd480f96cd parse more information from book filenames (#15655) 2025-12-13 08:29:28 -07:00
Niels van Velzen
6b6d54a07c Remove legacy API route middleware (#15669) 2025-12-13 08:26:22 -07:00
Bond-009
428beda1c7 Merge pull request #15780 from jellyfin/renovate/ci-deps
Update github/codeql-action action to v4.31.8
2025-12-13 10:43:57 +01:00
Bond-009
baa8d40940 Merge pull request #15774 from stevenaw/optimize-GetUniqueFlags
Optimize GetUniqueFlags<T>()
2025-12-12 18:00:25 +01:00
renovate[bot]
c8bdee26b7 Update github/codeql-action action to v4.31.8 2025-12-12 12:13:35 +00:00
stevenaw
ef73ed6ef7 optimize GetUniqueFlags() 2025-12-11 22:15:19 -05:00
Veldermon-rbg
d70e0fe9cf Translated using Weblate (Maori)
Translation: Jellyfin/Jellyfin
Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/mi/
2025-12-10 05:20:53 +00:00
Veldermon-rbg
053cc9406d Added translation using Weblate (Maori) 2025-12-10 00:29:33 +00:00
Bas
0f85120c5e Translated using Weblate (Dutch)
Translation: Jellyfin/Jellyfin
Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/nl/
2025-12-10 00:29:32 +00:00
Tom O'Neill
25aef7fabf Translated using Weblate (Dutch)
Translation: Jellyfin/Jellyfin
Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/nl/
2025-12-10 00:29:32 +00:00
Mark Cilia Vincenti
492ea66841 Proper pinning of SkiaSharp to prevent accidental updates (#15736) 2025-12-08 21:16:14 -07:00
evan314159
8b2a8b94b6 avoid Take(0) when limit == 0 (#14608)
Co-authored-by: Evan <evan@MacBook-Pro.local>
2025-12-08 21:15:46 -07:00
xin
f24e80701c Fix typo in CheckOrCreateMarker exception (#15341) 2025-12-08 21:06:17 -07:00
Cody Robibero
0b3d6676d1 Add ability to sort and filter activity log entries (#15583) 2025-12-08 21:01:32 -07:00
Mark Cilia Vincenti
c3a8734adf Locking cleaning (#15713) 2025-12-08 21:01:12 -07:00
audrey-inglish
8fd59d6f33 Merge pull request #14879 from audrey-inglish/master
Fix: normalize punctuation when computing CleanName so searches without punctuation match (closes #1674)
2025-12-08 18:43:37 +01:00
Bond-009
da3bff3edf Merge pull request #15433 from theguymadmax/fix-recently-added-shows
Fix episodes showing up on recently added shows
2025-12-08 18:38:50 +01:00
Bond-009
45cb5a0008 Merge pull request #15704 from theguymadmax/add-cpu-to-template
Add CPU to issue template
2025-12-05 20:50:59 +01:00
Bond-009
ea097fb1a3 Merge pull request #15706 from jellyfin/renovate/ci-deps
Update CI dependencies
2025-12-05 20:47:46 +01:00
renovate[bot]
a25b48b151 Update CI dependencies 2025-12-05 18:58:06 +00:00
Furqaan Dawood
873f1d9e83 Added translation using Weblate (Swahili) 2025-12-04 14:41:47 +00:00
Bond-009
294439bf74 Merge pull request #15682 from jellyfin/renovate/ci-deps
Update CI dependencies
2025-12-03 20:05:29 +01:00
crobibero
6e74be0d46 Backport pull request #15672 from jellyfin/release-10.11.z
Cache OpenApi document generation

Original-merge: 8cd5652157

Merged-by: anthonylavado <anthony@lavado.ca>

Backported-by: Bond_009 <bond.009@outlook.com>
2025-12-03 14:04:28 -05:00
nyanmisaka
deb81eae10 Backport pull request #15670 from jellyfin/release-10.11.z
Fix the empty output of trickplay on RK3576

Original-merge: 98d1d0cb35

Merged-by: nielsvanvelzen <nielsvanvelzen@users.noreply.github.com>

Backported-by: Bond_009 <bond.009@outlook.com>
2025-12-03 14:04:27 -05:00
theguymadmax
70dcf3f7b3 Backport pull request #15594 from jellyfin/release-10.11.z
Fix isMovie filter logic

Original-merge: 94f3725208

Merged-by: crobibero <cody@robibe.ro>

Backported-by: Bond_009 <bond.009@outlook.com>
2025-12-03 14:04:25 -05:00
QuintonQu
ebcfed83c4 Backport pull request #15582 from jellyfin/release-10.11.z
Add hidden file check in BdInfoDirectoryInfo.cs.

Original-merge: 29b3aa8543

Merged-by: crobibero <cody@robibe.ro>

Backported-by: Bond_009 <bond.009@outlook.com>
2025-12-03 14:04:24 -05:00
theguymadmax
5d46278584 Backport pull request #15568 from jellyfin/release-10.11.z
Fix ResolveLinkTarget crashing on exFAT drives

Original-merge: fbb9a0b2c7

Merged-by: crobibero <cody@robibe.ro>

Backported-by: Bond_009 <bond.009@outlook.com>
2025-12-03 14:04:23 -05:00
theguymadmax
4f020a947a Backport pull request #15564 from jellyfin/release-10.11.z
Fix locked fields not saving

Original-merge: 0ee81e87be

Merged-by: crobibero <cody@robibe.ro>

Backported-by: Bond_009 <bond.009@outlook.com>
2025-12-03 14:04:22 -05:00
theguymadmax
3460d1de3c Backport pull request #15563 from jellyfin/release-10.11.z
Save item to database before providers run to prevent FK errors

Original-merge: c491a918c2

Merged-by: crobibero <cody@robibe.ro>

Backported-by: Bond_009 <bond.009@outlook.com>
2025-12-03 14:04:20 -05:00
gnattu
7d2e4cd817 Backport pull request #15557 from jellyfin/release-10.11.z
Restrict first video frame probing to file protocol

Original-merge: ee7ad83427

Merged-by: crobibero <cody@robibe.ro>

Backported-by: Bond_009 <bond.009@outlook.com>
2025-12-03 14:04:19 -05:00
gnattu
8cd6ef37c4 Backport pull request #15556 from jellyfin/release-10.11.z
Prevent copying HDR streams when only SDR is supported

Original-merge: 1e7e46cb82

Merged-by: crobibero <cody@robibe.ro>

Backported-by: Bond_009 <bond.009@outlook.com>
2025-12-03 14:04:18 -05:00
theguymadmax
e4daaf0d83 Backport pull request #15548 from jellyfin/release-10.11.z
Fix NullReferenceException in filesystem path comparison

Original-merge: 5ae444d96d

Merged-by: crobibero <cody@robibe.ro>

Backported-by: Bond_009 <bond.009@outlook.com>
2025-12-03 14:04:17 -05:00
theguymadmax
69c98af9f9 Add CPU to issue template 2025-12-03 09:45:50 -05:00
renovate[bot]
7425a493ee Update CI dependencies 2025-12-03 05:30:25 +00:00
Hasan Abdulaal
691c194152 Translated using Weblate (Arabic)
Translation: Jellyfin/Jellyfin
Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ar/
2025-12-02 13:27:39 +00:00
Niels van Velzen
2f8896c375 Merge pull request #15538 from KarkaLT/master
Add subtitle extraction timeout configuration option
2025-12-02 13:50:42 +01:00
Karolis
5182aec13f Add subtitle extraction timeout configuration option 2025-11-17 15:18:29 +02:00
theguymadmax
217ea488df Fix episode showing up on recently added shows 2025-11-07 09:39:23 -05:00
51 changed files with 1061 additions and 317 deletions

View File

@@ -87,6 +87,7 @@ body:
label: Jellyfin Server version label: Jellyfin Server version
description: What version of Jellyfin are you using? description: What version of Jellyfin are you using?
options: options:
- 10.11.4
- 10.11.3 - 10.11.3
- 10.11.2 - 10.11.2
- 10.11.1 - 10.11.1
@@ -139,13 +140,14 @@ body:
- **FFmpeg Version**: [e.g. 5.1.2-Jellyfin] - **FFmpeg Version**: [e.g. 5.1.2-Jellyfin]
- **Playback**: [Direct Play, Remux, Direct Stream, Transcode] - **Playback**: [Direct Play, Remux, Direct Stream, Transcode]
- **Hardware Acceleration**: [e.g. none, VAAPI, NVENC, etc.] - **Hardware Acceleration**: [e.g. none, VAAPI, NVENC, etc.]
- **CPU Model**: [e.g. AMD Ryzen 5 9600X, Intel Core i7-8565U, etc.]
- **GPU Model**: [e.g. none, UHD630, GTX1050, etc.] - **GPU Model**: [e.g. none, UHD630, GTX1050, etc.]
- **Installed Plugins**: [e.g. none, Fanart, Anime, etc.] - **Installed Plugins**: [e.g. none, Fanart, Anime, etc.]
- **Reverse Proxy**: [e.g. none, nginx, apache, etc.] - **Reverse Proxy**: [e.g. none, nginx, apache, etc.]
- **Base URL**: [e.g. none, yes: /example] - **Base URL**: [e.g. none, yes: /example]
- **Networking**: [e.g. Host, Bridge/NAT] - **Networking**: [e.g. Host, Bridge/NAT]
- **Jellyfin Data Storage**: [e.g. local SATA SSD, local HDD] - **Jellyfin Data Storage & Filesystem**: [e.g. local SATA SSD - ext4, local HDD - NTFS]
- **Media Storage**: [e.g. Local HDD, SMB Share] - **Media Storage & Filesystem**: [e.g. Local HDD - ext4, SMB Share]
- **External Integrations**: [e.g. Jellystat, Jellyseerr] - **External Integrations**: [e.g. Jellystat, Jellyseerr]
value: | value: |
- OS: - OS:
@@ -156,13 +158,14 @@ body:
- FFmpeg Version: - FFmpeg Version:
- Playback Method: - Playback Method:
- Hardware Acceleration: - Hardware Acceleration:
- CPU Model:
- GPU Model: - GPU Model:
- Plugins: - Plugins:
- Reverse Proxy: - Reverse Proxy:
- Base URL: - Base URL:
- Networking: - Networking:
- Jellyfin Data Storage: - Jellyfin Data Storage & Filesystem:
- Media Storage: - Media Storage & Filesystem:
- External Integrations: - External Integrations:
render: markdown render: markdown
validations: validations:

View File

@@ -20,18 +20,18 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
- name: Setup .NET - name: Setup .NET
uses: actions/setup-dotnet@2016bd2012dba4e32de620c46fe006a3ac9f0602 # v5.0.1 uses: actions/setup-dotnet@2016bd2012dba4e32de620c46fe006a3ac9f0602 # v5.0.1
with: with:
dotnet-version: '9.0.x' dotnet-version: '9.0.x'
- name: Initialize CodeQL - name: Initialize CodeQL
uses: github/codeql-action/init@fdbfb4d2750291e159f0156def62b853c2798ca2 # v4.31.5 uses: github/codeql-action/init@1b168cd39490f61582a9beae412bb7057a6b2c4e # v4.31.8
with: with:
languages: ${{ matrix.language }} languages: ${{ matrix.language }}
queries: +security-extended queries: +security-extended
- name: Autobuild - name: Autobuild
uses: github/codeql-action/autobuild@fdbfb4d2750291e159f0156def62b853c2798ca2 # v4.31.5 uses: github/codeql-action/autobuild@1b168cd39490f61582a9beae412bb7057a6b2c4e # v4.31.8
- name: Perform CodeQL Analysis - name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@fdbfb4d2750291e159f0156def62b853c2798ca2 # v4.31.5 uses: github/codeql-action/analyze@1b168cd39490f61582a9beae412bb7057a6b2c4e # v4.31.8

View File

@@ -11,7 +11,7 @@ jobs:
permissions: read-all permissions: read-all
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
with: with:
ref: ${{ github.event.pull_request.head.sha }} ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }} repository: ${{ github.event.pull_request.head.repo.full_name }}
@@ -26,7 +26,7 @@ jobs:
dotnet build Jellyfin.Server -o ./out dotnet build Jellyfin.Server -o ./out
- name: Upload Head - name: Upload Head
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with: with:
name: abi-head name: abi-head
retention-days: 14 retention-days: 14
@@ -40,7 +40,7 @@ jobs:
permissions: read-all permissions: read-all
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
with: with:
ref: ${{ github.event.pull_request.head.sha }} ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }} repository: ${{ github.event.pull_request.head.repo.full_name }}
@@ -65,7 +65,7 @@ jobs:
dotnet build Jellyfin.Server -o ./out dotnet build Jellyfin.Server -o ./out
- name: Upload Head - name: Upload Head
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with: with:
name: abi-base name: abi-base
retention-days: 14 retention-days: 14
@@ -85,13 +85,13 @@ jobs:
steps: steps:
- name: Download abi-head - name: Download abi-head
uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0 uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
with: with:
name: abi-head name: abi-head
path: abi-head path: abi-head
- name: Download abi-base - name: Download abi-base
uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0 uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
with: with:
name: abi-base name: abi-base
path: abi-base path: abi-base

View File

@@ -16,7 +16,7 @@ jobs:
permissions: read-all permissions: read-all
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
with: with:
ref: ${{ github.event.pull_request.head.sha }} ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }} repository: ${{ github.event.pull_request.head.repo.full_name }}
@@ -27,7 +27,7 @@ jobs:
- name: Generate openapi.json - name: Generate openapi.json
run: dotnet test tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj -c Release --filter "Jellyfin.Server.Integration.Tests.OpenApiSpecTests" run: dotnet test tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj -c Release --filter "Jellyfin.Server.Integration.Tests.OpenApiSpecTests"
- name: Upload openapi.json - name: Upload openapi.json
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with: with:
name: openapi-head name: openapi-head
retention-days: 14 retention-days: 14
@@ -41,7 +41,7 @@ jobs:
permissions: read-all permissions: read-all
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
with: with:
ref: ${{ github.event.pull_request.head.sha }} ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }} repository: ${{ github.event.pull_request.head.repo.full_name }}
@@ -61,7 +61,7 @@ jobs:
- name: Generate openapi.json - name: Generate openapi.json
run: dotnet test tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj -c Release --filter "Jellyfin.Server.Integration.Tests.OpenApiSpecTests" run: dotnet test tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj -c Release --filter "Jellyfin.Server.Integration.Tests.OpenApiSpecTests"
- name: Upload openapi.json - name: Upload openapi.json
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with: with:
name: openapi-base name: openapi-base
retention-days: 14 retention-days: 14
@@ -80,12 +80,12 @@ jobs:
- openapi-base - openapi-base
steps: steps:
- name: Download openapi-head - name: Download openapi-head
uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0 uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
with: with:
name: openapi-head name: openapi-head
path: openapi-head path: openapi-head
- name: Download openapi-base - name: Download openapi-base
uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0 uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
with: with:
name: openapi-base name: openapi-base
path: openapi-base path: openapi-base
@@ -158,7 +158,7 @@ jobs:
run: |- run: |-
echo "JELLYFIN_VERSION=$(date +'%Y%m%d%H%M%S')" >> $GITHUB_ENV echo "JELLYFIN_VERSION=$(date +'%Y%m%d%H%M%S')" >> $GITHUB_ENV
- name: Download openapi-head - name: Download openapi-head
uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0 uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
with: with:
name: openapi-head name: openapi-head
path: openapi-head path: openapi-head
@@ -220,7 +220,7 @@ jobs:
run: |- run: |-
echo "JELLYFIN_VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_ENV echo "JELLYFIN_VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_ENV
- name: Download openapi-head - name: Download openapi-head
uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0 uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
with: with:
name: openapi-head name: openapi-head
path: openapi-head path: openapi-head

View File

@@ -20,7 +20,7 @@ jobs:
runs-on: "${{ matrix.os }}" runs-on: "${{ matrix.os }}"
steps: steps:
- uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
- uses: actions/setup-dotnet@2016bd2012dba4e32de620c46fe006a3ac9f0602 # v5.0.1 - uses: actions/setup-dotnet@2016bd2012dba4e32de620c46fe006a3ac9f0602 # v5.0.1
with: with:
@@ -35,7 +35,7 @@ jobs:
--verbosity minimal --verbosity minimal
- name: Merge code coverage results - name: Merge code coverage results
uses: danielpalme/ReportGenerator-GitHub-Action@dcdfb6e704e87df6b2ed0cf123a6c9f69e364869 # v5.5.0 uses: danielpalme/ReportGenerator-GitHub-Action@ee0ae774f6d3afedcbd1683c1ab21b83670bdf8e # v5.5.1
with: with:
reports: "**/coverage.cobertura.xml" reports: "**/coverage.cobertura.xml"
targetdir: "merged/" targetdir: "merged/"

View File

@@ -24,7 +24,7 @@ jobs:
reactions: '+1' reactions: '+1'
- name: Checkout the latest code - name: Checkout the latest code
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
with: with:
token: ${{ secrets.JF_BOT_TOKEN }} token: ${{ secrets.JF_BOT_TOKEN }}
fetch-depth: 0 fetch-depth: 0
@@ -40,7 +40,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: pull in script - name: pull in script
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
with: with:
repository: jellyfin/jellyfin-triage-script repository: jellyfin/jellyfin-triage-script
- name: install python - name: install python

View File

@@ -16,7 +16,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: ${{ contains(github.repository, 'jellyfin/') }} if: ${{ contains(github.repository, 'jellyfin/') }}
steps: steps:
- uses: actions/stale@5f858e3efba33a5ca4407a664cc011ad407f2008 # v10.1.0 - uses: actions/stale@997185467fa4f803885201cee163a9f38240193d # v10.1.1
with: with:
repo-token: ${{ secrets.JF_BOT_TOKEN }} repo-token: ${{ secrets.JF_BOT_TOKEN }}
ascending: true ascending: true

View File

@@ -10,7 +10,7 @@ jobs:
issues: write issues: write
steps: steps:
- name: pull in script - name: pull in script
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
with: with:
repository: jellyfin/jellyfin-triage-script repository: jellyfin/jellyfin-triage-script
- name: install python - name: install python

View File

@@ -15,7 +15,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: ${{ contains(github.repository, 'jellyfin/') }} if: ${{ contains(github.repository, 'jellyfin/') }}
steps: steps:
- uses: actions/stale@5f858e3efba33a5ca4407a664cc011ad407f2008 # v10.1.0 - uses: actions/stale@997185467fa4f803885201cee163a9f38240193d # v10.1.1
with: with:
repo-token: ${{ secrets.JF_BOT_TOKEN }} repo-token: ${{ secrets.JF_BOT_TOKEN }}
ascending: true ascending: true

View File

@@ -33,7 +33,7 @@ jobs:
yq-version: v4.9.8 yq-version: v4.9.8
- name: Checkout Repository - name: Checkout Repository
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
with: with:
ref: ${{ env.TAG_BRANCH }} ref: ${{ env.TAG_BRANCH }}
@@ -66,7 +66,7 @@ jobs:
NEXT_VERSION: ${{ github.event.inputs.NEXT_VERSION }} NEXT_VERSION: ${{ github.event.inputs.NEXT_VERSION }}
steps: steps:
- name: Checkout Repository - name: Checkout Repository
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
with: with:
ref: ${{ env.TAG_BRANCH }} ref: ${{ env.TAG_BRANCH }}

View File

@@ -4,7 +4,7 @@
</PropertyGroup> </PropertyGroup>
<!-- Run "dotnet list package (dash,dash)outdated" to see the latest versions of each package.--> <!-- Run "dotnet list package (dash,dash)outdated" to see the latest versions of each package.-->
<ItemGroup Label="Package Dependencies"> <ItemGroup Label="Package Dependencies">
<PackageVersion Include="AsyncKeyedLock" Version="7.1.7" /> <PackageVersion Include="AsyncKeyedLock" Version="7.1.8" />
<PackageVersion Include="AutoFixture.AutoMoq" Version="4.18.1" /> <PackageVersion Include="AutoFixture.AutoMoq" Version="4.18.1" />
<PackageVersion Include="AutoFixture.Xunit2" Version="4.18.1" /> <PackageVersion Include="AutoFixture.Xunit2" Version="4.18.1" />
<PackageVersion Include="AutoFixture" Version="4.18.1" /> <PackageVersion Include="AutoFixture" Version="4.18.1" />
@@ -74,9 +74,9 @@
<PackageVersion Include="SerilogAnalyzer" Version="0.15.0" /> <PackageVersion Include="SerilogAnalyzer" Version="0.15.0" />
<PackageVersion Include="SharpFuzz" Version="2.2.0" /> <PackageVersion Include="SharpFuzz" Version="2.2.0" />
<!-- Pinned to 3.116.1 because https://github.com/jellyfin/jellyfin/pull/14255 --> <!-- Pinned to 3.116.1 because https://github.com/jellyfin/jellyfin/pull/14255 -->
<PackageVersion Include="SkiaSharp" Version="3.116.1" /> <PackageVersion Include="SkiaSharp" Version="[3.116.1]" />
<PackageVersion Include="SkiaSharp.HarfBuzz" Version="3.116.1" /> <PackageVersion Include="SkiaSharp.HarfBuzz" Version="[3.116.1]" />
<PackageVersion Include="SkiaSharp.NativeAssets.Linux" Version="3.116.1" /> <PackageVersion Include="SkiaSharp.NativeAssets.Linux" Version="[3.116.1]" />
<PackageVersion Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" /> <PackageVersion Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" />
<PackageVersion Include="StyleCop.Analyzers" Version="1.2.0-beta.556" /> <PackageVersion Include="StyleCop.Analyzers" Version="1.2.0-beta.556" />
<PackageVersion Include="Svg.Skia" Version="3.2.1" /> <PackageVersion Include="Svg.Skia" Version="3.2.1" />
@@ -96,4 +96,4 @@
<PackageVersion Include="Xunit.SkippableFact" Version="1.5.23" /> <PackageVersion Include="Xunit.SkippableFact" Version="1.5.23" />
<PackageVersion Include="xunit" Version="2.9.3" /> <PackageVersion Include="xunit" Version="2.9.3" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -0,0 +1,75 @@
using System.Text.RegularExpressions;
namespace Emby.Naming.Book
{
/// <summary>
/// Helper class to retrieve basic metadata from a book filename.
/// </summary>
public static class BookFileNameParser
{
private const string NameMatchGroup = "name";
private const string IndexMatchGroup = "index";
private const string YearMatchGroup = "year";
private const string SeriesNameMatchGroup = "seriesName";
private static readonly Regex[] _nameMatches =
[
// seriesName (seriesYear) #index (of count) (year) where only seriesName and index are required
new Regex(@"^(?<seriesName>.+?)((\s\((?<seriesYear>[0-9]{4})\))?)\s#(?<index>[0-9]+)((\s\(of\s(?<count>[0-9]+)\))?)((\s\((?<year>[0-9]{4})\))?)$"),
new Regex(@"^(?<name>.+?)\s\((?<seriesName>.+?),\s#(?<index>[0-9]+)\)((\s\((?<year>[0-9]{4})\))?)$"),
new Regex(@"^(?<index>[0-9]+)\s\-\s(?<name>.+?)((\s\((?<year>[0-9]{4})\))?)$"),
new Regex(@"(?<name>.*)\((?<year>[0-9]{4})\)"),
// last resort matches the whole string as the name
new Regex(@"(?<name>.*)")
];
/// <summary>
/// Parse a filename name to retrieve the book name, series name, index, and year.
/// </summary>
/// <param name="name">Book filename to parse for information.</param>
/// <returns>Returns <see cref="BookFileNameParserResult"/> object.</returns>
public static BookFileNameParserResult Parse(string? name)
{
var result = new BookFileNameParserResult();
if (name == null)
{
return result;
}
foreach (var regex in _nameMatches)
{
var match = regex.Match(name);
if (!match.Success)
{
continue;
}
if (match.Groups.TryGetValue(NameMatchGroup, out Group? nameGroup) && nameGroup.Success)
{
result.Name = nameGroup.Value.Trim();
}
if (match.Groups.TryGetValue(IndexMatchGroup, out Group? indexGroup) && indexGroup.Success && int.TryParse(indexGroup.Value, out var index))
{
result.Index = index;
}
if (match.Groups.TryGetValue(YearMatchGroup, out Group? yearGroup) && yearGroup.Success && int.TryParse(yearGroup.Value, out var year))
{
result.Year = year;
}
if (match.Groups.TryGetValue(SeriesNameMatchGroup, out Group? seriesGroup) && seriesGroup.Success)
{
result.SeriesName = seriesGroup.Value.Trim();
}
break;
}
return result;
}
}
}

View File

@@ -0,0 +1,41 @@
using System;
namespace Emby.Naming.Book
{
/// <summary>
/// Data object used to pass metadata parsed from a book filename.
/// </summary>
public class BookFileNameParserResult
{
/// <summary>
/// Initializes a new instance of the <see cref="BookFileNameParserResult"/> class.
/// </summary>
public BookFileNameParserResult()
{
Name = null;
Index = null;
Year = null;
SeriesName = null;
}
/// <summary>
/// Gets or sets the name of the book.
/// </summary>
public string? Name { get; set; }
/// <summary>
/// Gets or sets the book index.
/// </summary>
public int? Index { get; set; }
/// <summary>
/// Gets or sets the publication year.
/// </summary>
public int? Year { get; set; }
/// <summary>
/// Gets or sets the series name.
/// </summary>
public string? SeriesName { get; set; }
}
}

View File

@@ -497,8 +497,17 @@ namespace Emby.Server.Implementations.IO
/// <inheritdoc /> /// <inheritdoc />
public virtual bool AreEqual(string path1, string path2) public virtual bool AreEqual(string path1, string path2)
{ {
return Path.TrimEndingDirectorySeparator(path1).Equals( if (string.IsNullOrWhiteSpace(path1) || string.IsNullOrWhiteSpace(path2))
Path.TrimEndingDirectorySeparator(path2), {
return false;
}
var normalized1 = Path.TrimEndingDirectorySeparator(path1);
var normalized2 = Path.TrimEndingDirectorySeparator(path2);
return string.Equals(
normalized1,
normalized2,
_isEnvironmentCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); _isEnvironmentCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
} }

View File

@@ -2143,7 +2143,7 @@ namespace Emby.Server.Implementations.Library
item.ValidateImages(); item.ValidateImages();
_itemRepository.SaveImages(item); await _itemRepository.SaveImagesAsync(item).ConfigureAwait(false);
RegisterItem(item); RegisterItem(item);
} }

View File

@@ -5,12 +5,12 @@
using System; using System;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using Emby.Naming.Book;
using Jellyfin.Data.Enums; using Jellyfin.Data.Enums;
using Jellyfin.Extensions; using Jellyfin.Extensions;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Resolvers; using MediaBrowser.Controller.Resolvers;
using MediaBrowser.Model.Entities;
namespace Emby.Server.Implementations.Library.Resolvers.Books namespace Emby.Server.Implementations.Library.Resolvers.Books
{ {
@@ -35,17 +35,22 @@ namespace Emby.Server.Implementations.Library.Resolvers.Books
var extension = Path.GetExtension(args.Path.AsSpan()); var extension = Path.GetExtension(args.Path.AsSpan());
if (_validExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase)) if (!_validExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase))
{ {
// It's a book return null;
return new Book
{
Path = args.Path,
IsInMixedFolder = true
};
} }
return null; var result = BookFileNameParser.Parse(Path.GetFileNameWithoutExtension(args.Path));
return new Book
{
Path = args.Path,
Name = result.Name ?? string.Empty,
IndexNumber = result.Index,
ProductionYear = result.Year,
SeriesName = result.SeriesName ?? Path.GetFileName(Path.GetDirectoryName(args.Path)),
IsInMixedFolder = true,
};
} }
private Book GetBook(ItemResolveArgs args) private Book GetBook(ItemResolveArgs args)
@@ -59,15 +64,22 @@ namespace Emby.Server.Implementations.Library.Resolvers.Books
StringComparison.OrdinalIgnoreCase); StringComparison.OrdinalIgnoreCase);
}).ToList(); }).ToList();
// Don't return a Book if there is more (or less) than one document in the directory // directory is only considered a book when it contains exactly one supported file
// other library structures with multiple books to a directory will get picked up as individual files
if (bookFiles.Count != 1) if (bookFiles.Count != 1)
{ {
return null; return null;
} }
var result = BookFileNameParser.Parse(Path.GetFileName(args.Path));
return new Book return new Book
{ {
Path = bookFiles[0].FullName Path = bookFiles[0].FullName,
Name = result.Name ?? string.Empty,
IndexNumber = result.Index,
ProductionYear = result.Year,
SeriesName = result.SeriesName ?? string.Empty,
}; };
} }
} }

View File

@@ -42,7 +42,7 @@ namespace Emby.Server.Implementations.Library
results = results.GetRange(query.StartIndex.Value, totalRecordCount - query.StartIndex.Value); results = results.GetRange(query.StartIndex.Value, totalRecordCount - query.StartIndex.Value);
} }
if (query.Limit.HasValue) if (query.Limit.HasValue && query.Limit.Value > 0)
{ {
results = results.GetRange(0, Math.Min(query.Limit.Value, results.Count)); results = results.GetRange(0, Math.Min(query.Limit.Value, results.Count));
} }

View File

@@ -16,7 +16,7 @@
"Folders": "المجلدات", "Folders": "المجلدات",
"Genres": "التصنيفات", "Genres": "التصنيفات",
"HeaderAlbumArtists": "فناني الألبوم", "HeaderAlbumArtists": "فناني الألبوم",
"HeaderContinueWatching": "إستئناف المشاهدة", "HeaderContinueWatching": "أكمل المشاهدة",
"HeaderFavoriteAlbums": "الألبومات المفضلة", "HeaderFavoriteAlbums": "الألبومات المفضلة",
"HeaderFavoriteArtists": "الفنانون المفضلون", "HeaderFavoriteArtists": "الفنانون المفضلون",
"HeaderFavoriteEpisodes": "الحلقات المفضلة", "HeaderFavoriteEpisodes": "الحلقات المفضلة",

View File

@@ -0,0 +1,9 @@
{
"Albums": "Pukaemi",
"AppDeviceValues": "Taupānga: {0}, Pūrere: {1}",
"Application": "Taupānga",
"Artists": "Kaiwaiata",
"AuthenticationSucceededWithUserName": "{0} has been successfully authenticated",
"Books": "Ngā pukapuka",
"CameraImageUploadedFrom": "Kua tuku ake he whakaahua kāmera hou mai i {0}"
}

View File

@@ -0,0 +1 @@
{}

View File

@@ -266,7 +266,7 @@ namespace Emby.Server.Implementations.TV
items = items.Skip(query.StartIndex.Value); items = items.Skip(query.StartIndex.Value);
} }
if (query.Limit.HasValue) if (query.Limit.HasValue && query.Limit.Value > 0)
{ {
items = items.Take(query.Limit.Value); items = items.Take(query.Limit.Value);
} }

View File

@@ -1,13 +1,16 @@
using System; using System;
using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Jellyfin.Api.Constants; using Jellyfin.Data.Enums;
using Jellyfin.Data.Queries; using Jellyfin.Data.Queries;
using Jellyfin.Database.Implementations.Enums;
using MediaBrowser.Common.Api; using MediaBrowser.Common.Api;
using MediaBrowser.Model.Activity; using MediaBrowser.Model.Activity;
using MediaBrowser.Model.Querying; using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Api.Controllers; namespace Jellyfin.Api.Controllers;
@@ -32,10 +35,19 @@ public class ActivityLogController : BaseJellyfinApiController
/// <summary> /// <summary>
/// Gets activity log entries. /// Gets activity log entries.
/// </summary> /// </summary>
/// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param> /// <param name="startIndex">The record index to start at. All items with a lower index will be dropped from the results.</param>
/// <param name="limit">Optional. The maximum number of records to return.</param> /// <param name="limit">The maximum number of records to return.</param>
/// <param name="minDate">Optional. The minimum date. Format = ISO.</param> /// <param name="minDate">The minimum date.</param>
/// <param name="hasUserId">Optional. Filter log entries if it has user id, or not.</param> /// <param name="hasUserId">Filter log entries if it has user id, or not.</param>
/// <param name="name">Filter by name.</param>
/// <param name="overview">Filter by overview.</param>
/// <param name="shortOverview">Filter by short overview.</param>
/// <param name="type">Filter by type.</param>
/// <param name="itemId">Filter by item id.</param>
/// <param name="username">Filter by username.</param>
/// <param name="severity">Filter by log severity.</param>
/// <param name="sortBy">Specify one or more sort orders. Format: SortBy=Name,Type.</param>
/// <param name="sortOrder">Sort Order..</param>
/// <response code="200">Activity log returned.</response> /// <response code="200">Activity log returned.</response>
/// <returns>A <see cref="QueryResult{ActivityLogEntry}"/> containing the log entries.</returns> /// <returns>A <see cref="QueryResult{ActivityLogEntry}"/> containing the log entries.</returns>
[HttpGet("Entries")] [HttpGet("Entries")]
@@ -44,14 +56,60 @@ public class ActivityLogController : BaseJellyfinApiController
[FromQuery] int? startIndex, [FromQuery] int? startIndex,
[FromQuery] int? limit, [FromQuery] int? limit,
[FromQuery] DateTime? minDate, [FromQuery] DateTime? minDate,
[FromQuery] bool? hasUserId) [FromQuery] bool? hasUserId,
[FromQuery] string? name,
[FromQuery] string? overview,
[FromQuery] string? shortOverview,
[FromQuery] string? type,
[FromQuery] Guid? itemId,
[FromQuery] string? username,
[FromQuery] LogLevel? severity,
[FromQuery] ActivityLogSortBy[]? sortBy,
[FromQuery] SortOrder[]? sortOrder)
{ {
return await _activityManager.GetPagedResultAsync(new ActivityLogQuery var query = new ActivityLogQuery
{ {
Skip = startIndex, Skip = startIndex,
Limit = limit, Limit = limit,
MinDate = minDate, MinDate = minDate,
HasUserId = hasUserId HasUserId = hasUserId,
}).ConfigureAwait(false); Name = name,
Overview = overview,
ShortOverview = shortOverview,
Type = type,
ItemId = itemId,
Username = username,
Severity = severity,
OrderBy = GetOrderBy(sortBy ?? [], sortOrder ?? []),
};
return await _activityManager.GetPagedResultAsync(query).ConfigureAwait(false);
}
private static (ActivityLogSortBy SortBy, SortOrder SortOrder)[] GetOrderBy(
IReadOnlyList<ActivityLogSortBy> sortBy,
IReadOnlyList<SortOrder> requestedSortOrder)
{
if (sortBy.Count == 0)
{
return [];
}
var result = new (ActivityLogSortBy, SortOrder)[sortBy.Count];
var i = 0;
for (; i < requestedSortOrder.Count; i++)
{
result[i] = (sortBy[i], requestedSortOrder[i]);
}
// Add remaining elements with the first specified SortOrder
// or the default one if no SortOrders are specified
var order = requestedSortOrder.Count > 0 ? requestedSortOrder[0] : SortOrder.Ascending;
for (; i < sortBy.Count; i++)
{
result[i] = (sortBy[i], order);
}
return result;
} }
} }

View File

@@ -13,6 +13,7 @@ using Jellyfin.Extensions;
using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Dto; using MediaBrowser.Model.Dto;
@@ -568,7 +569,7 @@ public class UserLibraryController : BaseJellyfinApiController
var item = i.Item2[0]; var item = i.Item2[0];
var childCount = 0; var childCount = 0;
if (i.Item1 is not null && (i.Item2.Count > 1 || i.Item1 is MusicAlbum)) if (i.Item1 is not null && (i.Item2.Count > 1 || i.Item1 is MusicAlbum || i.Item1 is Series ))
{ {
item = i.Item1; item = i.Item1;
childCount = i.Item2.Count; childCount = i.Item2.Count;

View File

@@ -1,53 +0,0 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Api.Middleware;
/// <summary>
/// Removes /emby and /mediabrowser from requested route.
/// </summary>
public class LegacyEmbyRouteRewriteMiddleware
{
private const string EmbyPath = "/emby";
private const string MediabrowserPath = "/mediabrowser";
private readonly RequestDelegate _next;
private readonly ILogger<LegacyEmbyRouteRewriteMiddleware> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="LegacyEmbyRouteRewriteMiddleware"/> class.
/// </summary>
/// <param name="next">The next delegate in the pipeline.</param>
/// <param name="logger">The logger.</param>
public LegacyEmbyRouteRewriteMiddleware(
RequestDelegate next,
ILogger<LegacyEmbyRouteRewriteMiddleware> logger)
{
_next = next;
_logger = logger;
}
/// <summary>
/// Executes the middleware action.
/// </summary>
/// <param name="httpContext">The current HTTP context.</param>
/// <returns>The async task.</returns>
public async Task Invoke(HttpContext httpContext)
{
var localPath = httpContext.Request.Path.ToString();
if (localPath.StartsWith(EmbyPath, StringComparison.OrdinalIgnoreCase))
{
httpContext.Request.Path = localPath[EmbyPath.Length..];
_logger.LogDebug("Removing {EmbyPath} from route.", EmbyPath);
}
else if (localPath.StartsWith(MediabrowserPath, StringComparison.OrdinalIgnoreCase))
{
httpContext.Request.Path = localPath[MediabrowserPath.Length..];
_logger.LogDebug("Removing {MediabrowserPath} from route.", MediabrowserPath);
}
await _next(httpContext).ConfigureAwait(false);
}
}

View File

@@ -0,0 +1,49 @@
namespace Jellyfin.Data.Enums;
/// <summary>
/// Activity log sorting options.
/// </summary>
public enum ActivityLogSortBy
{
/// <summary>
/// Sort by name.
/// </summary>
Name = 0,
/// <summary>
/// Sort by overview.
/// </summary>
Overiew = 1,
/// <summary>
/// Sort by short overview.
/// </summary>
ShortOverview = 2,
/// <summary>
/// Sort by type.
/// </summary>
Type = 3,
/*
/// <summary>
/// Sort by item name.
/// </summary>
Item = 4,
*/
/// <summary>
/// Sort by date.
/// </summary>
DateCreated = 5,
/// <summary>
/// Sort by username.
/// </summary>
Username = 6,
/// <summary>
/// Sort by severity.
/// </summary>
LogSeverity = 7
}

View File

@@ -1,20 +1,63 @@
using System; using System;
using System.Collections.Generic;
using Jellyfin.Data.Enums;
using Jellyfin.Database.Implementations.Enums;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Data.Queries namespace Jellyfin.Data.Queries;
/// <summary>
/// A class representing a query to the activity logs.
/// </summary>
public class ActivityLogQuery : PaginatedQuery
{ {
/// <summary> /// <summary>
/// A class representing a query to the activity logs. /// Gets or sets a value indicating whether to take entries with a user id.
/// </summary> /// </summary>
public class ActivityLogQuery : PaginatedQuery public bool? HasUserId { get; set; }
{
/// <summary>
/// Gets or sets a value indicating whether to take entries with a user id.
/// </summary>
public bool? HasUserId { get; set; }
/// <summary> /// <summary>
/// Gets or sets the minimum date to query for. /// Gets or sets the minimum date to query for.
/// </summary> /// </summary>
public DateTime? MinDate { get; set; } public DateTime? MinDate { get; set; }
}
/// <summary>
/// Gets or sets the name filter.
/// </summary>
public string? Name { get; set; }
/// <summary>
/// Gets or sets the overview filter.
/// </summary>
public string? Overview { get; set; }
/// <summary>
/// Gets or sets the short overview filter.
/// </summary>
public string? ShortOverview { get; set; }
/// <summary>
/// Gets or sets the type filter.
/// </summary>
public string? Type { get; set; }
/// <summary>
/// Gets or sets the item filter.
/// </summary>
public Guid? ItemId { get; set; }
/// <summary>
/// Gets or sets the username filter.
/// </summary>
public string? Username { get; set; }
/// <summary>
/// Gets or sets the log level filter.
/// </summary>
public LogLevel? Severity { get; set; }
/// <summary>
/// Gets or sets the result ordering.
/// </summary>
public IReadOnlyCollection<(ActivityLogSortBy, SortOrder)>? OrderBy { get; set; }
} }

View File

@@ -1,103 +1,198 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using Jellyfin.Data.Enums;
using Jellyfin.Data.Events; using Jellyfin.Data.Events;
using Jellyfin.Data.Queries; using Jellyfin.Data.Queries;
using Jellyfin.Database.Implementations; using Jellyfin.Database.Implementations;
using Jellyfin.Database.Implementations.Entities; using Jellyfin.Database.Implementations.Entities;
using Jellyfin.Database.Implementations.Enums;
using Jellyfin.Extensions;
using MediaBrowser.Model.Activity; using MediaBrowser.Model.Activity;
using MediaBrowser.Model.Querying; using MediaBrowser.Model.Querying;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
namespace Jellyfin.Server.Implementations.Activity namespace Jellyfin.Server.Implementations.Activity;
/// <summary>
/// Manages the storage and retrieval of <see cref="ActivityLog"/> instances.
/// </summary>
public class ActivityManager : IActivityManager
{ {
private readonly IDbContextFactory<JellyfinDbContext> _provider;
/// <summary> /// <summary>
/// Manages the storage and retrieval of <see cref="ActivityLog"/> instances. /// Initializes a new instance of the <see cref="ActivityManager"/> class.
/// </summary> /// </summary>
public class ActivityManager : IActivityManager /// <param name="provider">The Jellyfin database provider.</param>
public ActivityManager(IDbContextFactory<JellyfinDbContext> provider)
{ {
private readonly IDbContextFactory<JellyfinDbContext> _provider; _provider = provider;
}
/// <summary> /// <inheritdoc/>
/// Initializes a new instance of the <see cref="ActivityManager"/> class. public event EventHandler<GenericEventArgs<ActivityLogEntry>>? EntryCreated;
/// </summary>
/// <param name="provider">The Jellyfin database provider.</param> /// <inheritdoc/>
public ActivityManager(IDbContextFactory<JellyfinDbContext> provider) public async Task CreateAsync(ActivityLog entry)
{
var dbContext = await _provider.CreateDbContextAsync().ConfigureAwait(false);
await using (dbContext.ConfigureAwait(false))
{ {
_provider = provider; dbContext.ActivityLogs.Add(entry);
await dbContext.SaveChangesAsync().ConfigureAwait(false);
} }
/// <inheritdoc/> EntryCreated?.Invoke(this, new GenericEventArgs<ActivityLogEntry>(ConvertToOldModel(entry)));
public event EventHandler<GenericEventArgs<ActivityLogEntry>>? EntryCreated; }
/// <inheritdoc/> /// <inheritdoc/>
public async Task CreateAsync(ActivityLog entry) public async Task<QueryResult<ActivityLogEntry>> GetPagedResultAsync(ActivityLogQuery query)
{
// TODO allow sorting and filtering by item id. Currently not possible because ActivityLog stores the item id as a string.
var dbContext = await _provider.CreateDbContextAsync().ConfigureAwait(false);
await using (dbContext.ConfigureAwait(false))
{ {
var dbContext = await _provider.CreateDbContextAsync().ConfigureAwait(false); // TODO switch to LeftJoin in .NET 10.
await using (dbContext.ConfigureAwait(false)) var entries = from a in dbContext.ActivityLogs
join u in dbContext.Users on a.UserId equals u.Id into ugj
from u in ugj.DefaultIfEmpty()
select new ExpandedActivityLog { ActivityLog = a, Username = u.Username };
if (query.HasUserId is not null)
{ {
dbContext.ActivityLogs.Add(entry); entries = entries.Where(e => e.ActivityLog.UserId.Equals(default) != query.HasUserId.Value);
await dbContext.SaveChangesAsync().ConfigureAwait(false);
} }
EntryCreated?.Invoke(this, new GenericEventArgs<ActivityLogEntry>(ConvertToOldModel(entry))); if (query.MinDate is not null)
}
/// <inheritdoc/>
public async Task<QueryResult<ActivityLogEntry>> GetPagedResultAsync(ActivityLogQuery query)
{
var dbContext = await _provider.CreateDbContextAsync().ConfigureAwait(false);
await using (dbContext.ConfigureAwait(false))
{ {
var entries = dbContext.ActivityLogs entries = entries.Where(e => e.ActivityLog.DateCreated >= query.MinDate.Value);
.OrderByDescending(entry => entry.DateCreated)
.Where(entry => query.MinDate == null || entry.DateCreated >= query.MinDate)
.Where(entry => !query.HasUserId.HasValue || entry.UserId.Equals(default) != query.HasUserId.Value);
return new QueryResult<ActivityLogEntry>(
query.Skip,
await entries.CountAsync().ConfigureAwait(false),
await entries
.Skip(query.Skip ?? 0)
.Take(query.Limit ?? 100)
.Select(entity => new ActivityLogEntry(entity.Name, entity.Type, entity.UserId)
{
Id = entity.Id,
Overview = entity.Overview,
ShortOverview = entity.ShortOverview,
ItemId = entity.ItemId,
Date = entity.DateCreated,
Severity = entity.LogSeverity
})
.ToListAsync()
.ConfigureAwait(false));
} }
}
/// <inheritdoc /> if (!string.IsNullOrEmpty(query.Name))
public async Task CleanAsync(DateTime startDate)
{
var dbContext = await _provider.CreateDbContextAsync().ConfigureAwait(false);
await using (dbContext.ConfigureAwait(false))
{ {
await dbContext.ActivityLogs entries = entries.Where(e => EF.Functions.Like(e.ActivityLog.Name, $"%{query.Name}%"));
.Where(entry => entry.DateCreated <= startDate)
.ExecuteDeleteAsync()
.ConfigureAwait(false);
} }
}
private static ActivityLogEntry ConvertToOldModel(ActivityLog entry) if (!string.IsNullOrEmpty(query.Overview))
{
return new ActivityLogEntry(entry.Name, entry.Type, entry.UserId)
{ {
Id = entry.Id, entries = entries.Where(e => EF.Functions.Like(e.ActivityLog.Overview, $"%{query.Overview}%"));
Overview = entry.Overview, }
ShortOverview = entry.ShortOverview,
ItemId = entry.ItemId, if (!string.IsNullOrEmpty(query.ShortOverview))
Date = entry.DateCreated, {
Severity = entry.LogSeverity entries = entries.Where(e => EF.Functions.Like(e.ActivityLog.ShortOverview, $"%{query.ShortOverview}%"));
}; }
if (!string.IsNullOrEmpty(query.Type))
{
entries = entries.Where(e => EF.Functions.Like(e.ActivityLog.Type, $"%{query.Type}%"));
}
if (!query.ItemId.IsNullOrEmpty())
{
var itemId = query.ItemId.Value.ToString("N");
entries = entries.Where(e => e.ActivityLog.ItemId == itemId);
}
if (!string.IsNullOrEmpty(query.Username))
{
entries = entries.Where(e => EF.Functions.Like(e.Username, $"%{query.Username}%"));
}
if (query.Severity is not null)
{
entries = entries.Where(e => e.ActivityLog.LogSeverity == query.Severity);
}
return new QueryResult<ActivityLogEntry>(
query.Skip,
await entries.CountAsync().ConfigureAwait(false),
await ApplyOrdering(entries, query.OrderBy)
.Skip(query.Skip ?? 0)
.Take(query.Limit ?? 100)
.Select(entity => new ActivityLogEntry(entity.ActivityLog.Name, entity.ActivityLog.Type, entity.ActivityLog.UserId)
{
Id = entity.ActivityLog.Id,
Overview = entity.ActivityLog.Overview,
ShortOverview = entity.ActivityLog.ShortOverview,
ItemId = entity.ActivityLog.ItemId,
Date = entity.ActivityLog.DateCreated,
Severity = entity.ActivityLog.LogSeverity
})
.ToListAsync()
.ConfigureAwait(false));
} }
} }
/// <inheritdoc />
public async Task CleanAsync(DateTime startDate)
{
var dbContext = await _provider.CreateDbContextAsync().ConfigureAwait(false);
await using (dbContext.ConfigureAwait(false))
{
await dbContext.ActivityLogs
.Where(entry => entry.DateCreated <= startDate)
.ExecuteDeleteAsync()
.ConfigureAwait(false);
}
}
private static ActivityLogEntry ConvertToOldModel(ActivityLog entry)
{
return new ActivityLogEntry(entry.Name, entry.Type, entry.UserId)
{
Id = entry.Id,
Overview = entry.Overview,
ShortOverview = entry.ShortOverview,
ItemId = entry.ItemId,
Date = entry.DateCreated,
Severity = entry.LogSeverity
};
}
private IOrderedQueryable<ExpandedActivityLog> ApplyOrdering(IQueryable<ExpandedActivityLog> query, IReadOnlyCollection<(ActivityLogSortBy, SortOrder)>? sorting)
{
if (sorting is null || sorting.Count == 0)
{
return query.OrderByDescending(e => e.ActivityLog.DateCreated);
}
IOrderedQueryable<ExpandedActivityLog> ordered = null!;
foreach (var (sortBy, sortOrder) in sorting)
{
var orderBy = MapOrderBy(sortBy);
ordered = sortOrder == SortOrder.Ascending
? (ordered ?? query).OrderBy(orderBy)
: (ordered ?? query).OrderByDescending(orderBy);
}
return ordered;
}
private Expression<Func<ExpandedActivityLog, object?>> MapOrderBy(ActivityLogSortBy sortBy)
{
return sortBy switch
{
ActivityLogSortBy.Name => e => e.ActivityLog.Name,
ActivityLogSortBy.Overiew => e => e.ActivityLog.Overview,
ActivityLogSortBy.ShortOverview => e => e.ActivityLog.ShortOverview,
ActivityLogSortBy.Type => e => e.ActivityLog.Type,
ActivityLogSortBy.DateCreated => e => e.ActivityLog.DateCreated,
ActivityLogSortBy.Username => e => e.Username,
ActivityLogSortBy.LogSeverity => e => e.ActivityLog.LogSeverity,
_ => throw new ArgumentOutOfRangeException(nameof(sortBy), sortBy, "Unhandled ActivityLogSortBy")
};
}
private class ExpandedActivityLog
{
public ActivityLog ActivityLog { get; set; } = null!;
public string? Username { get; set; }
}
} }

View File

@@ -158,7 +158,7 @@ namespace Jellyfin.Server.Implementations.Devices
devices = devices.Skip(query.Skip.Value); devices = devices.Skip(query.Skip.Value);
} }
if (query.Limit.HasValue) if (query.Limit.HasValue && query.Limit.Value > 0)
{ {
devices = devices.Take(query.Limit.Value); devices = devices.Take(query.Limit.Value);
} }

View File

@@ -250,7 +250,7 @@ public sealed class BaseItemRepository
public QueryResult<BaseItemDto> GetItems(InternalItemsQuery filter) public QueryResult<BaseItemDto> GetItems(InternalItemsQuery filter)
{ {
ArgumentNullException.ThrowIfNull(filter); ArgumentNullException.ThrowIfNull(filter);
if (!filter.EnableTotalRecordCount || (!filter.Limit.HasValue && (filter.StartIndex ?? 0) == 0)) if (!filter.EnableTotalRecordCount || ((filter.Limit ?? 0) == 0 && (filter.StartIndex ?? 0) == 0))
{ {
var returnList = GetItemList(filter); var returnList = GetItemList(filter);
return new QueryResult<BaseItemDto>( return new QueryResult<BaseItemDto>(
@@ -326,7 +326,7 @@ public sealed class BaseItemRepository
.OrderByDescending(g => g.MaxDateCreated) .OrderByDescending(g => g.MaxDateCreated)
.Select(g => g); .Select(g => g);
if (filter.Limit.HasValue) if (filter.Limit.HasValue && filter.Limit.Value > 0)
{ {
subqueryGrouped = subqueryGrouped.Take(filter.Limit.Value); subqueryGrouped = subqueryGrouped.Take(filter.Limit.Value);
} }
@@ -367,7 +367,7 @@ public sealed class BaseItemRepository
.OrderByDescending(g => g.LastPlayedDate) .OrderByDescending(g => g.LastPlayedDate)
.Select(g => g.Key!); .Select(g => g.Key!);
if (filter.Limit.HasValue) if (filter.Limit.HasValue && filter.Limit.Value > 0)
{ {
query = query.Take(filter.Limit.Value); query = query.Take(filter.Limit.Value);
} }
@@ -425,19 +425,14 @@ public sealed class BaseItemRepository
private IQueryable<BaseItemEntity> ApplyQueryPaging(IQueryable<BaseItemEntity> dbQuery, InternalItemsQuery filter) private IQueryable<BaseItemEntity> ApplyQueryPaging(IQueryable<BaseItemEntity> dbQuery, InternalItemsQuery filter)
{ {
if (filter.Limit.HasValue || filter.StartIndex.HasValue) if (filter.StartIndex.HasValue && filter.StartIndex.Value > 0)
{ {
var offset = filter.StartIndex ?? 0; dbQuery = dbQuery.Skip(filter.StartIndex.Value);
}
if (offset > 0) if (filter.Limit.HasValue && filter.Limit.Value > 0)
{ {
dbQuery = dbQuery.Skip(offset); dbQuery = dbQuery.Take(filter.Limit.Value);
}
if (filter.Limit.HasValue)
{
dbQuery = dbQuery.Take(filter.Limit.Value);
}
} }
return dbQuery; return dbQuery;
@@ -552,22 +547,34 @@ public sealed class BaseItemRepository
} }
/// <inheritdoc /> /// <inheritdoc />
public void SaveImages(BaseItemDto item) public async Task SaveImagesAsync(BaseItemDto item, CancellationToken cancellationToken = default)
{ {
ArgumentNullException.ThrowIfNull(item); ArgumentNullException.ThrowIfNull(item);
var images = item.ImageInfos.Select(e => Map(item.Id, e)); var images = item.ImageInfos.Select(e => Map(item.Id, e)).ToArray();
using var context = _dbProvider.CreateDbContext();
if (!context.BaseItems.Any(bi => bi.Id == item.Id)) var context = await _dbProvider.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
await using (context.ConfigureAwait(false))
{ {
_logger.LogWarning("Unable to save ImageInfo for non existing BaseItem"); if (!await context.BaseItems
return; .AnyAsync(bi => bi.Id == item.Id, cancellationToken)
} .ConfigureAwait(false))
{
_logger.LogWarning("Unable to save ImageInfo for non existing BaseItem");
return;
}
context.BaseItemImageInfos.Where(e => e.ItemId == item.Id).ExecuteDelete(); await context.BaseItemImageInfos
context.BaseItemImageInfos.AddRange(images); .Where(e => e.ItemId == item.Id)
context.SaveChanges(); .ExecuteDeleteAsync(cancellationToken)
.ConfigureAwait(false);
await context.BaseItemImageInfos
.AddRangeAsync(images, cancellationToken)
.ConfigureAwait(false);
await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
}
} }
/// <inheritdoc /> /// <inheritdoc />
@@ -618,12 +625,18 @@ public sealed class BaseItemRepository
{ {
context.BaseItemProviders.Where(e => e.ItemId == entity.Id).ExecuteDelete(); context.BaseItemProviders.Where(e => e.ItemId == entity.Id).ExecuteDelete();
context.BaseItemImageInfos.Where(e => e.ItemId == entity.Id).ExecuteDelete(); context.BaseItemImageInfos.Where(e => e.ItemId == entity.Id).ExecuteDelete();
context.BaseItemMetadataFields.Where(e => e.ItemId == entity.Id).ExecuteDelete();
if (entity.Images is { Count: > 0 }) if (entity.Images is { Count: > 0 })
{ {
context.BaseItemImageInfos.AddRange(entity.Images); context.BaseItemImageInfos.AddRange(entity.Images);
} }
if (entity.LockedFields is { Count: > 0 })
{
context.BaseItemMetadataFields.AddRange(entity.LockedFields);
}
context.BaseItems.Attach(entity).State = EntityState.Modified; context.BaseItems.Attach(entity).State = EntityState.Modified;
} }
} }
@@ -1184,7 +1197,7 @@ public sealed class BaseItemRepository
{ {
ArgumentNullException.ThrowIfNull(filter); ArgumentNullException.ThrowIfNull(filter);
if (!filter.Limit.HasValue) if (!(filter.Limit.HasValue && filter.Limit.Value > 0))
{ {
filter.EnableTotalRecordCount = false; filter.EnableTotalRecordCount = false;
} }
@@ -1263,19 +1276,14 @@ public sealed class BaseItemRepository
result.TotalRecordCount = query.Count(); result.TotalRecordCount = query.Count();
} }
if (filter.Limit.HasValue || filter.StartIndex.HasValue) if (filter.StartIndex.HasValue && filter.StartIndex.Value > 0)
{ {
var offset = filter.StartIndex ?? 0; query = query.Skip(filter.StartIndex.Value);
}
if (offset > 0) if (filter.Limit.HasValue && filter.Limit.Value > 0)
{ {
query = query.Skip(offset); query = query.Take(filter.Limit.Value);
}
if (filter.Limit.HasValue)
{
query = query.Take(filter.Limit.Value);
}
} }
IQueryable<BaseItemEntity>? itemCountQuery = null; IQueryable<BaseItemEntity>? itemCountQuery = null;
@@ -1356,7 +1364,7 @@ public sealed class BaseItemRepository
private static void PrepareFilterQuery(InternalItemsQuery query) private static void PrepareFilterQuery(InternalItemsQuery query)
{ {
if (query.Limit.HasValue && query.EnableGroupByMetadataKey) if (query.Limit.HasValue && query.Limit.Value > 0 && query.EnableGroupByMetadataKey)
{ {
query.Limit = query.Limit.Value + 4; query.Limit = query.Limit.Value + 4;
} }
@@ -1367,14 +1375,54 @@ public sealed class BaseItemRepository
} }
} }
private string GetCleanValue(string value) /// <summary>
/// Gets the clean value for search and sorting purposes.
/// </summary>
/// <param name="value">The value to clean.</param>
/// <returns>The cleaned value.</returns>
public static string GetCleanValue(string value)
{ {
if (string.IsNullOrWhiteSpace(value)) if (string.IsNullOrWhiteSpace(value))
{ {
return value; return value;
} }
return value.RemoveDiacritics().ToLowerInvariant(); var noDiacritics = value.RemoveDiacritics();
// Build a string where any punctuation or symbol is treated as a separator (space).
var sb = new StringBuilder(noDiacritics.Length);
var previousWasSpace = false;
foreach (var ch in noDiacritics)
{
char outCh;
if (char.IsLetterOrDigit(ch) || char.IsWhiteSpace(ch))
{
outCh = ch;
}
else
{
outCh = ' ';
}
// normalize any whitespace character to a single ASCII space.
if (char.IsWhiteSpace(outCh))
{
if (!previousWasSpace)
{
sb.Append(' ');
previousWasSpace = true;
}
}
else
{
sb.Append(outCh);
previousWasSpace = false;
}
}
// trim leading/trailing spaces that may have been added.
var collapsed = sb.ToString().Trim();
return collapsed.ToLowerInvariant();
} }
private List<(ItemValueType MagicNumber, string Value)> GetItemValuesToSave(BaseItemDto item, List<string> inheritedTags) private List<(ItemValueType MagicNumber, string Value)> GetItemValuesToSave(BaseItemDto item, List<string> inheritedTags)
@@ -1647,19 +1695,18 @@ public sealed class BaseItemRepository
var tags = filter.Tags.ToList(); var tags = filter.Tags.ToList();
var excludeTags = filter.ExcludeTags.ToList(); var excludeTags = filter.ExcludeTags.ToList();
if (filter.IsMovie == true) if (filter.IsMovie.HasValue)
{ {
if (filter.IncludeItemTypes.Length == 0 var shouldIncludeAllMovieTypes = filter.IsMovie.Value
|| filter.IncludeItemTypes.Contains(BaseItemKind.Movie) && (filter.IncludeItemTypes.Length == 0
|| filter.IncludeItemTypes.Contains(BaseItemKind.Trailer)) || filter.IncludeItemTypes.Contains(BaseItemKind.Movie)
|| filter.IncludeItemTypes.Contains(BaseItemKind.Trailer));
if (!shouldIncludeAllMovieTypes)
{ {
baseQuery = baseQuery.Where(e => e.IsMovie); baseQuery = baseQuery.Where(e => e.IsMovie == filter.IsMovie.Value);
} }
} }
else if (filter.IsMovie.HasValue)
{
baseQuery = baseQuery.Where(e => e.IsMovie == filter.IsMovie);
}
if (filter.IsSeries.HasValue) if (filter.IsSeries.HasValue)
{ {

View File

@@ -117,18 +117,5 @@ namespace Jellyfin.Server.Extensions
{ {
return appBuilder.UseMiddleware<RobotsRedirectionMiddleware>(); return appBuilder.UseMiddleware<RobotsRedirectionMiddleware>();
} }
/// <summary>
/// Adds /emby and /mediabrowser route trimming to the application pipeline.
/// </summary>
/// <remarks>
/// This must be injected before any path related middleware.
/// </remarks>
/// <param name="appBuilder">The application builder.</param>
/// <returns>The updated application builder.</returns>
public static IApplicationBuilder UsePathTrim(this IApplicationBuilder appBuilder)
{
return appBuilder.UseMiddleware<LegacyEmbyRouteRewriteMiddleware>();
}
} }
} }

View File

@@ -33,9 +33,11 @@ using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Cors.Infrastructure; using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen; using Swashbuckle.AspNetCore.SwaggerGen;
using AuthenticationSchemes = Jellyfin.Api.Constants.AuthenticationSchemes; using AuthenticationSchemes = Jellyfin.Api.Constants.AuthenticationSchemes;
@@ -259,7 +261,8 @@ namespace Jellyfin.Server.Extensions
c.OperationFilter<FileRequestFilter>(); c.OperationFilter<FileRequestFilter>();
c.OperationFilter<ParameterObsoleteFilter>(); c.OperationFilter<ParameterObsoleteFilter>();
c.DocumentFilter<AdditionalModelFilter>(); c.DocumentFilter<AdditionalModelFilter>();
}); })
.Replace(ServiceDescriptor.Transient<ISwaggerProvider, CachingOpenApiProvider>());
} }
private static void AddPolicy(this AuthorizationOptions authorizationOptions, string policyName, IAuthorizationRequirement authorizationRequirement) private static void AddPolicy(this AuthorizationOptions authorizationOptions, string policyName, IAuthorizationRequirement authorizationRequirement)

View File

@@ -0,0 +1,79 @@
using System;
using AsyncKeyedLock;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace Jellyfin.Server.Filters;
/// <summary>
/// OpenApi provider with caching.
/// </summary>
internal sealed class CachingOpenApiProvider : ISwaggerProvider
{
private const string CacheKey = "openapi.json";
private static readonly MemoryCacheEntryOptions _cacheOptions = new() { SlidingExpiration = TimeSpan.FromMinutes(5) };
private static readonly AsyncNonKeyedLocker _lock = new(1);
private static readonly TimeSpan _lockTimeout = TimeSpan.FromSeconds(1);
private readonly IMemoryCache _memoryCache;
private readonly SwaggerGenerator _swaggerGenerator;
private readonly SwaggerGeneratorOptions _swaggerGeneratorOptions;
/// <summary>
/// Initializes a new instance of the <see cref="CachingOpenApiProvider"/> class.
/// </summary>
/// <param name="optionsAccessor">The options accessor.</param>
/// <param name="apiDescriptionsProvider">The api descriptions provider.</param>
/// <param name="schemaGenerator">The schema generator.</param>
/// <param name="memoryCache">The memory cache.</param>
public CachingOpenApiProvider(
IOptions<SwaggerGeneratorOptions> optionsAccessor,
IApiDescriptionGroupCollectionProvider apiDescriptionsProvider,
ISchemaGenerator schemaGenerator,
IMemoryCache memoryCache)
{
_swaggerGeneratorOptions = optionsAccessor.Value;
_swaggerGenerator = new SwaggerGenerator(_swaggerGeneratorOptions, apiDescriptionsProvider, schemaGenerator);
_memoryCache = memoryCache;
}
/// <inheritdoc />
public OpenApiDocument GetSwagger(string documentName, string? host = null, string? basePath = null)
{
if (_memoryCache.TryGetValue(CacheKey, out OpenApiDocument? openApiDocument) && openApiDocument is not null)
{
return AdjustDocument(openApiDocument, host, basePath);
}
using var acquired = _lock.LockOrNull(_lockTimeout);
if (_memoryCache.TryGetValue(CacheKey, out openApiDocument) && openApiDocument is not null)
{
return AdjustDocument(openApiDocument, host, basePath);
}
if (acquired is null)
{
throw new InvalidOperationException("OpenApi document is generating");
}
openApiDocument = _swaggerGenerator.GetSwagger(documentName);
_memoryCache.Set(CacheKey, openApiDocument, _cacheOptions);
return AdjustDocument(openApiDocument, host, basePath);
}
private OpenApiDocument AdjustDocument(OpenApiDocument document, string? host, string? basePath)
{
document.Servers = _swaggerGeneratorOptions.Servers.Count != 0
? _swaggerGeneratorOptions.Servers
: string.IsNullOrEmpty(host) && string.IsNullOrEmpty(basePath)
? []
: [new OpenApiServer { Url = $"{host}{basePath}" }];
return document;
}
}

View File

@@ -0,0 +1,105 @@
using System;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Database.Implementations;
using Jellyfin.Database.Implementations.Entities;
using Jellyfin.Extensions;
using Jellyfin.Server.Implementations.Item;
using Jellyfin.Server.ServerSetupApp;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Server.Migrations.Routines;
/// <summary>
/// Migration to refresh CleanName values for all library items.
/// </summary>
[JellyfinMigration("2025-10-08T12:00:00", nameof(RefreshCleanNames))]
[JellyfinMigrationBackup(JellyfinDb = true)]
public class RefreshCleanNames : IAsyncMigrationRoutine
{
private readonly IStartupLogger<RefreshCleanNames> _logger;
private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
/// <summary>
/// Initializes a new instance of the <see cref="RefreshCleanNames"/> class.
/// </summary>
/// <param name="logger">The logger.</param>
/// <param name="dbProvider">Instance of the <see cref="IDbContextFactory{JellyfinDbContext}"/> interface.</param>
public RefreshCleanNames(
IStartupLogger<RefreshCleanNames> logger,
IDbContextFactory<JellyfinDbContext> dbProvider)
{
_logger = logger;
_dbProvider = dbProvider;
}
/// <inheritdoc />
public async Task PerformAsync(CancellationToken cancellationToken)
{
const int Limit = 1000;
int itemCount = 0;
var sw = Stopwatch.StartNew();
using var context = _dbProvider.CreateDbContext();
var records = context.BaseItems.Count(b => !string.IsNullOrEmpty(b.Name));
_logger.LogInformation("Refreshing CleanName for {Count} library items", records);
var processedInPartition = 0;
await foreach (var item in context.BaseItems
.Where(b => !string.IsNullOrEmpty(b.Name))
.OrderBy(e => e.Id)
.WithPartitionProgress((partition) => _logger.LogInformation("Processed: {Offset}/{Total} - Updated: {UpdatedCount} - Time: {Elapsed}", partition * Limit, records, itemCount, sw.Elapsed))
.PartitionEagerAsync(Limit, cancellationToken)
.WithCancellation(cancellationToken)
.ConfigureAwait(false))
{
try
{
var newCleanName = string.IsNullOrWhiteSpace(item.Name) ? string.Empty : BaseItemRepository.GetCleanValue(item.Name);
if (!string.Equals(newCleanName, item.CleanName, StringComparison.Ordinal))
{
_logger.LogDebug(
"Updating CleanName for item {Id}: '{OldValue}' -> '{NewValue}'",
item.Id,
item.CleanName,
newCleanName);
item.CleanName = newCleanName;
itemCount++;
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to update CleanName for item {Id} ({Name})", item.Id, item.Name);
}
processedInPartition++;
if (processedInPartition >= Limit)
{
await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// Clear tracked entities to avoid memory growth across partitions
context.ChangeTracker.Clear();
processedInPartition = 0;
}
}
// Save any remaining changes after the loop
if (processedInPartition > 0)
{
await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
context.ChangeTracker.Clear();
}
_logger.LogInformation(
"Refreshed CleanName for {UpdatedCount} out of {TotalCount} items in {Time}",
itemCount,
records,
sw.Elapsed);
}
}

View File

@@ -173,9 +173,6 @@ namespace Jellyfin.Server
mainApp.UseHttpsRedirection(); mainApp.UseHttpsRedirection();
} }
// This must be injected before any path related middleware.
mainApp.UsePathTrim();
if (appConfig.HostWebClient()) if (appConfig.HostWebClient())
{ {
var extensionProvider = new FileExtensionContentTypeProvider(); var extensionProvider = new FileExtensionContentTypeProvider();

View File

@@ -1,7 +1,7 @@
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16 # Visual Studio Version 18
VisualStudioVersion = 16.0.30503.244 VisualStudioVersion = 18.0.11222.15 d18.0
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server", "Jellyfin.Server\Jellyfin.Server.csproj", "{07E39F42-A2C6-4B32-AF8C-725F957A73FF}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server", "Jellyfin.Server\Jellyfin.Server.csproj", "{07E39F42-A2C6-4B32-AF8C-725F957A73FF}"
EndProject EndProject
@@ -30,6 +30,7 @@ EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{41093F42-C7CC-4D07-956B-6182CBEDE2EC}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{41093F42-C7CC-4D07-956B-6182CBEDE2EC}"
ProjectSection(SolutionItems) = preProject ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig .editorconfig = .editorconfig
Directory.Packages.props = Directory.Packages.props
SharedVersion.cs = SharedVersion.cs SharedVersion.cs = SharedVersion.cs
EndProjectSection EndProjectSection
EndProject EndProject

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<!-- ProjectGuid is only included as a requirement for SonarQube analysis --> <!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
<PropertyGroup> <PropertyGroup>

View File

@@ -1409,7 +1409,7 @@ namespace MediaBrowser.Controller.Entities
if (this is BoxSet && (query.OrderBy is null || query.OrderBy.Count == 0)) if (this is BoxSet && (query.OrderBy is null || query.OrderBy.Count == 0))
{ {
realChildren = realChildren realChildren = realChildren
.OrderBy(e => e.ProductionYear ?? int.MaxValue) .OrderBy(e => e.PremiereDate ?? DateTime.MaxValue)
.ToArray(); .ToArray();
} }

View File

@@ -455,7 +455,7 @@ namespace MediaBrowser.Controller.Entities
var itemsArray = totalRecordLimit.HasValue ? items.Take(totalRecordLimit.Value).ToArray() : items.ToArray(); var itemsArray = totalRecordLimit.HasValue ? items.Take(totalRecordLimit.Value).ToArray() : items.ToArray();
var totalCount = itemsArray.Length; var totalCount = itemsArray.Length;
if (query.Limit.HasValue) if (query.Limit.HasValue && query.Limit.Value > 0)
{ {
itemsArray = itemsArray.Skip(query.StartIndex ?? 0).Take(query.Limit.Value).ToArray(); itemsArray = itemsArray.Skip(query.StartIndex ?? 0).Take(query.Limit.Value).ToArray();
} }

View File

@@ -63,6 +63,29 @@ public static class FileSystemHelper
} }
} }
/// <summary>
/// Resolves a single link hop for the specified path.
/// </summary>
/// <remarks>
/// Returns <c>null</c> if the path is not a symbolic link or the filesystem does not support link resolution (e.g., exFAT).
/// </remarks>
/// <param name="path">The file path to resolve.</param>
/// <returns>
/// A <see cref="FileInfo"/> representing the next link target if the path is a link; otherwise, <c>null</c>.
/// </returns>
private static FileInfo? Resolve(string path)
{
try
{
return File.ResolveLinkTarget(path, returnFinalTarget: false) as FileInfo;
}
catch (IOException)
{
// Filesystem doesn't support links (e.g., exFAT).
return null;
}
}
/// <summary> /// <summary>
/// Gets the target of the specified file link. /// Gets the target of the specified file link.
/// </summary> /// </summary>
@@ -84,23 +107,26 @@ public static class FileSystemHelper
if (!returnFinalTarget) if (!returnFinalTarget)
{ {
return File.ResolveLinkTarget(linkPath, returnFinalTarget: false) as FileInfo; return Resolve(linkPath);
} }
if (File.ResolveLinkTarget(linkPath, returnFinalTarget: false) is not FileInfo targetInfo) var targetInfo = Resolve(linkPath);
{ if (targetInfo is null || !targetInfo.Exists)
return null;
}
if (!targetInfo.Exists)
{ {
return targetInfo; return targetInfo;
} }
var currentPath = targetInfo.FullName; var currentPath = targetInfo.FullName;
var visited = new HashSet<string>(StringComparer.Ordinal) { linkPath, currentPath }; var visited = new HashSet<string>(StringComparer.Ordinal) { linkPath, currentPath };
while (File.ResolveLinkTarget(currentPath, returnFinalTarget: false) is FileInfo linkInfo)
while (true)
{ {
var linkInfo = Resolve(currentPath);
if (linkInfo is null)
{
break;
}
var targetPath = linkInfo.FullName; var targetPath = linkInfo.FullName;
// If an infinite loop is detected, return the file info for the // If an infinite loop is detected, return the file info for the

View File

@@ -2378,6 +2378,13 @@ namespace MediaBrowser.Controller.MediaEncoding
var requestHasSDR = requestedRangeTypes.Contains(VideoRangeType.SDR.ToString(), StringComparison.OrdinalIgnoreCase); var requestHasSDR = requestedRangeTypes.Contains(VideoRangeType.SDR.ToString(), StringComparison.OrdinalIgnoreCase);
var requestHasDOVI = requestedRangeTypes.Contains(VideoRangeType.DOVI.ToString(), StringComparison.OrdinalIgnoreCase); var requestHasDOVI = requestedRangeTypes.Contains(VideoRangeType.DOVI.ToString(), StringComparison.OrdinalIgnoreCase);
// If SDR is the only supported range, we should not copy any of the HDR streams.
// All the following copy check assumes at least one HDR format is supported.
if (requestedRangeTypes.Length == 1 && requestHasSDR && videoStream.VideoRangeType != VideoRangeType.SDR)
{
return false;
}
// If the client does not support DOVI and the video stream is DOVI without fallback, we should not copy it. // If the client does not support DOVI and the video stream is DOVI without fallback, we should not copy it.
if (!requestHasDOVI && videoStream.VideoRangeType == VideoRangeType.DOVI) if (!requestHasDOVI && videoStream.VideoRangeType == VideoRangeType.DOVI)
{ {
@@ -5942,28 +5949,37 @@ namespace MediaBrowser.Controller.MediaEncoding
var isFullAfbcPipeline = isEncoderSupportAfbc && isDrmInDrmOut && !doOclTonemap; var isFullAfbcPipeline = isEncoderSupportAfbc && isDrmInDrmOut && !doOclTonemap;
var swapOutputWandH = doRkVppTranspose && swapWAndH; var swapOutputWandH = doRkVppTranspose && swapWAndH;
var outFormat = doOclTonemap ? "p010" : (isMjpegEncoder ? "bgra" : "nv12"); // RGA only support full range in rgb fmts var outFormat = doOclTonemap ? "p010" : "nv12";
var hwScaleFilter = GetHwScaleFilter("vpp", "rkrga", outFormat, swapOutputWandH, swpInW, swpInH, reqW, reqH, reqMaxW, reqMaxH); var hwScaleFilter = GetHwScaleFilter("vpp", "rkrga", outFormat, swapOutputWandH, swpInW, swpInH, reqW, reqH, reqMaxW, reqMaxH);
var doScaling = GetHwScaleFilter("vpp", "rkrga", string.Empty, swapOutputWandH, swpInW, swpInH, reqW, reqH, reqMaxW, reqMaxH); var doScaling = !string.IsNullOrEmpty(GetHwScaleFilter("vpp", "rkrga", string.Empty, swapOutputWandH, swpInW, swpInH, reqW, reqH, reqMaxW, reqMaxH));
if (!hasSubs if (!hasSubs
|| doRkVppTranspose || doRkVppTranspose
|| !isFullAfbcPipeline || !isFullAfbcPipeline
|| !string.IsNullOrEmpty(doScaling)) || doScaling)
{ {
var isScaleRatioSupported = IsScaleRatioSupported(inW, inH, reqW, reqH, reqMaxW, reqMaxH, 8.0f);
// RGA3 hardware only support (1/8 ~ 8) scaling in each blit operation, // RGA3 hardware only support (1/8 ~ 8) scaling in each blit operation,
// but in Trickplay there's a case: (3840/320 == 12), enable 2pass for it // but in Trickplay there's a case: (3840/320 == 12), enable 2pass for it
if (!string.IsNullOrEmpty(doScaling) if (doScaling && !isScaleRatioSupported)
&& !IsScaleRatioSupported(inW, inH, reqW, reqH, reqMaxW, reqMaxH, 8.0f))
{ {
// Vendor provided BSP kernel has an RGA driver bug that causes the output to be corrupted for P010 format. // Vendor provided BSP kernel has an RGA driver bug that causes the output to be corrupted for P010 format.
// Use NV15 instead of P010 to avoid the issue. // Use NV15 instead of P010 to avoid the issue.
// SDR inputs are using BGRA formats already which is not affected. // SDR inputs are using BGRA formats already which is not affected.
var intermediateFormat = string.Equals(outFormat, "p010", StringComparison.OrdinalIgnoreCase) ? "nv15" : outFormat; var intermediateFormat = doOclTonemap ? "nv15" : (isMjpegEncoder ? "bgra" : outFormat);
var hwScaleFilterFirstPass = $"scale_rkrga=w=iw/7.9:h=ih/7.9:format={intermediateFormat}:force_original_aspect_ratio=increase:force_divisible_by=4:afbc=1"; var hwScaleFilterFirstPass = $"scale_rkrga=w=iw/7.9:h=ih/7.9:format={intermediateFormat}:force_original_aspect_ratio=increase:force_divisible_by=4:afbc=1";
mainFilters.Add(hwScaleFilterFirstPass); mainFilters.Add(hwScaleFilterFirstPass);
} }
// The RKMPP MJPEG encoder on some newer chip models no longer supports RGB input.
// Use 2pass here to enable RGA output of full-range YUV in the 2nd pass.
if (isMjpegEncoder && !doOclTonemap && ((doScaling && isScaleRatioSupported) || !doScaling))
{
var hwScaleFilterFirstPass = "vpp_rkrga=format=bgra:afbc=1";
mainFilters.Add(hwScaleFilterFirstPass);
}
if (!string.IsNullOrEmpty(hwScaleFilter) && doRkVppTranspose) if (!string.IsNullOrEmpty(hwScaleFilter) && doRkVppTranspose)
{ {
hwScaleFilter += $":transpose={transposeDir}"; hwScaleFilter += $":transpose={transposeDir}";

View File

@@ -33,7 +33,7 @@ public interface IItemRepository
/// <param name="cancellationToken">The cancellation token.</param> /// <param name="cancellationToken">The cancellation token.</param>
void SaveItems(IReadOnlyList<BaseItem> items, CancellationToken cancellationToken); void SaveItems(IReadOnlyList<BaseItem> items, CancellationToken cancellationToken);
void SaveImages(BaseItem item); Task SaveImagesAsync(BaseItem item, CancellationToken cancellationToken = default);
/// <summary> /// <summary>
/// Retrieves the item. /// Retrieves the item.

View File

@@ -1,3 +1,4 @@
using System;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using BDInfo.IO; using BDInfo.IO;
@@ -58,6 +59,8 @@ public class BdInfoDirectoryInfo : IDirectoryInfo
} }
} }
private static bool IsHidden(ReadOnlySpan<char> name) => name.StartsWith('.');
/// <summary> /// <summary>
/// Gets the directories. /// Gets the directories.
/// </summary> /// </summary>
@@ -65,6 +68,7 @@ public class BdInfoDirectoryInfo : IDirectoryInfo
public IDirectoryInfo[] GetDirectories() public IDirectoryInfo[] GetDirectories()
{ {
return _fileSystem.GetDirectories(_impl.FullName) return _fileSystem.GetDirectories(_impl.FullName)
.Where(d => !IsHidden(d.Name))
.Select(x => new BdInfoDirectoryInfo(_fileSystem, x)) .Select(x => new BdInfoDirectoryInfo(_fileSystem, x))
.ToArray(); .ToArray();
} }
@@ -76,6 +80,7 @@ public class BdInfoDirectoryInfo : IDirectoryInfo
public IFileInfo[] GetFiles() public IFileInfo[] GetFiles()
{ {
return _fileSystem.GetFiles(_impl.FullName) return _fileSystem.GetFiles(_impl.FullName)
.Where(d => !IsHidden(d.Name))
.Select(x => new BdInfoFileInfo(x)) .Select(x => new BdInfoFileInfo(x))
.ToArray(); .ToArray();
} }
@@ -88,6 +93,7 @@ public class BdInfoDirectoryInfo : IDirectoryInfo
public IFileInfo[] GetFiles(string searchPattern) public IFileInfo[] GetFiles(string searchPattern)
{ {
return _fileSystem.GetFiles(_impl.FullName, new[] { searchPattern }, false, false) return _fileSystem.GetFiles(_impl.FullName, new[] { searchPattern }, false, false)
.Where(d => !IsHidden(d.Name))
.Select(x => new BdInfoFileInfo(x)) .Select(x => new BdInfoFileInfo(x))
.ToArray(); .ToArray();
} }
@@ -105,6 +111,7 @@ public class BdInfoDirectoryInfo : IDirectoryInfo
new[] { searchPattern }, new[] { searchPattern },
false, false,
searchOption == SearchOption.AllDirectories) searchOption == SearchOption.AllDirectories)
.Where(d => !IsHidden(d.Name))
.Select(x => new BdInfoFileInfo(x)) .Select(x => new BdInfoFileInfo(x))
.ToArray(); .ToArray();
} }

View File

@@ -511,7 +511,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
? "{0} -i {1} -threads {2} -v warning -print_format json -show_streams -show_chapters -show_format" ? "{0} -i {1} -threads {2} -v warning -print_format json -show_streams -show_chapters -show_format"
: "{0} -i {1} -threads {2} -v warning -print_format json -show_streams -show_format"; : "{0} -i {1} -threads {2} -v warning -print_format json -show_streams -show_format";
if (!isAudio && _proberSupportsFirstVideoFrame) if (protocol == MediaProtocol.File && !isAudio && _proberSupportsFirstVideoFrame)
{ {
args += " -show_frames -only_first_vframe"; args += " -show_frames -only_first_vframe";
} }

View File

@@ -13,8 +13,10 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsyncKeyedLock; using AsyncKeyedLock;
using MediaBrowser.Common; using MediaBrowser.Common;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net; using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.IO; using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Library;
@@ -37,6 +39,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
private readonly IMediaSourceManager _mediaSourceManager; private readonly IMediaSourceManager _mediaSourceManager;
private readonly ISubtitleParser _subtitleParser; private readonly ISubtitleParser _subtitleParser;
private readonly IPathManager _pathManager; private readonly IPathManager _pathManager;
private readonly IServerConfigurationManager _serverConfigurationManager;
/// <summary> /// <summary>
/// The _semaphoreLocks. /// The _semaphoreLocks.
@@ -54,7 +57,8 @@ namespace MediaBrowser.MediaEncoding.Subtitles
IHttpClientFactory httpClientFactory, IHttpClientFactory httpClientFactory,
IMediaSourceManager mediaSourceManager, IMediaSourceManager mediaSourceManager,
ISubtitleParser subtitleParser, ISubtitleParser subtitleParser,
IPathManager pathManager) IPathManager pathManager,
IServerConfigurationManager serverConfigurationManager)
{ {
_logger = logger; _logger = logger;
_fileSystem = fileSystem; _fileSystem = fileSystem;
@@ -63,6 +67,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles
_mediaSourceManager = mediaSourceManager; _mediaSourceManager = mediaSourceManager;
_subtitleParser = subtitleParser; _subtitleParser = subtitleParser;
_pathManager = pathManager; _pathManager = pathManager;
_serverConfigurationManager = serverConfigurationManager;
} }
private MemoryStream ConvertSubtitles( private MemoryStream ConvertSubtitles(
@@ -394,7 +399,8 @@ namespace MediaBrowser.MediaEncoding.Subtitles
try try
{ {
await process.WaitForExitAsync(TimeSpan.FromMinutes(30)).ConfigureAwait(false); var timeoutMinutes = _serverConfigurationManager.GetEncodingOptions().SubtitleExtractionTimeoutMinutes;
await process.WaitForExitAsync(TimeSpan.FromMinutes(timeoutMinutes)).ConfigureAwait(false);
exitCode = process.ExitCode; exitCode = process.ExitCode;
} }
catch (OperationCanceledException) catch (OperationCanceledException)
@@ -677,7 +683,8 @@ namespace MediaBrowser.MediaEncoding.Subtitles
try try
{ {
await process.WaitForExitAsync(TimeSpan.FromMinutes(30)).ConfigureAwait(false); var timeoutMinutes = _serverConfigurationManager.GetEncodingOptions().SubtitleExtractionTimeoutMinutes;
await process.WaitForExitAsync(TimeSpan.FromMinutes(timeoutMinutes)).ConfigureAwait(false);
exitCode = process.ExitCode; exitCode = process.ExitCode;
} }
catch (OperationCanceledException) catch (OperationCanceledException)
@@ -828,7 +835,8 @@ namespace MediaBrowser.MediaEncoding.Subtitles
try try
{ {
await process.WaitForExitAsync(TimeSpan.FromMinutes(30)).ConfigureAwait(false); var timeoutMinutes = _serverConfigurationManager.GetEncodingOptions().SubtitleExtractionTimeoutMinutes;
await process.WaitForExitAsync(TimeSpan.FromMinutes(timeoutMinutes)).ConfigureAwait(false);
exitCode = process.ExitCode; exitCode = process.ExitCode;
} }
catch (OperationCanceledException) catch (OperationCanceledException)

View File

@@ -1,5 +1,3 @@
#pragma warning disable CS1591
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Jellyfin.Data.Events; using Jellyfin.Data.Events;
@@ -7,21 +5,36 @@ using Jellyfin.Data.Queries;
using Jellyfin.Database.Implementations.Entities; using Jellyfin.Database.Implementations.Entities;
using MediaBrowser.Model.Querying; using MediaBrowser.Model.Querying;
namespace MediaBrowser.Model.Activity namespace MediaBrowser.Model.Activity;
/// <summary>
/// Interface for the activity manager.
/// </summary>
public interface IActivityManager
{ {
public interface IActivityManager /// <summary>
{ /// The event that is triggered when an entity is created.
event EventHandler<GenericEventArgs<ActivityLogEntry>> EntryCreated; /// </summary>
event EventHandler<GenericEventArgs<ActivityLogEntry>> EntryCreated;
Task CreateAsync(ActivityLog entry); /// <summary>
/// Create a new activity log entry.
/// </summary>
/// <param name="entry">The entry to create.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
Task CreateAsync(ActivityLog entry);
Task<QueryResult<ActivityLogEntry>> GetPagedResultAsync(ActivityLogQuery query); /// <summary>
/// Get a paged list of activity log entries.
/// </summary>
/// <param name="query">The activity log query.</param>
/// <returns>The page of entries.</returns>
Task<QueryResult<ActivityLogEntry>> GetPagedResultAsync(ActivityLogQuery query);
/// <summary> /// <summary>
/// Remove all activity logs before the specified date. /// Remove all activity logs before the specified date.
/// </summary> /// </summary>
/// <param name="startDate">Activity log start date.</param> /// <param name="startDate">Activity log start date.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
Task CleanAsync(DateTime startDate); Task CleanAsync(DateTime startDate);
}
} }

View File

@@ -57,6 +57,7 @@ public class EncodingOptions
AllowHevcEncoding = false; AllowHevcEncoding = false;
AllowAv1Encoding = false; AllowAv1Encoding = false;
EnableSubtitleExtraction = true; EnableSubtitleExtraction = true;
SubtitleExtractionTimeoutMinutes = 30;
AllowOnDemandMetadataBasedKeyframeExtractionForExtensions = ["mkv"]; AllowOnDemandMetadataBasedKeyframeExtractionForExtensions = ["mkv"];
HardwareDecodingCodecs = ["h264", "vc1"]; HardwareDecodingCodecs = ["h264", "vc1"];
} }
@@ -286,6 +287,11 @@ public class EncodingOptions
/// </summary> /// </summary>
public bool EnableSubtitleExtraction { get; set; } public bool EnableSubtitleExtraction { get; set; }
/// <summary>
/// Gets or sets the timeout for subtitle extraction in minutes.
/// </summary>
public int SubtitleExtractionTimeoutMinutes { get; set; }
/// <summary> /// <summary>
/// Gets or sets the codecs hardware encoding is used for. /// Gets or sets the codecs hardware encoding is used for.
/// </summary> /// </summary>

View File

@@ -151,9 +151,9 @@ namespace MediaBrowser.Providers.Manager
.ConfigureAwait(false); .ConfigureAwait(false);
updateType |= beforeSaveResult; updateType |= beforeSaveResult;
if (!isFirstRefresh) if (isFirstRefresh)
{ {
updateType = await SaveInternal(item, refreshOptions, updateType, isFirstRefresh, requiresRefresh, metadataResult, cancellationToken).ConfigureAwait(false); await SaveItemAsync(metadataResult, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
} }
// Next run metadata providers // Next run metadata providers

View File

@@ -64,13 +64,13 @@ public static class EnumerableExtensions
/// <typeparam name="T">The type of item.</typeparam> /// <typeparam name="T">The type of item.</typeparam>
/// <returns>The IEnumerable{Enum}.</returns> /// <returns>The IEnumerable{Enum}.</returns>
public static IEnumerable<T> GetUniqueFlags<T>(this T flags) public static IEnumerable<T> GetUniqueFlags<T>(this T flags)
where T : Enum where T : struct, Enum
{ {
foreach (Enum value in Enum.GetValues(flags.GetType())) foreach (T value in Enum.GetValues<T>())
{ {
if (flags.HasFlag(value)) if (flags.HasFlag(value))
{ {
yield return (T)value; yield return value;
} }
} }
} }

View File

@@ -240,12 +240,9 @@ namespace Jellyfin.LiveTv.Channels
var all = channels; var all = channels;
var totalCount = all.Count; var totalCount = all.Count;
if (query.StartIndex.HasValue || query.Limit.HasValue) int startIndex = query.StartIndex ?? 0;
{ int count = (query.Limit ?? 0) > 0 ? Math.Min(query.Limit.Value, totalCount - startIndex) : totalCount - startIndex;
int startIndex = query.StartIndex ?? 0; all = all.GetRange(query.StartIndex ?? 0, count);
int count = query.Limit is null ? totalCount - startIndex : Math.Min(query.Limit.Value, totalCount - startIndex);
all = all.GetRange(startIndex, count);
}
if (query.RefreshLatestChannelItems) if (query.RefreshLatestChannelItems)
{ {

View File

@@ -287,7 +287,7 @@ namespace Jellyfin.LiveTv
GenreIds = query.GenreIds GenreIds = query.GenreIds
}; };
if (query.Limit.HasValue) if (query.Limit.HasValue && query.Limit.Value > 0)
{ {
internalQuery.Limit = Math.Max(query.Limit.Value * 4, 200); internalQuery.Limit = Math.Max(query.Limit.Value * 4, 200);
} }
@@ -305,7 +305,7 @@ namespace Jellyfin.LiveTv
IEnumerable<BaseItem> programs = orderedPrograms; IEnumerable<BaseItem> programs = orderedPrograms;
if (query.Limit.HasValue) if (query.Limit.HasValue && query.Limit.Value > 0)
{ {
programs = programs.Take(query.Limit.Value); programs = programs.Take(query.Limit.Value);
} }

View File

@@ -0,0 +1,109 @@
using System;
using AutoFixture;
using AutoFixture.AutoMoq;
using Jellyfin.Server.Implementations.Item;
using MediaBrowser.Controller.Entities.TV;
using Microsoft.Extensions.Configuration;
using Moq;
using Xunit;
namespace Jellyfin.Server.Implementations.Tests.Data
{
public class SearchPunctuationTests
{
private readonly IFixture _fixture;
private readonly BaseItemRepository _repo;
public SearchPunctuationTests()
{
var appHost = new Mock<MediaBrowser.Controller.IServerApplicationHost>();
appHost.Setup(x => x.ExpandVirtualPath(It.IsAny<string>()))
.Returns((string x) => x);
appHost.Setup(x => x.ReverseVirtualPath(It.IsAny<string>()))
.Returns((string x) => x);
var configSection = new Mock<IConfigurationSection>();
configSection
.SetupGet(x => x[It.Is<string>(s => s == MediaBrowser.Controller.Extensions.ConfigurationExtensions.SqliteCacheSizeKey)])
.Returns("0");
var config = new Mock<IConfiguration>();
config
.Setup(x => x.GetSection(It.Is<string>(s => s == MediaBrowser.Controller.Extensions.ConfigurationExtensions.SqliteCacheSizeKey)))
.Returns(configSection.Object);
_fixture = new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true });
_fixture.Inject(appHost.Object);
_fixture.Inject(config.Object);
_repo = _fixture.Create<BaseItemRepository>();
}
[Fact]
public void CleanName_keeps_punctuation_and_search_without_punctuation_passes()
{
var series = new Series
{
Id = Guid.NewGuid(),
Name = "Mr. Robot"
};
series.SortName = "Mr. Robot";
var entity = _repo.Map(series);
Assert.Equal("mr robot", entity.CleanName);
var searchTerm = "Mr Robot".ToLowerInvariant();
Assert.Contains(searchTerm, entity.CleanName ?? string.Empty, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("Spider-Man: Homecoming", "spider man homecoming")]
[InlineData("Beyoncé — Live!", "beyonce live")]
[InlineData("Hello, World!", "hello world")]
[InlineData("(The) Good, the Bad & the Ugly", "the good the bad the ugly")]
[InlineData("Wall-E", "wall e")]
[InlineData("No. 1: The Beginning", "no 1 the beginning")]
[InlineData("Café-au-lait", "cafe au lait")]
public void CleanName_normalizes_various_punctuation(string title, string expectedClean)
{
var series = new Series
{
Id = Guid.NewGuid(),
Name = title
};
series.SortName = title;
var entity = _repo.Map(series);
Assert.Equal(expectedClean, entity.CleanName);
// Ensure a search term without punctuation would match
var searchTerm = expectedClean;
Assert.Contains(searchTerm, entity.CleanName ?? string.Empty, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("Face/Off", "face off")]
[InlineData("V/H/S", "v h s")]
public void CleanName_normalizes_titles_withslashes(string title, string expectedClean)
{
var series = new Series
{
Id = Guid.NewGuid(),
Name = title
};
series.SortName = title;
var entity = _repo.Map(series);
Assert.Equal(expectedClean, entity.CleanName);
// Ensure a search term without punctuation would match
var searchTerm = expectedClean;
Assert.Contains(searchTerm, entity.CleanName ?? string.Empty, StringComparison.OrdinalIgnoreCase);
}
}
}