aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.ci/azure-pipelines-abi.yml93
-rw-r--r--.ci/azure-pipelines-main.yml71
-rw-r--r--.ci/azure-pipelines-package.yml274
-rw-r--r--.ci/azure-pipelines-test.yml98
-rw-r--r--.ci/azure-pipelines.yml64
-rw-r--r--.github/workflows/ci-codeql-analysis.yml6
-rw-r--r--.github/workflows/ci-openapi.yml4
-rw-r--r--.github/workflows/ci-tests.yml2
-rw-r--r--CONTRIBUTORS.md1
-rw-r--r--Directory.Packages.props10
-rw-r--r--Emby.Photos/PhotoProvider.cs241
-rw-r--r--Emby.Server.Implementations/ApplicationHost.cs2
-rw-r--r--Emby.Server.Implementations/Devices/DeviceId.cs14
-rw-r--r--Emby.Server.Implementations/Library/LibraryManager.cs16
-rw-r--r--Emby.Server.Implementations/Library/LiveStreamHelper.cs10
-rw-r--r--Emby.Server.Implementations/Library/MusicManager.cs39
-rw-r--r--Emby.Server.Implementations/Library/SearchEngine.cs10
-rw-r--r--Emby.Server.Implementations/Localization/Core/fr.json4
-rw-r--r--Emby.Server.Implementations/Localization/Core/hi.json28
-rw-r--r--Jellyfin.Api/Controllers/ImageController.cs338
-rw-r--r--Jellyfin.Api/Controllers/ItemsController.cs130
-rw-r--r--Jellyfin.Api/Controllers/LyricsController.cs12
-rw-r--r--Jellyfin.Api/Controllers/PlaystateController.cs168
-rw-r--r--Jellyfin.Api/Controllers/SuggestionsController.cs43
-rw-r--r--Jellyfin.Api/Controllers/UniversalAudioController.cs9
-rw-r--r--Jellyfin.Api/Controllers/UserController.cs92
-rw-r--r--Jellyfin.Api/Controllers/UserLibraryController.cs287
-rw-r--r--Jellyfin.Api/Controllers/UserViewsController.cs61
-rw-r--r--Jellyfin.Data/Enums/MediaStreamProtocol.cs22
-rw-r--r--Jellyfin.Server/Helpers/StartupHelpers.cs3
-rw-r--r--Jellyfin.Server/Migrations/MigrationRunner.cs3
-rw-r--r--Jellyfin.Server/Migrations/Routines/UpdateDefaultPluginRepository.cs52
-rw-r--r--MediaBrowser.Controller/Channels/IHasCacheKey.cs4
-rw-r--r--MediaBrowser.Controller/Channels/ISearchableChannel.cs21
-rw-r--r--MediaBrowser.Controller/Channels/ISupportsLatestMedia.cs4
-rw-r--r--MediaBrowser.Controller/Entities/CollectionFolder.cs11
-rw-r--r--MediaBrowser.Controller/Library/ILibraryManager.cs3
-rw-r--r--MediaBrowser.Controller/Library/IMusicManager.cs8
-rw-r--r--MediaBrowser.Controller/LiveTv/ChannelInfo.cs2
-rw-r--r--MediaBrowser.Controller/Lyrics/ILyricManager.cs17
-rw-r--r--MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs194
-rw-r--r--MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs161
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs2
-rw-r--r--MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs1
-rw-r--r--MediaBrowser.MediaEncoding/Transcoding/TranscodeManager.cs9
-rw-r--r--MediaBrowser.Model/Configuration/EncodingOptions.cs6
-rw-r--r--MediaBrowser.Model/Configuration/LibraryOptions.cs2
-rw-r--r--MediaBrowser.Model/Dlna/StreamBuilder.cs16
-rw-r--r--MediaBrowser.Model/Dlna/StreamInfo.cs14
-rw-r--r--MediaBrowser.Model/Dlna/TranscodingProfile.cs3
-rw-r--r--MediaBrowser.Model/Drawing/ImageFormat.cs17
-rw-r--r--MediaBrowser.Model/Drawing/ImageFormatExtensions.cs2
-rw-r--r--MediaBrowser.Model/Dto/MediaSourceInfo.cs4
-rw-r--r--MediaBrowser.Model/Search/SearchQuery.cs3
-rw-r--r--MediaBrowser.Model/System/LogFile.cs3
-rw-r--r--MediaBrowser.Model/Tasks/ITaskTrigger.cs2
-rw-r--r--MediaBrowser.Providers/Lyric/LyricManager.cs51
-rw-r--r--MediaBrowser.Providers/Manager/ProviderManager.cs114
-rw-r--r--MediaBrowser.Providers/MediaBrowser.Providers.csproj1
-rw-r--r--MediaBrowser.Providers/MediaInfo/AudioFileProber.cs37
-rw-r--r--MediaBrowser.Providers/MediaInfo/ProbeProvider.cs8
-rw-r--r--MediaBrowser.Providers/Plugins/Omdb/JsonOmdbNotAvailableStringConverter.cs3
-rw-r--r--src/Jellyfin.Drawing.Skia/SkiaEncoder.cs46
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonDefaultStringEnumConverter.cs49
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonDefaultStringEnumConverterFactory.cs31
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonGuidConverter.cs2
-rw-r--r--src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs5
-rw-r--r--src/Jellyfin.Extensions/Json/JsonDefaults.cs1
-rw-r--r--src/Jellyfin.Extensions/Json/Utf8JsonExtensions.cs27
-rw-r--r--src/Jellyfin.LiveTv/Channels/ChannelManager.cs1
-rw-r--r--src/Jellyfin.LiveTv/Guide/GuideManager.cs42
-rw-r--r--tests/Jellyfin.Extensions.Tests/Json/Converters/JsonDefaultStringEnumConverterTests.cs112
-rw-r--r--tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs9
-rw-r--r--tests/Jellyfin.Model.Tests/Drawing/ImageFormatExtensionsTests.cs4
-rw-r--r--tests/Jellyfin.Providers.Tests/Manager/ProviderManagerTests.cs4
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest.json (renamed from tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json)0
-rw-r--r--tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs6
77 files changed, 1995 insertions, 1274 deletions
diff --git a/.ci/azure-pipelines-abi.yml b/.ci/azure-pipelines-abi.yml
deleted file mode 100644
index 547a514f8..000000000
--- a/.ci/azure-pipelines-abi.yml
+++ /dev/null
@@ -1,93 +0,0 @@
-parameters:
-- name: Packages
- type: object
- default: {}
-- name: LinuxImage
- type: string
- default: "ubuntu-latest"
-- name: DotNetSdkVersion
- type: string
- default: 8.0.x
-
-jobs:
- - job: CompatibilityCheck
- displayName: Compatibility Check
- dependsOn: Build
- condition: and(succeeded(), variables['System.PullRequest.PullRequestNumber'])
-
- pool:
- vmImage: "${{ parameters.LinuxImage }}"
-
- strategy:
- matrix:
- ${{ each Package in parameters.Packages }}:
- ${{ Package.key }}:
- NugetPackageName: ${{ Package.value.NugetPackageName }}
- AssemblyFileName: ${{ Package.value.AssemblyFileName }}
- maxParallel: 2
-
- steps:
- - checkout: none
-
- - task: UseDotNet@2
- displayName: "Update DotNet"
- inputs:
- packageType: sdk
- version: ${{ parameters.DotNetSdkVersion }}
-
- - task: DotNetCoreCLI@2
- displayName: 'Install ABI CompatibilityChecker Tool'
- inputs:
- command: custom
- custom: tool
- arguments: 'update compatibilitychecker -g'
-
- - task: DownloadPipelineArtifact@2
- displayName: 'Download New Assembly Build Artifact'
- inputs:
- source: 'current'
- artifact: "$(NugetPackageName)"
- path: "$(System.ArtifactsDirectory)/new-artifacts"
- runVersion: "latest"
-
- - task: CopyFiles@2
- displayName: 'Copy New Assembly Build Artifact'
- inputs:
- sourceFolder: $(System.ArtifactsDirectory)/new-artifacts
- contents: '**/*.dll'
- targetFolder: $(System.ArtifactsDirectory)/new-release
- cleanTargetFolder: true
- overWrite: true
- flattenFolders: true
-
- - task: DownloadPipelineArtifact@2
- displayName: 'Download Reference Assembly Build Artifact'
- enabled: false
- inputs:
- source: "specific"
- artifact: "$(NugetPackageName)"
- path: "$(System.ArtifactsDirectory)/current-artifacts"
- project: "$(System.TeamProjectId)"
- pipeline: "$(System.DefinitionId)"
- runVersion: "latestFromBranch"
- runBranch: "refs/heads/$(System.PullRequest.TargetBranch)"
-
- - task: CopyFiles@2
- displayName: 'Copy Reference Assembly Build Artifact'
- enabled: false
- inputs:
- sourceFolder: $(System.ArtifactsDirectory)/current-artifacts
- contents: '**/*.dll'
- targetFolder: $(System.ArtifactsDirectory)/current-release
- cleanTargetFolder: true
- overWrite: true
- flattenFolders: true
-
- - task: DotNetCoreCLI@2
- displayName: 'Execute ABI Compatibility Check Tool'
- enabled: false
- inputs:
- command: custom
- custom: compat
- arguments: 'current-release/$(AssemblyFileName) new-release/$(AssemblyFileName) --azure-pipelines --warnings-only'
- workingDirectory: $(System.ArtifactsDirectory)
diff --git a/.ci/azure-pipelines-main.yml b/.ci/azure-pipelines-main.yml
deleted file mode 100644
index 0702aeb6b..000000000
--- a/.ci/azure-pipelines-main.yml
+++ /dev/null
@@ -1,71 +0,0 @@
-parameters:
- LinuxImage: 'ubuntu-latest'
- RestoreBuildProjects: 'Jellyfin.Server/Jellyfin.Server.csproj'
- DotNetSdkVersion: 8.0.x
-
-jobs:
- - job: Build
- displayName: Build
- strategy:
- matrix:
- Release:
- BuildConfiguration: Release
- Debug:
- BuildConfiguration: Debug
- pool:
- vmImage: '${{ parameters.LinuxImage }}'
- steps:
- - checkout: self
- clean: true
- submodules: true
- persistCredentials: true
-
- - task: UseDotNet@2
- displayName: 'Update DotNet'
- inputs:
- packageType: sdk
- version: ${{ parameters.DotNetSdkVersion }}
-
- - task: DotNetCoreCLI@2
- displayName: 'Publish Server'
- inputs:
- command: publish
- publishWebProjects: false
- projects: '${{ parameters.RestoreBuildProjects }}'
- arguments: '--configuration $(BuildConfiguration) --output $(Build.ArtifactStagingDirectory)'
- zipAfterPublish: false
-
- - task: PublishPipelineArtifact@1
- displayName: 'Publish Artifact Naming'
- condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release'))
- inputs:
- targetPath: '$(build.ArtifactStagingDirectory)/Jellyfin.Server/Emby.Naming.dll'
- artifactName: 'Jellyfin.Naming'
-
- - task: PublishPipelineArtifact@1
- displayName: 'Publish Artifact Controller'
- condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release'))
- inputs:
- targetPath: '$(build.ArtifactStagingDirectory)/Jellyfin.Server/MediaBrowser.Controller.dll'
- artifactName: 'Jellyfin.Controller'
-
- - task: PublishPipelineArtifact@1
- displayName: 'Publish Artifact Model'
- condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release'))
- inputs:
- targetPath: '$(build.ArtifactStagingDirectory)/Jellyfin.Server/MediaBrowser.Model.dll'
- artifactName: 'Jellyfin.Model'
-
- - task: PublishPipelineArtifact@1
- displayName: 'Publish Artifact Common'
- condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release'))
- inputs:
- targetPath: '$(build.ArtifactStagingDirectory)/Jellyfin.Server/MediaBrowser.Common.dll'
- artifactName: 'Jellyfin.Common'
-
- - task: PublishPipelineArtifact@1
- displayName: 'Publish Artifact Extensions'
- condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release'))
- inputs:
- targetPath: '$(build.ArtifactStagingDirectory)/Jellyfin.Server/Jellyfin.Extensions.dll'
- artifactName: 'Jellyfin.Extensions'
diff --git a/.ci/azure-pipelines-package.yml b/.ci/azure-pipelines-package.yml
deleted file mode 100644
index b0684c0d4..000000000
--- a/.ci/azure-pipelines-package.yml
+++ /dev/null
@@ -1,274 +0,0 @@
-jobs:
-- job: BuildPackage
- displayName: 'Build Packages'
-
- strategy:
- matrix:
- CentOS.amd64:
- BuildConfiguration: centos.amd64
- Fedora.amd64:
- BuildConfiguration: fedora.amd64
- Debian.amd64:
- BuildConfiguration: debian.amd64
- Debian.arm64:
- BuildConfiguration: debian.arm64
- Debian.armhf:
- BuildConfiguration: debian.armhf
- Ubuntu.amd64:
- BuildConfiguration: ubuntu.amd64
- Ubuntu.arm64:
- BuildConfiguration: ubuntu.arm64
- Ubuntu.armhf:
- BuildConfiguration: ubuntu.armhf
- Linux.amd64:
- BuildConfiguration: linux.amd64
- Linux.amd64-musl:
- BuildConfiguration: linux.amd64-musl
- Linux.arm64:
- BuildConfiguration: linux.arm64
- Linux.musl-linux-arm64:
- BuildConfiguration: linux.musl-linux-arm64
- Linux.armhf:
- BuildConfiguration: linux.armhf
- Windows.amd64:
- BuildConfiguration: windows.amd64
- MacOS.amd64:
- BuildConfiguration: macos.amd64
- MacOS.arm64:
- BuildConfiguration: macos.arm64
- Portable:
- BuildConfiguration: portable
-
- pool:
- vmImage: 'ubuntu-latest'
-
- steps:
- - script: echo "##vso[task.setvariable variable=JellyfinVersion]$( awk -F '/' '{ print $NF }' <<<'$(Build.SourceBranch)' | sed 's/^v//' )"
- displayName: Set release version (stable)
- condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v')
-
- - script: 'docker build -f deployment/Dockerfile.$(BuildConfiguration) -t jellyfin-server-$(BuildConfiguration) --label "org.opencontainers.image.url=$(Build.Repository.Uri)" --label "org.opencontainers.image.revision=$(Build.SourceVersion)" deployment'
- displayName: 'Build Dockerfile'
-
- - script: 'docker image ls -a && docker run -v $(pwd)/deployment/dist:/dist -v $(pwd):/jellyfin -e IS_UNSTABLE="yes" -e BUILD_ID=$(Build.BuildNumber) jellyfin-server-$(BuildConfiguration)'
- displayName: 'Run Dockerfile (unstable)'
- condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/master')
-
- - script: 'docker image ls -a && docker run -v $(pwd)/deployment/dist:/dist -v $(pwd):/jellyfin -e IS_UNSTABLE="no" -e BUILD_ID=$(Build.BuildNumber) jellyfin-server-$(BuildConfiguration)'
- displayName: 'Run Dockerfile (stable)'
- condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v')
-
- - task: PublishPipelineArtifact@1
- displayName: 'Publish Release'
- inputs:
- targetPath: '$(Build.SourcesDirectory)/deployment/dist'
- artifactName: 'jellyfin-server-$(BuildConfiguration)'
-
- - task: SSH@0
- displayName: 'Create target directory on repository server'
- inputs:
- sshEndpoint: repository
- runOptions: 'inline'
- inline: 'mkdir -p /srv/repository/incoming/azure/$(Build.BuildNumber)/$(BuildConfiguration)'
-
- - task: CopyFilesOverSSH@0
- displayName: 'Upload artifacts to repository server'
- inputs:
- sshEndpoint: repository
- sourceFolder: '$(Build.SourcesDirectory)/deployment/dist'
- contents: '**'
- targetFolder: '/srv/repository/incoming/azure/$(Build.BuildNumber)/$(BuildConfiguration)'
-
-- job: OpenAPISpec
- dependsOn: Test
- condition: or(startsWith(variables['Build.SourceBranch'], 'refs/heads/master'),startsWith(variables['Build.SourceBranch'], 'refs/tags/v'))
- displayName: 'Push OpenAPI Spec to repository'
-
- pool:
- vmImage: 'ubuntu-latest'
-
- steps:
- - script: echo "##vso[task.setvariable variable=JellyfinVersion]$( awk -F '/' '{ print $NF }' <<<'$(Build.SourceBranch)' | sed 's/^v//' )"
- displayName: Set release version (stable)
- condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v')
-
- - task: DownloadPipelineArtifact@2
- displayName: 'Download OpenAPI Spec'
- inputs:
- source: 'current'
- artifact: "OpenAPI Spec"
- path: "$(System.ArtifactsDirectory)/openapispec"
- runVersion: "latest"
-
- - task: SSH@0
- displayName: 'Create target directory on repository server'
- inputs:
- sshEndpoint: repository
- runOptions: 'inline'
- inline: 'mkdir -p /srv/repository/incoming/azure/$(Build.BuildNumber)'
-
- - task: CopyFilesOverSSH@0
- displayName: 'Upload artifacts to repository server'
- inputs:
- sshEndpoint: repository
- sourceFolder: '$(System.ArtifactsDirectory)/openapispec'
- contents: 'openapi.json'
- targetFolder: '/srv/repository/incoming/azure/$(Build.BuildNumber)'
-
-- job: BuildDocker
- displayName: 'Build Docker'
-
- strategy:
- matrix:
- amd64:
- BuildConfiguration: amd64
- arm64:
- BuildConfiguration: arm64
- armhf:
- BuildConfiguration: armhf
-
- pool:
- vmImage: 'ubuntu-latest'
-
- variables:
- - name: JellyfinVersion
- value: 0.0.0
-
- steps:
- - script: echo "##vso[task.setvariable variable=JellyfinVersion]$( awk -F '/' '{ print $NF }' <<<'$(Build.SourceBranch)' | sed 's/^v//' )"
- displayName: Set release version (stable)
- condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v')
-
- - task: Docker@2
- displayName: 'Push Unstable Image'
- condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/master')
- inputs:
- repository: 'jellyfin/jellyfin-server'
- command: buildAndPush
- buildContext: '.'
- Dockerfile: 'deployment/Dockerfile.docker.$(BuildConfiguration)'
- containerRegistry: Docker Hub
- tags: |
- unstable-$(Build.BuildNumber)-$(BuildConfiguration)
- unstable-$(BuildConfiguration)
-
- - task: Docker@2
- displayName: 'Push Stable Image'
- condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v')
- inputs:
- repository: 'jellyfin/jellyfin-server'
- command: buildAndPush
- buildContext: '.'
- Dockerfile: 'deployment/Dockerfile.docker.$(BuildConfiguration)'
- containerRegistry: Docker Hub
- tags: |
- stable-$(Build.BuildNumber)-$(BuildConfiguration)
- $(JellyfinVersion)-$(BuildConfiguration)
-
-- job: CollectArtifacts
- timeoutInMinutes: 20
- displayName: 'Collect Artifacts'
- condition: succeededOrFailed()
- continueOnError: true
- dependsOn:
- - BuildPackage
- - BuildDocker
-
- pool:
- vmImage: 'ubuntu-latest'
-
- steps:
- - task: SSH@0
- displayName: 'Update Unstable Repository'
- continueOnError: true
- condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/master')
- inputs:
- sshEndpoint: repository
- runOptions: 'commands'
- commands: nohup sudo /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) unstable &
-
- - task: SSH@0
- displayName: 'Update Stable Repository'
- continueOnError: true
- condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v')
- inputs:
- sshEndpoint: repository
- runOptions: 'commands'
- commands: nohup sudo /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) $(Build.SourceBranch) &
-
-- job: PublishNuget
- displayName: 'Publish NuGet packages'
-
- pool:
- vmImage: 'ubuntu-latest'
-
- variables:
- - name: JellyfinVersion
- value: $[replace(variables['Build.SourceBranch'],'refs/tags/v','')]
-
- steps:
- - task: UseDotNet@2
- displayName: 'Use .NET 8.0 sdk'
- inputs:
- packageType: 'sdk'
- version: '8.0.x'
-
- - task: DotNetCoreCLI@2
- displayName: 'Build Stable Nuget packages'
- condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v')
- inputs:
- command: 'custom'
- projects: |
- Jellyfin.Data/Jellyfin.Data.csproj
- MediaBrowser.Common/MediaBrowser.Common.csproj
- MediaBrowser.Controller/MediaBrowser.Controller.csproj
- MediaBrowser.Model/MediaBrowser.Model.csproj
- Emby.Naming/Emby.Naming.csproj
- src/Jellyfin.Extensions/Jellyfin.Extensions.csproj
- custom: 'pack'
- arguments: -o $(Build.ArtifactStagingDirectory) -p:Version=$(JellyfinVersion)
-
- - task: DotNetCoreCLI@2
- displayName: 'Build Unstable Nuget packages'
- condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/master')
- inputs:
- command: 'custom'
- projects: |
- Jellyfin.Data/Jellyfin.Data.csproj
- MediaBrowser.Common/MediaBrowser.Common.csproj
- MediaBrowser.Controller/MediaBrowser.Controller.csproj
- MediaBrowser.Model/MediaBrowser.Model.csproj
- Emby.Naming/Emby.Naming.csproj
- src/Jellyfin.Extensions/Jellyfin.Extensions.csproj
- custom: 'pack'
- arguments: '--version-suffix $(Build.BuildNumber) -o $(Build.ArtifactStagingDirectory) -p:Stability=Unstable'
-
- - task: PublishBuildArtifacts@1
- displayName: 'Publish Nuget packages'
- inputs:
- pathToPublish: $(Build.ArtifactStagingDirectory)
- artifactName: Jellyfin Nuget Packages
-
- - task: NuGetCommand@2
- displayName: 'Push Nuget packages to stable feed'
- condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v')
- inputs:
- command: 'push'
- packagesToPush: '$(Build.ArtifactStagingDirectory)/**/*.nupkg'
- nuGetFeedType: 'external'
- publishFeedCredentials: 'NugetOrg'
- allowPackageConflicts: true # This ignores an error if the version already exists
-
- - task: NuGetAuthenticate@1
- displayName: 'Authenticate to unstable Nuget feed'
- condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/master')
-
- - task: NuGetCommand@2
- displayName: 'Push Nuget packages to unstable feed'
- condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/master')
- inputs:
- command: 'push'
- packagesToPush: '$(Build.ArtifactStagingDirectory)/**/*.nupkg;!$(Build.ArtifactStagingDirectory)/**/*.symbols.nupkg' # No symbols since Azure Artifact does not support it
- nuGetFeedType: 'internal'
- publishVstsFeed: '7cce6c46-d610-45e3-9fb7-65a6bfd1b671/a5746b79-f369-42db-93ff-59cd066f9327'
- allowPackageConflicts: true # This ignores an error if the version already exists
diff --git a/.ci/azure-pipelines-test.yml b/.ci/azure-pipelines-test.yml
deleted file mode 100644
index 3549c691c..000000000
--- a/.ci/azure-pipelines-test.yml
+++ /dev/null
@@ -1,98 +0,0 @@
-parameters:
-- name: ImageNames
- type: object
- default:
- Linux: "ubuntu-latest"
- Windows: "windows-latest"
- macOS: "macos-latest"
-- name: TestProjects
- type: string
- default: "tests/**/*Tests.csproj"
-- name: DotNetSdkVersion
- type: string
- default: 8.0.x
-
-jobs:
- - job: Test
- displayName: Test
- strategy:
- matrix:
- ${{ each imageName in parameters.ImageNames }}:
- ${{ imageName.key }}:
- ImageName: ${{ imageName.value }}
- pool:
- vmImage: "$(ImageName)"
- steps:
- - checkout: self
- clean: true
- submodules: true
- persistCredentials: false
-
- # This is required for the SonarCloud analyzer
- - task: UseDotNet@2
- displayName: "Install .NET SDK 5.x"
- condition: eq(variables['ImageName'], 'ubuntu-latest')
- inputs:
- packageType: sdk
- version: '5.x'
-
- - task: UseDotNet@2
- displayName: "Update DotNet"
- inputs:
- packageType: sdk
- version: ${{ parameters.DotNetSdkVersion }}
-
- - task: SonarCloudPrepare@1
- displayName: 'Prepare analysis on SonarCloud'
- condition: eq(variables['ImageName'], 'ubuntu-latest')
- enabled: false
- inputs:
- SonarCloud: 'Sonarcloud for Jellyfin'
- organization: 'jellyfin'
- projectKey: 'jellyfin_jellyfin'
-
- - task: DotNetCoreCLI@2
- displayName: 'Run CLI Tests'
- inputs:
- command: "test"
- projects: ${{ parameters.TestProjects }}
- arguments: '--configuration Release --collect:"XPlat Code Coverage" --settings tests/coverletArgs.runsettings --verbosity minimal'
- publishTestResults: true
- testRunTitle: $(Agent.JobName)
- workingDirectory: "$(Build.SourcesDirectory)"
-
- - task: SonarCloudAnalyze@1
- displayName: 'Run Code Analysis'
- condition: eq(variables['ImageName'], 'ubuntu-latest')
- enabled: false
-
- - task: SonarCloudPublish@1
- displayName: 'Publish Quality Gate Result'
- condition: eq(variables['ImageName'], 'ubuntu-latest')
- enabled: false
-
- - task: Palmmedia.reportgenerator.reportgenerator-build-release-task.reportgenerator@4
- condition: and(succeeded(), eq(variables['Agent.OS'], 'Linux')) # !! THIS is for V1 only V2 will/should support merging
- displayName: 'Run ReportGenerator'
- inputs:
- reports: "$(Agent.TempDirectory)/**/coverage.cobertura.xml"
- targetdir: "$(Agent.TempDirectory)/merged/"
- reporttypes: "Cobertura"
-
- ## V2 is already in the repository but it does not work "wrong number of segments" YAML error.
- - task: PublishCodeCoverageResults@1
- condition: and(succeeded(), eq(variables['Agent.OS'], 'Linux')) # !! THIS is for V1 only V2 will/should support merging
- displayName: 'Publish Code Coverage'
- inputs:
- codeCoverageTool: "cobertura"
- #summaryFileLocation: '$(Agent.TempDirectory)/**/coverage.cobertura.xml' # !!THIS IS FOR V2
- summaryFileLocation: "$(Agent.TempDirectory)/merged/**.xml"
- pathToSources: $(Build.SourcesDirectory)
- failIfCoverageEmpty: true
-
- - task: PublishPipelineArtifact@1
- displayName: 'Publish OpenAPI Artifact'
- condition: and(succeeded(), eq(variables['Agent.OS'], 'Linux'))
- inputs:
- targetPath: "tests/Jellyfin.Server.Integration.Tests/bin/Release/net8.0/openapi.json"
- artifactName: 'OpenAPI Spec'
diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml
deleted file mode 100644
index 19c9caacb..000000000
--- a/.ci/azure-pipelines.yml
+++ /dev/null
@@ -1,64 +0,0 @@
-name: $(Date:yyyyMMdd)$(Rev:.r)
-
-variables:
-- name: TestProjects
- value: 'tests/**/*Tests.csproj'
-- name: RestoreBuildProjects
- value: 'Jellyfin.Server/Jellyfin.Server.csproj'
-
-pr:
- autoCancel: true
-
-trigger:
- batch: true
- branches:
- include:
- - '*'
- tags:
- include:
- - 'v*'
-
-jobs:
-- ${{ if not(startsWith(variables['Build.SourceBranch'], 'refs/tags/v')) }}:
- - template: azure-pipelines-main.yml
- parameters:
- LinuxImage: 'ubuntu-latest'
- RestoreBuildProjects: $(RestoreBuildProjects)
-
-- ${{ if not(or(startsWith(variables['Build.SourceBranch'], 'refs/tags/v'), startsWith(variables['Build.SourceBranch'], 'refs/heads/master'))) }}:
- - template: azure-pipelines-test.yml
- parameters:
- ImageNames:
- Linux: 'ubuntu-latest'
- Windows: 'windows-latest'
- macOS: 'macos-latest'
-
-- ${{ if or(startsWith(variables['Build.SourceBranch'], 'refs/tags/v'), startsWith(variables['Build.SourceBranch'], 'refs/heads/master')) }}:
- - template: azure-pipelines-test.yml
- parameters:
- ImageNames:
- Linux: 'ubuntu-latest'
-
-- ${{ if not(or(startsWith(variables['Build.SourceBranch'], 'refs/tags/v'), startsWith(variables['Build.SourceBranch'], 'refs/heads/master'))) }}:
- - template: azure-pipelines-abi.yml
- parameters:
- Packages:
- Naming:
- NugetPackageName: Jellyfin.Naming
- AssemblyFileName: Emby.Naming.dll
- Controller:
- NugetPackageName: Jellyfin.Controller
- AssemblyFileName: MediaBrowser.Controller.dll
- Model:
- NugetPackageName: Jellyfin.Model
- AssemblyFileName: MediaBrowser.Model.dll
- Common:
- NugetPackageName: Jellyfin.Common
- AssemblyFileName: MediaBrowser.Common.dll
- Extensions:
- NugetPackageName: Jellyfin.Extensions
- AssemblyFileName: Jellyfin.Extensions.dll
- LinuxImage: 'ubuntu-latest'
-
-- ${{ if or(startsWith(variables['Build.SourceBranch'], 'refs/tags/v'), startsWith(variables['Build.SourceBranch'], 'refs/heads/master')) }}:
- - template: azure-pipelines-package.yml
diff --git a/.github/workflows/ci-codeql-analysis.yml b/.github/workflows/ci-codeql-analysis.yml
index 20307dd7d..7bc304186 100644
--- a/.github/workflows/ci-codeql-analysis.yml
+++ b/.github/workflows/ci-codeql-analysis.yml
@@ -27,11 +27,11 @@ jobs:
dotnet-version: '8.0.x'
- name: Initialize CodeQL
- uses: github/codeql-action/init@8a470fddafa5cbb6266ee11b37ef4d8aae19c571 # v3.24.6
+ uses: github/codeql-action/init@3ab4101902695724f9365a384f86c1074d94e18c # v3.24.7
with:
languages: ${{ matrix.language }}
queries: +security-extended
- name: Autobuild
- uses: github/codeql-action/autobuild@8a470fddafa5cbb6266ee11b37ef4d8aae19c571 # v3.24.6
+ uses: github/codeql-action/autobuild@3ab4101902695724f9365a384f86c1074d94e18c # v3.24.7
- name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@8a470fddafa5cbb6266ee11b37ef4d8aae19c571 # v3.24.6
+ uses: github/codeql-action/analyze@3ab4101902695724f9365a384f86c1074d94e18c # v3.24.7
diff --git a/.github/workflows/ci-openapi.yml b/.github/workflows/ci-openapi.yml
index c56349941..b5ccafb86 100644
--- a/.github/workflows/ci-openapi.yml
+++ b/.github/workflows/ci-openapi.yml
@@ -78,12 +78,12 @@ jobs:
- openapi-base
steps:
- name: Download openapi-head
- uses: actions/download-artifact@87c55149d96e628cc2ef7e6fc2aab372015aec85 # v4.1.3
+ uses: actions/download-artifact@c850b930e6ba138125429b7e5c93fc707a7f8427 # v4.1.4
with:
name: openapi-head
path: openapi-head
- name: Download openapi-base
- uses: actions/download-artifact@87c55149d96e628cc2ef7e6fc2aab372015aec85 # v4.1.3
+ uses: actions/download-artifact@c850b930e6ba138125429b7e5c93fc707a7f8427 # v4.1.4
with:
name: openapi-base
path: openapi-base
diff --git a/.github/workflows/ci-tests.yml b/.github/workflows/ci-tests.yml
index 8ee6b3028..96c2df354 100644
--- a/.github/workflows/ci-tests.yml
+++ b/.github/workflows/ci-tests.yml
@@ -34,7 +34,7 @@ jobs:
--verbosity minimal
- name: Merge code coverage results
- uses: danielpalme/ReportGenerator-GitHub-Action@b067e0c5d288fb4277b9f397b2dc6013f60381f0 # 5.2.2
+ uses: danielpalme/ReportGenerator-GitHub-Action@7a0988e399533f3680a732dceda1a967cafdafcd # 5.2.3
with:
reports: "**/coverage.cobertura.xml"
targetdir: "merged/"
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index 55642e4e2..e9c0fb2ad 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -180,6 +180,7 @@
_ [Barasingha](https://github.com/MaVdbussche)
- [Gauvino](https://github.com/Gauvino)
- [felix920506](https://github.com/felix920506)
+ - [btopherjohnson](https://github.com/btopherjohnson)
# Emby Contributors
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 1d7ebfaf4..1d012e546 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -8,15 +8,15 @@
<PackageVersion Include="AutoFixture.AutoMoq" Version="4.18.1" />
<PackageVersion Include="AutoFixture.Xunit2" Version="4.18.1" />
<PackageVersion Include="AutoFixture" Version="4.18.1" />
- <PackageVersion Include="BDInfo" Version="0.7.6.2" />
+ <PackageVersion Include="BDInfo" Version="0.8.0" />
<PackageVersion Include="BlurHashSharp.SkiaSharp" Version="1.3.2" />
<PackageVersion Include="BlurHashSharp" Version="1.3.2" />
<PackageVersion Include="CommandLineParser" Version="2.9.1" />
- <PackageVersion Include="coverlet.collector" Version="6.0.1" />
+ <PackageVersion Include="coverlet.collector" Version="6.0.2" />
<PackageVersion Include="Diacritics" Version="3.3.27" />
<PackageVersion Include="DiscUtils.Udf" Version="0.16.13" />
<PackageVersion Include="DotNet.Glob" Version="3.1.3" />
- <PackageVersion Include="EFCoreSecondLevelCacheInterceptor" Version="4.2.2" />
+ <PackageVersion Include="EFCoreSecondLevelCacheInterceptor" Version="4.2.3" />
<PackageVersion Include="FsCheck.Xunit" Version="2.16.6" />
<PackageVersion Include="HarfBuzzSharp.NativeAssets.Linux" Version="7.3.0.1" />
<PackageVersion Include="IDisposableAnalyzers" Version="4.0.7" />
@@ -72,7 +72,7 @@
<PackageVersion Include="SkiaSharp.NativeAssets.Linux" Version="2.88.7" />
<PackageVersion Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" />
<PackageVersion Include="StyleCop.Analyzers" Version="1.2.0-beta.556" />
- <PackageVersion Include="Svg.Skia" Version="1.0.0.13" />
+ <PackageVersion Include="Svg.Skia" Version="1.0.0.16" />
<PackageVersion Include="Swashbuckle.AspNetCore.ReDoc" Version="6.5.0" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageVersion Include="System.Globalization" Version="4.3.0" />
@@ -81,7 +81,7 @@
<PackageVersion Include="System.Text.Json" Version="8.0.2" />
<PackageVersion Include="System.Threading.Tasks.Dataflow" Version="8.0.0" />
<PackageVersion Include="TagLibSharp" Version="2.3.0" />
- <PackageVersion Include="TMDbLib" Version="2.1.0" />
+ <PackageVersion Include="TMDbLib" Version="2.2.0" />
<PackageVersion Include="UTF.Unknown" Version="2.5.1" />
<PackageVersion Include="Xunit.Priority" Version="1.1.6" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.5.7" />
diff --git a/Emby.Photos/PhotoProvider.cs b/Emby.Photos/PhotoProvider.cs
index 27329a7f2..e2f1ca813 100644
--- a/Emby.Photos/PhotoProvider.cs
+++ b/Emby.Photos/PhotoProvider.cs
@@ -16,167 +16,160 @@ using TagLib.IFD;
using TagLib.IFD.Entries;
using TagLib.IFD.Tags;
-namespace Emby.Photos
+namespace Emby.Photos;
+
+/// <summary>
+/// Metadata provider for photos.
+/// </summary>
+public class PhotoProvider : ICustomMetadataProvider<Photo>, IForcedProvider, IHasItemChangeMonitor
{
+ private readonly ILogger<PhotoProvider> _logger;
+ private readonly IImageProcessor _imageProcessor;
+
+ // These are causing taglib to hang
+ private readonly string[] _includeExtensions = [".jpg", ".jpeg", ".png", ".tiff", ".cr2", ".webp", ".avif"];
+
/// <summary>
- /// Metadata provider for photos.
+ /// Initializes a new instance of the <see cref="PhotoProvider" /> class.
/// </summary>
- public class PhotoProvider : ICustomMetadataProvider<Photo>, IForcedProvider, IHasItemChangeMonitor
+ /// <param name="logger">The logger.</param>
+ /// <param name="imageProcessor">The image processor.</param>
+ public PhotoProvider(ILogger<PhotoProvider> logger, IImageProcessor imageProcessor)
{
- private readonly ILogger<PhotoProvider> _logger;
- private readonly IImageProcessor _imageProcessor;
-
- // These are causing taglib to hang
- private readonly string[] _includeExtensions = new string[] { ".jpg", ".jpeg", ".png", ".tiff", ".cr2", ".webp", ".avif" };
-
- /// <summary>
- /// Initializes a new instance of the <see cref="PhotoProvider" /> class.
- /// </summary>
- /// <param name="logger">The logger.</param>
- /// <param name="imageProcessor">The image processor.</param>
- public PhotoProvider(ILogger<PhotoProvider> logger, IImageProcessor imageProcessor)
- {
- _logger = logger;
- _imageProcessor = imageProcessor;
- }
+ _logger = logger;
+ _imageProcessor = imageProcessor;
+ }
- /// <inheritdoc />
- public string Name => "Embedded Information";
+ /// <inheritdoc />
+ public string Name => "Embedded Information";
- /// <inheritdoc />
- public bool HasChanged(BaseItem item, IDirectoryService directoryService)
+ /// <inheritdoc />
+ public bool HasChanged(BaseItem item, IDirectoryService directoryService)
+ {
+ if (item.IsFileProtocol)
{
- if (item.IsFileProtocol)
- {
- var file = directoryService.GetFile(item.Path);
- return file is not null && file.LastWriteTimeUtc != item.DateModified;
- }
-
- return false;
+ var file = directoryService.GetFile(item.Path);
+ return file is not null && file.LastWriteTimeUtc != item.DateModified;
}
- /// <inheritdoc />
- public Task<ItemUpdateType> FetchAsync(Photo item, MetadataRefreshOptions options, CancellationToken cancellationToken)
- {
- item.SetImagePath(ImageType.Primary, item.Path);
+ return false;
+ }
- // Examples: https://github.com/mono/taglib-sharp/blob/a5f6949a53d09ce63ee7495580d6802921a21f14/tests/fixtures/TagLib.Tests.Images/NullOrientationTest.cs
- if (_includeExtensions.Contains(Path.GetExtension(item.Path.AsSpan()), StringComparison.OrdinalIgnoreCase))
+ /// <inheritdoc />
+ public Task<ItemUpdateType> FetchAsync(Photo item, MetadataRefreshOptions options, CancellationToken cancellationToken)
+ {
+ item.SetImagePath(ImageType.Primary, item.Path);
+
+ // Examples: https://github.com/mono/taglib-sharp/blob/a5f6949a53d09ce63ee7495580d6802921a21f14/tests/fixtures/TagLib.Tests.Images/NullOrientationTest.cs
+ if (_includeExtensions.Contains(Path.GetExtension(item.Path.AsSpan()), StringComparison.OrdinalIgnoreCase))
+ {
+ try
{
- try
+ using var file = TagLib.File.Create(item.Path);
+ if (file.GetTag(TagTypes.TiffIFD) is IFDTag tag)
{
- using (var file = TagLib.File.Create(item.Path))
+ var structure = tag.Structure;
+ if (structure?.GetEntry(0, (ushort)IFDEntryTag.ExifIFD) is SubIFDEntry exif)
{
- if (file.GetTag(TagTypes.TiffIFD) is IFDTag tag)
+ var exifStructure = exif.Structure;
+ if (exifStructure is not null)
{
- var structure = tag.Structure;
- if (structure is not null
- && structure.GetEntry(0, (ushort)IFDEntryTag.ExifIFD) is SubIFDEntry exif)
+ if (exifStructure.GetEntry(0, (ushort)ExifEntryTag.ApertureValue) is RationalIFDEntry apertureEntry)
{
- var exifStructure = exif.Structure;
- if (exifStructure is not null)
- {
- var entry = exifStructure.GetEntry(0, (ushort)ExifEntryTag.ApertureValue) as RationalIFDEntry;
- if (entry is not null)
- {
- item.Aperture = (double)entry.Value.Numerator / entry.Value.Denominator;
- }
-
- entry = exifStructure.GetEntry(0, (ushort)ExifEntryTag.ShutterSpeedValue) as RationalIFDEntry;
- if (entry is not null)
- {
- item.ShutterSpeed = (double)entry.Value.Numerator / entry.Value.Denominator;
- }
- }
+ item.Aperture = (double)apertureEntry.Value.Numerator / apertureEntry.Value.Denominator;
+ }
+
+ if (exifStructure.GetEntry(0, (ushort)ExifEntryTag.ShutterSpeedValue) is RationalIFDEntry shutterSpeedEntry)
+ {
+ item.ShutterSpeed = (double)shutterSpeedEntry.Value.Numerator / shutterSpeedEntry.Value.Denominator;
}
}
+ }
+ }
- if (file is TagLib.Image.File image)
- {
- item.CameraMake = image.ImageTag.Make;
- item.CameraModel = image.ImageTag.Model;
+ if (file is TagLib.Image.File image)
+ {
+ item.CameraMake = image.ImageTag.Make;
+ item.CameraModel = image.ImageTag.Model;
- item.Width = image.Properties.PhotoWidth;
- item.Height = image.Properties.PhotoHeight;
+ item.Width = image.Properties.PhotoWidth;
+ item.Height = image.Properties.PhotoHeight;
- var rating = image.ImageTag.Rating;
- item.CommunityRating = rating.HasValue ? rating : null;
+ item.CommunityRating = image.ImageTag.Rating;
- item.Overview = image.ImageTag.Comment;
+ item.Overview = image.ImageTag.Comment;
- if (!string.IsNullOrWhiteSpace(image.ImageTag.Title)
- && !item.LockedFields.Contains(MetadataField.Name))
- {
- item.Name = image.ImageTag.Title;
- }
+ if (!string.IsNullOrWhiteSpace(image.ImageTag.Title)
+ && !item.LockedFields.Contains(MetadataField.Name))
+ {
+ item.Name = image.ImageTag.Title;
+ }
- var dateTaken = image.ImageTag.DateTime;
- if (dateTaken.HasValue)
- {
- item.DateCreated = dateTaken.Value;
- item.PremiereDate = dateTaken.Value;
- item.ProductionYear = dateTaken.Value.Year;
- }
+ var dateTaken = image.ImageTag.DateTime;
+ if (dateTaken.HasValue)
+ {
+ item.DateCreated = dateTaken.Value;
+ item.PremiereDate = dateTaken.Value;
+ item.ProductionYear = dateTaken.Value.Year;
+ }
- item.Genres = image.ImageTag.Genres;
- item.Tags = image.ImageTag.Keywords;
- item.Software = image.ImageTag.Software;
+ item.Genres = image.ImageTag.Genres;
+ item.Tags = image.ImageTag.Keywords;
+ item.Software = image.ImageTag.Software;
- if (image.ImageTag.Orientation == TagLib.Image.ImageOrientation.None)
- {
- item.Orientation = null;
- }
- else if (Enum.TryParse(image.ImageTag.Orientation.ToString(), true, out ImageOrientation orientation))
- {
- item.Orientation = orientation;
- }
+ if (image.ImageTag.Orientation == TagLib.Image.ImageOrientation.None)
+ {
+ item.Orientation = null;
+ }
+ else if (Enum.TryParse(image.ImageTag.Orientation.ToString(), true, out ImageOrientation orientation))
+ {
+ item.Orientation = orientation;
+ }
- item.ExposureTime = image.ImageTag.ExposureTime;
- item.FocalLength = image.ImageTag.FocalLength;
+ item.ExposureTime = image.ImageTag.ExposureTime;
+ item.FocalLength = image.ImageTag.FocalLength;
- item.Latitude = image.ImageTag.Latitude;
- item.Longitude = image.ImageTag.Longitude;
- item.Altitude = image.ImageTag.Altitude;
+ item.Latitude = image.ImageTag.Latitude;
+ item.Longitude = image.ImageTag.Longitude;
+ item.Altitude = image.ImageTag.Altitude;
- if (image.ImageTag.ISOSpeedRatings.HasValue)
- {
- item.IsoSpeedRating = Convert.ToInt32(image.ImageTag.ISOSpeedRatings.Value);
- }
- else
- {
- item.IsoSpeedRating = null;
- }
- }
+ if (image.ImageTag.ISOSpeedRatings.HasValue)
+ {
+ item.IsoSpeedRating = Convert.ToInt32(image.ImageTag.ISOSpeedRatings.Value);
+ }
+ else
+ {
+ item.IsoSpeedRating = null;
}
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Image Provider - Error reading image tag for {0}", item.Path);
}
}
-
- if (item.Width <= 0 || item.Height <= 0)
+ catch (Exception ex)
{
- var img = item.GetImageInfo(ImageType.Primary, 0);
+ _logger.LogError(ex, "Image Provider - Error reading image tag for {0}", item.Path);
+ }
+ }
- try
- {
- var size = _imageProcessor.GetImageDimensions(item, img);
+ if (item.Width <= 0 || item.Height <= 0)
+ {
+ var img = item.GetImageInfo(ImageType.Primary, 0);
- if (size.Width > 0 && size.Height > 0)
- {
- item.Width = size.Width;
- item.Height = size.Height;
- }
- }
- catch (ArgumentException)
+ try
+ {
+ var size = _imageProcessor.GetImageDimensions(item, img);
+
+ if (size.Width > 0 && size.Height > 0)
{
- // format not supported
+ item.Width = size.Width;
+ item.Height = size.Height;
}
}
-
- const ItemUpdateType Result = ItemUpdateType.ImageUpdate | ItemUpdateType.MetadataImport;
- return Task.FromResult(Result);
+ catch (ArgumentException)
+ {
+ // format not supported
+ }
}
+
+ const ItemUpdateType Result = ItemUpdateType.ImageUpdate | ItemUpdateType.MetadataImport;
+ return Task.FromResult(Result);
}
}
diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs
index 745753440..acabbb059 100644
--- a/Emby.Server.Implementations/ApplicationHost.cs
+++ b/Emby.Server.Implementations/ApplicationHost.cs
@@ -146,7 +146,7 @@ namespace Emby.Server.Implementations
_startupConfig = startupConfig;
Logger = LoggerFactory.CreateLogger<ApplicationHost>();
- _deviceId = new DeviceId(ApplicationPaths, LoggerFactory);
+ _deviceId = new DeviceId(ApplicationPaths, LoggerFactory.CreateLogger<DeviceId>());
ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version;
ApplicationVersionString = ApplicationVersion.ToString(3);
diff --git a/Emby.Server.Implementations/Devices/DeviceId.cs b/Emby.Server.Implementations/Devices/DeviceId.cs
index b3f5549bc..2459178d8 100644
--- a/Emby.Server.Implementations/Devices/DeviceId.cs
+++ b/Emby.Server.Implementations/Devices/DeviceId.cs
@@ -1,5 +1,3 @@
-#nullable disable
-
#pragma warning disable CS1591
using System;
@@ -17,19 +15,19 @@ namespace Emby.Server.Implementations.Devices
private readonly ILogger<DeviceId> _logger;
private readonly object _syncLock = new object();
- private string _id;
+ private string? _id;
- public DeviceId(IApplicationPaths appPaths, ILoggerFactory loggerFactory)
+ public DeviceId(IApplicationPaths appPaths, ILogger<DeviceId> logger)
{
_appPaths = appPaths;
- _logger = loggerFactory.CreateLogger<DeviceId>();
+ _logger = logger;
}
- public string Value => _id ?? (_id = GetDeviceId());
+ public string Value => _id ??= GetDeviceId();
private string CachePath => Path.Combine(_appPaths.DataPath, "device.txt");
- private string GetCachedId()
+ private string? GetCachedId()
{
try
{
@@ -65,7 +63,7 @@ namespace Emby.Server.Implementations.Devices
{
var path = CachePath;
- Directory.CreateDirectory(Path.GetDirectoryName(path));
+ Directory.CreateDirectory(Path.GetDirectoryName(path) ?? throw new InvalidOperationException("Path can't be a root directory."));
lock (_syncLock)
{
diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs
index 13a381060..a2abafd2a 100644
--- a/Emby.Server.Implementations/Library/LibraryManager.cs
+++ b/Emby.Server.Implementations/Library/LibraryManager.cs
@@ -1860,7 +1860,7 @@ namespace Emby.Server.Implementations.Library
try
{
var index = item.GetImageIndex(img);
- image = await ConvertImageToLocal(item, img, index).ConfigureAwait(false);
+ image = await ConvertImageToLocal(item, img, index, removeOnFailure: true).ConfigureAwait(false);
}
catch (ArgumentException)
{
@@ -2787,7 +2787,7 @@ namespace Emby.Server.Implementations.Library
await SavePeopleMetadataAsync(people, cancellationToken).ConfigureAwait(false);
}
- public async Task<ItemImageInfo> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex)
+ public async Task<ItemImageInfo> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex, bool removeOnFailure)
{
foreach (var url in image.Path.Split('|'))
{
@@ -2806,6 +2806,7 @@ namespace Emby.Server.Implementations.Library
if (ex.StatusCode.HasValue
&& (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forbidden))
{
+ _logger.LogDebug(ex, "Error downloading image {Url}", url);
continue;
}
@@ -2813,11 +2814,14 @@ namespace Emby.Server.Implementations.Library
}
}
- // Remove this image to prevent it from retrying over and over
- item.RemoveImage(image);
- await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
+ if (removeOnFailure)
+ {
+ // Remove this image to prevent it from retrying over and over
+ item.RemoveImage(image);
+ await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
+ }
- throw new InvalidOperationException();
+ throw new InvalidOperationException("Unable to convert any images to local");
}
public async Task AddVirtualFolder(string name, CollectionTypeOptions? collectionType, LibraryOptions options, bool refreshLibrary)
diff --git a/Emby.Server.Implementations/Library/LiveStreamHelper.cs b/Emby.Server.Implementations/Library/LiveStreamHelper.cs
index d4aeae41a..0ebfe3ae7 100644
--- a/Emby.Server.Implementations/Library/LiveStreamHelper.cs
+++ b/Emby.Server.Implementations/Library/LiveStreamHelper.cs
@@ -1,5 +1,3 @@
-#nullable disable
-
#pragma warning disable CS1591
using System;
@@ -37,16 +35,16 @@ namespace Emby.Server.Implementations.Library
_appPaths = appPaths;
}
- public async Task AddMediaInfoWithProbe(MediaSourceInfo mediaSource, bool isAudio, string cacheKey, bool addProbeDelay, CancellationToken cancellationToken)
+ public async Task AddMediaInfoWithProbe(MediaSourceInfo mediaSource, bool isAudio, string? cacheKey, bool addProbeDelay, CancellationToken cancellationToken)
{
var originalRuntime = mediaSource.RunTimeTicks;
var now = DateTime.UtcNow;
- MediaInfo mediaInfo = null;
+ MediaInfo? mediaInfo = null;
var cacheFilePath = string.IsNullOrEmpty(cacheKey) ? null : Path.Combine(_appPaths.CachePath, "mediainfo", cacheKey.GetMD5().ToString("N", CultureInfo.InvariantCulture) + ".json");
- if (!string.IsNullOrEmpty(cacheKey))
+ if (cacheFilePath is not null)
{
try
{
@@ -91,7 +89,7 @@ namespace Emby.Server.Implementations.Library
if (cacheFilePath is not null)
{
- Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
+ Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath) ?? throw new InvalidOperationException("Path can't be a root directory."));
FileStream createStream = AsyncFile.OpenWrite(cacheFilePath);
await using (createStream.ConfigureAwait(false))
{
diff --git a/Emby.Server.Implementations/Library/MusicManager.cs b/Emby.Server.Implementations/Library/MusicManager.cs
index 078f4ad21..a69a0f33f 100644
--- a/Emby.Server.Implementations/Library/MusicManager.cs
+++ b/Emby.Server.Implementations/Library/MusicManager.cs
@@ -1,5 +1,3 @@
-#nullable disable
-
#pragma warning disable CS1591
using System;
@@ -13,7 +11,6 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
-using MediaBrowser.Model.Querying;
using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
namespace Emby.Server.Implementations.Library
@@ -27,33 +24,35 @@ namespace Emby.Server.Implementations.Library
_libraryManager = libraryManager;
}
- public List<BaseItem> GetInstantMixFromSong(Audio item, User user, DtoOptions dtoOptions)
+ public List<BaseItem> GetInstantMixFromSong(Audio item, User? user, DtoOptions dtoOptions)
{
- var list = new List<Audio>
+ var list = new List<BaseItem>
{
item
};
- return list.Concat(GetInstantMixFromGenres(item.Genres, user, dtoOptions)).ToList();
+ list.AddRange(GetInstantMixFromGenres(item.Genres, user, dtoOptions));
+
+ return list;
}
/// <inheritdoc />
- public List<BaseItem> GetInstantMixFromArtist(MusicArtist artist, User user, DtoOptions dtoOptions)
+ public List<BaseItem> GetInstantMixFromArtist(MusicArtist artist, User? user, DtoOptions dtoOptions)
{
return GetInstantMixFromGenres(artist.Genres, user, dtoOptions);
}
- public List<BaseItem> GetInstantMixFromAlbum(MusicAlbum item, User user, DtoOptions dtoOptions)
+ public List<BaseItem> GetInstantMixFromAlbum(MusicAlbum item, User? user, DtoOptions dtoOptions)
{
return GetInstantMixFromGenres(item.Genres, user, dtoOptions);
}
- public List<BaseItem> GetInstantMixFromFolder(Folder item, User user, DtoOptions dtoOptions)
+ public List<BaseItem> GetInstantMixFromFolder(Folder item, User? user, DtoOptions dtoOptions)
{
var genres = item
.GetRecursiveChildren(user, new InternalItemsQuery(user)
{
- IncludeItemTypes = new[] { BaseItemKind.Audio },
+ IncludeItemTypes = [BaseItemKind.Audio],
DtoOptions = dtoOptions
})
.Cast<Audio>()
@@ -64,12 +63,12 @@ namespace Emby.Server.Implementations.Library
return GetInstantMixFromGenres(genres, user, dtoOptions);
}
- public List<BaseItem> GetInstantMixFromPlaylist(Playlist item, User user, DtoOptions dtoOptions)
+ public List<BaseItem> GetInstantMixFromPlaylist(Playlist item, User? user, DtoOptions dtoOptions)
{
return GetInstantMixFromGenres(item.Genres, user, dtoOptions);
}
- public List<BaseItem> GetInstantMixFromGenres(IEnumerable<string> genres, User user, DtoOptions dtoOptions)
+ public List<BaseItem> GetInstantMixFromGenres(IEnumerable<string> genres, User? user, DtoOptions dtoOptions)
{
var genreIds = genres.DistinctNames().Select(i =>
{
@@ -86,27 +85,23 @@ namespace Emby.Server.Implementations.Library
return GetInstantMixFromGenreIds(genreIds, user, dtoOptions);
}
- public List<BaseItem> GetInstantMixFromGenreIds(Guid[] genreIds, User user, DtoOptions dtoOptions)
+ public List<BaseItem> GetInstantMixFromGenreIds(Guid[] genreIds, User? user, DtoOptions dtoOptions)
{
return _libraryManager.GetItemList(new InternalItemsQuery(user)
{
- IncludeItemTypes = new[] { BaseItemKind.Audio },
-
- GenreIds = genreIds.ToArray(),
-
+ IncludeItemTypes = [BaseItemKind.Audio],
+ GenreIds = genreIds,
Limit = 200,
-
- OrderBy = new[] { (ItemSortBy.Random, SortOrder.Ascending) },
-
+ OrderBy = [(ItemSortBy.Random, SortOrder.Ascending)],
DtoOptions = dtoOptions
});
}
- public List<BaseItem> GetInstantMixFromItem(BaseItem item, User user, DtoOptions dtoOptions)
+ public List<BaseItem> GetInstantMixFromItem(BaseItem item, User? user, DtoOptions dtoOptions)
{
if (item is MusicGenre)
{
- return GetInstantMixFromGenreIds(new[] { item.Id }, user, dtoOptions);
+ return GetInstantMixFromGenreIds([item.Id], user, dtoOptions);
}
if (item is Playlist playlist)
diff --git a/Emby.Server.Implementations/Library/SearchEngine.cs b/Emby.Server.Implementations/Library/SearchEngine.cs
index 020cb517d..7f3f8615e 100644
--- a/Emby.Server.Implementations/Library/SearchEngine.cs
+++ b/Emby.Server.Implementations/Library/SearchEngine.cs
@@ -1,5 +1,3 @@
-#nullable disable
-
#pragma warning disable CS1591
using System;
@@ -29,7 +27,7 @@ namespace Emby.Server.Implementations.Library
public QueryResult<SearchHintInfo> GetSearchHints(SearchQuery query)
{
- User user = null;
+ User? user = null;
if (!query.UserId.IsEmpty())
{
user = _userManager.GetUserById(query.UserId);
@@ -69,7 +67,7 @@ namespace Emby.Server.Implementations.Library
/// <param name="user">The user.</param>
/// <returns>IEnumerable{SearchHintResult}.</returns>
/// <exception cref="ArgumentException"><c>query.SearchTerm</c> is <c>null</c> or empty.</exception>
- private List<SearchHintInfo> GetSearchHints(SearchQuery query, User user)
+ private List<SearchHintInfo> GetSearchHints(SearchQuery query, User? user)
{
var searchTerm = query.SearchTerm;
@@ -78,7 +76,7 @@ namespace Emby.Server.Implementations.Library
searchTerm = searchTerm.Trim().RemoveDiacritics();
var excludeItemTypes = query.ExcludeItemTypes.ToList();
- var includeItemTypes = (query.IncludeItemTypes ?? Array.Empty<BaseItemKind>()).ToList();
+ var includeItemTypes = query.IncludeItemTypes.ToList();
excludeItemTypes.Add(BaseItemKind.Year);
excludeItemTypes.Add(BaseItemKind.Folder);
@@ -179,7 +177,7 @@ namespace Emby.Server.Implementations.Library
{
if (!searchQuery.ParentId.IsEmpty())
{
- searchQuery.AncestorIds = new[] { searchQuery.ParentId };
+ searchQuery.AncestorIds = [searchQuery.ParentId];
searchQuery.ParentId = Guid.Empty;
}
diff --git a/Emby.Server.Implementations/Localization/Core/fr.json b/Emby.Server.Implementations/Localization/Core/fr.json
index e0aff7954..9bbf1dc29 100644
--- a/Emby.Server.Implementations/Localization/Core/fr.json
+++ b/Emby.Server.Implementations/Localization/Core/fr.json
@@ -1,6 +1,6 @@
{
"Albums": "Albums",
- "AppDeviceValues": "Application : {0}, Appareil : {1}",
+ "AppDeviceValues": "Application: {0}, Appareil: {1}",
"Application": "Application",
"Artists": "Artistes",
"AuthenticationSucceededWithUserName": "{0} authentifié avec succès",
@@ -29,7 +29,7 @@
"Inherit": "Hériter",
"ItemAddedWithName": "{0} a été ajouté à la médiathèque",
"ItemRemovedWithName": "{0} a été supprimé de la médiathèque",
- "LabelIpAddressValue": "Adresse IP : {0}",
+ "LabelIpAddressValue": "Adresse IP: {0}",
"LabelRunningTimeValue": "Durée : {0}",
"Latest": "Derniers",
"MessageApplicationUpdated": "Le serveur Jellyfin a été mis à jour",
diff --git a/Emby.Server.Implementations/Localization/Core/hi.json b/Emby.Server.Implementations/Localization/Core/hi.json
index 3f4dea523..a28352219 100644
--- a/Emby.Server.Implementations/Localization/Core/hi.json
+++ b/Emby.Server.Implementations/Localization/Core/hi.json
@@ -4,27 +4,27 @@
"HeaderNextUp": "इसके बाद",
"HeaderLiveTV": "लाइव टीवी",
"HeaderFavoriteSongs": "पसंदीदा गीत",
- "HeaderFavoriteShows": "पसंदीदा शोज",
- "HeaderFavoriteEpisodes": "पसंदीदा एपिसोड्स",
- "HeaderFavoriteArtists": "पसंदीदा कलाकारसमूह",
+ "HeaderFavoriteShows": "पसंदीदा शो",
+ "HeaderFavoriteEpisodes": "पसंदीदा प्रकरण",
+ "HeaderFavoriteArtists": "पसंदीदा कलाकार",
"HeaderFavoriteAlbums": "पसंदीदा एलबम्स",
- "HeaderContinueWatching": "देखते रहिए",
+ "HeaderContinueWatching": "देखना जारी रखें",
"HeaderAlbumArtists": "एल्बम कलाकार",
- "Genres": "शैली",
+ "Genres": "शैलियां",
"Forced": "बलपूर्वक",
- "Folders": "फ़ोल्डरें",
+ "Folders": "फ़ोल्डर",
"Favorites": "पसंदीदा",
"FailedLoginAttemptWithUserName": "{0} से लॉगिन असफल हुआ",
- "DeviceOnlineWithName": "{0} से संयोग हो गया है",
- "DeviceOfflineWithName": "{0} से संयोग विच्छिन्न हो गया है",
+ "DeviceOnlineWithName": "{0} कनेक्ट हो गया है",
+ "DeviceOfflineWithName": "{0} डिस्कनेक्ट हो गया है",
"Default": "प्राथमिक",
- "Collections": "संग्रहों",
- "ChapterNameValue": "अध्याय",
+ "Collections": "संग्रह",
+ "ChapterNameValue": "अध्याय {0}",
"Channels": "चैनल",
- "CameraImageUploadedFrom": "{0} से एक नया कैमरावाला चित्र अपलोड किया गया है",
- "Books": "पुस्तकों",
- "AuthenticationSucceededWithUserName": "सफलता से प्रमाणीकृत",
- "Artists": "कलाकारों",
+ "CameraImageUploadedFrom": "{0} से एक नया कैमरा छवि अपलोड की गई है",
+ "Books": "पुस्तकें",
+ "AuthenticationSucceededWithUserName": "{0} सफलतापूर्वक प्रमाणित किया गया",
+ "Artists": "कलाकार",
"Application": "एप्लिकेशन",
"AppDeviceValues": "एप: {0}, उपकरण: {1}",
"NotificationOptionPluginUninstalled": "प्लगइन अनइंस्टाल हो गया",
diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs
index c031ce338..6b38fa7d3 100644
--- a/Jellyfin.Api/Controllers/ImageController.cs
+++ b/Jellyfin.Api/Controllers/ImageController.cs
@@ -11,8 +11,9 @@ using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Api.Attributes;
-using Jellyfin.Api.Constants;
+using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
+using Jellyfin.Extensions;
using MediaBrowser.Common.Api;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Configuration;
@@ -87,31 +88,26 @@ public class ImageController : BaseJellyfinApiController
/// Sets the user image.
/// </summary>
/// <param name="userId">User Id.</param>
- /// <param name="imageType">(Unused) Image type.</param>
- /// <param name="index">(Unused) Image index.</param>
/// <response code="204">Image updated.</response>
/// <response code="403">User does not have permission to delete the image.</response>
/// <returns>A <see cref="NoContentResult"/>.</returns>
- [HttpPost("Users/{userId}/Images/{imageType}")]
+ [HttpPost("UserImage")]
[Authorize]
[AcceptsImageFile]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
- [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "imageType", Justification = "Imported from ServiceStack")]
- [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")]
public async Task<ActionResult> PostUserImage(
- [FromRoute, Required] Guid userId,
- [FromRoute, Required] ImageType imageType,
- [FromQuery] int? index = null)
+ [FromQuery] Guid? userId)
{
- var user = _userManager.GetUserById(userId);
+ var requestUserId = RequestHelpers.GetUserId(User, userId);
+ var user = _userManager.GetUserById(requestUserId);
if (user is null)
{
return NotFound();
}
- if (!RequestHelpers.AssertCanUpdateUser(_userManager, HttpContext.User, userId, true))
+ if (!RequestHelpers.AssertCanUpdateUser(_userManager, HttpContext.User, requestUserId, true))
{
return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the image.");
}
@@ -148,87 +144,69 @@ public class ImageController : BaseJellyfinApiController
/// </summary>
/// <param name="userId">User Id.</param>
/// <param name="imageType">(Unused) Image type.</param>
+ /// <response code="204">Image updated.</response>
+ /// <response code="403">User does not have permission to delete the image.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Users/{userId}/Images/{imageType}")]
+ [Authorize]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ [AcceptsImageFile]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "imageType", Justification = "Imported from ServiceStack")]
+ public Task<ActionResult> PostUserImageLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] ImageType imageType)
+ => PostUserImage(userId);
+
+ /// <summary>
+ /// Sets the user image.
+ /// </summary>
+ /// <param name="userId">User Id.</param>
+ /// <param name="imageType">(Unused) Image type.</param>
/// <param name="index">(Unused) Image index.</param>
/// <response code="204">Image updated.</response>
/// <response code="403">User does not have permission to delete the image.</response>
/// <returns>A <see cref="NoContentResult"/>.</returns>
[HttpPost("Users/{userId}/Images/{imageType}/{index}")]
[Authorize]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
[AcceptsImageFile]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "imageType", Justification = "Imported from ServiceStack")]
[SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")]
- public async Task<ActionResult> PostUserImageByIndex(
+ public Task<ActionResult> PostUserImageByIndexLegacy(
[FromRoute, Required] Guid userId,
[FromRoute, Required] ImageType imageType,
[FromRoute] int index)
- {
- var user = _userManager.GetUserById(userId);
- if (user is null)
- {
- return NotFound();
- }
-
- if (!RequestHelpers.AssertCanUpdateUser(_userManager, HttpContext.User, userId, true))
- {
- return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the image.");
- }
-
- if (!TryGetImageExtensionFromContentType(Request.ContentType, out string? extension))
- {
- return BadRequest("Incorrect ContentType.");
- }
-
- var stream = GetFromBase64Stream(Request.Body);
- await using (stream.ConfigureAwait(false))
- {
- // Handle image/png; charset=utf-8
- var mimeType = Request.ContentType?.Split(';').FirstOrDefault();
- var userDataPath = Path.Combine(_serverConfigurationManager.ApplicationPaths.UserConfigurationDirectoryPath, user.Username);
- if (user.ProfileImage is not null)
- {
- await _userManager.ClearProfileImageAsync(user).ConfigureAwait(false);
- }
-
- user.ProfileImage = new Data.Entities.ImageInfo(Path.Combine(userDataPath, "profile" + extension));
-
- await _providerManager
- .SaveImage(stream, mimeType, user.ProfileImage.Path)
- .ConfigureAwait(false);
- await _userManager.UpdateUserAsync(user).ConfigureAwait(false);
-
- return NoContent();
- }
- }
+ => PostUserImage(userId);
/// <summary>
/// Delete the user's image.
/// </summary>
/// <param name="userId">User Id.</param>
- /// <param name="imageType">(Unused) Image type.</param>
- /// <param name="index">(Unused) Image index.</param>
/// <response code="204">Image deleted.</response>
/// <response code="403">User does not have permission to delete the image.</response>
/// <returns>A <see cref="NoContentResult"/>.</returns>
- [HttpDelete("Users/{userId}/Images/{imageType}")]
+ [HttpDelete("UserImage")]
[Authorize]
- [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "imageType", Justification = "Imported from ServiceStack")]
- [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<ActionResult> DeleteUserImage(
- [FromRoute, Required] Guid userId,
- [FromRoute, Required] ImageType imageType,
- [FromQuery] int? index = null)
+ [FromQuery] Guid? userId)
{
- if (!RequestHelpers.AssertCanUpdateUser(_userManager, HttpContext.User, userId, true))
+ var requestUserId = RequestHelpers.GetUserId(User, userId);
+ if (!RequestHelpers.AssertCanUpdateUser(_userManager, HttpContext.User, requestUserId, true))
{
return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to delete the image.");
}
- var user = _userManager.GetUserById(userId);
+ var user = _userManager.GetUserById(requestUserId);
if (user?.ProfileImage is null)
{
return NoContent();
@@ -256,40 +234,42 @@ public class ImageController : BaseJellyfinApiController
/// <response code="204">Image deleted.</response>
/// <response code="403">User does not have permission to delete the image.</response>
/// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpDelete("Users/{userId}/Images/{imageType}")]
+ [Authorize]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "imageType", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ public Task<ActionResult> DeleteUserImageLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] ImageType imageType,
+ [FromQuery] int? index = null)
+ => DeleteUserImage(userId);
+
+ /// <summary>
+ /// Delete the user's image.
+ /// </summary>
+ /// <param name="userId">User Id.</param>
+ /// <param name="imageType">(Unused) Image type.</param>
+ /// <param name="index">(Unused) Image index.</param>
+ /// <response code="204">Image deleted.</response>
+ /// <response code="403">User does not have permission to delete the image.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
[HttpDelete("Users/{userId}/Images/{imageType}/{index}")]
[Authorize]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
[SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "imageType", Justification = "Imported from ServiceStack")]
[SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
- public async Task<ActionResult> DeleteUserImageByIndex(
+ public Task<ActionResult> DeleteUserImageByIndexLegacy(
[FromRoute, Required] Guid userId,
[FromRoute, Required] ImageType imageType,
[FromRoute] int index)
- {
- if (!RequestHelpers.AssertCanUpdateUser(_userManager, HttpContext.User, userId, true))
- {
- return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to delete the image.");
- }
-
- var user = _userManager.GetUserById(userId);
- if (user?.ProfileImage is null)
- {
- return NoContent();
- }
-
- try
- {
- System.IO.File.Delete(user.ProfileImage.Path);
- }
- catch (IOException e)
- {
- _logger.LogError(e, "Error deleting user profile image:");
- }
-
- await _userManager.ClearProfileImageAsync(user).ConfigureAwait(false);
- return NoContent();
- }
+ => DeleteUserImage(userId);
/// <summary>
/// Delete an item's image.
@@ -542,7 +522,6 @@ public class ImageController : BaseJellyfinApiController
/// <param name="fillWidth">Width of box to fill.</param>
/// <param name="fillHeight">Height of box to fill.</param>
/// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
- /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
/// <param name="format">Optional. The <see cref="ImageFormat"/> of the returned image.</param>
/// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param>
/// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param>
@@ -572,7 +551,6 @@ public class ImageController : BaseJellyfinApiController
[FromQuery] int? fillWidth,
[FromQuery] int? fillHeight,
[FromQuery] string? tag,
- [FromQuery, ParameterObsolete] bool? cropWhitespace,
[FromQuery] ImageFormat? format,
[FromQuery] double? percentPlayed,
[FromQuery] int? unplayedCount,
@@ -623,7 +601,6 @@ public class ImageController : BaseJellyfinApiController
/// <param name="fillWidth">Width of box to fill.</param>
/// <param name="fillHeight">Height of box to fill.</param>
/// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
- /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
/// <param name="format">Optional. The <see cref="ImageFormat"/> of the returned image.</param>
/// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param>
/// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param>
@@ -653,7 +630,6 @@ public class ImageController : BaseJellyfinApiController
[FromQuery] int? fillWidth,
[FromQuery] int? fillHeight,
[FromQuery] string? tag,
- [FromQuery, ParameterObsolete] bool? cropWhitespace,
[FromQuery] ImageFormat? format,
[FromQuery] double? percentPlayed,
[FromQuery] int? unplayedCount,
@@ -702,7 +678,6 @@ public class ImageController : BaseJellyfinApiController
/// <param name="fillWidth">Width of box to fill.</param>
/// <param name="fillHeight">Height of box to fill.</param>
/// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
- /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
/// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param>
/// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param>
/// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param>
@@ -732,7 +707,6 @@ public class ImageController : BaseJellyfinApiController
[FromQuery] int? fillWidth,
[FromQuery] int? fillHeight,
[FromRoute, Required] string tag,
- [FromQuery, ParameterObsolete] bool? cropWhitespace,
[FromRoute, Required] ImageFormat format,
[FromRoute, Required] double percentPlayed,
[FromRoute, Required] int unplayedCount,
@@ -785,7 +759,6 @@ public class ImageController : BaseJellyfinApiController
/// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
/// <param name="fillWidth">Width of box to fill.</param>
/// <param name="fillHeight">Height of box to fill.</param>
- /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
/// <param name="blur">Optional. Blur image.</param>
/// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
/// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
@@ -815,7 +788,6 @@ public class ImageController : BaseJellyfinApiController
[FromQuery] int? quality,
[FromQuery] int? fillWidth,
[FromQuery] int? fillHeight,
- [FromQuery, ParameterObsolete] bool? cropWhitespace,
[FromQuery] int? blur,
[FromQuery] string? backgroundColor,
[FromQuery] string? foregroundLayer,
@@ -865,7 +837,6 @@ public class ImageController : BaseJellyfinApiController
/// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
/// <param name="fillWidth">Width of box to fill.</param>
/// <param name="fillHeight">Height of box to fill.</param>
- /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
/// <param name="blur">Optional. Blur image.</param>
/// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
/// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
@@ -895,7 +866,6 @@ public class ImageController : BaseJellyfinApiController
[FromQuery] int? quality,
[FromQuery] int? fillWidth,
[FromQuery] int? fillHeight,
- [FromQuery, ParameterObsolete] bool? cropWhitespace,
[FromQuery] int? blur,
[FromQuery] string? backgroundColor,
[FromQuery] string? foregroundLayer,
@@ -946,7 +916,6 @@ public class ImageController : BaseJellyfinApiController
/// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
/// <param name="fillWidth">Width of box to fill.</param>
/// <param name="fillHeight">Height of box to fill.</param>
- /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
/// <param name="blur">Optional. Blur image.</param>
/// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
/// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
@@ -976,7 +945,6 @@ public class ImageController : BaseJellyfinApiController
[FromQuery] int? quality,
[FromQuery] int? fillWidth,
[FromQuery] int? fillHeight,
- [FromQuery, ParameterObsolete] bool? cropWhitespace,
[FromQuery] int? blur,
[FromQuery] string? backgroundColor,
[FromQuery] string? foregroundLayer)
@@ -1025,7 +993,6 @@ public class ImageController : BaseJellyfinApiController
/// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
/// <param name="fillWidth">Width of box to fill.</param>
/// <param name="fillHeight">Height of box to fill.</param>
- /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
/// <param name="blur">Optional. Blur image.</param>
/// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
/// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
@@ -1055,7 +1022,6 @@ public class ImageController : BaseJellyfinApiController
[FromQuery] int? quality,
[FromQuery] int? fillWidth,
[FromQuery] int? fillHeight,
- [FromQuery, ParameterObsolete] bool? cropWhitespace,
[FromQuery] int? blur,
[FromQuery] string? backgroundColor,
[FromQuery] string? foregroundLayer,
@@ -1106,7 +1072,6 @@ public class ImageController : BaseJellyfinApiController
/// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
/// <param name="fillWidth">Width of box to fill.</param>
/// <param name="fillHeight">Height of box to fill.</param>
- /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
/// <param name="blur">Optional. Blur image.</param>
/// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
/// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
@@ -1136,7 +1101,6 @@ public class ImageController : BaseJellyfinApiController
[FromQuery] int? quality,
[FromQuery] int? fillWidth,
[FromQuery] int? fillHeight,
- [FromQuery, ParameterObsolete] bool? cropWhitespace,
[FromQuery] int? blur,
[FromQuery] string? backgroundColor,
[FromQuery] string? foregroundLayer)
@@ -1185,7 +1149,6 @@ public class ImageController : BaseJellyfinApiController
/// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
/// <param name="fillWidth">Width of box to fill.</param>
/// <param name="fillHeight">Height of box to fill.</param>
- /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
/// <param name="blur">Optional. Blur image.</param>
/// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
/// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
@@ -1215,7 +1178,6 @@ public class ImageController : BaseJellyfinApiController
[FromQuery] int? quality,
[FromQuery] int? fillWidth,
[FromQuery] int? fillHeight,
- [FromQuery, ParameterObsolete] bool? cropWhitespace,
[FromQuery] int? blur,
[FromQuery] string? backgroundColor,
[FromQuery] string? foregroundLayer,
@@ -1266,7 +1228,6 @@ public class ImageController : BaseJellyfinApiController
/// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
/// <param name="fillWidth">Width of box to fill.</param>
/// <param name="fillHeight">Height of box to fill.</param>
- /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
/// <param name="blur">Optional. Blur image.</param>
/// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
/// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
@@ -1296,7 +1257,6 @@ public class ImageController : BaseJellyfinApiController
[FromQuery] int? quality,
[FromQuery] int? fillWidth,
[FromQuery] int? fillHeight,
- [FromQuery, ParameterObsolete] bool? cropWhitespace,
[FromQuery] int? blur,
[FromQuery] string? backgroundColor,
[FromQuery] string? foregroundLayer)
@@ -1345,7 +1305,6 @@ public class ImageController : BaseJellyfinApiController
/// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
/// <param name="fillWidth">Width of box to fill.</param>
/// <param name="fillHeight">Height of box to fill.</param>
- /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
/// <param name="blur">Optional. Blur image.</param>
/// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
/// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
@@ -1375,7 +1334,6 @@ public class ImageController : BaseJellyfinApiController
[FromQuery] int? quality,
[FromQuery] int? fillWidth,
[FromQuery] int? fillHeight,
- [FromQuery, ParameterObsolete] bool? cropWhitespace,
[FromQuery] int? blur,
[FromQuery] string? backgroundColor,
[FromQuery] string? foregroundLayer,
@@ -1426,7 +1384,6 @@ public class ImageController : BaseJellyfinApiController
/// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
/// <param name="fillWidth">Width of box to fill.</param>
/// <param name="fillHeight">Height of box to fill.</param>
- /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
/// <param name="blur">Optional. Blur image.</param>
/// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
/// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
@@ -1456,7 +1413,6 @@ public class ImageController : BaseJellyfinApiController
[FromQuery] int? quality,
[FromQuery] int? fillWidth,
[FromQuery] int? fillHeight,
- [FromQuery, ParameterObsolete] bool? cropWhitespace,
[FromQuery] int? blur,
[FromQuery] string? backgroundColor,
[FromQuery] string? foregroundLayer)
@@ -1493,7 +1449,6 @@ public class ImageController : BaseJellyfinApiController
/// Get user profile image.
/// </summary>
/// <param name="userId">User id.</param>
- /// <param name="imageType">Image type.</param>
/// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
/// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param>
/// <param name="maxWidth">The maximum image width to return.</param>
@@ -1505,25 +1460,25 @@ public class ImageController : BaseJellyfinApiController
/// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
/// <param name="fillWidth">Width of box to fill.</param>
/// <param name="fillHeight">Height of box to fill.</param>
- /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
/// <param name="blur">Optional. Blur image.</param>
/// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
/// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
/// <param name="imageIndex">Image index.</param>
/// <response code="200">Image stream returned.</response>
+ /// <response code="400">User id not provided.</response>
/// <response code="404">Item not found.</response>
/// <returns>
/// A <see cref="FileStreamResult"/> containing the file stream on success,
/// or a <see cref="NotFoundResult"/> if item not found.
/// </returns>
- [HttpGet("Users/{userId}/Images/{imageType}")]
- [HttpHead("Users/{userId}/Images/{imageType}", Name = "HeadUserImage")]
+ [HttpGet("UserImage")]
+ [HttpHead("UserImage", Name = "HeadUserImage")]
[ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesImageFile]
public async Task<ActionResult> GetUserImage(
- [FromRoute, Required] Guid userId,
- [FromRoute, Required] ImageType imageType,
+ [FromQuery] Guid? userId,
[FromQuery] string? tag,
[FromQuery] ImageFormat? format,
[FromQuery] int? maxWidth,
@@ -1535,13 +1490,18 @@ public class ImageController : BaseJellyfinApiController
[FromQuery] int? quality,
[FromQuery] int? fillWidth,
[FromQuery] int? fillHeight,
- [FromQuery, ParameterObsolete] bool? cropWhitespace,
[FromQuery] int? blur,
[FromQuery] string? backgroundColor,
[FromQuery] string? foregroundLayer,
[FromQuery] int? imageIndex)
{
- var user = _userManager.GetUserById(userId);
+ var requestUserId = userId ?? User.GetUserId();
+ if (requestUserId.IsEmpty())
+ {
+ return BadRequest("UserId is required if unauthenticated");
+ }
+
+ var user = _userManager.GetUserById(requestUserId);
if (user?.ProfileImage is null)
{
return NotFound();
@@ -1566,7 +1526,7 @@ public class ImageController : BaseJellyfinApiController
return await GetImageInternal(
user.Id,
- imageType,
+ ImageType.Profile,
imageIndex,
tag,
format,
@@ -1592,6 +1552,75 @@ public class ImageController : BaseJellyfinApiController
/// </summary>
/// <param name="userId">User id.</param>
/// <param name="imageType">Image type.</param>
+ /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
+ /// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param>
+ /// <param name="maxWidth">The maximum image width to return.</param>
+ /// <param name="maxHeight">The maximum image height to return.</param>
+ /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param>
+ /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param>
+ /// <param name="width">The fixed image width to return.</param>
+ /// <param name="height">The fixed image height to return.</param>
+ /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
+ /// <param name="fillWidth">Width of box to fill.</param>
+ /// <param name="fillHeight">Height of box to fill.</param>
+ /// <param name="blur">Optional. Blur image.</param>
+ /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
+ /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
+ /// <param name="imageIndex">Image index.</param>
+ /// <response code="200">Image stream returned.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>
+ /// A <see cref="FileStreamResult"/> containing the file stream on success,
+ /// or a <see cref="NotFoundResult"/> if item not found.
+ /// </returns>
+ [HttpGet("Users/{userId}/Images/{imageType}")]
+ [HttpHead("Users/{userId}/Images/{imageType}", Name = "HeadUserImageLegacy")]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ProducesImageFile]
+ public Task<ActionResult> GetUserImageLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] ImageType imageType,
+ [FromQuery] string? tag,
+ [FromQuery] ImageFormat? format,
+ [FromQuery] int? maxWidth,
+ [FromQuery] int? maxHeight,
+ [FromQuery] double? percentPlayed,
+ [FromQuery] int? unplayedCount,
+ [FromQuery] int? width,
+ [FromQuery] int? height,
+ [FromQuery] int? quality,
+ [FromQuery] int? fillWidth,
+ [FromQuery] int? fillHeight,
+ [FromQuery] int? blur,
+ [FromQuery] string? backgroundColor,
+ [FromQuery] string? foregroundLayer,
+ [FromQuery] int? imageIndex)
+ => GetUserImage(
+ userId,
+ tag,
+ format,
+ maxWidth,
+ maxHeight,
+ percentPlayed,
+ unplayedCount,
+ width,
+ height,
+ quality,
+ fillWidth,
+ fillHeight,
+ blur,
+ backgroundColor,
+ foregroundLayer,
+ imageIndex);
+
+ /// <summary>
+ /// Get user profile image.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="imageType">Image type.</param>
/// <param name="imageIndex">Image index.</param>
/// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param>
/// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param>
@@ -1604,7 +1633,6 @@ public class ImageController : BaseJellyfinApiController
/// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param>
/// <param name="fillWidth">Width of box to fill.</param>
/// <param name="fillHeight">Height of box to fill.</param>
- /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param>
/// <param name="blur">Optional. Blur image.</param>
/// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param>
/// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param>
@@ -1615,11 +1643,13 @@ public class ImageController : BaseJellyfinApiController
/// or a <see cref="NotFoundResult"/> if item not found.
/// </returns>
[HttpGet("Users/{userId}/Images/{imageType}/{imageIndex}")]
- [HttpHead("Users/{userId}/Images/{imageType}/{imageIndex}", Name = "HeadUserImageByIndex")]
+ [HttpHead("Users/{userId}/Images/{imageType}/{imageIndex}", Name = "HeadUserImageByIndexLegacy")]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesImageFile]
- public async Task<ActionResult> GetUserImageByIndex(
+ public Task<ActionResult> GetUserImageByIndexLegacy(
[FromRoute, Required] Guid userId,
[FromRoute, Required] ImageType imageType,
[FromRoute, Required] int imageIndex,
@@ -1634,56 +1664,26 @@ public class ImageController : BaseJellyfinApiController
[FromQuery] int? quality,
[FromQuery] int? fillWidth,
[FromQuery] int? fillHeight,
- [FromQuery, ParameterObsolete] bool? cropWhitespace,
[FromQuery] int? blur,
[FromQuery] string? backgroundColor,
[FromQuery] string? foregroundLayer)
- {
- var user = _userManager.GetUserById(userId);
- if (user?.ProfileImage is null)
- {
- return NotFound();
- }
-
- var info = new ItemImageInfo
- {
- Path = user.ProfileImage.Path,
- Type = ImageType.Profile,
- DateModified = user.ProfileImage.LastModified
- };
-
- if (width.HasValue)
- {
- info.Width = width.Value;
- }
-
- if (height.HasValue)
- {
- info.Height = height.Value;
- }
-
- return await GetImageInternal(
- user.Id,
- imageType,
- imageIndex,
- tag,
- format,
- maxWidth,
- maxHeight,
- percentPlayed,
- unplayedCount,
- width,
- height,
- quality,
- fillWidth,
- fillHeight,
- blur,
- backgroundColor,
- foregroundLayer,
- null,
- info)
- .ConfigureAwait(false);
- }
+ => GetUserImage(
+ userId,
+ tag,
+ format,
+ maxWidth,
+ maxHeight,
+ percentPlayed,
+ unplayedCount,
+ width,
+ height,
+ quality,
+ fillWidth,
+ fillHeight,
+ blur,
+ backgroundColor,
+ foregroundLayer,
+ imageIndex);
/// <summary>
/// Generates or gets the splashscreen.
@@ -1993,7 +1993,7 @@ public class ImageController : BaseJellyfinApiController
{
if (format.HasValue)
{
- return new[] { format.Value };
+ return [format.Value];
}
return GetClientSupportedFormats();
diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs
index d10fba920..26ae1a820 100644
--- a/Jellyfin.Api/Controllers/ItemsController.cs
+++ b/Jellyfin.Api/Controllers/ItemsController.cs
@@ -612,8 +612,10 @@ public class ItemsController : BaseJellyfinApiController
/// <param name="enableImages">Optional, include image information in output.</param>
/// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items.</returns>
[HttpGet("Users/{userId}/Items")]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
[ProducesResponseType(StatusCodes.Status200OK)]
- public ActionResult<QueryResult<BaseItemDto>> GetItemsByUserId(
+ public ActionResult<QueryResult<BaseItemDto>> GetItemsByUserIdLegacy(
[FromRoute] Guid userId,
[FromQuery] string? maxOfficialRating,
[FromQuery] bool? hasThemeSong,
@@ -699,8 +701,7 @@ public class ItemsController : BaseJellyfinApiController
[FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds,
[FromQuery] bool enableTotalRecordCount = true,
[FromQuery] bool? enableImages = true)
- {
- return GetItems(
+ => GetItems(
userId,
maxOfficialRating,
hasThemeSong,
@@ -786,7 +787,6 @@ public class ItemsController : BaseJellyfinApiController
genreIds,
enableTotalRecordCount,
enableImages);
- }
/// <summary>
/// Gets items based on a query.
@@ -808,10 +808,10 @@ public class ItemsController : BaseJellyfinApiController
/// <param name="excludeActiveSessions">Optional. Whether to exclude the currently active sessions.</param>
/// <response code="200">Items returned.</response>
/// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items that are resumable.</returns>
- [HttpGet("Users/{userId}/Items/Resume")]
+ [HttpGet("UserItems/Resume")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<QueryResult<BaseItemDto>> GetResumeItems(
- [FromRoute, Required] Guid userId,
+ [FromQuery] Guid? userId,
[FromQuery] int? startIndex,
[FromQuery] int? limit,
[FromQuery] string? searchTerm,
@@ -827,7 +827,8 @@ public class ItemsController : BaseJellyfinApiController
[FromQuery] bool? enableImages = true,
[FromQuery] bool excludeActiveSessions = false)
{
- var user = _userManager.GetUserById(userId);
+ var requestUserId = RequestHelpers.GetUserId(User, userId);
+ var user = _userManager.GetUserById(requestUserId);
if (user is null)
{
return NotFound();
@@ -854,7 +855,7 @@ public class ItemsController : BaseJellyfinApiController
if (excludeActiveSessions)
{
excludeItemIds = _sessionManager.Sessions
- .Where(s => s.UserId.Equals(userId) && s.NowPlayingItem is not null)
+ .Where(s => s.UserId.Equals(requestUserId) && s.NowPlayingItem is not null)
.Select(s => s.NowPlayingItem.Id)
.ToArray();
}
@@ -888,6 +889,63 @@ public class ItemsController : BaseJellyfinApiController
}
/// <summary>
+ /// Gets items based on a query.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="startIndex">The start index.</param>
+ /// <param name="limit">The item limit.</param>
+ /// <param name="searchTerm">The search term.</param>
+ /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param>
+ /// <param name="mediaTypes">Optional. Filter by MediaType. Allows multiple, comma delimited.</param>
+ /// <param name="enableUserData">Optional. Include user data.</param>
+ /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimited.</param>
+ /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param>
+ /// <param name="enableImages">Optional. Include image information in output.</param>
+ /// <param name="excludeActiveSessions">Optional. Whether to exclude the currently active sessions.</param>
+ /// <response code="200">Items returned.</response>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items that are resumable.</returns>
+ [HttpGet("Users/{userId}/Items/Resume")]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult<QueryResult<BaseItemDto>> GetResumeItemsLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] string? searchTerm,
+ [FromQuery] Guid? parentId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] MediaType[] mediaTypes,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
+ [FromQuery] bool enableTotalRecordCount = true,
+ [FromQuery] bool? enableImages = true,
+ [FromQuery] bool excludeActiveSessions = false)
+ => GetResumeItems(
+ userId,
+ startIndex,
+ limit,
+ searchTerm,
+ parentId,
+ fields,
+ mediaTypes,
+ enableUserData,
+ imageTypeLimit,
+ enableImageTypes,
+ excludeItemTypes,
+ includeItemTypes,
+ enableTotalRecordCount,
+ enableImages,
+ excludeActiveSessions);
+
+ /// <summary>
/// Get Item User Data.
/// </summary>
/// <param name="userId">The user id.</param>
@@ -895,25 +953,44 @@ public class ItemsController : BaseJellyfinApiController
/// <response code="200">return item user data.</response>
/// <response code="404">Item is not found.</response>
/// <returns>Return <see cref="UserItemDataDto"/>.</returns>
- [HttpGet("Users/{userId}/Items/{itemId}/UserData")]
+ [HttpGet("UserItems/{itemId}/UserData")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<UserItemDataDto> GetItemUserData(
- [FromRoute, Required] Guid userId,
+ [FromQuery] Guid? userId,
[FromRoute, Required] Guid itemId)
{
- if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, userId, true))
+ var requestUserId = RequestHelpers.GetUserId(User, userId);
+ if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, requestUserId, true))
{
return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to view this item user data.");
}
- var user = _userManager.GetUserById(userId) ?? throw new ResourceNotFoundException();
+ var user = _userManager.GetUserById(requestUserId) ?? throw new ResourceNotFoundException();
var item = _libraryManager.GetItemById(itemId);
return (item == null) ? NotFound() : _userDataRepository.GetUserDataDto(item, user);
}
/// <summary>
+ /// Get Item User Data.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="itemId">The item id.</param>
+ /// <response code="200">return item user data.</response>
+ /// <response code="404">Item is not found.</response>
+ /// <returns>Return <see cref="UserItemDataDto"/>.</returns>
+ [HttpGet("Users/{userId}/Items/{itemId}/UserData")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public ActionResult<UserItemDataDto> GetItemUserDataLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId)
+ => GetItemUserData(userId, itemId);
+
+ /// <summary>
/// Update Item User Data.
/// </summary>
/// <param name="userId">The user id.</param>
@@ -922,20 +999,21 @@ public class ItemsController : BaseJellyfinApiController
/// <response code="200">return updated user item data.</response>
/// <response code="404">Item is not found.</response>
/// <returns>Return <see cref="UserItemDataDto"/>.</returns>
- [HttpPost("Users/{userId}/Items/{itemId}/UserData")]
+ [HttpPost("UserItems/{itemId}/UserData")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<UserItemDataDto> UpdateItemUserData(
- [FromRoute, Required] Guid userId,
+ [FromQuery] Guid? userId,
[FromRoute, Required] Guid itemId,
[FromBody, Required] UpdateUserItemDataDto userDataDto)
{
- if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, userId, true))
+ var requestUserId = RequestHelpers.GetUserId(User, userId);
+ if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, requestUserId, true))
{
return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update this item user data.");
}
- var user = _userManager.GetUserById(userId) ?? throw new ResourceNotFoundException();
+ var user = _userManager.GetUserById(requestUserId) ?? throw new ResourceNotFoundException();
var item = _libraryManager.GetItemById(itemId);
if (item == null)
{
@@ -946,4 +1024,24 @@ public class ItemsController : BaseJellyfinApiController
return _userDataRepository.GetUserDataDto(item, user);
}
+
+ /// <summary>
+ /// Update Item User Data.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="itemId">The item id.</param>
+ /// <param name="userDataDto">New user data object.</param>
+ /// <response code="200">return updated user item data.</response>
+ /// <response code="404">Item is not found.</response>
+ /// <returns>Return <see cref="UserItemDataDto"/>.</returns>
+ [HttpPost("Users/{userId}/Items/{itemId}/UserData")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public ActionResult<UserItemDataDto> UpdateItemUserDataLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId,
+ [FromBody, Required] UpdateUserItemDataDto userDataDto)
+ => UpdateItemUserData(userId, itemId, userDataDto);
}
diff --git a/Jellyfin.Api/Controllers/LyricsController.cs b/Jellyfin.Api/Controllers/LyricsController.cs
index 4fccf2cb4..f2b312b47 100644
--- a/Jellyfin.Api/Controllers/LyricsController.cs
+++ b/Jellyfin.Api/Controllers/LyricsController.cs
@@ -146,13 +146,11 @@ public class LyricsController : BaseJellyfinApiController
await using (stream.ConfigureAwait(false))
{
await Request.Body.CopyToAsync(stream).ConfigureAwait(false);
- var uploadedLyric = await _lyricManager.UploadLyricAsync(
- audio,
- new LyricResponse
- {
- Format = format,
- Stream = stream
- }).ConfigureAwait(false);
+ var uploadedLyric = await _lyricManager.SaveLyricAsync(
+ audio,
+ format,
+ stream)
+ .ConfigureAwait(false);
if (uploadedLyric is null)
{
diff --git a/Jellyfin.Api/Controllers/PlaystateController.cs b/Jellyfin.Api/Controllers/PlaystateController.cs
index bde2f4d1a..949d101dc 100644
--- a/Jellyfin.Api/Controllers/PlaystateController.cs
+++ b/Jellyfin.Api/Controllers/PlaystateController.cs
@@ -68,15 +68,16 @@ public class PlaystateController : BaseJellyfinApiController
/// <response code="200">Item marked as played.</response>
/// <response code="404">Item not found.</response>
/// <returns>An <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>, or a <see cref="NotFoundResult"/> if item was not found.</returns>
- [HttpPost("Users/{userId}/PlayedItems/{itemId}")]
+ [HttpPost("UserPlayedItems/{itemId}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<UserItemDataDto>> MarkPlayedItem(
- [FromRoute, Required] Guid userId,
+ [FromQuery] Guid? userId,
[FromRoute, Required] Guid itemId,
[FromQuery, ModelBinder(typeof(LegacyDateTimeModelBinder))] DateTime? datePlayed)
{
- var user = _userManager.GetUserById(userId);
+ var requestUserId = RequestHelpers.GetUserId(User, userId);
+ var user = _userManager.GetUserById(requestUserId);
if (user is null)
{
return NotFound();
@@ -106,6 +107,26 @@ public class PlaystateController : BaseJellyfinApiController
}
/// <summary>
+ /// Marks an item as played for user.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="datePlayed">Optional. The date the item was played.</param>
+ /// <response code="200">Item marked as played.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>An <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>, or a <see cref="NotFoundResult"/> if item was not found.</returns>
+ [HttpPost("Users/{userId}/PlayedItems/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public Task<ActionResult<UserItemDataDto>> MarkPlayedItemLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId,
+ [FromQuery, ModelBinder(typeof(LegacyDateTimeModelBinder))] DateTime? datePlayed)
+ => MarkPlayedItem(userId, itemId, datePlayed);
+
+ /// <summary>
/// Marks an item as unplayed for user.
/// </summary>
/// <param name="userId">User id.</param>
@@ -113,12 +134,15 @@ public class PlaystateController : BaseJellyfinApiController
/// <response code="200">Item marked as unplayed.</response>
/// <response code="404">Item not found.</response>
/// <returns>A <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>, or a <see cref="NotFoundResult"/> if item was not found.</returns>
- [HttpDelete("Users/{userId}/PlayedItems/{itemId}")]
+ [HttpDelete("UserPlayedItems/{itemId}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
- public async Task<ActionResult<UserItemDataDto>> MarkUnplayedItem([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId)
+ public async Task<ActionResult<UserItemDataDto>> MarkUnplayedItem(
+ [FromQuery] Guid? userId,
+ [FromRoute, Required] Guid itemId)
{
- var user = _userManager.GetUserById(userId);
+ var requestUserId = RequestHelpers.GetUserId(User, userId);
+ var user = _userManager.GetUserById(requestUserId);
if (user is null)
{
return NotFound();
@@ -148,6 +172,24 @@ public class PlaystateController : BaseJellyfinApiController
}
/// <summary>
+ /// Marks an item as unplayed for user.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <response code="200">Item marked as unplayed.</response>
+ /// <response code="404">Item not found.</response>
+ /// <returns>A <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>, or a <see cref="NotFoundResult"/> if item was not found.</returns>
+ [HttpDelete("Users/{userId}/PlayedItems/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public Task<ActionResult<UserItemDataDto>> MarkUnplayedItemLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId)
+ => MarkUnplayedItem(userId, itemId);
+
+ /// <summary>
/// Reports playback has started within a session.
/// </summary>
/// <param name="playbackStartInfo">The playback start info.</param>
@@ -215,9 +257,8 @@ public class PlaystateController : BaseJellyfinApiController
}
/// <summary>
- /// Reports that a user has begun playing an item.
+ /// Reports that a session has begun playing an item.
/// </summary>
- /// <param name="userId">User id.</param>
/// <param name="itemId">Item id.</param>
/// <param name="mediaSourceId">The id of the MediaSource.</param>
/// <param name="audioStreamIndex">The audio stream index.</param>
@@ -228,11 +269,9 @@ public class PlaystateController : BaseJellyfinApiController
/// <param name="canSeek">Indicates if the client can seek.</param>
/// <response code="204">Play start recorded.</response>
/// <returns>A <see cref="NoContentResult"/>.</returns>
- [HttpPost("Users/{userId}/PlayingItems/{itemId}")]
+ [HttpPost("PlayingItems/{itemId}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
- [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
public async Task<ActionResult> OnPlaybackStart(
- [FromRoute, Required] Guid userId,
[FromRoute, Required] Guid itemId,
[FromQuery] string? mediaSourceId,
[FromQuery] int? audioStreamIndex,
@@ -261,11 +300,41 @@ public class PlaystateController : BaseJellyfinApiController
}
/// <summary>
- /// Reports a user's playback progress.
+ /// Reports that a user has begun playing an item.
/// </summary>
/// <param name="userId">User id.</param>
/// <param name="itemId">Item id.</param>
/// <param name="mediaSourceId">The id of the MediaSource.</param>
+ /// <param name="audioStreamIndex">The audio stream index.</param>
+ /// <param name="subtitleStreamIndex">The subtitle stream index.</param>
+ /// <param name="playMethod">The play method.</param>
+ /// <param name="liveStreamId">The live stream id.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <param name="canSeek">Indicates if the client can seek.</param>
+ /// <response code="204">Play start recorded.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Users/{userId}/PlayingItems/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
+ public Task<ActionResult> OnPlaybackStartLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] string? mediaSourceId,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] PlayMethod? playMethod,
+ [FromQuery] string? liveStreamId,
+ [FromQuery] string? playSessionId,
+ [FromQuery] bool canSeek = false)
+ => OnPlaybackStart(itemId, mediaSourceId, audioStreamIndex, subtitleStreamIndex, playMethod, liveStreamId, playSessionId, canSeek);
+
+ /// <summary>
+ /// Reports a session's playback progress.
+ /// </summary>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="mediaSourceId">The id of the MediaSource.</param>
/// <param name="positionTicks">Optional. The current position, in ticks. 1 tick = 10000 ms.</param>
/// <param name="audioStreamIndex">The audio stream index.</param>
/// <param name="subtitleStreamIndex">The subtitle stream index.</param>
@@ -278,11 +347,9 @@ public class PlaystateController : BaseJellyfinApiController
/// <param name="isMuted">Indicates if the player is muted.</param>
/// <response code="204">Play progress recorded.</response>
/// <returns>A <see cref="NoContentResult"/>.</returns>
- [HttpPost("Users/{userId}/PlayingItems/{itemId}/Progress")]
+ [HttpPost("PlayingItems/{itemId}/Progress")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
- [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
public async Task<ActionResult> OnPlaybackProgress(
- [FromRoute, Required] Guid userId,
[FromRoute, Required] Guid itemId,
[FromQuery] string? mediaSourceId,
[FromQuery] long? positionTicks,
@@ -319,22 +386,58 @@ public class PlaystateController : BaseJellyfinApiController
}
/// <summary>
- /// Reports that a user has stopped playing an item.
+ /// Reports a user's playback progress.
/// </summary>
/// <param name="userId">User id.</param>
/// <param name="itemId">Item id.</param>
/// <param name="mediaSourceId">The id of the MediaSource.</param>
+ /// <param name="positionTicks">Optional. The current position, in ticks. 1 tick = 10000 ms.</param>
+ /// <param name="audioStreamIndex">The audio stream index.</param>
+ /// <param name="subtitleStreamIndex">The subtitle stream index.</param>
+ /// <param name="volumeLevel">Scale of 0-100.</param>
+ /// <param name="playMethod">The play method.</param>
+ /// <param name="liveStreamId">The live stream id.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <param name="repeatMode">The repeat mode.</param>
+ /// <param name="isPaused">Indicates if the player is paused.</param>
+ /// <param name="isMuted">Indicates if the player is muted.</param>
+ /// <response code="204">Play progress recorded.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpPost("Users/{userId}/PlayingItems/{itemId}/Progress")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
+ public Task<ActionResult> OnPlaybackProgressLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] string? mediaSourceId,
+ [FromQuery] long? positionTicks,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] int? volumeLevel,
+ [FromQuery] PlayMethod? playMethod,
+ [FromQuery] string? liveStreamId,
+ [FromQuery] string? playSessionId,
+ [FromQuery] RepeatMode? repeatMode,
+ [FromQuery] bool isPaused = false,
+ [FromQuery] bool isMuted = false)
+ => OnPlaybackProgress(itemId, mediaSourceId, positionTicks, audioStreamIndex, subtitleStreamIndex, volumeLevel, playMethod, liveStreamId, playSessionId, repeatMode, isPaused, isMuted);
+
+ /// <summary>
+ /// Reports that a session has stopped playing an item.
+ /// </summary>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="mediaSourceId">The id of the MediaSource.</param>
/// <param name="nextMediaType">The next media type that will play.</param>
/// <param name="positionTicks">Optional. The position, in ticks, where playback stopped. 1 tick = 10000 ms.</param>
/// <param name="liveStreamId">The live stream id.</param>
/// <param name="playSessionId">The play session id.</param>
/// <response code="204">Playback stop recorded.</response>
/// <returns>A <see cref="NoContentResult"/>.</returns>
- [HttpDelete("Users/{userId}/PlayingItems/{itemId}")]
+ [HttpDelete("PlayingItems/{itemId}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
- [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
public async Task<ActionResult> OnPlaybackStopped(
- [FromRoute, Required] Guid userId,
[FromRoute, Required] Guid itemId,
[FromQuery] string? mediaSourceId,
[FromQuery] string? nextMediaType,
@@ -364,6 +467,33 @@ public class PlaystateController : BaseJellyfinApiController
}
/// <summary>
+ /// Reports that a user has stopped playing an item.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="mediaSourceId">The id of the MediaSource.</param>
+ /// <param name="nextMediaType">The next media type that will play.</param>
+ /// <param name="positionTicks">Optional. The position, in ticks, where playback stopped. 1 tick = 10000 ms.</param>
+ /// <param name="liveStreamId">The live stream id.</param>
+ /// <param name="playSessionId">The play session id.</param>
+ /// <response code="204">Playback stop recorded.</response>
+ /// <returns>A <see cref="NoContentResult"/>.</returns>
+ [HttpDelete("Users/{userId}/PlayingItems/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
+ public Task<ActionResult> OnPlaybackStoppedLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] string? mediaSourceId,
+ [FromQuery] string? nextMediaType,
+ [FromQuery] long? positionTicks,
+ [FromQuery] string? liveStreamId,
+ [FromQuery] string? playSessionId)
+ => OnPlaybackStopped(itemId, mediaSourceId, nextMediaType, positionTicks, liveStreamId, playSessionId);
+
+ /// <summary>
/// Updates the played status.
/// </summary>
/// <param name="user">The user.</param>
diff --git a/Jellyfin.Api/Controllers/SuggestionsController.cs b/Jellyfin.Api/Controllers/SuggestionsController.cs
index 2aa6d25a7..ad625cc6e 100644
--- a/Jellyfin.Api/Controllers/SuggestionsController.cs
+++ b/Jellyfin.Api/Controllers/SuggestionsController.cs
@@ -1,7 +1,9 @@
using System;
using System.ComponentModel.DataAnnotations;
using Jellyfin.Api.Extensions;
+using Jellyfin.Api.Helpers;
using Jellyfin.Api.ModelBinders;
+using Jellyfin.Data.Entities;
using Jellyfin.Data.Enums;
using Jellyfin.Extensions;
using MediaBrowser.Controller.Dto;
@@ -53,19 +55,26 @@ public class SuggestionsController : BaseJellyfinApiController
/// <param name="enableTotalRecordCount">Whether to enable the total record count.</param>
/// <response code="200">Suggestions returned.</response>
/// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the suggestions.</returns>
- [HttpGet("Users/{userId}/Suggestions")]
+ [HttpGet("Items/Suggestions")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<QueryResult<BaseItemDto>> GetSuggestions(
- [FromRoute, Required] Guid userId,
+ [FromQuery] Guid? userId,
[FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] MediaType[] mediaType,
[FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] type,
[FromQuery] int? startIndex,
[FromQuery] int? limit,
[FromQuery] bool enableTotalRecordCount = false)
{
- var user = userId.IsEmpty()
- ? null
- : _userManager.GetUserById(userId);
+ User? user;
+ if (userId.IsNullOrEmpty())
+ {
+ user = null;
+ }
+ else
+ {
+ var requestUserId = RequestHelpers.GetUserId(User, userId);
+ user = _userManager.GetUserById(requestUserId);
+ }
var dtoOptions = new DtoOptions().AddClientFields(User);
var result = _libraryManager.GetItemsResult(new InternalItemsQuery(user)
@@ -88,4 +97,28 @@ public class SuggestionsController : BaseJellyfinApiController
result.TotalRecordCount,
dtoList);
}
+
+ /// <summary>
+ /// Gets suggestions.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="mediaType">The media types.</param>
+ /// <param name="type">The type.</param>
+ /// <param name="startIndex">Optional. The start index.</param>
+ /// <param name="limit">Optional. The limit.</param>
+ /// <param name="enableTotalRecordCount">Whether to enable the total record count.</param>
+ /// <response code="200">Suggestions returned.</response>
+ /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the suggestions.</returns>
+ [HttpGet("Users/{userId}/Suggestions")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public ActionResult<QueryResult<BaseItemDto>> GetSuggestionsLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] MediaType[] mediaType,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] type,
+ [FromQuery] int? startIndex,
+ [FromQuery] int? limit,
+ [FromQuery] bool enableTotalRecordCount = false)
+ => GetSuggestions(userId, mediaType, type, startIndex, limit, enableTotalRecordCount);
}
diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs
index 0a416aedb..634fca2eb 100644
--- a/Jellyfin.Api/Controllers/UniversalAudioController.cs
+++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs
@@ -8,6 +8,7 @@ using Jellyfin.Api.Attributes;
using Jellyfin.Api.Helpers;
using Jellyfin.Api.ModelBinders;
using Jellyfin.Api.Models.StreamingDtos;
+using Jellyfin.Data.Enums;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
@@ -98,7 +99,7 @@ public class UniversalAudioController : BaseJellyfinApiController
[FromQuery] int? audioBitRate,
[FromQuery] long? startTimeTicks,
[FromQuery] string? transcodingContainer,
- [FromQuery] string? transcodingProtocol,
+ [FromQuery] MediaStreamProtocol? transcodingProtocol,
[FromQuery] int? maxAudioSampleRate,
[FromQuery] int? maxAudioBitDepth,
[FromQuery] bool? enableRemoteMedia,
@@ -156,7 +157,7 @@ public class UniversalAudioController : BaseJellyfinApiController
}
var isStatic = mediaSource.SupportsDirectStream;
- if (!isStatic && string.Equals(mediaSource.TranscodingSubProtocol, "hls", StringComparison.OrdinalIgnoreCase))
+ if (!isStatic && mediaSource.TranscodingSubProtocol == MediaStreamProtocol.hls)
{
// hls segment container can only be mpegts or fmp4 per ffmpeg documentation
// ffmpeg option -> file extension
@@ -232,7 +233,7 @@ public class UniversalAudioController : BaseJellyfinApiController
string[] containers,
string? transcodingContainer,
string? audioCodec,
- string? transcodingProtocol,
+ MediaStreamProtocol? transcodingProtocol,
bool? breakOnNonKeyFrames,
int? transcodingAudioChannels,
int? maxAudioSampleRate,
@@ -267,7 +268,7 @@ public class UniversalAudioController : BaseJellyfinApiController
Context = EncodingContext.Streaming,
Container = transcodingContainer ?? "mp3",
AudioCodec = audioCodec ?? "mp3",
- Protocol = transcodingProtocol ?? "http",
+ Protocol = transcodingProtocol ?? MediaStreamProtocol.http,
BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
MaxAudioChannels = transcodingAudioChannels?.ToString(CultureInfo.InvariantCulture)
}
diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs
index ea10ee24f..c3923a2ad 100644
--- a/Jellyfin.Api/Controllers/UserController.cs
+++ b/Jellyfin.Api/Controllers/UserController.cs
@@ -178,6 +178,7 @@ public class UserController : BaseJellyfinApiController
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
+ [ApiExplorerSettings(IgnoreApi = true)]
[Obsolete("Authenticate with username instead")]
public async Task<ActionResult<AuthenticationResult>> AuthenticateUser(
[FromRoute, Required] Guid userId,
@@ -263,21 +264,22 @@ public class UserController : BaseJellyfinApiController
/// <response code="403">User is not allowed to update the password.</response>
/// <response code="404">User not found.</response>
/// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="ForbidResult"/> or a <see cref="NotFoundResult"/> on failure.</returns>
- [HttpPost("{userId}/Password")]
+ [HttpPost("Password")]
[Authorize]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult> UpdateUserPassword(
- [FromRoute, Required] Guid userId,
+ [FromQuery] Guid? userId,
[FromBody, Required] UpdateUserPassword request)
{
- if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, userId, true))
+ var requestUserId = userId ?? User.GetUserId();
+ if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, requestUserId, true))
{
return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the password.");
}
- var user = _userManager.GetUserById(userId);
+ var user = _userManager.GetUserById(requestUserId);
if (user is null)
{
@@ -290,7 +292,7 @@ public class UserController : BaseJellyfinApiController
}
else
{
- if (!User.IsInRole(UserRoles.Administrator) || User.GetUserId().Equals(userId))
+ if (!User.IsInRole(UserRoles.Administrator) || (userId.HasValue && User.GetUserId().Equals(userId.Value)))
{
var success = await _userManager.AuthenticateUser(
user.Username,
@@ -316,6 +318,27 @@ public class UserController : BaseJellyfinApiController
}
/// <summary>
+ /// Updates a user's password.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="request">The <see cref="UpdateUserPassword"/> request.</param>
+ /// <response code="204">Password successfully reset.</response>
+ /// <response code="403">User is not allowed to update the password.</response>
+ /// <response code="404">User not found.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="ForbidResult"/> or a <see cref="NotFoundResult"/> on failure.</returns>
+ [HttpPost("{userId}/Password")]
+ [Authorize]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public Task<ActionResult> UpdateUserPasswordLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromBody, Required] UpdateUserPassword request)
+ => UpdateUserPassword(userId, request);
+
+ /// <summary>
/// Updates a user's easy password.
/// </summary>
/// <param name="userId">The user id.</param>
@@ -326,6 +349,7 @@ public class UserController : BaseJellyfinApiController
/// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="ForbidResult"/> or a <see cref="NotFoundResult"/> on failure.</returns>
[HttpPost("{userId}/EasyPassword")]
[Obsolete("Use Quick Connect instead")]
+ [ApiExplorerSettings(IgnoreApi = true)]
[Authorize]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
@@ -346,22 +370,23 @@ public class UserController : BaseJellyfinApiController
/// <response code="400">User information was not supplied.</response>
/// <response code="403">User update forbidden.</response>
/// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="BadRequestResult"/> or a <see cref="ForbidResult"/> on failure.</returns>
- [HttpPost("{userId}")]
+ [HttpPost]
[Authorize]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<ActionResult> UpdateUser(
- [FromRoute, Required] Guid userId,
+ [FromQuery] Guid? userId,
[FromBody, Required] UserDto updateUser)
{
- var user = _userManager.GetUserById(userId);
+ var requestUserId = userId ?? User.GetUserId();
+ var user = _userManager.GetUserById(requestUserId);
if (user is null)
{
return NotFound();
}
- if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, userId, true))
+ if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, requestUserId, true))
{
return StatusCode(StatusCodes.Status403Forbidden, "User update not allowed.");
}
@@ -377,6 +402,27 @@ public class UserController : BaseJellyfinApiController
}
/// <summary>
+ /// Updates a user.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="updateUser">The updated user model.</param>
+ /// <response code="204">User updated.</response>
+ /// <response code="400">User information was not supplied.</response>
+ /// <response code="403">User update forbidden.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success or a <see cref="BadRequestResult"/> or a <see cref="ForbidResult"/> on failure.</returns>
+ [HttpPost("{userId}")]
+ [Authorize]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public Task<ActionResult> UpdateUserLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromBody, Required] UserDto updateUser)
+ => UpdateUser(userId, updateUser);
+
+ /// <summary>
/// Updates a user policy.
/// </summary>
/// <param name="userId">The user id.</param>
@@ -440,25 +486,45 @@ public class UserController : BaseJellyfinApiController
/// <response code="204">User configuration updated.</response>
/// <response code="403">User configuration update forbidden.</response>
/// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
- [HttpPost("{userId}/Configuration")]
+ [HttpPost("Configuration")]
[Authorize]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<ActionResult> UpdateUserConfiguration(
- [FromRoute, Required] Guid userId,
+ [FromQuery] Guid? userId,
[FromBody, Required] UserConfiguration userConfig)
{
- if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, userId, true))
+ var requestUserId = userId ?? User.GetUserId();
+ if (!RequestHelpers.AssertCanUpdateUser(_userManager, User, requestUserId, true))
{
return StatusCode(StatusCodes.Status403Forbidden, "User configuration update not allowed");
}
- await _userManager.UpdateConfigurationAsync(userId, userConfig).ConfigureAwait(false);
+ await _userManager.UpdateConfigurationAsync(requestUserId, userConfig).ConfigureAwait(false);
return NoContent();
}
/// <summary>
+ /// Updates a user configuration.
+ /// </summary>
+ /// <param name="userId">The user id.</param>
+ /// <param name="userConfig">The new user configuration.</param>
+ /// <response code="204">User configuration updated.</response>
+ /// <response code="403">User configuration update forbidden.</response>
+ /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
+ [HttpPost("{userId}/Configuration")]
+ [Authorize]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status403Forbidden)]
+ public Task<ActionResult> UpdateUserConfigurationLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromBody, Required] UserConfiguration userConfig)
+ => UpdateUserConfiguration(userId, userConfig);
+
+ /// <summary>
/// Creates a user.
/// </summary>
/// <param name="request">The create user by name request body.</param>
diff --git a/Jellyfin.Api/Controllers/UserLibraryController.cs b/Jellyfin.Api/Controllers/UserLibraryController.cs
index e3bfd4ea9..c19ad33c8 100644
--- a/Jellyfin.Api/Controllers/UserLibraryController.cs
+++ b/Jellyfin.Api/Controllers/UserLibraryController.cs
@@ -5,6 +5,7 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Api.Extensions;
+using Jellyfin.Api.Helpers;
using Jellyfin.Api.ModelBinders;
using Jellyfin.Data.Entities;
using Jellyfin.Data.Enums;
@@ -13,12 +14,10 @@ using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Lyrics;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Lyrics;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
@@ -39,7 +38,6 @@ public class UserLibraryController : BaseJellyfinApiController
private readonly IDtoService _dtoService;
private readonly IUserViewManager _userViewManager;
private readonly IFileSystem _fileSystem;
- private readonly ILyricManager _lyricManager;
/// <summary>
/// Initializes a new instance of the <see cref="UserLibraryController"/> class.
@@ -50,15 +48,13 @@ public class UserLibraryController : BaseJellyfinApiController
/// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
/// <param name="userViewManager">Instance of the <see cref="IUserViewManager"/> interface.</param>
/// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
- /// <param name="lyricManager">Instance of the <see cref="ILyricManager"/> interface.</param>
public UserLibraryController(
IUserManager userManager,
IUserDataManager userDataRepository,
ILibraryManager libraryManager,
IDtoService dtoService,
IUserViewManager userViewManager,
- IFileSystem fileSystem,
- ILyricManager lyricManager)
+ IFileSystem fileSystem)
{
_userManager = userManager;
_userDataRepository = userDataRepository;
@@ -66,7 +62,6 @@ public class UserLibraryController : BaseJellyfinApiController
_dtoService = dtoService;
_userViewManager = userViewManager;
_fileSystem = fileSystem;
- _lyricManager = lyricManager;
}
/// <summary>
@@ -76,11 +71,14 @@ public class UserLibraryController : BaseJellyfinApiController
/// <param name="itemId">Item id.</param>
/// <response code="200">Item returned.</response>
/// <returns>An <see cref="OkResult"/> containing the item.</returns>
- [HttpGet("Users/{userId}/Items/{itemId}")]
+ [HttpGet("Items/{itemId}")]
[ProducesResponseType(StatusCodes.Status200OK)]
- public async Task<ActionResult<BaseItemDto>> GetItem([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId)
+ public async Task<ActionResult<BaseItemDto>> GetItem(
+ [FromQuery] Guid? userId,
+ [FromRoute, Required] Guid itemId)
{
- var user = _userManager.GetUserById(userId);
+ var requestUserId = RequestHelpers.GetUserId(User, userId);
+ var user = _userManager.GetUserById(requestUserId);
if (user is null)
{
return NotFound();
@@ -110,16 +108,33 @@ public class UserLibraryController : BaseJellyfinApiController
}
/// <summary>
+ /// Gets an item from a user's library.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <response code="200">Item returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the item.</returns>
+ [HttpGet("Users/{userId}/Items/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public Task<ActionResult<BaseItemDto>> GetItemLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId)
+ => GetItem(userId, itemId);
+
+ /// <summary>
/// Gets the root folder from a user's library.
/// </summary>
/// <param name="userId">User id.</param>
/// <response code="200">Root folder returned.</response>
/// <returns>An <see cref="OkResult"/> containing the user's root folder.</returns>
- [HttpGet("Users/{userId}/Items/Root")]
+ [HttpGet("Items/Root")]
[ProducesResponseType(StatusCodes.Status200OK)]
- public ActionResult<BaseItemDto> GetRootFolder([FromRoute, Required] Guid userId)
+ public ActionResult<BaseItemDto> GetRootFolder([FromQuery] Guid? userId)
{
- var user = _userManager.GetUserById(userId);
+ var requestUserId = RequestHelpers.GetUserId(User, userId);
+ var user = _userManager.GetUserById(requestUserId);
if (user is null)
{
return NotFound();
@@ -131,17 +146,34 @@ public class UserLibraryController : BaseJellyfinApiController
}
/// <summary>
+ /// Gets the root folder from a user's library.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <response code="200">Root folder returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the user's root folder.</returns>
+ [HttpGet("Users/{userId}/Items/Root")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public ActionResult<BaseItemDto> GetRootFolderLegacy(
+ [FromRoute, Required] Guid userId)
+ => GetRootFolder(userId);
+
+ /// <summary>
/// Gets intros to play before the main media item plays.
/// </summary>
/// <param name="userId">User id.</param>
/// <param name="itemId">Item id.</param>
/// <response code="200">Intros returned.</response>
/// <returns>An <see cref="OkResult"/> containing the intros to play.</returns>
- [HttpGet("Users/{userId}/Items/{itemId}/Intros")]
+ [HttpGet("Items/{itemId}/Intros")]
[ProducesResponseType(StatusCodes.Status200OK)]
- public async Task<ActionResult<QueryResult<BaseItemDto>>> GetIntros([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId)
+ public async Task<ActionResult<QueryResult<BaseItemDto>>> GetIntros(
+ [FromQuery] Guid? userId,
+ [FromRoute, Required] Guid itemId)
{
- var user = _userManager.GetUserById(userId);
+ var requestUserId = RequestHelpers.GetUserId(User, userId);
+ var user = _userManager.GetUserById(requestUserId);
if (user is null)
{
return NotFound();
@@ -171,17 +203,36 @@ public class UserLibraryController : BaseJellyfinApiController
}
/// <summary>
+ /// Gets intros to play before the main media item plays.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <response code="200">Intros returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the intros to play.</returns>
+ [HttpGet("Users/{userId}/Items/{itemId}/Intros")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public Task<ActionResult<QueryResult<BaseItemDto>>> GetIntrosLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId)
+ => GetIntros(userId, itemId);
+
+ /// <summary>
/// Marks an item as a favorite.
/// </summary>
/// <param name="userId">User id.</param>
/// <param name="itemId">Item id.</param>
/// <response code="200">Item marked as favorite.</response>
/// <returns>An <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>.</returns>
- [HttpPost("Users/{userId}/FavoriteItems/{itemId}")]
+ [HttpPost("UserFavoriteItems/{itemId}")]
[ProducesResponseType(StatusCodes.Status200OK)]
- public ActionResult<UserItemDataDto> MarkFavoriteItem([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId)
+ public ActionResult<UserItemDataDto> MarkFavoriteItem(
+ [FromQuery] Guid? userId,
+ [FromRoute, Required] Guid itemId)
{
- var user = _userManager.GetUserById(userId);
+ var requestUserId = RequestHelpers.GetUserId(User, userId);
+ var user = _userManager.GetUserById(requestUserId);
if (user is null)
{
return NotFound();
@@ -207,17 +258,36 @@ public class UserLibraryController : BaseJellyfinApiController
}
/// <summary>
+ /// Marks an item as a favorite.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <response code="200">Item marked as favorite.</response>
+ /// <returns>An <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>.</returns>
+ [HttpPost("Users/{userId}/FavoriteItems/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public ActionResult<UserItemDataDto> MarkFavoriteItemLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId)
+ => MarkFavoriteItem(userId, itemId);
+
+ /// <summary>
/// Unmarks item as a favorite.
/// </summary>
/// <param name="userId">User id.</param>
/// <param name="itemId">Item id.</param>
/// <response code="200">Item unmarked as favorite.</response>
/// <returns>An <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>.</returns>
- [HttpDelete("Users/{userId}/FavoriteItems/{itemId}")]
+ [HttpDelete("UserFavoriteItems/{itemId}")]
[ProducesResponseType(StatusCodes.Status200OK)]
- public ActionResult<UserItemDataDto> UnmarkFavoriteItem([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId)
+ public ActionResult<UserItemDataDto> UnmarkFavoriteItem(
+ [FromQuery] Guid? userId,
+ [FromRoute, Required] Guid itemId)
{
- var user = _userManager.GetUserById(userId);
+ var requestUserId = RequestHelpers.GetUserId(User, userId);
+ var user = _userManager.GetUserById(requestUserId);
if (user is null)
{
return NotFound();
@@ -243,17 +313,36 @@ public class UserLibraryController : BaseJellyfinApiController
}
/// <summary>
+ /// Unmarks item as a favorite.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <response code="200">Item unmarked as favorite.</response>
+ /// <returns>An <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>.</returns>
+ [HttpDelete("Users/{userId}/FavoriteItems/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public ActionResult<UserItemDataDto> UnmarkFavoriteItemLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId)
+ => UnmarkFavoriteItem(userId, itemId);
+
+ /// <summary>
/// Deletes a user's saved personal rating for an item.
/// </summary>
/// <param name="userId">User id.</param>
/// <param name="itemId">Item id.</param>
/// <response code="200">Personal rating removed.</response>
/// <returns>An <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>.</returns>
- [HttpDelete("Users/{userId}/Items/{itemId}/Rating")]
+ [HttpDelete("UserItems/{itemId}/Rating")]
[ProducesResponseType(StatusCodes.Status200OK)]
- public ActionResult<UserItemDataDto> DeleteUserItemRating([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId)
+ public ActionResult<UserItemDataDto> DeleteUserItemRating(
+ [FromQuery] Guid? userId,
+ [FromRoute, Required] Guid itemId)
{
- var user = _userManager.GetUserById(userId);
+ var requestUserId = RequestHelpers.GetUserId(User, userId);
+ var user = _userManager.GetUserById(requestUserId);
if (user is null)
{
return NotFound();
@@ -279,6 +368,22 @@ public class UserLibraryController : BaseJellyfinApiController
}
/// <summary>
+ /// Deletes a user's saved personal rating for an item.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <response code="200">Personal rating removed.</response>
+ /// <returns>An <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>.</returns>
+ [HttpDelete("Users/{userId}/Items/{itemId}/Rating")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public ActionResult<UserItemDataDto> DeleteUserItemRatingLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId)
+ => DeleteUserItemRating(userId, itemId);
+
+ /// <summary>
/// Updates a user's rating for an item.
/// </summary>
/// <param name="userId">User id.</param>
@@ -286,11 +391,15 @@ public class UserLibraryController : BaseJellyfinApiController
/// <param name="likes">Whether this <see cref="UpdateUserItemRating" /> is likes.</param>
/// <response code="200">Item rating updated.</response>
/// <returns>An <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>.</returns>
- [HttpPost("Users/{userId}/Items/{itemId}/Rating")]
+ [HttpPost("UserItems/{itemId}/Rating")]
[ProducesResponseType(StatusCodes.Status200OK)]
- public ActionResult<UserItemDataDto> UpdateUserItemRating([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId, [FromQuery] bool? likes)
+ public ActionResult<UserItemDataDto> UpdateUserItemRating(
+ [FromQuery] Guid? userId,
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] bool? likes)
{
- var user = _userManager.GetUserById(userId);
+ var requestUserId = RequestHelpers.GetUserId(User, userId);
+ var user = _userManager.GetUserById(requestUserId);
if (user is null)
{
return NotFound();
@@ -316,17 +425,38 @@ public class UserLibraryController : BaseJellyfinApiController
}
/// <summary>
+ /// Updates a user's rating for an item.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <param name="likes">Whether this <see cref="UpdateUserItemRating" /> is likes.</param>
+ /// <response code="200">Item rating updated.</response>
+ /// <returns>An <see cref="OkResult"/> containing the <see cref="UserItemDataDto"/>.</returns>
+ [HttpPost("Users/{userId}/Items/{itemId}/Rating")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public ActionResult<UserItemDataDto> UpdateUserItemRatingLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId,
+ [FromQuery] bool? likes)
+ => UpdateUserItemRating(userId, itemId, likes);
+
+ /// <summary>
/// Gets local trailers for an item.
/// </summary>
/// <param name="userId">User id.</param>
/// <param name="itemId">Item id.</param>
/// <response code="200">An <see cref="OkResult"/> containing the item's local trailers.</response>
/// <returns>The items local trailers.</returns>
- [HttpGet("Users/{userId}/Items/{itemId}/LocalTrailers")]
+ [HttpGet("Items/{itemId}/LocalTrailers")]
[ProducesResponseType(StatusCodes.Status200OK)]
- public ActionResult<IEnumerable<BaseItemDto>> GetLocalTrailers([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId)
+ public ActionResult<IEnumerable<BaseItemDto>> GetLocalTrailers(
+ [FromQuery] Guid? userId,
+ [FromRoute, Required] Guid itemId)
{
- var user = _userManager.GetUserById(userId);
+ var requestUserId = RequestHelpers.GetUserId(User, userId);
+ var user = _userManager.GetUserById(requestUserId);
if (user is null)
{
return NotFound();
@@ -361,17 +491,36 @@ public class UserLibraryController : BaseJellyfinApiController
}
/// <summary>
+ /// Gets local trailers for an item.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <response code="200">An <see cref="OkResult"/> containing the item's local trailers.</response>
+ /// <returns>The items local trailers.</returns>
+ [HttpGet("Users/{userId}/Items/{itemId}/LocalTrailers")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public ActionResult<IEnumerable<BaseItemDto>> GetLocalTrailersLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId)
+ => GetLocalTrailers(userId, itemId);
+
+ /// <summary>
/// Gets special features for an item.
/// </summary>
/// <param name="userId">User id.</param>
/// <param name="itemId">Item id.</param>
/// <response code="200">Special features returned.</response>
/// <returns>An <see cref="OkResult"/> containing the special features.</returns>
- [HttpGet("Users/{userId}/Items/{itemId}/SpecialFeatures")]
+ [HttpGet("Items/{itemId}/SpecialFeatures")]
[ProducesResponseType(StatusCodes.Status200OK)]
- public ActionResult<IEnumerable<BaseItemDto>> GetSpecialFeatures([FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId)
+ public ActionResult<IEnumerable<BaseItemDto>> GetSpecialFeatures(
+ [FromQuery] Guid? userId,
+ [FromRoute, Required] Guid itemId)
{
- var user = _userManager.GetUserById(userId);
+ var requestUserId = RequestHelpers.GetUserId(User, userId);
+ var user = _userManager.GetUserById(requestUserId);
if (user is null)
{
return NotFound();
@@ -402,6 +551,22 @@ public class UserLibraryController : BaseJellyfinApiController
}
/// <summary>
+ /// Gets special features for an item.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="itemId">Item id.</param>
+ /// <response code="200">Special features returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the special features.</returns>
+ [HttpGet("Users/{userId}/Items/{itemId}/SpecialFeatures")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public ActionResult<IEnumerable<BaseItemDto>> GetSpecialFeaturesLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromRoute, Required] Guid itemId)
+ => GetSpecialFeatures(userId, itemId);
+
+ /// <summary>
/// Gets latest media.
/// </summary>
/// <param name="userId">User id.</param>
@@ -417,10 +582,10 @@ public class UserLibraryController : BaseJellyfinApiController
/// <param name="groupItems">Whether or not to group items into a parent container.</param>
/// <response code="200">Latest media returned.</response>
/// <returns>An <see cref="OkResult"/> containing the latest media.</returns>
- [HttpGet("Users/{userId}/Items/Latest")]
+ [HttpGet("Items/Latest")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<IEnumerable<BaseItemDto>> GetLatestMedia(
- [FromRoute, Required] Guid userId,
+ [FromQuery] Guid? userId,
[FromQuery] Guid? parentId,
[FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
@@ -432,7 +597,8 @@ public class UserLibraryController : BaseJellyfinApiController
[FromQuery] int limit = 20,
[FromQuery] bool groupItems = true)
{
- var user = _userManager.GetUserById(userId);
+ var requestUserId = RequestHelpers.GetUserId(User, userId);
+ var user = _userManager.GetUserById(requestUserId);
if (user is null)
{
return NotFound();
@@ -458,7 +624,7 @@ public class UserLibraryController : BaseJellyfinApiController
IsPlayed = isPlayed,
Limit = limit,
ParentId = parentId ?? Guid.Empty,
- UserId = userId,
+ UserId = requestUserId,
},
dtoOptions);
@@ -483,6 +649,51 @@ public class UserLibraryController : BaseJellyfinApiController
return Ok(dtos);
}
+ /// <summary>
+ /// Gets latest media.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
+ /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param>
+ /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
+ /// <param name="isPlayed">Filter by items that are played, or not.</param>
+ /// <param name="enableImages">Optional. include image information in output.</param>
+ /// <param name="imageTypeLimit">Optional. the max number of images to return, per image type.</param>
+ /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
+ /// <param name="enableUserData">Optional. include user data.</param>
+ /// <param name="limit">Return item limit.</param>
+ /// <param name="groupItems">Whether or not to group items into a parent container.</param>
+ /// <response code="200">Latest media returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the latest media.</returns>
+ [HttpGet("Users/{userId}/Items/Latest")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public ActionResult<IEnumerable<BaseItemDto>> GetLatestMediaLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromQuery] Guid? parentId,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
+ [FromQuery] bool? isPlayed,
+ [FromQuery] bool? enableImages,
+ [FromQuery] int? imageTypeLimit,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery] bool? enableUserData,
+ [FromQuery] int limit = 20,
+ [FromQuery] bool groupItems = true)
+ => GetLatestMedia(
+ userId,
+ parentId,
+ fields,
+ includeItemTypes,
+ isPlayed,
+ enableImages,
+ imageTypeLimit,
+ enableImageTypes,
+ enableUserData,
+ limit,
+ groupItems);
+
private async Task RefreshItemOnDemandIfNeeded(BaseItem item)
{
if (item is Person)
diff --git a/Jellyfin.Api/Controllers/UserViewsController.cs b/Jellyfin.Api/Controllers/UserViewsController.cs
index 035d04474..bf3ce1d39 100644
--- a/Jellyfin.Api/Controllers/UserViewsController.cs
+++ b/Jellyfin.Api/Controllers/UserViewsController.cs
@@ -4,6 +4,7 @@ using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using Jellyfin.Api.Extensions;
+using Jellyfin.Api.Helpers;
using Jellyfin.Api.ModelBinders;
using Jellyfin.Api.Models.UserViewDtos;
using Jellyfin.Data.Enums;
@@ -59,19 +60,17 @@ public class UserViewsController : BaseJellyfinApiController
/// <param name="includeHidden">Whether or not to include hidden content.</param>
/// <response code="200">User views returned.</response>
/// <returns>An <see cref="OkResult"/> containing the user views.</returns>
- [HttpGet("Users/{userId}/Views")]
+ [HttpGet("UserViews")]
[ProducesResponseType(StatusCodes.Status200OK)]
public QueryResult<BaseItemDto> GetUserViews(
- [FromRoute, Required] Guid userId,
+ [FromQuery] Guid? userId,
[FromQuery] bool? includeExternalContent,
[FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] CollectionType?[] presetViews,
[FromQuery] bool includeHidden = false)
{
- var query = new UserViewQuery
- {
- UserId = userId,
- IncludeHidden = includeHidden
- };
+ userId = RequestHelpers.GetUserId(User, userId);
+
+ var query = new UserViewQuery { UserId = userId.Value, IncludeHidden = includeHidden };
if (includeExternalContent.HasValue)
{
@@ -92,7 +91,7 @@ public class UserViewsController : BaseJellyfinApiController
fields.Add(ItemFields.DisplayPreferencesId);
dtoOptions.Fields = fields.ToArray();
- var user = _userManager.GetUserById(userId);
+ var user = _userManager.GetUserById(userId.Value);
var dtos = folders.Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user))
.ToArray();
@@ -101,6 +100,26 @@ public class UserViewsController : BaseJellyfinApiController
}
/// <summary>
+ /// Get user views.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <param name="includeExternalContent">Whether or not to include external views such as channels or live tv.</param>
+ /// <param name="presetViews">Preset views.</param>
+ /// <param name="includeHidden">Whether or not to include hidden content.</param>
+ /// <response code="200">User views returned.</response>
+ /// <returns>An <see cref="OkResult"/> containing the user views.</returns>
+ [HttpGet("Users/{userId}/Views")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public QueryResult<BaseItemDto> GetUserViewsLegacy(
+ [FromRoute, Required] Guid userId,
+ [FromQuery] bool? includeExternalContent,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] CollectionType?[] presetViews,
+ [FromQuery] bool includeHidden = false)
+ => GetUserViews(userId, includeExternalContent, presetViews, includeHidden);
+
+ /// <summary>
/// Get user view grouping options.
/// </summary>
/// <param name="userId">User id.</param>
@@ -110,12 +129,13 @@ public class UserViewsController : BaseJellyfinApiController
/// An <see cref="OkResult"/> containing the user view grouping options
/// or a <see cref="NotFoundResult"/> if user not found.
/// </returns>
- [HttpGet("Users/{userId}/GroupingOptions")]
+ [HttpGet("UserViews/GroupingOptions")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
- public ActionResult<IEnumerable<SpecialViewOptionDto>> GetGroupingOptions([FromRoute, Required] Guid userId)
+ public ActionResult<IEnumerable<SpecialViewOptionDto>> GetGroupingOptions([FromQuery] Guid? userId)
{
- var user = _userManager.GetUserById(userId);
+ userId = RequestHelpers.GetUserId(User, userId);
+ var user = _userManager.GetUserById(userId.Value);
if (user is null)
{
return NotFound();
@@ -133,4 +153,23 @@ public class UserViewsController : BaseJellyfinApiController
.OrderBy(i => i.Name)
.AsEnumerable());
}
+
+ /// <summary>
+ /// Get user view grouping options.
+ /// </summary>
+ /// <param name="userId">User id.</param>
+ /// <response code="200">User view grouping options returned.</response>
+ /// <response code="404">User not found.</response>
+ /// <returns>
+ /// An <see cref="OkResult"/> containing the user view grouping options
+ /// or a <see cref="NotFoundResult"/> if user not found.
+ /// </returns>
+ [HttpGet("Users/{userId}/GroupingOptions")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
+ [Obsolete("Kept for backwards compatibility")]
+ [ApiExplorerSettings(IgnoreApi = true)]
+ public ActionResult<IEnumerable<SpecialViewOptionDto>> GetGroupingOptionsLegacy(
+ [FromRoute, Required] Guid userId)
+ => GetGroupingOptions(userId);
}
diff --git a/Jellyfin.Data/Enums/MediaStreamProtocol.cs b/Jellyfin.Data/Enums/MediaStreamProtocol.cs
new file mode 100644
index 000000000..844dc95c1
--- /dev/null
+++ b/Jellyfin.Data/Enums/MediaStreamProtocol.cs
@@ -0,0 +1,22 @@
+#pragma warning disable SA1300 // Lowercase required for backwards compat.
+using System.ComponentModel;
+
+namespace Jellyfin.Data.Enums;
+
+/// <summary>
+/// Media streaming protocol.
+/// Lowercase for backwards compatibility.
+/// </summary>
+[DefaultValue(http)]
+public enum MediaStreamProtocol
+{
+ /// <summary>
+ /// HTTP.
+ /// </summary>
+ http = 0,
+
+ /// <summary>
+ /// HTTP Live Streaming.
+ /// </summary>
+ hls = 1
+}
diff --git a/Jellyfin.Server/Helpers/StartupHelpers.cs b/Jellyfin.Server/Helpers/StartupHelpers.cs
index 66d393dec..5311a30e4 100644
--- a/Jellyfin.Server/Helpers/StartupHelpers.cs
+++ b/Jellyfin.Server/Helpers/StartupHelpers.cs
@@ -57,6 +57,9 @@ public static class StartupHelpers
logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
+ logger.LogInformation("Log directory path: {LogDirectoryPath}", appPaths.LogDirectoryPath);
+ logger.LogInformation("Config directory path: {ConfigurationDirectoryPath}", appPaths.ConfigurationDirectoryPath);
+ logger.LogInformation("Cache path: {CachePath}", appPaths.CachePath);
logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
}
diff --git a/Jellyfin.Server/Migrations/MigrationRunner.cs b/Jellyfin.Server/Migrations/MigrationRunner.cs
index 757b56a49..44aa43044 100644
--- a/Jellyfin.Server/Migrations/MigrationRunner.cs
+++ b/Jellyfin.Server/Migrations/MigrationRunner.cs
@@ -43,7 +43,8 @@ namespace Jellyfin.Server.Migrations
typeof(Routines.MigrateAuthenticationDb),
typeof(Routines.FixPlaylistOwner),
typeof(Routines.MigrateRatingLevels),
- typeof(Routines.AddDefaultCastReceivers)
+ typeof(Routines.AddDefaultCastReceivers),
+ typeof(Routines.UpdateDefaultPluginRepository)
};
/// <summary>
diff --git a/Jellyfin.Server/Migrations/Routines/UpdateDefaultPluginRepository.cs b/Jellyfin.Server/Migrations/Routines/UpdateDefaultPluginRepository.cs
new file mode 100644
index 000000000..7e8c8ac87
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Routines/UpdateDefaultPluginRepository.cs
@@ -0,0 +1,52 @@
+using System;
+using MediaBrowser.Controller.Configuration;
+
+namespace Jellyfin.Server.Migrations.Routines;
+
+/// <summary>
+/// Migration to update the default Jellyfin plugin repository.
+/// </summary>
+public class UpdateDefaultPluginRepository : IMigrationRoutine
+{
+ private const string NewRepositoryUrl = "https://repo.jellyfin.org/files/plugin/manifest.json";
+ private const string OldRepositoryUrl = "https://repo.jellyfin.org/releases/plugin/manifest-stable.json";
+
+ private readonly IServerConfigurationManager _serverConfigurationManager;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UpdateDefaultPluginRepository"/> class.
+ /// </summary>
+ /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
+ public UpdateDefaultPluginRepository(IServerConfigurationManager serverConfigurationManager)
+ {
+ _serverConfigurationManager = serverConfigurationManager;
+ }
+
+ /// <inheritdoc />
+ public Guid Id => new("852816E0-2712-49A9-9240-C6FC5FCAD1A8");
+
+ /// <inheritdoc />
+ public string Name => "UpdateDefaultPluginRepository10.9";
+
+ /// <inheritdoc />
+ public bool PerformOnNewInstall => true;
+
+ /// <inheritdoc />
+ public void Perform()
+ {
+ var updated = false;
+ foreach (var repo in _serverConfigurationManager.Configuration.PluginRepositories)
+ {
+ if (string.Equals(repo.Url, OldRepositoryUrl, StringComparison.OrdinalIgnoreCase))
+ {
+ repo.Url = NewRepositoryUrl;
+ updated = true;
+ }
+ }
+
+ if (updated)
+ {
+ _serverConfigurationManager.SaveConfiguration();
+ }
+ }
+}
diff --git a/MediaBrowser.Controller/Channels/IHasCacheKey.cs b/MediaBrowser.Controller/Channels/IHasCacheKey.cs
index 9fae43033..7d5207c34 100644
--- a/MediaBrowser.Controller/Channels/IHasCacheKey.cs
+++ b/MediaBrowser.Controller/Channels/IHasCacheKey.cs
@@ -1,5 +1,3 @@
-#nullable disable
-
#pragma warning disable CS1591
namespace MediaBrowser.Controller.Channels
@@ -11,6 +9,6 @@ namespace MediaBrowser.Controller.Channels
/// </summary>
/// <param name="userId">The user identifier.</param>
/// <returns>System.String.</returns>
- string GetCacheKey(string userId);
+ string? GetCacheKey(string? userId);
}
}
diff --git a/MediaBrowser.Controller/Channels/ISearchableChannel.cs b/MediaBrowser.Controller/Channels/ISearchableChannel.cs
deleted file mode 100644
index b87943a6e..000000000
--- a/MediaBrowser.Controller/Channels/ISearchableChannel.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-#nullable disable
-
-#pragma warning disable CS1591
-
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace MediaBrowser.Controller.Channels
-{
- public interface ISearchableChannel
- {
- /// <summary>
- /// Searches the specified search term.
- /// </summary>
- /// <param name="searchInfo">The search information.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{IEnumerable{ChannelItemInfo}}.</returns>
- Task<IEnumerable<ChannelItemInfo>> Search(ChannelSearchInfo searchInfo, CancellationToken cancellationToken);
- }
-}
diff --git a/MediaBrowser.Controller/Channels/ISupportsLatestMedia.cs b/MediaBrowser.Controller/Channels/ISupportsLatestMedia.cs
index 8ad93387e..8ecc68bab 100644
--- a/MediaBrowser.Controller/Channels/ISupportsLatestMedia.cs
+++ b/MediaBrowser.Controller/Channels/ISupportsLatestMedia.cs
@@ -1,6 +1,4 @@
-#nullable disable
-
-#pragma warning disable CS1591
+#pragma warning disable CS1591
using System.Collections.Generic;
using System.Threading;
diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs
index 992bb19bb..676a47c88 100644
--- a/MediaBrowser.Controller/Entities/CollectionFolder.cs
+++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs
@@ -11,6 +11,7 @@ using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
+using Jellyfin.Data.Entities;
using Jellyfin.Data.Enums;
using Jellyfin.Extensions.Json;
using MediaBrowser.Controller.IO;
@@ -95,6 +96,16 @@ namespace MediaBrowser.Controller.Entities
return GetLibraryOptions(Path);
}
+ public override bool IsVisible(User user)
+ {
+ if (GetLibraryOptions().Enabled)
+ {
+ return base.IsVisible(user);
+ }
+
+ return false;
+ }
+
private static LibraryOptions LoadLibraryOptions(string path)
{
try
diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs
index e44c09783..6532f7a34 100644
--- a/MediaBrowser.Controller/Library/ILibraryManager.cs
+++ b/MediaBrowser.Controller/Library/ILibraryManager.cs
@@ -517,8 +517,9 @@ namespace MediaBrowser.Controller.Library
/// <param name="item">The item.</param>
/// <param name="image">The image.</param>
/// <param name="imageIndex">Index of the image.</param>
+ /// <param name="removeOnFailure">Whether to remove the image from the item on failure.</param>
/// <returns>Task.</returns>
- Task<ItemImageInfo> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex);
+ Task<ItemImageInfo> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex, bool removeOnFailure = true);
/// <summary>
/// Gets the items.
diff --git a/MediaBrowser.Controller/Library/IMusicManager.cs b/MediaBrowser.Controller/Library/IMusicManager.cs
index ec34a868b..93073cc79 100644
--- a/MediaBrowser.Controller/Library/IMusicManager.cs
+++ b/MediaBrowser.Controller/Library/IMusicManager.cs
@@ -1,5 +1,3 @@
-#nullable disable
-
#pragma warning disable CA1002, CS1591
using System.Collections.Generic;
@@ -19,7 +17,7 @@ namespace MediaBrowser.Controller.Library
/// <param name="user">The user to use.</param>
/// <param name="dtoOptions">The options to use.</param>
/// <returns>List of items.</returns>
- List<BaseItem> GetInstantMixFromItem(BaseItem item, User user, DtoOptions dtoOptions);
+ List<BaseItem> GetInstantMixFromItem(BaseItem item, User? user, DtoOptions dtoOptions);
/// <summary>
/// Gets the instant mix from artist.
@@ -28,7 +26,7 @@ namespace MediaBrowser.Controller.Library
/// <param name="user">The user to use.</param>
/// <param name="dtoOptions">The options to use.</param>
/// <returns>List of items.</returns>
- List<BaseItem> GetInstantMixFromArtist(MusicArtist artist, User user, DtoOptions dtoOptions);
+ List<BaseItem> GetInstantMixFromArtist(MusicArtist artist, User? user, DtoOptions dtoOptions);
/// <summary>
/// Gets the instant mix from genre.
@@ -37,6 +35,6 @@ namespace MediaBrowser.Controller.Library
/// <param name="user">The user to use.</param>
/// <param name="dtoOptions">The options to use.</param>
/// <returns>List of items.</returns>
- List<BaseItem> GetInstantMixFromGenres(IEnumerable<string> genres, User user, DtoOptions dtoOptions);
+ List<BaseItem> GetInstantMixFromGenres(IEnumerable<string> genres, User? user, DtoOptions dtoOptions);
}
}
diff --git a/MediaBrowser.Controller/LiveTv/ChannelInfo.cs b/MediaBrowser.Controller/LiveTv/ChannelInfo.cs
index 699c15f93..52581df45 100644
--- a/MediaBrowser.Controller/LiveTv/ChannelInfo.cs
+++ b/MediaBrowser.Controller/LiveTv/ChannelInfo.cs
@@ -54,7 +54,7 @@ namespace MediaBrowser.Controller.LiveTv
public string ChannelGroup { get; set; }
/// <summary>
- /// Gets or sets the the image path if it can be accessed directly from the file system.
+ /// Gets or sets the image path if it can be accessed directly from the file system.
/// </summary>
/// <value>The image path.</value>
public string ImagePath { get; set; }
diff --git a/MediaBrowser.Controller/Lyrics/ILyricManager.cs b/MediaBrowser.Controller/Lyrics/ILyricManager.cs
index f4376a1ee..1e71b87eb 100644
--- a/MediaBrowser.Controller/Lyrics/ILyricManager.cs
+++ b/MediaBrowser.Controller/Lyrics/ILyricManager.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Entities;
@@ -69,12 +70,22 @@ public interface ILyricManager
CancellationToken cancellationToken);
/// <summary>
- /// Upload new lyrics.
+ /// Saves new lyrics.
/// </summary>
/// <param name="audio">The audio file the lyrics belong to.</param>
- /// <param name="lyricResponse">The lyric response.</param>
+ /// <param name="format">The lyrics format.</param>
+ /// <param name="lyrics">The lyrics.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
- Task<LyricDto?> UploadLyricAsync(Audio audio, LyricResponse lyricResponse);
+ Task<LyricDto?> SaveLyricAsync(Audio audio, string format, string lyrics);
+
+ /// <summary>
+ /// Saves new lyrics.
+ /// </summary>
+ /// <param name="audio">The audio file the lyrics belong to.</param>
+ /// <param name="format">The lyrics format.</param>
+ /// <param name="lyrics">The lyrics.</param>
+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
+ Task<LyricDto?> SaveLyricAsync(Audio audio, string format, Stream lyrics);
/// <summary>
/// Get the remote lyrics.
diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
index b6738e7cc..946f7266c 100644
--- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
+++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
@@ -253,6 +253,14 @@ namespace MediaBrowser.Controller.MediaEncoding
&& _mediaEncoder.SupportsFilterWithOption(FilterOptionType.OverlayVulkanFrameSync);
}
+ private bool IsVideoToolboxFullSupported()
+ {
+ return _mediaEncoder.SupportsHwaccel("videotoolbox")
+ && _mediaEncoder.SupportsFilter("yadif_videotoolbox")
+ && _mediaEncoder.SupportsFilter("overlay_videotoolbox")
+ && _mediaEncoder.SupportsFilter("scale_vt");
+ }
+
private bool IsHwTonemapAvailable(EncodingJobInfo state, EncodingOptions options)
{
if (state.VideoStream is null
@@ -272,7 +280,8 @@ namespace MediaBrowser.Controller.MediaEncoding
var isNvdecDecoder = vidDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase);
var isVaapiDecoder = vidDecoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase);
var isD3d11vaDecoder = vidDecoder.Contains("d3d11va", StringComparison.OrdinalIgnoreCase);
- return isSwDecoder || isNvdecDecoder || isVaapiDecoder || isD3d11vaDecoder;
+ var isVideoToolBoxDecoder = vidDecoder.Contains("videotoolbox", StringComparison.OrdinalIgnoreCase);
+ return isSwDecoder || isNvdecDecoder || isVaapiDecoder || isD3d11vaDecoder || isVideoToolBoxDecoder;
}
return state.VideoStream.VideoRange == VideoRange.HDR
@@ -308,6 +317,21 @@ namespace MediaBrowser.Controller.MediaEncoding
&& state.VideoStream.VideoRangeType == VideoRangeType.HDR10;
}
+ private bool IsVideoToolboxTonemapAvailable(EncodingJobInfo state, EncodingOptions options)
+ {
+ if (state.VideoStream is null
+ || !options.EnableVideoToolboxTonemapping
+ || GetVideoColorBitDepth(state) != 10)
+ {
+ return false;
+ }
+
+ // Certain DV profile 5 video works in Safari with direct playing, but the VideoToolBox does not produce correct mapping results with transcoding.
+ // All other HDR formats working.
+ return state.VideoStream.VideoRange == VideoRange.HDR
+ && state.VideoStream.VideoRangeType is VideoRangeType.HDR10 or VideoRangeType.HLG or VideoRangeType.HDR10Plus;
+ }
+
/// <summary>
/// Gets the name of the output video codec.
/// </summary>
@@ -4954,22 +4978,30 @@ namespace MediaBrowser.Controller.MediaEncoding
return (null, null, null);
}
- var swFilterChain = GetSwVidFilterChain(state, options, vidEncoder);
+ var isMacOS = OperatingSystem.IsMacOS();
+ var vidDecoder = GetHardwareVideoDecoder(state, options) ?? string.Empty;
+ var isVtEncoder = vidEncoder.Contains("videotoolbox", StringComparison.OrdinalIgnoreCase);
+ var isVtFullSupported = isMacOS && IsVideoToolboxFullSupported();
+ var isVtOclSupported = isVtFullSupported && IsOpenclFullSupported();
- if (!options.EnableHardwareEncoding)
+ // legacy videotoolbox pipeline (disable hw filters)
+ if (!isVtEncoder
+ || !isVtOclSupported
+ || !_mediaEncoder.SupportsFilter("alphasrc"))
{
- return swFilterChain;
+ return GetSwVidFilterChain(state, options, vidEncoder);
}
- if (_mediaEncoder.EncoderVersion.CompareTo(new Version("5.0.0")) < 0)
- {
- // All features used here requires ffmpeg 5.0 or later, fallback to software filters if using an old ffmpeg
- return swFilterChain;
- }
+ // preferred videotoolbox + vt/ocl filters pipeline
+ return GetAppleVidFiltersPreferred(state, options, vidDecoder, vidEncoder);
+ }
- var doDeintH264 = state.DeInterlace("h264", true) || state.DeInterlace("avc", true);
- var doDeintHevc = state.DeInterlace("h265", true) || state.DeInterlace("hevc", true);
- var doDeintH2645 = doDeintH264 || doDeintHevc;
+ public (List<string> MainFilters, List<string> SubFilters, List<string> OverlayFilters) GetAppleVidFiltersPreferred(
+ EncodingJobInfo state,
+ EncodingOptions options,
+ string vidDecoder,
+ string vidEncoder)
+ {
var inW = state.VideoStream?.Width;
var inH = state.VideoStream?.Height;
var reqW = state.BaseRequest.Width;
@@ -4977,33 +5009,114 @@ namespace MediaBrowser.Controller.MediaEncoding
var reqMaxW = state.BaseRequest.MaxWidth;
var reqMaxH = state.BaseRequest.MaxHeight;
var threeDFormat = state.MediaSource.Video3DFormat;
- var newfilters = new List<string>();
- var noOverlay = swFilterChain.OverlayFilters.Count == 0;
- var supportsHwDeint = _mediaEncoder.SupportsFilter("yadif_videotoolbox");
- // fallback to software filters if we are using filters not supported by hardware yet.
- var useHardwareFilters = noOverlay && (!doDeintH2645 || supportsHwDeint);
- if (!useHardwareFilters)
+ var isVtEncoder = vidEncoder.Contains("videotoolbox", StringComparison.OrdinalIgnoreCase);
+
+ var doDeintH264 = state.DeInterlace("h264", true) || state.DeInterlace("avc", true);
+ var doDeintHevc = state.DeInterlace("h265", true) || state.DeInterlace("hevc", true);
+ var doDeintH2645 = doDeintH264 || doDeintHevc;
+ var doVtTonemap = IsVideoToolboxTonemapAvailable(state, options);
+ var doOclTonemap = !doVtTonemap && IsHwTonemapAvailable(state, options);
+
+ var scaleFormat = string.Empty;
+ if (!string.Equals(state.VideoStream.PixelFormat, "yuv420p", StringComparison.OrdinalIgnoreCase))
{
- return swFilterChain;
+ // Use P010 for OpenCL tone mapping, otherwise force an 8bit output.
+ scaleFormat = doOclTonemap ? "p010le" : "nv12";
}
- // ffmpeg cannot use videotoolbox to scale
- var swScaleFilter = GetSwScaleFilter(state, options, vidEncoder, inW, inH, threeDFormat, reqW, reqH, reqMaxW, reqMaxH);
- newfilters.Add(swScaleFilter);
+ var hwScaleFilter = GetHwScaleFilter("vt", scaleFormat, inW, inH, reqW, reqH, reqMaxW, reqMaxH);
- // hwupload on videotoolbox encoders can automatically convert AVFrame into its CVPixelBuffer equivalent
- // videotoolbox will automatically convert the CVPixelBuffer to a pixel format the encoder supports, so we don't have to set a pixel format explicitly here
- // This will reduce CPU usage significantly on UHD videos with 10 bit colors because we bypassed the ffmpeg pixel format conversion
- newfilters.Add("hwupload");
+ var hasSubs = state.SubtitleStream is not null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
+ var hasTextSubs = hasSubs && state.SubtitleStream.IsTextSubtitleStream;
+ var hasGraphicalSubs = hasSubs && !state.SubtitleStream.IsTextSubtitleStream;
+ var hasAssSubs = hasSubs
+ && (string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase));
+
+ if (!isVtEncoder)
+ {
+ // should not happen.
+ return (null, null, null);
+ }
+
+ /* Make main filters for video stream */
+ var mainFilters = new List<string>();
+ // Color override is only required for OpenCL where hardware surface is in use
+ if (doOclTonemap)
+ {
+ mainFilters.Add(GetOverwriteColorPropertiesParam(state, doOclTonemap));
+ }
+
+ // INPUT videotoolbox/memory surface(vram/uma)
+ // this will pass-through automatically if in/out format matches.
+ mainFilters.Add("format=nv12|p010le|videotoolbox_vld");
+ mainFilters.Add("hwupload=derive_device=videotoolbox");
+
+ // hw deint
if (doDeintH2645)
{
var deintFilter = GetHwDeinterlaceFilter(state, options, "videotoolbox");
- newfilters.Add(deintFilter);
+ mainFilters.Add(deintFilter);
}
- return (newfilters, swFilterChain.SubFilters, swFilterChain.OverlayFilters);
+ if (doVtTonemap)
+ {
+ const string VtTonemapArgs = "color_matrix=bt709:color_primaries=bt709:color_transfer=bt709";
+
+ // scale_vt can handle scaling & tonemapping in one shot, just like vpp_qsv.
+ hwScaleFilter = string.IsNullOrEmpty(hwScaleFilter)
+ ? "scale_vt=" + VtTonemapArgs
+ : hwScaleFilter + ":" + VtTonemapArgs;
+ }
+
+ // hw scale & vt tonemap
+ mainFilters.Add(hwScaleFilter);
+
+ // ocl tonemap
+ if (doOclTonemap)
+ {
+ // map from videotoolbox to opencl via videotoolbox-opencl interop.
+ mainFilters.Add("hwmap=derive_device=opencl:mode=read");
+
+ var tonemapFilter = GetHwTonemapFilter(options, "opencl", "nv12");
+ mainFilters.Add(tonemapFilter);
+
+ // OUTPUT videotoolbox(nv12) surface(vram/uma)
+ // reverse-mapping via videotoolbox-opencl interop.
+ mainFilters.Add("hwmap=derive_device=videotoolbox:mode=write:reverse=1");
+ }
+
+ /* Make sub and overlay filters for subtitle stream */
+ var subFilters = new List<string>();
+ var overlayFilters = new List<string>();
+
+ if (hasSubs)
+ {
+ if (hasGraphicalSubs)
+ {
+ var subPreProcFilters = GetGraphicalSubPreProcessFilters(inW, inH, reqW, reqH, reqMaxW, reqMaxH);
+ subFilters.Add(subPreProcFilters);
+ subFilters.Add("format=bgra");
+ }
+ else if (hasTextSubs)
+ {
+ var framerate = state.VideoStream?.RealFrameRate;
+ var subFramerate = hasAssSubs ? Math.Min(framerate ?? 25, 60) : 10;
+
+ var alphaSrcFilter = GetAlphaSrcFilter(state, inW, inH, reqW, reqH, reqMaxW, reqMaxH, subFramerate);
+ var subTextSubtitlesFilter = GetTextSubtitlesFilter(state, true, true);
+ subFilters.Add(alphaSrcFilter);
+ subFilters.Add("format=bgra");
+ subFilters.Add(subTextSubtitlesFilter);
+ }
+
+ subFilters.Add("hwupload=derive_device=videotoolbox");
+ overlayFilters.Add("overlay_videotoolbox=eof_action=pass:repeatlast=0");
+ }
+
+ return (mainFilters, subFilters, overlayFilters);
}
/// <summary>
@@ -5995,22 +6108,37 @@ namespace MediaBrowser.Controller.MediaEncoding
|| string.Equals("yuvj420p", videoStream.PixelFormat, StringComparison.OrdinalIgnoreCase);
var is8_10bitSwFormatsVt = is8bitSwFormatsVt || string.Equals("yuv420p10le", videoStream.PixelFormat, StringComparison.OrdinalIgnoreCase);
+ // Hardware surface only make sense when interop with OpenCL
+ // VideoToolbox's Hardware surface in ffmpeg is not only slower than hwupload, but also breaks HDR in many cases.
+ // For example: https://trac.ffmpeg.org/ticket/10884
+ var useOclToneMapping = !IsVideoToolboxTonemapAvailable(state, options)
+ && options.EnableTonemapping
+ && state.VideoStream is not null
+ && GetVideoColorBitDepth(state) == 10
+ && state.VideoStream.VideoRange == VideoRange.HDR
+ && (state.VideoStream.VideoRangeType == VideoRangeType.HDR10
+ || state.VideoStream.VideoRangeType == VideoRangeType.HLG
+ || (state.VideoStream.VideoRangeType == VideoRangeType.DOVI
+ && string.Equals(state.VideoStream.Codec, "hevc", StringComparison.OrdinalIgnoreCase)));
+
+ var useHwSurface = useOclToneMapping && IsVideoToolboxFullSupported() && _mediaEncoder.SupportsFilter("alphasrc");
+
if (is8bitSwFormatsVt)
{
if (string.Equals("avc", videoStream.Codec, StringComparison.OrdinalIgnoreCase)
|| string.Equals("h264", videoStream.Codec, StringComparison.OrdinalIgnoreCase))
{
- return GetHwaccelType(state, options, "h264", bitDepth, false);
+ return GetHwaccelType(state, options, "h264", bitDepth, useHwSurface);
}
if (string.Equals("mpeg2video", videoStream.Codec, StringComparison.OrdinalIgnoreCase))
{
- return GetHwaccelType(state, options, "mpeg2video", bitDepth, false);
+ return GetHwaccelType(state, options, "mpeg2video", bitDepth, useHwSurface);
}
if (string.Equals("mpeg4", videoStream.Codec, StringComparison.OrdinalIgnoreCase))
{
- return GetHwaccelType(state, options, "mpeg4", bitDepth, false);
+ return GetHwaccelType(state, options, "mpeg4", bitDepth, useHwSurface);
}
}
@@ -6019,12 +6147,12 @@ namespace MediaBrowser.Controller.MediaEncoding
if (string.Equals("hevc", videoStream.Codec, StringComparison.OrdinalIgnoreCase)
|| string.Equals("h265", videoStream.Codec, StringComparison.OrdinalIgnoreCase))
{
- return GetHwaccelType(state, options, "hevc", bitDepth, false);
+ return GetHwaccelType(state, options, "hevc", bitDepth, useHwSurface);
}
if (string.Equals("vp9", videoStream.Codec, StringComparison.OrdinalIgnoreCase))
{
- return GetHwaccelType(state, options, "vp9", bitDepth, false);
+ return GetHwaccelType(state, options, "vp9", bitDepth, useHwSurface);
}
}
diff --git a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs
index ff91a60a7..a11440ced 100644
--- a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs
+++ b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs
@@ -1,7 +1,7 @@
#pragma warning disable CS1591
using System;
-using System.Collections.Concurrent;
+using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
@@ -9,6 +9,7 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AsyncKeyedLock;
+using MediaBrowser.Common;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Entities;
@@ -138,7 +139,8 @@ namespace MediaBrowser.MediaEncoding.Attachments
var processArgs = string.Format(
CultureInfo.InvariantCulture,
- "-dump_attachment:t \"\" -y -i {0} -t 0 -f null null",
+ "-dump_attachment:t \"\" -y {0} -i {1} -t 0 -f null null",
+ inputPath.EndsWith(".concat\"", StringComparison.OrdinalIgnoreCase) ? "-f concat -safe 0" : string.Empty,
inputPath);
int exitCode;
@@ -230,6 +232,8 @@ namespace MediaBrowser.MediaEncoding.Attachments
MediaAttachment mediaAttachment,
CancellationToken cancellationToken)
{
+ await CacheAllAttachments(mediaPath, inputFile, mediaSource, cancellationToken).ConfigureAwait(false);
+
var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, mediaAttachment.Index);
await ExtractAttachment(inputFile, mediaSource, mediaAttachment.Index, outputPath, cancellationToken)
.ConfigureAwait(false);
@@ -237,6 +241,159 @@ namespace MediaBrowser.MediaEncoding.Attachments
return outputPath;
}
+ private async Task CacheAllAttachments(
+ string mediaPath,
+ string inputFile,
+ MediaSourceInfo mediaSource,
+ CancellationToken cancellationToken)
+ {
+ var outputFileLocks = new List<AsyncKeyedLockReleaser<string>>();
+ var extractableAttachmentIds = new List<int>();
+
+ try
+ {
+ foreach (var attachment in mediaSource.MediaAttachments)
+ {
+ var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, attachment.Index);
+
+ var @outputFileLock = _semaphoreLocks.GetOrAdd(outputPath);
+ await @outputFileLock.SemaphoreSlim.WaitAsync(cancellationToken).ConfigureAwait(false);
+
+ if (File.Exists(outputPath))
+ {
+ @outputFileLock.Dispose();
+ continue;
+ }
+
+ outputFileLocks.Add(@outputFileLock);
+ extractableAttachmentIds.Add(attachment.Index);
+ }
+
+ if (extractableAttachmentIds.Count > 0)
+ {
+ await CacheAllAttachmentsInternal(mediaPath, inputFile, mediaSource, extractableAttachmentIds, cancellationToken).ConfigureAwait(false);
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex, "Unable to cache media attachments for File:{File}", mediaPath);
+ }
+ finally
+ {
+ foreach (var @outputFileLock in outputFileLocks)
+ {
+ @outputFileLock.Dispose();
+ }
+ }
+ }
+
+ private async Task CacheAllAttachmentsInternal(
+ string mediaPath,
+ string inputFile,
+ MediaSourceInfo mediaSource,
+ List<int> extractableAttachmentIds,
+ CancellationToken cancellationToken)
+ {
+ var outputPaths = new List<string>();
+ var processArgs = string.Empty;
+
+ foreach (var attachmentId in extractableAttachmentIds)
+ {
+ var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, attachmentId);
+
+ Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calculated path ({outputPath}) is not valid."));
+
+ outputPaths.Add(outputPath);
+ processArgs += string.Format(
+ CultureInfo.InvariantCulture,
+ " -dump_attachment:{0} \"{1}\"",
+ attachmentId,
+ EncodingUtils.NormalizePath(outputPath));
+ }
+
+ processArgs += string.Format(
+ CultureInfo.InvariantCulture,
+ " -i \"{0}\" -t 0 -f null null",
+ inputFile);
+
+ int exitCode;
+
+ using (var process = new Process
+ {
+ StartInfo = new ProcessStartInfo
+ {
+ Arguments = processArgs,
+ FileName = _mediaEncoder.EncoderPath,
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ WindowStyle = ProcessWindowStyle.Hidden,
+ ErrorDialog = false
+ },
+ EnableRaisingEvents = true
+ })
+ {
+ _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
+
+ process.Start();
+
+ try
+ {
+ await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
+ exitCode = process.ExitCode;
+ }
+ catch (OperationCanceledException)
+ {
+ process.Kill(true);
+ exitCode = -1;
+ }
+ }
+
+ var failed = false;
+
+ if (exitCode == -1)
+ {
+ failed = true;
+
+ foreach (var outputPath in outputPaths)
+ {
+ try
+ {
+ _logger.LogWarning("Deleting extracted media attachment due to failure: {Path}", outputPath);
+ _fileSystem.DeleteFile(outputPath);
+ }
+ catch (FileNotFoundException)
+ {
+ // ffmpeg failed, so it is normal that one or more expected output files do not exist.
+ // There is no need to log anything for the user here.
+ }
+ catch (IOException ex)
+ {
+ _logger.LogError(ex, "Error deleting extracted media attachment {Path}", outputPath);
+ }
+ }
+ }
+ else
+ {
+ foreach (var outputPath in outputPaths)
+ {
+ if (!File.Exists(outputPath))
+ {
+ _logger.LogError("ffmpeg media attachment extraction failed for {InputPath} to {OutputPath}", inputFile, outputPath);
+ failed = true;
+ continue;
+ }
+
+ _logger.LogInformation("ffmpeg media attachment extraction completed for {InputPath} to {OutputPath}", inputFile, outputPath);
+ }
+ }
+
+ if (failed)
+ {
+ throw new FfmpegException(
+ string.Format(CultureInfo.InvariantCulture, "ffmpeg media attachment extraction failed for {0}", inputFile));
+ }
+ }
+
private async Task ExtractAttachment(
string inputFile,
MediaSourceInfo mediaSource,
diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
index fdca28390..6549125d3 100644
--- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
@@ -128,6 +128,8 @@ namespace MediaBrowser.MediaEncoding.Encoder
"overlay_vulkan",
// videotoolbox
"yadif_videotoolbox",
+ "scale_vt",
+ "overlay_videotoolbox",
// rkrga
"scale_rkrga",
"vpp_rkrga",
diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
index 317aba418..5397a6752 100644
--- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
+++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
@@ -79,6 +79,7 @@ namespace MediaBrowser.MediaEncoding.Probing
"5/8erl in Ehr'n",
"Smith/Kotzen",
"We;Na",
+ "LSR/CITY",
};
/// <summary>
diff --git a/MediaBrowser.MediaEncoding/Transcoding/TranscodeManager.cs b/MediaBrowser.MediaEncoding/Transcoding/TranscodeManager.cs
index 8bace15c6..5d51a901a 100644
--- a/MediaBrowser.MediaEncoding/Transcoding/TranscodeManager.cs
+++ b/MediaBrowser.MediaEncoding/Transcoding/TranscodeManager.cs
@@ -724,7 +724,14 @@ public sealed class TranscodeManager : ITranscodeManager, IDisposable
foreach (var file in _fileSystem.GetFilePaths(path, true))
{
- _fileSystem.DeleteFile(file);
+ try
+ {
+ _fileSystem.DeleteFile(file);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error deleting encoded media cache file {Path}", path);
+ }
}
}
diff --git a/MediaBrowser.Model/Configuration/EncodingOptions.cs b/MediaBrowser.Model/Configuration/EncodingOptions.cs
index 84c735f9c..ab6f0d867 100644
--- a/MediaBrowser.Model/Configuration/EncodingOptions.cs
+++ b/MediaBrowser.Model/Configuration/EncodingOptions.cs
@@ -28,6 +28,7 @@ public class EncodingOptions
VaapiDevice = "/dev/dri/renderD128";
EnableTonemapping = false;
EnableVppTonemapping = false;
+ EnableVideoToolboxTonemapping = false;
TonemappingAlgorithm = "bt2390";
TonemappingMode = "auto";
TonemappingRange = "auto";
@@ -147,6 +148,11 @@ public class EncodingOptions
public bool EnableVppTonemapping { get; set; }
/// <summary>
+ /// Gets or sets a value indicating whether videotoolbox tonemapping is enabled.
+ /// </summary>
+ public bool EnableVideoToolboxTonemapping { get; set; }
+
+ /// <summary>
/// Gets or sets the tone-mapping algorithm.
/// </summary>
public string TonemappingAlgorithm { get; set; }
diff --git a/MediaBrowser.Model/Configuration/LibraryOptions.cs b/MediaBrowser.Model/Configuration/LibraryOptions.cs
index 42148a276..e777d5fd8 100644
--- a/MediaBrowser.Model/Configuration/LibraryOptions.cs
+++ b/MediaBrowser.Model/Configuration/LibraryOptions.cs
@@ -27,6 +27,8 @@ namespace MediaBrowser.Model.Configuration
SeasonZeroDisplayName = "Specials";
}
+ public bool Enabled { get; set; } = true;
+
public bool EnablePhotos { get; set; }
public bool EnableRealtimeMonitor { get; set; }
diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs
index e6b7f4d9b..55d1c3d51 100644
--- a/MediaBrowser.Model/Dlna/StreamBuilder.cs
+++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs
@@ -345,7 +345,7 @@ namespace MediaBrowser.Model.Dlna
/// <param name="profile">The <see cref="DeviceProfile"/>.</param>
/// <param name="type">The <see cref="DlnaProfileType"/>.</param>
/// <param name="playProfile">The <see cref="DirectPlayProfile"/> object to get the video stream from.</param>
- /// <returns>The the normalized input container.</returns>
+ /// <returns>The normalized input container.</returns>
public static string? NormalizeMediaSourceFormatIntoSingleContainer(string inputContainer, DeviceProfile? profile, DlnaProfileType type, DirectPlayProfile? playProfile = null)
{
if (string.IsNullOrEmpty(inputContainer))
@@ -557,7 +557,7 @@ namespace MediaBrowser.Model.Dlna
private static void SetStreamInfoOptionsFromDirectPlayProfile(MediaOptions options, MediaSourceInfo item, StreamInfo playlistItem, DirectPlayProfile? directPlayProfile)
{
var container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, options.Profile, DlnaProfileType.Video, directPlayProfile);
- var protocol = "http";
+ var protocol = MediaStreamProtocol.http;
item.TranscodingContainer = container;
item.TranscodingSubProtocol = protocol;
@@ -648,7 +648,7 @@ namespace MediaBrowser.Model.Dlna
if (directPlay == PlayMethod.DirectPlay)
{
- playlistItem.SubProtocol = "http";
+ playlistItem.SubProtocol = MediaStreamProtocol.http;
var audioStreamIndex = directPlayInfo.AudioStreamIndex ?? audioStream?.Index;
if (audioStreamIndex.HasValue)
@@ -803,7 +803,7 @@ namespace MediaBrowser.Model.Dlna
var videoCodecs = ContainerProfile.SplitValue(videoCodec);
// Enforce HLS video codec restrictions
- if (string.Equals(playlistItem.SubProtocol, "hls", StringComparison.OrdinalIgnoreCase))
+ if (playlistItem.SubProtocol == MediaStreamProtocol.hls)
{
videoCodecs = videoCodecs.Where(codec => _supportedHlsVideoCodecs.Contains(codec)).ToArray();
}
@@ -840,7 +840,7 @@ namespace MediaBrowser.Model.Dlna
var audioCodecs = ContainerProfile.SplitValue(audioCodec);
// Enforce HLS audio codec restrictions
- if (string.Equals(playlistItem.SubProtocol, "hls", StringComparison.OrdinalIgnoreCase))
+ if (playlistItem.SubProtocol == MediaStreamProtocol.hls)
{
if (string.Equals(playlistItem.Container, "mp4", StringComparison.OrdinalIgnoreCase))
{
@@ -1350,7 +1350,7 @@ namespace MediaBrowser.Model.Dlna
/// <param name="transcoderSupport">The <see cref="ITranscoderSupport"/>.</param>
/// <param name="outputContainer">The output container.</param>
/// <param name="transcodingSubProtocol">The subtitle transoding protocol.</param>
- /// <returns>The the normalized input container.</returns>
+ /// <returns>The normalized input container.</returns>
public static SubtitleProfile GetSubtitleProfile(
MediaSourceInfo mediaSource,
MediaStream subtitleStream,
@@ -1358,9 +1358,9 @@ namespace MediaBrowser.Model.Dlna
PlayMethod playMethod,
ITranscoderSupport transcoderSupport,
string? outputContainer,
- string? transcodingSubProtocol)
+ MediaStreamProtocol? transcodingSubProtocol)
{
- if (!subtitleStream.IsExternal && (playMethod != PlayMethod.Transcode || !string.Equals(transcodingSubProtocol, "hls", StringComparison.OrdinalIgnoreCase)))
+ if (!subtitleStream.IsExternal && (playMethod != PlayMethod.Transcode || transcodingSubProtocol != MediaStreamProtocol.hls))
{
// Look for supported embedded subs of the same format
foreach (var profile in subtitleProfiles)
diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs
index fc146df30..75e5b6d18 100644
--- a/MediaBrowser.Model/Dlna/StreamInfo.cs
+++ b/MediaBrowser.Model/Dlna/StreamInfo.cs
@@ -36,7 +36,7 @@ namespace MediaBrowser.Model.Dlna
public string? Container { get; set; }
- public string? SubProtocol { get; set; }
+ public MediaStreamProtocol SubProtocol { get; set; }
public long StartPositionTicks { get; set; }
@@ -670,7 +670,7 @@ namespace MediaBrowser.Model.Dlna
if (MediaType == DlnaProfileType.Audio)
{
- if (string.Equals(SubProtocol, "hls", StringComparison.OrdinalIgnoreCase))
+ if (SubProtocol == MediaStreamProtocol.hls)
{
return string.Format(CultureInfo.InvariantCulture, "{0}/audio/{1}/master.m3u8?{2}", baseUrl, ItemId, queryString);
}
@@ -678,7 +678,7 @@ namespace MediaBrowser.Model.Dlna
return string.Format(CultureInfo.InvariantCulture, "{0}/audio/{1}/stream{2}?{3}", baseUrl, ItemId, extension, queryString);
}
- if (string.Equals(SubProtocol, "hls", StringComparison.OrdinalIgnoreCase))
+ if (SubProtocol == MediaStreamProtocol.hls)
{
return string.Format(CultureInfo.InvariantCulture, "{0}/videos/{1}/master.m3u8?{2}", baseUrl, ItemId, queryString);
}
@@ -716,9 +716,7 @@ namespace MediaBrowser.Model.Dlna
long startPositionTicks = item.StartPositionTicks;
- var isHls = string.Equals(item.SubProtocol, "hls", StringComparison.OrdinalIgnoreCase);
-
- if (isHls)
+ if (item.SubProtocol == MediaStreamProtocol.hls)
{
list.Add(new NameValuePair("StartTimeTicks", string.Empty));
}
@@ -780,7 +778,7 @@ namespace MediaBrowser.Model.Dlna
list.Add(new NameValuePair("SubtitleCodec", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Embed ? subtitleCodecs : string.Empty));
- if (isHls)
+ if (item.SubProtocol == MediaStreamProtocol.hls)
{
list.Add(new NameValuePair("SegmentContainer", item.Container ?? string.Empty));
@@ -831,7 +829,7 @@ namespace MediaBrowser.Model.Dlna
var list = new List<SubtitleStreamInfo>();
// HLS will preserve timestamps so we can just grab the full subtitle stream
- long startPositionTicks = string.Equals(SubProtocol, "hls", StringComparison.OrdinalIgnoreCase)
+ long startPositionTicks = SubProtocol == MediaStreamProtocol.hls
? 0
: (PlayMethod == PlayMethod.Transcode && !CopyTimestamps ? StartPositionTicks : 0);
diff --git a/MediaBrowser.Model/Dlna/TranscodingProfile.cs b/MediaBrowser.Model/Dlna/TranscodingProfile.cs
index b4f6ec255..891448c66 100644
--- a/MediaBrowser.Model/Dlna/TranscodingProfile.cs
+++ b/MediaBrowser.Model/Dlna/TranscodingProfile.cs
@@ -3,6 +3,7 @@
using System;
using System.ComponentModel;
using System.Xml.Serialization;
+using Jellyfin.Data.Enums;
namespace MediaBrowser.Model.Dlna
{
@@ -26,7 +27,7 @@ namespace MediaBrowser.Model.Dlna
public string AudioCodec { get; set; } = string.Empty;
[XmlAttribute("protocol")]
- public string Protocol { get; set; } = string.Empty;
+ public MediaStreamProtocol Protocol { get; set; } = MediaStreamProtocol.http;
[DefaultValue(false)]
[XmlAttribute("estimateContentLength")]
diff --git a/MediaBrowser.Model/Drawing/ImageFormat.cs b/MediaBrowser.Model/Drawing/ImageFormat.cs
index 511c16a4e..6a586f6e3 100644
--- a/MediaBrowser.Model/Drawing/ImageFormat.cs
+++ b/MediaBrowser.Model/Drawing/ImageFormat.cs
@@ -6,28 +6,33 @@ namespace MediaBrowser.Model.Drawing
public enum ImageFormat
{
/// <summary>
- /// The BMP.
+ /// BMP format.
/// </summary>
Bmp,
/// <summary>
- /// The GIF.
+ /// GIF format.
/// </summary>
Gif,
/// <summary>
- /// The JPG.
+ /// JPG format.
/// </summary>
Jpg,
/// <summary>
- /// The PNG.
+ /// PNG format.
/// </summary>
Png,
/// <summary>
- /// The webp.
+ /// WEBP format.
/// </summary>
- Webp
+ Webp,
+
+ /// <summary>
+ /// SVG format.
+ /// </summary>
+ Svg,
}
}
diff --git a/MediaBrowser.Model/Drawing/ImageFormatExtensions.cs b/MediaBrowser.Model/Drawing/ImageFormatExtensions.cs
index 1bb24112e..1c60ba460 100644
--- a/MediaBrowser.Model/Drawing/ImageFormatExtensions.cs
+++ b/MediaBrowser.Model/Drawing/ImageFormatExtensions.cs
@@ -22,6 +22,7 @@ public static class ImageFormatExtensions
ImageFormat.Jpg => MediaTypeNames.Image.Jpeg,
ImageFormat.Png => "image/png",
ImageFormat.Webp => "image/webp",
+ ImageFormat.Svg => "image/svg+xml",
_ => throw new InvalidEnumArgumentException(nameof(format), (int)format, typeof(ImageFormat))
};
@@ -39,6 +40,7 @@ public static class ImageFormatExtensions
ImageFormat.Jpg => ".jpg",
ImageFormat.Png => ".png",
ImageFormat.Webp => ".webp",
+ ImageFormat.Svg => ".svg",
_ => throw new InvalidEnumArgumentException(nameof(format), (int)format, typeof(ImageFormat))
};
}
diff --git a/MediaBrowser.Model/Dto/MediaSourceInfo.cs b/MediaBrowser.Model/Dto/MediaSourceInfo.cs
index 520832aee..b7236b1e8 100644
--- a/MediaBrowser.Model/Dto/MediaSourceInfo.cs
+++ b/MediaBrowser.Model/Dto/MediaSourceInfo.cs
@@ -4,6 +4,8 @@
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
+using Jellyfin.Data.Enums;
+using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Session;
@@ -102,7 +104,7 @@ namespace MediaBrowser.Model.Dto
public string TranscodingUrl { get; set; }
- public string TranscodingSubProtocol { get; set; }
+ public MediaStreamProtocol TranscodingSubProtocol { get; set; }
public string TranscodingContainer { get; set; }
diff --git a/MediaBrowser.Model/Search/SearchQuery.cs b/MediaBrowser.Model/Search/SearchQuery.cs
index b91fd8657..8126b8bfc 100644
--- a/MediaBrowser.Model/Search/SearchQuery.cs
+++ b/MediaBrowser.Model/Search/SearchQuery.cs
@@ -1,4 +1,3 @@
-#nullable disable
#pragma warning disable CS1591
using System;
@@ -31,7 +30,7 @@ namespace MediaBrowser.Model.Search
/// Gets or sets the search term.
/// </summary>
/// <value>The search term.</value>
- public string SearchTerm { get; set; }
+ public required string SearchTerm { get; set; }
/// <summary>
/// Gets or sets the start index. Used for paging.
diff --git a/MediaBrowser.Model/System/LogFile.cs b/MediaBrowser.Model/System/LogFile.cs
index aec910c92..d4eb6bafc 100644
--- a/MediaBrowser.Model/System/LogFile.cs
+++ b/MediaBrowser.Model/System/LogFile.cs
@@ -1,4 +1,3 @@
-#nullable disable
#pragma warning disable CS1591
using System;
@@ -29,6 +28,6 @@ namespace MediaBrowser.Model.System
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
- public string Name { get; set; }
+ public required string Name { get; set; }
}
}
diff --git a/MediaBrowser.Model/Tasks/ITaskTrigger.cs b/MediaBrowser.Model/Tasks/ITaskTrigger.cs
index 0536f4ef7..bc8438855 100644
--- a/MediaBrowser.Model/Tasks/ITaskTrigger.cs
+++ b/MediaBrowser.Model/Tasks/ITaskTrigger.cs
@@ -24,7 +24,7 @@ namespace MediaBrowser.Model.Tasks
/// <param name="lastResult">Result of the last run triggered task.</param>
/// <param name="logger">The <see cref="ILogger"/>.</param>
/// <param name="taskName">The name of the task.</param>
- /// <param name="isApplicationStartup">Whether or not this is is fired during startup.</param>
+ /// <param name="isApplicationStartup">Whether or not this is fired during startup.</param>
void Start(TaskResult? lastResult, ILogger logger, string taskName, bool isApplicationStartup);
/// <summary>
diff --git a/MediaBrowser.Providers/Lyric/LyricManager.cs b/MediaBrowser.Providers/Lyric/LyricManager.cs
index 60734b89a..f4b18a8c1 100644
--- a/MediaBrowser.Providers/Lyric/LyricManager.cs
+++ b/MediaBrowser.Providers/Lyric/LyricManager.cs
@@ -155,13 +155,13 @@ public class LyricManager : ILyricManager
return null;
}
- var parsedLyrics = await InternalParseRemoteLyricsAsync(response, cancellationToken).ConfigureAwait(false);
+ var parsedLyrics = await InternalParseRemoteLyricsAsync(response.Format, response.Stream, cancellationToken).ConfigureAwait(false);
if (parsedLyrics is null)
{
return null;
}
- await TrySaveLyric(audio, libraryOptions, response).ConfigureAwait(false);
+ await TrySaveLyric(audio, libraryOptions, response.Format, response.Stream).ConfigureAwait(false);
return parsedLyrics;
}
catch (RateLimitExceededException)
@@ -182,19 +182,33 @@ public class LyricManager : ILyricManager
}
/// <inheritdoc />
- public async Task<LyricDto?> UploadLyricAsync(Audio audio, LyricResponse lyricResponse)
+ public async Task<LyricDto?> SaveLyricAsync(Audio audio, string format, string lyrics)
{
ArgumentNullException.ThrowIfNull(audio);
- ArgumentNullException.ThrowIfNull(lyricResponse);
+ ArgumentException.ThrowIfNullOrEmpty(format);
+ ArgumentException.ThrowIfNullOrEmpty(lyrics);
+
+ var bytes = Encoding.UTF8.GetBytes(lyrics);
+ using var lyricStream = new MemoryStream(bytes, 0, bytes.Length, false, true);
+ return await SaveLyricAsync(audio, format, lyricStream).ConfigureAwait(false);
+ }
+
+ /// <inheritdoc />
+ public async Task<LyricDto?> SaveLyricAsync(Audio audio, string format, Stream lyrics)
+ {
+ ArgumentNullException.ThrowIfNull(audio);
+ ArgumentException.ThrowIfNullOrEmpty(format);
+ ArgumentNullException.ThrowIfNull(lyrics);
+
var libraryOptions = BaseItem.LibraryManager.GetLibraryOptions(audio);
- var parsed = await InternalParseRemoteLyricsAsync(lyricResponse, CancellationToken.None).ConfigureAwait(false);
+ var parsed = await InternalParseRemoteLyricsAsync(format, lyrics, CancellationToken.None).ConfigureAwait(false);
if (parsed is null)
{
return null;
}
- await TrySaveLyric(audio, libraryOptions, lyricResponse).ConfigureAwait(false);
+ await TrySaveLyric(audio, libraryOptions, format, lyrics).ConfigureAwait(false);
return parsed;
}
@@ -209,7 +223,7 @@ public class LyricManager : ILyricManager
return null;
}
- return await InternalParseRemoteLyricsAsync(lyricResponse, cancellationToken).ConfigureAwait(false);
+ return await InternalParseRemoteLyricsAsync(lyricResponse.Format, lyricResponse.Stream, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
@@ -289,12 +303,12 @@ public class LyricManager : ILyricManager
private string GetProviderId(string name)
=> name.ToLowerInvariant().GetMD5().ToString("N", CultureInfo.InvariantCulture);
- private async Task<LyricDto?> InternalParseRemoteLyricsAsync(LyricResponse lyricResponse, CancellationToken cancellationToken)
+ private async Task<LyricDto?> InternalParseRemoteLyricsAsync(string format, Stream lyricStream, CancellationToken cancellationToken)
{
- lyricResponse.Stream.Seek(0, SeekOrigin.Begin);
- using var streamReader = new StreamReader(lyricResponse.Stream, leaveOpen: true);
+ lyricStream.Seek(0, SeekOrigin.Begin);
+ using var streamReader = new StreamReader(lyricStream, leaveOpen: true);
var lyrics = await streamReader.ReadToEndAsync(cancellationToken).ConfigureAwait(false);
- var lyricFile = new LyricFile($"lyric.{lyricResponse.Format}", lyrics);
+ var lyricFile = new LyricFile($"lyric.{format}", lyrics);
foreach (var parser in _lyricParsers)
{
var parsedLyrics = parser.ParseLyrics(lyricFile);
@@ -334,7 +348,7 @@ public class LyricManager : ILyricManager
var parsedResults = new List<RemoteLyricInfoDto>();
foreach (var result in searchResults)
{
- var parsedLyrics = await InternalParseRemoteLyricsAsync(result.Lyrics, cancellationToken).ConfigureAwait(false);
+ var parsedLyrics = await InternalParseRemoteLyricsAsync(result.Lyrics.Format, result.Lyrics.Stream, cancellationToken).ConfigureAwait(false);
if (parsedLyrics is null)
{
continue;
@@ -361,24 +375,23 @@ public class LyricManager : ILyricManager
private async Task TrySaveLyric(
Audio audio,
LibraryOptions libraryOptions,
- LyricResponse lyricResponse)
+ string format,
+ Stream lyricStream)
{
var saveInMediaFolder = libraryOptions.SaveLyricsWithMedia;
var memoryStream = new MemoryStream();
await using (memoryStream.ConfigureAwait(false))
{
- var stream = lyricResponse.Stream;
-
- await using (stream.ConfigureAwait(false))
+ await using (lyricStream.ConfigureAwait(false))
{
- stream.Seek(0, SeekOrigin.Begin);
- await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
+ lyricStream.Seek(0, SeekOrigin.Begin);
+ await lyricStream.CopyToAsync(memoryStream).ConfigureAwait(false);
memoryStream.Seek(0, SeekOrigin.Begin);
}
var savePaths = new List<string>();
- var saveFileName = Path.GetFileNameWithoutExtension(audio.Path) + "." + lyricResponse.Format.ReplaceLineEndings(string.Empty).ToLowerInvariant();
+ var saveFileName = Path.GetFileNameWithoutExtension(audio.Path) + "." + format.ReplaceLineEndings(string.Empty).ToLowerInvariant();
if (saveInMediaFolder)
{
diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs
index 81a299015..f34034964 100644
--- a/MediaBrowser.Providers/Manager/ProviderManager.cs
+++ b/MediaBrowser.Providers/Manager/ProviderManager.cs
@@ -9,6 +9,7 @@ using System.Net.Http;
using System.Net.Mime;
using System.Threading;
using System.Threading.Tasks;
+using AsyncKeyedLock;
using Jellyfin.Data.Enums;
using Jellyfin.Data.Events;
using Jellyfin.Extensions;
@@ -30,6 +31,7 @@ using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Providers;
+using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Book = MediaBrowser.Controller.Entities.Book;
using Episode = MediaBrowser.Controller.Entities.TV.Episode;
@@ -59,6 +61,13 @@ namespace MediaBrowser.Providers.Manager
private readonly ConcurrentDictionary<Guid, double> _activeRefreshes = new();
private readonly CancellationTokenSource _disposeCancellationTokenSource = new();
private readonly PriorityQueue<(Guid ItemId, MetadataRefreshOptions RefreshOptions), RefreshPriority> _refreshQueue = new();
+ private readonly IMemoryCache _memoryCache;
+
+ private readonly AsyncKeyedLocker<string> _imageSaveLock = new(o =>
+ {
+ o.PoolSize = 20;
+ o.PoolInitialFill = 1;
+ });
private IImageProvider[] _imageProviders = Array.Empty<IImageProvider>();
private IMetadataService[] _metadataServices = Array.Empty<IMetadataService>();
@@ -81,6 +90,7 @@ namespace MediaBrowser.Providers.Manager
/// <param name="libraryManager">The library manager.</param>
/// <param name="baseItemManager">The BaseItem manager.</param>
/// <param name="lyricManager">The lyric manager.</param>
+ /// <param name="memoryCache">The memory cache.</param>
public ProviderManager(
IHttpClientFactory httpClientFactory,
ISubtitleManager subtitleManager,
@@ -91,7 +101,8 @@ namespace MediaBrowser.Providers.Manager
IServerApplicationPaths appPaths,
ILibraryManager libraryManager,
IBaseItemManager baseItemManager,
- ILyricManager lyricManager)
+ ILyricManager lyricManager,
+ IMemoryCache memoryCache)
{
_logger = logger;
_httpClientFactory = httpClientFactory;
@@ -103,6 +114,7 @@ namespace MediaBrowser.Providers.Manager
_subtitleManager = subtitleManager;
_baseItemManager = baseItemManager;
_lyricManager = lyricManager;
+ _memoryCache = memoryCache;
}
/// <inheritdoc/>
@@ -150,52 +162,79 @@ namespace MediaBrowser.Providers.Manager
/// <inheritdoc/>
public async Task SaveImage(BaseItem item, string url, ImageType type, int? imageIndex, CancellationToken cancellationToken)
{
- var httpClient = _httpClientFactory.CreateClient(NamedClient.Default);
- using var response = await httpClient.GetAsync(url, cancellationToken).ConfigureAwait(false);
-
- if (response.StatusCode != HttpStatusCode.OK)
+ using (await _imageSaveLock.LockAsync(url, cancellationToken).ConfigureAwait(false))
{
- throw new HttpRequestException("Invalid image received.", null, response.StatusCode);
- }
+ if (_memoryCache.TryGetValue(url, out (string ContentType, byte[] ImageContents)? cachedValue)
+ && cachedValue is not null)
+ {
+ var imageContents = cachedValue.Value.ImageContents;
+ var cacheStream = new MemoryStream(imageContents, 0, imageContents.Length, false);
+ await using (cacheStream.ConfigureAwait(false))
+ {
+ await SaveImage(
+ item,
+ cacheStream,
+ cachedValue.Value.ContentType,
+ type,
+ imageIndex,
+ cancellationToken).ConfigureAwait(false);
+ return;
+ }
+ }
- var contentType = response.Content.Headers.ContentType?.MediaType;
+ var httpClient = _httpClientFactory.CreateClient(NamedClient.Default);
+ using var response = await httpClient.GetAsync(url, cancellationToken).ConfigureAwait(false);
- // Workaround for tvheadend channel icons
- // TODO: Isolate this hack into the tvh plugin
- if (string.IsNullOrEmpty(contentType))
- {
- if (url.Contains("/imagecache/", StringComparison.OrdinalIgnoreCase))
+ response.EnsureSuccessStatusCode();
+
+ var contentType = response.Content.Headers.ContentType?.MediaType;
+
+ // Workaround for tvheadend channel icons
+ // TODO: Isolate this hack into the tvh plugin
+ if (string.IsNullOrEmpty(contentType))
{
- contentType = "image/png";
+ if (url.Contains("/imagecache/", StringComparison.OrdinalIgnoreCase))
+ {
+ contentType = MediaTypeNames.Image.Png;
+ }
+ else
+ {
+ throw new HttpRequestException("Invalid image received: contentType not set.", null, response.StatusCode);
+ }
}
- else
+
+ // TVDb will sometimes serve a rubbish 404 html page with a 200 OK code, because reasons...
+ if (contentType.Equals(MediaTypeNames.Text.Html, StringComparison.OrdinalIgnoreCase))
{
- throw new HttpRequestException("Invalid image received: contentType not set.", null, response.StatusCode);
+ throw new HttpRequestException("Invalid image received.", null, HttpStatusCode.NotFound);
}
- }
- // TVDb will sometimes serve a rubbish 404 html page with a 200 OK code, because reasons...
- if (contentType.Equals(MediaTypeNames.Text.Html, StringComparison.OrdinalIgnoreCase))
- {
- throw new HttpRequestException("Invalid image received.", null, HttpStatusCode.NotFound);
- }
+ // some iptv/epg providers don't correctly report media type, extract from url if no extension found
+ if (string.IsNullOrWhiteSpace(MimeTypes.ToExtension(contentType)))
+ {
+ // Strip query parameters from url to get actual path.
+ contentType = MimeTypes.GetMimeType(new Uri(url).GetLeftPart(UriPartial.Path));
+ }
- // some iptv/epg providers don't correctly report media type, extract from url if no extension found
- if (string.IsNullOrWhiteSpace(MimeTypes.ToExtension(contentType)))
- {
- contentType = MimeTypes.GetMimeType(url);
- }
+ if (!contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
+ {
+ throw new HttpRequestException($"Request returned {contentType} instead of an image type", null, HttpStatusCode.NotFound);
+ }
- var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
- await using (stream.ConfigureAwait(false))
- {
- await SaveImage(
- item,
- stream,
- contentType,
- type,
- imageIndex,
- cancellationToken).ConfigureAwait(false);
+ var responseBytes = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
+ var stream = new MemoryStream(responseBytes, 0, responseBytes.Length, false);
+ await using (stream.ConfigureAwait(false))
+ {
+ _memoryCache.Set(url, (contentType, responseBytes), TimeSpan.FromSeconds(10));
+
+ await SaveImage(
+ item,
+ stream,
+ contentType,
+ type,
+ imageIndex,
+ cancellationToken).ConfigureAwait(false);
+ }
}
}
@@ -1115,6 +1154,7 @@ namespace MediaBrowser.Providers.Manager
}
_disposeCancellationTokenSource.Dispose();
+ _imageSaveLock.Dispose();
}
_disposed = true;
diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj
index 7a50c6cf4..dfb6319ac 100644
--- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj
+++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj
@@ -15,6 +15,7 @@
</ItemGroup>
<ItemGroup>
+ <PackageReference Include="AsyncKeyedLock" />
<PackageReference Include="LrcParser" />
<PackageReference Include="MetaBrainz.MusicBrainz" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" />
diff --git a/MediaBrowser.Providers/MediaInfo/AudioFileProber.cs b/MediaBrowser.Providers/MediaInfo/AudioFileProber.cs
index 0df624bdb..c9fe4c9b6 100644
--- a/MediaBrowser.Providers/MediaInfo/AudioFileProber.cs
+++ b/MediaBrowser.Providers/MediaInfo/AudioFileProber.cs
@@ -10,6 +10,7 @@ using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Lyrics;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Providers;
@@ -36,6 +37,7 @@ namespace MediaBrowser.Providers.MediaInfo
private readonly ILibraryManager _libraryManager;
private readonly IMediaSourceManager _mediaSourceManager;
private readonly LyricResolver _lyricResolver;
+ private readonly ILyricManager _lyricManager;
/// <summary>
/// Initializes a new instance of the <see cref="AudioFileProber"/> class.
@@ -46,13 +48,15 @@ namespace MediaBrowser.Providers.MediaInfo
/// <param name="itemRepo">Instance of the <see cref="IItemRepository"/> interface.</param>
/// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
/// <param name="lyricResolver">Instance of the <see cref="LyricResolver"/> interface.</param>
+ /// <param name="lyricManager">Instance of the <see cref="ILyricManager"/> interface.</param>
public AudioFileProber(
ILogger<AudioFileProber> logger,
IMediaSourceManager mediaSourceManager,
IMediaEncoder mediaEncoder,
IItemRepository itemRepo,
ILibraryManager libraryManager,
- LyricResolver lyricResolver)
+ LyricResolver lyricResolver,
+ ILyricManager lyricManager)
{
_logger = logger;
_mediaEncoder = mediaEncoder;
@@ -60,6 +64,7 @@ namespace MediaBrowser.Providers.MediaInfo
_libraryManager = libraryManager;
_mediaSourceManager = mediaSourceManager;
_lyricResolver = lyricResolver;
+ _lyricManager = lyricManager;
}
[GeneratedRegex(@"I:\s+(.*?)\s+LUFS")]
@@ -107,7 +112,7 @@ namespace MediaBrowser.Providers.MediaInfo
cancellationToken.ThrowIfCancellationRequested();
- Fetch(item, result, options, cancellationToken);
+ await FetchAsync(item, result, options, cancellationToken).ConfigureAwait(false);
}
var libraryOptions = _libraryManager.GetLibraryOptions(item);
@@ -211,7 +216,8 @@ namespace MediaBrowser.Providers.MediaInfo
/// <param name="mediaInfo">The <see cref="Model.MediaInfo.MediaInfo"/>.</param>
/// <param name="options">The <see cref="MetadataRefreshOptions"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
- protected void Fetch(
+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
+ private async Task FetchAsync(
Audio audio,
Model.MediaInfo.MediaInfo mediaInfo,
MetadataRefreshOptions options,
@@ -222,10 +228,11 @@ namespace MediaBrowser.Providers.MediaInfo
audio.RunTimeTicks = mediaInfo.RunTimeTicks;
audio.Size = mediaInfo.Size;
+ audio.PremiereDate = mediaInfo.PremiereDate;
if (!audio.IsLocked)
{
- FetchDataFromTags(audio, options);
+ await FetchDataFromTags(audio, options).ConfigureAwait(false);
}
var mediaStreams = new List<MediaStream>(mediaInfo.MediaStreams);
@@ -241,9 +248,9 @@ namespace MediaBrowser.Providers.MediaInfo
/// </summary>
/// <param name="audio">The <see cref="Audio"/>.</param>
/// <param name="options">The <see cref="MetadataRefreshOptions"/>.</param>
- private void FetchDataFromTags(Audio audio, MetadataRefreshOptions options)
+ private async Task FetchDataFromTags(Audio audio, MetadataRefreshOptions options)
{
- var file = TagLib.File.Create(audio.Path);
+ using var file = TagLib.File.Create(audio.Path);
var tagTypes = file.TagTypesOnDisk;
Tag? tags = null;
@@ -342,9 +349,9 @@ namespace MediaBrowser.Providers.MediaInfo
}
}
- if (!audio.LockedFields.Contains(MetadataField.Name))
+ if (!audio.LockedFields.Contains(MetadataField.Name) && !string.IsNullOrEmpty(tags.Title))
{
- audio.Name = options.ReplaceAllMetadata || string.IsNullOrEmpty(audio.Name) ? tags.Title : audio.Name;
+ audio.Name = tags.Title;
}
if (options.ReplaceAllMetadata)
@@ -364,7 +371,11 @@ namespace MediaBrowser.Providers.MediaInfo
{
var year = Convert.ToInt32(tags.Year);
audio.ProductionYear = year;
- audio.PremiereDate = new DateTime(year, 01, 01);
+
+ if (!audio.PremiereDate.HasValue)
+ {
+ audio.PremiereDate = new DateTime(year, 01, 01);
+ }
}
if (!audio.LockedFields.Contains(MetadataField.Genres))
@@ -398,6 +409,14 @@ namespace MediaBrowser.Providers.MediaInfo
{
audio.SetProviderId(MetadataProvider.MusicBrainzTrack, tags.MusicBrainzTrackId);
}
+
+ // Save extracted lyrics if they exist,
+ // and if we are replacing all metadata or the audio doesn't yet have lyrics.
+ if (!string.IsNullOrWhiteSpace(tags.Lyrics)
+ && (options.ReplaceAllMetadata || audio.GetMediaStreams().All(s => s.Type != MediaStreamType.Lyric)))
+ {
+ await _lyricManager.SaveLyricAsync(audio, "lrc", tags.Lyrics).ConfigureAwait(false);
+ }
}
}
diff --git a/MediaBrowser.Providers/MediaInfo/ProbeProvider.cs b/MediaBrowser.Providers/MediaInfo/ProbeProvider.cs
index 8bb874f0d..8bb8d5bb4 100644
--- a/MediaBrowser.Providers/MediaInfo/ProbeProvider.cs
+++ b/MediaBrowser.Providers/MediaInfo/ProbeProvider.cs
@@ -13,6 +13,7 @@ using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Lyrics;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Providers;
@@ -64,6 +65,7 @@ namespace MediaBrowser.Providers.MediaInfo
/// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/>.</param>
/// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
/// <param name="namingOptions">The <see cref="NamingOptions"/>.</param>
+ /// <param name="lyricManager">Instance of the <see cref="ILyricManager"/> interface.</param>
public ProbeProvider(
IMediaSourceManager mediaSourceManager,
IMediaEncoder mediaEncoder,
@@ -77,7 +79,8 @@ namespace MediaBrowser.Providers.MediaInfo
ILibraryManager libraryManager,
IFileSystem fileSystem,
ILoggerFactory loggerFactory,
- NamingOptions namingOptions)
+ NamingOptions namingOptions,
+ ILyricManager lyricManager)
{
_logger = loggerFactory.CreateLogger<ProbeProvider>();
_audioResolver = new AudioResolver(loggerFactory.CreateLogger<AudioResolver>(), localization, mediaEncoder, fileSystem, namingOptions);
@@ -105,7 +108,8 @@ namespace MediaBrowser.Providers.MediaInfo
mediaEncoder,
itemRepo,
libraryManager,
- _lyricResolver);
+ _lyricResolver,
+ lyricManager);
}
/// <inheritdoc />
diff --git a/MediaBrowser.Providers/Plugins/Omdb/JsonOmdbNotAvailableStringConverter.cs b/MediaBrowser.Providers/Plugins/Omdb/JsonOmdbNotAvailableStringConverter.cs
index f35880a04..7e9befa8c 100644
--- a/MediaBrowser.Providers/Plugins/Omdb/JsonOmdbNotAvailableStringConverter.cs
+++ b/MediaBrowser.Providers/Plugins/Omdb/JsonOmdbNotAvailableStringConverter.cs
@@ -1,6 +1,7 @@
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
+using Jellyfin.Extensions.Json;
namespace MediaBrowser.Providers.Plugins.Omdb
{
@@ -12,7 +13,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb
/// <inheritdoc />
public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
- if (reader.TokenType == JsonTokenType.Null)
+ if (reader.IsNull())
{
return null;
}
diff --git a/src/Jellyfin.Drawing.Skia/SkiaEncoder.cs b/src/Jellyfin.Drawing.Skia/SkiaEncoder.cs
index 4ae5a9a48..a158e5c86 100644
--- a/src/Jellyfin.Drawing.Skia/SkiaEncoder.cs
+++ b/src/Jellyfin.Drawing.Skia/SkiaEncoder.cs
@@ -19,8 +19,8 @@ namespace Jellyfin.Drawing.Skia;
/// </summary>
public class SkiaEncoder : IImageEncoder
{
+ private const string SvgFormat = "svg";
private static readonly HashSet<string> _transparentImageTypes = new(StringComparer.OrdinalIgnoreCase) { ".png", ".gif", ".webp" };
-
private readonly ILogger<SkiaEncoder> _logger;
private readonly IApplicationPaths _appPaths;
private static readonly SKImageFilter _imageFilter;
@@ -89,12 +89,13 @@ public class SkiaEncoder : IImageEncoder
// working on windows at least
"cr2",
"nef",
- "arw"
+ "arw",
+ SvgFormat
};
/// <inheritdoc/>
public IReadOnlyCollection<ImageFormat> SupportedOutputFormats
- => new HashSet<ImageFormat> { ImageFormat.Webp, ImageFormat.Jpg, ImageFormat.Png };
+ => new HashSet<ImageFormat> { ImageFormat.Webp, ImageFormat.Jpg, ImageFormat.Png, ImageFormat.Svg };
/// <summary>
/// Check if the native lib is available.
@@ -187,7 +188,8 @@ public class SkiaEncoder : IImageEncoder
ArgumentException.ThrowIfNullOrEmpty(path);
var extension = Path.GetExtension(path.AsSpan()).TrimStart('.');
- if (!SupportedInputFormats.Contains(extension, StringComparison.OrdinalIgnoreCase))
+ if (!SupportedInputFormats.Contains(extension, StringComparison.OrdinalIgnoreCase)
+ || extension.Equals(SvgFormat, StringComparison.OrdinalIgnoreCase))
{
_logger.LogDebug("Unable to compute blur hash due to unsupported format: {ImagePath}", path);
return string.Empty;
@@ -312,6 +314,31 @@ public class SkiaEncoder : IImageEncoder
return Decode(path, false, orientation, out _);
}
+ private SKBitmap? GetBitmapFromSvg(string path)
+ {
+ if (!File.Exists(path))
+ {
+ throw new FileNotFoundException("File not found", path);
+ }
+
+ using var svg = SKSvg.CreateFromFile(path);
+ if (svg.Drawable is null)
+ {
+ return null;
+ }
+
+ var width = (int)Math.Round(svg.Drawable.Bounds.Width);
+ var height = (int)Math.Round(svg.Drawable.Bounds.Height);
+
+ var bitmap = new SKBitmap(width, height);
+ using var canvas = new SKCanvas(bitmap);
+ canvas.DrawPicture(svg.Picture);
+ canvas.Flush();
+ canvas.Save();
+
+ return bitmap;
+ }
+
private SKBitmap OrientImage(SKBitmap bitmap, SKEncodedOrigin origin)
{
var needsFlip = origin is SKEncodedOrigin.LeftBottom or SKEncodedOrigin.LeftTop or SKEncodedOrigin.RightBottom or SKEncodedOrigin.RightTop;
@@ -402,6 +429,12 @@ public class SkiaEncoder : IImageEncoder
return inputPath;
}
+ if (outputFormat == ImageFormat.Svg
+ && !inputFormat.Equals(SvgFormat, StringComparison.OrdinalIgnoreCase))
+ {
+ throw new ArgumentException($"Requested svg output from {inputFormat} input");
+ }
+
var skiaOutputFormat = GetImageFormat(outputFormat);
var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
@@ -409,7 +442,10 @@ public class SkiaEncoder : IImageEncoder
var blur = options.Blur ?? 0;
var hasIndicator = options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);
- using var bitmap = GetBitmap(inputPath, autoOrient, orientation);
+ using var bitmap = inputFormat.Equals(SvgFormat, StringComparison.OrdinalIgnoreCase)
+ ? GetBitmapFromSvg(inputPath)
+ : GetBitmap(inputPath, autoOrient, orientation);
+
if (bitmap is null)
{
throw new InvalidDataException($"Skia unable to read image {inputPath}");
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonDefaultStringEnumConverter.cs b/src/Jellyfin.Extensions/Json/Converters/JsonDefaultStringEnumConverter.cs
new file mode 100644
index 000000000..06ecfc558
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonDefaultStringEnumConverter.cs
@@ -0,0 +1,49 @@
+using System;
+using System.ComponentModel;
+using System.Reflection;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Jellyfin.Extensions.Json.Converters;
+
+/// <summary>
+/// Json unknown enum converter.
+/// </summary>
+/// <typeparam name="T">The type of enum.</typeparam>
+public class JsonDefaultStringEnumConverter<T> : JsonConverter<T>
+ where T : struct, Enum
+{
+ private readonly JsonConverter<T> _baseConverter;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="JsonDefaultStringEnumConverter{T}"/> class.
+ /// </summary>
+ /// <param name="baseConverter">The base json converter.</param>
+ public JsonDefaultStringEnumConverter(JsonConverter<T> baseConverter)
+ {
+ _baseConverter = baseConverter;
+ }
+
+ /// <inheritdoc />
+ public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ if (reader.IsNull() || reader.IsEmptyString())
+ {
+ var customValueAttribute = typeToConvert.GetCustomAttribute<DefaultValueAttribute>();
+ if (customValueAttribute?.Value is null)
+ {
+ throw new InvalidOperationException($"Default value not set for '{typeToConvert.Name}'");
+ }
+
+ return (T)customValueAttribute.Value;
+ }
+
+ return _baseConverter.Read(ref reader, typeToConvert, options);
+ }
+
+ /// <inheritdoc />
+ public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
+ {
+ _baseConverter.Write(writer, value, options);
+ }
+}
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonDefaultStringEnumConverterFactory.cs b/src/Jellyfin.Extensions/Json/Converters/JsonDefaultStringEnumConverterFactory.cs
new file mode 100644
index 000000000..5a9bf546e
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonDefaultStringEnumConverterFactory.cs
@@ -0,0 +1,31 @@
+using System;
+using System.ComponentModel;
+using System.Reflection;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Jellyfin.Extensions.Json.Converters;
+
+/// <summary>
+/// Utilizes the JsonStringEnumConverter and sets a default value if not provided.
+/// </summary>
+public class JsonDefaultStringEnumConverterFactory : JsonConverterFactory
+{
+ private static readonly JsonStringEnumConverter _baseConverterFactory = new();
+
+ /// <inheritdoc />
+ public override bool CanConvert(Type typeToConvert)
+ {
+ return _baseConverterFactory.CanConvert(typeToConvert)
+ && typeToConvert.IsDefined(typeof(DefaultValueAttribute));
+ }
+
+ /// <inheritdoc />
+ public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)
+ {
+ var baseConverter = _baseConverterFactory.CreateConverter(typeToConvert, options);
+ var converterType = typeof(JsonDefaultStringEnumConverter<>).MakeGenericType(typeToConvert);
+
+ return (JsonConverter?)Activator.CreateInstance(converterType, baseConverter);
+ }
+}
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonGuidConverter.cs b/src/Jellyfin.Extensions/Json/Converters/JsonGuidConverter.cs
index ea6d141cb..2964c6943 100644
--- a/src/Jellyfin.Extensions/Json/Converters/JsonGuidConverter.cs
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonGuidConverter.cs
@@ -12,7 +12,7 @@ namespace Jellyfin.Extensions.Json.Converters
{
/// <inheritdoc />
public override Guid Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
- => reader.TokenType == JsonTokenType.Null
+ => reader.IsNull()
? Guid.Empty
: ReadInternal(ref reader);
diff --git a/src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs b/src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs
index 28437023f..94004fa49 100644
--- a/src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs
+++ b/src/Jellyfin.Extensions/Json/Converters/JsonNullableStructConverter.cs
@@ -15,10 +15,7 @@ namespace Jellyfin.Extensions.Json.Converters
/// <inheritdoc />
public override TStruct? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
- // Token is empty string.
- if (reader.TokenType == JsonTokenType.String
- && ((reader.HasValueSequence && reader.ValueSequence.IsEmpty)
- || (!reader.HasValueSequence && reader.ValueSpan.IsEmpty)))
+ if (reader.IsEmptyString())
{
return null;
}
diff --git a/src/Jellyfin.Extensions/Json/JsonDefaults.cs b/src/Jellyfin.Extensions/Json/JsonDefaults.cs
index 9e6d4c3f8..cbe5849ec 100644
--- a/src/Jellyfin.Extensions/Json/JsonDefaults.cs
+++ b/src/Jellyfin.Extensions/Json/JsonDefaults.cs
@@ -38,6 +38,7 @@ namespace Jellyfin.Extensions.Json
new JsonNullableGuidConverter(),
new JsonVersionConverter(),
new JsonFlagEnumConverterFactory(),
+ new JsonDefaultStringEnumConverterFactory(),
new JsonStringEnumConverter(),
new JsonNullableStructConverterFactory(),
new JsonDateTimeConverter(),
diff --git a/src/Jellyfin.Extensions/Json/Utf8JsonExtensions.cs b/src/Jellyfin.Extensions/Json/Utf8JsonExtensions.cs
new file mode 100644
index 000000000..d06508a26
--- /dev/null
+++ b/src/Jellyfin.Extensions/Json/Utf8JsonExtensions.cs
@@ -0,0 +1,27 @@
+using System.Text.Json;
+
+namespace Jellyfin.Extensions.Json;
+
+/// <summary>
+/// Extensions for Utf8JsonReader and Utf8JsonWriter.
+/// </summary>
+public static class Utf8JsonExtensions
+{
+ /// <summary>
+ /// Determines if the reader contains an empty string.
+ /// </summary>
+ /// <param name="reader">The reader.</param>
+ /// <returns>Whether the reader contains an empty string.</returns>
+ public static bool IsEmptyString(this Utf8JsonReader reader)
+ => reader.TokenType == JsonTokenType.String
+ && ((reader.HasValueSequence && reader.ValueSequence.IsEmpty)
+ || (!reader.HasValueSequence && reader.ValueSpan.IsEmpty));
+
+ /// <summary>
+ /// Determines if the reader contains a null value.
+ /// </summary>
+ /// <param name="reader">The reader.</param>
+ /// <returns>Whether the reader contains null.</returns>
+ public static bool IsNull(this Utf8JsonReader reader)
+ => reader.TokenType == JsonTokenType.Null;
+}
diff --git a/src/Jellyfin.LiveTv/Channels/ChannelManager.cs b/src/Jellyfin.LiveTv/Channels/ChannelManager.cs
index 1948a9ab9..cce2911dc 100644
--- a/src/Jellyfin.LiveTv/Channels/ChannelManager.cs
+++ b/src/Jellyfin.LiveTv/Channels/ChannelManager.cs
@@ -570,7 +570,6 @@ namespace Jellyfin.LiveTv.Channels
return new ChannelFeatures(channel.Name, channel.Id)
{
CanFilter = !features.MaxPageSize.HasValue,
- CanSearch = provider is ISearchableChannel,
ContentTypes = features.ContentTypes.ToArray(),
DefaultSortFields = features.DefaultSortFields.ToArray(),
MaxPageSize = features.MaxPageSize,
diff --git a/src/Jellyfin.LiveTv/Guide/GuideManager.cs b/src/Jellyfin.LiveTv/Guide/GuideManager.cs
index 39f174cc2..093970c38 100644
--- a/src/Jellyfin.LiveTv/Guide/GuideManager.cs
+++ b/src/Jellyfin.LiveTv/Guide/GuideManager.cs
@@ -27,6 +27,8 @@ public class GuideManager : IGuideManager
private const string EtagKey = "ProgramEtag";
private const string ExternalServiceTag = "ExternalServiceId";
+ private static readonly ParallelOptions _cacheParallelOptions = new() { MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, 10) };
+
private readonly ILogger<GuideManager> _logger;
private readonly IConfigurationManager _config;
private readonly IFileSystem _fileSystem;
@@ -209,6 +211,7 @@ public class GuideManager : IGuideManager
_logger.LogInformation("Refreshing guide with {0} days of guide data", guideDays);
+ var maxCacheDate = DateTime.UtcNow.AddDays(2);
foreach (var currentChannel in list)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -263,6 +266,7 @@ public class GuideManager : IGuideManager
if (newPrograms.Count > 0)
{
_libraryManager.CreateItems(newPrograms, null, cancellationToken);
+ await PrecacheImages(newPrograms, maxCacheDate).ConfigureAwait(false);
}
if (updatedPrograms.Count > 0)
@@ -272,6 +276,7 @@ public class GuideManager : IGuideManager
currentChannel,
ItemUpdateType.MetadataImport,
cancellationToken).ConfigureAwait(false);
+ await PrecacheImages(updatedPrograms, maxCacheDate).ConfigureAwait(false);
}
currentChannel.IsMovie = isMovie;
@@ -708,4 +713,41 @@ public class GuideManager : IGuideManager
return (item, isNew, isUpdated);
}
+
+ private async Task PrecacheImages(IReadOnlyList<BaseItem> programs, DateTime maxCacheDate)
+ {
+ await Parallel.ForEachAsync(
+ programs
+ .Where(p => p.EndDate.HasValue && p.EndDate.Value < maxCacheDate)
+ .DistinctBy(p => p.Id),
+ _cacheParallelOptions,
+ async (program, cancellationToken) =>
+ {
+ for (var i = 0; i < program.ImageInfos.Length; i++)
+ {
+ if (cancellationToken.IsCancellationRequested)
+ {
+ return;
+ }
+
+ var imageInfo = program.ImageInfos[i];
+ if (!imageInfo.IsLocalFile)
+ {
+ try
+ {
+ program.ImageInfos[i] = await _libraryManager.ConvertImageToLocal(
+ program,
+ imageInfo,
+ imageIndex: 0,
+ removeOnFailure: false)
+ .ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex, "Unable to precache {Url}", imageInfo.Path);
+ }
+ }
+ }
+ }).ConfigureAwait(false);
+ }
}
diff --git a/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonDefaultStringEnumConverterTests.cs b/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonDefaultStringEnumConverterTests.cs
new file mode 100644
index 000000000..5d86d6bae
--- /dev/null
+++ b/tests/Jellyfin.Extensions.Tests/Json/Converters/JsonDefaultStringEnumConverterTests.cs
@@ -0,0 +1,112 @@
+using System.Text.Json;
+using Jellyfin.Data.Enums;
+using Jellyfin.Extensions.Json.Converters;
+using Xunit;
+
+namespace Jellyfin.Extensions.Tests.Json.Converters;
+
+public class JsonDefaultStringEnumConverterTests
+{
+ private readonly JsonSerializerOptions _jsonOptions = new() { Converters = { new JsonDefaultStringEnumConverterFactory() } };
+
+ /// <summary>
+ /// Test to ensure that `null` and empty string are deserialized to the default value.
+ /// </summary>
+ /// <param name="input">The input string.</param>
+ /// <param name="output">The expected enum value.</param>
+ [Theory]
+ [InlineData("\"\"", MediaStreamProtocol.http)]
+ [InlineData("\"Http\"", MediaStreamProtocol.http)]
+ [InlineData("\"Hls\"", MediaStreamProtocol.hls)]
+ public void Deserialize_Enum_Direct(string input, MediaStreamProtocol output)
+ {
+ var value = JsonSerializer.Deserialize<MediaStreamProtocol>(input, _jsonOptions);
+ Assert.Equal(output, value);
+ }
+
+ /// <summary>
+ /// Test to ensure that `null` and empty string are deserialized to the default value.
+ /// </summary>
+ /// <param name="input">The input string.</param>
+ /// <param name="output">The expected enum value.</param>
+ [Theory]
+ [InlineData(null, MediaStreamProtocol.http)]
+ [InlineData("\"\"", MediaStreamProtocol.http)]
+ [InlineData("\"Http\"", MediaStreamProtocol.http)]
+ [InlineData("\"Hls\"", MediaStreamProtocol.hls)]
+ public void Deserialize_Enum(string? input, MediaStreamProtocol output)
+ {
+ input ??= "null";
+ var json = $"{{ \"EnumValue\": {input} }}";
+ var value = JsonSerializer.Deserialize<TestClass>(json, _jsonOptions);
+ Assert.NotNull(value);
+ Assert.Equal(output, value.EnumValue);
+ }
+
+ /// <summary>
+ /// Test to ensure that empty string is deserialized to the default value,
+ /// and `null` is deserialized to `null`.
+ /// </summary>
+ /// <param name="input">The input string.</param>
+ /// <param name="output">The expected enum value.</param>
+ [Theory]
+ [InlineData(null, null)]
+ [InlineData("\"\"", MediaStreamProtocol.http)]
+ [InlineData("\"Http\"", MediaStreamProtocol.http)]
+ [InlineData("\"Hls\"", MediaStreamProtocol.hls)]
+ public void Deserialize_Enum_Nullable(string? input, MediaStreamProtocol? output)
+ {
+ input ??= "null";
+ var json = $"{{ \"EnumValue\": {input} }}";
+ var value = JsonSerializer.Deserialize<NullTestClass>(json, _jsonOptions);
+ Assert.NotNull(value);
+ Assert.Equal(output, value.EnumValue);
+ }
+
+ /// <summary>
+ /// Ensures that the roundtrip serialization & deserialization is successful.
+ /// </summary>
+ /// <param name="input">Input enum.</param>
+ /// <param name="output">Output enum.</param>
+ [Theory]
+ [InlineData(MediaStreamProtocol.http, MediaStreamProtocol.http)]
+ [InlineData(MediaStreamProtocol.hls, MediaStreamProtocol.hls)]
+ public void Enum_RoundTrip(MediaStreamProtocol input, MediaStreamProtocol output)
+ {
+ var inputObj = new TestClass { EnumValue = input };
+
+ var outputObj = JsonSerializer.Deserialize<TestClass>(JsonSerializer.Serialize(inputObj, _jsonOptions), _jsonOptions);
+
+ Assert.NotNull(outputObj);
+ Assert.Equal(output, outputObj.EnumValue);
+ }
+
+ /// <summary>
+ /// Ensures that the roundtrip serialization & deserialization is successful, including null.
+ /// </summary>
+ /// <param name="input">Input enum.</param>
+ /// <param name="output">Output enum.</param>
+ [Theory]
+ [InlineData(MediaStreamProtocol.http, MediaStreamProtocol.http)]
+ [InlineData(MediaStreamProtocol.hls, MediaStreamProtocol.hls)]
+ [InlineData(null, null)]
+ public void Enum_RoundTrip_Nullable(MediaStreamProtocol? input, MediaStreamProtocol? output)
+ {
+ var inputObj = new NullTestClass { EnumValue = input };
+
+ var outputObj = JsonSerializer.Deserialize<NullTestClass>(JsonSerializer.Serialize(inputObj, _jsonOptions), _jsonOptions);
+
+ Assert.NotNull(outputObj);
+ Assert.Equal(output, outputObj.EnumValue);
+ }
+
+ private sealed class TestClass
+ {
+ public MediaStreamProtocol EnumValue { get; set; }
+ }
+
+ private sealed class NullTestClass
+ {
+ public MediaStreamProtocol? EnumValue { get; set; }
+ }
+}
diff --git a/tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs b/tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs
index 909de8f72..6d88dbb8e 100644
--- a/tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs
+++ b/tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs
@@ -5,6 +5,7 @@ using System.Linq;
using System.Runtime.Serialization;
using System.Text.Json;
using System.Threading.Tasks;
+using Jellyfin.Data.Enums;
using Jellyfin.Extensions.Json;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
@@ -388,21 +389,21 @@ namespace Jellyfin.Model.Tests
// Assert.Equal("webm", val.Container);
Assert.Equal(streamInfo.Container, uri.Extension);
Assert.Equal("stream", uri.Filename);
- Assert.Equal("http", streamInfo.SubProtocol);
+ Assert.Equal(MediaStreamProtocol.http, streamInfo.SubProtocol);
}
else if (transcodeProtocol.Equals("HLS.mp4", StringComparison.Ordinal))
{
Assert.Equal("mp4", streamInfo.Container);
Assert.Equal("m3u8", uri.Extension);
Assert.Equal("master", uri.Filename);
- Assert.Equal("hls", streamInfo.SubProtocol);
+ Assert.Equal(MediaStreamProtocol.hls, streamInfo.SubProtocol);
}
else
{
Assert.Equal("ts", streamInfo.Container);
Assert.Equal("m3u8", uri.Extension);
Assert.Equal("master", uri.Filename);
- Assert.Equal("hls", streamInfo.SubProtocol);
+ Assert.Equal(MediaStreamProtocol.hls, streamInfo.SubProtocol);
}
// Full transcode
@@ -488,7 +489,7 @@ namespace Jellyfin.Model.Tests
}
else if (playMethod is null)
{
- Assert.Null(streamInfo.SubProtocol);
+ Assert.Equal(MediaStreamProtocol.http, streamInfo.SubProtocol);
Assert.Equal("stream", uri.Filename);
Assert.False(streamInfo.EstimateContentLength);
diff --git a/tests/Jellyfin.Model.Tests/Drawing/ImageFormatExtensionsTests.cs b/tests/Jellyfin.Model.Tests/Drawing/ImageFormatExtensionsTests.cs
index 198ad5a27..2399a10a3 100644
--- a/tests/Jellyfin.Model.Tests/Drawing/ImageFormatExtensionsTests.cs
+++ b/tests/Jellyfin.Model.Tests/Drawing/ImageFormatExtensionsTests.cs
@@ -27,7 +27,7 @@ public static class ImageFormatExtensionsTests
[InlineData((ImageFormat)int.MinValue)]
[InlineData((ImageFormat)int.MaxValue)]
[InlineData((ImageFormat)(-1))]
- [InlineData((ImageFormat)5)]
+ [InlineData((ImageFormat)6)]
public static void GetMimeType_Valid_ThrowsInvalidEnumArgumentException(ImageFormat format)
=> Assert.Throws<InvalidEnumArgumentException>(() => format.GetMimeType());
@@ -40,7 +40,7 @@ public static class ImageFormatExtensionsTests
[InlineData((ImageFormat)int.MinValue)]
[InlineData((ImageFormat)int.MaxValue)]
[InlineData((ImageFormat)(-1))]
- [InlineData((ImageFormat)5)]
+ [InlineData((ImageFormat)6)]
public static void GetExtension_Valid_ThrowsInvalidEnumArgumentException(ImageFormat format)
=> Assert.Throws<InvalidEnumArgumentException>(() => format.GetExtension());
}
diff --git a/tests/Jellyfin.Providers.Tests/Manager/ProviderManagerTests.cs b/tests/Jellyfin.Providers.Tests/Manager/ProviderManagerTests.cs
index 478db6941..6fccce049 100644
--- a/tests/Jellyfin.Providers.Tests/Manager/ProviderManagerTests.cs
+++ b/tests/Jellyfin.Providers.Tests/Manager/ProviderManagerTests.cs
@@ -17,6 +17,7 @@ using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
+using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
@@ -572,7 +573,8 @@ namespace Jellyfin.Providers.Tests.Manager
Mock.Of<IServerApplicationPaths>(),
libraryManager.Object,
baseItemManager!,
- Mock.Of<ILyricManager>());
+ Mock.Of<ILyricManager>(),
+ Mock.Of<IMemoryCache>());
return providerManager;
}
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest.json
index 57367ce88..57367ce88 100644
--- a/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json
+++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest.json
diff --git a/tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs
index 5caf7d124..f58a3276b 100644
--- a/tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs
+++ b/tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs
@@ -50,7 +50,7 @@ namespace Jellyfin.Server.Implementations.Tests.Updates
{
PackageInfo[] packages = await _installationManager.GetPackages(
"Jellyfin Stable",
- "https://repo.jellyfin.org/releases/plugin/manifest-stable.json",
+ "https://repo.jellyfin.org/files/plugin/manifest.json",
false);
Assert.Equal(25, packages.Length);
@@ -61,7 +61,7 @@ namespace Jellyfin.Server.Implementations.Tests.Updates
{
PackageInfo[] packages = await _installationManager.GetPackages(
"Jellyfin Stable",
- "https://repo.jellyfin.org/releases/plugin/manifest-stable.json",
+ "https://repo.jellyfin.org/files/plugin/manifest.json",
false);
packages = _installationManager.FilterPackages(packages, "Anime").ToArray();
@@ -73,7 +73,7 @@ namespace Jellyfin.Server.Implementations.Tests.Updates
{
PackageInfo[] packages = await _installationManager.GetPackages(
"Jellyfin Stable",
- "https://repo.jellyfin.org/releases/plugin/manifest-stable.json",
+ "https://repo.jellyfin.org/files/plugin/manifest.json",
false);
packages = _installationManager.FilterPackages(packages, id: new Guid("a4df60c5-6ab4-412a-8f79-2cab93fb2bc5")).ToArray();