diff --git a/.ci/azure-pipelines-abi.yml b/.ci/azure-pipelines-abi.yml
index 4d38a906e6..14df7e7c8d 100644
--- a/.ci/azure-pipelines-abi.yml
+++ b/.ci/azure-pipelines-abi.yml
@@ -7,7 +7,7 @@ parameters:
default: "ubuntu-latest"
- name: DotNetSdkVersion
type: string
- default: 3.1.100
+ default: 5.0.100
jobs:
- job: CompatibilityCheck
@@ -62,6 +62,7 @@ jobs:
- task: DownloadPipelineArtifact@2
displayName: 'Download Reference Assembly Build Artifact'
+ enabled: false
inputs:
source: "specific"
artifact: "$(NugetPackageName)"
@@ -73,6 +74,7 @@ jobs:
- task: CopyFiles@2
displayName: 'Copy Reference Assembly Build Artifact'
+ enabled: false
inputs:
sourceFolder: $(System.ArtifactsDirectory)/current-artifacts
contents: '**/*.dll'
@@ -83,6 +85,7 @@ jobs:
- task: DotNetCoreCLI@2
displayName: 'Execute ABI Compatibility Check Tool'
+ enabled: false
inputs:
command: custom
custom: compat
diff --git a/.ci/azure-pipelines-api-client.yml b/.ci/azure-pipelines-api-client.yml
new file mode 100644
index 0000000000..1c447fd977
--- /dev/null
+++ b/.ci/azure-pipelines-api-client.yml
@@ -0,0 +1,58 @@
+parameters:
+ - name: LinuxImage
+ type: string
+ default: "ubuntu-latest"
+ - name: GeneratorVersion
+ type: string
+ default: "5.0.0-beta2"
+
+jobs:
+- job: GenerateApiClients
+ displayName: 'Generate Api Clients'
+ condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v')
+ dependsOn: Test
+
+ pool:
+ vmImage: "${{ parameters.LinuxImage }}"
+
+ steps:
+ - task: DownloadPipelineArtifact@2
+ displayName: 'Download OpenAPI Spec Artifact'
+ inputs:
+ source: 'current'
+ artifact: "OpenAPI Spec"
+ path: "$(System.ArtifactsDirectory)/openapispec"
+ runVersion: "latest"
+
+ - task: CmdLine@2
+ displayName: 'Download OpenApi Generator'
+ inputs:
+ script: "wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/${{ parameters.GeneratorVersion }}/openapi-generator-cli-${{ parameters.GeneratorVersion }}.jar -O openapi-generator-cli.jar"
+
+## Authenticate with npm registry
+ - task: npmAuthenticate@0
+ inputs:
+ workingFile: ./.npmrc
+ customEndpoint: 'jellyfin-bot for NPM'
+
+## Generate npm api client
+ - task: CmdLine@2
+ displayName: 'Build stable typescript axios client'
+ inputs:
+ script: "bash ./apiclient/templates/typescript/axios/generate.sh $(System.ArtifactsDirectory)"
+
+## Run npm install
+ - task: Npm@1
+ displayName: 'Install npm dependencies'
+ inputs:
+ command: install
+ workingDir: ./apiclient/generated/typescript/axios
+
+## Publish npm packages
+ - task: Npm@1
+ displayName: 'Publish stable typescript axios client'
+ inputs:
+ command: publish
+ publishRegistry: useExternalRegistry
+ publishEndpoint: 'jellyfin-bot for NPM'
+ workingDir: ./apiclient/generated/typescript/axios
diff --git a/.ci/azure-pipelines-main.yml b/.ci/azure-pipelines-main.yml
index 7617f0f5a2..95dd3ccac2 100644
--- a/.ci/azure-pipelines-main.yml
+++ b/.ci/azure-pipelines-main.yml
@@ -1,7 +1,7 @@
parameters:
LinuxImage: 'ubuntu-latest'
RestoreBuildProjects: 'Jellyfin.Server/Jellyfin.Server.csproj'
- DotNetSdkVersion: 3.1.100
+ DotNetSdkVersion: 5.0.100
jobs:
- job: Build
diff --git a/.ci/azure-pipelines-package.yml b/.ci/azure-pipelines-package.yml
index cc845afd43..d478516b83 100644
--- a/.ci/azure-pipelines-package.yml
+++ b/.ci/azure-pipelines-package.yml
@@ -65,6 +65,38 @@ jobs:
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:
+ - 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'
@@ -135,7 +167,7 @@ jobs:
inputs:
sshEndpoint: repository
runOptions: 'commands'
- commands: sudo nohup -n /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) unstable &
+ commands: nohup sudo /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) unstable &
- task: SSH@0
displayName: 'Update Stable Repository'
@@ -144,7 +176,7 @@ jobs:
inputs:
sshEndpoint: repository
runOptions: 'commands'
- commands: sudo nohup -n /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) &
+ commands: nohup sudo /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) &
- job: PublishNuget
displayName: 'Publish NuGet packages'
@@ -156,6 +188,12 @@ jobs:
vmImage: 'ubuntu-latest'
steps:
+ - task: UseDotNet@2
+ displayName: 'Use .NET 5.0 sdk'
+ inputs:
+ packageType: 'sdk'
+ version: '5.0.x'
+
- task: DotNetCoreCLI@2
displayName: 'Build Stable Nuget packages'
condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v')
diff --git a/.ci/azure-pipelines-test.yml b/.ci/azure-pipelines-test.yml
index eca8aa90f9..4ceda978a6 100644
--- a/.ci/azure-pipelines-test.yml
+++ b/.ci/azure-pipelines-test.yml
@@ -10,7 +10,7 @@ parameters:
default: "tests/**/*Tests.csproj"
- name: DotNetSdkVersion
type: string
- default: 3.1.100
+ default: 5.0.100
jobs:
- job: Test
@@ -56,7 +56,7 @@ jobs:
inputs:
command: "test"
projects: ${{ parameters.TestProjects }}
- arguments: '--configuration Release --collect:"XPlat Code Coverage" --settings tests/coverletArgs.runsettings --verbosity minimal "-p:GenerateDocumentationFile=False"'
+ arguments: '--configuration Release --collect:"XPlat Code Coverage" --settings tests/coverletArgs.runsettings --verbosity minimal'
publishTestResults: true
testRunTitle: $(Agent.JobName)
workingDirectory: "$(Build.SourcesDirectory)"
@@ -94,5 +94,5 @@ jobs:
displayName: 'Publish OpenAPI Artifact'
condition: and(succeeded(), eq(variables['Agent.OS'], 'Linux'))
inputs:
- targetPath: "tests/Jellyfin.Api.Tests/bin/Release/netcoreapp3.1/openapi.json"
+ targetPath: "tests/Jellyfin.Api.Tests/bin/Release/net5.0/openapi.json"
artifactName: 'OpenAPI Spec'
diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml
index b417aae678..ec4c254358 100644
--- a/.ci/azure-pipelines.yml
+++ b/.ci/azure-pipelines.yml
@@ -6,7 +6,7 @@ variables:
- name: RestoreBuildProjects
value: 'Jellyfin.Server/Jellyfin.Server.csproj'
- name: DotNetSdkVersion
- value: 3.1.100
+ value: 5.0.100
pr:
autoCancel: true
@@ -34,6 +34,12 @@ jobs:
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
@@ -55,3 +61,6 @@ jobs:
- ${{ if or(startsWith(variables['Build.SourceBranch'], 'refs/tags/v'), startsWith(variables['Build.SourceBranch'], 'refs/heads/master')) }}:
- template: azure-pipelines-package.yml
+
+- ${{ if or(startsWith(variables['Build.SourceBranch'], 'refs/tags/v'), startsWith(variables['Build.SourceBranch'], 'refs/heads/master')) }}:
+ - template: azure-pipelines-api-client.yml
diff --git a/.gitignore b/.gitignore
index 0df7606ce9..7cd3d0068a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -276,3 +276,4 @@ BenchmarkDotNet.Artifacts
web/
web-src.*
MediaBrowser.WebDashboard/jellyfin-web
+apiclient/generated
diff --git a/.npmrc b/.npmrc
new file mode 100644
index 0000000000..b7a317000b
--- /dev/null
+++ b/.npmrc
@@ -0,0 +1,3 @@
+registry=https://registry.npmjs.org/
+@jellyfin:registry=https://pkgs.dev.azure.com/jellyfin-project/jellyfin/_packaging/unstable/npm/registry/
+always-auth=true
\ No newline at end of file
diff --git a/.vscode/launch.json b/.vscode/launch.json
index bf1bd65cbe..e55ea22485 100644
--- a/.vscode/launch.json
+++ b/.vscode/launch.json
@@ -6,19 +6,23 @@
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
- "program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/netcoreapp3.1/jellyfin.dll",
+ "program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/net5.0/jellyfin.dll",
"args": [],
"cwd": "${workspaceFolder}/Jellyfin.Server",
"console": "internalConsole",
"stopAtEntry": false,
- "internalConsoleOptions": "openOnSessionStart"
+ "internalConsoleOptions": "openOnSessionStart",
+ "serverReadyAction": {
+ "action": "openExternally",
+ "pattern": "Overriding address\\(es\\) \\'(https?:\\S+)\\'",
+ }
},
{
"name": ".NET Core Launch (nowebclient)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
- "program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/netcoreapp3.1/jellyfin.dll",
+ "program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/net5.0/jellyfin.dll",
"args": ["--nowebclient"],
"cwd": "${workspaceFolder}/Jellyfin.Server",
"console": "internalConsole",
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index efd83012e9..a97a4c7416 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -103,6 +103,8 @@
- [sl1288](https://github.com/sl1288)
- [sorinyo2004](https://github.com/sorinyo2004)
- [sparky8251](https://github.com/sparky8251)
+ - [spookbits](https://github.com/spookbits)
+ - [ssenart] (https://github.com/ssenart)
- [stanionascu](https://github.com/stanionascu)
- [stevehayles](https://github.com/stevehayles)
- [SuperSandro2000](https://github.com/SuperSandro2000)
@@ -136,6 +138,7 @@
- [KristupasSavickas](https://github.com/KristupasSavickas)
- [Pusta](https://github.com/pusta)
- [nielsvanvelzen](https://github.com/nielsvanvelzen)
+ - [skyfrk](https://github.com/skyfrk)
# Emby Contributors
diff --git a/Dockerfile b/Dockerfile
index 69af9b77b5..963027b49c 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,4 +1,4 @@
-ARG DOTNET_VERSION=3.1
+ARG DOTNET_VERSION=5.0
FROM node:alpine as web-builder
ARG JELLYFIN_WEB_VERSION=master
@@ -8,7 +8,7 @@ RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine-
&& yarn install \
&& mv dist /dist
-FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster as builder
+FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION}-buster-slim as builder
WORKDIR /repo
COPY . .
ENV DOTNET_CLI_TELEMETRY_OPTOUT=1
diff --git a/Dockerfile.arm b/Dockerfile.arm
index efeed25dff..e0eaca0edd 100644
--- a/Dockerfile.arm
+++ b/Dockerfile.arm
@@ -2,7 +2,7 @@
#####################################
# Requires binfm_misc registration
# https://github.com/multiarch/qemu-user-static#binfmt_misc-register
-ARG DOTNET_VERSION=3.1
+ARG DOTNET_VERSION=5.0
FROM node:alpine as web-builder
@@ -14,7 +14,7 @@ RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine-
&& mv dist /dist
-FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION} as builder
+FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} as builder
WORKDIR /repo
COPY . .
ENV DOTNET_CLI_TELEMETRY_OPTOUT=1
diff --git a/Dockerfile.arm64 b/Dockerfile.arm64
index 1f2c2ec36d..db7de935cf 100644
--- a/Dockerfile.arm64
+++ b/Dockerfile.arm64
@@ -2,7 +2,7 @@
#####################################
# Requires binfm_misc registration
# https://github.com/multiarch/qemu-user-static#binfmt_misc-register
-ARG DOTNET_VERSION=3.1
+ARG DOTNET_VERSION=5.0
FROM node:alpine as web-builder
@@ -14,7 +14,7 @@ RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine-
&& mv dist /dist
-FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION} as builder
+FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} as builder
WORKDIR /repo
COPY . .
ENV DOTNET_CLI_TELEMETRY_OPTOUT=1
diff --git a/DvdLib/DvdLib.csproj b/DvdLib/DvdLib.csproj
index 64d041cb05..7bbd9acf82 100644
--- a/DvdLib/DvdLib.csproj
+++ b/DvdLib/DvdLib.csproj
@@ -10,7 +10,7 @@
- netstandard2.1
+ net5.0
false
true
true
diff --git a/DvdLib/Ifo/Dvd.cs b/DvdLib/Ifo/Dvd.cs
index 361319625c..b4a11ed5d6 100644
--- a/DvdLib/Ifo/Dvd.cs
+++ b/DvdLib/Ifo/Dvd.cs
@@ -31,7 +31,7 @@ namespace DvdLib.Ifo
continue;
}
- var nums = ifo.Name.Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
+ var nums = ifo.Name.Split('_', StringSplitOptions.RemoveEmptyEntries);
if (nums.Length >= 2 && ushort.TryParse(nums[1], out var ifoNumber))
{
ReadVTS(ifoNumber, ifo.FullName);
diff --git a/Emby.Dlna/Common/Argument.cs b/Emby.Dlna/Common/Argument.cs
index f375e6049c..430a3b47d5 100644
--- a/Emby.Dlna/Common/Argument.cs
+++ b/Emby.Dlna/Common/Argument.cs
@@ -1,13 +1,23 @@
-#pragma warning disable CS1591
-
namespace Emby.Dlna.Common
{
+ ///
+ /// DLNA Query parameter type, used when quering DLNA devices via SOAP.
+ ///
public class Argument
{
- public string Name { get; set; }
+ ///
+ /// Gets or sets name of the DLNA argument.
+ ///
+ public string Name { get; set; } = string.Empty;
- public string Direction { get; set; }
+ ///
+ /// Gets or sets the direction of the parameter.
+ ///
+ public string Direction { get; set; } = string.Empty;
- public string RelatedStateVariable { get; set; }
+ ///
+ /// Gets or sets the related DLNA state variable for this argument.
+ ///
+ public string RelatedStateVariable { get; set; } = string.Empty;
}
}
diff --git a/Emby.Dlna/Common/DeviceIcon.cs b/Emby.Dlna/Common/DeviceIcon.cs
index c3f7fa8aaa..f9fd1dcec6 100644
--- a/Emby.Dlna/Common/DeviceIcon.cs
+++ b/Emby.Dlna/Common/DeviceIcon.cs
@@ -1,29 +1,41 @@
-#pragma warning disable CS1591
-
using System.Globalization;
namespace Emby.Dlna.Common
{
+ ///
+ /// Defines the .
+ ///
public class DeviceIcon
{
- public string Url { get; set; }
+ ///
+ /// Gets or sets the Url.
+ ///
+ public string Url { get; set; } = string.Empty;
- public string MimeType { get; set; }
+ ///
+ /// Gets or sets the MimeType.
+ ///
+ public string MimeType { get; set; } = string.Empty;
+ ///
+ /// Gets or sets the Width.
+ ///
public int Width { get; set; }
+ ///
+ /// Gets or sets the Height.
+ ///
public int Height { get; set; }
- public string Depth { get; set; }
+ ///
+ /// Gets or sets the Depth.
+ ///
+ public string Depth { get; set; } = string.Empty;
///
public override string ToString()
{
- return string.Format(
- CultureInfo.InvariantCulture,
- "{0}x{1}",
- Height,
- Width);
+ return string.Format(CultureInfo.InvariantCulture, "{0}x{1}", Height, Width);
}
}
}
diff --git a/Emby.Dlna/Common/DeviceService.cs b/Emby.Dlna/Common/DeviceService.cs
index 44c0a0412a..c1369558ec 100644
--- a/Emby.Dlna/Common/DeviceService.cs
+++ b/Emby.Dlna/Common/DeviceService.cs
@@ -1,21 +1,36 @@
-#pragma warning disable CS1591
-
namespace Emby.Dlna.Common
{
+ ///
+ /// Defines the .
+ ///
public class DeviceService
{
- public string ServiceType { get; set; }
+ ///
+ /// Gets or sets the Service Type.
+ ///
+ public string ServiceType { get; set; } = string.Empty;
- public string ServiceId { get; set; }
+ ///
+ /// Gets or sets the Service Id.
+ ///
+ public string ServiceId { get; set; } = string.Empty;
- public string ScpdUrl { get; set; }
+ ///
+ /// Gets or sets the Scpd Url.
+ ///
+ public string ScpdUrl { get; set; } = string.Empty;
- public string ControlUrl { get; set; }
+ ///
+ /// Gets or sets the Control Url.
+ ///
+ public string ControlUrl { get; set; } = string.Empty;
- public string EventSubUrl { get; set; }
+ ///
+ /// Gets or sets the EventSubUrl.
+ ///
+ public string EventSubUrl { get; set; } = string.Empty;
///
- public override string ToString()
- => ServiceId;
+ public override string ToString() => ServiceId;
}
}
diff --git a/Emby.Dlna/Common/ServiceAction.cs b/Emby.Dlna/Common/ServiceAction.cs
index d458d7f3f6..02b81a0aa7 100644
--- a/Emby.Dlna/Common/ServiceAction.cs
+++ b/Emby.Dlna/Common/ServiceAction.cs
@@ -1,24 +1,31 @@
-#pragma warning disable CS1591
-
using System.Collections.Generic;
namespace Emby.Dlna.Common
{
+ ///
+ /// Defines the .
+ ///
public class ServiceAction
{
+ ///
+ /// Initializes a new instance of the class.
+ ///
public ServiceAction()
{
ArgumentList = new List();
}
- public string Name { get; set; }
+ ///
+ /// Gets or sets the name of the action.
+ ///
+ public string Name { get; set; } = string.Empty;
+ ///
+ /// Gets the ArgumentList.
+ ///
public List ArgumentList { get; }
///
- public override string ToString()
- {
- return Name;
- }
+ public override string ToString() => Name;
}
}
diff --git a/Emby.Dlna/Common/StateVariable.cs b/Emby.Dlna/Common/StateVariable.cs
index 6daf7ab6b2..fd733e0853 100644
--- a/Emby.Dlna/Common/StateVariable.cs
+++ b/Emby.Dlna/Common/StateVariable.cs
@@ -1,27 +1,34 @@
-#pragma warning disable CS1591
-
using System;
using System.Collections.Generic;
namespace Emby.Dlna.Common
{
+ ///
+ /// Defines the .
+ ///
public class StateVariable
{
- public StateVariable()
- {
- AllowedValues = Array.Empty();
- }
+ ///
+ /// Gets or sets the name of the state variable.
+ ///
+ public string Name { get; set; } = string.Empty;
- public string Name { get; set; }
-
- public string DataType { get; set; }
+ ///
+ /// Gets or sets the data type of the state variable.
+ ///
+ public string DataType { get; set; } = string.Empty;
+ ///
+ /// Gets or sets a value indicating whether it sends events.
+ ///
public bool SendsEvents { get; set; }
- public IReadOnlyList AllowedValues { get; set; }
+ ///
+ /// Gets or sets the allowed values range.
+ ///
+ public IReadOnlyList AllowedValues { get; set; } = Array.Empty();
///
- public override string ToString()
- => Name;
+ public override string ToString() => Name;
}
}
diff --git a/Emby.Dlna/ContentDirectory/ContentDirectoryService.cs b/Emby.Dlna/ContentDirectory/ContentDirectoryService.cs
index 5760f260cf..2f3107450c 100644
--- a/Emby.Dlna/ContentDirectory/ContentDirectoryService.cs
+++ b/Emby.Dlna/ContentDirectory/ContentDirectoryService.cs
@@ -19,6 +19,9 @@ using Microsoft.Extensions.Logging;
namespace Emby.Dlna.ContentDirectory
{
+ ///
+ /// Defines the .
+ ///
public class ContentDirectoryService : BaseService, IContentDirectory
{
private readonly ILibraryManager _libraryManager;
@@ -33,6 +36,22 @@ namespace Emby.Dlna.ContentDirectory
private readonly IMediaEncoder _mediaEncoder;
private readonly ITVSeriesManager _tvSeriesManager;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The to use in the instance.
+ /// The to use in the instance.
+ /// The to use in the instance.
+ /// The to use in the instance.
+ /// The to use in the instance.
+ /// The to use in the instance.
+ /// The to use in the instance.
+ /// The to use in the instance.
+ /// The to use in the instance.
+ /// The to use in the instance.
+ /// The to use in the instance.
+ /// The to use in the instance.
+ /// The to use in the instance.
public ContentDirectoryService(
IDlnaManager dlna,
IUserDataManager userDataManager,
@@ -62,7 +81,10 @@ namespace Emby.Dlna.ContentDirectory
_tvSeriesManager = tvSeriesManager;
}
- private int SystemUpdateId
+ ///
+ /// Gets the system id. (A unique id which changes on when our definition changes.)
+ ///
+ private static int SystemUpdateId
{
get
{
@@ -75,14 +97,18 @@ namespace Emby.Dlna.ContentDirectory
///
public string GetServiceXml()
{
- return new ContentDirectoryXmlBuilder().GetXml();
+ return ContentDirectoryXmlBuilder.GetXml();
}
///
public Task ProcessControlRequestAsync(ControlRequest request)
{
- var profile = _dlna.GetProfile(request.Headers) ??
- _dlna.GetDefaultProfile();
+ if (request == null)
+ {
+ throw new ArgumentNullException(nameof(request));
+ }
+
+ var profile = _dlna.GetProfile(request.Headers) ?? _dlna.GetDefaultProfile();
var serverAddress = request.RequestedUrl.Substring(0, request.RequestedUrl.IndexOf("/dlna", StringComparison.OrdinalIgnoreCase));
@@ -107,6 +133,11 @@ namespace Emby.Dlna.ContentDirectory
.ProcessControlRequestAsync(request);
}
+ ///
+ /// Get the user stored in the device profile.
+ ///
+ /// The .
+ /// The .
private User GetUser(DeviceProfile profile)
{
if (!string.IsNullOrEmpty(profile.UserId))
diff --git a/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs b/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs
index 743dcc5161..3edaabb70e 100644
--- a/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs
+++ b/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs
@@ -6,143 +6,154 @@ using Emby.Dlna.Service;
namespace Emby.Dlna.ContentDirectory
{
- public class ContentDirectoryXmlBuilder
+ ///
+ /// Defines the .
+ ///
+ public static class ContentDirectoryXmlBuilder
{
- public string GetXml()
+ ///
+ /// Gets the ContentDirectory:1 service template.
+ /// See http://upnp.org/specs/av/UPnP-av-ContentDirectory-v1-Service.pdf.
+ ///
+ /// An XML description of this service.
+ public static string GetXml()
{
- return new ServiceXmlBuilder().GetXml(
- new ServiceActionListBuilder().GetActions(),
- GetStateVariables());
+ return new ServiceXmlBuilder().GetXml(ServiceActionListBuilder.GetActions(), GetStateVariables());
}
+ ///
+ /// Get the list of state variables for this invocation.
+ ///
+ /// The .
private static IEnumerable GetStateVariables()
{
- var list = new List();
-
- list.Add(new StateVariable
+ var list = new List
{
- Name = "A_ARG_TYPE_Filter",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_Filter",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_SortCriteria",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_SortCriteria",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_Index",
- DataType = "ui4",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_Index",
+ DataType = "ui4",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_Count",
- DataType = "ui4",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_Count",
+ DataType = "ui4",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_UpdateID",
- DataType = "ui4",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_UpdateID",
+ DataType = "ui4",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "SearchCapabilities",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "SearchCapabilities",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "SortCapabilities",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "SortCapabilities",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "SystemUpdateID",
- DataType = "ui4",
- SendsEvents = true
- });
+ new StateVariable
+ {
+ Name = "SystemUpdateID",
+ DataType = "ui4",
+ SendsEvents = true
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_SearchCriteria",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_SearchCriteria",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_Result",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_Result",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_ObjectID",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_ObjectID",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_BrowseFlag",
- DataType = "string",
- SendsEvents = false,
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_BrowseFlag",
+ DataType = "string",
+ SendsEvents = false,
- AllowedValues = new[]
+ AllowedValues = new[]
{
"BrowseMetadata",
"BrowseDirectChildren"
}
- });
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_BrowseLetter",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_BrowseLetter",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_CategoryType",
- DataType = "ui4",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_CategoryType",
+ DataType = "ui4",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_RID",
- DataType = "ui4",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_RID",
+ DataType = "ui4",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_PosSec",
- DataType = "ui4",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_PosSec",
+ DataType = "ui4",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_Featurelist",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_Featurelist",
+ DataType = "string",
+ SendsEvents = false
+ }
+ };
return list;
}
diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs
index 4b108b89ea..9f35c19594 100644
--- a/Emby.Dlna/ContentDirectory/ControlHandler.cs
+++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs
@@ -1,6 +1,5 @@
-#pragma warning disable CS1591
-
using System;
+using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
@@ -8,6 +7,7 @@ using System.Linq;
using System.Text;
using System.Threading;
using System.Xml;
+using Emby.Dlna.Configuration;
using Emby.Dlna.Didl;
using Emby.Dlna.Service;
using Jellyfin.Data.Entities;
@@ -38,6 +38,9 @@ using Series = MediaBrowser.Controller.Entities.TV.Series;
namespace Emby.Dlna.ContentDirectory
{
+ ///
+ /// Defines the .
+ ///
public class ControlHandler : BaseControlHandler
{
private const string NsDc = "http://purl.org/dc/elements/1.1/";
@@ -58,6 +61,24 @@ namespace Emby.Dlna.ContentDirectory
private readonly DeviceProfile _profile;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The for use with the instance.
+ /// The for use with the instance.
+ /// The for use with the instance.
+ /// The server address to use in this instance> for use with the instance.
+ /// The for use with the instance.
+ /// The for use with the instance.
+ /// The for use with the instance.
+ /// The for use with the instance.
+ /// The system id for use with the instance.
+ /// The for use with the instance.
+ /// The for use with the instance.
+ /// The for use with the instance.
+ /// The for use with the instance.
+ /// The for use with the instance.
+ /// The for use with the instance.
public ControlHandler(
ILogger logger,
ILibraryManager libraryManager,
@@ -102,6 +123,16 @@ namespace Emby.Dlna.ContentDirectory
///
protected override void WriteResult(string methodName, IDictionary methodParams, XmlWriter xmlWriter)
{
+ if (xmlWriter == null)
+ {
+ throw new ArgumentNullException(nameof(xmlWriter));
+ }
+
+ if (methodParams == null)
+ {
+ throw new ArgumentNullException(nameof(methodParams));
+ }
+
const string DeviceId = "test";
if (string.Equals(methodName, "GetSearchCapabilities", StringComparison.OrdinalIgnoreCase))
@@ -167,6 +198,10 @@ namespace Emby.Dlna.ContentDirectory
throw new ResourceNotFoundException("Unexpected control request name: " + methodName);
}
+ ///
+ /// Adds a "XSetBookmark" element to the xml document.
+ ///
+ /// The .
private void HandleXSetBookmark(IDictionary sparams)
{
var id = sparams["ObjectID"];
@@ -189,41 +224,69 @@ namespace Emby.Dlna.ContentDirectory
CancellationToken.None);
}
- private void HandleGetSearchCapabilities(XmlWriter xmlWriter)
+ ///
+ /// Adds the "SearchCaps" element to the xml document.
+ ///
+ /// The .
+ private static void HandleGetSearchCapabilities(XmlWriter xmlWriter)
{
xmlWriter.WriteElementString(
"SearchCaps",
"res@resolution,res@size,res@duration,dc:title,dc:creator,upnp:actor,upnp:artist,upnp:genre,upnp:album,dc:date,upnp:class,@id,@refID,@protocolInfo,upnp:author,dc:description,pv:avKeywords");
}
- private void HandleGetSortCapabilities(XmlWriter xmlWriter)
+ ///
+ /// Adds the "SortCaps" element to the xml document.
+ ///
+ /// The .
+ private static void HandleGetSortCapabilities(XmlWriter xmlWriter)
{
xmlWriter.WriteElementString(
"SortCaps",
"res@duration,res@size,res@bitrate,dc:date,dc:title,dc:size,upnp:album,upnp:artist,upnp:albumArtist,upnp:episodeNumber,upnp:genre,upnp:originalTrackNumber,upnp:rating");
}
- private void HandleGetSortExtensionCapabilities(XmlWriter xmlWriter)
+ ///
+ /// Adds the "SortExtensionCaps" element to the xml document.
+ ///
+ /// The .
+ private static void HandleGetSortExtensionCapabilities(XmlWriter xmlWriter)
{
xmlWriter.WriteElementString(
"SortExtensionCaps",
"res@duration,res@size,res@bitrate,dc:date,dc:title,dc:size,upnp:album,upnp:artist,upnp:albumArtist,upnp:episodeNumber,upnp:genre,upnp:originalTrackNumber,upnp:rating");
}
+ ///
+ /// Adds the "Id" element to the xml document.
+ ///
+ /// The .
private void HandleGetSystemUpdateID(XmlWriter xmlWriter)
{
xmlWriter.WriteElementString("Id", _systemUpdateId.ToString(CultureInfo.InvariantCulture));
}
- private void HandleGetFeatureList(XmlWriter xmlWriter)
+ ///
+ /// Adds the "FeatureList" element to the xml document.
+ ///
+ /// The .
+ private static void HandleGetFeatureList(XmlWriter xmlWriter)
{
xmlWriter.WriteElementString("FeatureList", WriteFeatureListXml());
}
- private void HandleXGetFeatureList(XmlWriter xmlWriter)
+ ///
+ /// Adds the "FeatureList" element to the xml document.
+ ///
+ /// The .
+ private static void HandleXGetFeatureList(XmlWriter xmlWriter)
=> HandleGetFeatureList(xmlWriter);
- private string WriteFeatureListXml()
+ ///
+ /// Builds a static feature list.
+ ///
+ /// The xml feature list.
+ private static string WriteFeatureListXml()
{
// TODO: clean this up
var builder = new StringBuilder();
@@ -242,9 +305,16 @@ namespace Emby.Dlna.ContentDirectory
return builder.ToString();
}
- public string GetValueOrDefault(IDictionary sparams, string key, string defaultValue)
+ ///
+ /// Returns the value in the key of the dictionary, or defaultValue if it doesn't exist.
+ ///
+ /// The .
+ /// The key.
+ /// The defaultValue.
+ /// The .
+ public static string GetValueOrDefault(IDictionary sparams, string key, string defaultValue)
{
- if (sparams.TryGetValue(key, out string val))
+ if (sparams != null && sparams.TryGetValue(key, out string val))
{
return val;
}
@@ -252,6 +322,12 @@ namespace Emby.Dlna.ContentDirectory
return defaultValue;
}
+ ///
+ /// Builds the "Browse" xml response.
+ ///
+ /// The .
+ /// The .
+ /// The device Id to use.
private void HandleBrowse(XmlWriter xmlWriter, IDictionary sparams, string deviceId)
{
var id = sparams["ObjectID"];
@@ -313,7 +389,6 @@ namespace Emby.Dlna.ContentDirectory
}
else
{
- var dlnaOptions = _config.GetDlnaConfiguration();
_didlBuilder.WriteItemElement(writer, item, _user, null, null, deviceId, filter);
}
@@ -326,7 +401,6 @@ namespace Emby.Dlna.ContentDirectory
provided = childrenResult.Items.Count;
- var dlnaOptions = _config.GetDlnaConfiguration();
foreach (var i in childrenResult.Items)
{
var childItem = i.Item;
@@ -357,12 +431,24 @@ namespace Emby.Dlna.ContentDirectory
xmlWriter.WriteElementString("UpdateID", _systemUpdateId.ToString(CultureInfo.InvariantCulture));
}
+ ///
+ /// Builds the response to the "X_BrowseByLetter request.
+ ///
+ /// The .
+ /// The .
+ /// The device id.
private void HandleXBrowseByLetter(XmlWriter xmlWriter, IDictionary sparams, string deviceId)
{
// TODO: Implement this method
HandleSearch(xmlWriter, sparams, deviceId);
}
+ ///
+ /// Builds a response to the "Search" request.
+ ///
+ /// The xmlWriter.
+ /// The sparams.
+ /// The deviceId.
private void HandleSearch(XmlWriter xmlWriter, IDictionary sparams, string deviceId)
{
var searchCriteria = new SearchCriteria(GetValueOrDefault(sparams, "SearchCriteria", string.Empty));
@@ -442,7 +528,17 @@ namespace Emby.Dlna.ContentDirectory
xmlWriter.WriteElementString("UpdateID", _systemUpdateId.ToString(CultureInfo.InvariantCulture));
}
- private QueryResult GetChildrenSorted(BaseItem item, User user, SearchCriteria search, SortCriteria sort, int? startIndex, int? limit)
+ ///
+ /// Returns the child items meeting the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
+ /// The start index.
+ /// The maximum number to return.
+ /// The .
+ private static QueryResult GetChildrenSorted(BaseItem item, User user, SearchCriteria search, SortCriteria sort, int? startIndex, int? limit)
{
var folder = (Folder)item;
@@ -487,18 +583,32 @@ namespace Emby.Dlna.ContentDirectory
User = user,
Recursive = true,
IsMissing = false,
- ExcludeItemTypes = new[] { typeof(Book).Name },
+ ExcludeItemTypes = new[] { nameof(Book) },
IsFolder = isFolder,
MediaTypes = mediaTypes,
DtoOptions = GetDtoOptions()
});
}
- private DtoOptions GetDtoOptions()
+ ///
+ /// Returns a new DtoOptions object.
+ ///
+ /// The .
+ private static DtoOptions GetDtoOptions()
{
return new DtoOptions(true);
}
+ ///
+ /// Returns the User items meeting the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
+ /// The start index.
+ /// The maximum number to return.
+ /// The .
private QueryResult GetUserItems(BaseItem item, StubType? stubType, User user, SortCriteria sort, int? startIndex, int? limit)
{
if (item is MusicGenre)
@@ -556,7 +666,7 @@ namespace Emby.Dlna.ContentDirectory
Limit = limit,
StartIndex = startIndex,
IsVirtualItem = false,
- ExcludeItemTypes = new[] { typeof(Book).Name },
+ ExcludeItemTypes = new[] { nameof(Book) },
IsPlaceHolder = false,
DtoOptions = GetDtoOptions()
};
@@ -568,6 +678,14 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(queryResult);
}
+ ///
+ /// Returns the Live Tv Channels meeting the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The start index.
+ /// The maximum number to return.
+ /// The .
private QueryResult GetLiveTvChannels(User user, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
@@ -575,7 +693,7 @@ namespace Emby.Dlna.ContentDirectory
StartIndex = startIndex,
Limit = limit,
};
- query.IncludeItemTypes = new[] { typeof(LiveTvChannel).Name };
+ query.IncludeItemTypes = new[] { nameof(LiveTvChannel) };
SetSorting(query, sort, false);
@@ -584,6 +702,16 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ ///
+ /// Returns the music folders meeting the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
+ /// The start index.
+ /// The maximum number to return.
+ /// The .
private QueryResult GetMusicFolders(BaseItem item, User user, StubType? stubType, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
@@ -643,57 +771,58 @@ namespace Emby.Dlna.ContentDirectory
return GetMusicGenres(item, user, query);
}
- var list = new List();
-
- list.Add(new ServerItem(item)
+ var list = new List
{
- StubType = StubType.Latest
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.Latest
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Playlists
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.Playlists
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Albums
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.Albums
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.AlbumArtists
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.AlbumArtists
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Artists
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.Artists
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Songs
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.Songs
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Genres
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.Genres
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.FavoriteArtists
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.FavoriteArtists
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.FavoriteAlbums
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.FavoriteAlbums
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.FavoriteSongs
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.FavoriteSongs
+ }
+ };
return new QueryResult
{
@@ -702,6 +831,16 @@ namespace Emby.Dlna.ContentDirectory
};
}
+ ///
+ /// Returns the movie folders meeting the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
+ /// The start index.
+ /// The maximum number to return.
+ /// The .
private QueryResult GetMovieFolders(BaseItem item, User user, StubType? stubType, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
@@ -776,6 +915,13 @@ namespace Emby.Dlna.ContentDirectory
};
}
+ ///
+ /// Returns the folders meeting the criteria.
+ ///
+ /// The .
+ /// The start index.
+ /// The maximum number to return.
+ /// The .
private QueryResult GetFolders(User user, int? startIndex, int? limit)
{
var folders = _libraryManager.GetUserRootFolder().GetChildren(user, true)
@@ -796,6 +942,16 @@ namespace Emby.Dlna.ContentDirectory
limit);
}
+ ///
+ /// Returns the TV folders meeting the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
+ /// The start index.
+ /// The maximum number to return.
+ /// The .
private QueryResult GetTvFolders(BaseItem item, User user, StubType? stubType, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
@@ -840,42 +996,43 @@ namespace Emby.Dlna.ContentDirectory
return GetGenres(item, user, query);
}
- var list = new List();
-
- list.Add(new ServerItem(item)
+ var list = new List
{
- StubType = StubType.ContinueWatching
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.ContinueWatching
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.NextUp
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.NextUp
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Latest
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.Latest
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Series
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.Series
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.FavoriteSeries
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.FavoriteSeries
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.FavoriteEpisodes
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.FavoriteEpisodes
+ },
- list.Add(new ServerItem(item)
- {
- StubType = StubType.Genres
- });
+ new ServerItem(item)
+ {
+ StubType = StubType.Genres
+ }
+ };
return new QueryResult
{
@@ -884,6 +1041,13 @@ namespace Emby.Dlna.ContentDirectory
};
}
+ ///
+ /// Returns the Movies that are part watched that meet the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetMovieContinueWatching(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
@@ -904,136 +1068,213 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ ///
+ /// Returns the series meeting the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetSeries(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
- query.IncludeItemTypes = new[] { typeof(Series).Name };
+ query.IncludeItemTypes = new[] { nameof(Series) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ ///
+ /// Returns the Movie folders meeting the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetMovieMovies(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
- query.IncludeItemTypes = new[] { typeof(Movie).Name };
+ query.IncludeItemTypes = new[] { nameof(Movie) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ ///
+ /// Returns the Movie collections meeting the criteria.
+ ///
+ /// The see cref="User"/>.
+ /// The see cref="InternalItemsQuery"/>.
+ /// The .
private QueryResult GetMovieCollections(User user, InternalItemsQuery query)
{
query.Recursive = true;
// query.Parent = parent;
query.SetUser(user);
- query.IncludeItemTypes = new[] { typeof(BoxSet).Name };
+ query.IncludeItemTypes = new[] { nameof(BoxSet) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ ///
+ /// Returns the Music albums meeting the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetMusicAlbums(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
- query.IncludeItemTypes = new[] { typeof(MusicAlbum).Name };
+ query.IncludeItemTypes = new[] { nameof(MusicAlbum) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ ///
+ /// Returns the Music songs meeting the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetMusicSongs(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
- query.IncludeItemTypes = new[] { typeof(Audio).Name };
+ query.IncludeItemTypes = new[] { nameof(Audio) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ ///
+ /// Returns the songs tagged as favourite that meet the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetFavoriteSongs(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
query.IsFavorite = true;
- query.IncludeItemTypes = new[] { typeof(Audio).Name };
+ query.IncludeItemTypes = new[] { nameof(Audio) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ ///
+ /// Returns the series tagged as favourite that meet the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetFavoriteSeries(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
query.IsFavorite = true;
- query.IncludeItemTypes = new[] { typeof(Series).Name };
+ query.IncludeItemTypes = new[] { nameof(Series) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ ///
+ /// Returns the episodes tagged as favourite that meet the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetFavoriteEpisodes(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
query.IsFavorite = true;
- query.IncludeItemTypes = new[] { typeof(Episode).Name };
+ query.IncludeItemTypes = new[] { nameof(Episode) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ ///
+ /// Returns the movies tagged as favourite that meet the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetMovieFavorites(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
query.IsFavorite = true;
- query.IncludeItemTypes = new[] { typeof(Movie).Name };
+ query.IncludeItemTypes = new[] { nameof(Movie) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ ///
+ /// /// Returns the albums tagged as favourite that meet the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetFavoriteAlbums(BaseItem parent, User user, InternalItemsQuery query)
{
query.Recursive = true;
query.Parent = parent;
query.SetUser(user);
query.IsFavorite = true;
- query.IncludeItemTypes = new[] { typeof(MusicAlbum).Name };
+ query.IncludeItemTypes = new[] { nameof(MusicAlbum) };
var result = _libraryManager.GetItemsResult(query);
return ToResult(result);
}
+ ///
+ /// Returns the genres meeting the criteria.
+ /// The GetGenres.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetGenres(BaseItem parent, User user, InternalItemsQuery query)
{
var genresResult = _libraryManager.GetGenres(new InternalItemsQuery(user)
@@ -1052,6 +1293,13 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ ///
+ /// Returns the music genres meeting the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetMusicGenres(BaseItem parent, User user, InternalItemsQuery query)
{
var genresResult = _libraryManager.GetMusicGenres(new InternalItemsQuery(user)
@@ -1070,6 +1318,13 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ ///
+ /// Returns the music albums by artist that meet the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetMusicAlbumArtists(BaseItem parent, User user, InternalItemsQuery query)
{
var artists = _libraryManager.GetAlbumArtists(new InternalItemsQuery(user)
@@ -1088,6 +1343,13 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ ///
+ /// Returns the music artists meeting the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetMusicArtists(BaseItem parent, User user, InternalItemsQuery query)
{
var artists = _libraryManager.GetArtists(new InternalItemsQuery(user)
@@ -1106,6 +1368,13 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ ///
+ /// Returns the artists tagged as favourite that meet the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetFavoriteArtists(BaseItem parent, User user, InternalItemsQuery query)
{
var artists = _libraryManager.GetArtists(new InternalItemsQuery(user)
@@ -1125,6 +1394,12 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ ///
+ /// Returns the music playlists meeting the criteria.
+ ///
+ /// The user.
+ /// The query.
+ /// The .
private QueryResult GetMusicPlaylists(User user, InternalItemsQuery query)
{
query.Parent = null;
@@ -1137,6 +1412,13 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ ///
+ /// Returns the latest music meeting the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetMusicLatest(BaseItem parent, User user, InternalItemsQuery query)
{
query.OrderBy = Array.Empty<(string, SortOrder)>();
@@ -1155,6 +1437,12 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(items);
}
+ ///
+ /// Returns the next up item meeting the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetNextUp(BaseItem parent, InternalItemsQuery query)
{
query.OrderBy = Array.Empty<(string, SortOrder)>();
@@ -1172,6 +1460,13 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ ///
+ /// Returns the latest tv meeting the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetTvLatest(BaseItem parent, User user, InternalItemsQuery query)
{
query.OrderBy = Array.Empty<(string, SortOrder)>();
@@ -1181,7 +1476,7 @@ namespace Emby.Dlna.ContentDirectory
{
UserId = user.Id,
Limit = 50,
- IncludeItemTypes = new[] { typeof(Episode).Name },
+ IncludeItemTypes = new[] { nameof(Episode) },
ParentId = parent == null ? Guid.Empty : parent.Id,
GroupItems = false
},
@@ -1190,6 +1485,13 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(items);
}
+ ///
+ /// Returns the latest movies meeting the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
private QueryResult GetMovieLatest(BaseItem parent, User user, InternalItemsQuery query)
{
query.OrderBy = Array.Empty<(string, SortOrder)>();
@@ -1208,6 +1510,16 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(items);
}
+ ///
+ /// Returns music artist items that meet the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
+ /// The start index.
+ /// The maximum number to return.
+ /// The .
private QueryResult GetMusicArtistItems(BaseItem item, Guid parentId, User user, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
@@ -1215,7 +1527,7 @@ namespace Emby.Dlna.ContentDirectory
Recursive = true,
ParentId = parentId,
ArtistIds = new[] { item.Id },
- IncludeItemTypes = new[] { typeof(MusicAlbum).Name },
+ IncludeItemTypes = new[] { nameof(MusicAlbum) },
Limit = limit,
StartIndex = startIndex,
DtoOptions = GetDtoOptions()
@@ -1228,6 +1540,16 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ ///
+ /// Returns the genre items meeting the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
+ /// The start index.
+ /// The maximum number to return.
+ /// The .
private QueryResult GetGenreItems(BaseItem item, Guid parentId, User user, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
@@ -1252,6 +1574,16 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
+ ///
+ /// Returns the music genre items meeting the criteria.
+ ///
+ /// The .
+ /// The .
+ /// The .
+ /// The .
+ /// The start index.
+ /// The maximum number to return.
+ /// The .
private QueryResult GetMusicGenreItems(BaseItem item, Guid parentId, User user, SortCriteria sort, int? startIndex, int? limit)
{
var query = new InternalItemsQuery(user)
@@ -1259,7 +1591,7 @@ namespace Emby.Dlna.ContentDirectory
Recursive = true,
ParentId = parentId,
GenreIds = new[] { item.Id },
- IncludeItemTypes = new[] { typeof(MusicAlbum).Name },
+ IncludeItemTypes = new[] { nameof(MusicAlbum) },
Limit = limit,
StartIndex = startIndex,
DtoOptions = GetDtoOptions()
@@ -1272,7 +1604,12 @@ namespace Emby.Dlna.ContentDirectory
return ToResult(result);
}
- private QueryResult ToResult(BaseItem[] result)
+ ///
+ /// Converts a array into a .
+ ///
+ /// An array of .
+ /// A .
+ private static QueryResult ToResult(BaseItem[] result)
{
var serverItems = result
.Select(i => new ServerItem(i))
@@ -1285,7 +1622,12 @@ namespace Emby.Dlna.ContentDirectory
};
}
- private QueryResult ToResult(QueryResult result)
+ ///
+ /// Converts a to a .
+ ///
+ /// A .
+ /// The .
+ private static QueryResult ToResult(QueryResult result)
{
var serverItems = result
.Items
@@ -1299,7 +1641,13 @@ namespace Emby.Dlna.ContentDirectory
};
}
- private void SetSorting(InternalItemsQuery query, SortCriteria sort, bool isPreSorted)
+ ///
+ /// Sets the sorting method on a query.
+ ///
+ /// The .
+ /// The .
+ /// True if pre-sorted.
+ private static void SetSorting(InternalItemsQuery query, SortCriteria sort, bool isPreSorted)
{
if (isPreSorted)
{
@@ -1311,13 +1659,25 @@ namespace Emby.Dlna.ContentDirectory
}
}
- private QueryResult ApplyPaging(QueryResult result, int? startIndex, int? limit)
+ ///
+ /// Apply paging to a query.
+ ///
+ /// The .
+ /// The start index.
+ /// The maximum number to return.
+ /// A .
+ private static QueryResult ApplyPaging(QueryResult result, int? startIndex, int? limit)
{
result.Items = result.Items.Skip(startIndex ?? 0).Take(limit ?? int.MaxValue).ToArray();
return result;
}
+ ///
+ /// Retreives the ServerItem id.
+ ///
+ /// The id.
+ /// The .
private ServerItem GetItemFromObjectId(string id)
{
return DidlBuilder.IsIdRoot(id)
@@ -1326,6 +1686,11 @@ namespace Emby.Dlna.ContentDirectory
: ParseItemId(id);
}
+ ///
+ /// Parses the item id into a .
+ ///
+ /// The .
+ /// The corresponding .
private ServerItem ParseItemId(string id)
{
StubType? stubType = null;
@@ -1346,8 +1711,8 @@ namespace Emby.Dlna.ContentDirectory
{
if (id.StartsWith(name + "_", StringComparison.OrdinalIgnoreCase))
{
- stubType = (StubType)Enum.Parse(typeof(StubType), name, true);
- id = id.Split(new[] { '_' }, 2)[1];
+ stubType = Enum.Parse(name, true);
+ id = id.Split('_', 2)[1];
break;
}
diff --git a/Emby.Dlna/ContentDirectory/ServerItem.cs b/Emby.Dlna/ContentDirectory/ServerItem.cs
index e406054149..34244000c1 100644
--- a/Emby.Dlna/ContentDirectory/ServerItem.cs
+++ b/Emby.Dlna/ContentDirectory/ServerItem.cs
@@ -4,8 +4,15 @@ using MediaBrowser.Controller.Entities;
namespace Emby.Dlna.ContentDirectory
{
+ ///
+ /// Defines the .
+ ///
internal class ServerItem
{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The .
public ServerItem(BaseItem item)
{
Item = item;
@@ -16,8 +23,14 @@ namespace Emby.Dlna.ContentDirectory
}
}
+ ///
+ /// Gets or sets the underlying base item.
+ ///
public BaseItem Item { get; set; }
+ ///
+ /// Gets or sets the DLNA item type.
+ ///
public StubType? StubType { get; set; }
}
}
diff --git a/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs b/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs
index 921b14e394..7e3db46519 100644
--- a/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs
+++ b/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs
@@ -1,13 +1,18 @@
-#pragma warning disable CS1591
-
using System.Collections.Generic;
using Emby.Dlna.Common;
namespace Emby.Dlna.ContentDirectory
{
- public class ServiceActionListBuilder
+ ///
+ /// Defines the .
+ ///
+ public static class ServiceActionListBuilder
{
- public IEnumerable GetActions()
+ ///
+ /// Returns a list of services that this instance provides.
+ ///
+ /// An .
+ public static IEnumerable GetActions()
{
return new[]
{
@@ -22,6 +27,10 @@ namespace Emby.Dlna.ContentDirectory
};
}
+ ///
+ /// Returns the action details for "GetSystemUpdateID".
+ ///
+ /// The .
private static ServiceAction GetGetSystemUpdateIDAction()
{
var action = new ServiceAction
@@ -39,6 +48,10 @@ namespace Emby.Dlna.ContentDirectory
return action;
}
+ ///
+ /// Returns the action details for "GetSearchCapabilities".
+ ///
+ /// The .
private static ServiceAction GetSearchCapabilitiesAction()
{
var action = new ServiceAction
@@ -56,6 +69,10 @@ namespace Emby.Dlna.ContentDirectory
return action;
}
+ ///
+ /// Returns the action details for "GetSortCapabilities".
+ ///
+ /// The .
private static ServiceAction GetSortCapabilitiesAction()
{
var action = new ServiceAction
@@ -73,6 +90,10 @@ namespace Emby.Dlna.ContentDirectory
return action;
}
+ ///
+ /// Returns the action details for "X_GetFeatureList".
+ ///
+ /// The .
private static ServiceAction GetX_GetFeatureListAction()
{
var action = new ServiceAction
@@ -90,6 +111,10 @@ namespace Emby.Dlna.ContentDirectory
return action;
}
+ ///
+ /// Returns the action details for "Search".
+ ///
+ /// The .
private static ServiceAction GetSearchAction()
{
var action = new ServiceAction
@@ -170,7 +195,11 @@ namespace Emby.Dlna.ContentDirectory
return action;
}
- private ServiceAction GetBrowseAction()
+ ///
+ /// Returns the action details for "Browse".
+ ///
+ /// The .
+ private static ServiceAction GetBrowseAction()
{
var action = new ServiceAction
{
@@ -250,7 +279,11 @@ namespace Emby.Dlna.ContentDirectory
return action;
}
- private ServiceAction GetBrowseByLetterAction()
+ ///
+ /// Returns the action details for "X_BrowseByLetter".
+ ///
+ /// The .
+ private static ServiceAction GetBrowseByLetterAction()
{
var action = new ServiceAction
{
@@ -337,7 +370,11 @@ namespace Emby.Dlna.ContentDirectory
return action;
}
- private ServiceAction GetXSetBookmarkAction()
+ ///
+ /// Returns the action details for "X_SetBookmark".
+ ///
+ /// The .
+ private static ServiceAction GetXSetBookmarkAction()
{
var action = new ServiceAction
{
diff --git a/Emby.Dlna/ContentDirectory/StubType.cs b/Emby.Dlna/ContentDirectory/StubType.cs
index eee405d3e7..982ae5d68e 100644
--- a/Emby.Dlna/ContentDirectory/StubType.cs
+++ b/Emby.Dlna/ContentDirectory/StubType.cs
@@ -3,6 +3,9 @@
namespace Emby.Dlna.ContentDirectory
{
+ ///
+ /// Defines the DLNA item types.
+ ///
public enum StubType
{
Folder = 0,
diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs
index 5b8a89d8f3..abaf522bca 100644
--- a/Emby.Dlna/Didl/DidlBuilder.cs
+++ b/Emby.Dlna/Didl/DidlBuilder.cs
@@ -123,7 +123,7 @@ namespace Emby.Dlna.Didl
{
foreach (var att in profile.XmlRootAttributes)
{
- var parts = att.Name.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
+ var parts = att.Name.Split(':', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 2)
{
writer.WriteAttributeString(parts[0], parts[1], null, att.Value);
diff --git a/Emby.Dlna/Didl/Filter.cs b/Emby.Dlna/Didl/Filter.cs
index b58fdff2c9..d703f043eb 100644
--- a/Emby.Dlna/Didl/Filter.cs
+++ b/Emby.Dlna/Didl/Filter.cs
@@ -18,7 +18,7 @@ namespace Emby.Dlna.Didl
{
_all = string.Equals(filter, "*", StringComparison.OrdinalIgnoreCase);
- _fields = (filter ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
+ _fields = (filter ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries);
}
public bool Contains(string field)
diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs
index 1807ac6a13..069400833e 100644
--- a/Emby.Dlna/DlnaManager.cs
+++ b/Emby.Dlna/DlnaManager.cs
@@ -383,9 +383,9 @@ namespace Emby.Dlna
continue;
}
- var filename = Path.GetFileName(name).Substring(namespaceName.Length);
-
- var path = Path.Combine(systemProfilesPath, filename);
+ var path = Path.Join(
+ systemProfilesPath,
+ Path.GetFileName(name.AsSpan()).Slice(namespaceName.Length));
using (var stream = _assembly.GetManifestResourceStream(name))
{
diff --git a/Emby.Dlna/Emby.Dlna.csproj b/Emby.Dlna/Emby.Dlna.csproj
index 6ed49944c0..bd30cc1e11 100644
--- a/Emby.Dlna/Emby.Dlna.csproj
+++ b/Emby.Dlna/Emby.Dlna.csproj
@@ -17,7 +17,7 @@
- netstandard2.1
+ net5.0
false
true
true
diff --git a/Emby.Dlna/Eventing/DlnaEventManager.cs b/Emby.Dlna/Eventing/DlnaEventManager.cs
index 7d8da86ef9..b6e45c50ea 100644
--- a/Emby.Dlna/Eventing/DlnaEventManager.cs
+++ b/Emby.Dlna/Eventing/DlnaEventManager.cs
@@ -83,7 +83,7 @@ namespace Emby.Dlna.Eventing
if (!string.IsNullOrEmpty(header))
{
// Starts with SECOND-
- header = header.Split('-').Last();
+ header = header.Split('-')[^1];
if (int.TryParse(header, NumberStyles.Integer, _usCulture, out var val))
{
@@ -168,7 +168,7 @@ namespace Emby.Dlna.Eventing
builder.Append("");
- using var options = new HttpRequestMessage(new HttpMethod("NOTIFY"), subscription.CallbackUrl);
+ using var options = new HttpRequestMessage(new HttpMethod("NOTIFY"), subscription.CallbackUrl);
options.Content = new StringContent(builder.ToString(), Encoding.UTF8, MediaTypeNames.Text.Xml);
options.Headers.TryAddWithoutValidation("NT", subscription.NotificationType);
options.Headers.TryAddWithoutValidation("NTS", "upnp:propchange");
diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs
index 40c2cc0e0a..f8a00efaca 100644
--- a/Emby.Dlna/Main/DlnaEntryPoint.cs
+++ b/Emby.Dlna/Main/DlnaEntryPoint.cs
@@ -257,9 +257,10 @@ namespace Emby.Dlna.Main
private async Task RegisterServerEndpoints()
{
- var addresses = await _appHost.GetLocalIpAddresses(CancellationToken.None).ConfigureAwait(false);
+ var addresses = await _appHost.GetLocalIpAddresses().ConfigureAwait(false);
var udn = CreateUuid(_appHost.SystemId);
+ var descriptorUri = "/dlna/" + udn + "/description.xml";
foreach (var address in addresses)
{
@@ -279,7 +280,6 @@ namespace Emby.Dlna.Main
_logger.LogInformation("Registering publisher for {0} on {1}", fullService, address);
- var descriptorUri = "/dlna/" + udn + "/description.xml";
var uri = new Uri(_appHost.GetLocalApiUrl(address) + descriptorUri);
var device = new SsdpRootDevice
diff --git a/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs b/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs
index 8bf0cd961b..464f71a6f1 100644
--- a/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs
+++ b/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs
@@ -1,5 +1,3 @@
-#pragma warning disable CS1591
-
using System;
using System.Collections.Generic;
using System.Xml;
@@ -10,8 +8,16 @@ using Microsoft.Extensions.Logging;
namespace Emby.Dlna.MediaReceiverRegistrar
{
+ ///
+ /// Defines the .
+ ///
public class ControlHandler : BaseControlHandler
{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The for use with the instance.
+ /// The for use with the instance.
public ControlHandler(IServerConfigurationManager config, ILogger logger)
: base(config, logger)
{
@@ -35,9 +41,17 @@ namespace Emby.Dlna.MediaReceiverRegistrar
throw new ResourceNotFoundException("Unexpected control request name: " + methodName);
}
+ ///
+ /// Records that the handle is authorized in the xml stream.
+ ///
+ /// The .
private static void HandleIsAuthorized(XmlWriter xmlWriter)
=> xmlWriter.WriteElementString("Result", "1");
+ ///
+ /// Records that the handle is validated in the xml stream.
+ ///
+ /// The .
private static void HandleIsValidated(XmlWriter xmlWriter)
=> xmlWriter.WriteElementString("Result", "1");
}
diff --git a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarService.cs b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarService.cs
index e6d845e1e4..a5aae515c4 100644
--- a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarService.cs
+++ b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarService.cs
@@ -1,5 +1,3 @@
-#pragma warning disable CS1591
-
using System.Net.Http;
using System.Threading.Tasks;
using Emby.Dlna.Service;
@@ -8,10 +6,19 @@ using Microsoft.Extensions.Logging;
namespace Emby.Dlna.MediaReceiverRegistrar
{
+ ///
+ /// Defines the .
+ ///
public class MediaReceiverRegistrarService : BaseService, IMediaReceiverRegistrar
{
private readonly IServerConfigurationManager _config;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The for use with the instance.
+ /// The for use with the instance.
+ /// The for use with the instance.
public MediaReceiverRegistrarService(
ILogger logger,
IHttpClientFactory httpClientFactory,
@@ -24,7 +31,7 @@ namespace Emby.Dlna.MediaReceiverRegistrar
///
public string GetServiceXml()
{
- return new MediaReceiverRegistrarXmlBuilder().GetXml();
+ return MediaReceiverRegistrarXmlBuilder.GetXml();
}
///
diff --git a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs
index 26994925d1..37840cd096 100644
--- a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs
+++ b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs
@@ -1,79 +1,89 @@
-#pragma warning disable CS1591
-
using System.Collections.Generic;
using Emby.Dlna.Common;
using Emby.Dlna.Service;
+using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.MediaReceiverRegistrar
{
- public class MediaReceiverRegistrarXmlBuilder
+ ///
+ /// Defines the .
+ /// See https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-drmnd/5d37515e-7a63-4709-8258-8fd4e0ed4482.
+ ///
+ public static class MediaReceiverRegistrarXmlBuilder
{
- public string GetXml()
+ ///
+ /// Retrieves an XML description of the X_MS_MediaReceiverRegistrar.
+ ///
+ /// An XML representation of this service.
+ public static string GetXml()
{
- return new ServiceXmlBuilder().GetXml(
- new ServiceActionListBuilder().GetActions(),
- GetStateVariables());
+ return new ServiceXmlBuilder().GetXml(ServiceActionListBuilder.GetActions(), GetStateVariables());
}
+ ///
+ /// The a list of all the state variables for this invocation.
+ ///
+ /// The .
private static IEnumerable GetStateVariables()
{
- var list = new List();
-
- list.Add(new StateVariable
+ var list = new List
{
- Name = "AuthorizationGrantedUpdateID",
- DataType = "ui4",
- SendsEvents = true
- });
+ new StateVariable
+ {
+ Name = "AuthorizationGrantedUpdateID",
+ DataType = "ui4",
+ SendsEvents = true
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_DeviceID",
- DataType = "string",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_DeviceID",
+ DataType = "string",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "AuthorizationDeniedUpdateID",
- DataType = "ui4",
- SendsEvents = true
- });
+ new StateVariable
+ {
+ Name = "AuthorizationDeniedUpdateID",
+ DataType = "ui4",
+ SendsEvents = true
+ },
- list.Add(new StateVariable
- {
- Name = "ValidationSucceededUpdateID",
- DataType = "ui4",
- SendsEvents = true
- });
+ new StateVariable
+ {
+ Name = "ValidationSucceededUpdateID",
+ DataType = "ui4",
+ SendsEvents = true
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_RegistrationRespMsg",
- DataType = "bin.base64",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_RegistrationRespMsg",
+ DataType = "bin.base64",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_RegistrationReqMsg",
- DataType = "bin.base64",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_RegistrationReqMsg",
+ DataType = "bin.base64",
+ SendsEvents = false
+ },
- list.Add(new StateVariable
- {
- Name = "ValidationRevokedUpdateID",
- DataType = "ui4",
- SendsEvents = true
- });
+ new StateVariable
+ {
+ Name = "ValidationRevokedUpdateID",
+ DataType = "ui4",
+ SendsEvents = true
+ },
- list.Add(new StateVariable
- {
- Name = "A_ARG_TYPE_Result",
- DataType = "int",
- SendsEvents = false
- });
+ new StateVariable
+ {
+ Name = "A_ARG_TYPE_Result",
+ DataType = "int",
+ SendsEvents = false
+ }
+ };
return list;
}
diff --git a/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs b/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs
index 13545c6894..1dc9c79c14 100644
--- a/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs
+++ b/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs
@@ -1,13 +1,19 @@
-#pragma warning disable CS1591
-
using System.Collections.Generic;
using Emby.Dlna.Common;
+using MediaBrowser.Model.Dlna;
namespace Emby.Dlna.MediaReceiverRegistrar
{
- public class ServiceActionListBuilder
+ ///
+ /// Defines the .
+ ///
+ public static class ServiceActionListBuilder
{
- public IEnumerable GetActions()
+ ///
+ /// Returns a list of services that this instance provides.
+ ///
+ /// An .
+ public static IEnumerable GetActions()
{
return new[]
{
@@ -21,6 +27,10 @@ namespace Emby.Dlna.MediaReceiverRegistrar
};
}
+ ///
+ /// Returns the action details for "IsValidated".
+ ///
+ /// The .
private static ServiceAction GetIsValidated()
{
var action = new ServiceAction
@@ -43,6 +53,10 @@ namespace Emby.Dlna.MediaReceiverRegistrar
return action;
}
+ ///
+ /// Returns the action details for "IsAuthorized".
+ ///
+ /// The .
private static ServiceAction GetIsAuthorized()
{
var action = new ServiceAction
@@ -65,6 +79,10 @@ namespace Emby.Dlna.MediaReceiverRegistrar
return action;
}
+ ///
+ /// Returns the action details for "RegisterDevice".
+ ///
+ /// The .
private static ServiceAction GetRegisterDevice()
{
var action = new ServiceAction
@@ -87,6 +105,10 @@ namespace Emby.Dlna.MediaReceiverRegistrar
return action;
}
+ ///
+ /// Returns the action details for "GetValidationSucceededUpdateID".
+ ///
+ /// The .
private static ServiceAction GetGetValidationSucceededUpdateID()
{
var action = new ServiceAction
@@ -103,7 +125,11 @@ namespace Emby.Dlna.MediaReceiverRegistrar
return action;
}
- private ServiceAction GetGetAuthorizationDeniedUpdateID()
+ ///
+ /// Returns the action details for "GetGetAuthorizationDeniedUpdateID".
+ ///
+ /// The .
+ private static ServiceAction GetGetAuthorizationDeniedUpdateID()
{
var action = new ServiceAction
{
@@ -119,7 +145,11 @@ namespace Emby.Dlna.MediaReceiverRegistrar
return action;
}
- private ServiceAction GetGetValidationRevokedUpdateID()
+ ///
+ /// Returns the action details for "GetValidationRevokedUpdateID".
+ ///
+ /// The .
+ private static ServiceAction GetGetValidationRevokedUpdateID()
{
var action = new ServiceAction
{
@@ -135,7 +165,11 @@ namespace Emby.Dlna.MediaReceiverRegistrar
return action;
}
- private ServiceAction GetGetAuthorizationGrantedUpdateID()
+ ///
+ /// Returns the action details for "GetAuthorizationGrantedUpdateID".
+ ///
+ /// The .
+ private static ServiceAction GetGetAuthorizationGrantedUpdateID()
{
var action = new ServiceAction
{
diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs
index 460ac2d8d1..3907b2a396 100644
--- a/Emby.Dlna/PlayTo/PlayToController.cs
+++ b/Emby.Dlna/PlayTo/PlayToController.cs
@@ -326,7 +326,7 @@ namespace Emby.Dlna.PlayTo
public Task SendPlayCommand(PlayRequest command, CancellationToken cancellationToken)
{
- _logger.LogDebug("{0} - Received PlayRequest: {1}", this._session.DeviceName, command.PlayCommand);
+ _logger.LogDebug("{0} - Received PlayRequest: {1}", _session.DeviceName, command.PlayCommand);
var user = command.ControllingUserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(command.ControllingUserId);
@@ -339,7 +339,7 @@ namespace Emby.Dlna.PlayTo
var startIndex = command.StartIndex ?? 0;
if (startIndex > 0)
{
- items = items.Skip(startIndex).ToList();
+ items = items.GetRange(startIndex, items.Count - startIndex);
}
var playlist = new List();
@@ -811,7 +811,7 @@ namespace Emby.Dlna.PlayTo
}
///
- public Task SendMessage(string name, Guid messageId, T data, CancellationToken cancellationToken)
+ public Task SendMessage(SessionMessageType name, Guid messageId, T data, CancellationToken cancellationToken)
{
if (_disposed)
{
@@ -823,17 +823,17 @@ namespace Emby.Dlna.PlayTo
return Task.CompletedTask;
}
- if (string.Equals(name, "Play", StringComparison.OrdinalIgnoreCase))
+ if (name == SessionMessageType.Play)
{
return SendPlayCommand(data as PlayRequest, cancellationToken);
}
- if (string.Equals(name, "PlayState", StringComparison.OrdinalIgnoreCase))
+ if (name == SessionMessageType.PlayState)
{
return SendPlaystateCommand(data as PlaystateRequest, cancellationToken);
}
- if (string.Equals(name, "GeneralCommand", StringComparison.OrdinalIgnoreCase))
+ if (name == SessionMessageType.GeneralCommand)
{
return SendGeneralCommand(data as GeneralCommand, cancellationToken);
}
@@ -881,7 +881,10 @@ namespace Emby.Dlna.PlayTo
return null;
}
- mediaSource = await _mediaSourceManager.GetMediaSource(Item, MediaSourceId, LiveStreamId, false, cancellationToken).ConfigureAwait(false);
+ if (_mediaSourceManager != null)
+ {
+ mediaSource = await _mediaSourceManager.GetMediaSource(Item, MediaSourceId, LiveStreamId, false, cancellationToken).ConfigureAwait(false);
+ }
return mediaSource;
}
@@ -942,7 +945,10 @@ namespace Emby.Dlna.PlayTo
request.DeviceId = values.GetValueOrDefault("DeviceId");
request.MediaSourceId = values.GetValueOrDefault("MediaSourceId");
request.LiveStreamId = values.GetValueOrDefault("LiveStreamId");
- request.IsDirectStream = string.Equals("true", values.GetValueOrDefault("Static"), StringComparison.OrdinalIgnoreCase);
+
+ // Be careful, IsDirectStream==true by default (Static != false or not in query).
+ // See initialization of StreamingRequestDto in AudioController.GetAudioStream() method : Static = @static ?? true.
+ request.IsDirectStream = !string.Equals("false", values.GetValueOrDefault("Static"), StringComparison.OrdinalIgnoreCase);
request.AudioStreamIndex = GetIntValue(values, "AudioStreamIndex");
request.SubtitleStreamIndex = GetIntValue(values, "SubtitleStreamIndex");
diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs
index 21877f121f..e93aef3043 100644
--- a/Emby.Dlna/PlayTo/PlayToManager.cs
+++ b/Emby.Dlna/PlayTo/PlayToManager.cs
@@ -217,15 +217,15 @@ namespace Emby.Dlna.PlayTo
SupportedCommands = new[]
{
- GeneralCommandType.VolumeDown.ToString(),
- GeneralCommandType.VolumeUp.ToString(),
- GeneralCommandType.Mute.ToString(),
- GeneralCommandType.Unmute.ToString(),
- GeneralCommandType.ToggleMute.ToString(),
- GeneralCommandType.SetVolume.ToString(),
- GeneralCommandType.SetAudioStreamIndex.ToString(),
- GeneralCommandType.SetSubtitleStreamIndex.ToString(),
- GeneralCommandType.PlayMediaSource.ToString()
+ GeneralCommandType.VolumeDown,
+ GeneralCommandType.VolumeUp,
+ GeneralCommandType.Mute,
+ GeneralCommandType.Unmute,
+ GeneralCommandType.ToggleMute,
+ GeneralCommandType.SetVolume,
+ GeneralCommandType.SetAudioStreamIndex,
+ GeneralCommandType.SetSubtitleStreamIndex,
+ GeneralCommandType.PlayMediaSource
},
SupportsMediaControl = true
diff --git a/Emby.Dlna/PlayTo/SsdpHttpClient.cs b/Emby.Dlna/PlayTo/SsdpHttpClient.cs
index c8c36fc972..f4d7937907 100644
--- a/Emby.Dlna/PlayTo/SsdpHttpClient.cs
+++ b/Emby.Dlna/PlayTo/SsdpHttpClient.cs
@@ -45,7 +45,7 @@ namespace Emby.Dlna.PlayTo
header,
cancellationToken)
.ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
using var reader = new StreamReader(stream, Encoding.UTF8);
return XDocument.Parse(
await reader.ReadToEndAsync().ConfigureAwait(false),
@@ -94,7 +94,7 @@ namespace Emby.Dlna.PlayTo
options.Headers.UserAgent.ParseAdd(USERAGENT);
options.Headers.TryAddWithoutValidation("FriendlyName.DLNA.ORG", FriendlyName);
using var response = await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
using var reader = new StreamReader(stream, Encoding.UTF8);
return XDocument.Parse(
await reader.ReadToEndAsync().ConfigureAwait(false),
diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs
index d160e33393..198852ec17 100644
--- a/Emby.Dlna/Service/BaseControlHandler.cs
+++ b/Emby.Dlna/Service/BaseControlHandler.cs
@@ -60,10 +60,8 @@ namespace Emby.Dlna.Service
Async = true
};
- using (var reader = XmlReader.Create(streamReader, readerSettings))
- {
- requestInfo = await ParseRequestAsync(reader).ConfigureAwait(false);
- }
+ using var reader = XmlReader.Create(streamReader, readerSettings);
+ requestInfo = await ParseRequestAsync(reader).ConfigureAwait(false);
}
Logger.LogDebug("Received control request {0}", requestInfo.LocalName);
@@ -124,10 +122,8 @@ namespace Emby.Dlna.Service
{
if (!reader.IsEmptyElement)
{
- using (var subReader = reader.ReadSubtree())
- {
- return await ParseBodyTagAsync(subReader).ConfigureAwait(false);
- }
+ using var subReader = reader.ReadSubtree();
+ return await ParseBodyTagAsync(subReader).ConfigureAwait(false);
}
else
{
@@ -150,12 +146,12 @@ namespace Emby.Dlna.Service
}
}
- return new ControlRequestInfo();
+ throw new EndOfStreamException("Stream ended but no body tag found.");
}
private async Task ParseBodyTagAsync(XmlReader reader)
{
- var result = new ControlRequestInfo();
+ string namespaceURI = null, localName = null;
await reader.MoveToContentAsync().ConfigureAwait(false);
await reader.ReadAsync().ConfigureAwait(false);
@@ -165,16 +161,15 @@ namespace Emby.Dlna.Service
{
if (reader.NodeType == XmlNodeType.Element)
{
- result.LocalName = reader.LocalName;
- result.NamespaceURI = reader.NamespaceURI;
+ localName = reader.LocalName;
+ namespaceURI = reader.NamespaceURI;
if (!reader.IsEmptyElement)
{
- using (var subReader = reader.ReadSubtree())
- {
- await ParseFirstBodyChildAsync(subReader, result.Headers).ConfigureAwait(false);
- return result;
- }
+ var result = new ControlRequestInfo(localName, namespaceURI);
+ using var subReader = reader.ReadSubtree();
+ await ParseFirstBodyChildAsync(subReader, result.Headers).ConfigureAwait(false);
+ return result;
}
else
{
@@ -187,7 +182,12 @@ namespace Emby.Dlna.Service
}
}
- return result;
+ if (localName != null && namespaceURI != null)
+ {
+ return new ControlRequestInfo(localName, namespaceURI);
+ }
+
+ throw new EndOfStreamException("Stream ended but no control found.");
}
private async Task ParseFirstBodyChildAsync(XmlReader reader, IDictionary headers)
@@ -234,11 +234,18 @@ namespace Emby.Dlna.Service
private class ControlRequestInfo
{
+ public ControlRequestInfo(string localName, string namespaceUri)
+ {
+ LocalName = localName;
+ NamespaceURI = namespaceUri;
+ Headers = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ }
+
public string LocalName { get; set; }
public string NamespaceURI { get; set; }
- public Dictionary Headers { get; } = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ public Dictionary Headers { get; }
}
}
}
diff --git a/Emby.Drawing/Emby.Drawing.csproj b/Emby.Drawing/Emby.Drawing.csproj
index 092f8580a6..7d479a5c65 100644
--- a/Emby.Drawing/Emby.Drawing.csproj
+++ b/Emby.Drawing/Emby.Drawing.csproj
@@ -6,7 +6,7 @@
- netstandard2.1
+ net5.0
false
true
true
diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs
index ed20292f6b..8a2301d2d6 100644
--- a/Emby.Drawing/ImageProcessor.cs
+++ b/Emby.Drawing/ImageProcessor.cs
@@ -36,7 +36,7 @@ namespace Emby.Drawing
private readonly IImageEncoder _imageEncoder;
private readonly IMediaEncoder _mediaEncoder;
- private bool _disposed = false;
+ private bool _disposed;
///
/// Initializes a new instance of the class.
@@ -466,11 +466,11 @@ namespace Emby.Drawing
}
///
- public void CreateImageCollage(ImageCollageOptions options)
+ public void CreateImageCollage(ImageCollageOptions options, string? libraryName)
{
_logger.LogInformation("Creating image collage and saving to {Path}", options.OutputPath);
- _imageEncoder.CreateImageCollage(options);
+ _imageEncoder.CreateImageCollage(options, libraryName);
_logger.LogInformation("Completed creation of image collage and saved to {Path}", options.OutputPath);
}
diff --git a/Emby.Drawing/NullImageEncoder.cs b/Emby.Drawing/NullImageEncoder.cs
index bbb5c17162..2a1cfd3da5 100644
--- a/Emby.Drawing/NullImageEncoder.cs
+++ b/Emby.Drawing/NullImageEncoder.cs
@@ -38,7 +38,7 @@ namespace Emby.Drawing
}
///
- public void CreateImageCollage(ImageCollageOptions options)
+ public void CreateImageCollage(ImageCollageOptions options, string? libraryName)
{
throw new NotImplementedException();
}
diff --git a/Emby.Naming/Audio/AlbumParser.cs b/Emby.Naming/Audio/AlbumParser.cs
index b63be3a647..bbfdccc902 100644
--- a/Emby.Naming/Audio/AlbumParser.cs
+++ b/Emby.Naming/Audio/AlbumParser.cs
@@ -1,6 +1,3 @@
-#nullable enable
-#pragma warning disable CS1591
-
using System;
using System.Globalization;
using System.IO;
@@ -9,15 +6,27 @@ using Emby.Naming.Common;
namespace Emby.Naming.Audio
{
+ ///
+ /// Helper class to determine if Album is multipart.
+ ///
public class AlbumParser
{
private readonly NamingOptions _options;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Naming options containing AlbumStackingPrefixes.
public AlbumParser(NamingOptions options)
{
_options = options;
}
+ ///
+ /// Function that determines if album is multipart.
+ ///
+ /// Path to file.
+ /// True if album is multipart.
public bool IsMultiPart(string path)
{
var filename = Path.GetFileName(path);
diff --git a/Emby.Naming/Audio/AudioFileParser.cs b/Emby.Naming/Audio/AudioFileParser.cs
index 6b2f4be93e..8b47dd12e4 100644
--- a/Emby.Naming/Audio/AudioFileParser.cs
+++ b/Emby.Naming/Audio/AudioFileParser.cs
@@ -1,6 +1,3 @@
-#nullable enable
-#pragma warning disable CS1591
-
using System;
using System.IO;
using System.Linq;
@@ -8,8 +5,17 @@ using Emby.Naming.Common;
namespace Emby.Naming.Audio
{
+ ///
+ /// Static helper class to determine if file at path is audio file.
+ ///
public static class AudioFileParser
{
+ ///
+ /// Static helper method to determine if file at path is audio file.
+ ///
+ /// Path to file.
+ /// containing AudioFileExtensions.
+ /// True if file at path is audio file.
public static bool IsAudioFile(string path, NamingOptions options)
{
var extension = Path.GetExtension(path);
diff --git a/Emby.Naming/AudioBook/AudioBookFileInfo.cs b/Emby.Naming/AudioBook/AudioBookFileInfo.cs
index c4863b50ab..862e396677 100644
--- a/Emby.Naming/AudioBook/AudioBookFileInfo.cs
+++ b/Emby.Naming/AudioBook/AudioBookFileInfo.cs
@@ -7,6 +7,21 @@ namespace Emby.Naming.AudioBook
///
public class AudioBookFileInfo : IComparable
{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Path to audiobook file.
+ /// File type.
+ /// Number of part this file represents.
+ /// Number of chapter this file represents.
+ public AudioBookFileInfo(string path, string container, int? partNumber = default, int? chapterNumber = default)
+ {
+ Path = path;
+ Container = container;
+ PartNumber = partNumber;
+ ChapterNumber = chapterNumber;
+ }
+
///
/// Gets or sets the path.
///
@@ -31,14 +46,8 @@ namespace Emby.Naming.AudioBook
/// The chapter number.
public int? ChapterNumber { get; set; }
- ///
- /// Gets or sets a value indicating whether this instance is a directory.
- ///
- /// The type.
- public bool IsDirectory { get; set; }
-
///
- public int CompareTo(AudioBookFileInfo other)
+ public int CompareTo(AudioBookFileInfo? other)
{
if (ReferenceEquals(this, other))
{
diff --git a/Emby.Naming/AudioBook/AudioBookFilePathParser.cs b/Emby.Naming/AudioBook/AudioBookFilePathParser.cs
index 14edd64926..7b4429ab15 100644
--- a/Emby.Naming/AudioBook/AudioBookFilePathParser.cs
+++ b/Emby.Naming/AudioBook/AudioBookFilePathParser.cs
@@ -1,6 +1,3 @@
-#nullable enable
-#pragma warning disable CS1591
-
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
@@ -8,15 +5,27 @@ using Emby.Naming.Common;
namespace Emby.Naming.AudioBook
{
+ ///
+ /// Parser class to extract part and/or chapter number from audiobook filename.
+ ///
public class AudioBookFilePathParser
{
private readonly NamingOptions _options;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Naming options containing AudioBookPartsExpressions.
public AudioBookFilePathParser(NamingOptions options)
{
_options = options;
}
+ ///
+ /// Based on regex determines if filename includes part/chapter number.
+ ///
+ /// Path to audiobook file.
+ /// Returns object.
public AudioBookFilePathParserResult Parse(string path)
{
AudioBookFilePathParserResult result = default;
@@ -52,8 +61,6 @@ namespace Emby.Naming.AudioBook
}
}
- result.Success = result.ChapterNumber.HasValue || result.PartNumber.HasValue;
-
return result;
}
}
diff --git a/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs b/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs
index 7bfc4479d2..48ab8b57dc 100644
--- a/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs
+++ b/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs
@@ -1,14 +1,18 @@
-#nullable enable
-#pragma warning disable CS1591
-
namespace Emby.Naming.AudioBook
{
+ ///
+ /// Data object for passing result of audiobook part/chapter extraction.
+ ///
public struct AudioBookFilePathParserResult
{
+ ///
+ /// Gets or sets optional number of path extracted from audiobook filename.
+ ///
public int? PartNumber { get; set; }
+ ///
+ /// Gets or sets optional number of chapter extracted from audiobook filename.
+ ///
public int? ChapterNumber { get; set; }
-
- public bool Success { get; set; }
}
}
diff --git a/Emby.Naming/AudioBook/AudioBookInfo.cs b/Emby.Naming/AudioBook/AudioBookInfo.cs
index b0b5bd881f..adf403ab6d 100644
--- a/Emby.Naming/AudioBook/AudioBookInfo.cs
+++ b/Emby.Naming/AudioBook/AudioBookInfo.cs
@@ -10,11 +10,18 @@ namespace Emby.Naming.AudioBook
///
/// Initializes a new instance of the class.
///
- public AudioBookInfo()
+ /// Name of audiobook.
+ /// Year of audiobook release.
+ /// List of files composing the actual audiobook.
+ /// List of extra files.
+ /// Alternative version of files.
+ public AudioBookInfo(string name, int? year, List? files, List? extras, List? alternateVersions)
{
- Files = new List();
- Extras = new List();
- AlternateVersions = new List();
+ Name = name;
+ Year = year;
+ Files = files ?? new List();
+ Extras = extras ?? new List();
+ AlternateVersions = alternateVersions ?? new List();
}
///
diff --git a/Emby.Naming/AudioBook/AudioBookListResolver.cs b/Emby.Naming/AudioBook/AudioBookListResolver.cs
index f4ba11a0d1..e9ea9b7a5d 100644
--- a/Emby.Naming/AudioBook/AudioBookListResolver.cs
+++ b/Emby.Naming/AudioBook/AudioBookListResolver.cs
@@ -1,6 +1,6 @@
-#pragma warning disable CS1591
-
+using System;
using System.Collections.Generic;
+using System.IO;
using System.Linq;
using Emby.Naming.Common;
using Emby.Naming.Video;
@@ -8,40 +8,145 @@ using MediaBrowser.Model.IO;
namespace Emby.Naming.AudioBook
{
+ ///
+ /// Class used to resolve Name, Year, alternative files and extras from stack of files.
+ ///
public class AudioBookListResolver
{
private readonly NamingOptions _options;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Naming options passed along to and .
public AudioBookListResolver(NamingOptions options)
{
_options = options;
}
+ ///
+ /// Resolves Name, Year and differentiate alternative files and extras from regular audiobook files.
+ ///
+ /// List of files related to audiobook.
+ /// Returns IEnumerable of .
public IEnumerable Resolve(IEnumerable files)
{
var audioBookResolver = new AudioBookResolver(_options);
+ // File with empty fullname will be sorted out here.
var audiobookFileInfos = files
- .Select(i => audioBookResolver.Resolve(i.FullName, i.IsDirectory))
- .Where(i => i != null)
+ .Select(i => audioBookResolver.Resolve(i.FullName))
+ .OfType()
.ToList();
- // Filter out all extras, otherwise they could cause stacks to not be resolved
- // See the unit test TestStackedWithTrailer
- var metadata = audiobookFileInfos
- .Select(i => new FileSystemMetadata { FullName = i.Path, IsDirectory = i.IsDirectory });
-
var stackResult = new StackResolver(_options)
- .ResolveAudioBooks(metadata);
+ .ResolveAudioBooks(audiobookFileInfos);
foreach (var stack in stackResult)
{
- var stackFiles = stack.Files.Select(i => audioBookResolver.Resolve(i, stack.IsDirectoryStack)).ToList();
+ var stackFiles = stack.Files
+ .Select(i => audioBookResolver.Resolve(i))
+ .OfType()
+ .ToList();
+
stackFiles.Sort();
- var info = new AudioBookInfo { Files = stackFiles, Name = stack.Name };
+
+ var nameParserResult = new AudioBookNameParser(_options).Parse(stack.Name);
+
+ FindExtraAndAlternativeFiles(ref stackFiles, out var extras, out var alternativeVersions, nameParserResult);
+
+ var info = new AudioBookInfo(
+ nameParserResult.Name,
+ nameParserResult.Year,
+ stackFiles,
+ extras,
+ alternativeVersions);
yield return info;
}
}
+
+ private void FindExtraAndAlternativeFiles(ref List stackFiles, out List extras, out List alternativeVersions, AudioBookNameParserResult nameParserResult)
+ {
+ extras = new List();
+ alternativeVersions = new List();
+
+ var haveChaptersOrPages = stackFiles.Any(x => x.ChapterNumber != null || x.PartNumber != null);
+ var groupedBy = stackFiles.GroupBy(file => new { file.ChapterNumber, file.PartNumber });
+ var nameWithReplacedDots = nameParserResult.Name.Replace(" ", ".");
+
+ foreach (var group in groupedBy)
+ {
+ if (group.Key.ChapterNumber == null && group.Key.PartNumber == null)
+ {
+ if (group.Count() > 1 || haveChaptersOrPages)
+ {
+ var ex = new List();
+ var alt = new List();
+
+ foreach (var audioFile in group)
+ {
+ var name = Path.GetFileNameWithoutExtension(audioFile.Path);
+ if (name.Equals("audiobook") ||
+ name.Contains(nameParserResult.Name, StringComparison.OrdinalIgnoreCase) ||
+ name.Contains(nameWithReplacedDots, StringComparison.OrdinalIgnoreCase))
+ {
+ alt.Add(audioFile);
+ }
+ else
+ {
+ ex.Add(audioFile);
+ }
+ }
+
+ if (ex.Count > 0)
+ {
+ var extra = ex
+ .OrderBy(x => x.Container)
+ .ThenBy(x => x.Path)
+ .ToList();
+
+ stackFiles = stackFiles.Except(extra).ToList();
+ extras.AddRange(extra);
+ }
+
+ if (alt.Count > 0)
+ {
+ var alternatives = alt
+ .OrderBy(x => x.Container)
+ .ThenBy(x => x.Path)
+ .ToList();
+
+ var main = FindMainAudioBookFile(alternatives, nameParserResult.Name);
+ alternatives.Remove(main);
+ stackFiles = stackFiles.Except(alternatives).ToList();
+ alternativeVersions.AddRange(alternatives);
+ }
+ }
+ }
+ else if (group.Count() > 1)
+ {
+ var alternatives = group
+ .OrderBy(x => x.Container)
+ .ThenBy(x => x.Path)
+ .Skip(1)
+ .ToList();
+
+ stackFiles = stackFiles.Except(alternatives).ToList();
+ alternativeVersions.AddRange(alternatives);
+ }
+ }
+ }
+
+ private AudioBookFileInfo FindMainAudioBookFile(List files, string name)
+ {
+ var main = files.Find(x => Path.GetFileNameWithoutExtension(x.Path).Equals(name, StringComparison.OrdinalIgnoreCase));
+ main ??= files.FirstOrDefault(x => Path.GetFileNameWithoutExtension(x.Path).Equals("audiobook", StringComparison.OrdinalIgnoreCase));
+ main ??= files.OrderBy(x => x.Container)
+ .ThenBy(x => x.Path)
+ .First();
+
+ return main;
+ }
}
}
diff --git a/Emby.Naming/AudioBook/AudioBookNameParser.cs b/Emby.Naming/AudioBook/AudioBookNameParser.cs
new file mode 100644
index 0000000000..120482bc2c
--- /dev/null
+++ b/Emby.Naming/AudioBook/AudioBookNameParser.cs
@@ -0,0 +1,67 @@
+using System.Globalization;
+using System.Text.RegularExpressions;
+using Emby.Naming.Common;
+
+namespace Emby.Naming.AudioBook
+{
+ ///
+ /// Helper class to retrieve name and year from audiobook previously retrieved name.
+ ///
+ public class AudioBookNameParser
+ {
+ private readonly NamingOptions _options;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Naming options containing AudioBookNamesExpressions.
+ public AudioBookNameParser(NamingOptions options)
+ {
+ _options = options;
+ }
+
+ ///
+ /// Parse name and year from previously determined name of audiobook.
+ ///
+ /// Name of the audiobook.
+ /// Returns object.
+ public AudioBookNameParserResult Parse(string name)
+ {
+ AudioBookNameParserResult result = default;
+ foreach (var expression in _options.AudioBookNamesExpressions)
+ {
+ var match = new Regex(expression, RegexOptions.IgnoreCase).Match(name);
+ if (match.Success)
+ {
+ if (result.Name == null)
+ {
+ var value = match.Groups["name"];
+ if (value.Success)
+ {
+ result.Name = value.Value;
+ }
+ }
+
+ if (!result.Year.HasValue)
+ {
+ var value = match.Groups["year"];
+ if (value.Success)
+ {
+ if (int.TryParse(value.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intValue))
+ {
+ result.Year = intValue;
+ }
+ }
+ }
+ }
+ }
+
+ if (string.IsNullOrEmpty(result.Name))
+ {
+ result.Name = name;
+ }
+
+ return result;
+ }
+ }
+}
diff --git a/Emby.Naming/AudioBook/AudioBookNameParserResult.cs b/Emby.Naming/AudioBook/AudioBookNameParserResult.cs
new file mode 100644
index 0000000000..3f2d7b2b0b
--- /dev/null
+++ b/Emby.Naming/AudioBook/AudioBookNameParserResult.cs
@@ -0,0 +1,18 @@
+namespace Emby.Naming.AudioBook
+{
+ ///
+ /// Data object used to pass result of name and year parsing.
+ ///
+ public struct AudioBookNameParserResult
+ {
+ ///
+ /// Gets or sets name of audiobook.
+ ///
+ public string Name { get; set; }
+
+ ///
+ /// Gets or sets optional year of release.
+ ///
+ public int? Year { get; set; }
+ }
+}
diff --git a/Emby.Naming/AudioBook/AudioBookResolver.cs b/Emby.Naming/AudioBook/AudioBookResolver.cs
index ed53bd04fa..f6ad3601d7 100644
--- a/Emby.Naming/AudioBook/AudioBookResolver.cs
+++ b/Emby.Naming/AudioBook/AudioBookResolver.cs
@@ -1,5 +1,3 @@
-#pragma warning disable CS1591
-
using System;
using System.IO;
using System.Linq;
@@ -7,35 +5,32 @@ using Emby.Naming.Common;
namespace Emby.Naming.AudioBook
{
+ ///
+ /// Resolve specifics (path, container, partNumber, chapterNumber) about audiobook file.
+ ///
public class AudioBookResolver
{
private readonly NamingOptions _options;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// containing AudioFileExtensions and also used to pass to AudioBookFilePathParser.
public AudioBookResolver(NamingOptions options)
{
_options = options;
}
- public AudioBookFileInfo ParseFile(string path)
+ ///
+ /// Resolve specifics (path, container, partNumber, chapterNumber) about audiobook file.
+ ///
+ /// Path to audiobook file.
+ /// Returns object.
+ public AudioBookFileInfo? Resolve(string path)
{
- return Resolve(path, false);
- }
-
- public AudioBookFileInfo ParseDirectory(string path)
- {
- return Resolve(path, true);
- }
-
- public AudioBookFileInfo Resolve(string path, bool isDirectory = false)
- {
- if (string.IsNullOrEmpty(path))
- {
- throw new ArgumentNullException(nameof(path));
- }
-
- // TODO
- if (isDirectory)
+ if (path.Length == 0 || Path.GetFileNameWithoutExtension(path).Length == 0)
{
+ // Return null to indicate this path will not be used, instead of stopping whole process with exception
return null;
}
@@ -51,14 +46,11 @@ namespace Emby.Naming.AudioBook
var parsingResult = new AudioBookFilePathParser(_options).Parse(path);
- return new AudioBookFileInfo
- {
- Path = path,
- Container = container,
- ChapterNumber = parsingResult.ChapterNumber,
- PartNumber = parsingResult.PartNumber,
- IsDirectory = isDirectory
- };
+ return new AudioBookFileInfo(
+ path,
+ container,
+ chapterNumber: parsingResult.ChapterNumber,
+ partNumber: parsingResult.PartNumber);
}
}
}
diff --git a/Emby.Naming/Common/EpisodeExpression.cs b/Emby.Naming/Common/EpisodeExpression.cs
index ed6ba8881c..19d3c7aab0 100644
--- a/Emby.Naming/Common/EpisodeExpression.cs
+++ b/Emby.Naming/Common/EpisodeExpression.cs
@@ -1,28 +1,32 @@
-#pragma warning disable CS1591
-
using System;
using System.Text.RegularExpressions;
namespace Emby.Naming.Common
{
+ ///
+ /// Regular expressions for parsing TV Episodes.
+ ///
public class EpisodeExpression
{
private string _expression;
- private Regex _regex;
+ private Regex? _regex;
- public EpisodeExpression(string expression, bool byDate)
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Regular expressions.
+ /// True if date is expected.
+ public EpisodeExpression(string expression, bool byDate = false)
{
- Expression = expression;
+ _expression = expression;
IsByDate = byDate;
DateTimeFormats = Array.Empty();
SupportsAbsoluteEpisodeNumbers = true;
}
- public EpisodeExpression(string expression)
- : this(expression, false)
- {
- }
-
+ ///
+ /// Gets or sets raw expressions string.
+ ///
public string Expression
{
get => _expression;
@@ -33,16 +37,34 @@ namespace Emby.Naming.Common
}
}
+ ///
+ /// Gets or sets a value indicating whether gets or sets property indicating if date can be find in expression.
+ ///
public bool IsByDate { get; set; }
+ ///
+ /// Gets or sets a value indicating whether gets or sets property indicating if expression is optimistic.
+ ///
public bool IsOptimistic { get; set; }
+ ///
+ /// Gets or sets a value indicating whether gets or sets property indicating if expression is named.
+ ///
public bool IsNamed { get; set; }
+ ///
+ /// Gets or sets a value indicating whether gets or sets property indicating if expression supports episodes with absolute numbers.
+ ///
public bool SupportsAbsoluteEpisodeNumbers { get; set; }
+ ///
+ /// Gets or sets optional list of date formats used for date parsing.
+ ///
public string[] DateTimeFormats { get; set; }
+ ///
+ /// Gets a expressions objects (creates it if null).
+ ///
public Regex Regex => _regex ??= new Regex(Expression, RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
}
diff --git a/Emby.Naming/Common/MediaType.cs b/Emby.Naming/Common/MediaType.cs
index 148833765f..dc9784c6da 100644
--- a/Emby.Naming/Common/MediaType.cs
+++ b/Emby.Naming/Common/MediaType.cs
@@ -1,7 +1,8 @@
-#pragma warning disable CS1591
-
namespace Emby.Naming.Common
{
+ ///
+ /// Type of audiovisual media.
+ ///
public enum MediaType
{
///
diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs
index fd4244f64d..035d1b2280 100644
--- a/Emby.Naming/Common/NamingOptions.cs
+++ b/Emby.Naming/Common/NamingOptions.cs
@@ -1,15 +1,21 @@
-#pragma warning disable CS1591
-
using System;
using System.Linq;
using System.Text.RegularExpressions;
using Emby.Naming.Video;
using MediaBrowser.Model.Entities;
+// ReSharper disable StringLiteralTypo
+
namespace Emby.Naming.Common
{
+ ///
+ /// Big ugly class containing lot of different naming options that should be split and injected instead of passes everywhere.
+ ///
public class NamingOptions
{
+ ///
+ /// Initializes a new instance of the class.
+ ///
public NamingOptions()
{
VideoFileExtensions = new[]
@@ -75,63 +81,52 @@ namespace Emby.Naming.Common
StubTypes = new[]
{
- new StubTypeRule
- {
- StubType = "dvd",
- Token = "dvd"
- },
- new StubTypeRule
- {
- StubType = "hddvd",
- Token = "hddvd"
- },
- new StubTypeRule
- {
- StubType = "bluray",
- Token = "bluray"
- },
- new StubTypeRule
- {
- StubType = "bluray",
- Token = "brrip"
- },
- new StubTypeRule
- {
- StubType = "bluray",
- Token = "bd25"
- },
- new StubTypeRule
- {
- StubType = "bluray",
- Token = "bd50"
- },
- new StubTypeRule
- {
- StubType = "vhs",
- Token = "vhs"
- },
- new StubTypeRule
- {
- StubType = "tv",
- Token = "HDTV"
- },
- new StubTypeRule
- {
- StubType = "tv",
- Token = "PDTV"
- },
- new StubTypeRule
- {
- StubType = "tv",
- Token = "DSR"
- }
+ new StubTypeRule(
+ stubType: "dvd",
+ token: "dvd"),
+
+ new StubTypeRule(
+ stubType: "hddvd",
+ token: "hddvd"),
+
+ new StubTypeRule(
+ stubType: "bluray",
+ token: "bluray"),
+
+ new StubTypeRule(
+ stubType: "bluray",
+ token: "brrip"),
+
+ new StubTypeRule(
+ stubType: "bluray",
+ token: "bd25"),
+
+ new StubTypeRule(
+ stubType: "bluray",
+ token: "bd50"),
+
+ new StubTypeRule(
+ stubType: "vhs",
+ token: "vhs"),
+
+ new StubTypeRule(
+ stubType: "tv",
+ token: "HDTV"),
+
+ new StubTypeRule(
+ stubType: "tv",
+ token: "PDTV"),
+
+ new StubTypeRule(
+ stubType: "tv",
+ token: "DSR")
};
VideoFileStackingExpressions = new[]
{
- "(.*?)([ _.-]*(?:cd|dvd|p(?:ar)?t|dis[ck])[ _.-]*[0-9]+)(.*?)(\\.[^.]+)$",
- "(.*?)([ _.-]*(?:cd|dvd|p(?:ar)?t|dis[ck])[ _.-]*[a-d])(.*?)(\\.[^.]+)$",
- "(.*?)([ ._-]*[a-d])(.*?)(\\.[^.]+)$"
+ "(?.*?)(?[ _.-]*(?:cd|dvd|p(?:ar)?t|dis[ck])[ _.-]*[0-9]+)(?.*?)(?\\.[^.]+)$",
+ "(?.*?)(?[ _.-]*(?:cd|dvd|p(?:ar)?t|dis[ck])[ _.-]*[a-d])(?.*?)(?\\.[^.]+)$",
+ "(?.*?)(?[ ._-]*[a-d])(?.*?)(?\\.[^.]+)$"
};
CleanDateTimes = new[]
@@ -142,7 +137,7 @@ namespace Emby.Naming.Common
CleanStrings = new[]
{
- @"[ _\,\.\(\)\[\]\-](3d|sbs|tab|hsbs|htab|mvc|HDR|HDC|UHD|UltraHD|4k|ac3|dts|custom|dc|divx|divx5|dsr|dsrip|dutch|dvd|dvdrip|dvdscr|dvdscreener|screener|dvdivx|cam|fragment|fs|hdtv|hdrip|hdtvrip|internal|limited|multisubs|ntsc|ogg|ogm|pal|pdtv|proper|repack|rerip|retail|cd[1-9]|r3|r5|bd5|bd|se|svcd|swedish|german|read.nfo|nfofix|unrated|ws|telesync|ts|telecine|tc|brrip|bdrip|480p|480i|576p|576i|720p|720i|1080p|1080i|2160p|hrhd|hrhdtv|hddvd|bluray|x264|h264|xvid|xvidvd|xxx|www.www|\[.*\])([ _\,\.\(\)\[\]\-]|$)",
+ @"[ _\,\.\(\)\[\]\-](3d|sbs|tab|hsbs|htab|mvc|HDR|HDC|UHD|UltraHD|4k|ac3|dts|custom|dc|divx|divx5|dsr|dsrip|dutch|dvd|dvdrip|dvdscr|dvdscreener|screener|dvdivx|cam|fragment|fs|hdtv|hdrip|hdtvrip|internal|limited|multisubs|ntsc|ogg|ogm|pal|pdtv|proper|repack|rerip|retail|cd[1-9]|r3|r5|bd5|bd|se|svcd|swedish|german|read.nfo|nfofix|unrated|ws|telesync|ts|telecine|tc|brrip|bdrip|480p|480i|576p|576i|720p|720i|1080p|1080i|2160p|hrhd|hrhdtv|hddvd|bluray|blu-ray|x264|x265|h264|xvid|xvidvd|xxx|www.www|AAC|DTS|\[.*\])([ _\,\.\(\)\[\]\-]|$)",
@"(\[.*\])"
};
@@ -255,7 +250,7 @@ namespace Emby.Naming.Common
},
//
new EpisodeExpression(@"[\._ -]()[Ee][Pp]_?([0-9]+)([^\\/]*)$"),
- new EpisodeExpression("([0-9]{4})[\\.-]([0-9]{2})[\\.-]([0-9]{2})", true)
+ new EpisodeExpression("(?[0-9]{4})[\\.-](?[0-9]{2})[\\.-](?[0-9]{2})", true)
{
DateTimeFormats = new[]
{
@@ -264,7 +259,7 @@ namespace Emby.Naming.Common
"yyyy_MM_dd"
}
},
- new EpisodeExpression("([0-9]{2})[\\.-]([0-9]{2})[\\.-]([0-9]{4})", true)
+ new EpisodeExpression(@"(?[0-9]{2})[.-](?[0-9]{2})[.-](?[0-9]{4})", true)
{
DateTimeFormats = new[]
{
@@ -286,7 +281,12 @@ namespace Emby.Naming.Common
{
SupportsAbsoluteEpisodeNumbers = true
},
- new EpisodeExpression(@"[\\\\/\\._ -](?(?![0-9]+[0-9][0-9])([^\\\/])*)[\\\\/\\._ -](?[0-9]+)(?[0-9][0-9](?:(?:[a-i]|\\.[1-9])(?![0-9]))?)([\\._ -][^\\\\/]*)$")
+
+ // Case Closed (1996-2007)/Case Closed - 317.mkv
+ // /server/anything_102.mp4
+ // /server/james.corden.2017.04.20.anne.hathaway.720p.hdtv.x264-crooks.mkv
+ // /server/anything_1996.11.14.mp4
+ new EpisodeExpression(@"[\\/._ -](?(?![0-9]+[0-9][0-9])([^\\\/_])*)[\\\/._ -](?[0-9]+)(?[0-9][0-9](?:(?:[a-i]|\.[1-9])(?![0-9]))?)([._ -][^\\\/]*)$")
{
IsOptimistic = true,
IsNamed = true,
@@ -381,247 +381,193 @@ namespace Emby.Naming.Common
VideoExtraRules = new[]
{
- new ExtraRule
- {
- ExtraType = ExtraType.Trailer,
- RuleType = ExtraRuleType.Filename,
- Token = "trailer",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Trailer,
- RuleType = ExtraRuleType.Suffix,
- Token = "-trailer",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Trailer,
- RuleType = ExtraRuleType.Suffix,
- Token = ".trailer",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Trailer,
- RuleType = ExtraRuleType.Suffix,
- Token = "_trailer",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Trailer,
- RuleType = ExtraRuleType.Suffix,
- Token = " trailer",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Sample,
- RuleType = ExtraRuleType.Filename,
- Token = "sample",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Sample,
- RuleType = ExtraRuleType.Suffix,
- Token = "-sample",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Sample,
- RuleType = ExtraRuleType.Suffix,
- Token = ".sample",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Sample,
- RuleType = ExtraRuleType.Suffix,
- Token = "_sample",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Sample,
- RuleType = ExtraRuleType.Suffix,
- Token = " sample",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = ExtraType.ThemeSong,
- RuleType = ExtraRuleType.Filename,
- Token = "theme",
- MediaType = MediaType.Audio
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Scene,
- RuleType = ExtraRuleType.Suffix,
- Token = "-scene",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Clip,
- RuleType = ExtraRuleType.Suffix,
- Token = "-clip",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Interview,
- RuleType = ExtraRuleType.Suffix,
- Token = "-interview",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = ExtraType.BehindTheScenes,
- RuleType = ExtraRuleType.Suffix,
- Token = "-behindthescenes",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = ExtraType.DeletedScene,
- RuleType = ExtraRuleType.Suffix,
- Token = "-deleted",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Clip,
- RuleType = ExtraRuleType.Suffix,
- Token = "-featurette",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Clip,
- RuleType = ExtraRuleType.Suffix,
- Token = "-short",
- MediaType = MediaType.Video
- },
- new ExtraRule
- {
- ExtraType = ExtraType.BehindTheScenes,
- RuleType = ExtraRuleType.DirectoryName,
- Token = "behind the scenes",
- MediaType = MediaType.Video,
- },
- new ExtraRule
- {
- ExtraType = ExtraType.DeletedScene,
- RuleType = ExtraRuleType.DirectoryName,
- Token = "deleted scenes",
- MediaType = MediaType.Video,
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Interview,
- RuleType = ExtraRuleType.DirectoryName,
- Token = "interviews",
- MediaType = MediaType.Video,
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Scene,
- RuleType = ExtraRuleType.DirectoryName,
- Token = "scenes",
- MediaType = MediaType.Video,
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Sample,
- RuleType = ExtraRuleType.DirectoryName,
- Token = "samples",
- MediaType = MediaType.Video,
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Clip,
- RuleType = ExtraRuleType.DirectoryName,
- Token = "shorts",
- MediaType = MediaType.Video,
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Clip,
- RuleType = ExtraRuleType.DirectoryName,
- Token = "featurettes",
- MediaType = MediaType.Video,
- },
- new ExtraRule
- {
- ExtraType = ExtraType.Unknown,
- RuleType = ExtraRuleType.DirectoryName,
- Token = "extras",
- MediaType = MediaType.Video,
- },
+ new ExtraRule(
+ ExtraType.Trailer,
+ ExtraRuleType.Filename,
+ "trailer",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Trailer,
+ ExtraRuleType.Suffix,
+ "-trailer",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Trailer,
+ ExtraRuleType.Suffix,
+ ".trailer",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Trailer,
+ ExtraRuleType.Suffix,
+ "_trailer",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Trailer,
+ ExtraRuleType.Suffix,
+ " trailer",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Sample,
+ ExtraRuleType.Filename,
+ "sample",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Sample,
+ ExtraRuleType.Suffix,
+ "-sample",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Sample,
+ ExtraRuleType.Suffix,
+ ".sample",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Sample,
+ ExtraRuleType.Suffix,
+ "_sample",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Sample,
+ ExtraRuleType.Suffix,
+ " sample",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.ThemeSong,
+ ExtraRuleType.Filename,
+ "theme",
+ MediaType.Audio),
+
+ new ExtraRule(
+ ExtraType.Scene,
+ ExtraRuleType.Suffix,
+ "-scene",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Clip,
+ ExtraRuleType.Suffix,
+ "-clip",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Interview,
+ ExtraRuleType.Suffix,
+ "-interview",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.BehindTheScenes,
+ ExtraRuleType.Suffix,
+ "-behindthescenes",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.DeletedScene,
+ ExtraRuleType.Suffix,
+ "-deleted",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Clip,
+ ExtraRuleType.Suffix,
+ "-featurette",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Clip,
+ ExtraRuleType.Suffix,
+ "-short",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.BehindTheScenes,
+ ExtraRuleType.DirectoryName,
+ "behind the scenes",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.DeletedScene,
+ ExtraRuleType.DirectoryName,
+ "deleted scenes",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Interview,
+ ExtraRuleType.DirectoryName,
+ "interviews",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Scene,
+ ExtraRuleType.DirectoryName,
+ "scenes",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Sample,
+ ExtraRuleType.DirectoryName,
+ "samples",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Clip,
+ ExtraRuleType.DirectoryName,
+ "shorts",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Clip,
+ ExtraRuleType.DirectoryName,
+ "featurettes",
+ MediaType.Video),
+
+ new ExtraRule(
+ ExtraType.Unknown,
+ ExtraRuleType.DirectoryName,
+ "extras",
+ MediaType.Video),
};
Format3DRules = new[]
{
// Kodi rules:
- new Format3DRule
- {
- PreceedingToken = "3d",
- Token = "hsbs"
- },
- new Format3DRule
- {
- PreceedingToken = "3d",
- Token = "sbs"
- },
- new Format3DRule
- {
- PreceedingToken = "3d",
- Token = "htab"
- },
- new Format3DRule
- {
- PreceedingToken = "3d",
- Token = "tab"
- },
- // Media Browser rules:
- new Format3DRule
- {
- Token = "fsbs"
- },
- new Format3DRule
- {
- Token = "hsbs"
- },
- new Format3DRule
- {
- Token = "sbs"
- },
- new Format3DRule
- {
- Token = "ftab"
- },
- new Format3DRule
- {
- Token = "htab"
- },
- new Format3DRule
- {
- Token = "tab"
- },
- new Format3DRule
- {
- Token = "sbs3d"
- },
- new Format3DRule
- {
- Token = "mvc"
- }
+ new Format3DRule(
+ precedingToken: "3d",
+ token: "hsbs"),
+
+ new Format3DRule(
+ precedingToken: "3d",
+ token: "sbs"),
+
+ new Format3DRule(
+ precedingToken: "3d",
+ token: "htab"),
+
+ new Format3DRule(
+ precedingToken: "3d",
+ token: "tab"),
+
+ // Media Browser rules:
+ new Format3DRule("fsbs"),
+ new Format3DRule("hsbs"),
+ new Format3DRule("sbs"),
+ new Format3DRule("ftab"),
+ new Format3DRule("htab"),
+ new Format3DRule("tab"),
+ new Format3DRule("sbs3d"),
+ new Format3DRule("mvc")
};
+
AudioBookPartsExpressions = new[]
{
// Detect specified chapters, like CH 01
@@ -631,13 +577,20 @@ namespace Emby.Naming.Common
// Chapter is often beginning of filename
"^(?[0-9]+)",
// Part if often ending of filename
- "(?[0-9]+)$",
+ @"(?[0-9]+)$",
// Sometimes named as 0001_005 (chapter_part)
"(?[0-9]+)_(?[0-9]+)",
// Some audiobooks are ripped from cd's, and will be named by disk number.
@"dis(?:c|k)[\s_-]?(?[0-9]+)"
};
+ AudioBookNamesExpressions = new[]
+ {
+ // Detect year usually in brackets after name Batman (2020)
+ @"^(?.+?)\s*\(\s*(?\d{4})\s*\)\s*$",
+ @"^\s*(?[^ ].*?)\s*$"
+ };
+
var extensions = VideoFileExtensions.ToList();
extensions.AddRange(new[]
@@ -673,7 +626,7 @@ namespace Emby.Naming.Common
".mxf"
});
- MultipleEpisodeExpressions = new string[]
+ MultipleEpisodeExpressions = new[]
{
@".*(\\|\/)[sS]?(?[0-9]{1,4})[xX](?[0-9]{1,3})((-| - )[0-9]{1,4}[eExX](?[0-9]{1,3}))+[^\\\/]*$",
@".*(\\|\/)[sS]?(?[0-9]{1,4})[xX](?[0-9]{1,3})((-| - )[0-9]{1,4}[xX][eE](?[0-9]{1,3}))+[^\\\/]*$",
@@ -697,56 +650,139 @@ namespace Emby.Naming.Common
Compile();
}
+ ///
+ /// Gets or sets list of audio file extensions.
+ ///
public string[] AudioFileExtensions { get; set; }
+ ///
+ /// Gets or sets list of album stacking prefixes.
+ ///
public string[] AlbumStackingPrefixes { get; set; }
+ ///
+ /// Gets or sets list of subtitle file extensions.
+ ///
public string[] SubtitleFileExtensions { get; set; }
+ ///
+ /// Gets or sets list of subtitles flag delimiters.
+ ///
public char[] SubtitleFlagDelimiters { get; set; }
+ ///
+ /// Gets or sets list of subtitle forced flags.
+ ///
public string[] SubtitleForcedFlags { get; set; }
+ ///
+ /// Gets or sets list of subtitle default flags.
+ ///
public string[] SubtitleDefaultFlags { get; set; }
+ ///
+ /// Gets or sets list of episode regular expressions.
+ ///
public EpisodeExpression[] EpisodeExpressions { get; set; }
+ ///
+ /// Gets or sets list of raw episode without season regular expressions strings.
+ ///
public string[] EpisodeWithoutSeasonExpressions { get; set; }
+ ///
+ /// Gets or sets list of raw multi-part episodes regular expressions strings.
+ ///
public string[] EpisodeMultiPartExpressions { get; set; }
+ ///
+ /// Gets or sets list of video file extensions.
+ ///
public string[] VideoFileExtensions { get; set; }
+ ///
+ /// Gets or sets list of video stub file extensions.
+ ///
public string[] StubFileExtensions { get; set; }
+ ///
+ /// Gets or sets list of raw audiobook parts regular expressions strings.
+ ///
public string[] AudioBookPartsExpressions { get; set; }
+ ///
+ /// Gets or sets list of raw audiobook names regular expressions strings.
+ ///
+ public string[] AudioBookNamesExpressions { get; set; }
+
+ ///
+ /// Gets or sets list of stub type rules.
+ ///
public StubTypeRule[] StubTypes { get; set; }
+ ///
+ /// Gets or sets list of video flag delimiters.
+ ///
public char[] VideoFlagDelimiters { get; set; }
+ ///
+ /// Gets or sets list of 3D Format rules.
+ ///
public Format3DRule[] Format3DRules { get; set; }
+ ///
+ /// Gets or sets list of raw video file-stacking expressions strings.
+ ///
public string[] VideoFileStackingExpressions { get; set; }
+ ///
+ /// Gets or sets list of raw clean DateTimes regular expressions strings.
+ ///
public string[] CleanDateTimes { get; set; }
+ ///
+ /// Gets or sets list of raw clean strings regular expressions strings.
+ ///
public string[] CleanStrings { get; set; }
+ ///
+ /// Gets or sets list of multi-episode regular expressions.
+ ///
public EpisodeExpression[] MultipleEpisodeExpressions { get; set; }
+ ///
+ /// Gets or sets list of extra rules for videos.
+ ///
public ExtraRule[] VideoExtraRules { get; set; }
- public Regex[] VideoFileStackingRegexes { get; private set; }
+ ///
+ /// Gets list of video file-stack regular expressions.
+ ///
+ public Regex[] VideoFileStackingRegexes { get; private set; } = Array.Empty();
- public Regex[] CleanDateTimeRegexes { get; private set; }
+ ///
+ /// Gets list of clean datetime regular expressions.
+ ///
+ public Regex[] CleanDateTimeRegexes { get; private set; } = Array.Empty();
- public Regex[] CleanStringRegexes { get; private set; }
+ ///
+ /// Gets list of clean string regular expressions.
+ ///
+ public Regex[] CleanStringRegexes { get; private set; } = Array.Empty();
- public Regex[] EpisodeWithoutSeasonRegexes { get; private set; }
+ ///
+ /// Gets list of episode without season regular expressions.
+ ///
+ public Regex[] EpisodeWithoutSeasonRegexes { get; private set; } = Array.Empty();
- public Regex[] EpisodeMultiPartRegexes { get; private set; }
+ ///
+ /// Gets list of multi-part episode regular expressions.
+ ///
+ public Regex[] EpisodeMultiPartRegexes { get; private set; } = Array.Empty();
+ ///
+ /// Compiles raw regex strings into regexes.
+ ///
public void Compile()
{
VideoFileStackingRegexes = VideoFileStackingExpressions.Select(Compile).ToArray();
diff --git a/Emby.Naming/Emby.Naming.csproj b/Emby.Naming/Emby.Naming.csproj
index 6857f9952c..24c15759d4 100644
--- a/Emby.Naming/Emby.Naming.csproj
+++ b/Emby.Naming/Emby.Naming.csproj
@@ -6,7 +6,7 @@
- netstandard2.1
+ net5.0
false
true
true
@@ -14,6 +14,7 @@
true
true
snupkg
+ enable
@@ -38,7 +39,7 @@
-
+
diff --git a/Emby.Naming/Subtitles/SubtitleInfo.cs b/Emby.Naming/Subtitles/SubtitleInfo.cs
index f39c496b7a..1fb2e0dc89 100644
--- a/Emby.Naming/Subtitles/SubtitleInfo.cs
+++ b/Emby.Naming/Subtitles/SubtitleInfo.cs
@@ -1,9 +1,23 @@
-#pragma warning disable CS1591
-
namespace Emby.Naming.Subtitles
{
+ ///
+ /// Class holding information about subtitle.
+ ///
public class SubtitleInfo
{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Path to file.
+ /// Is subtitle default.
+ /// Is subtitle forced.
+ public SubtitleInfo(string path, bool isDefault, bool isForced)
+ {
+ Path = path;
+ IsDefault = isDefault;
+ IsForced = isForced;
+ }
+
///
/// Gets or sets the path.
///
@@ -14,7 +28,7 @@ namespace Emby.Naming.Subtitles
/// Gets or sets the language.
///
/// The language.
- public string Language { get; set; }
+ public string? Language { get; set; }
///
/// Gets or sets a value indicating whether this instance is default.
diff --git a/Emby.Naming/Subtitles/SubtitleParser.cs b/Emby.Naming/Subtitles/SubtitleParser.cs
index 24e59f90a3..e872452519 100644
--- a/Emby.Naming/Subtitles/SubtitleParser.cs
+++ b/Emby.Naming/Subtitles/SubtitleParser.cs
@@ -1,6 +1,3 @@
-#nullable enable
-#pragma warning disable CS1591
-
using System;
using System.IO;
using System.Linq;
@@ -8,20 +5,32 @@ using Emby.Naming.Common;
namespace Emby.Naming.Subtitles
{
+ ///
+ /// Subtitle Parser class.
+ ///
public class SubtitleParser
{
private readonly NamingOptions _options;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// object containing SubtitleFileExtensions, SubtitleDefaultFlags, SubtitleForcedFlags and SubtitleFlagDelimiters.
public SubtitleParser(NamingOptions options)
{
_options = options;
}
+ ///
+ /// Parse file to determine if is subtitle and .
+ ///
+ /// Path to file.
+ /// Returns null or object if parsing is successful.
public SubtitleInfo? ParseFile(string path)
{
if (path.Length == 0)
{
- throw new ArgumentException("File path can't be empty.", nameof(path));
+ return null;
}
var extension = Path.GetExtension(path);
@@ -31,12 +40,10 @@ namespace Emby.Naming.Subtitles
}
var flags = GetFlags(path);
- var info = new SubtitleInfo
- {
- Path = path,
- IsDefault = _options.SubtitleDefaultFlags.Any(i => flags.Contains(i, StringComparer.OrdinalIgnoreCase)),
- IsForced = _options.SubtitleForcedFlags.Any(i => flags.Contains(i, StringComparer.OrdinalIgnoreCase))
- };
+ var info = new SubtitleInfo(
+ path,
+ _options.SubtitleDefaultFlags.Any(i => flags.Contains(i, StringComparer.OrdinalIgnoreCase)),
+ _options.SubtitleForcedFlags.Any(i => flags.Contains(i, StringComparer.OrdinalIgnoreCase)));
var parts = flags.Where(i => !_options.SubtitleDefaultFlags.Contains(i, StringComparer.OrdinalIgnoreCase)
&& !_options.SubtitleForcedFlags.Contains(i, StringComparer.OrdinalIgnoreCase))
diff --git a/Emby.Naming/TV/EpisodeInfo.cs b/Emby.Naming/TV/EpisodeInfo.cs
index 250df4e2d3..a8920b36ae 100644
--- a/Emby.Naming/TV/EpisodeInfo.cs
+++ b/Emby.Naming/TV/EpisodeInfo.cs
@@ -1,9 +1,19 @@
-#pragma warning disable CS1591
-
namespace Emby.Naming.TV
{
+ ///
+ /// Holder object for Episode information.
+ ///
public class EpisodeInfo
{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Path to the file.
+ public EpisodeInfo(string path)
+ {
+ Path = path;
+ }
+
///
/// Gets or sets the path.
///
@@ -14,19 +24,19 @@ namespace Emby.Naming.TV
/// Gets or sets the container.
///
/// The container.
- public string Container { get; set; }
+ public string? Container { get; set; }
///
/// Gets or sets the name of the series.
///
/// The name of the series.
- public string SeriesName { get; set; }
+ public string? SeriesName { get; set; }
///
/// Gets or sets the format3 d.
///
/// The format3 d.
- public string Format3D { get; set; }
+ public string? Format3D { get; set; }
///
/// Gets or sets a value indicating whether [is3 d].
@@ -44,20 +54,41 @@ namespace Emby.Naming.TV
/// Gets or sets the type of the stub.
///
/// The type of the stub.
- public string StubType { get; set; }
+ public string? StubType { get; set; }
+ ///
+ /// Gets or sets optional season number.
+ ///
public int? SeasonNumber { get; set; }
+ ///
+ /// Gets or sets optional episode number.
+ ///
public int? EpisodeNumber { get; set; }
- public int? EndingEpsiodeNumber { get; set; }
+ ///
+ /// Gets or sets optional ending episode number. For multi-episode files 1-13.
+ ///
+ public int? EndingEpisodeNumber { get; set; }
+ ///
+ /// Gets or sets optional year of release.
+ ///
public int? Year { get; set; }
+ ///
+ /// Gets or sets optional year of release.
+ ///
public int? Month { get; set; }
+ ///
+ /// Gets or sets optional day of release.
+ ///
public int? Day { get; set; }
+ ///
+ /// Gets or sets a value indicating whether by date expression was used.
+ ///
public bool IsByDate { get; set; }
}
}
diff --git a/Emby.Naming/TV/EpisodePathParser.cs b/Emby.Naming/TV/EpisodePathParser.cs
index a6af689c72..6d0597356b 100644
--- a/Emby.Naming/TV/EpisodePathParser.cs
+++ b/Emby.Naming/TV/EpisodePathParser.cs
@@ -1,6 +1,3 @@
-#pragma warning disable CS1591
-#nullable enable
-
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -9,15 +6,32 @@ using Emby.Naming.Common;
namespace Emby.Naming.TV
{
+ ///
+ /// Used to parse information about episode from path.
+ ///
public class EpisodePathParser
{
private readonly NamingOptions _options;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// object containing EpisodeExpressions and MultipleEpisodeExpressions.
public EpisodePathParser(NamingOptions options)
{
_options = options;
}
+ ///
+ /// Parses information about episode from path.
+ ///
+ /// Path.
+ /// Is path for a directory or file.
+ /// Do we want to use IsNamed expressions.
+ /// Do we want to use Optimistic expressions.
+ /// Do we want to use expressions supporting absolute episode numbers.
+ /// Should we attempt to retrieve extended information.
+ /// Returns object.
public EpisodePathParserResult Parse(
string path,
bool isDirectory,
@@ -146,7 +160,7 @@ namespace Emby.Naming.TV
{
if (int.TryParse(endingNumberGroup.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out num))
{
- result.EndingEpsiodeNumber = num;
+ result.EndingEpisodeNumber = num;
}
}
}
@@ -186,7 +200,7 @@ namespace Emby.Naming.TV
private void FillAdditional(string path, EpisodePathParserResult info)
{
- var expressions = _options.MultipleEpisodeExpressions.ToList();
+ var expressions = _options.MultipleEpisodeExpressions.Where(i => i.IsNamed).ToList();
if (string.IsNullOrEmpty(info.SeriesName))
{
@@ -200,11 +214,6 @@ namespace Emby.Naming.TV
{
foreach (var i in expressions)
{
- if (!i.IsNamed)
- {
- continue;
- }
-
var result = Parse(path, i);
if (!result.Success)
@@ -217,13 +226,13 @@ namespace Emby.Naming.TV
info.SeriesName = result.SeriesName;
}
- if (!info.EndingEpsiodeNumber.HasValue && info.EpisodeNumber.HasValue)
+ if (!info.EndingEpisodeNumber.HasValue && info.EpisodeNumber.HasValue)
{
- info.EndingEpsiodeNumber = result.EndingEpsiodeNumber;
+ info.EndingEpisodeNumber = result.EndingEpisodeNumber;
}
if (!string.IsNullOrEmpty(info.SeriesName)
- && (!info.EpisodeNumber.HasValue || info.EndingEpsiodeNumber.HasValue))
+ && (!info.EpisodeNumber.HasValue || info.EndingEpisodeNumber.HasValue))
{
break;
}
diff --git a/Emby.Naming/TV/EpisodePathParserResult.cs b/Emby.Naming/TV/EpisodePathParserResult.cs
index 05f921edc9..233d5a4f6c 100644
--- a/Emby.Naming/TV/EpisodePathParserResult.cs
+++ b/Emby.Naming/TV/EpisodePathParserResult.cs
@@ -1,25 +1,54 @@
-#pragma warning disable CS1591
-
namespace Emby.Naming.TV
{
+ ///
+ /// Holder object for result.
+ ///
public class EpisodePathParserResult
{
+ ///
+ /// Gets or sets optional season number.
+ ///
public int? SeasonNumber { get; set; }
+ ///
+ /// Gets or sets optional episode number.
+ ///
public int? EpisodeNumber { get; set; }
- public int? EndingEpsiodeNumber { get; set; }
+ ///
+ /// Gets or sets optional ending episode number. For multi-episode files 1-13.
+ ///
+ public int? EndingEpisodeNumber { get; set; }
- public string SeriesName { get; set; }
+ ///
+ /// Gets or sets the name of the series.
+ ///
+ /// The name of the series.
+ public string? SeriesName { get; set; }
+ ///
+ /// Gets or sets a value indicating whether parsing was successful.
+ ///
public bool Success { get; set; }
+ ///
+ /// Gets or sets a value indicating whether by date expression was used.
+ ///
public bool IsByDate { get; set; }
+ ///
+ /// Gets or sets optional year of release.
+ ///
public int? Year { get; set; }
+ ///
+ /// Gets or sets optional year of release.
+ ///
public int? Month { get; set; }
+ ///
+ /// Gets or sets optional day of release.
+ ///
public int? Day { get; set; }
}
}
diff --git a/Emby.Naming/TV/EpisodeResolver.cs b/Emby.Naming/TV/EpisodeResolver.cs
index 6994f69fc4..f7df587864 100644
--- a/Emby.Naming/TV/EpisodeResolver.cs
+++ b/Emby.Naming/TV/EpisodeResolver.cs
@@ -1,6 +1,3 @@
-#pragma warning disable CS1591
-#nullable enable
-
using System;
using System.IO;
using System.Linq;
@@ -9,15 +6,32 @@ using Emby.Naming.Video;
namespace Emby.Naming.TV
{
+ ///
+ /// Used to resolve information about episode from path.
+ ///
public class EpisodeResolver
{
private readonly NamingOptions _options;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// object containing VideoFileExtensions and passed to , , and .
public EpisodeResolver(NamingOptions options)
{
_options = options;
}
+ ///
+ /// Resolve information about episode from path.
+ ///
+ /// Path.
+ /// Is path for a directory or file.
+ /// Do we want to use IsNamed expressions.
+ /// Do we want to use Optimistic expressions.
+ /// Do we want to use expressions supporting absolute episode numbers.
+ /// Should we attempt to retrieve extended information.
+ /// Returns null or object if successful.
public EpisodeInfo? Resolve(
string path,
bool isDirectory,
@@ -54,12 +68,11 @@ namespace Emby.Naming.TV
var parsingResult = new EpisodePathParser(_options)
.Parse(path, isDirectory, isNamed, isOptimistic, supportsAbsoluteNumbers, fillExtendedInfo);
- return new EpisodeInfo
+ return new EpisodeInfo(path)
{
- Path = path,
Container = container,
IsStub = isStub,
- EndingEpsiodeNumber = parsingResult.EndingEpsiodeNumber,
+ EndingEpisodeNumber = parsingResult.EndingEpisodeNumber,
EpisodeNumber = parsingResult.EpisodeNumber,
SeasonNumber = parsingResult.SeasonNumber,
SeriesName = parsingResult.SeriesName,
diff --git a/Emby.Naming/TV/SeasonPathParser.cs b/Emby.Naming/TV/SeasonPathParser.cs
index d2e324dda5..d11c7c99e8 100644
--- a/Emby.Naming/TV/SeasonPathParser.cs
+++ b/Emby.Naming/TV/SeasonPathParser.cs
@@ -1,11 +1,12 @@
-#pragma warning disable CS1591
-
using System;
using System.Globalization;
using System.IO;
namespace Emby.Naming.TV
{
+ ///
+ /// Class to parse season paths.
+ ///
public static class SeasonPathParser
{
///
@@ -23,6 +24,13 @@ namespace Emby.Naming.TV
"stagione"
};
+ ///
+ /// Attempts to parse season number from path.
+ ///
+ /// Path to season.
+ /// Support special aliases when parsing.
+ /// Support numeric season folders when parsing.
+ /// Returns object.
public static SeasonPathParserResult Parse(string path, bool supportSpecialAliases, bool supportNumericSeasonFolders)
{
var result = new SeasonPathParserResult();
@@ -101,9 +109,9 @@ namespace Emby.Naming.TV
}
var parts = filename.Split(new[] { '.', '_', ' ', '-' }, StringSplitOptions.RemoveEmptyEntries);
- for (int i = 0; i < parts.Length; i++)
+ foreach (var part in parts)
{
- if (TryGetSeasonNumberFromPart(parts[i], out int seasonNumber))
+ if (TryGetSeasonNumberFromPart(part, out int seasonNumber))
{
return (seasonNumber, true);
}
@@ -139,7 +147,7 @@ namespace Emby.Naming.TV
var numericStart = -1;
var length = 0;
- var hasOpenParenth = false;
+ var hasOpenParenthesis = false;
var isSeasonFolder = true;
// Find out where the numbers start, and then keep going until they end
@@ -147,7 +155,7 @@ namespace Emby.Naming.TV
{
if (char.IsNumber(path[i]))
{
- if (!hasOpenParenth)
+ if (!hasOpenParenthesis)
{
if (numericStart == -1)
{
@@ -167,11 +175,11 @@ namespace Emby.Naming.TV
var currentChar = path[i];
if (currentChar == '(')
{
- hasOpenParenth = true;
+ hasOpenParenthesis = true;
}
else if (currentChar == ')')
{
- hasOpenParenth = false;
+ hasOpenParenthesis = false;
}
}
diff --git a/Emby.Naming/TV/SeasonPathParserResult.cs b/Emby.Naming/TV/SeasonPathParserResult.cs
index a142fafea0..b4b6f236a7 100644
--- a/Emby.Naming/TV/SeasonPathParserResult.cs
+++ b/Emby.Naming/TV/SeasonPathParserResult.cs
@@ -1,7 +1,8 @@
-#pragma warning disable CS1591
-
namespace Emby.Naming.TV
{
+ ///
+ /// Data object to pass result of .
+ ///
public class SeasonPathParserResult
{
///
@@ -16,6 +17,10 @@ namespace Emby.Naming.TV
/// true if success; otherwise, false.
public bool Success { get; set; }
+ ///
+ /// Gets or sets a value indicating whether "Is season folder".
+ /// Seems redundant and barely used.
+ ///
public bool IsSeasonFolder { get; set; }
}
}
diff --git a/Emby.Naming/Video/CleanDateTimeParser.cs b/Emby.Naming/Video/CleanDateTimeParser.cs
index 579c9e91e1..0ee633dcc6 100644
--- a/Emby.Naming/Video/CleanDateTimeParser.cs
+++ b/Emby.Naming/Video/CleanDateTimeParser.cs
@@ -1,6 +1,3 @@
-#pragma warning disable CS1591
-#nullable enable
-
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
@@ -12,9 +9,20 @@ namespace Emby.Naming.Video
///
public static class CleanDateTimeParser
{
+ ///
+ /// Attempts to clean the name.
+ ///
+ /// Name of video.
+ /// Optional list of regexes to clean the name.
+ /// Returns object.
public static CleanDateTimeResult Clean(string name, IReadOnlyList cleanDateTimeRegexes)
{
CleanDateTimeResult result = new CleanDateTimeResult(name);
+ if (string.IsNullOrEmpty(name))
+ {
+ return result;
+ }
+
var len = cleanDateTimeRegexes.Count;
for (int i = 0; i < len; i++)
{
diff --git a/Emby.Naming/Video/CleanDateTimeResult.cs b/Emby.Naming/Video/CleanDateTimeResult.cs
index 57eeaa7e32..c675a19d0f 100644
--- a/Emby.Naming/Video/CleanDateTimeResult.cs
+++ b/Emby.Naming/Video/CleanDateTimeResult.cs
@@ -1,22 +1,21 @@
-#pragma warning disable CS1591
-#nullable enable
-
namespace Emby.Naming.Video
{
+ ///
+ /// Holder structure for name and year.
+ ///
public readonly struct CleanDateTimeResult
{
- public CleanDateTimeResult(string name, int? year)
+ ///
+ /// Initializes a new instance of the struct.
+ ///
+ /// Name of video.
+ /// Year of release.
+ public CleanDateTimeResult(string name, int? year = null)
{
Name = name;
Year = year;
}
- public CleanDateTimeResult(string name)
- {
- Name = name;
- Year = null;
- }
-
///
/// Gets the name.
///
diff --git a/Emby.Naming/Video/CleanStringParser.cs b/Emby.Naming/Video/CleanStringParser.cs
index 3f584d5847..09a0cd1893 100644
--- a/Emby.Naming/Video/CleanStringParser.cs
+++ b/Emby.Naming/Video/CleanStringParser.cs
@@ -1,6 +1,3 @@
-#pragma warning disable CS1591
-#nullable enable
-
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
@@ -12,6 +9,13 @@ namespace Emby.Naming.Video
///
public static class CleanStringParser
{
+ ///
+ /// Attempts to extract clean name with regular expressions.
+ ///
+ /// Name of file.
+ /// List of regex to parse name and year from.
+ /// Parsing result string.
+ /// True if parsing was successful.
public static bool TryClean(string name, IReadOnlyList expressions, out ReadOnlySpan newName)
{
var len = expressions.Count;
diff --git a/Emby.Naming/Video/ExtraResolver.cs b/Emby.Naming/Video/ExtraResolver.cs
index fc0424faab..1d3b36a1ad 100644
--- a/Emby.Naming/Video/ExtraResolver.cs
+++ b/Emby.Naming/Video/ExtraResolver.cs
@@ -1,5 +1,3 @@
-#pragma warning disable CS1591
-
using System;
using System.IO;
using System.Linq;
@@ -9,15 +7,27 @@ using Emby.Naming.Common;
namespace Emby.Naming.Video
{
+ ///
+ /// Resolve if file is extra for video.
+ ///
public class ExtraResolver
{
private readonly NamingOptions _options;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// object containing VideoExtraRules and passed to and .
public ExtraResolver(NamingOptions options)
{
_options = options;
}
+ ///
+ /// Attempts to resolve if file is extra.
+ ///
+ /// Path to file.
+ /// Returns object.
public ExtraResult GetExtraInfo(string path)
{
return _options.VideoExtraRules
@@ -43,10 +53,6 @@ namespace Emby.Naming.Video
return result;
}
}
- else
- {
- return result;
- }
if (rule.RuleType == ExtraRuleType.Filename)
{
diff --git a/Emby.Naming/Video/ExtraResult.cs b/Emby.Naming/Video/ExtraResult.cs
index 15db32e876..243fc2b415 100644
--- a/Emby.Naming/Video/ExtraResult.cs
+++ b/Emby.Naming/Video/ExtraResult.cs
@@ -1,9 +1,10 @@
-#pragma warning disable CS1591
-
using MediaBrowser.Model.Entities;
namespace Emby.Naming.Video
{
+ ///
+ /// Holder object for passing results from ExtraResolver.
+ ///
public class ExtraResult
{
///
@@ -16,6 +17,6 @@ namespace Emby.Naming.Video
/// Gets or sets the rule.
///
/// The rule.
- public ExtraRule Rule { get; set; }
+ public ExtraRule? Rule { get; set; }
}
}
diff --git a/Emby.Naming/Video/ExtraRule.cs b/Emby.Naming/Video/ExtraRule.cs
index 7c9702e244..e267ac55fc 100644
--- a/Emby.Naming/Video/ExtraRule.cs
+++ b/Emby.Naming/Video/ExtraRule.cs
@@ -1,5 +1,3 @@
-#pragma warning disable CS1591
-
using MediaBrowser.Model.Entities;
using MediaType = Emby.Naming.Common.MediaType;
@@ -10,6 +8,21 @@ namespace Emby.Naming.Video
///
public class ExtraRule
{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Type of extra.
+ /// Type of rule.
+ /// Token.
+ /// Media type.
+ public ExtraRule(ExtraType extraType, ExtraRuleType ruleType, string token, MediaType mediaType)
+ {
+ Token = token;
+ ExtraType = extraType;
+ RuleType = ruleType;
+ MediaType = mediaType;
+ }
+
///
/// Gets or sets the token to use for matching against the file path.
///
diff --git a/Emby.Naming/Video/ExtraRuleType.cs b/Emby.Naming/Video/ExtraRuleType.cs
index e89876f4ae..3243195057 100644
--- a/Emby.Naming/Video/ExtraRuleType.cs
+++ b/Emby.Naming/Video/ExtraRuleType.cs
@@ -1,7 +1,8 @@
-#pragma warning disable CS1591
-
namespace Emby.Naming.Video
{
+ ///
+ /// Extra rules type to determine against what should be matched.
+ ///
public enum ExtraRuleType
{
///
@@ -22,6 +23,6 @@ namespace Emby.Naming.Video
///
/// Match against the name of the directory containing the file.
///
- DirectoryName = 3,
+ DirectoryName = 3
}
}
diff --git a/Emby.Naming/Video/FileStack.cs b/Emby.Naming/Video/FileStack.cs
index 3ef190b865..6519db57c3 100644
--- a/Emby.Naming/Video/FileStack.cs
+++ b/Emby.Naming/Video/FileStack.cs
@@ -1,24 +1,43 @@
-#pragma warning disable CS1591
-
using System;
using System.Collections.Generic;
using System.Linq;
namespace Emby.Naming.Video
{
+ ///
+ /// Object holding list of files paths with additional information.
+ ///
public class FileStack
{
+ ///
+ /// Initializes a new instance of the class.
+ ///
public FileStack()
{
Files = new List();
}
- public string Name { get; set; }
+ ///
+ /// Gets or sets name of file stack.
+ ///
+ public string Name { get; set; } = string.Empty;
+ ///
+ /// Gets or sets list of paths in stack.
+ ///
public List Files { get; set; }
+ ///
+ /// Gets or sets a value indicating whether stack is directory stack.
+ ///
public bool IsDirectoryStack { get; set; }
+ ///
+ /// Helper function to determine if path is in the stack.
+ ///
+ /// Path of desired file.
+ /// Requested type of stack.
+ /// True if file is in the stack.
public bool ContainsFile(string file, bool isDirectory)
{
if (IsDirectoryStack == isDirectory)
diff --git a/Emby.Naming/Video/FlagParser.cs b/Emby.Naming/Video/FlagParser.cs
index a8bd9d5c5d..439de18138 100644
--- a/Emby.Naming/Video/FlagParser.cs
+++ b/Emby.Naming/Video/FlagParser.cs
@@ -1,37 +1,53 @@
-#pragma warning disable CS1591
-
using System;
using System.IO;
using Emby.Naming.Common;
namespace Emby.Naming.Video
{
+ ///
+ /// Parses list of flags from filename based on delimiters.
+ ///
public class FlagParser
{
private readonly NamingOptions _options;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// object containing VideoFlagDelimiters.
public FlagParser(NamingOptions options)
{
_options = options;
}
+ ///
+ /// Calls GetFlags function with _options.VideoFlagDelimiters parameter.
+ ///
+ /// Path to file.
+ /// List of found flags.
public string[] GetFlags(string path)
{
return GetFlags(path, _options.VideoFlagDelimiters);
}
- public string[] GetFlags(string path, char[] delimeters)
+ ///
+ /// Parses flags from filename based on delimiters.
+ ///
+ /// Path to file.
+ /// Delimiters used to extract flags.
+ /// List of found flags.
+ public string[] GetFlags(string path, char[] delimiters)
{
if (string.IsNullOrEmpty(path))
{
- throw new ArgumentNullException(nameof(path));
+ return Array.Empty();
}
// Note: the tags need be be surrounded be either a space ( ), hyphen -, dot . or underscore _.
var file = Path.GetFileName(path);
- return file.Split(delimeters, StringSplitOptions.RemoveEmptyEntries);
+ return file.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
}
}
}
diff --git a/Emby.Naming/Video/Format3DParser.cs b/Emby.Naming/Video/Format3DParser.cs
index 51c26af863..4fd5d78ba7 100644
--- a/Emby.Naming/Video/Format3DParser.cs
+++ b/Emby.Naming/Video/Format3DParser.cs
@@ -1,28 +1,38 @@
-#pragma warning disable CS1591
-
using System;
using System.Linq;
using Emby.Naming.Common;
namespace Emby.Naming.Video
{
+ ///
+ /// Parste 3D format related flags.
+ ///
public class Format3DParser
{
private readonly NamingOptions _options;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// object containing VideoFlagDelimiters and passes options to .
public Format3DParser(NamingOptions options)
{
_options = options;
}
+ ///
+ /// Parse 3D format related flags.
+ ///
+ /// Path to file.
+ /// Returns object.
public Format3DResult Parse(string path)
{
int oldLen = _options.VideoFlagDelimiters.Length;
- var delimeters = new char[oldLen + 1];
- _options.VideoFlagDelimiters.CopyTo(delimeters, 0);
- delimeters[oldLen] = ' ';
+ var delimiters = new char[oldLen + 1];
+ _options.VideoFlagDelimiters.CopyTo(delimiters, 0);
+ delimiters[oldLen] = ' ';
- return Parse(new FlagParser(_options).GetFlags(path, delimeters));
+ return Parse(new FlagParser(_options).GetFlags(path, delimiters));
}
internal Format3DResult Parse(string[] videoFlags)
@@ -44,7 +54,7 @@ namespace Emby.Naming.Video
{
var result = new Format3DResult();
- if (string.IsNullOrEmpty(rule.PreceedingToken))
+ if (string.IsNullOrEmpty(rule.PrecedingToken))
{
result.Format3D = new[] { rule.Token }.FirstOrDefault(i => videoFlags.Contains(i, StringComparer.OrdinalIgnoreCase));
result.Is3D = !string.IsNullOrEmpty(result.Format3D);
@@ -57,13 +67,13 @@ namespace Emby.Naming.Video
else
{
var foundPrefix = false;
- string format = null;
+ string? format = null;
foreach (var flag in videoFlags)
{
if (foundPrefix)
{
- result.Tokens.Add(rule.PreceedingToken);
+ result.Tokens.Add(rule.PrecedingToken);
if (string.Equals(rule.Token, flag, StringComparison.OrdinalIgnoreCase))
{
@@ -74,7 +84,7 @@ namespace Emby.Naming.Video
break;
}
- foundPrefix = string.Equals(flag, rule.PreceedingToken, StringComparison.OrdinalIgnoreCase);
+ foundPrefix = string.Equals(flag, rule.PrecedingToken, StringComparison.OrdinalIgnoreCase);
}
result.Is3D = foundPrefix && !string.IsNullOrEmpty(format);
diff --git a/Emby.Naming/Video/Format3DResult.cs b/Emby.Naming/Video/Format3DResult.cs
index fa0e9d3b80..ac935f2030 100644
--- a/Emby.Naming/Video/Format3DResult.cs
+++ b/Emby.Naming/Video/Format3DResult.cs
@@ -1,11 +1,15 @@
-#pragma warning disable CS1591
-
using System.Collections.Generic;
namespace Emby.Naming.Video
{
+ ///
+ /// Helper object to return data from .
+ ///
public class Format3DResult
{
+ ///
+ /// Initializes a new instance of the class.
+ ///
public Format3DResult()
{
Tokens = new List();
@@ -21,7 +25,7 @@ namespace Emby.Naming.Video
/// Gets or sets the format3 d.
///
/// The format3 d.
- public string Format3D { get; set; }
+ public string? Format3D { get; set; }
///
/// Gets or sets the tokens.
diff --git a/Emby.Naming/Video/Format3DRule.cs b/Emby.Naming/Video/Format3DRule.cs
index 310ec84e8f..e562691df9 100644
--- a/Emby.Naming/Video/Format3DRule.cs
+++ b/Emby.Naming/Video/Format3DRule.cs
@@ -1,9 +1,21 @@
-#pragma warning disable CS1591
-
namespace Emby.Naming.Video
{
+ ///
+ /// Data holder class for 3D format rule.
+ ///
public class Format3DRule
{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Token.
+ /// Token present before current token.
+ public Format3DRule(string token, string? precedingToken = null)
+ {
+ Token = token;
+ PrecedingToken = precedingToken;
+ }
+
///
/// Gets or sets the token.
///
@@ -11,9 +23,9 @@ namespace Emby.Naming.Video
public string Token { get; set; }
///
- /// Gets or sets the preceeding token.
+ /// Gets or sets the preceding token.
///
- /// The preceeding token.
- public string PreceedingToken { get; set; }
+ /// The preceding token.
+ public string? PrecedingToken { get; set; }
}
}
diff --git a/Emby.Naming/Video/StackResolver.cs b/Emby.Naming/Video/StackResolver.cs
index f733cd2620..550c429614 100644
--- a/Emby.Naming/Video/StackResolver.cs
+++ b/Emby.Naming/Video/StackResolver.cs
@@ -1,58 +1,88 @@
-#pragma warning disable CS1591
-
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
+using Emby.Naming.AudioBook;
using Emby.Naming.Common;
using MediaBrowser.Model.IO;
namespace Emby.Naming.Video
{
+ ///
+ /// Resolve from list of paths.
+ ///
public class StackResolver
{
private readonly NamingOptions _options;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// object containing VideoFileStackingRegexes and passes options to .
public StackResolver(NamingOptions options)
{
_options = options;
}
+ ///
+ /// Resolves only directories from paths.
+ ///
+ /// List of paths.
+ /// Enumerable of directories.
public IEnumerable ResolveDirectories(IEnumerable files)
{
return Resolve(files.Select(i => new FileSystemMetadata { FullName = i, IsDirectory = true }));
}
+ ///
+ /// Resolves only files from paths.
+ ///
+ /// List of paths.
+ /// Enumerable of files.
public IEnumerable ResolveFiles(IEnumerable files)
{
return Resolve(files.Select(i => new FileSystemMetadata { FullName = i, IsDirectory = false }));
}
- public IEnumerable ResolveAudioBooks(IEnumerable files)
+ ///
+ /// Resolves audiobooks from paths.
+ ///
+ /// List of paths.
+ /// Enumerable of directories.
+ public IEnumerable ResolveAudioBooks(IEnumerable files)
{
- var groupedDirectoryFiles = files.GroupBy(file =>
- file.IsDirectory
- ? file.FullName
- : Path.GetDirectoryName(file.FullName));
+ var groupedDirectoryFiles = files.GroupBy(file => Path.GetDirectoryName(file.Path));
foreach (var directory in groupedDirectoryFiles)
{
- var stack = new FileStack { Name = Path.GetFileName(directory.Key), IsDirectoryStack = false };
- foreach (var file in directory)
+ if (string.IsNullOrEmpty(directory.Key))
{
- if (file.IsDirectory)
+ foreach (var file in directory)
{
- continue;
+ var stack = new FileStack { Name = Path.GetFileNameWithoutExtension(file.Path), IsDirectoryStack = false };
+ stack.Files.Add(file.Path);
+ yield return stack;
+ }
+ }
+ else
+ {
+ var stack = new FileStack { Name = Path.GetFileName(directory.Key), IsDirectoryStack = false };
+ foreach (var file in directory)
+ {
+ stack.Files.Add(file.Path);
}
- stack.Files.Add(file.FullName);
+ yield return stack;
}
-
- yield return stack;
}
}
+ ///
+ /// Resolves videos from paths.
+ ///
+ /// List of paths.
+ /// Enumerable of videos.
public IEnumerable Resolve(IEnumerable files)
{
var resolver = new VideoResolver(_options);
@@ -81,10 +111,10 @@ namespace Emby.Naming.Video
if (match1.Success)
{
- var title1 = match1.Groups[1].Value;
- var volume1 = match1.Groups[2].Value;
- var ignore1 = match1.Groups[3].Value;
- var extension1 = match1.Groups[4].Value;
+ var title1 = match1.Groups["title"].Value;
+ var volume1 = match1.Groups["volume"].Value;
+ var ignore1 = match1.Groups["ignore"].Value;
+ var extension1 = match1.Groups["extension"].Value;
var j = i + 1;
while (j < list.Count)
diff --git a/Emby.Naming/Video/StubResolver.cs b/Emby.Naming/Video/StubResolver.cs
index f1b5d7bcca..079987fe8a 100644
--- a/Emby.Naming/Video/StubResolver.cs
+++ b/Emby.Naming/Video/StubResolver.cs
@@ -1,6 +1,3 @@
-#pragma warning disable CS1591
-#nullable enable
-
using System;
using System.IO;
using System.Linq;
@@ -8,13 +5,23 @@ using Emby.Naming.Common;
namespace Emby.Naming.Video
{
+ ///
+ /// Resolve if file is stub (.disc).
+ ///
public static class StubResolver
{
+ ///
+ /// Tries to resolve if file is stub (.disc).
+ ///
+ /// Path to file.
+ /// NamingOptions containing StubFileExtensions and StubTypes.
+ /// Stub type.
+ /// True if file is a stub.
public static bool TryResolveFile(string path, NamingOptions options, out string? stubType)
{
stubType = default;
- if (path == null)
+ if (string.IsNullOrEmpty(path))
{
return false;
}
diff --git a/Emby.Naming/Video/StubResult.cs b/Emby.Naming/Video/StubResult.cs
deleted file mode 100644
index 1b8e99b0dc..0000000000
--- a/Emby.Naming/Video/StubResult.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-#pragma warning disable CS1591
-
-namespace Emby.Naming.Video
-{
- public struct StubResult
- {
- ///
- /// Gets or sets a value indicating whether this instance is stub.
- ///
- /// true if this instance is stub; otherwise, false.
- public bool IsStub { get; set; }
-
- ///
- /// Gets or sets the type of the stub.
- ///
- /// The type of the stub.
- public string StubType { get; set; }
- }
-}
diff --git a/Emby.Naming/Video/StubTypeRule.cs b/Emby.Naming/Video/StubTypeRule.cs
index 8285cb51a3..dfb3ac013d 100644
--- a/Emby.Naming/Video/StubTypeRule.cs
+++ b/Emby.Naming/Video/StubTypeRule.cs
@@ -1,9 +1,21 @@
-#pragma warning disable CS1591
-
namespace Emby.Naming.Video
{
+ ///
+ /// Data class holding information about Stub type rule.
+ ///
public class StubTypeRule
{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Token.
+ /// Stub type.
+ public StubTypeRule(string token, string stubType)
+ {
+ Token = token;
+ StubType = stubType;
+ }
+
///
/// Gets or sets the token.
///
diff --git a/Emby.Naming/Video/VideoFileInfo.cs b/Emby.Naming/Video/VideoFileInfo.cs
index 11e789b663..1457db7378 100644
--- a/Emby.Naming/Video/VideoFileInfo.cs
+++ b/Emby.Naming/Video/VideoFileInfo.cs
@@ -7,6 +7,35 @@ namespace Emby.Naming.Video
///
public class VideoFileInfo
{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Name of file.
+ /// Path to the file.
+ /// Container type.
+ /// Year of release.
+ /// Extra type.
+ /// Extra rule.
+ /// Format 3D.
+ /// Is 3D.
+ /// Is Stub.
+ /// Stub type.
+ /// Is directory.
+ public VideoFileInfo(string name, string path, string? container, int? year = default, ExtraType? extraType = default, ExtraRule? extraRule = default, string? format3D = default, bool is3D = default, bool isStub = default, string? stubType = default, bool isDirectory = default)
+ {
+ Path = path;
+ Container = container;
+ Name = name;
+ Year = year;
+ ExtraType = extraType;
+ ExtraRule = extraRule;
+ Format3D = format3D;
+ Is3D = is3D;
+ IsStub = isStub;
+ StubType = stubType;
+ IsDirectory = isDirectory;
+ }
+
///
/// Gets or sets the path.
///
@@ -17,7 +46,7 @@ namespace Emby.Naming.Video
/// Gets or sets the container.
///
/// The container.
- public string Container { get; set; }
+ public string? Container { get; set; }
///
/// Gets or sets the name.
@@ -41,13 +70,13 @@ namespace Emby.Naming.Video
/// Gets or sets the extra rule.
///
/// The extra rule.
- public ExtraRule ExtraRule { get; set; }
+ public ExtraRule? ExtraRule { get; set; }
///
/// Gets or sets the format3 d.
///
/// The format3 d.
- public string Format3D { get; set; }
+ public string? Format3D { get; set; }
///
/// Gets or sets a value indicating whether [is3 d].
@@ -65,7 +94,7 @@ namespace Emby.Naming.Video
/// Gets or sets the type of the stub.
///
/// The type of the stub.
- public string StubType { get; set; }
+ public string? StubType { get; set; }
///
/// Gets or sets a value indicating whether this instance is a directory.
@@ -84,8 +113,7 @@ namespace Emby.Naming.Video
///
public override string ToString()
{
- // Makes debugging easier
- return Name ?? base.ToString();
+ return "VideoFileInfo(Name: '" + Name + "')";
}
}
}
diff --git a/Emby.Naming/Video/VideoInfo.cs b/Emby.Naming/Video/VideoInfo.cs
index ea74c40e2a..930fdb33f8 100644
--- a/Emby.Naming/Video/VideoInfo.cs
+++ b/Emby.Naming/Video/VideoInfo.cs
@@ -12,7 +12,7 @@ namespace Emby.Naming.Video
/// Initializes a new instance of the class.
///
/// The name.
- public VideoInfo(string name)
+ public VideoInfo(string? name)
{
Name = name;
@@ -25,7 +25,7 @@ namespace Emby.Naming.Video
/// Gets or sets the name.
///
/// The name.
- public string Name { get; set; }
+ public string? Name { get; set; }
///
/// Gets or sets the year.
diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs
index 948fe037b5..19cc491cfb 100644
--- a/Emby.Naming/Video/VideoListResolver.cs
+++ b/Emby.Naming/Video/VideoListResolver.cs
@@ -1,5 +1,3 @@
-#pragma warning disable CS1591
-
using System;
using System.Collections.Generic;
using System.IO;
@@ -11,22 +9,35 @@ using MediaBrowser.Model.IO;
namespace Emby.Naming.Video
{
+ ///
+ /// Resolves alternative versions and extras from list of video files.
+ ///
public class VideoListResolver
{
private readonly NamingOptions _options;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// object containing CleanStringRegexes and VideoFlagDelimiters and passes options to and .
public VideoListResolver(NamingOptions options)
{
_options = options;
}
+ ///
+ /// Resolves alternative versions and extras from list of video files.
+ ///
+ /// List of related video files.
+ /// Indication we should consider multi-versions of content.
+ /// Returns enumerable of which groups files togeather when related.
public IEnumerable Resolve(List files, bool supportMultiVersion = true)
{
var videoResolver = new VideoResolver(_options);
var videoInfos = files
.Select(i => videoResolver.Resolve(i.FullName, i.IsDirectory))
- .Where(i => i != null)
+ .OfType()
.ToList();
// Filter out all extras, otherwise they could cause stacks to not be resolved
@@ -39,7 +50,7 @@ namespace Emby.Naming.Video
.Resolve(nonExtras).ToList();
var remainingFiles = videoInfos
- .Where(i => !stackResult.Any(s => s.ContainsFile(i.Path, i.IsDirectory)))
+ .Where(i => !stackResult.Any(s => i.Path != null && s.ContainsFile(i.Path, i.IsDirectory)))
.ToList();
var list = new List();
@@ -48,7 +59,9 @@ namespace Emby.Naming.Video
{
var info = new VideoInfo(stack.Name)
{
- Files = stack.Files.Select(i => videoResolver.Resolve(i, stack.IsDirectoryStack)).ToList()
+ Files = stack.Files.Select(i => videoResolver.Resolve(i, stack.IsDirectoryStack))
+ .OfType()
+ .ToList()
};
info.Year = info.Files[0].Year;
@@ -133,7 +146,7 @@ namespace Emby.Naming.Video
}
// If there's only one video, accept all trailers
- // Be lenient because people use all kinds of mish mash conventions with trailers
+ // Be lenient because people use all kinds of mishmash conventions with trailers.
if (list.Count == 1)
{
var trailers = remainingFiles
@@ -203,15 +216,21 @@ namespace Emby.Naming.Video
return videos.Select(i => i.Year ?? -1).Distinct().Count() < 2;
}
- private bool IsEligibleForMultiVersion(string folderName, string testFilename)
+ private bool IsEligibleForMultiVersion(string folderName, string? testFilename)
{
testFilename = Path.GetFileNameWithoutExtension(testFilename) ?? string.Empty;
if (testFilename.StartsWith(folderName, StringComparison.OrdinalIgnoreCase))
{
+ if (CleanStringParser.TryClean(testFilename, _options.CleanStringRegexes, out var cleanName))
+ {
+ testFilename = cleanName.ToString();
+ }
+
testFilename = testFilename.Substring(folderName.Length).Trim();
return string.IsNullOrEmpty(testFilename)
- || testFilename[0] == '-'
+ || testFilename[0].Equals('-')
+ || testFilename[0].Equals('_')
|| string.IsNullOrWhiteSpace(Regex.Replace(testFilename, @"\[([^]]*)\]", string.Empty));
}
diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs
index b4aee614b0..d7165d8d7f 100644
--- a/Emby.Naming/Video/VideoResolver.cs
+++ b/Emby.Naming/Video/VideoResolver.cs
@@ -1,6 +1,3 @@
-#pragma warning disable CS1591
-#nullable enable
-
using System;
using System.IO;
using System.Linq;
@@ -8,10 +5,18 @@ using Emby.Naming.Common;
namespace Emby.Naming.Video
{
+ ///
+ /// Resolves from file path.
+ ///
public class VideoResolver
{
private readonly NamingOptions _options;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// object containing VideoFileExtensions, StubFileExtensions, CleanStringRegexes and CleanDateTimeRegexes
+ /// and passes options in , , and .
public VideoResolver(NamingOptions options)
{
_options = options;
@@ -22,7 +27,7 @@ namespace Emby.Naming.Video
///
/// The path.
/// VideoFileInfo.
- public VideoFileInfo? ResolveDirectory(string path)
+ public VideoFileInfo? ResolveDirectory(string? path)
{
return Resolve(path, true);
}
@@ -32,7 +37,7 @@ namespace Emby.Naming.Video
///
/// The path.
/// VideoFileInfo.
- public VideoFileInfo? ResolveFile(string path)
+ public VideoFileInfo? ResolveFile(string? path)
{
return Resolve(path, false);
}
@@ -45,11 +50,11 @@ namespace Emby.Naming.Video
/// Whether or not the name should be parsed for info.
/// VideoFileInfo.
/// path is null.
- public VideoFileInfo? Resolve(string path, bool isDirectory, bool parseName = true)
+ public VideoFileInfo? Resolve(string? path, bool isDirectory, bool parseName = true)
{
if (string.IsNullOrEmpty(path))
{
- throw new ArgumentNullException(nameof(path));
+ return null;
}
bool isStub = false;
@@ -99,39 +104,58 @@ namespace Emby.Naming.Video
}
}
- return new VideoFileInfo
- {
- Path = path,
- Container = container,
- IsStub = isStub,
- Name = name,
- Year = year,
- StubType = stubType,
- Is3D = format3DResult.Is3D,
- Format3D = format3DResult.Format3D,
- ExtraType = extraResult.ExtraType,
- IsDirectory = isDirectory,
- ExtraRule = extraResult.Rule
- };
+ return new VideoFileInfo(
+ path: path,
+ container: container,
+ isStub: isStub,
+ name: name,
+ year: year,
+ stubType: stubType,
+ is3D: format3DResult.Is3D,
+ format3D: format3DResult.Format3D,
+ extraType: extraResult.ExtraType,
+ isDirectory: isDirectory,
+ extraRule: extraResult.Rule);
}
+ ///
+ /// Determines if path is video file based on extension.
+ ///
+ /// Path to file.
+ /// True if is video file.
public bool IsVideoFile(string path)
{
var extension = Path.GetExtension(path) ?? string.Empty;
return _options.VideoFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase);
}
+ ///
+ /// Determines if path is video file stub based on extension.
+ ///
+ /// Path to file.
+ /// True if is video file stub.
public bool IsStubFile(string path)
{
var extension = Path.GetExtension(path) ?? string.Empty;
return _options.StubFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase);
}
+ ///
+ /// Tries to clean name of clutter.
+ ///
+ /// Raw name.
+ /// Clean name.
+ /// True if cleaning of name was successful.
public bool TryCleanString(string name, out ReadOnlySpan newName)
{
return CleanStringParser.TryClean(name, _options.CleanStringRegexes, out newName);
}
+ ///
+ /// Tries to get name and year from raw name.
+ ///
+ /// Raw name.
+ /// Returns with name and optional year.
public CleanDateTimeResult CleanDateTime(string name)
{
return CleanDateTimeParser.Clean(name, _options.CleanDateTimeRegexes);
diff --git a/Emby.Notifications/Emby.Notifications.csproj b/Emby.Notifications/Emby.Notifications.csproj
index 1d430a5e58..16ee918c46 100644
--- a/Emby.Notifications/Emby.Notifications.csproj
+++ b/Emby.Notifications/Emby.Notifications.csproj
@@ -6,7 +6,7 @@
- netstandard2.1
+ net5.0
false
true
true
diff --git a/Emby.Notifications/NotificationEntryPoint.cs b/Emby.Notifications/NotificationEntryPoint.cs
index ded22d26cc..7433d3c8ae 100644
--- a/Emby.Notifications/NotificationEntryPoint.cs
+++ b/Emby.Notifications/NotificationEntryPoint.cs
@@ -83,7 +83,7 @@ namespace Emby.Notifications
return Task.CompletedTask;
}
- private async void OnAppHostHasPendingRestartChanged(object sender, EventArgs e)
+ private async void OnAppHostHasPendingRestartChanged(object? sender, EventArgs e)
{
var type = NotificationType.ServerRestartRequired.ToString();
@@ -99,7 +99,7 @@ namespace Emby.Notifications
await SendNotification(notification, null).ConfigureAwait(false);
}
- private async void OnActivityManagerEntryCreated(object sender, GenericEventArgs e)
+ private async void OnActivityManagerEntryCreated(object? sender, GenericEventArgs e)
{
var entry = e.Argument;
@@ -132,7 +132,7 @@ namespace Emby.Notifications
return _config.GetConfiguration("notifications");
}
- private async void OnAppHostHasUpdateAvailableChanged(object sender, EventArgs e)
+ private async void OnAppHostHasUpdateAvailableChanged(object? sender, EventArgs e)
{
if (!_appHost.HasUpdateAvailable)
{
@@ -151,7 +151,7 @@ namespace Emby.Notifications
await SendNotification(notification, null).ConfigureAwait(false);
}
- private void OnLibraryManagerItemAdded(object sender, ItemChangeEventArgs e)
+ private void OnLibraryManagerItemAdded(object? sender, ItemChangeEventArgs e)
{
if (!FilterItem(e.Item))
{
@@ -197,7 +197,7 @@ namespace Emby.Notifications
return item.SourceType == SourceType.Library;
}
- private async void LibraryUpdateTimerCallback(object state)
+ private async void LibraryUpdateTimerCallback(object? state)
{
List items;
@@ -209,7 +209,10 @@ namespace Emby.Notifications
_libraryUpdateTimer = null;
}
- items = items.Take(10).ToList();
+ if (items.Count > 10)
+ {
+ items = items.GetRange(0, 10);
+ }
foreach (var item in items)
{
diff --git a/Emby.Photos/Emby.Photos.csproj b/Emby.Photos/Emby.Photos.csproj
index dbe01257f4..62e33e6c44 100644
--- a/Emby.Photos/Emby.Photos.csproj
+++ b/Emby.Photos/Emby.Photos.csproj
@@ -19,7 +19,7 @@
- netstandard2.1
+ net5.0
false
true
true
diff --git a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs
index 2adc1d6c34..660bbb2deb 100644
--- a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs
+++ b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs
@@ -62,7 +62,7 @@ namespace Emby.Server.Implementations.AppBase
}
///
- public string VirtualDataPath { get; } = "%AppDataPath%";
+ public string VirtualDataPath => "%AppDataPath%";
///
/// Gets the image cache path.
diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs
index 4ab0a2a3f2..4f72c8ce15 100644
--- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs
+++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs
@@ -133,6 +133,33 @@ namespace Emby.Server.Implementations.AppBase
}
}
+ ///
+ /// Manually pre-loads a factory so that it is available pre system initialisation.
+ ///
+ /// Class to register.
+ public virtual void RegisterConfiguration()
+ where T : IConfigurationFactory
+ {
+ IConfigurationFactory factory = Activator.CreateInstance();
+
+ if (_configurationFactories == null)
+ {
+ _configurationFactories = new[] { factory };
+ }
+ else
+ {
+ var oldLen = _configurationFactories.Length;
+ var arr = new IConfigurationFactory[oldLen + 1];
+ _configurationFactories.CopyTo(arr, 0);
+ arr[oldLen] = factory;
+ _configurationFactories = arr;
+ }
+
+ _configurationStores = _configurationFactories
+ .SelectMany(i => i.GetConfigurations())
+ .ToArray();
+ }
+
///
/// Adds parts.
///
diff --git a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs
index 4c9ab33a7c..77819c7649 100644
--- a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs
+++ b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs
@@ -3,6 +3,7 @@
using System;
using System.IO;
using System.Linq;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Model.Serialization;
namespace Emby.Server.Implementations.AppBase
@@ -35,7 +36,7 @@ namespace Emby.Server.Implementations.AppBase
}
catch (Exception)
{
- configuration = Activator.CreateInstance(type);
+ configuration = Activator.CreateInstance(type) ?? throw new ArgumentException($"Provided path ({type}) is not valid.", nameof(type));
}
using var stream = new MemoryStream(buffer?.Length ?? 0);
@@ -48,8 +49,9 @@ namespace Emby.Server.Implementations.AppBase
// If the file didn't exist before, or if something has changed, re-save
if (buffer == null || !newBytes.AsSpan(0, newBytesLen).SequenceEqual(buffer))
{
- Directory.CreateDirectory(Path.GetDirectoryName(path));
+ var directory = Path.GetDirectoryName(path) ?? throw new ArgumentException($"Provided path ({path}) is not valid.", nameof(path));
+ Directory.CreateDirectory(directory);
// Save it after load in case we got new items
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
{
diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs
index b4f7319f8e..17b99c858f 100644
--- a/Emby.Server.Implementations/ApplicationHost.cs
+++ b/Emby.Server.Implementations/ApplicationHost.cs
@@ -4,7 +4,6 @@ using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
@@ -30,7 +29,6 @@ using Emby.Server.Implementations.Cryptography;
using Emby.Server.Implementations.Data;
using Emby.Server.Implementations.Devices;
using Emby.Server.Implementations.Dto;
-using Emby.Server.Implementations.HttpServer;
using Emby.Server.Implementations.HttpServer.Security;
using Emby.Server.Implementations.IO;
using Emby.Server.Implementations.Library;
@@ -97,6 +95,7 @@ using MediaBrowser.Model.Tasks;
using MediaBrowser.Providers.Chapters;
using MediaBrowser.Providers.Manager;
using MediaBrowser.Providers.Plugins.TheTvdb;
+using MediaBrowser.Providers.Plugins.Tmdb;
using MediaBrowser.Providers.Subtitles;
using MediaBrowser.XbmcMetadata.Providers;
using Microsoft.AspNetCore.Mvc;
@@ -127,8 +126,6 @@ namespace Emby.Server.Implementations
private IMediaEncoder _mediaEncoder;
private ISessionManager _sessionManager;
private IHttpClientFactory _httpClientFactory;
- private IWebSocketManager _webSocketManager;
-
private string[] _urlPrefixes;
///
@@ -258,8 +255,8 @@ namespace Emby.Server.Implementations
IServiceCollection serviceCollection)
{
_xmlSerializer = new MyXmlSerializer();
- _jsonSerializer = new JsonSerializer();
-
+ _jsonSerializer = new JsonSerializer();
+
ServiceCollection = serviceCollection;
_networkManager = networkManager;
@@ -339,7 +336,7 @@ namespace Emby.Server.Implementations
/// Gets the email address for use within a comment section of a user agent field.
/// Presently used to provide contact information to MusicBrainz service.
///
- public string ApplicationUserAgentAddress { get; } = "team@jellyfin.org";
+ public string ApplicationUserAgentAddress => "team@jellyfin.org";
///
/// Gets the current application name.
@@ -403,7 +400,7 @@ namespace Emby.Server.Implementations
///
/// Resolves this instance.
///
- /// The type
+ /// The type.
/// ``0.
public T Resolve() => ServiceProvider.GetService();
@@ -499,24 +496,11 @@ namespace Emby.Server.Implementations
HttpsPort = ServerConfiguration.DefaultHttpsPort;
}
- if (Plugins != null)
- {
- var pluginBuilder = new StringBuilder();
-
- foreach (var plugin in Plugins)
- {
- pluginBuilder.Append(plugin.Name)
- .Append(' ')
- .Append(plugin.Version)
- .AppendLine();
- }
-
- Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString());
- }
-
DiscoverTypes();
RegisterServices();
+
+ RegisterPluginServices();
}
///
@@ -537,6 +521,7 @@ namespace Emby.Server.Implementations
ServiceCollection.AddSingleton(_fileSystemManager);
ServiceCollection.AddSingleton();
+ ServiceCollection.AddSingleton();
ServiceCollection.AddSingleton(_networkManager);
@@ -665,7 +650,6 @@ namespace Emby.Server.Implementations
_mediaEncoder = Resolve();
_sessionManager = Resolve();
_httpClientFactory = Resolve();
- _webSocketManager = Resolve();
((AuthenticationRepository)Resolve()).Initialize();
@@ -781,12 +765,25 @@ namespace Emby.Server.Implementations
ConfigurationManager.AddParts(GetExports());
_plugins = GetExports()
- .Select(LoadPlugin)
.Where(i => i != null)
.ToArray();
+ if (Plugins != null)
+ {
+ var pluginBuilder = new StringBuilder();
+
+ foreach (var plugin in Plugins)
+ {
+ pluginBuilder.Append(plugin.Name)
+ .Append(' ')
+ .Append(plugin.Version)
+ .AppendLine();
+ }
+
+ Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString());
+ }
+
_urlPrefixes = GetUrlPrefixes().ToArray();
- _webSocketManager.Init(GetExports());
Resolve().AddParts(
GetExports(),
@@ -815,21 +812,6 @@ namespace Emby.Server.Implementations
Resolve().AddParts(GetExports());
}
- private IPlugin LoadPlugin(IPlugin plugin)
- {
- try
- {
- plugin.RegisterServices(ServiceCollection);
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error loading plugin {PluginName}", plugin.GetType().FullName);
- return null;
- }
-
- return plugin;
- }
-
///
/// Discovers the types.
///
@@ -840,6 +822,22 @@ namespace Emby.Server.Implementations
_allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
}
+ private void RegisterPluginServices()
+ {
+ foreach (var pluginServiceRegistrator in GetExportTypes())
+ {
+ try
+ {
+ var instance = (IPluginServiceRegistrator)Activator.CreateInstance(pluginServiceRegistrator);
+ instance.RegisterServices(ServiceCollection);
+ }
+ catch (Exception ex)
+ {
+ Logger.LogError(ex, "Error registering plugin services from {Assembly}.", pluginServiceRegistrator.Assembly);
+ }
+ }
+ }
+
private IEnumerable GetTypes(IEnumerable assemblies)
{
foreach (var ass in assemblies)
@@ -994,80 +992,60 @@ namespace Emby.Server.Implementations
protected abstract void RestartInternal();
- ///
- /// Comparison function used in .
- ///
- /// Item to compare.
- /// Item to compare with.
- /// Boolean result of the operation.
- private static int VersionCompare(
- (Version PluginVersion, string Name, string Path) a,
- (Version PluginVersion, string Name, string Path) b)
+ ///
+ public IEnumerable GetLocalPlugins(string path, bool cleanup = true)
{
- int compare = string.Compare(a.Name, b.Name, true, CultureInfo.InvariantCulture);
-
- if (compare == 0)
+ var minimumVersion = new Version(0, 0, 0, 1);
+ var versions = new List();
+ if (!Directory.Exists(path))
{
- return a.PluginVersion.CompareTo(b.PluginVersion);
+ // Plugin path doesn't exist, don't try to enumerate subfolders.
+ return Enumerable.Empty();
}
- return compare;
- }
-
- ///
- /// Returns a list of plugins to install.
- ///
- /// Path to check.
- /// True if an attempt should be made to delete old plugs.
- /// Enumerable list of dlls to load.
- private IEnumerable GetPlugins(string path, bool cleanup = true)
- {
- var dllList = new List();
- var versions = new List<(Version PluginVersion, string Name, string Path)>();
var directories = Directory.EnumerateDirectories(path, "*.*", SearchOption.TopDirectoryOnly);
- string metafile;
foreach (var dir in directories)
{
try
{
- metafile = Path.Combine(dir, "meta.json");
+ var metafile = Path.Combine(dir, "meta.json");
if (File.Exists(metafile))
{
var manifest = _jsonSerializer.DeserializeFromFile(metafile);
if (!Version.TryParse(manifest.TargetAbi, out var targetAbi))
{
- targetAbi = new Version(0, 0, 0, 1);
+ targetAbi = minimumVersion;
}
if (!Version.TryParse(manifest.Version, out var version))
{
- version = new Version(0, 0, 0, 1);
+ version = minimumVersion;
}
if (ApplicationVersion >= targetAbi)
{
// Only load Plugins if the plugin is built for this version or below.
- versions.Add((version, manifest.Name, dir));
+ versions.Add(new LocalPlugin(manifest.Guid, manifest.Name, version, dir));
}
}
else
{
// No metafile, so lets see if the folder is versioned.
- metafile = dir.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)[^1];
-
+ metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1];
+
int versionIndex = dir.LastIndexOf('_');
- if (versionIndex != -1 && Version.TryParse(dir.Substring(versionIndex + 1), out Version ver))
+ if (versionIndex != -1 && Version.TryParse(dir.Substring(versionIndex + 1), out Version parsedVersion))
{
// Versioned folder.
- versions.Add((ver, metafile, dir));
+ versions.Add(new LocalPlugin(Guid.Empty, metafile, parsedVersion, dir));
}
else
{
- // Un-versioned folder - Add it under the path name and version 0.0.0.1.
- versions.Add((new Version(0, 0, 0, 1), metafile, dir));
- }
+ // Un-versioned folder - Add it under the path name and version 0.0.0.1.
+ versions.Add(new LocalPlugin(Guid.Empty, metafile, minimumVersion, dir));
+ }
}
}
catch
@@ -1077,14 +1055,14 @@ namespace Emby.Server.Implementations
}
string lastName = string.Empty;
- versions.Sort(VersionCompare);
+ versions.Sort(LocalPlugin.Compare);
// Traverse backwards through the list.
// The first item will be the latest version.
for (int x = versions.Count - 1; x >= 0; x--)
{
if (!string.Equals(lastName, versions[x].Name, StringComparison.OrdinalIgnoreCase))
{
- dllList.AddRange(Directory.EnumerateFiles(versions[x].Path, "*.dll", SearchOption.AllDirectories));
+ versions[x].DllFiles.AddRange(Directory.EnumerateFiles(versions[x].Path, "*.dll", SearchOption.AllDirectories));
lastName = versions[x].Name;
continue;
}
@@ -1092,6 +1070,7 @@ namespace Emby.Server.Implementations
if (!string.IsNullOrEmpty(lastName) && cleanup)
{
// Attempt a cleanup of old folders.
+ versions.RemoveAt(x);
try
{
Logger.LogDebug("Deleting {Path}", versions[x].Path);
@@ -1104,7 +1083,7 @@ namespace Emby.Server.Implementations
}
}
- return dllList;
+ return versions;
}
///
@@ -1115,21 +1094,24 @@ namespace Emby.Server.Implementations
{
if (Directory.Exists(ApplicationPaths.PluginsPath))
{
- foreach (var file in GetPlugins(ApplicationPaths.PluginsPath))
+ foreach (var plugin in GetLocalPlugins(ApplicationPaths.PluginsPath))
{
- Assembly plugAss;
- try
+ foreach (var file in plugin.DllFiles)
{
- plugAss = Assembly.LoadFrom(file);
- }
- catch (FileLoadException ex)
- {
- Logger.LogError(ex, "Failed to load assembly {Path}", file);
- continue;
- }
+ Assembly plugAss;
+ try
+ {
+ plugAss = Assembly.LoadFrom(file);
+ }
+ catch (FileLoadException ex)
+ {
+ Logger.LogError(ex, "Failed to load assembly {Path}", file);
+ continue;
+ }
- Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
- yield return plugAss;
+ Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
+ yield return plugAss;
+ }
}
}
@@ -1396,7 +1378,7 @@ namespace Emby.Server.Implementations
using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
var result = await System.Text.Json.JsonSerializer.DeserializeAsync(stream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false);
var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
diff --git a/Emby.Server.Implementations/Browser/BrowserLauncher.cs b/Emby.Server.Implementations/Browser/BrowserLauncher.cs
deleted file mode 100644
index f8108d1c2d..0000000000
--- a/Emby.Server.Implementations/Browser/BrowserLauncher.cs
+++ /dev/null
@@ -1,51 +0,0 @@
-using System;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Configuration;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.Logging;
-
-namespace Emby.Server.Implementations.Browser
-{
- ///
- /// Assists in opening application URLs in an external browser.
- ///
- public static class BrowserLauncher
- {
- ///
- /// Opens the home page of the web client.
- ///
- /// The app host.
- public static void OpenWebApp(IServerApplicationHost appHost)
- {
- TryOpenUrl(appHost, "/web/index.html");
- }
-
- ///
- /// Opens the swagger API page.
- ///
- /// The app host.
- public static void OpenSwaggerPage(IServerApplicationHost appHost)
- {
- TryOpenUrl(appHost, "/api-docs/swagger");
- }
-
- ///
- /// Opens the specified URL in an external browser window. Any exceptions will be logged, but ignored.
- ///
- /// The application host.
- /// The URL to open, relative to the server base URL.
- private static void TryOpenUrl(IServerApplicationHost appHost, string relativeUrl)
- {
- try
- {
- string baseUrl = appHost.GetLocalApiUrl("localhost");
- appHost.LaunchUrl(baseUrl + relativeUrl);
- }
- catch (Exception ex)
- {
- var logger = appHost.Resolve>();
- logger?.LogError(ex, "Failed to open browser window with URL {URL}", relativeUrl);
- }
- }
- }
-}
diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs
index fb1bb65a09..19045b72b4 100644
--- a/Emby.Server.Implementations/Channels/ChannelManager.cs
+++ b/Emby.Server.Implementations/Channels/ChannelManager.cs
@@ -250,21 +250,16 @@ namespace Emby.Server.Implementations.Channels
var all = channels;
var totalCount = all.Count;
- if (query.StartIndex.HasValue)
+ if (query.StartIndex.HasValue || query.Limit.HasValue)
{
- all = all.Skip(query.StartIndex.Value).ToList();
+ int startIndex = query.StartIndex ?? 0;
+ int count = query.Limit == null ? totalCount - startIndex : Math.Min(query.Limit.Value, totalCount - startIndex);
+ all = all.GetRange(startIndex, count);
}
- if (query.Limit.HasValue)
- {
- all = all.Take(query.Limit.Value).ToList();
- }
-
- var returnItems = all.ToArray();
-
if (query.RefreshLatestChannelItems)
{
- foreach (var item in returnItems)
+ foreach (var item in all)
{
RefreshLatestChannelItems(GetChannelProvider(item), CancellationToken.None).GetAwaiter().GetResult();
}
@@ -272,7 +267,7 @@ namespace Emby.Server.Implementations.Channels
return new QueryResult
{
- Items = returnItems,
+ Items = all,
TotalRecordCount = totalCount
};
}
@@ -543,7 +538,7 @@ namespace Emby.Server.Implementations.Channels
return _libraryManager.GetItemIds(
new InternalItemsQuery
{
- IncludeItemTypes = new[] { typeof(Channel).Name },
+ IncludeItemTypes = new[] { nameof(Channel) },
OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) }
}).Select(i => GetChannelFeatures(i.ToString("N", CultureInfo.InvariantCulture))).ToArray();
}
diff --git a/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs b/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs
index eeb49b8fef..2391eed428 100644
--- a/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs
+++ b/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs
@@ -51,7 +51,7 @@ namespace Emby.Server.Implementations.Channels
var uninstalledChannels = _libraryManager.GetItemList(new InternalItemsQuery
{
- IncludeItemTypes = new[] { typeof(Channel).Name },
+ IncludeItemTypes = new[] { nameof(Channel) },
ExcludeItemIds = installedChannelIds.ToArray()
});
diff --git a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs
index fd302d1365..12a9e44e70 100644
--- a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs
+++ b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs
@@ -3,6 +3,7 @@
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Model.Cryptography;
using static MediaBrowser.Common.Cryptography.Constants;
@@ -80,7 +81,7 @@ namespace Emby.Server.Implementations.Cryptography
throw new CryptographicException($"Requested hash method is not supported: {hashMethod}");
}
- using var h = HashAlgorithm.Create(hashMethod);
+ using var h = HashAlgorithm.Create(hashMethod) ?? throw new ResourceNotFoundException($"Unknown hash method: {hashMethod}.");
if (salt.Length == 0)
{
return h.ComputeHash(bytes);
diff --git a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs
index 0fb050a7a5..8c756a7f4c 100644
--- a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs
+++ b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs
@@ -157,7 +157,8 @@ namespace Emby.Server.Implementations.Data
protected bool TableExists(ManagedConnection connection, string name)
{
- return connection.RunInTransaction(db =>
+ return connection.RunInTransaction(
+ db =>
{
using (var statement = PrepareStatement(db, "select DISTINCT tbl_name from sqlite_master"))
{
diff --git a/Emby.Server.Implementations/Data/SqliteExtensions.cs b/Emby.Server.Implementations/Data/SqliteExtensions.cs
index 70a6df977f..1af301ceb0 100644
--- a/Emby.Server.Implementations/Data/SqliteExtensions.cs
+++ b/Emby.Server.Implementations/Data/SqliteExtensions.cs
@@ -107,20 +107,6 @@ namespace Emby.Server.Implementations.Data
return null;
}
- public static void Attach(SQLiteDatabaseConnection db, string path, string alias)
- {
- var commandText = string.Format(
- CultureInfo.InvariantCulture,
- "attach @path as {0};",
- alias);
-
- using (var statement = db.PrepareStatement(commandText))
- {
- statement.TryBind("@path", path);
- statement.MoveNext();
- }
- }
-
public static bool IsDBNull(this IReadOnlyList result, int index)
{
return result[index].SQLiteType == SQLiteType.Null;
diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs
index ab60cee618..638c7a9b49 100644
--- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs
+++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs
@@ -219,7 +219,8 @@ namespace Emby.Server.Implementations.Data
{
connection.RunQueries(queries);
- connection.RunInTransaction(db =>
+ connection.RunInTransaction(
+ db =>
{
var existingColumnNames = GetColumnNames(db, "AncestorIds");
AddColumn(db, "AncestorIds", "AncestorIdText", "Text", existingColumnNames);
@@ -495,7 +496,8 @@ namespace Emby.Server.Implementations.Data
using (var connection = GetConnection())
{
- connection.RunInTransaction(db =>
+ connection.RunInTransaction(
+ db =>
{
using (var saveImagesStatement = base.PrepareStatement(db, "Update TypedBaseItems set Images=@Images where guid=@Id"))
{
@@ -546,7 +548,8 @@ namespace Emby.Server.Implementations.Data
using (var connection = GetConnection())
{
- connection.RunInTransaction(db =>
+ connection.RunInTransaction(
+ db =>
{
SaveItemsInTranscation(db, tuples);
}, TransactionMode);
@@ -1004,7 +1007,7 @@ namespace Emby.Server.Implementations.Data
return;
}
- var parts = value.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
+ var parts = value.Split('|', StringSplitOptions.RemoveEmptyEntries);
foreach (var part in parts)
{
@@ -1054,7 +1057,7 @@ namespace Emby.Server.Implementations.Data
return;
}
- var parts = value.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
+ var parts = value.Split('|' , StringSplitOptions.RemoveEmptyEntries);
var list = new List();
foreach (var part in parts)
{
@@ -1093,7 +1096,7 @@ namespace Emby.Server.Implementations.Data
public ItemImageInfo ItemImageInfoFromValueString(string value)
{
- var parts = value.Split(new[] { '*' }, StringSplitOptions.None);
+ var parts = value.Split('*', StringSplitOptions.None);
if (parts.Length < 3)
{
@@ -1529,7 +1532,7 @@ namespace Emby.Server.Implementations.Data
{
if (!reader.IsDBNull(index))
{
- item.Genres = reader.GetString(index).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
+ item.Genres = reader.GetString(index).Split('|', StringSplitOptions.RemoveEmptyEntries);
}
index++;
@@ -1590,7 +1593,7 @@ namespace Emby.Server.Implementations.Data
{
IEnumerable GetLockedFields(string s)
{
- foreach (var i in s.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
+ foreach (var i in s.Split('|', StringSplitOptions.RemoveEmptyEntries))
{
if (Enum.TryParse(i, true, out MetadataField parsedValue))
{
@@ -1609,7 +1612,7 @@ namespace Emby.Server.Implementations.Data
{
if (!reader.IsDBNull(index))
{
- item.Studios = reader.GetString(index).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
+ item.Studios = reader.GetString(index).Split('|', StringSplitOptions.RemoveEmptyEntries);
}
index++;
@@ -1619,7 +1622,7 @@ namespace Emby.Server.Implementations.Data
{
if (!reader.IsDBNull(index))
{
- item.Tags = reader.GetString(index).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
+ item.Tags = reader.GetString(index).Split('|', StringSplitOptions.RemoveEmptyEntries);
}
index++;
@@ -1633,7 +1636,7 @@ namespace Emby.Server.Implementations.Data
{
IEnumerable GetTrailerTypes(string s)
{
- foreach (var i in s.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
+ foreach (var i in s.Split('|', StringSplitOptions.RemoveEmptyEntries))
{
if (Enum.TryParse(i, true, out TrailerType parsedValue))
{
@@ -1808,7 +1811,7 @@ namespace Emby.Server.Implementations.Data
{
if (!reader.IsDBNull(index))
{
- item.ProductionLocations = reader.GetString(index).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
+ item.ProductionLocations = reader.GetString(index).Split('|', StringSplitOptions.RemoveEmptyEntries).ToArray();
}
index++;
@@ -1845,14 +1848,14 @@ namespace Emby.Server.Implementations.Data
{
if (item is IHasArtist hasArtists && !reader.IsDBNull(index))
{
- hasArtists.Artists = reader.GetString(index).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
+ hasArtists.Artists = reader.GetString(index).Split('|', StringSplitOptions.RemoveEmptyEntries);
}
index++;
if (item is IHasAlbumArtist hasAlbumArtists && !reader.IsDBNull(index))
{
- hasAlbumArtists.AlbumArtists = reader.GetString(index).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
+ hasAlbumArtists.AlbumArtists = reader.GetString(index).Split('|', StringSplitOptions.RemoveEmptyEntries);
}
index++;
@@ -2032,7 +2035,8 @@ namespace Emby.Server.Implementations.Data
using (var connection = GetConnection())
{
- connection.RunInTransaction(db =>
+ connection.RunInTransaction(
+ db =>
{
// First delete chapters
db.Execute("delete from " + ChaptersTableName + " where ItemId=@ItemId", idBlob);
@@ -2263,7 +2267,6 @@ namespace Emby.Server.Implementations.Data
return query.IncludeItemTypes.Contains("Trailer", StringComparer.OrdinalIgnoreCase);
}
-
private static readonly HashSet _artistExcludeParentTypes = new HashSet(StringComparer.OrdinalIgnoreCase)
{
"Series",
@@ -2400,11 +2403,11 @@ namespace Emby.Server.Implementations.Data
if (string.IsNullOrEmpty(item.OfficialRating))
{
- builder.Append("((OfficialRating is null) * 10)");
+ builder.Append("(OfficialRating is null * 10)");
}
else
{
- builder.Append("((OfficialRating=@ItemOfficialRating) * 10)");
+ builder.Append("(OfficialRating=@ItemOfficialRating * 10)");
}
if (item.ProductionYear.HasValue)
@@ -2413,8 +2416,26 @@ namespace Emby.Server.Implementations.Data
builder.Append("+(Select Case When Abs(COALESCE(ProductionYear, 0) - @ItemProductionYear) < 5 Then 5 Else 0 End )");
}
- //// genres, tags
- builder.Append("+ ((Select count(CleanValue) from ItemValues where ItemId=Guid and CleanValue in (select CleanValue from itemvalues where ItemId=@SimilarItemId)) * 10)");
+ // genres, tags, studios, person, year?
+ builder.Append("+ (Select count(1) * 10 from ItemValues where ItemId=Guid and CleanValue in (select CleanValue from itemvalues where ItemId=@SimilarItemId))");
+
+ if (item is MusicArtist)
+ {
+ // Match albums where the artist is AlbumArtist against other albums.
+ // It is assumed that similar albums => similar artists.
+ builder.Append(
+ @"+ (WITH artistValues AS (
+ SELECT DISTINCT albumValues.CleanValue
+ FROM ItemValues albumValues
+ INNER JOIN ItemValues artistAlbums ON albumValues.ItemId = artistAlbums.ItemId
+ INNER JOIN TypedBaseItems artistItem ON artistAlbums.CleanValue = artistItem.CleanName AND artistAlbums.TYPE = 1 AND artistItem.Guid = @SimilarItemId
+ ), similarArtist AS (
+ SELECT albumValues.ItemId
+ FROM ItemValues albumValues
+ INNER JOIN ItemValues artistAlbums ON albumValues.ItemId = artistAlbums.ItemId
+ INNER JOIN TypedBaseItems artistItem ON artistAlbums.CleanValue = artistItem.CleanName AND artistAlbums.TYPE = 1 AND artistItem.Guid = A.Guid
+ ) SELECT COUNT(DISTINCT(CleanValue)) * 10 FROM ItemValues WHERE ItemId IN (SELECT ItemId FROM similarArtist) AND CleanValue IN (SELECT CleanValue FROM artistValues))");
+ }
builder.Append(") as SimilarityScore");
@@ -2922,7 +2943,8 @@ namespace Emby.Server.Implementations.Data
var result = new QueryResult();
using (var connection = GetConnection(true))
{
- connection.RunInTransaction(db =>
+ connection.RunInTransaction(
+ db =>
{
var statements = PrepareAll(db, statementTexts);
@@ -3291,7 +3313,6 @@ namespace Emby.Server.Implementations.Data
}
}
-
var isReturningZeroItems = query.Limit.HasValue && query.Limit <= 0;
var statementTexts = new List();
@@ -3326,7 +3347,8 @@ namespace Emby.Server.Implementations.Data
var result = new QueryResult();
using (var connection = GetConnection(true))
{
- connection.RunInTransaction(db =>
+ connection.RunInTransaction(
+ db =>
{
var statements = PrepareAll(db, statementTexts);
@@ -3910,7 +3932,7 @@ namespace Emby.Server.Implementations.Data
if (query.IsPlayed.HasValue)
{
// We should probably figure this out for all folders, but for right now, this is the only place where we need it
- if (query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], typeof(Series).Name, StringComparison.OrdinalIgnoreCase))
+ if (query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], nameof(Series), StringComparison.OrdinalIgnoreCase))
{
if (query.IsPlayed.Value)
{
@@ -4751,29 +4773,29 @@ namespace Emby.Server.Implementations.Data
{
var list = new List();
- if (IsTypeInQuery(typeof(Person).Name, query))
+ if (IsTypeInQuery(nameof(Person), query))
{
- list.Add(typeof(Person).Name);
+ list.Add(nameof(Person));
}
- if (IsTypeInQuery(typeof(Genre).Name, query))
+ if (IsTypeInQuery(nameof(Genre), query))
{
- list.Add(typeof(Genre).Name);
+ list.Add(nameof(Genre));
}
- if (IsTypeInQuery(typeof(MusicGenre).Name, query))
+ if (IsTypeInQuery(nameof(MusicGenre), query))
{
- list.Add(typeof(MusicGenre).Name);
+ list.Add(nameof(MusicGenre));
}
- if (IsTypeInQuery(typeof(MusicArtist).Name, query))
+ if (IsTypeInQuery(nameof(MusicArtist), query))
{
- list.Add(typeof(MusicArtist).Name);
+ list.Add(nameof(MusicArtist));
}
- if (IsTypeInQuery(typeof(Studio).Name, query))
+ if (IsTypeInQuery(nameof(Studio), query))
{
- list.Add(typeof(Studio).Name);
+ list.Add(nameof(Studio));
}
return list;
@@ -4828,12 +4850,12 @@ namespace Emby.Server.Implementations.Data
var types = new[]
{
- typeof(Episode).Name,
- typeof(Video).Name,
- typeof(Movie).Name,
- typeof(MusicVideo).Name,
- typeof(Series).Name,
- typeof(Season).Name
+ nameof(Episode),
+ nameof(Video),
+ nameof(Movie),
+ nameof(MusicVideo),
+ nameof(Series),
+ nameof(Season)
};
if (types.Any(i => query.IncludeItemTypes.Contains(i, StringComparer.OrdinalIgnoreCase)))
@@ -4901,7 +4923,8 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
using (var connection = GetConnection())
{
- connection.RunInTransaction(db =>
+ connection.RunInTransaction(
+ db =>
{
connection.ExecuteAll(sql);
}, TransactionMode);
@@ -4952,7 +4975,8 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
using (var connection = GetConnection())
{
- connection.RunInTransaction(db =>
+ connection.RunInTransaction(
+ db =>
{
var idBlob = id.ToByteArray();
@@ -4996,26 +5020,33 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
CheckDisposed();
- var commandText = "select Distinct Name from People";
+ var commandText = new StringBuilder("select Distinct p.Name from People p");
+
+ if (query.User != null && query.IsFavorite.HasValue)
+ {
+ commandText.Append(" LEFT JOIN TypedBaseItems tbi ON tbi.Name=p.Name AND tbi.Type='");
+ commandText.Append(typeof(Person).FullName);
+ commandText.Append("' LEFT JOIN UserDatas ON tbi.UserDataKey=key AND userId=@UserId");
+ }
var whereClauses = GetPeopleWhereClauses(query, null);
if (whereClauses.Count != 0)
{
- commandText += " where " + string.Join(" AND ", whereClauses);
+ commandText.Append(" where ").Append(string.Join(" AND ", whereClauses));
}
- commandText += " order by ListOrder";
+ commandText.Append(" order by ListOrder");
if (query.Limit > 0)
{
- commandText += " LIMIT " + query.Limit;
+ commandText.Append(" LIMIT ").Append(query.Limit);
}
using (var connection = GetConnection(true))
{
var list = new List();
- using (var statement = PrepareStatement(connection, commandText))
+ using (var statement = PrepareStatement(connection, commandText.ToString()))
{
// Run this again to bind the params
GetPeopleWhereClauses(query, statement);
@@ -5039,7 +5070,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
CheckDisposed();
- var commandText = "select ItemId, Name, Role, PersonType, SortOrder from People";
+ var commandText = "select ItemId, Name, Role, PersonType, SortOrder from People p";
var whereClauses = GetPeopleWhereClauses(query, null);
@@ -5081,19 +5112,13 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
if (!query.ItemId.Equals(Guid.Empty))
{
whereClauses.Add("ItemId=@ItemId");
- if (statement != null)
- {
- statement.TryBind("@ItemId", query.ItemId.ToByteArray());
- }
+ statement?.TryBind("@ItemId", query.ItemId.ToByteArray());
}
if (!query.AppearsInItemId.Equals(Guid.Empty))
{
- whereClauses.Add("Name in (Select Name from People where ItemId=@AppearsInItemId)");
- if (statement != null)
- {
- statement.TryBind("@AppearsInItemId", query.AppearsInItemId.ToByteArray());
- }
+ whereClauses.Add("p.Name in (Select Name from People where ItemId=@AppearsInItemId)");
+ statement?.TryBind("@AppearsInItemId", query.AppearsInItemId.ToByteArray());
}
var queryPersonTypes = query.PersonTypes.Where(IsValidPersonType).ToList();
@@ -5101,10 +5126,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
if (queryPersonTypes.Count == 1)
{
whereClauses.Add("PersonType=@PersonType");
- if (statement != null)
- {
- statement.TryBind("@PersonType", queryPersonTypes[0]);
- }
+ statement?.TryBind("@PersonType", queryPersonTypes[0]);
}
else if (queryPersonTypes.Count > 1)
{
@@ -5118,10 +5140,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
if (queryExcludePersonTypes.Count == 1)
{
whereClauses.Add("PersonType<>@PersonType");
- if (statement != null)
- {
- statement.TryBind("@PersonType", queryExcludePersonTypes[0]);
- }
+ statement?.TryBind("@PersonType", queryExcludePersonTypes[0]);
}
else if (queryExcludePersonTypes.Count > 1)
{
@@ -5133,19 +5152,24 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
if (query.MaxListOrder.HasValue)
{
whereClauses.Add("ListOrder<=@MaxListOrder");
- if (statement != null)
- {
- statement.TryBind("@MaxListOrder", query.MaxListOrder.Value);
- }
+ statement?.TryBind("@MaxListOrder", query.MaxListOrder.Value);
}
if (!string.IsNullOrWhiteSpace(query.NameContains))
{
- whereClauses.Add("Name like @NameContains");
- if (statement != null)
- {
- statement.TryBind("@NameContains", "%" + query.NameContains + "%");
- }
+ whereClauses.Add("p.Name like @NameContains");
+ statement?.TryBind("@NameContains", "%" + query.NameContains + "%");
+ }
+
+ if (query.IsFavorite.HasValue)
+ {
+ whereClauses.Add("isFavorite=@IsFavorite");
+ statement?.TryBind("@IsFavorite", query.IsFavorite.Value);
+ }
+
+ if (query.User != null)
+ {
+ statement?.TryBind("@UserId", query.User.InternalId);
}
return whereClauses;
@@ -5359,7 +5383,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
itemCountColumns = new Dictionary()
{
- { "itemTypes", "(" + itemCountColumnQuery + ") as itemTypes"}
+ { "itemTypes", "(" + itemCountColumnQuery + ") as itemTypes" }
};
}
@@ -5414,6 +5438,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
NameStartsWithOrGreater = query.NameStartsWithOrGreater,
Tags = query.Tags,
OfficialRatings = query.OfficialRatings,
+ StudioIds = query.StudioIds,
GenreIds = query.GenreIds,
Genres = query.Genres,
Years = query.Years,
@@ -5586,7 +5611,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
return counts;
}
- var allTypes = typeString.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
+ var allTypes = typeString.Split('|', StringSplitOptions.RemoveEmptyEntries)
.ToLookup(x => x);
foreach (var type in allTypes)
@@ -5746,7 +5771,8 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
using (var connection = GetConnection())
{
- connection.RunInTransaction(db =>
+ connection.RunInTransaction(
+ db =>
{
var itemIdBlob = itemId.ToByteArray();
@@ -5900,7 +5926,8 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
using (var connection = GetConnection())
{
- connection.RunInTransaction(db =>
+ connection.RunInTransaction(
+ db =>
{
var itemIdBlob = id.ToByteArray();
@@ -6006,7 +6033,6 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
}
}
-
///
/// Gets the chapter.
///
@@ -6235,7 +6261,8 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
using (var connection = GetConnection())
{
- connection.RunInTransaction(db =>
+ connection.RunInTransaction(
+ db =>
{
var itemIdBlob = id.ToByteArray();
diff --git a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs
index 4a78aac8e6..2c4e8e0fcc 100644
--- a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs
+++ b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs
@@ -44,7 +44,8 @@ namespace Emby.Server.Implementations.Data
var users = userDatasTableExists ? null : userManager.Users;
- connection.RunInTransaction(db =>
+ connection.RunInTransaction(
+ db =>
{
db.ExecuteAll(string.Join(";", new[] {
@@ -178,7 +179,8 @@ namespace Emby.Server.Implementations.Data
using (var connection = GetConnection())
{
- connection.RunInTransaction(db =>
+ connection.RunInTransaction(
+ db =>
{
SaveUserData(db, internalUserId, key, userData);
}, TransactionMode);
@@ -246,7 +248,8 @@ namespace Emby.Server.Implementations.Data
using (var connection = GetConnection())
{
- connection.RunInTransaction(db =>
+ connection.RunInTransaction(
+ db =>
{
foreach (var userItemData in userDataList)
{
diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs
index 94cfed767b..f3e3a6397f 100644
--- a/Emby.Server.Implementations/Dto/DtoService.cs
+++ b/Emby.Server.Implementations/Dto/DtoService.cs
@@ -275,7 +275,7 @@ namespace Emby.Server.Implementations.Dto
continue;
}
- var containers = container.Split(new[] { ',' });
+ var containers = container.Split(',');
if (containers.Length < 2)
{
continue;
@@ -465,10 +465,9 @@ namespace Emby.Server.Implementations.Dto
{
var parentAlbumIds = _libraryManager.GetItemIds(new InternalItemsQuery
{
- IncludeItemTypes = new[] { typeof(MusicAlbum).Name },
+ IncludeItemTypes = new[] { nameof(MusicAlbum) },
Name = item.Album,
Limit = 1
-
});
if (parentAlbumIds.Count > 0)
@@ -1139,6 +1138,7 @@ namespace Emby.Server.Implementations.Dto
if (episodeSeries != null)
{
dto.SeriesPrimaryImageTag = GetTagAndFillBlurhash(dto, episodeSeries, ImageType.Primary);
+ AttachPrimaryImageAspectRatio(dto, episodeSeries);
}
}
@@ -1185,6 +1185,7 @@ namespace Emby.Server.Implementations.Dto
if (series != null)
{
dto.SeriesPrimaryImageTag = GetTagAndFillBlurhash(dto, series, ImageType.Primary);
+ AttachPrimaryImageAspectRatio(dto, series);
}
}
}
diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj
index c84c7b53df..d360bb00f2 100644
--- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj
+++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj
@@ -22,7 +22,7 @@
-
+
@@ -32,13 +32,13 @@
-
-
-
-
-
+
+
+
+
+
-
+
@@ -49,10 +49,12 @@
- netstandard2.1
+ net5.0
false
true
true
+
+ AD0001
diff --git a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs
index c9d21d9638..ff64e217a0 100644
--- a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs
+++ b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs
@@ -16,6 +16,7 @@ using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Session;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.EntryPoints
@@ -105,7 +106,7 @@ namespace Emby.Server.Implementations.EntryPoints
try
{
- _sessionManager.SendMessageToAdminSessions("RefreshProgress", dict, CancellationToken.None);
+ _sessionManager.SendMessageToAdminSessions(SessionMessageType.RefreshProgress, dict, CancellationToken.None);
}
catch
{
@@ -123,7 +124,7 @@ namespace Emby.Server.Implementations.EntryPoints
try
{
- _sessionManager.SendMessageToAdminSessions("RefreshProgress", collectionFolderDict, CancellationToken.None);
+ _sessionManager.SendMessageToAdminSessions(SessionMessageType.RefreshProgress, collectionFolderDict, CancellationToken.None);
}
catch
{
@@ -345,7 +346,7 @@ namespace Emby.Server.Implementations.EntryPoints
try
{
- await _sessionManager.SendMessageToUserSessions(new List { userId }, "LibraryChanged", info, cancellationToken).ConfigureAwait(false);
+ await _sessionManager.SendMessageToUserSessions(new List { userId }, SessionMessageType.LibraryChanged, info, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
diff --git a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs
index 44d2580d68..824bb85f44 100644
--- a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs
+++ b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs
@@ -10,6 +10,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.EntryPoints
@@ -46,25 +47,25 @@ namespace Emby.Server.Implementations.EntryPoints
private async void OnLiveTvManagerSeriesTimerCreated(object sender, GenericEventArgs e)
{
- await SendMessage("SeriesTimerCreated", e.Argument).ConfigureAwait(false);
+ await SendMessage(SessionMessageType.SeriesTimerCreated, e.Argument).ConfigureAwait(false);
}
private async void OnLiveTvManagerTimerCreated(object sender, GenericEventArgs e)
{
- await SendMessage("TimerCreated", e.Argument).ConfigureAwait(false);
+ await SendMessage(SessionMessageType.TimerCreated, e.Argument).ConfigureAwait(false);
}
private async void OnLiveTvManagerSeriesTimerCancelled(object sender, GenericEventArgs e)
{
- await SendMessage("SeriesTimerCancelled", e.Argument).ConfigureAwait(false);
+ await SendMessage(SessionMessageType.SeriesTimerCancelled, e.Argument).ConfigureAwait(false);
}
private async void OnLiveTvManagerTimerCancelled(object sender, GenericEventArgs e)
{
- await SendMessage("TimerCancelled", e.Argument).ConfigureAwait(false);
+ await SendMessage(SessionMessageType.TimerCancelled, e.Argument).ConfigureAwait(false);
}
- private async Task SendMessage(string name, TimerEventInfo info)
+ private async Task SendMessage(SessionMessageType name, TimerEventInfo info)
{
var users = _userManager.Users.Where(i => i.HasPermission(PermissionKind.EnableLiveTvAccess)).Select(i => i.Id).ToList();
diff --git a/Emby.Server.Implementations/EntryPoints/StartupWizard.cs b/Emby.Server.Implementations/EntryPoints/StartupWizard.cs
deleted file mode 100644
index 2e738deeb5..0000000000
--- a/Emby.Server.Implementations/EntryPoints/StartupWizard.cs
+++ /dev/null
@@ -1,83 +0,0 @@
-using System.Threading.Tasks;
-using Emby.Server.Implementations.Browser;
-using MediaBrowser.Controller;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Extensions;
-using MediaBrowser.Controller.Plugins;
-using Microsoft.Extensions.Configuration;
-
-namespace Emby.Server.Implementations.EntryPoints
-{
- ///
- /// Class StartupWizard.
- ///
- public sealed class StartupWizard : IServerEntryPoint
- {
- private readonly IServerApplicationHost _appHost;
- private readonly IConfiguration _appConfig;
- private readonly IServerConfigurationManager _config;
- private readonly IStartupOptions _startupOptions;
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The application host.
- /// The application configuration.
- /// The configuration manager.
- /// The application startup options.
- public StartupWizard(
- IServerApplicationHost appHost,
- IConfiguration appConfig,
- IServerConfigurationManager config,
- IStartupOptions startupOptions)
- {
- _appHost = appHost;
- _appConfig = appConfig;
- _config = config;
- _startupOptions = startupOptions;
- }
-
- ///
- public Task RunAsync()
- {
- Run();
- return Task.CompletedTask;
- }
-
- private void Run()
- {
- if (!_appHost.CanLaunchWebBrowser)
- {
- return;
- }
-
- // Always launch the startup wizard if possible when it has not been completed
- if (!_config.Configuration.IsStartupWizardCompleted && _appConfig.HostWebClient())
- {
- BrowserLauncher.OpenWebApp(_appHost);
- return;
- }
-
- // Do nothing if the web app is configured to not run automatically
- if (!_config.Configuration.AutoRunWebApp || _startupOptions.NoAutoRunWebApp)
- {
- return;
- }
-
- // Launch the swagger page if the web client is not hosted, otherwise open the web client
- if (_appConfig.HostWebClient())
- {
- BrowserLauncher.OpenWebApp(_appHost);
- }
- else
- {
- BrowserLauncher.OpenSwaggerPage(_appHost);
- }
- }
-
- ///
- public void Dispose()
- {
- }
- }
-}
diff --git a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs
index 3618b88c5d..1989e9ed25 100644
--- a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs
+++ b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs
@@ -28,7 +28,6 @@ namespace Emby.Server.Implementations.EntryPoints
private readonly object _syncLock = new object();
private Timer _updateTimer;
-
public UserDataChangeNotifier(IUserDataManager userDataManager, ISessionManager sessionManager, IUserManager userManager)
{
_userDataManager = userDataManager;
@@ -116,7 +115,7 @@ namespace Emby.Server.Implementations.EntryPoints
private Task SendNotifications(Guid userId, List changedItems, CancellationToken cancellationToken)
{
- return _sessionManager.SendMessageToUserSessions(new List { userId }, "UserDataChanged", () => GetUserDataChangeInfo(userId, changedItems), cancellationToken);
+ return _sessionManager.SendMessageToUserSessions(new List { userId }, SessionMessageType.UserDataChanged, () => GetUserDataChangeInfo(userId, changedItems), cancellationToken);
}
private UserDataChangeInfo GetUserDataChangeInfo(Guid userId, List changedItems)
diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs
index 68d981ad1f..df7a034e8f 100644
--- a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs
+++ b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs
@@ -1,6 +1,7 @@
#pragma warning disable CS1591
using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Authentication;
using MediaBrowser.Controller.Net;
using Microsoft.AspNetCore.Http;
@@ -19,12 +20,12 @@ namespace Emby.Server.Implementations.HttpServer.Security
public AuthorizationInfo Authenticate(HttpRequest request)
{
var auth = _authorizationContext.GetAuthorizationInfo(request);
- if (auth?.User == null)
+ if (!auth.IsAuthenticated)
{
- return null;
+ throw new AuthenticationException("Invalid token.");
}
- if (auth.User.HasPermission(PermissionKind.IsDisabled))
+ if (auth.User?.HasPermission(PermissionKind.IsDisabled) ?? false)
{
throw new SecurityException("User account has been disabled.");
}
diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs
index 4b407dd9d2..fdf2e3908a 100644
--- a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs
+++ b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs
@@ -36,8 +36,7 @@ namespace Emby.Server.Implementations.HttpServer.Security
public AuthorizationInfo GetAuthorizationInfo(HttpRequest requestContext)
{
var auth = GetAuthorizationDictionary(requestContext);
- var (authInfo, _) =
- GetAuthorizationInfoFromDictionary(auth, requestContext.Headers, requestContext.Query);
+ var authInfo = GetAuthorizationInfoFromDictionary(auth, requestContext.Headers, requestContext.Query);
return authInfo;
}
@@ -49,19 +48,13 @@ namespace Emby.Server.Implementations.HttpServer.Security
private AuthorizationInfo GetAuthorization(HttpContext httpReq)
{
var auth = GetAuthorizationDictionary(httpReq);
- var (authInfo, originalAuthInfo) =
- GetAuthorizationInfoFromDictionary(auth, httpReq.Request.Headers, httpReq.Request.Query);
-
- if (originalAuthInfo != null)
- {
- httpReq.Request.HttpContext.Items["OriginalAuthenticationInfo"] = originalAuthInfo;
- }
+ var authInfo = GetAuthorizationInfoFromDictionary(auth, httpReq.Request.Headers, httpReq.Request.Query);
httpReq.Request.HttpContext.Items["AuthorizationInfo"] = authInfo;
return authInfo;
}
- private (AuthorizationInfo authInfo, AuthenticationInfo originalAuthenticationInfo) GetAuthorizationInfoFromDictionary(
+ private AuthorizationInfo GetAuthorizationInfoFromDictionary(
in Dictionary auth,
in IHeaderDictionary headers,
in IQueryCollection queryString)
@@ -108,88 +101,102 @@ namespace Emby.Server.Implementations.HttpServer.Security
Device = device,
DeviceId = deviceId,
Version = version,
- Token = token
+ Token = token,
+ IsAuthenticated = false
};
- AuthenticationInfo originalAuthenticationInfo = null;
- if (!string.IsNullOrWhiteSpace(token))
+ if (string.IsNullOrWhiteSpace(token))
{
- var result = _authRepo.Get(new AuthenticationInfoQuery
+ // Request doesn't contain a token.
+ return authInfo;
+ }
+
+ var result = _authRepo.Get(new AuthenticationInfoQuery
+ {
+ AccessToken = token
+ });
+
+ if (result.Items.Count > 0)
+ {
+ authInfo.IsAuthenticated = true;
+ }
+
+ var originalAuthenticationInfo = result.Items.Count > 0 ? result.Items[0] : null;
+
+ if (originalAuthenticationInfo != null)
+ {
+ var updateToken = false;
+
+ // TODO: Remove these checks for IsNullOrWhiteSpace
+ if (string.IsNullOrWhiteSpace(authInfo.Client))
{
- AccessToken = token
- });
+ authInfo.Client = originalAuthenticationInfo.AppName;
+ }
- originalAuthenticationInfo = result.Items.Count > 0 ? result.Items[0] : null;
-
- if (originalAuthenticationInfo != null)
+ if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
{
- var updateToken = false;
+ authInfo.DeviceId = originalAuthenticationInfo.DeviceId;
+ }
- // TODO: Remove these checks for IsNullOrWhiteSpace
- if (string.IsNullOrWhiteSpace(authInfo.Client))
- {
- authInfo.Client = originalAuthenticationInfo.AppName;
- }
+ // Temporary. TODO - allow clients to specify that the token has been shared with a casting device
+ var allowTokenInfoUpdate = authInfo.Client == null || authInfo.Client.IndexOf("chromecast", StringComparison.OrdinalIgnoreCase) == -1;
- if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
+ if (string.IsNullOrWhiteSpace(authInfo.Device))
+ {
+ authInfo.Device = originalAuthenticationInfo.DeviceName;
+ }
+ else if (!string.Equals(authInfo.Device, originalAuthenticationInfo.DeviceName, StringComparison.OrdinalIgnoreCase))
+ {
+ if (allowTokenInfoUpdate)
{
- authInfo.DeviceId = originalAuthenticationInfo.DeviceId;
+ updateToken = true;
+ originalAuthenticationInfo.DeviceName = authInfo.Device;
}
+ }
- // Temporary. TODO - allow clients to specify that the token has been shared with a casting device
- var allowTokenInfoUpdate = authInfo.Client == null || authInfo.Client.IndexOf("chromecast", StringComparison.OrdinalIgnoreCase) == -1;
+ if (string.IsNullOrWhiteSpace(authInfo.Version))
+ {
+ authInfo.Version = originalAuthenticationInfo.AppVersion;
+ }
+ else if (!string.Equals(authInfo.Version, originalAuthenticationInfo.AppVersion, StringComparison.OrdinalIgnoreCase))
+ {
+ if (allowTokenInfoUpdate)
+ {
+ updateToken = true;
+ originalAuthenticationInfo.AppVersion = authInfo.Version;
+ }
+ }
- if (string.IsNullOrWhiteSpace(authInfo.Device))
- {
- authInfo.Device = originalAuthenticationInfo.DeviceName;
- }
- else if (!string.Equals(authInfo.Device, originalAuthenticationInfo.DeviceName, StringComparison.OrdinalIgnoreCase))
- {
- if (allowTokenInfoUpdate)
- {
- updateToken = true;
- originalAuthenticationInfo.DeviceName = authInfo.Device;
- }
- }
+ if ((DateTime.UtcNow - originalAuthenticationInfo.DateLastActivity).TotalMinutes > 3)
+ {
+ originalAuthenticationInfo.DateLastActivity = DateTime.UtcNow;
+ updateToken = true;
+ }
- if (string.IsNullOrWhiteSpace(authInfo.Version))
- {
- authInfo.Version = originalAuthenticationInfo.AppVersion;
- }
- else if (!string.Equals(authInfo.Version, originalAuthenticationInfo.AppVersion, StringComparison.OrdinalIgnoreCase))
- {
- if (allowTokenInfoUpdate)
- {
- updateToken = true;
- originalAuthenticationInfo.AppVersion = authInfo.Version;
- }
- }
+ if (!originalAuthenticationInfo.UserId.Equals(Guid.Empty))
+ {
+ authInfo.User = _userManager.GetUserById(originalAuthenticationInfo.UserId);
- if ((DateTime.UtcNow - originalAuthenticationInfo.DateLastActivity).TotalMinutes > 3)
+ if (authInfo.User != null && !string.Equals(authInfo.User.Username, originalAuthenticationInfo.UserName, StringComparison.OrdinalIgnoreCase))
{
- originalAuthenticationInfo.DateLastActivity = DateTime.UtcNow;
+ originalAuthenticationInfo.UserName = authInfo.User.Username;
updateToken = true;
}
- if (!originalAuthenticationInfo.UserId.Equals(Guid.Empty))
- {
- authInfo.User = _userManager.GetUserById(originalAuthenticationInfo.UserId);
+ authInfo.IsApiKey = true;
+ }
+ else
+ {
+ authInfo.IsApiKey = false;
+ }
- if (authInfo.User != null && !string.Equals(authInfo.User.Username, originalAuthenticationInfo.UserName, StringComparison.OrdinalIgnoreCase))
- {
- originalAuthenticationInfo.UserName = authInfo.User.Username;
- updateToken = true;
- }
- }
-
- if (updateToken)
- {
- _authRepo.Update(originalAuthenticationInfo);
- }
+ if (updateToken)
+ {
+ _authRepo.Update(originalAuthenticationInfo);
}
}
- return (authInfo, originalAuthenticationInfo);
+ return authInfo;
}
///
@@ -238,7 +245,7 @@ namespace Emby.Server.Implementations.HttpServer.Security
return null;
}
- var parts = authorizationHeader.Split(new[] { ' ' }, 2);
+ var parts = authorizationHeader.Split(' ', 2);
// There should be at least to parts
if (parts.Length != 2)
@@ -262,12 +269,12 @@ namespace Emby.Server.Implementations.HttpServer.Security
foreach (var item in parts)
{
- var param = item.Trim().Split(new[] { '=' }, 2);
+ var param = item.Trim().Split('=', 2);
if (param.Length == 2)
{
- var value = NormalizeValue(param[1].Trim(new[] { '"' }));
- result.Add(param[0], value);
+ var value = NormalizeValue(param[1].Trim('"'));
+ result[param[0]] = value;
}
}
diff --git a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs
index 7eae4e7646..fed2addf80 100644
--- a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs
+++ b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs
@@ -11,6 +11,7 @@ using System.Threading.Tasks;
using MediaBrowser.Common.Json;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Net;
+using MediaBrowser.Model.Session;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
@@ -227,7 +228,7 @@ namespace Emby.Server.Implementations.HttpServer
Connection = this
};
- if (info.MessageType.Equals("KeepAlive", StringComparison.Ordinal))
+ if (info.MessageType == SessionMessageType.KeepAlive)
{
await SendKeepAliveResponse().ConfigureAwait(false);
}
@@ -244,7 +245,7 @@ namespace Emby.Server.Implementations.HttpServer
new WebSocketMessage
{
MessageId = Guid.NewGuid(),
- MessageType = "KeepAlive"
+ MessageType = SessionMessageType.KeepAlive
}, CancellationToken.None);
}
diff --git a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs
index 89c1b7ea08..71ece80a75 100644
--- a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs
+++ b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs
@@ -2,7 +2,6 @@
using System;
using System.Collections.Generic;
-using System.Linq;
using System.Net.WebSockets;
using System.Threading.Tasks;
using Jellyfin.Data.Events;
@@ -14,16 +13,18 @@ namespace Emby.Server.Implementations.HttpServer
{
public class WebSocketManager : IWebSocketManager
{
+ private readonly Lazy> _webSocketListeners;
private readonly ILogger _logger;
private readonly ILoggerFactory _loggerFactory;
- private IWebSocketListener[] _webSocketListeners = Array.Empty();
private bool _disposed = false;
public WebSocketManager(
+ Lazy> webSocketListeners,
ILogger logger,
ILoggerFactory loggerFactory)
{
+ _webSocketListeners = webSocketListeners;
_logger = logger;
_loggerFactory = loggerFactory;
}
@@ -68,15 +69,6 @@ namespace Emby.Server.Implementations.HttpServer
}
}
- ///
- /// Adds the rest handlers.
- ///
- /// The web socket listeners.
- public void Init(IEnumerable listeners)
- {
- _webSocketListeners = listeners.ToArray();
- }
-
///
/// Processes the web socket message received.
///
@@ -90,7 +82,8 @@ namespace Emby.Server.Implementations.HttpServer
IEnumerable GetTasks()
{
- foreach (var x in _webSocketListeners)
+ var listeners = _webSocketListeners.Value;
+ foreach (var x in listeners)
{
yield return x.ProcessMessageAsync(result);
}
diff --git a/Emby.Server.Implementations/IStartupOptions.cs b/Emby.Server.Implementations/IStartupOptions.cs
index e7e72c686b..4bef59543f 100644
--- a/Emby.Server.Implementations/IStartupOptions.cs
+++ b/Emby.Server.Implementations/IStartupOptions.cs
@@ -16,11 +16,6 @@ namespace Emby.Server.Implementations
///
bool IsService { get; }
- ///
- /// Gets the value of the --noautorunwebapp command line option.
- ///
- bool NoAutoRunWebApp { get; }
-
///
/// Gets the value of the --package-name command line option.
///
diff --git a/Emby.Server.Implementations/Images/ArtistImageProvider.cs b/Emby.Server.Implementations/Images/ArtistImageProvider.cs
index bf57382ed4..afa4ec7b1b 100644
--- a/Emby.Server.Implementations/Images/ArtistImageProvider.cs
+++ b/Emby.Server.Implementations/Images/ArtistImageProvider.cs
@@ -42,7 +42,7 @@ namespace Emby.Server.Implementations.Images
// return _libraryManager.GetItemList(new InternalItemsQuery
// {
// ArtistIds = new[] { item.Id },
- // IncludeItemTypes = new[] { typeof(MusicAlbum).Name },
+ // IncludeItemTypes = new[] { nameof(MusicAlbum) },
// OrderBy = new[] { (ItemSortBy.Random, SortOrder.Ascending) },
// Limit = 4,
// Recursive = true,
diff --git a/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs b/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs
index 57302b5067..5f7e51858a 100644
--- a/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs
+++ b/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs
@@ -133,9 +133,20 @@ namespace Emby.Server.Implementations.Images
protected virtual IEnumerable GetStripCollageImagePaths(BaseItem primaryItem, IEnumerable items)
{
+ var useBackdrop = primaryItem is CollectionFolder;
return items
.Select(i =>
{
+ // Use Backdrop instead of Primary image for Library images.
+ if (useBackdrop)
+ {
+ var backdrop = i.GetImageInfo(ImageType.Backdrop, 0);
+ if (backdrop != null && backdrop.IsLocalFile)
+ {
+ return backdrop.Path;
+ }
+ }
+
var image = i.GetImageInfo(ImageType.Primary, 0);
if (image != null && image.IsLocalFile)
{
@@ -190,7 +201,7 @@ namespace Emby.Server.Implementations.Images
return null;
}
- ImageProcessor.CreateImageCollage(options);
+ ImageProcessor.CreateImageCollage(options, primaryItem.Name);
return outputPath;
}
diff --git a/Emby.Server.Implementations/Images/GenreImageProvider.cs b/Emby.Server.Implementations/Images/GenreImageProvider.cs
index 1cd4cd66bd..3817882312 100644
--- a/Emby.Server.Implementations/Images/GenreImageProvider.cs
+++ b/Emby.Server.Implementations/Images/GenreImageProvider.cs
@@ -42,7 +42,12 @@ namespace Emby.Server.Implementations.Images
return _libraryManager.GetItemList(new InternalItemsQuery
{
Genres = new[] { item.Name },
- IncludeItemTypes = new[] { typeof(MusicAlbum).Name, typeof(MusicVideo).Name, typeof(Audio).Name },
+ IncludeItemTypes = new[]
+ {
+ nameof(MusicAlbum),
+ nameof(MusicVideo),
+ nameof(Audio)
+ },
OrderBy = new[] { (ItemSortBy.Random, SortOrder.Ascending) },
Limit = 4,
Recursive = true,
@@ -77,7 +82,7 @@ namespace Emby.Server.Implementations.Images
return _libraryManager.GetItemList(new InternalItemsQuery
{
Genres = new[] { item.Name },
- IncludeItemTypes = new[] { typeof(Series).Name, typeof(Movie).Name },
+ IncludeItemTypes = new[] { nameof(Series), nameof(Movie) },
OrderBy = new[] { (ItemSortBy.Random, SortOrder.Ascending) },
Limit = 4,
Recursive = true,
diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs
index 00282b71a5..d838734414 100644
--- a/Emby.Server.Implementations/Library/LibraryManager.cs
+++ b/Emby.Server.Implementations/Library/LibraryManager.cs
@@ -6,6 +6,7 @@ using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
+using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Emby.Naming.Audio;
@@ -2440,6 +2441,21 @@ namespace Emby.Server.Implementations.Library
new SubtitleResolver(BaseItem.LocalizationManager).AddExternalSubtitleStreams(streams, videoPath, streams.Count, files);
}
+ public BaseItem GetParentItem(string parentId, Guid? userId)
+ {
+ if (!string.IsNullOrEmpty(parentId))
+ {
+ return GetItemById(new Guid(parentId));
+ }
+
+ if (userId.HasValue && userId != Guid.Empty)
+ {
+ return GetUserRootFolder();
+ }
+
+ return RootFolder;
+ }
+
///
public bool IsVideoFile(string path)
{
@@ -2470,9 +2486,10 @@ namespace Emby.Server.Implementations.Library
var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd;
+ // TODO nullable - what are we trying to do there with empty episodeInfo?
var episodeInfo = episode.IsFileProtocol
- ? resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming) ?? new Naming.TV.EpisodeInfo()
- : new Naming.TV.EpisodeInfo();
+ ? resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming) ?? new Naming.TV.EpisodeInfo(episode.Path)
+ : new Naming.TV.EpisodeInfo(episode.Path);
try
{
@@ -2561,12 +2578,12 @@ namespace Emby.Server.Implementations.Library
if (!episode.IndexNumberEnd.HasValue || forceRefresh)
{
- if (episode.IndexNumberEnd != episodeInfo.EndingEpsiodeNumber)
+ if (episode.IndexNumberEnd != episodeInfo.EndingEpisodeNumber)
{
changed = true;
}
- episode.IndexNumberEnd = episodeInfo.EndingEpsiodeNumber;
+ episode.IndexNumberEnd = episodeInfo.EndingEpisodeNumber;
}
if (!episode.ParentIndexNumber.HasValue || forceRefresh)
@@ -2690,7 +2707,7 @@ namespace Emby.Server.Implementations.Library
var videos = videoListResolver.Resolve(fileSystemChildren);
- var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files.First().Path, StringComparison.OrdinalIgnoreCase));
+ var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files[0].Path, StringComparison.OrdinalIgnoreCase));
if (currentVideo != null)
{
@@ -2892,7 +2909,7 @@ namespace Emby.Server.Implementations.Library
return item.GetImageInfo(image.Type, imageIndex);
}
- catch (HttpException ex)
+ catch (HttpRequestException ex)
{
if (ex.StatusCode.HasValue
&& (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forbidden))
diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs
index 67cf8bf5ba..928f5f88e4 100644
--- a/Emby.Server.Implementations/Library/MediaSourceManager.cs
+++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs
@@ -1,6 +1,7 @@
#pragma warning disable CS1591
using System;
+using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
@@ -43,7 +44,7 @@ namespace Emby.Server.Implementations.Library
private readonly ILocalizationManager _localizationManager;
private readonly IApplicationPaths _appPaths;
- private readonly Dictionary _openStreams = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ private readonly ConcurrentDictionary _openStreams = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase);
private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1);
private IMediaSourceProvider[] _providers;
@@ -582,29 +583,20 @@ namespace Emby.Server.Implementations.Library
mediaSource.InferTotalBitrate();
}
- public async Task GetDirectStreamProviderByUniqueId(string uniqueId, CancellationToken cancellationToken)
+ public Task GetDirectStreamProviderByUniqueId(string uniqueId, CancellationToken cancellationToken)
{
- await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
-
- try
+ var info = _openStreams.Values.FirstOrDefault(i =>
{
- var info = _openStreams.Values.FirstOrDefault(i =>
+ var liveStream = i as ILiveStream;
+ if (liveStream != null)
{
- var liveStream = i as ILiveStream;
- if (liveStream != null)
- {
- return string.Equals(liveStream.UniqueId, uniqueId, StringComparison.OrdinalIgnoreCase);
- }
+ return string.Equals(liveStream.UniqueId, uniqueId, StringComparison.OrdinalIgnoreCase);
+ }
- return false;
- });
+ return false;
+ });
- return info as IDirectStreamProvider;
- }
- finally
- {
- _liveStreamSemaphore.Release();
- }
+ return Task.FromResult(info as IDirectStreamProvider);
}
public async Task OpenLiveStream(LiveStreamRequest request, CancellationToken cancellationToken)
@@ -793,29 +785,20 @@ namespace Emby.Server.Implementations.Library
return new Tuple(info.MediaSource, info as IDirectStreamProvider);
}
- private async Task GetLiveStreamInfo(string id, CancellationToken cancellationToken)
+ private Task GetLiveStreamInfo(string id, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException(nameof(id));
}
- await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
-
- try
+ if (_openStreams.TryGetValue(id, out ILiveStream info))
{
- if (_openStreams.TryGetValue(id, out ILiveStream info))
- {
- return info;
- }
- else
- {
- throw new ResourceNotFoundException();
- }
+ return Task.FromResult(info);
}
- finally
+ else
{
- _liveStreamSemaphore.Release();
+ return Task.FromException(new ResourceNotFoundException());
}
}
@@ -844,7 +827,7 @@ namespace Emby.Server.Implementations.Library
if (liveStream.ConsumerCount <= 0)
{
- _openStreams.Remove(id);
+ _openStreams.TryRemove(id, out _);
_logger.LogInformation("Closing live stream {0}", id);
@@ -866,7 +849,7 @@ namespace Emby.Server.Implementations.Library
throw new ArgumentException("Key can't be empty.", nameof(key));
}
- var keys = key.Split(new[] { LiveStreamIdDelimeter }, 2);
+ var keys = key.Split(LiveStreamIdDelimeter, 2);
var provider = _providers.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture), keys[0], StringComparison.OrdinalIgnoreCase));
diff --git a/Emby.Server.Implementations/Library/MusicManager.cs b/Emby.Server.Implementations/Library/MusicManager.cs
index 877fdec86e..658c53f288 100644
--- a/Emby.Server.Implementations/Library/MusicManager.cs
+++ b/Emby.Server.Implementations/Library/MusicManager.cs
@@ -49,7 +49,7 @@ namespace Emby.Server.Implementations.Library
var genres = item
.GetRecursiveChildren(user, new InternalItemsQuery(user)
{
- IncludeItemTypes = new[] { typeof(Audio).Name },
+ IncludeItemTypes = new[] { nameof(Audio) },
DtoOptions = dtoOptions
})
.Cast
/// The collection id.
- /// Item ids, comma delimited.
+ /// Item ids, comma delimited.
/// Items added to collection.
/// A indicating success.
[HttpPost("{collectionId}/Items")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
- public async Task AddToCollection([FromRoute, Required] Guid collectionId, [FromQuery, Required] string itemIds)
+ public async Task AddToCollection([FromRoute, Required] Guid collectionId, [FromQuery, Required] string ids)
{
- await _collectionManager.AddToCollectionAsync(collectionId, RequestHelpers.GetGuids(itemIds)).ConfigureAwait(true);
+ await _collectionManager.AddToCollectionAsync(collectionId, RequestHelpers.GetGuids(ids)).ConfigureAwait(true);
return NoContent();
}
@@ -98,14 +98,14 @@ namespace Jellyfin.Api.Controllers
/// Removes items from a collection.
///
/// The collection id.
- /// Item ids, comma delimited.
+ /// Item ids, comma delimited.
/// Items removed from collection.
/// A indicating success.
[HttpDelete("{collectionId}/Items")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
- public async Task RemoveFromCollection([FromRoute, Required] Guid collectionId, [FromQuery, Required] string itemIds)
+ public async Task RemoveFromCollection([FromRoute, Required] Guid collectionId, [FromQuery, Required] string ids)
{
- await _collectionManager.RemoveFromCollectionAsync(collectionId, RequestHelpers.GetGuids(itemIds)).ConfigureAwait(false);
+ await _collectionManager.RemoveFromCollectionAsync(collectionId, RequestHelpers.GetGuids(ids)).ConfigureAwait(false);
return NoContent();
}
}
diff --git a/Jellyfin.Api/Controllers/DevicesController.cs b/Jellyfin.Api/Controllers/DevicesController.cs
index 74380c2eff..b3e3490c2a 100644
--- a/Jellyfin.Api/Controllers/DevicesController.cs
+++ b/Jellyfin.Api/Controllers/DevicesController.cs
@@ -15,7 +15,7 @@ namespace Jellyfin.Api.Controllers
///
/// Devices Controller.
///
- [Authorize(Policy = Policies.DefaultAuthorization)]
+ [Authorize(Policy = Policies.RequiresElevation)]
public class DevicesController : BaseJellyfinApiController
{
private readonly IDeviceManager _deviceManager;
@@ -46,7 +46,6 @@ namespace Jellyfin.Api.Controllers
/// Devices retrieved.
/// An containing the list of devices.
[HttpGet]
- [Authorize(Policy = Policies.RequiresElevation)]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult> GetDevices([FromQuery] bool? supportsSync, [FromQuery] Guid? userId)
{
@@ -62,7 +61,6 @@ namespace Jellyfin.Api.Controllers
/// Device not found.
/// An containing the device info on success, or a if the device could not be found.
[HttpGet("Info")]
- [Authorize(Policy = Policies.RequiresElevation)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult GetDeviceInfo([FromQuery, Required] string id)
@@ -84,7 +82,6 @@ namespace Jellyfin.Api.Controllers
/// Device not found.
/// An containing the device info on success, or a if the device could not be found.
[HttpGet("Options")]
- [Authorize(Policy = Policies.RequiresElevation)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult GetDeviceOptions([FromQuery, Required] string id)
@@ -107,7 +104,6 @@ namespace Jellyfin.Api.Controllers
/// Device not found.
/// A on success, or a if the device could not be found.
[HttpPost("Options")]
- [Authorize(Policy = Policies.RequiresElevation)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult UpdateDeviceOptions(
diff --git a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs
index 874467c75b..76f5717e30 100644
--- a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs
+++ b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs
@@ -81,6 +81,9 @@ namespace Jellyfin.Api.Controllers
dto.CustomPrefs["enableNextVideoInfoOverlay"] = displayPreferences.EnableNextVideoInfoOverlay.ToString(CultureInfo.InvariantCulture);
dto.CustomPrefs["tvhome"] = displayPreferences.TvHome;
+ // This will essentially be a noop if no changes have been made, but new prefs must be saved at least.
+ _displayPreferencesManager.SaveChanges();
+
return dto;
}
diff --git a/Jellyfin.Api/Controllers/DlnaServerController.cs b/Jellyfin.Api/Controllers/DlnaServerController.cs
index 271ae293b4..4e6455eaa7 100644
--- a/Jellyfin.Api/Controllers/DlnaServerController.cs
+++ b/Jellyfin.Api/Controllers/DlnaServerController.cs
@@ -77,6 +77,7 @@ namespace Jellyfin.Api.Controllers
/// Gets Dlna media receiver registrar xml.
///
/// Server UUID.
+ /// Dlna media receiver registrar xml returned.
/// Dlna media receiver registrar xml.
[HttpGet("{serverId}/MediaReceiverRegistrar")]
[HttpGet("{serverId}/MediaReceiverRegistrar/MediaReceiverRegistrar", Name = "GetMediaReceiverRegistrar_2")]
@@ -94,6 +95,7 @@ namespace Jellyfin.Api.Controllers
/// Gets Dlna media receiver registrar xml.
///
/// Server UUID.
+ /// Dlna media receiver registrar xml returned.
/// Dlna media receiver registrar xml.
[HttpGet("{serverId}/ConnectionManager")]
[HttpGet("{serverId}/ConnectionManager/ConnectionManager", Name = "GetConnectionManager_2")]
@@ -111,8 +113,12 @@ namespace Jellyfin.Api.Controllers
/// Process a content directory control request.
///
/// Server UUID.
+ /// Request processed.
/// Control response.
[HttpPost("{serverId}/ContentDirectory/Control")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Produces(MediaTypeNames.Text.Xml)]
+ [ProducesFile(MediaTypeNames.Text.Xml)]
public async Task> ProcessContentDirectoryControlRequest([FromRoute, Required] string serverId)
{
return await ProcessControlRequestInternalAsync(serverId, Request.Body, _contentDirectory).ConfigureAwait(false);
@@ -122,8 +128,12 @@ namespace Jellyfin.Api.Controllers
/// Process a connection manager control request.
///
/// Server UUID.
+ /// Request processed.
/// Control response.
[HttpPost("{serverId}/ConnectionManager/Control")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Produces(MediaTypeNames.Text.Xml)]
+ [ProducesFile(MediaTypeNames.Text.Xml)]
public async Task> ProcessConnectionManagerControlRequest([FromRoute, Required] string serverId)
{
return await ProcessControlRequestInternalAsync(serverId, Request.Body, _connectionManager).ConfigureAwait(false);
@@ -133,8 +143,12 @@ namespace Jellyfin.Api.Controllers
/// Process a media receiver registrar control request.
///
/// Server UUID.
+ /// Request processed.
/// Control response.
[HttpPost("{serverId}/MediaReceiverRegistrar/Control")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Produces(MediaTypeNames.Text.Xml)]
+ [ProducesFile(MediaTypeNames.Text.Xml)]
public async Task> ProcessMediaReceiverRegistrarControlRequest([FromRoute, Required] string serverId)
{
return await ProcessControlRequestInternalAsync(serverId, Request.Body, _mediaReceiverRegistrar).ConfigureAwait(false);
@@ -144,11 +158,15 @@ namespace Jellyfin.Api.Controllers
/// Processes an event subscription request.
///
/// Server UUID.
+ /// Request processed.
/// Event subscription response.
[HttpSubscribe("{serverId}/MediaReceiverRegistrar/Events")]
[HttpUnsubscribe("{serverId}/MediaReceiverRegistrar/Events")]
[ApiExplorerSettings(IgnoreApi = true)] // Ignore in openapi docs
[SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Produces(MediaTypeNames.Text.Xml)]
+ [ProducesFile(MediaTypeNames.Text.Xml)]
public ActionResult ProcessMediaReceiverRegistrarEventRequest(string serverId)
{
return ProcessEventRequest(_mediaReceiverRegistrar);
@@ -158,11 +176,15 @@ namespace Jellyfin.Api.Controllers
/// Processes an event subscription request.
///
/// Server UUID.
+ /// Request processed.
/// Event subscription response.
[HttpSubscribe("{serverId}/ContentDirectory/Events")]
[HttpUnsubscribe("{serverId}/ContentDirectory/Events")]
[ApiExplorerSettings(IgnoreApi = true)] // Ignore in openapi docs
[SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Produces(MediaTypeNames.Text.Xml)]
+ [ProducesFile(MediaTypeNames.Text.Xml)]
public ActionResult ProcessContentDirectoryEventRequest(string serverId)
{
return ProcessEventRequest(_contentDirectory);
@@ -172,11 +194,15 @@ namespace Jellyfin.Api.Controllers
/// Processes an event subscription request.
///
/// Server UUID.
+ /// Request processed.
/// Event subscription response.
[HttpSubscribe("{serverId}/ConnectionManager/Events")]
[HttpUnsubscribe("{serverId}/ConnectionManager/Events")]
[ApiExplorerSettings(IgnoreApi = true)] // Ignore in openapi docs
[SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [Produces(MediaTypeNames.Text.Xml)]
+ [ProducesFile(MediaTypeNames.Text.Xml)]
public ActionResult ProcessConnectionManagerEventRequest(string serverId)
{
return ProcessEventRequest(_connectionManager);
diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs
index 1153a601e7..6e59da798c 100644
--- a/Jellyfin.Api/Controllers/DynamicHlsController.cs
+++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs
@@ -14,6 +14,7 @@ using Jellyfin.Api.Helpers;
using Jellyfin.Api.Models.PlaybackDtos;
using Jellyfin.Api.Models.StreamingDtos;
using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Devices;
using MediaBrowser.Controller.Dlna;
@@ -295,6 +296,7 @@ namespace Jellyfin.Api.Controllers
/// Optional. Whether to break on non key frames.
/// Optional. Specify a specific audio sample rate, e.g. 44100.
/// Optional. The maximum audio bit depth.
+ /// Optional. The maximum streaming bitrate.
/// Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.
/// Optional. Specify a specific number of audio channels to encode to, e.g. 2.
/// Optional. Specify a maximum number of audio channels to encode to, e.g. 2.
@@ -351,6 +353,7 @@ namespace Jellyfin.Api.Controllers
[FromQuery] bool? breakOnNonKeyFrames,
[FromQuery] int? audioSampleRate,
[FromQuery] int? maxAudioBitDepth,
+ [FromQuery] int? maxStreamingBitrate,
[FromQuery] int? audioBitRate,
[FromQuery] int? audioChannels,
[FromQuery] int? maxAudioChannels,
@@ -403,7 +406,7 @@ namespace Jellyfin.Api.Controllers
BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
AudioSampleRate = audioSampleRate,
MaxAudioChannels = maxAudioChannels,
- AudioBitRate = audioBitRate,
+ AudioBitRate = audioBitRate ?? maxStreamingBitrate,
MaxAudioBitDepth = maxAudioBitDepth,
AudioChannels = audioChannels,
Profile = profile,
@@ -623,6 +626,7 @@ namespace Jellyfin.Api.Controllers
/// Optional. Whether to break on non key frames.
/// Optional. Specify a specific audio sample rate, e.g. 44100.
/// Optional. The maximum audio bit depth.
+ /// Optional. The maximum streaming bitrate.
/// Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.
/// Optional. Specify a specific number of audio channels to encode to, e.g. 2.
/// Optional. Specify a maximum number of audio channels to encode to, e.g. 2.
@@ -677,6 +681,7 @@ namespace Jellyfin.Api.Controllers
[FromQuery] bool? breakOnNonKeyFrames,
[FromQuery] int? audioSampleRate,
[FromQuery] int? maxAudioBitDepth,
+ [FromQuery] int? maxStreamingBitrate,
[FromQuery] int? audioBitRate,
[FromQuery] int? audioChannels,
[FromQuery] int? maxAudioChannels,
@@ -729,7 +734,7 @@ namespace Jellyfin.Api.Controllers
BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
AudioSampleRate = audioSampleRate,
MaxAudioChannels = maxAudioChannels,
- AudioBitRate = audioBitRate,
+ AudioBitRate = audioBitRate ?? maxStreamingBitrate,
MaxAudioBitDepth = maxAudioBitDepth,
AudioChannels = audioChannels,
Profile = profile,
@@ -959,6 +964,7 @@ namespace Jellyfin.Api.Controllers
/// Optional. Whether to break on non key frames.
/// Optional. Specify a specific audio sample rate, e.g. 44100.
/// Optional. The maximum audio bit depth.
+ /// Optional. The maximum streaming bitrate.
/// Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.
/// Optional. Specify a specific number of audio channels to encode to, e.g. 2.
/// Optional. Specify a maximum number of audio channels to encode to, e.g. 2.
@@ -1017,6 +1023,7 @@ namespace Jellyfin.Api.Controllers
[FromQuery] bool? breakOnNonKeyFrames,
[FromQuery] int? audioSampleRate,
[FromQuery] int? maxAudioBitDepth,
+ [FromQuery] int? maxStreamingBitrate,
[FromQuery] int? audioBitRate,
[FromQuery] int? audioChannels,
[FromQuery] int? maxAudioChannels,
@@ -1069,7 +1076,7 @@ namespace Jellyfin.Api.Controllers
BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
AudioSampleRate = audioSampleRate,
MaxAudioChannels = maxAudioChannels,
- AudioBitRate = audioBitRate,
+ AudioBitRate = audioBitRate ?? maxStreamingBitrate,
MaxAudioBitDepth = maxAudioBitDepth,
AudioChannels = audioChannels,
Profile = profile,
@@ -1341,7 +1348,9 @@ namespace Jellyfin.Api.Controllers
var mapArgs = state.IsOutputVideo ? _encodingHelper.GetMapArgs(state) : string.Empty;
- var outputTsArg = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state.Request.SegmentContainer);
+ var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
+
+ var outputTsArg = Path.Combine(directory, Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state.Request.SegmentContainer);
var segmentFormat = GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.');
if (string.Equals(segmentFormat, "ts", StringComparison.OrdinalIgnoreCase))
@@ -1559,8 +1568,7 @@ namespace Jellyfin.Api.Controllers
private string GetSegmentPath(StreamState state, string playlist, int index)
{
- var folder = Path.GetDirectoryName(playlist);
-
+ var folder = Path.GetDirectoryName(playlist) ?? throw new ArgumentException($"Provided path ({playlist}) is not valid.", nameof(playlist));
var filename = Path.GetFileNameWithoutExtension(playlist);
return Path.Combine(folder, filename + index.ToString(CultureInfo.InvariantCulture) + GetSegmentFileExtension(state.Request.SegmentContainer));
diff --git a/Jellyfin.Api/Controllers/EnvironmentController.cs b/Jellyfin.Api/Controllers/EnvironmentController.cs
index ce88b0b995..b0b4b5af51 100644
--- a/Jellyfin.Api/Controllers/EnvironmentController.cs
+++ b/Jellyfin.Api/Controllers/EnvironmentController.cs
@@ -5,6 +5,7 @@ using System.IO;
using System.Linq;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Models.EnvironmentDtos;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Model.IO;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
@@ -16,7 +17,7 @@ namespace Jellyfin.Api.Controllers
///
/// Environment Controller.
///
- [Authorize(Policy = Policies.RequiresElevation)]
+ [Authorize(Policy = Policies.FirstTimeSetupOrElevated)]
public class EnvironmentController : BaseJellyfinApiController
{
private const char UncSeparator = '\\';
@@ -103,6 +104,11 @@ namespace Jellyfin.Api.Controllers
if (validatePathDto.ValidateWritable)
{
+ if (validatePathDto.Path == null)
+ {
+ throw new ResourceNotFoundException(nameof(validatePathDto.Path));
+ }
+
var file = Path.Combine(validatePathDto.Path, Guid.NewGuid().ToString());
try
{
diff --git a/Jellyfin.Api/Controllers/FilterController.cs b/Jellyfin.Api/Controllers/FilterController.cs
index 2a567c8461..008bb58d16 100644
--- a/Jellyfin.Api/Controllers/FilterController.cs
+++ b/Jellyfin.Api/Controllers/FilterController.cs
@@ -78,8 +78,8 @@ namespace Jellyfin.Api.Controllers
var query = new InternalItemsQuery
{
User = user,
- MediaTypes = (mediaTypes ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries),
- IncludeItemTypes = (includeItemTypes ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries),
+ MediaTypes = (mediaTypes ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries),
+ IncludeItemTypes = (includeItemTypes ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries),
Recursive = true,
EnableTotalRecordCount = false,
DtoOptions = new DtoOptions
@@ -168,7 +168,7 @@ namespace Jellyfin.Api.Controllers
var genreQuery = new InternalItemsQuery(user)
{
IncludeItemTypes =
- (includeItemTypes ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries),
+ (includeItemTypes ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries),
DtoOptions = new DtoOptions
{
Fields = Array.Empty(),
diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs
index de6aa86c94..9c222135d0 100644
--- a/Jellyfin.Api/Controllers/GenresController.cs
+++ b/Jellyfin.Api/Controllers/GenresController.cs
@@ -1,15 +1,16 @@
using System;
using System.ComponentModel.DataAnnotations;
-using System.Globalization;
using System.Linq;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
@@ -47,30 +48,16 @@ namespace Jellyfin.Api.Controllers
///
/// Gets all genres from a given item, folder, or the entire library.
///
- /// Optional filter by minimum community rating.
/// Optional. The record index to start at. All items with a lower index will be dropped from the results.
/// Optional. The maximum number of records to return.
/// The search term.
/// Specify this to localize the search to a specific item or folder. Omit to use the root.
- /// 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.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited.
/// Optional. If specified, results will be filtered in based on item type. This allows multiple, comma delimited.
- /// Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.
/// Optional filter by items that are marked as favorite, or not.
- /// Optional filter by MediaType. Allows multiple, comma delimited.
- /// Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited.
- /// Optional, include user data.
/// Optional, the max number of images to return, per image type.
/// Optional. The image types to include in the output.
- /// Optional. If specified, results will be filtered to include only those containing the specified person.
- /// Optional. If specified, results will be filtered to include only those containing the specified person id.
- /// Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited.
- /// Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited.
/// User id.
/// Optional filter by items whose name is sorted equally or greater than a given input string.
/// Optional filter by items whose name is sorted equally than a given input string.
@@ -82,30 +69,16 @@ namespace Jellyfin.Api.Controllers
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult> GetGenres(
- [FromQuery] double? minCommunityRating,
[FromQuery] int? startIndex,
[FromQuery] int? limit,
[FromQuery] string? searchTerm,
[FromQuery] string? parentId,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] string? excludeItemTypes,
[FromQuery] string? includeItemTypes,
- [FromQuery] string? filters,
[FromQuery] bool? isFavorite,
- [FromQuery] string? mediaTypes,
- [FromQuery] string? genres,
- [FromQuery] string? genreIds,
- [FromQuery] string? officialRatings,
- [FromQuery] string? tags,
- [FromQuery] string? years,
- [FromQuery] bool? enableUserData,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes,
- [FromQuery] string? person,
- [FromQuery] string? personIds,
- [FromQuery] string? personTypes,
- [FromQuery] string? studios,
- [FromQuery] string? studioIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
[FromQuery] Guid? userId,
[FromQuery] string? nameStartsWithOrGreater,
[FromQuery] string? nameStartsWith,
@@ -113,45 +86,24 @@ namespace Jellyfin.Api.Controllers
[FromQuery] bool? enableImages = true,
[FromQuery] bool enableTotalRecordCount = true)
{
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
- .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+ .AddAdditionalDtoOptions(enableImages, false, imageTypeLimit, enableImageTypes);
- User? user = null;
- BaseItem parentItem;
+ User? user = userId.HasValue && userId != Guid.Empty ? _userManager.GetUserById(userId.Value) : null;
- if (userId.HasValue && !userId.Equals(Guid.Empty))
- {
- user = _userManager.GetUserById(userId.Value);
- parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(parentId);
- }
- else
- {
- parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.RootFolder : _libraryManager.GetItemById(parentId);
- }
+ var parentItem = _libraryManager.GetParentItem(parentId, userId);
var query = new InternalItemsQuery(user)
{
ExcludeItemTypes = RequestHelpers.Split(excludeItemTypes, ',', true),
IncludeItemTypes = RequestHelpers.Split(includeItemTypes, ',', true),
- MediaTypes = RequestHelpers.Split(mediaTypes, ',', true),
StartIndex = startIndex,
Limit = limit,
IsFavorite = isFavorite,
NameLessThan = nameLessThan,
NameStartsWith = nameStartsWith,
NameStartsWithOrGreater = nameStartsWithOrGreater,
- Tags = RequestHelpers.Split(tags, '|', true),
- OfficialRatings = RequestHelpers.Split(officialRatings, '|', true),
- Genres = RequestHelpers.Split(genres, '|', true),
- GenreIds = RequestHelpers.GetGuids(genreIds),
- StudioIds = RequestHelpers.GetGuids(studioIds),
- Person = person,
- PersonIds = RequestHelpers.GetGuids(personIds),
- PersonTypes = RequestHelpers.Split(personTypes, ',', true),
- Years = RequestHelpers.Split(years, ',', true).Select(y => Convert.ToInt32(y, CultureInfo.InvariantCulture)).ToArray(),
- MinCommunityRating = minCommunityRating,
DtoOptions = dtoOptions,
SearchTerm = searchTerm,
EnableTotalRecordCount = enableTotalRecordCount
@@ -169,87 +121,20 @@ namespace Jellyfin.Api.Controllers
}
}
- // Studios
- if (!string.IsNullOrEmpty(studios))
+ QueryResult<(BaseItem, ItemCounts)> result;
+ if (parentItem is ICollectionFolder parentCollectionFolder
+ && (string.Equals(parentCollectionFolder.CollectionType, CollectionType.Music, StringComparison.Ordinal)
+ || string.Equals(parentCollectionFolder.CollectionType, CollectionType.MusicVideos, StringComparison.Ordinal)))
{
- query.StudioIds = studios.Split('|')
- .Select(i =>
- {
- try
- {
- return _libraryManager.GetStudio(i);
- }
- catch
- {
- return null;
- }
- }).Where(i => i != null)
- .Select(i => i!.Id)
- .ToArray();
+ result = _libraryManager.GetMusicGenres(query);
+ }
+ else
+ {
+ result = _libraryManager.GetGenres(query);
}
- foreach (var filter in RequestHelpers.GetFilters(filters))
- {
- switch (filter)
- {
- case ItemFilter.Dislikes:
- query.IsLiked = false;
- break;
- case ItemFilter.IsFavorite:
- query.IsFavorite = true;
- break;
- case ItemFilter.IsFavoriteOrLikes:
- query.IsFavoriteOrLiked = true;
- break;
- case ItemFilter.IsFolder:
- query.IsFolder = true;
- break;
- case ItemFilter.IsNotFolder:
- query.IsFolder = false;
- break;
- case ItemFilter.IsPlayed:
- query.IsPlayed = true;
- break;
- case ItemFilter.IsResumable:
- query.IsResumable = true;
- break;
- case ItemFilter.IsUnplayed:
- query.IsPlayed = false;
- break;
- case ItemFilter.Likes:
- query.IsLiked = true;
- break;
- }
- }
-
- var result = new QueryResult<(BaseItem, ItemCounts)>();
-
- var dtos = result.Items.Select(i =>
- {
- var (baseItem, counts) = i;
- var dto = _dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user);
-
- if (!string.IsNullOrWhiteSpace(includeItemTypes))
- {
- dto.ChildCount = counts.ItemCount;
- dto.ProgramCount = counts.ProgramCount;
- dto.SeriesCount = counts.SeriesCount;
- dto.EpisodeCount = counts.EpisodeCount;
- dto.MovieCount = counts.MovieCount;
- dto.TrailerCount = counts.TrailerCount;
- dto.AlbumCount = counts.AlbumCount;
- dto.SongCount = counts.SongCount;
- dto.ArtistCount = counts.ArtistCount;
- }
-
- return dto;
- });
-
- return new QueryResult
- {
- Items = dtos.ToArray(),
- TotalRecordCount = result.TotalRecordCount
- };
+ var shouldIncludeItemTypes = !string.IsNullOrEmpty(includeItemTypes);
+ return RequestHelpers.CreateQueryResult(result, dtoOptions, _dtoService, shouldIncludeItemTypes, user);
}
///
@@ -291,7 +176,7 @@ namespace Jellyfin.Api.Controllers
return _dtoService.GetBaseItemDto(item, dtoOptions);
}
- private T GetItemFromSlugName(ILibraryManager libraryManager, string name, DtoOptions dtoOptions)
+ private T? GetItemFromSlugName(ILibraryManager libraryManager, string name, DtoOptions dtoOptions)
where T : BaseItem, new()
{
var result = libraryManager.GetItemList(new InternalItemsQuery
diff --git a/Jellyfin.Api/Controllers/HlsSegmentController.cs b/Jellyfin.Api/Controllers/HlsSegmentController.cs
index 054e586ce3..3b75e8d431 100644
--- a/Jellyfin.Api/Controllers/HlsSegmentController.cs
+++ b/Jellyfin.Api/Controllers/HlsSegmentController.cs
@@ -8,6 +8,7 @@ using Jellyfin.Api.Attributes;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Helpers;
using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Model.IO;
@@ -134,7 +135,8 @@ namespace Jellyfin.Api.Controllers
var playlistPath = _fileSystem.GetFilePaths(transcodeFolderPath)
.FirstOrDefault(i =>
string.Equals(Path.GetExtension(i), ".m3u8", StringComparison.OrdinalIgnoreCase)
- && i.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1);
+ && i.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1)
+ ?? throw new ResourceNotFoundException($"Provided path ({transcodeFolderPath}) is not valid.");
return GetFileResult(file, playlistPath);
}
diff --git a/Jellyfin.Api/Controllers/ImageByNameController.cs b/Jellyfin.Api/Controllers/ImageByNameController.cs
index 980c3273dd..198dbc51fc 100644
--- a/Jellyfin.Api/Controllers/ImageByNameController.cs
+++ b/Jellyfin.Api/Controllers/ImageByNameController.cs
@@ -161,7 +161,7 @@ namespace Jellyfin.Api.Controllers
/// Theme to search.
/// File name to search for.
/// A containing the image contents on success, or a if the image could not be found.
- private ActionResult GetImageFile(string basePath, string? theme, string? name)
+ private ActionResult GetImageFile(string basePath, string theme, string? name)
{
var themeFolder = Path.Combine(basePath, theme);
if (Directory.Exists(themeFolder))
diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs
index 7afec1219e..76e53b9a53 100644
--- a/Jellyfin.Api/Controllers/ImageController.cs
+++ b/Jellyfin.Api/Controllers/ImageController.cs
@@ -5,6 +5,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
+using System.Net.Mime;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Api.Attributes;
@@ -109,7 +110,7 @@ namespace Jellyfin.Api.Controllers
var userDataPath = Path.Combine(_serverConfigurationManager.ApplicationPaths.UserConfigurationDirectoryPath, user.Username);
if (user.ProfileImage != null)
{
- _userManager.ClearProfileImage(user);
+ await _userManager.ClearProfileImageAsync(user).ConfigureAwait(false);
}
user.ProfileImage = new Data.Entities.ImageInfo(Path.Combine(userDataPath, "profile" + MimeTypes.ToExtension(mimeType)));
@@ -138,7 +139,7 @@ namespace Jellyfin.Api.Controllers
[SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
- public ActionResult DeleteUserImage(
+ public async Task DeleteUserImage(
[FromRoute, Required] Guid userId,
[FromRoute, Required] ImageType imageType,
[FromRoute] int? index = null)
@@ -158,7 +159,7 @@ namespace Jellyfin.Api.Controllers
_logger.LogError(e, "Error deleting user profile image:");
}
- _userManager.ClearProfileImage(user);
+ await _userManager.ClearProfileImageAsync(user).ConfigureAwait(false);
return NoContent();
}
@@ -333,7 +334,7 @@ namespace Jellyfin.Api.Controllers
/// Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.
/// Optional. Supply the cache tag from the item object to receive strong caching headers.
/// Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.
- /// Determines the output format of the image - original,gif,jpg,png.
+ /// Optional. The of the returned image.
/// Optional. Add a played indicator.
/// Optional. Percent to render for the percent played overlay.
/// Optional. Unplayed count overlay to render.
@@ -364,7 +365,7 @@ namespace Jellyfin.Api.Controllers
[FromQuery] int? quality,
[FromQuery] string? tag,
[FromQuery] bool? cropWhitespace,
- [FromQuery] string? format,
+ [FromQuery] ImageFormat? format,
[FromQuery] bool? addPlayedIndicator,
[FromQuery] double? percentPlayed,
[FromQuery] int? unplayedCount,
@@ -443,7 +444,7 @@ namespace Jellyfin.Api.Controllers
[FromQuery] int? quality,
[FromRoute, Required] string tag,
[FromQuery] bool? cropWhitespace,
- [FromRoute, Required] string format,
+ [FromRoute, Required] ImageFormat format,
[FromQuery] bool? addPlayedIndicator,
[FromRoute, Required] double percentPlayed,
[FromRoute, Required] int unplayedCount,
@@ -516,7 +517,7 @@ namespace Jellyfin.Api.Controllers
[FromRoute, Required] string name,
[FromRoute, Required] ImageType imageType,
[FromQuery] string tag,
- [FromQuery] string format,
+ [FromQuery] ImageFormat? format,
[FromQuery] int? maxWidth,
[FromQuery] int? maxHeight,
[FromQuery] double? percentPlayed,
@@ -595,7 +596,7 @@ namespace Jellyfin.Api.Controllers
[FromRoute, Required] string name,
[FromRoute, Required] ImageType imageType,
[FromQuery] string tag,
- [FromQuery] string format,
+ [FromQuery] ImageFormat? format,
[FromQuery] int? maxWidth,
[FromQuery] int? maxHeight,
[FromQuery] double? percentPlayed,
@@ -674,7 +675,7 @@ namespace Jellyfin.Api.Controllers
[FromRoute, Required] string name,
[FromRoute, Required] ImageType imageType,
[FromQuery] string tag,
- [FromQuery] string format,
+ [FromQuery] ImageFormat? format,
[FromQuery] int? maxWidth,
[FromQuery] int? maxHeight,
[FromQuery] double? percentPlayed,
@@ -753,7 +754,7 @@ namespace Jellyfin.Api.Controllers
[FromRoute, Required] string name,
[FromRoute, Required] ImageType imageType,
[FromQuery] string tag,
- [FromQuery] string format,
+ [FromQuery] ImageFormat? format,
[FromQuery] int? maxWidth,
[FromQuery] int? maxHeight,
[FromQuery] double? percentPlayed,
@@ -832,7 +833,7 @@ namespace Jellyfin.Api.Controllers
[FromRoute, Required] string name,
[FromRoute, Required] ImageType imageType,
[FromRoute, Required] string tag,
- [FromRoute, Required] string format,
+ [FromRoute, Required] ImageFormat format,
[FromQuery] int? maxWidth,
[FromQuery] int? maxHeight,
[FromQuery] double? percentPlayed,
@@ -911,7 +912,7 @@ namespace Jellyfin.Api.Controllers
[FromRoute, Required] Guid userId,
[FromRoute, Required] ImageType imageType,
[FromQuery] string? tag,
- [FromQuery] string? format,
+ [FromQuery] ImageFormat? format,
[FromQuery] int? maxWidth,
[FromQuery] int? maxHeight,
[FromQuery] double? percentPlayed,
@@ -1038,7 +1039,7 @@ namespace Jellyfin.Api.Controllers
ImageType imageType,
int? imageIndex,
string? tag,
- string? format,
+ ImageFormat? format,
int? maxWidth,
int? maxHeight,
double? percentPlayed,
@@ -1128,12 +1129,11 @@ namespace Jellyfin.Api.Controllers
isHeadRequest).ConfigureAwait(false);
}
- private ImageFormat[] GetOutputFormats(string? format)
+ private ImageFormat[] GetOutputFormats(ImageFormat? format)
{
- if (!string.IsNullOrWhiteSpace(format)
- && Enum.TryParse(format, true, out ImageFormat parsedFormat))
+ if (format.HasValue)
{
- return new[] { parsedFormat };
+ return new[] { format.Value };
}
return GetClientSupportedFormats();
@@ -1157,7 +1157,7 @@ namespace Jellyfin.Api.Controllers
var acceptParam = Request.Query[HeaderNames.Accept];
- var supportsWebP = SupportsFormat(supportedFormats, acceptParam, "webp", false);
+ var supportsWebP = SupportsFormat(supportedFormats, acceptParam, ImageFormat.Webp, false);
if (!supportsWebP)
{
@@ -1179,7 +1179,7 @@ namespace Jellyfin.Api.Controllers
formats.Add(ImageFormat.Jpg);
formats.Add(ImageFormat.Png);
- if (SupportsFormat(supportedFormats, acceptParam, "gif", true))
+ if (SupportsFormat(supportedFormats, acceptParam, ImageFormat.Gif, true))
{
formats.Add(ImageFormat.Gif);
}
@@ -1187,9 +1187,10 @@ namespace Jellyfin.Api.Controllers
return formats.ToArray();
}
- private bool SupportsFormat(IReadOnlyCollection requestAcceptTypes, string acceptParam, string format, bool acceptAll)
+ private bool SupportsFormat(IReadOnlyCollection requestAcceptTypes, string acceptParam, ImageFormat format, bool acceptAll)
{
- var mimeType = "image/" + format;
+ var normalized = format.ToString().ToLowerInvariant();
+ var mimeType = "image/" + normalized;
if (requestAcceptTypes.Contains(mimeType))
{
@@ -1201,7 +1202,7 @@ namespace Jellyfin.Api.Controllers
return true;
}
- return string.Equals(acceptParam, format, StringComparison.OrdinalIgnoreCase);
+ return string.Equals(acceptParam, normalized, StringComparison.OrdinalIgnoreCase);
}
private async Task GetImageResult(
@@ -1268,7 +1269,7 @@ namespace Jellyfin.Api.Controllers
Response.Headers.Add(key, value);
}
- Response.ContentType = imageContentType;
+ Response.ContentType = imageContentType ?? MediaTypeNames.Text.Plain;
Response.Headers.Add(HeaderNames.Age, Convert.ToInt64((DateTime.UtcNow - dateImageModified).TotalSeconds).ToString(CultureInfo.InvariantCulture));
Response.Headers.Add(HeaderNames.Vary, HeaderNames.Accept);
diff --git a/Jellyfin.Api/Controllers/InstantMixController.cs b/Jellyfin.Api/Controllers/InstantMixController.cs
index 07fed97642..d17a26db43 100644
--- a/Jellyfin.Api/Controllers/InstantMixController.cs
+++ b/Jellyfin.Api/Controllers/InstantMixController.cs
@@ -4,12 +4,14 @@ using System.ComponentModel.DataAnnotations;
using System.Linq;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
+using Jellyfin.Api.ModelBinders;
using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
@@ -54,7 +56,7 @@ namespace Jellyfin.Api.Controllers
/// The item id.
/// Optional. Filter by user id, and attach user data.
/// Optional. The maximum number of records to return.
- /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. Include image information in output.
/// Optional. Include user data.
/// Optional. The max number of images to return, per image type.
@@ -67,18 +69,17 @@ namespace Jellyfin.Api.Controllers
[FromRoute, Required] Guid id,
[FromQuery] Guid? userId,
[FromQuery] int? limit,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] bool? enableImages,
[FromQuery] bool? enableUserData,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes)
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
{
var item = _libraryManager.GetItemById(id);
var user = userId.HasValue && !userId.Equals(Guid.Empty)
? _userManager.GetUserById(userId.Value)
: null;
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!);
var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions);
@@ -91,7 +92,7 @@ namespace Jellyfin.Api.Controllers
/// The item id.
/// Optional. Filter by user id, and attach user data.
/// Optional. The maximum number of records to return.
- /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. Include image information in output.
/// Optional. Include user data.
/// Optional. The max number of images to return, per image type.
@@ -104,18 +105,17 @@ namespace Jellyfin.Api.Controllers
[FromRoute, Required] Guid id,
[FromQuery] Guid? userId,
[FromQuery] int? limit,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] bool? enableImages,
[FromQuery] bool? enableUserData,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes)
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
{
var album = _libraryManager.GetItemById(id);
var user = userId.HasValue && !userId.Equals(Guid.Empty)
? _userManager.GetUserById(userId.Value)
: null;
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!);
var items = _musicManager.GetInstantMixFromItem(album, user, dtoOptions);
@@ -128,7 +128,7 @@ namespace Jellyfin.Api.Controllers
/// The item id.
/// Optional. Filter by user id, and attach user data.
/// Optional. The maximum number of records to return.
- /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. Include image information in output.
/// Optional. Include user data.
/// Optional. The max number of images to return, per image type.
@@ -141,18 +141,17 @@ namespace Jellyfin.Api.Controllers
[FromRoute, Required] Guid id,
[FromQuery] Guid? userId,
[FromQuery] int? limit,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] bool? enableImages,
[FromQuery] bool? enableUserData,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes)
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
{
var playlist = (Playlist)_libraryManager.GetItemById(id);
var user = userId.HasValue && !userId.Equals(Guid.Empty)
? _userManager.GetUserById(userId.Value)
: null;
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!);
var items = _musicManager.GetInstantMixFromItem(playlist, user, dtoOptions);
@@ -165,7 +164,7 @@ namespace Jellyfin.Api.Controllers
/// The genre name.
/// Optional. Filter by user id, and attach user data.
/// Optional. The maximum number of records to return.
- /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. Include image information in output.
/// Optional. Include user data.
/// Optional. The max number of images to return, per image type.
@@ -178,17 +177,16 @@ namespace Jellyfin.Api.Controllers
[FromRoute, Required] string name,
[FromQuery] Guid? userId,
[FromQuery] int? limit,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] bool? enableImages,
[FromQuery] bool? enableUserData,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes)
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
{
var user = userId.HasValue && !userId.Equals(Guid.Empty)
? _userManager.GetUserById(userId.Value)
: null;
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!);
var items = _musicManager.GetInstantMixFromGenres(new[] { name }, user, dtoOptions);
@@ -201,7 +199,7 @@ namespace Jellyfin.Api.Controllers
/// The item id.
/// Optional. Filter by user id, and attach user data.
/// Optional. The maximum number of records to return.
- /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. Include image information in output.
/// Optional. Include user data.
/// Optional. The max number of images to return, per image type.
@@ -214,18 +212,17 @@ namespace Jellyfin.Api.Controllers
[FromRoute, Required] Guid id,
[FromQuery] Guid? userId,
[FromQuery] int? limit,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] bool? enableImages,
[FromQuery] bool? enableUserData,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes)
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
{
var item = _libraryManager.GetItemById(id);
var user = userId.HasValue && !userId.Equals(Guid.Empty)
? _userManager.GetUserById(userId.Value)
: null;
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!);
var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions);
@@ -238,7 +235,7 @@ namespace Jellyfin.Api.Controllers
/// The item id.
/// Optional. Filter by user id, and attach user data.
/// Optional. The maximum number of records to return.
- /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. Include image information in output.
/// Optional. Include user data.
/// Optional. The max number of images to return, per image type.
@@ -251,18 +248,17 @@ namespace Jellyfin.Api.Controllers
[FromRoute, Required] Guid id,
[FromQuery] Guid? userId,
[FromQuery] int? limit,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] bool? enableImages,
[FromQuery] bool? enableUserData,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes)
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
{
var item = _libraryManager.GetItemById(id);
var user = userId.HasValue && !userId.Equals(Guid.Empty)
? _userManager.GetUserById(userId.Value)
: null;
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!);
var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions);
@@ -275,7 +271,7 @@ namespace Jellyfin.Api.Controllers
/// The item id.
/// Optional. Filter by user id, and attach user data.
/// Optional. The maximum number of records to return.
- /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. Include image information in output.
/// Optional. Include user data.
/// Optional. The max number of images to return, per image type.
@@ -288,18 +284,17 @@ namespace Jellyfin.Api.Controllers
[FromRoute, Required] Guid id,
[FromQuery] Guid? userId,
[FromQuery] int? limit,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] bool? enableImages,
[FromQuery] bool? enableUserData,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes)
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
{
var item = _libraryManager.GetItemById(id);
var user = userId.HasValue && !userId.Equals(Guid.Empty)
? _userManager.GetUserById(userId.Value)
: null;
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!);
var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions);
@@ -315,9 +310,9 @@ namespace Jellyfin.Api.Controllers
TotalRecordCount = list.Count
};
- if (limit.HasValue)
+ if (limit.HasValue && limit < list.Count)
{
- list = list.Take(limit.Value).ToList();
+ list = list.GetRange(0, limit.Value);
}
var returnList = _dtoService.GetBaseItemDtos(list, dtoOptions, user);
diff --git a/Jellyfin.Api/Controllers/ItemLookupController.cs b/Jellyfin.Api/Controllers/ItemLookupController.cs
index ab73aa4286..a7c1a63882 100644
--- a/Jellyfin.Api/Controllers/ItemLookupController.cs
+++ b/Jellyfin.Api/Controllers/ItemLookupController.cs
@@ -334,10 +334,16 @@ namespace Jellyfin.Api.Controllers
private async Task DownloadImage(string providerName, string url, Guid urlHash, string pointerCachePath)
{
using var result = await _providerManager.GetSearchImage(providerName, url, CancellationToken.None).ConfigureAwait(false);
+ if (result.Content.Headers.ContentType?.MediaType == null)
+ {
+ throw new ResourceNotFoundException(nameof(result.Content.Headers.ContentType));
+ }
+
var ext = result.Content.Headers.ContentType.MediaType.Split('/')[^1];
var fullCachePath = GetFullCachePath(urlHash + "." + ext);
- Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath));
+ var directory = Path.GetDirectoryName(fullCachePath) ?? throw new ResourceNotFoundException($"Provided path ({fullCachePath}) is not valid.");
+ Directory.CreateDirectory(directory);
using (var stream = result.Content)
{
await using var fileStream = new FileStream(
@@ -351,7 +357,9 @@ namespace Jellyfin.Api.Controllers
await stream.CopyToAsync(fileStream).ConfigureAwait(false);
}
- Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath));
+ var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath) ?? throw new ArgumentException($"Provided path ({pointerCachePath}) is not valid.", nameof(pointerCachePath));
+
+ Directory.CreateDirectory(pointerCacheDirectory);
await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath).ConfigureAwait(false);
}
diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs
index 652c4689d0..d8d371ebc3 100644
--- a/Jellyfin.Api/Controllers/ItemsController.cs
+++ b/Jellyfin.Api/Controllers/ItemsController.cs
@@ -5,6 +5,7 @@ using System.Linq;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
@@ -159,7 +160,7 @@ namespace Jellyfin.Api.Controllers
[FromQuery] bool? isHd,
[FromQuery] bool? is4K,
[FromQuery] string? locationTypes,
- [FromQuery] string? excludeLocationTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] excludeLocationTypes,
[FromQuery] bool? isMissing,
[FromQuery] bool? isUnaired,
[FromQuery] double? minCommunityRating,
@@ -179,13 +180,13 @@ namespace Jellyfin.Api.Controllers
[FromQuery] string? searchTerm,
[FromQuery] string? sortOrder,
[FromQuery] string? parentId,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] string? excludeItemTypes,
[FromQuery] string? includeItemTypes,
- [FromQuery] string? filters,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters,
[FromQuery] bool? isFavorite,
[FromQuery] string? mediaTypes,
- [FromQuery] string? imageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes,
[FromQuery] string? sortBy,
[FromQuery] bool? isPlayed,
[FromQuery] string? genres,
@@ -194,7 +195,7 @@ namespace Jellyfin.Api.Controllers
[FromQuery] string? years,
[FromQuery] bool? enableUserData,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
[FromQuery] string? person,
[FromQuery] string? personIds,
[FromQuery] string? personTypes,
@@ -233,8 +234,7 @@ namespace Jellyfin.Api.Controllers
var user = userId.HasValue && !userId.Equals(Guid.Empty)
? _userManager.GetUserById(userId.Value)
: null;
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
@@ -342,7 +342,7 @@ namespace Jellyfin.Api.Controllers
PersonIds = RequestHelpers.GetGuids(personIds),
PersonTypes = RequestHelpers.Split(personTypes, ',', true),
Years = RequestHelpers.Split(years, ',', true).Select(int.Parse).ToArray(),
- ImageTypes = RequestHelpers.Split(imageTypes, ',', true).Select(v => Enum.Parse(v, true)).ToArray(),
+ ImageTypes = imageTypes,
VideoTypes = RequestHelpers.Split(videoTypes, ',', true).Select(v => Enum.Parse(v, true)).ToArray(),
AdjacentTo = adjacentTo,
ItemIds = RequestHelpers.GetGuids(ids),
@@ -365,7 +365,7 @@ namespace Jellyfin.Api.Controllers
query.CollapseBoxSetItems = false;
}
- foreach (var filter in RequestHelpers.GetFilters(filters!))
+ foreach (var filter in filters)
{
switch (filter)
{
@@ -406,12 +406,9 @@ namespace Jellyfin.Api.Controllers
}
// ExcludeLocationTypes
- if (!string.IsNullOrEmpty(excludeLocationTypes))
+ if (excludeLocationTypes.Any(t => t == LocationType.Virtual))
{
- if (excludeLocationTypes.Split(',').Select(d => (LocationType)Enum.Parse(typeof(LocationType), d, true)).ToArray().Contains(LocationType.Virtual))
- {
- query.IsVirtualItem = false;
- }
+ query.IsVirtualItem = false;
}
if (!string.IsNullOrEmpty(locationTypes))
@@ -535,11 +532,11 @@ namespace Jellyfin.Api.Controllers
[FromQuery] int? limit,
[FromQuery] string? searchTerm,
[FromQuery] string? parentId,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] string? mediaTypes,
[FromQuery] bool? enableUserData,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
[FromQuery] string? excludeItemTypes,
[FromQuery] string? includeItemTypes,
[FromQuery] bool enableTotalRecordCount = true,
@@ -547,8 +544,7 @@ namespace Jellyfin.Api.Controllers
{
var user = _userManager.GetUserById(userId);
var parentIdGuid = string.IsNullOrWhiteSpace(parentId) ? Guid.Empty : new Guid(parentId);
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs
index 8a872ae133..1b115d800b 100644
--- a/Jellyfin.Api/Controllers/LibraryController.cs
+++ b/Jellyfin.Api/Controllers/LibraryController.cs
@@ -12,6 +12,7 @@ using Jellyfin.Api.Attributes;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
using Jellyfin.Api.Models.LibraryDtos;
using Jellyfin.Data.Entities;
using MediaBrowser.Common.Progress;
@@ -455,7 +456,7 @@ namespace Jellyfin.Api.Controllers
: null;
var dtoOptions = new DtoOptions().AddClientFields(Request);
- BaseItem parent = item.GetParent();
+ BaseItem? parent = item.GetParent();
while (parent != null)
{
@@ -466,7 +467,7 @@ namespace Jellyfin.Api.Controllers
baseItemDtos.Add(_dtoService.GetBaseItemDto(parent, dtoOptions, user));
- parent = parent.GetParent();
+ parent = parent?.GetParent();
}
return baseItemDtos;
@@ -680,12 +681,12 @@ namespace Jellyfin.Api.Controllers
/// 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, TrailerUrls.
/// Similar items returned.
/// A containing the similar items.
- [HttpGet("Artists/{itemId}/Similar", Name = "GetSimilarArtists2")]
+ [HttpGet("Artists/{itemId}/Similar", Name = "GetSimilarArtists")]
[HttpGet("Items/{itemId}/Similar")]
- [HttpGet("Albums/{itemId}/Similar", Name = "GetSimilarAlbums2")]
- [HttpGet("Shows/{itemId}/Similar", Name = "GetSimilarShows2")]
- [HttpGet("Movies/{itemId}/Similar", Name = "GetSimilarMovies2")]
- [HttpGet("Trailers/{itemId}/Similar", Name = "GetSimilarTrailers2")]
+ [HttpGet("Albums/{itemId}/Similar", Name = "GetSimilarAlbums")]
+ [HttpGet("Shows/{itemId}/Similar", Name = "GetSimilarShows")]
+ [HttpGet("Movies/{itemId}/Similar", Name = "GetSimilarMovies")]
+ [HttpGet("Trailers/{itemId}/Similar", Name = "GetSimilarTrailers")]
[Authorize(Policy = Policies.DefaultAuthorization)]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult> GetSimilarItems(
@@ -693,7 +694,7 @@ namespace Jellyfin.Api.Controllers
[FromQuery] string? excludeArtistIds,
[FromQuery] Guid? userId,
[FromQuery] int? limit,
- [FromQuery] string? fields)
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields)
{
var item = itemId.Equals(Guid.Empty)
? (!userId.Equals(Guid.Empty)
@@ -701,33 +702,71 @@ namespace Jellyfin.Api.Controllers
: _libraryManager.RootFolder)
: _libraryManager.GetItemById(itemId);
- var program = item as IHasProgramAttributes;
- var isMovie = item is MediaBrowser.Controller.Entities.Movies.Movie || (program != null && program.IsMovie) || item is Trailer;
- if (program != null && program.IsSeries)
- {
- return GetSimilarItemsResult(
- item,
- excludeArtistIds,
- userId,
- limit,
- fields,
- new[] { nameof(Series) },
- false);
- }
-
- if (item is MediaBrowser.Controller.Entities.TV.Episode || (item is IItemByName && !(item is MusicArtist)))
+ if (item is Episode || (item is IItemByName && !(item is MusicArtist)))
{
return new QueryResult();
}
- return GetSimilarItemsResult(
- item,
- excludeArtistIds,
- userId,
- limit,
- fields,
- new[] { item.GetType().Name },
- isMovie);
+ var user = userId.HasValue && !userId.Equals(Guid.Empty)
+ ? _userManager.GetUserById(userId.Value)
+ : null;
+ var dtoOptions = new DtoOptions { Fields = fields }
+ .AddClientFields(Request);
+
+ var program = item as IHasProgramAttributes;
+ bool? isMovie = item is Movie || (program != null && program.IsMovie) || item is Trailer;
+ bool? isSeries = item is Series || (program != null && program.IsSeries);
+
+ var includeItemTypes = new List();
+ if (isMovie.Value)
+ {
+ includeItemTypes.Add(nameof(Movie));
+ if (_serverConfigurationManager.Configuration.EnableExternalContentInSuggestions)
+ {
+ includeItemTypes.Add(nameof(Trailer));
+ includeItemTypes.Add(nameof(LiveTvProgram));
+ }
+ }
+ else if (isSeries.Value)
+ {
+ includeItemTypes.Add(nameof(Series));
+ }
+ else
+ {
+ // For non series and movie types these columns are typically null
+ isSeries = null;
+ isMovie = null;
+ includeItemTypes.Add(item.GetType().Name);
+ }
+
+ var query = new InternalItemsQuery(user)
+ {
+ Limit = limit,
+ IncludeItemTypes = includeItemTypes.ToArray(),
+ IsMovie = isMovie,
+ IsSeries = isSeries,
+ SimilarTo = item,
+ DtoOptions = dtoOptions,
+ EnableTotalRecordCount = !isMovie ?? true,
+ EnableGroupByMetadataKey = isMovie ?? false,
+ MinSimilarityScore = 2 // A remnant from album/artist scoring
+ };
+
+ // ExcludeArtistIds
+ if (!string.IsNullOrEmpty(excludeArtistIds))
+ {
+ query.ExcludeArtistIds = RequestHelpers.GetGuids(excludeArtistIds);
+ }
+
+ List itemsResult = _libraryManager.GetItemList(query);
+
+ var returnList = _dtoService.GetBaseItemDtos(itemsResult, dtoOptions, user);
+
+ return new QueryResult
+ {
+ Items = returnList,
+ TotalRecordCount = itemsResult.Count
+ };
}
///
@@ -854,7 +893,7 @@ namespace Jellyfin.Api.Controllers
return _libraryManager.GetItemsResult(query).TotalRecordCount;
}
- private BaseItem TranslateParentItem(BaseItem item, User user)
+ private BaseItem? TranslateParentItem(BaseItem item, User user)
{
return item.GetParent() is AggregateFolder
? _libraryManager.GetUserRootFolder().GetChildren(user, true)
@@ -880,75 +919,6 @@ namespace Jellyfin.Api.Controllers
}
}
- private QueryResult GetSimilarItemsResult(
- BaseItem item,
- string? excludeArtistIds,
- Guid? userId,
- int? limit,
- string? fields,
- string[] includeItemTypes,
- bool isMovie)
- {
- var user = userId.HasValue && !userId.Equals(Guid.Empty)
- ? _userManager.GetUserById(userId.Value)
- : null;
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
- .AddClientFields(Request);
-
- var query = new InternalItemsQuery(user)
- {
- Limit = limit,
- IncludeItemTypes = includeItemTypes,
- IsMovie = isMovie,
- SimilarTo = item,
- DtoOptions = dtoOptions,
- EnableTotalRecordCount = !isMovie,
- EnableGroupByMetadataKey = isMovie
- };
-
- // ExcludeArtistIds
- if (!string.IsNullOrEmpty(excludeArtistIds))
- {
- query.ExcludeArtistIds = RequestHelpers.GetGuids(excludeArtistIds);
- }
-
- List itemsResult;
-
- if (isMovie)
- {
- var itemTypes = new List { nameof(MediaBrowser.Controller.Entities.Movies.Movie) };
- if (_serverConfigurationManager.Configuration.EnableExternalContentInSuggestions)
- {
- itemTypes.Add(nameof(Trailer));
- itemTypes.Add(nameof(LiveTvProgram));
- }
-
- query.IncludeItemTypes = itemTypes.ToArray();
- itemsResult = _libraryManager.GetArtists(query).Items.Select(i => i.Item1).ToList();
- }
- else if (item is MusicArtist)
- {
- query.IncludeItemTypes = Array.Empty();
-
- itemsResult = _libraryManager.GetArtists(query).Items.Select(i => i.Item1).ToList();
- }
- else
- {
- itemsResult = _libraryManager.GetItemList(query);
- }
-
- var returnList = _dtoService.GetBaseItemDtos(itemsResult, dtoOptions, user);
-
- var result = new QueryResult
- {
- Items = returnList,
- TotalRecordCount = itemsResult.Count
- };
-
- return result;
- }
-
private static string[] GetRepresentativeItemTypes(string? contentType)
{
return contentType switch
diff --git a/Jellyfin.Api/Controllers/LibraryStructureController.cs b/Jellyfin.Api/Controllers/LibraryStructureController.cs
index d290e3c5bd..94995650cb 100644
--- a/Jellyfin.Api/Controllers/LibraryStructureController.cs
+++ b/Jellyfin.Api/Controllers/LibraryStructureController.cs
@@ -7,6 +7,7 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Api.Constants;
+using Jellyfin.Api.ModelBinders;
using Jellyfin.Api.Models.LibraryStructureDto;
using MediaBrowser.Common.Progress;
using MediaBrowser.Controller;
@@ -75,7 +76,7 @@ namespace Jellyfin.Api.Controllers
public async Task AddVirtualFolder(
[FromQuery] string? name,
[FromQuery] string? collectionType,
- [FromQuery] string[] paths,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] paths,
[FromBody] AddVirtualFolderDto? libraryOptionsDto,
[FromQuery] bool refreshLibrary = false)
{
diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs
index 3557e63047..29c0f1df4d 100644
--- a/Jellyfin.Api/Controllers/LiveTvController.cs
+++ b/Jellyfin.Api/Controllers/LiveTvController.cs
@@ -14,6 +14,7 @@ using Jellyfin.Api.Attributes;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
using Jellyfin.Api.Models.LiveTvDtos;
using Jellyfin.Data.Enums;
using MediaBrowser.Common;
@@ -26,6 +27,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Querying;
@@ -117,7 +119,7 @@ namespace Jellyfin.Api.Controllers
/// Optional. Include image information in output.
/// Optional. The max number of images to return, per image type.
/// "Optional. The image types to include in the output.
- /// 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.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. Include user data.
/// Optional. Key to sort by.
/// Optional. Sort order.
@@ -145,16 +147,15 @@ namespace Jellyfin.Api.Controllers
[FromQuery] bool? isDisliked,
[FromQuery] bool? enableImages,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] bool? enableUserData,
[FromQuery] string? sortBy,
[FromQuery] SortOrder? sortOrder,
[FromQuery] bool enableFavoriteSorting = false,
[FromQuery] bool addCurrentProgram = true)
{
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
@@ -238,7 +239,7 @@ namespace Jellyfin.Api.Controllers
/// Optional. Include image information in output.
/// Optional. The max number of images to return, per image type.
/// Optional. The image types to include in the output.
- /// 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.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. Include user data.
/// Optional. Filter for movies.
/// Optional. Filter for series.
@@ -262,8 +263,8 @@ namespace Jellyfin.Api.Controllers
[FromQuery] string? seriesTimerId,
[FromQuery] bool? enableImages,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] bool? enableUserData,
[FromQuery] bool? isMovie,
[FromQuery] bool? isSeries,
@@ -273,8 +274,7 @@ namespace Jellyfin.Api.Controllers
[FromQuery] bool? isLibraryItem,
[FromQuery] bool enableTotalRecordCount = true)
{
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
@@ -295,7 +295,7 @@ namespace Jellyfin.Api.Controllers
IsKids = isKids,
IsSports = isSports,
IsLibraryItem = isLibraryItem,
- Fields = RequestHelpers.GetItemFields(fields),
+ Fields = fields,
ImageTypeLimit = imageTypeLimit,
EnableImages = enableImages
}, dtoOptions);
@@ -315,7 +315,7 @@ namespace Jellyfin.Api.Controllers
/// Optional. Include image information in output.
/// Optional. The max number of images to return, per image type.
/// Optional. The image types to include in the output.
- /// 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.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. Include user data.
/// Optional. Return total record count.
/// Live tv recordings returned.
@@ -349,8 +349,8 @@ namespace Jellyfin.Api.Controllers
[FromQuery] string? seriesTimerId,
[FromQuery] bool? enableImages,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] bool? enableUserData,
[FromQuery] bool enableTotalRecordCount = true)
{
@@ -529,7 +529,7 @@ namespace Jellyfin.Api.Controllers
/// Optional. Include user data.
/// Optional. Filter by series timer id.
/// Optional. Filter by library series id.
- /// 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.
+ /// Optional. Specify additional fields of information to return in the output.
/// Retrieve total record count.
/// Live tv epgs returned.
///
@@ -560,11 +560,11 @@ namespace Jellyfin.Api.Controllers
[FromQuery] string? genreIds,
[FromQuery] bool? enableImages,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
[FromQuery] bool? enableUserData,
[FromQuery] string? seriesTimerId,
[FromQuery] Guid? librarySeriesId,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] bool enableTotalRecordCount = true)
{
var user = userId.HasValue && !userId.Equals(Guid.Empty)
@@ -591,7 +591,7 @@ namespace Jellyfin.Api.Controllers
IsKids = isKids,
IsSports = isSports,
SeriesTimerId = seriesTimerId,
- Genres = RequestHelpers.Split(genres, ',', true),
+ Genres = RequestHelpers.Split(genres, '|', true),
GenreIds = RequestHelpers.GetGuids(genreIds)
};
@@ -605,8 +605,7 @@ namespace Jellyfin.Api.Controllers
}
}
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
return await _liveTvManager.GetPrograms(query, dtoOptions, CancellationToken.None).ConfigureAwait(false);
@@ -647,7 +646,7 @@ namespace Jellyfin.Api.Controllers
IsKids = body.IsKids,
IsSports = body.IsSports,
SeriesTimerId = body.SeriesTimerId,
- Genres = RequestHelpers.Split(body.Genres, ',', true),
+ Genres = RequestHelpers.Split(body.Genres, '|', true),
GenreIds = RequestHelpers.GetGuids(body.GenreIds)
};
@@ -661,8 +660,7 @@ namespace Jellyfin.Api.Controllers
}
}
- var dtoOptions = new DtoOptions()
- .AddItemFields(body.Fields)
+ var dtoOptions = new DtoOptions { Fields = body.Fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(body.EnableImages, body.EnableUserData, body.ImageTypeLimit, body.EnableImageTypes);
return await _liveTvManager.GetPrograms(query, dtoOptions, CancellationToken.None).ConfigureAwait(false);
@@ -684,7 +682,7 @@ namespace Jellyfin.Api.Controllers
/// Optional. The max number of images to return, per image type.
/// Optional. The image types to include in the output.
/// The genres to return guide information for.
- /// 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.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. include user data.
/// Retrieve total record count.
/// Recommended epgs returned.
@@ -704,9 +702,9 @@ namespace Jellyfin.Api.Controllers
[FromQuery] bool? isSports,
[FromQuery] bool? enableImages,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
[FromQuery] string? genreIds,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] bool? enableUserData,
[FromQuery] bool enableTotalRecordCount = true)
{
@@ -728,8 +726,7 @@ namespace Jellyfin.Api.Controllers
GenreIds = RequestHelpers.GetGuids(genreIds)
};
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
return _liveTvManager.GetRecommendedPrograms(query, dtoOptions, CancellationToken.None);
@@ -1076,7 +1073,7 @@ namespace Jellyfin.Api.Controllers
var client = _httpClientFactory.CreateClient(NamedClient.Default);
// https://json.schedulesdirect.org/20141201/available/countries
// Can't dispose the response as it's required up the call chain.
- var response = await client.GetAsync("https://json.schedulesdirect.org/20141201/available/countries")
+ var response = await client.GetAsync(new Uri("https://json.schedulesdirect.org/20141201/available/countries"))
.ConfigureAwait(false);
return File(await response.Content.ReadAsStreamAsync().ConfigureAwait(false), MediaTypeNames.Application.Json);
@@ -1219,11 +1216,8 @@ namespace Jellyfin.Api.Controllers
return NotFound();
}
- await using var memoryStream = new MemoryStream();
- await new ProgressiveFileCopier(liveStreamInfo, null, _transcodingJobHelper, CancellationToken.None)
- .WriteToAsync(memoryStream, CancellationToken.None)
- .ConfigureAwait(false);
- return File(memoryStream, MimeTypes.GetMimeType("file." + container));
+ var liveStream = new ProgressiveFileStream(liveStreamInfo.GetFilePath(), null, _transcodingJobHelper);
+ return new FileStreamResult(liveStream, MimeTypes.GetMimeType("file." + container));
}
private void AssertUserCanManageLiveTv()
diff --git a/Jellyfin.Api/Controllers/MediaInfoController.cs b/Jellyfin.Api/Controllers/MediaInfoController.cs
index 4c21999b1b..186024585b 100644
--- a/Jellyfin.Api/Controllers/MediaInfoController.cs
+++ b/Jellyfin.Api/Controllers/MediaInfoController.cs
@@ -104,7 +104,7 @@ namespace Jellyfin.Api.Controllers
public async Task> GetPostedPlaybackInfo(
[FromRoute, Required] Guid itemId,
[FromQuery] Guid? userId,
- [FromQuery] long? maxStreamingBitrate,
+ [FromQuery] int? maxStreamingBitrate,
[FromQuery] long? startTimeTicks,
[FromQuery] int? audioStreamIndex,
[FromQuery] int? subtitleStreamIndex,
@@ -234,7 +234,7 @@ namespace Jellyfin.Api.Controllers
[FromQuery] string? openToken,
[FromQuery] Guid? userId,
[FromQuery] string? playSessionId,
- [FromQuery] long? maxStreamingBitrate,
+ [FromQuery] int? maxStreamingBitrate,
[FromQuery] long? startTimeTicks,
[FromQuery] int? audioStreamIndex,
[FromQuery] int? subtitleStreamIndex,
diff --git a/Jellyfin.Api/Controllers/MoviesController.cs b/Jellyfin.Api/Controllers/MoviesController.cs
index 7fcfc749de..ebc148fe56 100644
--- a/Jellyfin.Api/Controllers/MoviesController.cs
+++ b/Jellyfin.Api/Controllers/MoviesController.cs
@@ -4,6 +4,7 @@ using System.Globalization;
using System.Linq;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
+using Jellyfin.Api.ModelBinders;
using Jellyfin.Data.Entities;
using Jellyfin.Data.Enums;
using MediaBrowser.Common.Extensions;
@@ -65,15 +66,14 @@ namespace Jellyfin.Api.Controllers
public ActionResult> GetMovieRecommendations(
[FromQuery] Guid? userId,
[FromQuery] string? parentId,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] int categoryLimit = 5,
[FromQuery] int itemLimit = 8)
{
var user = userId.HasValue && !userId.Equals(Guid.Empty)
? _userManager.GetUserById(userId.Value)
: null;
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request);
var categories = new List();
@@ -85,8 +85,8 @@ namespace Jellyfin.Api.Controllers
IncludeItemTypes = new[]
{
nameof(Movie),
- // typeof(Trailer).Name,
- // typeof(LiveTvProgram).Name
+ // nameof(Trailer),
+ // nameof(LiveTvProgram)
},
// IsMovie = true
OrderBy = new[] { ItemSortBy.DatePlayed, ItemSortBy.Random }.Select(i => new ValueTuple(i, SortOrder.Descending)).ToArray(),
diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs
index 570ae8fdc7..229d9ff022 100644
--- a/Jellyfin.Api/Controllers/MusicGenresController.cs
+++ b/Jellyfin.Api/Controllers/MusicGenresController.cs
@@ -1,16 +1,17 @@
using System;
using System.ComponentModel.DataAnnotations;
-using System.Globalization;
using System.Linq;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
@@ -47,30 +48,16 @@ namespace Jellyfin.Api.Controllers
///
/// Gets all music genres from a given item, folder, or the entire library.
///
- /// Optional filter by minimum community rating.
/// Optional. The record index to start at. All items with a lower index will be dropped from the results.
/// Optional. The maximum number of records to return.
/// The search term.
/// Specify this to localize the search to a specific item or folder. Omit to use the root.
- /// 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.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited.
/// Optional. If specified, results will be filtered in based on item type. This allows multiple, comma delimited.
- /// Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.
/// Optional filter by items that are marked as favorite, or not.
- /// Optional filter by MediaType. Allows multiple, comma delimited.
- /// Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited.
- /// Optional, include user data.
/// Optional, the max number of images to return, per image type.
/// Optional. The image types to include in the output.
- /// Optional. If specified, results will be filtered to include only those containing the specified person.
- /// Optional. If specified, results will be filtered to include only those containing the specified person id.
- /// Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited.
- /// Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited.
/// User id.
/// Optional filter by items whose name is sorted equally or greater than a given input string.
/// Optional filter by items whose name is sorted equally than a given input string.
@@ -80,31 +67,18 @@ namespace Jellyfin.Api.Controllers
/// Music genres returned.
/// An containing the queryresult of music genres.
[HttpGet]
+ [Obsolete("Use GetGenres instead")]
public ActionResult> GetMusicGenres(
- [FromQuery] double? minCommunityRating,
[FromQuery] int? startIndex,
[FromQuery] int? limit,
[FromQuery] string? searchTerm,
[FromQuery] string? parentId,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] string? excludeItemTypes,
[FromQuery] string? includeItemTypes,
- [FromQuery] string? filters,
[FromQuery] bool? isFavorite,
- [FromQuery] string? mediaTypes,
- [FromQuery] string? genres,
- [FromQuery] string? genreIds,
- [FromQuery] string? officialRatings,
- [FromQuery] string? tags,
- [FromQuery] string? years,
- [FromQuery] bool? enableUserData,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes,
- [FromQuery] string? person,
- [FromQuery] string? personIds,
- [FromQuery] string? personTypes,
- [FromQuery] string? studios,
- [FromQuery] string? studioIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
[FromQuery] Guid? userId,
[FromQuery] string? nameStartsWithOrGreater,
[FromQuery] string? nameStartsWith,
@@ -112,45 +86,24 @@ namespace Jellyfin.Api.Controllers
[FromQuery] bool? enableImages = true,
[FromQuery] bool enableTotalRecordCount = true)
{
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
- .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
+ .AddAdditionalDtoOptions(enableImages, false, imageTypeLimit, enableImageTypes);
- User? user = null;
- BaseItem parentItem;
+ User? user = userId.HasValue && userId != Guid.Empty ? _userManager.GetUserById(userId.Value) : null;
- if (userId.HasValue && !userId.Equals(Guid.Empty))
- {
- user = _userManager.GetUserById(userId.Value);
- parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(parentId);
- }
- else
- {
- parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.RootFolder : _libraryManager.GetItemById(parentId);
- }
+ var parentItem = _libraryManager.GetParentItem(parentId, userId);
var query = new InternalItemsQuery(user)
{
ExcludeItemTypes = RequestHelpers.Split(excludeItemTypes, ',', true),
IncludeItemTypes = RequestHelpers.Split(includeItemTypes, ',', true),
- MediaTypes = RequestHelpers.Split(mediaTypes, ',', true),
StartIndex = startIndex,
Limit = limit,
IsFavorite = isFavorite,
NameLessThan = nameLessThan,
NameStartsWith = nameStartsWith,
NameStartsWithOrGreater = nameStartsWithOrGreater,
- Tags = RequestHelpers.Split(tags, '|', true),
- OfficialRatings = RequestHelpers.Split(officialRatings, '|', true),
- Genres = RequestHelpers.Split(genres, '|', true),
- GenreIds = RequestHelpers.GetGuids(genreIds),
- StudioIds = RequestHelpers.GetGuids(studioIds),
- Person = person,
- PersonIds = RequestHelpers.GetGuids(personIds),
- PersonTypes = RequestHelpers.Split(personTypes, ',', true),
- Years = RequestHelpers.Split(years, ',', true).Select(y => Convert.ToInt32(y, CultureInfo.InvariantCulture)).ToArray(),
- MinCommunityRating = minCommunityRating,
DtoOptions = dtoOptions,
SearchTerm = searchTerm,
EnableTotalRecordCount = enableTotalRecordCount
@@ -168,87 +121,10 @@ namespace Jellyfin.Api.Controllers
}
}
- // Studios
- if (!string.IsNullOrEmpty(studios))
- {
- query.StudioIds = studios.Split('|')
- .Select(i =>
- {
- try
- {
- return _libraryManager.GetStudio(i);
- }
- catch
- {
- return null;
- }
- }).Where(i => i != null)
- .Select(i => i!.Id)
- .ToArray();
- }
-
- foreach (var filter in RequestHelpers.GetFilters(filters))
- {
- switch (filter)
- {
- case ItemFilter.Dislikes:
- query.IsLiked = false;
- break;
- case ItemFilter.IsFavorite:
- query.IsFavorite = true;
- break;
- case ItemFilter.IsFavoriteOrLikes:
- query.IsFavoriteOrLiked = true;
- break;
- case ItemFilter.IsFolder:
- query.IsFolder = true;
- break;
- case ItemFilter.IsNotFolder:
- query.IsFolder = false;
- break;
- case ItemFilter.IsPlayed:
- query.IsPlayed = true;
- break;
- case ItemFilter.IsResumable:
- query.IsResumable = true;
- break;
- case ItemFilter.IsUnplayed:
- query.IsPlayed = false;
- break;
- case ItemFilter.Likes:
- query.IsLiked = true;
- break;
- }
- }
-
var result = _libraryManager.GetMusicGenres(query);
- var dtos = result.Items.Select(i =>
- {
- var (baseItem, counts) = i;
- var dto = _dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user);
-
- if (!string.IsNullOrWhiteSpace(includeItemTypes))
- {
- dto.ChildCount = counts.ItemCount;
- dto.ProgramCount = counts.ProgramCount;
- dto.SeriesCount = counts.SeriesCount;
- dto.EpisodeCount = counts.EpisodeCount;
- dto.MovieCount = counts.MovieCount;
- dto.TrailerCount = counts.TrailerCount;
- dto.AlbumCount = counts.AlbumCount;
- dto.SongCount = counts.SongCount;
- dto.ArtistCount = counts.ArtistCount;
- }
-
- return dto;
- });
-
- return new QueryResult
- {
- Items = dtos.ToArray(),
- TotalRecordCount = result.TotalRecordCount
- };
+ var shouldIncludeItemTypes = !string.IsNullOrWhiteSpace(includeItemTypes);
+ return RequestHelpers.CreateQueryResult(result, dtoOptions, _dtoService, shouldIncludeItemTypes, user);
}
///
@@ -263,7 +139,7 @@ namespace Jellyfin.Api.Controllers
{
var dtoOptions = new DtoOptions().AddClientFields(Request);
- MusicGenre item;
+ MusicGenre? item;
if (genreName.IndexOf(BaseItem.SlugChar, StringComparison.OrdinalIgnoreCase) != -1)
{
@@ -284,7 +160,7 @@ namespace Jellyfin.Api.Controllers
return _dtoService.GetBaseItemDto(item, dtoOptions);
}
- private T GetItemFromSlugName(ILibraryManager libraryManager, string name, DtoOptions dtoOptions)
+ private T? GetItemFromSlugName(ILibraryManager libraryManager, string name, DtoOptions dtoOptions)
where T : BaseItem, new()
{
var result = libraryManager.GetItemList(new InternalItemsQuery
diff --git a/Jellyfin.Api/Controllers/PackageController.cs b/Jellyfin.Api/Controllers/PackageController.cs
index eaf56aa563..1f797d6bc3 100644
--- a/Jellyfin.Api/Controllers/PackageController.cs
+++ b/Jellyfin.Api/Controllers/PackageController.cs
@@ -54,6 +54,11 @@ namespace Jellyfin.Api.Controllers
string.IsNullOrEmpty(assemblyGuid) ? default : Guid.Parse(assemblyGuid))
.FirstOrDefault();
+ if (result == null)
+ {
+ return NotFound();
+ }
+
return result;
}
@@ -77,6 +82,7 @@ namespace Jellyfin.Api.Controllers
/// Package name.
/// GUID of the associated assembly.
/// Optional version. Defaults to latest version.
+ /// Optional. Specify the repository to install from.
/// Package found.
/// Package not found.
/// A on success, or a if the package could not be found.
@@ -87,9 +93,16 @@ namespace Jellyfin.Api.Controllers
public async Task InstallPackage(
[FromRoute, Required] string name,
[FromQuery] string? assemblyGuid,
- [FromQuery] string? version)
+ [FromQuery] string? version,
+ [FromQuery] string? repositoryUrl)
{
var packages = await _installationManager.GetAvailablePackages().ConfigureAwait(false);
+ if (!string.IsNullOrEmpty(repositoryUrl))
+ {
+ packages = packages.Where(p => p.repositoryUrl.Equals(repositoryUrl, StringComparison.OrdinalIgnoreCase))
+ .ToList();
+ }
+
var package = _installationManager.GetCompatibleVersions(
packages,
name,
@@ -141,12 +154,13 @@ namespace Jellyfin.Api.Controllers
/// The list of package repositories.
/// Package repositories saved.
/// A .
- [HttpOptions("Repositories")]
+ [HttpPost("Repositories")]
[Authorize(Policy = Policies.DefaultAuthorization)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public ActionResult SetRepositories([FromBody] List repositoryInfos)
{
_serverConfigurationManager.Configuration.PluginRepositories = repositoryInfos;
+ _serverConfigurationManager.SaveConfiguration();
return NoContent();
}
}
diff --git a/Jellyfin.Api/Controllers/PersonsController.cs b/Jellyfin.Api/Controllers/PersonsController.cs
index 8bd610dad9..6ac3e6417a 100644
--- a/Jellyfin.Api/Controllers/PersonsController.cs
+++ b/Jellyfin.Api/Controllers/PersonsController.cs
@@ -1,15 +1,16 @@
using System;
using System.ComponentModel.DataAnnotations;
-using System.Globalization;
using System.Linq;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
@@ -26,6 +27,7 @@ namespace Jellyfin.Api.Controllers
private readonly ILibraryManager _libraryManager;
private readonly IDtoService _dtoService;
private readonly IUserManager _userManager;
+ private readonly IUserDataManager _userDataManager;
///
/// Initializes a new instance of the class.
@@ -33,221 +35,81 @@ namespace Jellyfin.Api.Controllers
/// Instance of the interface.
/// Instance of the interface.
/// Instance of the interface.
+ /// Instance of the interface.
public PersonsController(
ILibraryManager libraryManager,
IDtoService dtoService,
- IUserManager userManager)
+ IUserManager userManager,
+ IUserDataManager userDataManager)
{
_libraryManager = libraryManager;
_dtoService = dtoService;
_userManager = userManager;
+ _userDataManager = userDataManager;
}
///
- /// Gets all persons from a given item, folder, or the entire library.
+ /// Gets all persons.
///
- /// Optional filter by minimum community rating.
- /// Optional. The record index to start at. All items with a lower index will be dropped from the results.
/// Optional. The maximum number of records to return.
/// The search term.
- /// Specify this to localize the search to a specific item or folder. Omit to use the root.
- /// 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.
- /// Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited.
- /// Optional. If specified, results will be filtered in based on item type. This allows multiple, comma delimited.
- /// Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.
- /// Optional filter by items that are marked as favorite, or not.
- /// Optional filter by MediaType. Allows multiple, comma delimited.
- /// Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited.
+ /// Optional. Specify additional fields of information to return in the output.
+ /// Optional. Specify additional filters to apply.
+ /// Optional filter by items that are marked as favorite, or not. userId is required.
/// Optional, include user data.
/// Optional, the max number of images to return, per image type.
/// Optional. The image types to include in the output.
- /// Optional. If specified, results will be filtered to include only those containing the specified person.
- /// Optional. If specified, results will be filtered to include only those containing the specified person id.
- /// Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited.
- /// Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited.
+ /// Optional. If specified results will be filtered to exclude those containing the specified PersonType. Allows multiple, comma-delimited.
+ /// Optional. If specified results will be filtered to include only those containing the specified PersonType. Allows multiple, comma-delimited.
+ /// Optional. If specified, person results will be filtered on items related to said persons.
/// User id.
- /// Optional filter by items whose name is sorted equally or greater than a given input string.
- /// Optional filter by items whose name is sorted equally than a given input string.
- /// Optional filter by items whose name is equally or lesser than a given input string.
/// Optional, include image information in output.
- /// Optional. Include total record count.
/// Persons returned.
/// An containing the queryresult of persons.
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult> GetPersons(
- [FromQuery] double? minCommunityRating,
- [FromQuery] int? startIndex,
[FromQuery] int? limit,
[FromQuery] string? searchTerm,
- [FromQuery] string? parentId,
- [FromQuery] string? fields,
- [FromQuery] string? excludeItemTypes,
- [FromQuery] string? includeItemTypes,
- [FromQuery] string? filters,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters,
[FromQuery] bool? isFavorite,
- [FromQuery] string? mediaTypes,
- [FromQuery] string? genres,
- [FromQuery] string? genreIds,
- [FromQuery] string? officialRatings,
- [FromQuery] string? tags,
- [FromQuery] string? years,
[FromQuery] bool? enableUserData,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes,
- [FromQuery] string? person,
- [FromQuery] string? personIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
+ [FromQuery] string? excludePersonTypes,
[FromQuery] string? personTypes,
- [FromQuery] string? studios,
- [FromQuery] string? studioIds,
+ [FromQuery] string? appearsInItemId,
[FromQuery] Guid? userId,
- [FromQuery] string? nameStartsWithOrGreater,
- [FromQuery] string? nameStartsWith,
- [FromQuery] string? nameLessThan,
- [FromQuery] bool? enableImages = true,
- [FromQuery] bool enableTotalRecordCount = true)
+ [FromQuery] bool? enableImages = true)
{
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
User? user = null;
- BaseItem parentItem;
if (userId.HasValue && !userId.Equals(Guid.Empty))
{
user = _userManager.GetUserById(userId.Value);
- parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(parentId);
- }
- else
- {
- parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.RootFolder : _libraryManager.GetItemById(parentId);
}
- var query = new InternalItemsQuery(user)
+ var isFavoriteInFilters = filters.Any(f => f == ItemFilter.IsFavorite);
+ var peopleItems = _libraryManager.GetPeopleItems(new InternalPeopleQuery
{
- ExcludeItemTypes = RequestHelpers.Split(excludeItemTypes, ',', true),
- IncludeItemTypes = RequestHelpers.Split(includeItemTypes, ',', true),
- MediaTypes = RequestHelpers.Split(mediaTypes, ',', true),
- StartIndex = startIndex,
- Limit = limit,
- IsFavorite = isFavorite,
- NameLessThan = nameLessThan,
- NameStartsWith = nameStartsWith,
- NameStartsWithOrGreater = nameStartsWithOrGreater,
- Tags = RequestHelpers.Split(tags, '|', true),
- OfficialRatings = RequestHelpers.Split(officialRatings, '|', true),
- Genres = RequestHelpers.Split(genres, '|', true),
- GenreIds = RequestHelpers.GetGuids(genreIds),
- StudioIds = RequestHelpers.GetGuids(studioIds),
- Person = person,
- PersonIds = RequestHelpers.GetGuids(personIds),
PersonTypes = RequestHelpers.Split(personTypes, ',', true),
- Years = RequestHelpers.Split(years, ',', true).Select(y => Convert.ToInt32(y, CultureInfo.InvariantCulture)).ToArray(),
- MinCommunityRating = minCommunityRating,
- DtoOptions = dtoOptions,
- SearchTerm = searchTerm,
- EnableTotalRecordCount = enableTotalRecordCount
- };
-
- if (!string.IsNullOrWhiteSpace(parentId))
- {
- if (parentItem is Folder)
- {
- query.AncestorIds = new[] { new Guid(parentId) };
- }
- else
- {
- query.ItemIds = new[] { new Guid(parentId) };
- }
- }
-
- // Studios
- if (!string.IsNullOrEmpty(studios))
- {
- query.StudioIds = studios.Split('|')
- .Select(i =>
- {
- try
- {
- return _libraryManager.GetStudio(i);
- }
- catch
- {
- return null;
- }
- }).Where(i => i != null)
- .Select(i => i!.Id)
- .ToArray();
- }
-
- foreach (var filter in RequestHelpers.GetFilters(filters))
- {
- switch (filter)
- {
- case ItemFilter.Dislikes:
- query.IsLiked = false;
- break;
- case ItemFilter.IsFavorite:
- query.IsFavorite = true;
- break;
- case ItemFilter.IsFavoriteOrLikes:
- query.IsFavoriteOrLiked = true;
- break;
- case ItemFilter.IsFolder:
- query.IsFolder = true;
- break;
- case ItemFilter.IsNotFolder:
- query.IsFolder = false;
- break;
- case ItemFilter.IsPlayed:
- query.IsPlayed = true;
- break;
- case ItemFilter.IsResumable:
- query.IsResumable = true;
- break;
- case ItemFilter.IsUnplayed:
- query.IsPlayed = false;
- break;
- case ItemFilter.Likes:
- query.IsLiked = true;
- break;
- }
- }
-
- var result = new QueryResult<(BaseItem, ItemCounts)>();
-
- var dtos = result.Items.Select(i =>
- {
- var (baseItem, counts) = i;
- var dto = _dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user);
-
- if (!string.IsNullOrWhiteSpace(includeItemTypes))
- {
- dto.ChildCount = counts.ItemCount;
- dto.ProgramCount = counts.ProgramCount;
- dto.SeriesCount = counts.SeriesCount;
- dto.EpisodeCount = counts.EpisodeCount;
- dto.MovieCount = counts.MovieCount;
- dto.TrailerCount = counts.TrailerCount;
- dto.AlbumCount = counts.AlbumCount;
- dto.SongCount = counts.SongCount;
- dto.ArtistCount = counts.ArtistCount;
- }
-
- return dto;
+ ExcludePersonTypes = RequestHelpers.Split(excludePersonTypes, ',', true),
+ NameContains = searchTerm,
+ User = user,
+ IsFavorite = !isFavorite.HasValue && isFavoriteInFilters ? true : isFavorite,
+ AppearsInItemId = string.IsNullOrEmpty(appearsInItemId) ? Guid.Empty : Guid.Parse(appearsInItemId),
+ Limit = limit ?? 0
});
return new QueryResult
{
- Items = dtos.ToArray(),
- TotalRecordCount = result.TotalRecordCount
+ Items = peopleItems.Select(person => _dtoService.GetItemByNameDto(person, dtoOptions, null, user)).ToArray(),
+ TotalRecordCount = peopleItems.Count
};
}
diff --git a/Jellyfin.Api/Controllers/PlaylistsController.cs b/Jellyfin.Api/Controllers/PlaylistsController.cs
index 1e95bd2b38..4b3d8d3d39 100644
--- a/Jellyfin.Api/Controllers/PlaylistsController.cs
+++ b/Jellyfin.Api/Controllers/PlaylistsController.cs
@@ -5,11 +5,13 @@ using System.Threading.Tasks;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
using Jellyfin.Api.Models.PlaylistDtos;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Playlists;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization;
@@ -133,7 +135,7 @@ namespace Jellyfin.Api.Controllers
/// User id.
/// Optional. The record index to start at. All items with a lower index will be dropped from the results.
/// Optional. The maximum number of records to return.
- /// 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.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. Include image information in output.
/// Optional. Include user data.
/// Optional. The max number of images to return, per image type.
@@ -147,11 +149,11 @@ namespace Jellyfin.Api.Controllers
[FromQuery, Required] Guid userId,
[FromQuery] int? startIndex,
[FromQuery] int? limit,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] bool? enableImages,
[FromQuery] bool? enableUserData,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes)
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes)
{
var playlist = (Playlist)_libraryManager.GetItemById(playlistId);
if (playlist == null)
@@ -175,8 +177,7 @@ namespace Jellyfin.Api.Controllers
items = items.Take(limit.Value).ToArray();
}
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
diff --git a/Jellyfin.Api/Controllers/RemoteImageController.cs b/Jellyfin.Api/Controllers/RemoteImageController.cs
index 5f095443b9..5284888d82 100644
--- a/Jellyfin.Api/Controllers/RemoteImageController.cs
+++ b/Jellyfin.Api/Controllers/RemoteImageController.cs
@@ -157,9 +157,9 @@ namespace Jellyfin.Api.Controllers
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesImageFile]
- public async Task GetRemoteImage([FromQuery, Required] string imageUrl)
+ public async Task GetRemoteImage([FromQuery, Required] Uri imageUrl)
{
- var urlHash = imageUrl.GetMD5();
+ var urlHash = imageUrl.ToString().GetMD5();
var pointerCachePath = GetFullCachePath(urlHash.ToString());
string? contentPath = null;
@@ -245,17 +245,25 @@ namespace Jellyfin.Api.Controllers
/// The URL hash.
/// The pointer cache path.
/// Task.
- private async Task DownloadImage(string url, Guid urlHash, string pointerCachePath)
+ private async Task DownloadImage(Uri url, Guid urlHash, string pointerCachePath)
{
var httpClient = _httpClientFactory.CreateClient(NamedClient.Default);
using var response = await httpClient.GetAsync(url).ConfigureAwait(false);
- var ext = response.Content.Headers.ContentType.MediaType.Split('/').Last();
+ if (response.Content.Headers.ContentType?.MediaType == null)
+ {
+ throw new ResourceNotFoundException(nameof(response.Content.Headers.ContentType));
+ }
+
+ var ext = response.Content.Headers.ContentType.MediaType.Split('/')[^1];
var fullCachePath = GetFullCachePath(urlHash + "." + ext);
- Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath));
+ var fullCacheDirectory = Path.GetDirectoryName(fullCachePath) ?? throw new ResourceNotFoundException($"Provided path ({fullCachePath}) is not valid.");
+ Directory.CreateDirectory(fullCacheDirectory);
await using var fileStream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true);
await response.Content.CopyToAsync(fileStream).ConfigureAwait(false);
- Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath));
+
+ var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath) ?? throw new ArgumentException($"Provided path ({pointerCachePath}) is not valid.", nameof(pointerCachePath));
+ Directory.CreateDirectory(pointerCacheDirectory);
await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath, CancellationToken.None)
.ConfigureAwait(false);
}
diff --git a/Jellyfin.Api/Controllers/ScheduledTasksController.cs b/Jellyfin.Api/Controllers/ScheduledTasksController.cs
index ab7920895b..68e4f0586f 100644
--- a/Jellyfin.Api/Controllers/ScheduledTasksController.cs
+++ b/Jellyfin.Api/Controllers/ScheduledTasksController.cs
@@ -36,7 +36,7 @@ namespace Jellyfin.Api.Controllers
/// The list of scheduled tasks.
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
- public IEnumerable GetTasks(
+ public IEnumerable GetTasks(
[FromQuery] bool? isHidden,
[FromQuery] bool? isEnabled)
{
@@ -57,7 +57,7 @@ namespace Jellyfin.Api.Controllers
}
}
- yield return task;
+ yield return ScheduledTaskHelpers.GetTaskInfo(task);
}
}
diff --git a/Jellyfin.Api/Controllers/SearchController.cs b/Jellyfin.Api/Controllers/SearchController.cs
index 62c870cb1f..e75f0d06bb 100644
--- a/Jellyfin.Api/Controllers/SearchController.cs
+++ b/Jellyfin.Api/Controllers/SearchController.cs
@@ -260,7 +260,7 @@ namespace Jellyfin.Api.Controllers
}
}
- private T GetParentWithImage(BaseItem item, ImageType type)
+ private T? GetParentWithImage(BaseItem item, ImageType type)
where T : BaseItem
{
return item.GetParents().OfType().FirstOrDefault(i => i.HasImage(type));
diff --git a/Jellyfin.Api/Controllers/SessionController.cs b/Jellyfin.Api/Controllers/SessionController.cs
index 39bf6e6dc7..e506ac7bf1 100644
--- a/Jellyfin.Api/Controllers/SessionController.cs
+++ b/Jellyfin.Api/Controllers/SessionController.cs
@@ -5,6 +5,7 @@ using System.Linq;
using System.Threading;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Devices;
using MediaBrowser.Controller.Library;
@@ -378,7 +379,7 @@ namespace Jellyfin.Api.Controllers
public ActionResult PostCapabilities(
[FromQuery] string? id,
[FromQuery] string? playableMediaTypes,
- [FromQuery] string? supportedCommands,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] GeneralCommandType[] supportedCommands,
[FromQuery] bool supportsMediaControl = false,
[FromQuery] bool supportsSync = false,
[FromQuery] bool supportsPersistentIdentifier = true)
@@ -391,7 +392,7 @@ namespace Jellyfin.Api.Controllers
_sessionManager.ReportCapabilities(id, new ClientCapabilities
{
PlayableMediaTypes = RequestHelpers.Split(playableMediaTypes, ',', true),
- SupportedCommands = RequestHelpers.Split(supportedCommands, ',', true),
+ SupportedCommands = supportedCommands,
SupportsMediaControl = supportsMediaControl,
SupportsSync = supportsSync,
SupportsPersistentIdentifier = supportsPersistentIdentifier
diff --git a/Jellyfin.Api/Controllers/StudiosController.cs b/Jellyfin.Api/Controllers/StudiosController.cs
index cdd5f958e9..27dcd51bc2 100644
--- a/Jellyfin.Api/Controllers/StudiosController.cs
+++ b/Jellyfin.Api/Controllers/StudiosController.cs
@@ -1,14 +1,15 @@
using System;
using System.ComponentModel.DataAnnotations;
-using System.Linq;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
@@ -45,30 +46,17 @@ namespace Jellyfin.Api.Controllers
///
/// Gets all studios from a given item, folder, or the entire library.
///
- /// Optional filter by minimum community rating.
/// Optional. The record index to start at. All items with a lower index will be dropped from the results.
/// Optional. The maximum number of records to return.
/// Optional. Search term.
/// Specify this to localize the search to a specific item or folder. Omit to use the root.
- /// 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.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited.
/// Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.
- /// Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.
/// Optional filter by items that are marked as favorite, or not.
- /// Optional filter by MediaType. Allows multiple, comma delimited.
- /// Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited.
/// Optional, include user data.
/// Optional, the max number of images to return, per image type.
/// Optional. The image types to include in the output.
- /// Optional. If specified, results will be filtered to include only those containing the specified person.
- /// Optional. If specified, results will be filtered to include only those containing the specified person ids.
- /// Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited.
- /// Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited.
- /// Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited.
/// User id.
/// Optional filter by items whose name is sorted equally or greater than a given input string.
/// Optional filter by items whose name is sorted equally than a given input string.
@@ -80,30 +68,17 @@ namespace Jellyfin.Api.Controllers
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult> GetStudios(
- [FromQuery] double? minCommunityRating,
[FromQuery] int? startIndex,
[FromQuery] int? limit,
[FromQuery] string? searchTerm,
[FromQuery] string? parentId,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] string? excludeItemTypes,
[FromQuery] string? includeItemTypes,
- [FromQuery] string? filters,
[FromQuery] bool? isFavorite,
- [FromQuery] string? mediaTypes,
- [FromQuery] string? genres,
- [FromQuery] string? genreIds,
- [FromQuery] string? officialRatings,
- [FromQuery] string? tags,
- [FromQuery] string? years,
[FromQuery] bool? enableUserData,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes,
- [FromQuery] string? person,
- [FromQuery] string? personIds,
- [FromQuery] string? personTypes,
- [FromQuery] string? studios,
- [FromQuery] string? studioIds,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
[FromQuery] Guid? userId,
[FromQuery] string? nameStartsWithOrGreater,
[FromQuery] string? nameStartsWith,
@@ -111,49 +86,27 @@ namespace Jellyfin.Api.Controllers
[FromQuery] bool? enableImages = true,
[FromQuery] bool enableTotalRecordCount = true)
{
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
- User? user = null;
- BaseItem parentItem;
+ User? user = userId.HasValue && userId != Guid.Empty ? _userManager.GetUserById(userId.Value) : null;
- if (userId.HasValue && !userId.Equals(Guid.Empty))
- {
- user = _userManager.GetUserById(userId.Value);
- parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(parentId);
- }
- else
- {
- parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.RootFolder : _libraryManager.GetItemById(parentId);
- }
+ var parentItem = _libraryManager.GetParentItem(parentId, userId);
var excludeItemTypesArr = RequestHelpers.Split(excludeItemTypes, ',', true);
var includeItemTypesArr = RequestHelpers.Split(includeItemTypes, ',', true);
- var mediaTypesArr = RequestHelpers.Split(mediaTypes, ',', true);
var query = new InternalItemsQuery(user)
{
ExcludeItemTypes = excludeItemTypesArr,
IncludeItemTypes = includeItemTypesArr,
- MediaTypes = mediaTypesArr,
StartIndex = startIndex,
Limit = limit,
IsFavorite = isFavorite,
NameLessThan = nameLessThan,
NameStartsWith = nameStartsWith,
NameStartsWithOrGreater = nameStartsWithOrGreater,
- Tags = RequestHelpers.Split(tags, ',', true),
- OfficialRatings = RequestHelpers.Split(officialRatings, ',', true),
- Genres = RequestHelpers.Split(genres, ',', true),
- GenreIds = RequestHelpers.GetGuids(genreIds),
- StudioIds = RequestHelpers.GetGuids(studioIds),
- Person = person,
- PersonIds = RequestHelpers.GetGuids(personIds),
- PersonTypes = RequestHelpers.Split(personTypes, ',', true),
- Years = RequestHelpers.Split(years, ',', true).Select(int.Parse).ToArray(),
- MinCommunityRating = minCommunityRating,
DtoOptions = dtoOptions,
SearchTerm = searchTerm,
EnableTotalRecordCount = enableTotalRecordCount
@@ -171,84 +124,9 @@ namespace Jellyfin.Api.Controllers
}
}
- // Studios
- if (!string.IsNullOrEmpty(studios))
- {
- query.StudioIds = studios.Split('|').Select(i =>
- {
- try
- {
- return _libraryManager.GetStudio(i);
- }
- catch
- {
- return null;
- }
- }).Where(i => i != null).Select(i => i!.Id)
- .ToArray();
- }
-
- foreach (var filter in RequestHelpers.GetFilters(filters))
- {
- switch (filter)
- {
- case ItemFilter.Dislikes:
- query.IsLiked = false;
- break;
- case ItemFilter.IsFavorite:
- query.IsFavorite = true;
- break;
- case ItemFilter.IsFavoriteOrLikes:
- query.IsFavoriteOrLiked = true;
- break;
- case ItemFilter.IsFolder:
- query.IsFolder = true;
- break;
- case ItemFilter.IsNotFolder:
- query.IsFolder = false;
- break;
- case ItemFilter.IsPlayed:
- query.IsPlayed = true;
- break;
- case ItemFilter.IsResumable:
- query.IsResumable = true;
- break;
- case ItemFilter.IsUnplayed:
- query.IsPlayed = false;
- break;
- case ItemFilter.Likes:
- query.IsLiked = true;
- break;
- }
- }
-
- var result = new QueryResult<(BaseItem, ItemCounts)>();
- var dtos = result.Items.Select(i =>
- {
- var (baseItem, itemCounts) = i;
- var dto = _dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user);
-
- if (!string.IsNullOrWhiteSpace(includeItemTypes))
- {
- dto.ChildCount = itemCounts.ItemCount;
- dto.ProgramCount = itemCounts.ProgramCount;
- dto.SeriesCount = itemCounts.SeriesCount;
- dto.EpisodeCount = itemCounts.EpisodeCount;
- dto.MovieCount = itemCounts.MovieCount;
- dto.TrailerCount = itemCounts.TrailerCount;
- dto.AlbumCount = itemCounts.AlbumCount;
- dto.SongCount = itemCounts.SongCount;
- dto.ArtistCount = itemCounts.ArtistCount;
- }
-
- return dto;
- });
-
- return new QueryResult
- {
- Items = dtos.ToArray(),
- TotalRecordCount = result.TotalRecordCount
- };
+ var result = _libraryManager.GetStudios(query);
+ var shouldIncludeItemTypes = !string.IsNullOrEmpty(includeItemTypes);
+ return RequestHelpers.CreateQueryResult(result, dtoOptions, _dtoService, shouldIncludeItemTypes, user);
}
///
diff --git a/Jellyfin.Api/Controllers/SubtitleController.cs b/Jellyfin.Api/Controllers/SubtitleController.cs
index cc682ed542..a01ae31a0e 100644
--- a/Jellyfin.Api/Controllers/SubtitleController.cs
+++ b/Jellyfin.Api/Controllers/SubtitleController.cs
@@ -11,6 +11,9 @@ using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Api.Attributes;
using Jellyfin.Api.Constants;
+using Jellyfin.Api.Models.SubtitleDtos;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
@@ -21,6 +24,7 @@ using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Providers;
+using MediaBrowser.Model.Subtitles;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@@ -34,6 +38,7 @@ namespace Jellyfin.Api.Controllers
[Route("")]
public class SubtitleController : BaseJellyfinApiController
{
+ private readonly IServerConfigurationManager _serverConfigurationManager;
private readonly ILibraryManager _libraryManager;
private readonly ISubtitleManager _subtitleManager;
private readonly ISubtitleEncoder _subtitleEncoder;
@@ -46,6 +51,7 @@ namespace Jellyfin.Api.Controllers
///
/// Initializes a new instance of the class.
///
+ /// Instance of interface.
/// Instance of interface.
/// Instance of interface.
/// Instance of interface.
@@ -55,6 +61,7 @@ namespace Jellyfin.Api.Controllers
/// Instance of interface.
/// Instance of interface.
public SubtitleController(
+ IServerConfigurationManager serverConfigurationManager,
ILibraryManager libraryManager,
ISubtitleManager subtitleManager,
ISubtitleEncoder subtitleEncoder,
@@ -64,6 +71,7 @@ namespace Jellyfin.Api.Controllers
IAuthorizationContext authContext,
ILogger logger)
{
+ _serverConfigurationManager = serverConfigurationManager;
_libraryManager = libraryManager;
_subtitleManager = subtitleManager;
_subtitleEncoder = subtitleEncoder;
@@ -319,6 +327,33 @@ namespace Jellyfin.Api.Controllers
return File(Encoding.UTF8.GetBytes(builder.ToString()), MimeTypes.GetMimeType("playlist.m3u8"));
}
+ ///
+ /// Upload an external subtitle file.
+ ///
+ /// The item the subtitle belongs to.
+ /// The request body.
+ /// Subtitle uploaded.
+ /// A .
+ [HttpPost("Videos/{itemId}/Subtitles")]
+ public async Task UploadSubtitle(
+ [FromRoute, Required] Guid itemId,
+ [FromBody, Required] UploadSubtitleDto body)
+ {
+ var video = (Video)_libraryManager.GetItemById(itemId);
+ var data = Convert.FromBase64String(body.Data);
+ await using var memoryStream = new MemoryStream(data);
+ await _subtitleManager.UploadSubtitle(
+ video,
+ new SubtitleResponse
+ {
+ Format = body.Format,
+ Language = body.Language,
+ IsForced = body.IsForced,
+ Stream = memoryStream
+ }).ConfigureAwait(false);
+ return NoContent();
+ }
+
///
/// Encodes a subtitle in the specified format.
///
@@ -351,5 +386,95 @@ namespace Jellyfin.Api.Controllers
copyTimestamps,
CancellationToken.None);
}
+
+ ///
+ /// Gets a list of available fallback font files.
+ ///
+ /// Information retrieved.
+ /// An array of with the available font files.
+ [HttpGet("FallbackFont/Fonts")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public IEnumerable GetFallbackFontList()
+ {
+ var encodingOptions = _serverConfigurationManager.GetEncodingOptions();
+ var fallbackFontPath = encodingOptions.FallbackFontPath;
+
+ if (!string.IsNullOrEmpty(fallbackFontPath))
+ {
+ var files = _fileSystem.GetFiles(fallbackFontPath, new[] { ".woff", ".woff2", ".ttf", ".otf" }, false, false);
+ var fontFiles = files
+ .Select(i => new FontFile
+ {
+ Name = i.Name,
+ Size = i.Length,
+ DateCreated = _fileSystem.GetCreationTimeUtc(i),
+ DateModified = _fileSystem.GetLastWriteTimeUtc(i)
+ })
+ .OrderBy(i => i.Size)
+ .ThenBy(i => i.Name)
+ .ThenByDescending(i => i.DateModified)
+ .ThenByDescending(i => i.DateCreated);
+ // max total size 20M
+ const int MaxSize = 20971520;
+ var sizeCounter = 0L;
+ foreach (var fontFile in fontFiles)
+ {
+ sizeCounter += fontFile.Size;
+ if (sizeCounter >= MaxSize)
+ {
+ _logger.LogWarning("Some fonts will not be sent due to size limitations");
+ yield break;
+ }
+
+ yield return fontFile;
+ }
+ }
+ else
+ {
+ _logger.LogWarning("The path of fallback font folder has not been set");
+ encodingOptions.EnableFallbackFont = false;
+ }
+ }
+
+ ///
+ /// Gets a fallback font file.
+ ///
+ /// The name of the fallback font file to get.
+ /// Fallback font file retrieved.
+ /// The fallback font file.
+ [HttpGet("FallbackFont/Fonts/{name}")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult GetFallbackFont([FromRoute, Required] string name)
+ {
+ var encodingOptions = _serverConfigurationManager.GetEncodingOptions();
+ var fallbackFontPath = encodingOptions.FallbackFontPath;
+
+ if (!string.IsNullOrEmpty(fallbackFontPath))
+ {
+ var fontFile = _fileSystem.GetFiles(fallbackFontPath)
+ .First(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
+ var fileSize = fontFile?.Length;
+
+ if (fontFile != null && fileSize != null && fileSize > 0)
+ {
+ _logger.LogDebug("Fallback font size is {fileSize} Bytes", fileSize);
+ return PhysicalFile(fontFile.FullName, MimeTypes.GetMimeType(fontFile.FullName));
+ }
+ else
+ {
+ _logger.LogWarning("The selected font is null or empty");
+ }
+ }
+ else
+ {
+ _logger.LogWarning("The path of fallback font folder has not been set");
+ encodingOptions.EnableFallbackFont = false;
+ }
+
+ // returning HTTP 204 will break the SubtitlesOctopus
+ return Ok();
+ }
}
}
diff --git a/Jellyfin.Api/Controllers/SuggestionsController.cs b/Jellyfin.Api/Controllers/SuggestionsController.cs
index d7c81a3ab6..ad64adfbad 100644
--- a/Jellyfin.Api/Controllers/SuggestionsController.cs
+++ b/Jellyfin.Api/Controllers/SuggestionsController.cs
@@ -1,6 +1,7 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
+using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
using Jellyfin.Data.Enums;
@@ -9,6 +10,7 @@ using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Querying;
+using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@@ -18,6 +20,7 @@ namespace Jellyfin.Api.Controllers
/// The suggestions controller.
///
[Route("")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
public class SuggestionsController : BaseJellyfinApiController
{
private readonly IDtoService _dtoService;
diff --git a/Jellyfin.Api/Controllers/TrailersController.cs b/Jellyfin.Api/Controllers/TrailersController.cs
index 5157b08ae5..d78adcbcdc 100644
--- a/Jellyfin.Api/Controllers/TrailersController.cs
+++ b/Jellyfin.Api/Controllers/TrailersController.cs
@@ -1,6 +1,8 @@
using System;
using Jellyfin.Api.Constants;
+using Jellyfin.Api.ModelBinders;
using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
@@ -124,7 +126,7 @@ namespace Jellyfin.Api.Controllers
[FromQuery] bool? isHd,
[FromQuery] bool? is4K,
[FromQuery] string? locationTypes,
- [FromQuery] string? excludeLocationTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] excludeLocationTypes,
[FromQuery] bool? isMissing,
[FromQuery] bool? isUnaired,
[FromQuery] double? minCommunityRating,
@@ -144,12 +146,12 @@ namespace Jellyfin.Api.Controllers
[FromQuery] string? searchTerm,
[FromQuery] string? sortOrder,
[FromQuery] string? parentId,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] string? excludeItemTypes,
- [FromQuery] string? filters,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters,
[FromQuery] bool? isFavorite,
[FromQuery] string? mediaTypes,
- [FromQuery] string? imageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes,
[FromQuery] string? sortBy,
[FromQuery] bool? isPlayed,
[FromQuery] string? genres,
@@ -158,7 +160,7 @@ namespace Jellyfin.Api.Controllers
[FromQuery] string? years,
[FromQuery] bool? enableUserData,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
[FromQuery] string? person,
[FromQuery] string? personIds,
[FromQuery] string? personTypes,
diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs
index d158f6c342..6fd154836b 100644
--- a/Jellyfin.Api/Controllers/TvShowsController.cs
+++ b/Jellyfin.Api/Controllers/TvShowsController.cs
@@ -5,6 +5,7 @@ using System.Globalization;
using System.Linq;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
+using Jellyfin.Api.ModelBinders;
using Jellyfin.Data.Enums;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Dto;
@@ -13,6 +14,7 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.TV;
using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
@@ -57,7 +59,7 @@ namespace Jellyfin.Api.Controllers
/// The user id of the user to get the next up episodes for.
/// Optional. The record index to start at. All items with a lower index will be dropped from the results.
/// Optional. The maximum number of records to return.
- /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. Filter by series id.
/// Optional. Specify this to localize the search to a specific item or folder. Omit to use the root.
/// Optional. Include image information in output.
@@ -72,17 +74,16 @@ namespace Jellyfin.Api.Controllers
[FromQuery] Guid? userId,
[FromQuery] int? startIndex,
[FromQuery] int? limit,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] string? seriesId,
[FromQuery] string? parentId,
[FromQuery] bool? enableImges,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
[FromQuery] bool? enableUserData,
[FromQuery] bool enableTotalRecordCount = true)
{
- var options = new DtoOptions()
- .AddItemFields(fields!)
+ var options = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImges, enableUserData, imageTypeLimit, enableImageTypes!);
@@ -117,7 +118,7 @@ namespace Jellyfin.Api.Controllers
/// The user id of the user to get the upcoming episodes for.
/// Optional. The record index to start at. All items with a lower index will be dropped from the results.
/// Optional. The maximum number of records to return.
- /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. Specify this to localize the search to a specific item or folder. Omit to use the root.
/// Optional. Include image information in output.
/// Optional. The max number of images to return, per image type.
@@ -130,11 +131,11 @@ namespace Jellyfin.Api.Controllers
[FromQuery] Guid? userId,
[FromQuery] int? startIndex,
[FromQuery] int? limit,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] string? parentId,
[FromQuery] bool? enableImges,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
[FromQuery] bool? enableUserData)
{
var user = userId.HasValue && !userId.Equals(Guid.Empty)
@@ -145,8 +146,7 @@ namespace Jellyfin.Api.Controllers
var parentIdGuid = string.IsNullOrWhiteSpace(parentId) ? Guid.Empty : new Guid(parentId);
- var options = new DtoOptions()
- .AddItemFields(fields!)
+ var options = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImges, enableUserData, imageTypeLimit, enableImageTypes!);
@@ -196,7 +196,7 @@ namespace Jellyfin.Api.Controllers
public ActionResult> GetEpisodes(
[FromRoute, Required] string seriesId,
[FromQuery] Guid? userId,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] int? season,
[FromQuery] string? seasonId,
[FromQuery] bool? isMissing,
@@ -206,7 +206,7 @@ namespace Jellyfin.Api.Controllers
[FromQuery] int? limit,
[FromQuery] bool? enableImages,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
[FromQuery] bool? enableUserData,
[FromQuery] string? sortBy)
{
@@ -216,8 +216,7 @@ namespace Jellyfin.Api.Controllers
List episodes;
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields!)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!);
@@ -319,13 +318,13 @@ namespace Jellyfin.Api.Controllers
public ActionResult> GetSeasons(
[FromRoute, Required] string seriesId,
[FromQuery] Guid? userId,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] bool? isSpecialSeason,
[FromQuery] bool? isMissing,
[FromQuery] string? adjacentTo,
[FromQuery] bool? enableImages,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
[FromQuery] bool? enableUserData)
{
var user = userId.HasValue && !userId.Equals(Guid.Empty)
@@ -344,8 +343,7 @@ namespace Jellyfin.Api.Controllers
AdjacentTo = adjacentTo
});
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!);
diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs
index df20a92b3d..e10f1fe912 100644
--- a/Jellyfin.Api/Controllers/UniversalAudioController.cs
+++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs
@@ -76,6 +76,7 @@ namespace Jellyfin.Api.Controllers
/// Optional. The maximum number of audio channels.
/// Optional. The number of how many audio channels to transcode to.
/// Optional. The maximum streaming bitrate.
+ /// Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.
/// Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.
/// Optional. The container to transcode to.
/// Optional. The transcoding protocol.
@@ -88,23 +89,22 @@ namespace Jellyfin.Api.Controllers
/// Redirected to remote audio stream.
/// A containing the audio file.
[HttpGet("Audio/{itemId}/universal")]
- [HttpGet("Audio/{itemId}/universal.{container}", Name = "GetUniversalAudioStream_2")]
[HttpHead("Audio/{itemId}/universal", Name = "HeadUniversalAudioStream")]
- [HttpHead("Audio/{itemId}/universal.{container}", Name = "HeadUniversalAudioStream_2")]
[Authorize(Policy = Policies.DefaultAuthorization)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status302Found)]
[ProducesAudioFile]
public async Task GetUniversalAudioStream(
[FromRoute, Required] Guid itemId,
- [FromRoute] string? container,
+ [FromQuery] string? container,
[FromQuery] string? mediaSourceId,
[FromQuery] string? deviceId,
[FromQuery] Guid? userId,
[FromQuery] string? audioCodec,
[FromQuery] int? maxAudioChannels,
[FromQuery] int? transcodingAudioChannels,
- [FromQuery] long? maxStreamingBitrate,
+ [FromQuery] int? maxStreamingBitrate,
+ [FromQuery] int? audioBitRate,
[FromQuery] long? startTimeTicks,
[FromQuery] string? transcodingContainer,
[FromQuery] string? transcodingProtocol,
@@ -212,7 +212,7 @@ namespace Jellyfin.Api.Controllers
AudioSampleRate = maxAudioSampleRate,
MaxAudioChannels = maxAudioChannels,
MaxAudioBitDepth = maxAudioBitDepth,
- AudioChannels = isStatic ? (int?)null : Convert.ToInt32(Math.Min(maxStreamingBitrate ?? 192000, int.MaxValue)),
+ AudioBitRate = audioBitRate ?? maxStreamingBitrate,
StartTimeTicks = startTimeTicks,
SubtitleMethod = SubtitleDeliveryMethod.Hls,
RequireAvc = true,
@@ -244,7 +244,7 @@ namespace Jellyfin.Api.Controllers
BreakOnNonKeyFrames = breakOnNonKeyFrames,
AudioSampleRate = maxAudioSampleRate,
MaxAudioChannels = maxAudioChannels,
- AudioBitRate = isStatic ? (int?)null : Convert.ToInt32(Math.Min(maxStreamingBitrate ?? 192000, int.MaxValue)),
+ AudioBitRate = isStatic ? (int?)null : (audioBitRate ?? maxStreamingBitrate),
MaxAudioBitDepth = maxAudioBitDepth,
AudioChannels = maxAudioChannels,
CopyTimestamps = true,
@@ -270,20 +270,24 @@ namespace Jellyfin.Api.Controllers
{
var deviceProfile = new DeviceProfile();
- var directPlayProfiles = new List();
-
var containers = RequestHelpers.Split(container, ',', true);
-
- foreach (var cont in containers)
+ int len = containers.Length;
+ var directPlayProfiles = new DirectPlayProfile[len];
+ for (int i = 0; i < len; i++)
{
- var parts = RequestHelpers.Split(cont, ',', true);
+ var parts = RequestHelpers.Split(containers[i], '|', true);
- var audioCodecs = parts.Length == 1 ? null : string.Join(",", parts.Skip(1).ToArray());
+ var audioCodecs = parts.Length == 1 ? null : string.Join(',', parts.Skip(1));
- directPlayProfiles.Add(new DirectPlayProfile { Type = DlnaProfileType.Audio, Container = parts[0], AudioCodec = audioCodecs });
+ directPlayProfiles[i] = new DirectPlayProfile
+ {
+ Type = DlnaProfileType.Audio,
+ Container = parts[0],
+ AudioCodec = audioCodecs
+ };
}
- deviceProfile.DirectPlayProfiles = directPlayProfiles.ToArray();
+ deviceProfile.DirectPlayProfiles = directPlayProfiles;
deviceProfile.TranscodingProfiles = new[]
{
diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs
index 50bb8bb2aa..0f7c25d0e4 100644
--- a/Jellyfin.Api/Controllers/UserController.cs
+++ b/Jellyfin.Api/Controllers/UserController.cs
@@ -381,17 +381,13 @@ namespace Jellyfin.Api.Controllers
var user = _userManager.GetUserById(userId);
- if (string.Equals(user.Username, updateUser.Name, StringComparison.Ordinal))
- {
- await _userManager.UpdateUserAsync(user).ConfigureAwait(false);
- _userManager.UpdateConfiguration(user.Id, updateUser.Configuration);
- }
- else
+ if (!string.Equals(user.Username, updateUser.Name, StringComparison.Ordinal))
{
await _userManager.RenameUser(user, updateUser.Name).ConfigureAwait(false);
- _userManager.UpdateConfiguration(updateUser.Id, updateUser.Configuration);
}
+ await _userManager.UpdateConfigurationAsync(user.Id, updateUser.Configuration).ConfigureAwait(false);
+
return NoContent();
}
@@ -409,7 +405,7 @@ namespace Jellyfin.Api.Controllers
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
- public ActionResult UpdateUserPolicy(
+ public async Task UpdateUserPolicy(
[FromRoute, Required] Guid userId,
[FromBody] UserPolicy newPolicy)
{
@@ -447,7 +443,7 @@ namespace Jellyfin.Api.Controllers
_sessionManager.RevokeUserTokens(user.Id, currentToken);
}
- _userManager.UpdatePolicy(userId, newPolicy);
+ await _userManager.UpdatePolicyAsync(userId, newPolicy).ConfigureAwait(false);
return NoContent();
}
@@ -464,7 +460,7 @@ namespace Jellyfin.Api.Controllers
[Authorize(Policy = Policies.DefaultAuthorization)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
- public ActionResult UpdateUserConfiguration(
+ public async Task UpdateUserConfiguration(
[FromRoute, Required] Guid userId,
[FromBody] UserConfiguration userConfig)
{
@@ -473,7 +469,7 @@ namespace Jellyfin.Api.Controllers
return Forbid("User configuration update not allowed");
}
- _userManager.UpdateConfiguration(userId, userConfig);
+ await _userManager.UpdateConfigurationAsync(userId, userConfig).ConfigureAwait(false);
return NoContent();
}
@@ -534,6 +530,33 @@ namespace Jellyfin.Api.Controllers
return result;
}
+ ///
+ /// Gets the user based on auth token.
+ ///
+ /// User returned.
+ /// Token is not owned by a user.
+ /// A for the authenticated user.
+ [HttpGet("Me")]
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(StatusCodes.Status400BadRequest)]
+ public ActionResult GetCurrentUser()
+ {
+ var userId = ClaimHelpers.GetUserId(Request.HttpContext.User);
+ if (userId == null)
+ {
+ return BadRequest();
+ }
+
+ var user = _userManager.GetUserById(userId.Value);
+ if (user == null)
+ {
+ return BadRequest();
+ }
+
+ return _userManager.GetUserDto(user);
+ }
+
private IEnumerable Get(bool? isHidden, bool? isDisabled, bool filterByDevice, bool filterByNetwork)
{
var users = _userManager.Users;
diff --git a/Jellyfin.Api/Controllers/UserLibraryController.cs b/Jellyfin.Api/Controllers/UserLibraryController.cs
index 48262f0620..cfd8511297 100644
--- a/Jellyfin.Api/Controllers/UserLibraryController.cs
+++ b/Jellyfin.Api/Controllers/UserLibraryController.cs
@@ -7,6 +7,7 @@ using System.Threading.Tasks;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
@@ -251,7 +252,7 @@ namespace Jellyfin.Api.Controllers
///
/// User id.
/// Specify this to localize the search to a specific item or folder. Omit to use the root.
- /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, SortName, Studios, Taglines.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.
/// Filter by items that are played, or not.
/// Optional. include image information in output.
@@ -267,12 +268,12 @@ namespace Jellyfin.Api.Controllers
public ActionResult> GetLatestMedia(
[FromRoute, Required] Guid userId,
[FromQuery] Guid? parentId,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] string? includeItemTypes,
[FromQuery] bool? isPlayed,
[FromQuery] bool? enableImages,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
[FromQuery] bool? enableUserData,
[FromQuery] int limit = 20,
[FromQuery] bool groupItems = true)
@@ -287,8 +288,7 @@ namespace Jellyfin.Api.Controllers
}
}
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
diff --git a/Jellyfin.Api/Controllers/VideoAttachmentsController.cs b/Jellyfin.Api/Controllers/VideoAttachmentsController.cs
index 09a1c93e6a..418c0c1230 100644
--- a/Jellyfin.Api/Controllers/VideoAttachmentsController.cs
+++ b/Jellyfin.Api/Controllers/VideoAttachmentsController.cs
@@ -46,7 +46,7 @@ namespace Jellyfin.Api.Controllers
[Produces(MediaTypeNames.Application.Octet)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
- public async Task> GetAttachment(
+ public async Task GetAttachment(
[FromRoute, Required] Guid videoId,
[FromRoute, Required] string mediaSourceId,
[FromRoute, Required] int index)
diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs
index 2afa878f41..389dc8a088 100644
--- a/Jellyfin.Api/Controllers/VideoHlsController.cs
+++ b/Jellyfin.Api/Controllers/VideoHlsController.cs
@@ -11,6 +11,7 @@ using Jellyfin.Api.Helpers;
using Jellyfin.Api.Models.PlaybackDtos;
using Jellyfin.Api.Models.StreamingDtos;
using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Devices;
using MediaBrowser.Controller.Dlna;
@@ -361,7 +362,8 @@ namespace Jellyfin.Api.Controllers
var threads = _encodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec);
var inputModifier = _encodingHelper.GetInputModifier(state, _encodingOptions);
var format = !string.IsNullOrWhiteSpace(state.Request.SegmentContainer) ? "." + state.Request.SegmentContainer : ".ts";
- var outputTsArg = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d" + format;
+ var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
+ var outputTsArg = Path.Combine(directory, Path.GetFileNameWithoutExtension(outputPath)) + "%d" + format;
var segmentFormat = format.TrimStart('.');
if (string.Equals(segmentFormat, "ts", StringComparison.OrdinalIgnoreCase))
@@ -371,7 +373,7 @@ namespace Jellyfin.Api.Controllers
var baseUrlParam = string.Format(
CultureInfo.InvariantCulture,
- "\"hls{0}\"",
+ "\"hls/{0}/\"",
Path.GetFileNameWithoutExtension(outputPath));
return string.Format(
diff --git a/Jellyfin.Api/Controllers/YearsController.cs b/Jellyfin.Api/Controllers/YearsController.cs
index 4ecf0407bf..1b38e399d6 100644
--- a/Jellyfin.Api/Controllers/YearsController.cs
+++ b/Jellyfin.Api/Controllers/YearsController.cs
@@ -5,11 +5,13 @@ using System.Linq;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
+using Jellyfin.Api.ModelBinders;
using Jellyfin.Data.Entities;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
@@ -50,7 +52,7 @@ namespace Jellyfin.Api.Controllers
/// Optional. The maximum number of records to return.
/// Sort Order - Ascending,Descending.
/// Specify this to localize the search to a specific item or folder. Omit to use the root.
- /// 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.
+ /// Optional. Specify additional fields of information to return in the output.
/// Optional. If specified, results will be excluded based on item type. This allows multiple, comma delimited.
/// Optional. If specified, results will be included based on item type. This allows multiple, comma delimited.
/// Optional. Filter by MediaType. Allows multiple, comma delimited.
@@ -70,20 +72,19 @@ namespace Jellyfin.Api.Controllers
[FromQuery] int? limit,
[FromQuery] string? sortOrder,
[FromQuery] string? parentId,
- [FromQuery] string? fields,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
[FromQuery] string? excludeItemTypes,
[FromQuery] string? includeItemTypes,
[FromQuery] string? mediaTypes,
[FromQuery] string? sortBy,
[FromQuery] bool? enableUserData,
[FromQuery] int? imageTypeLimit,
- [FromQuery] string? enableImageTypes,
+ [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
[FromQuery] Guid? userId,
[FromQuery] bool recursive = true,
[FromQuery] bool? enableImages = true)
{
- var dtoOptions = new DtoOptions()
- .AddItemFields(fields)
+ var dtoOptions = new DtoOptions { Fields = fields }
.AddClientFields(Request)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
diff --git a/Jellyfin.Api/Extensions/DtoExtensions.cs b/Jellyfin.Api/Extensions/DtoExtensions.cs
index e61e9c29d9..f2abd515d3 100644
--- a/Jellyfin.Api/Extensions/DtoExtensions.cs
+++ b/Jellyfin.Api/Extensions/DtoExtensions.cs
@@ -1,6 +1,8 @@
using System;
+using System.Collections.Generic;
using System.Linq;
using Jellyfin.Api.Helpers;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
@@ -13,42 +15,6 @@ namespace Jellyfin.Api.Extensions
///
public static class DtoExtensions
{
- ///
- /// Add Dto Item fields.
- ///
- ///
- /// Converted from IHasItemFields.
- /// Legacy order: 1.
- ///
- /// DtoOptions object.
- /// Comma delimited string of fields.
- /// Modified DtoOptions object.
- internal static DtoOptions AddItemFields(this DtoOptions dtoOptions, string? fields)
- {
- if (string.IsNullOrEmpty(fields))
- {
- dtoOptions.Fields = Array.Empty();
- }
- else
- {
- dtoOptions.Fields = fields.Split(',')
- .Select(v =>
- {
- if (Enum.TryParse(v, true, out ItemFields value))
- {
- return (ItemFields?)value;
- }
-
- return null;
- })
- .Where(i => i.HasValue)
- .Select(i => i!.Value)
- .ToArray();
- }
-
- return dtoOptions;
- }
-
///
/// Add additional fields depending on client.
///
@@ -79,7 +45,7 @@ namespace Jellyfin.Api.Extensions
client.IndexOf("media center", StringComparison.OrdinalIgnoreCase) != -1 ||
client.IndexOf("classic", StringComparison.OrdinalIgnoreCase) != -1)
{
- int oldLen = dtoOptions.Fields.Length;
+ int oldLen = dtoOptions.Fields.Count;
var arr = new ItemFields[oldLen + 1];
dtoOptions.Fields.CopyTo(arr, 0);
arr[oldLen] = ItemFields.RecursiveItemCount;
@@ -97,7 +63,7 @@ namespace Jellyfin.Api.Extensions
client.IndexOf("samsung", StringComparison.OrdinalIgnoreCase) != -1 ||
client.IndexOf("androidtv", StringComparison.OrdinalIgnoreCase) != -1)
{
- int oldLen = dtoOptions.Fields.Length;
+ int oldLen = dtoOptions.Fields.Count;
var arr = new ItemFields[oldLen + 1];
dtoOptions.Fields.CopyTo(arr, 0);
arr[oldLen] = ItemFields.ChildCount;
@@ -126,7 +92,7 @@ namespace Jellyfin.Api.Extensions
bool? enableImages,
bool? enableUserData,
int? imageTypeLimit,
- string? enableImageTypes)
+ IReadOnlyList enableImageTypes)
{
dtoOptions.EnableImages = enableImages ?? true;
@@ -140,11 +106,9 @@ namespace Jellyfin.Api.Extensions
dtoOptions.EnableUserData = enableUserData.Value;
}
- if (!string.IsNullOrWhiteSpace(enableImageTypes))
+ if (enableImageTypes.Count != 0)
{
- dtoOptions.ImageTypes = enableImageTypes.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
- .Select(v => (ImageType)Enum.Parse(typeof(ImageType), v, true))
- .ToArray();
+ dtoOptions.ImageTypes = enableImageTypes;
}
return dtoOptions;
diff --git a/Jellyfin.Api/Helpers/AudioHelper.cs b/Jellyfin.Api/Helpers/AudioHelper.cs
index a3f2d88ce5..21ec2d32f9 100644
--- a/Jellyfin.Api/Helpers/AudioHelper.cs
+++ b/Jellyfin.Api/Helpers/AudioHelper.cs
@@ -1,8 +1,10 @@
-using System.Net.Http;
+using System;
+using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Api.Models.StreamingDtos;
using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Devices;
@@ -98,6 +100,11 @@ namespace Jellyfin.Api.Helpers
TranscodingJobType transcodingJobType,
StreamingRequestDto streamingRequest)
{
+ if (_httpContextAccessor.HttpContext == null)
+ {
+ throw new ResourceNotFoundException(nameof(_httpContextAccessor.HttpContext));
+ }
+
bool isHeadRequest = _httpContextAccessor.HttpContext.Request.Method == System.Net.WebRequestMethods.Http.Head;
var cancellationTokenSource = new CancellationTokenSource();
diff --git a/Jellyfin.Api/Helpers/ClaimHelpers.cs b/Jellyfin.Api/Helpers/ClaimHelpers.cs
index df235ced25..29e6b4193e 100644
--- a/Jellyfin.Api/Helpers/ClaimHelpers.cs
+++ b/Jellyfin.Api/Helpers/ClaimHelpers.cs
@@ -63,6 +63,19 @@ namespace Jellyfin.Api.Helpers
public static string? GetToken(in ClaimsPrincipal user)
=> GetClaimValue(user, InternalClaimTypes.Token);
+ ///
+ /// Gets a flag specifying whether the request is using an api key.
+ ///
+ /// Current claims principal.
+ /// The flag specifying whether the request is using an api key.
+ public static bool GetIsApiKey(in ClaimsPrincipal user)
+ {
+ var claimValue = GetClaimValue(user, InternalClaimTypes.IsApiKey);
+ return !string.IsNullOrEmpty(claimValue)
+ && bool.TryParse(claimValue, out var parsedClaimValue)
+ && parsedClaimValue;
+ }
+
private static string? GetClaimValue(in ClaimsPrincipal user, string name)
{
return user?.Identities
diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs
index af0519ffa8..e7fac50c64 100644
--- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs
+++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs
@@ -113,7 +113,7 @@ namespace Jellyfin.Api.Helpers
StreamingRequestDto streamingRequest,
bool enableAdaptiveBitrateStreaming)
{
- var isHeadRequest = _httpContextAccessor.HttpContext.Request.Method == WebRequestMethods.Http.Head;
+ var isHeadRequest = _httpContextAccessor.HttpContext?.Request.Method == WebRequestMethods.Http.Head;
var cancellationTokenSource = new CancellationTokenSource();
return await GetMasterPlaylistInternal(
streamingRequest,
@@ -130,6 +130,11 @@ namespace Jellyfin.Api.Helpers
TranscodingJobType transcodingJobType,
CancellationTokenSource cancellationTokenSource)
{
+ if (_httpContextAccessor.HttpContext == null)
+ {
+ throw new ResourceNotFoundException(nameof(_httpContextAccessor.HttpContext));
+ }
+
using var state = await StreamingHelpers.GetStreamingState(
streamingRequest,
_httpContextAccessor.HttpContext.Request,
@@ -155,7 +160,7 @@ namespace Jellyfin.Api.Helpers
return new FileContentResult(Array.Empty(), MimeTypes.GetMimeType("playlist.m3u8"));
}
- var totalBitrate = state.OutputAudioBitrate ?? 0 + state.OutputVideoBitrate ?? 0;
+ var totalBitrate = (state.OutputAudioBitrate ?? 0) + (state.OutputVideoBitrate ?? 0);
var builder = new StringBuilder();
@@ -487,14 +492,14 @@ namespace Jellyfin.Api.Helpers
if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
{
- string profile = state.GetRequestedProfiles("h264").FirstOrDefault();
+ string? profile = state.GetRequestedProfiles("h264").FirstOrDefault();
return HlsCodecStringHelpers.GetH264String(profile, level);
}
if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
|| string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase))
{
- string profile = state.GetRequestedProfiles("h265").FirstOrDefault();
+ string? profile = state.GetRequestedProfiles("h265").FirstOrDefault();
return HlsCodecStringHelpers.GetH265String(profile, level);
}
diff --git a/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs b/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs
index 6b516977e8..cfa2c1229a 100644
--- a/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs
+++ b/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs
@@ -24,12 +24,14 @@ namespace Jellyfin.Api.Helpers
/// Whether the current request is a HTTP HEAD request so only the headers get returned.
/// The making the remote request.
/// The current http context.
+ /// A cancellation token that can be used to cancel the operation.
/// A containing the API response.
public static async Task GetStaticRemoteStreamResult(
StreamState state,
bool isHeadRequest,
HttpClient httpClient,
- HttpContext httpContext)
+ HttpContext httpContext,
+ CancellationToken cancellationToken = default)
{
if (state.RemoteHttpHeaders.TryGetValue(HeaderNames.UserAgent, out var useragent))
{
@@ -37,8 +39,8 @@ namespace Jellyfin.Api.Helpers
}
// Can't dispose the response as it's required up the call chain.
- var response = await httpClient.GetAsync(state.MediaPath).ConfigureAwait(false);
- var contentType = response.Content.Headers.ContentType.ToString();
+ var response = await httpClient.GetAsync(new Uri(state.MediaPath)).ConfigureAwait(false);
+ var contentType = response.Content.Headers.ContentType?.ToString();
httpContext.Response.Headers[HeaderNames.AcceptRanges] = "none";
@@ -47,7 +49,7 @@ namespace Jellyfin.Api.Helpers
return new FileContentResult(Array.Empty(), contentType);
}
- return new FileStreamResult(await response.Content.ReadAsStreamAsync().ConfigureAwait(false), contentType);
+ return new FileStreamResult(await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false), contentType);
}
///
@@ -123,9 +125,8 @@ namespace Jellyfin.Api.Helpers
state.Dispose();
}
- await new ProgressiveFileCopier(outputPath, job, transcodingJobHelper, CancellationToken.None)
- .WriteToAsync(httpContext.Response.Body, CancellationToken.None).ConfigureAwait(false);
- return new FileStreamResult(httpContext.Response.Body, contentType);
+ var stream = new ProgressiveFileStream(outputPath, job, transcodingJobHelper);
+ return new FileStreamResult(stream, contentType);
}
finally
{
diff --git a/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs b/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs
index 95f1906ef0..1bd3d67ff2 100644
--- a/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs
+++ b/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs
@@ -23,7 +23,7 @@ namespace Jellyfin.Api.Helpers
///
/// AAC profile.
/// AAC codec string.
- public static string GetAACString(string profile)
+ public static string GetAACString(string? profile)
{
StringBuilder result = new StringBuilder("mp4a", 9);
@@ -46,7 +46,7 @@ namespace Jellyfin.Api.Helpers
/// H.264 profile.
/// H.264 level.
/// H.264 string.
- public static string GetH264String(string profile, int level)
+ public static string GetH264String(string? profile, int level)
{
StringBuilder result = new StringBuilder("avc1", 11);
@@ -80,7 +80,7 @@ namespace Jellyfin.Api.Helpers
/// H.265 profile.
/// H.265 level.
/// H.265 string.
- public static string GetH265String(string profile, int level)
+ public static string GetH265String(string? profile, int level)
{
// The h265 syntax is a bit of a mystery at the time this comment was written.
// This is what I've found through various sources:
diff --git a/Jellyfin.Api/Helpers/HlsHelpers.cs b/Jellyfin.Api/Helpers/HlsHelpers.cs
index 2424966973..45ce905668 100644
--- a/Jellyfin.Api/Helpers/HlsHelpers.cs
+++ b/Jellyfin.Api/Helpers/HlsHelpers.cs
@@ -45,6 +45,11 @@ namespace Jellyfin.Api.Helpers
while (!reader.EndOfStream)
{
var line = await reader.ReadLineAsync().ConfigureAwait(false);
+ if (line == null)
+ {
+ // Nothing currently in buffer.
+ break;
+ }
if (line.IndexOf("#EXTINF:", StringComparison.OrdinalIgnoreCase) != -1)
{
diff --git a/Jellyfin.Api/Helpers/MediaInfoHelper.cs b/Jellyfin.Api/Helpers/MediaInfoHelper.cs
index 1207fb5134..0d8315dee1 100644
--- a/Jellyfin.Api/Helpers/MediaInfoHelper.cs
+++ b/Jellyfin.Api/Helpers/MediaInfoHelper.cs
@@ -166,7 +166,7 @@ namespace Jellyfin.Api.Helpers
MediaSourceInfo mediaSource,
DeviceProfile profile,
AuthorizationInfo auth,
- long? maxBitrate,
+ int? maxBitrate,
long startTimeTicks,
string mediaSourceId,
int? audioStreamIndex,
@@ -551,10 +551,10 @@ namespace Jellyfin.Api.Helpers
}
}
- private long? GetMaxBitrate(long? clientMaxBitrate, User user, string ipAddress)
+ private int? GetMaxBitrate(int? clientMaxBitrate, User user, string ipAddress)
{
var maxBitrate = clientMaxBitrate;
- var remoteClientMaxBitrate = user?.RemoteClientBitrateLimit ?? 0;
+ var remoteClientMaxBitrate = user.RemoteClientBitrateLimit ?? 0;
if (remoteClientMaxBitrate <= 0)
{
diff --git a/Jellyfin.Api/Helpers/ProgressiveFileCopier.cs b/Jellyfin.Api/Helpers/ProgressiveFileCopier.cs
index e00ed33042..8bddf00d5f 100644
--- a/Jellyfin.Api/Helpers/ProgressiveFileCopier.cs
+++ b/Jellyfin.Api/Helpers/ProgressiveFileCopier.cs
@@ -5,6 +5,7 @@ using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Api.Models.PlaybackDtos;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.IO;
@@ -90,6 +91,11 @@ namespace Jellyfin.Api.Helpers
allowAsyncFileRead = true;
}
+ if (_path == null)
+ {
+ throw new ResourceNotFoundException(nameof(_path));
+ }
+
await using var inputStream = new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, fileOptions);
var eofCount = 0;
diff --git a/Jellyfin.Api/Helpers/ProgressiveFileStream.cs b/Jellyfin.Api/Helpers/ProgressiveFileStream.cs
new file mode 100644
index 0000000000..824870c7ef
--- /dev/null
+++ b/Jellyfin.Api/Helpers/ProgressiveFileStream.cs
@@ -0,0 +1,166 @@
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Models.PlaybackDtos;
+using MediaBrowser.Model.IO;
+
+namespace Jellyfin.Api.Helpers
+{
+ ///
+ /// A progressive file stream for transferring transcoded files as they are written to.
+ ///
+ public class ProgressiveFileStream : Stream
+ {
+ private readonly FileStream _fileStream;
+ private readonly TranscodingJobDto? _job;
+ private readonly TranscodingJobHelper _transcodingJobHelper;
+ private readonly bool _allowAsyncFileRead;
+ private int _bytesWritten;
+ private bool _disposed;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The path to the transcoded file.
+ /// The transcoding job information.
+ /// The transcoding job helper.
+ public ProgressiveFileStream(string filePath, TranscodingJobDto? job, TranscodingJobHelper transcodingJobHelper)
+ {
+ _job = job;
+ _transcodingJobHelper = transcodingJobHelper;
+ _bytesWritten = 0;
+
+ var fileOptions = FileOptions.SequentialScan;
+ _allowAsyncFileRead = false;
+
+ // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
+ if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
+ {
+ fileOptions |= FileOptions.Asynchronous;
+ _allowAsyncFileRead = true;
+ }
+
+ _fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, fileOptions);
+ }
+
+ ///
+ public override bool CanRead => _fileStream.CanRead;
+
+ ///
+ public override bool CanSeek => false;
+
+ ///
+ public override bool CanWrite => false;
+
+ ///
+ public override long Length => throw new NotSupportedException();
+
+ ///
+ public override long Position
+ {
+ get => throw new NotSupportedException();
+ set => throw new NotSupportedException();
+ }
+
+ ///
+ public override void Flush()
+ {
+ _fileStream.Flush();
+ }
+
+ ///
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ return _fileStream.Read(buffer, offset, count);
+ }
+
+ ///
+ public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ {
+ int totalBytesRead = 0;
+ int remainingBytesToRead = count;
+
+ int newOffset = offset;
+ while (remainingBytesToRead > 0)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ int bytesRead;
+ if (_allowAsyncFileRead)
+ {
+ bytesRead = await _fileStream.ReadAsync(buffer, newOffset, remainingBytesToRead, cancellationToken).ConfigureAwait(false);
+ }
+ else
+ {
+ bytesRead = _fileStream.Read(buffer, newOffset, remainingBytesToRead);
+ }
+
+ remainingBytesToRead -= bytesRead;
+ newOffset += bytesRead;
+
+ if (bytesRead > 0)
+ {
+ _bytesWritten += bytesRead;
+ totalBytesRead += bytesRead;
+
+ if (_job != null)
+ {
+ _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten);
+ }
+ }
+ else
+ {
+ // If the job is null it's a live stream and will require user action to close
+ if (_job?.HasExited ?? false)
+ {
+ break;
+ }
+
+ await Task.Delay(50, cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ return totalBytesRead;
+ }
+
+ ///
+ public override long Seek(long offset, SeekOrigin origin)
+ => throw new NotSupportedException();
+
+ ///
+ public override void SetLength(long value)
+ => throw new NotSupportedException();
+
+ ///
+ public override void Write(byte[] buffer, int offset, int count)
+ => throw new NotSupportedException();
+
+ ///
+ protected override void Dispose(bool disposing)
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ try
+ {
+ if (disposing)
+ {
+ _fileStream.Dispose();
+
+ if (_job != null)
+ {
+ _transcodingJobHelper.OnTranscodeEndRequest(_job);
+ }
+ }
+ }
+ finally
+ {
+ _disposed = true;
+ base.Dispose(disposing);
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs
index 8dcf08af56..f06f038ab5 100644
--- a/Jellyfin.Api/Helpers/RequestHelpers.cs
+++ b/Jellyfin.Api/Helpers/RequestHelpers.cs
@@ -1,11 +1,14 @@
using System;
-using System.Collections.Generic;
using System.Linq;
-using System.Net;
+using Jellyfin.Data.Entities;
using Jellyfin.Data.Enums;
using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Http;
@@ -56,18 +59,6 @@ namespace Jellyfin.Api.Helpers
return result;
}
- ///
- /// Get parsed filters.
- ///
- /// The filters.
- /// Item filters.
- public static IEnumerable GetFilters(string? filters)
- {
- return string.IsNullOrEmpty(filters)
- ? Array.Empty()
- : filters.Split(',').Select(v => Enum.Parse(v, true));
- }
-
///
/// Splits a string at a separating character into an array of substrings.
///
@@ -83,7 +74,7 @@ namespace Jellyfin.Api.Helpers
}
return removeEmpty
- ? value.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries)
+ ? value.Split(separator, StringSplitOptions.RemoveEmptyEntries)
: value.Split(separator);
}
@@ -173,5 +164,40 @@ namespace Jellyfin.Api.Helpers
.Select(i => i!.Value)
.ToArray();
}
+
+ internal static QueryResult CreateQueryResult(
+ QueryResult<(BaseItem, ItemCounts)> result,
+ DtoOptions dtoOptions,
+ IDtoService dtoService,
+ bool includeItemTypes,
+ User? user)
+ {
+ var dtos = result.Items.Select(i =>
+ {
+ var (baseItem, counts) = i;
+ var dto = dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user);
+
+ if (includeItemTypes)
+ {
+ dto.ChildCount = counts.ItemCount;
+ dto.ProgramCount = counts.ProgramCount;
+ dto.SeriesCount = counts.SeriesCount;
+ dto.EpisodeCount = counts.EpisodeCount;
+ dto.MovieCount = counts.MovieCount;
+ dto.TrailerCount = counts.TrailerCount;
+ dto.AlbumCount = counts.AlbumCount;
+ dto.SongCount = counts.SongCount;
+ dto.ArtistCount = counts.ArtistCount;
+ }
+
+ return dto;
+ });
+
+ return new QueryResult
+ {
+ Items = dtos.ToArray(),
+ TotalRecordCount = result.TotalRecordCount
+ };
+ }
}
}
diff --git a/Jellyfin.Api/Helpers/SimilarItemsHelper.cs b/Jellyfin.Api/Helpers/SimilarItemsHelper.cs
deleted file mode 100644
index b922e76cfd..0000000000
--- a/Jellyfin.Api/Helpers/SimilarItemsHelper.cs
+++ /dev/null
@@ -1,182 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using MediaBrowser.Controller.Dto;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Dto;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Querying;
-
-namespace Jellyfin.Api.Helpers
-{
- ///
- /// The similar items helper class.
- ///
- public static class SimilarItemsHelper
- {
- internal static QueryResult GetSimilarItemsResult(
- DtoOptions dtoOptions,
- IUserManager userManager,
- ILibraryManager libraryManager,
- IDtoService dtoService,
- Guid? userId,
- string id,
- string? excludeArtistIds,
- int? limit,
- Type[] includeTypes,
- Func, List, BaseItem, int> getSimilarityScore)
- {
- var user = userId.HasValue && !userId.Equals(Guid.Empty)
- ? userManager.GetUserById(userId.Value)
- : null;
-
- var item = string.IsNullOrEmpty(id) ?
- (!userId.Equals(Guid.Empty) ? libraryManager.GetUserRootFolder() :
- libraryManager.RootFolder) : libraryManager.GetItemById(id);
-
- var query = new InternalItemsQuery(user)
- {
- IncludeItemTypes = includeTypes.Select(i => i.Name).ToArray(),
- Recursive = true,
- DtoOptions = dtoOptions,
- ExcludeArtistIds = RequestHelpers.GetGuids(excludeArtistIds)
- };
-
- var inputItems = libraryManager.GetItemList(query);
-
- var items = GetSimilaritems(item, libraryManager, inputItems, getSimilarityScore)
- .ToList();
-
- var returnItems = items;
-
- if (limit.HasValue)
- {
- returnItems = returnItems.Take(limit.Value).ToList();
- }
-
- var dtos = dtoService.GetBaseItemDtos(returnItems, dtoOptions, user);
-
- return new QueryResult
- {
- Items = dtos,
- TotalRecordCount = items.Count
- };
- }
-
- ///
- /// Gets the similaritems.
- ///
- /// The item.
- /// The library manager.
- /// The input items.
- /// The get similarity score.
- /// IEnumerable{BaseItem}.
- private static IEnumerable GetSimilaritems(
- BaseItem item,
- ILibraryManager libraryManager,
- IEnumerable inputItems,
- Func, List, BaseItem, int> getSimilarityScore)
- {
- var itemId = item.Id;
- inputItems = inputItems.Where(i => i.Id != itemId);
- var itemPeople = libraryManager.GetPeople(item);
- var allPeople = libraryManager.GetPeople(new InternalPeopleQuery
- {
- AppearsInItemId = item.Id
- });
-
- return inputItems.Select(i => new Tuple(i, getSimilarityScore(item, itemPeople, allPeople, i)))
- .Where(i => i.Item2 > 2)
- .OrderByDescending(i => i.Item2)
- .Select(i => i.Item1);
- }
-
- private static IEnumerable GetTags(BaseItem item)
- {
- return item.Tags;
- }
-
- ///
- /// Gets the similiarity score.
- ///
- /// The item1.
- /// The item1 people.
- /// All people.
- /// The item2.
- /// System.Int32.
- internal static int GetSimiliarityScore(BaseItem item1, List item1People, List allPeople, BaseItem item2)
- {
- var points = 0;
-
- if (!string.IsNullOrEmpty(item1.OfficialRating) && string.Equals(item1.OfficialRating, item2.OfficialRating, StringComparison.OrdinalIgnoreCase))
- {
- points += 10;
- }
-
- // Find common genres
- points += item1.Genres.Where(i => item2.Genres.Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 10);
-
- // Find common tags
- points += GetTags(item1).Where(i => GetTags(item2).Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 10);
-
- // Find common studios
- points += item1.Studios.Where(i => item2.Studios.Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 3);
-
- var item2PeopleNames = allPeople.Where(i => i.ItemId == item2.Id)
- .Select(i => i.Name)
- .Where(i => !string.IsNullOrWhiteSpace(i))
- .DistinctNames()
- .ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
-
- points += item1People.Where(i => item2PeopleNames.ContainsKey(i.Name)).Sum(i =>
- {
- if (string.Equals(i.Type, PersonType.Director, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
- {
- return 5;
- }
-
- if (string.Equals(i.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
-
- if (string.Equals(i.Type, PersonType.Composer, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Composer, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
-
- if (string.Equals(i.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
-
- if (string.Equals(i.Type, PersonType.Writer, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
- {
- return 2;
- }
-
- return 1;
- });
-
- if (item1.ProductionYear.HasValue && item2.ProductionYear.HasValue)
- {
- var diff = Math.Abs(item1.ProductionYear.Value - item2.ProductionYear.Value);
-
- // Add if they came out within the same decade
- if (diff < 10)
- {
- points += 2;
- }
-
- // And more if within five years
- if (diff < 5)
- {
- points += 2;
- }
- }
-
- return points;
- }
- }
-}
diff --git a/Jellyfin.Api/Helpers/StreamingHelpers.cs b/Jellyfin.Api/Helpers/StreamingHelpers.cs
index f4ec29bdef..0566f4c4dd 100644
--- a/Jellyfin.Api/Helpers/StreamingHelpers.cs
+++ b/Jellyfin.Api/Helpers/StreamingHelpers.cs
@@ -83,8 +83,12 @@ namespace Jellyfin.Api.Helpers
}
streamingRequest.StreamOptions = ParseStreamOptions(httpRequest.Query);
+ if (httpRequest.Path.Value == null)
+ {
+ throw new ResourceNotFoundException(nameof(httpRequest.Path));
+ }
- var url = httpRequest.Path.Value.Split('.').Last();
+ var url = httpRequest.Path.Value.Split('.')[^1];
if (string.IsNullOrEmpty(streamingRequest.AudioCodec))
{
diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs
index 64d1227f7c..168dc27a83 100644
--- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs
+++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs
@@ -12,6 +12,7 @@ using Jellyfin.Api.Models.PlaybackDtos;
using Jellyfin.Api.Models.StreamingDtos;
using Jellyfin.Data.Enums;
using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
@@ -102,7 +103,7 @@ namespace Jellyfin.Api.Helpers
///
/// Playback session id.
/// The transcoding job.
- public TranscodingJobDto GetTranscodingJob(string playSessionId)
+ public TranscodingJobDto? GetTranscodingJob(string playSessionId)
{
lock (_activeTranscodingJobs)
{
@@ -116,7 +117,7 @@ namespace Jellyfin.Api.Helpers
/// Path to the transcoding file.
/// The .
/// The transcoding job.
- public TranscodingJobDto GetTranscodingJob(string path, TranscodingJobType type)
+ public TranscodingJobDto? GetTranscodingJob(string path, TranscodingJobType type)
{
lock (_activeTranscodingJobs)
{
@@ -193,10 +194,9 @@ namespace Jellyfin.Api.Helpers
/// Called when [transcode kill timer stopped].
///
/// The state.
- private async void OnTranscodeKillTimerStopped(object state)
+ private async void OnTranscodeKillTimerStopped(object? state)
{
- var job = (TranscodingJobDto)state;
-
+ var job = state as TranscodingJobDto ?? throw new ArgumentException($"{nameof(state)} is not of type {nameof(TranscodingJobDto)}", nameof(state));
if (!job.HasExited && job.Type != TranscodingJobType.Progressive)
{
var timeSinceLastPing = (DateTime.UtcNow - job.LastPingDate).TotalMilliseconds;
@@ -489,7 +489,8 @@ namespace Jellyfin.Api.Helpers
CancellationTokenSource cancellationTokenSource,
string? workingDirectory = null)
{
- Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
+ var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
+ Directory.CreateDirectory(directory);
await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false);
@@ -523,7 +524,7 @@ namespace Jellyfin.Api.Helpers
RedirectStandardInput = true,
FileName = _mediaEncoder.EncoderPath,
Arguments = commandLineArguments,
- WorkingDirectory = string.IsNullOrWhiteSpace(workingDirectory) ? null : workingDirectory,
+ WorkingDirectory = string.IsNullOrWhiteSpace(workingDirectory) ? string.Empty : workingDirectory,
ErrorDialog = false
},
EnableRaisingEvents = true
@@ -740,10 +741,7 @@ namespace Jellyfin.Api.Helpers
/// The state.
private void OnFfMpegProcessExited(Process process, TranscodingJobDto job, StreamState state)
{
- if (job != null)
- {
- job.HasExited = true;
- }
+ job.HasExited = true;
_logger.LogDebug("Disposing stream resources");
state.Dispose();
@@ -830,7 +828,7 @@ namespace Jellyfin.Api.Helpers
{
lock (_transcodingLocks)
{
- if (!_transcodingLocks.TryGetValue(outputPath, out SemaphoreSlim result))
+ if (!_transcodingLocks.TryGetValue(outputPath, out SemaphoreSlim? result))
{
result = new SemaphoreSlim(1, 1);
_transcodingLocks[outputPath] = result;
@@ -840,7 +838,7 @@ namespace Jellyfin.Api.Helpers
}
}
- private void OnPlaybackProgress(object sender, PlaybackProgressEventArgs e)
+ private void OnPlaybackProgress(object? sender, PlaybackProgressEventArgs e)
{
if (!string.IsNullOrWhiteSpace(e.PlaySessionId))
{
diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj
index c27dce8ddf..da6e5fa2d4 100644
--- a/Jellyfin.Api/Jellyfin.Api.csproj
+++ b/Jellyfin.Api/Jellyfin.Api.csproj
@@ -6,19 +6,21 @@
- netstandard2.1
+ net5.0
true
true
enable
+
+ AD0001
-
+
-
-
-
+
+
+
diff --git a/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs
new file mode 100644
index 0000000000..e90f48d2fe
--- /dev/null
+++ b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs
@@ -0,0 +1,90 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.ModelBinders
+{
+ ///
+ /// Comma delimited array model binder.
+ /// Returns an empty array of specified type if there is no query parameter.
+ ///
+ public class CommaDelimitedArrayModelBinder : IModelBinder
+ {
+ private readonly ILogger _logger;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Instance of the interface.
+ public CommaDelimitedArrayModelBinder(ILogger logger)
+ {
+ _logger = logger;
+ }
+
+ ///
+ public Task BindModelAsync(ModelBindingContext bindingContext)
+ {
+ var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
+ var elementType = bindingContext.ModelType.GetElementType() ?? bindingContext.ModelType.GenericTypeArguments[0];
+ var converter = TypeDescriptor.GetConverter(elementType);
+
+ if (valueProviderResult.Length > 1)
+ {
+ var typedValues = GetParsedResult(valueProviderResult.Values, elementType, converter);
+ bindingContext.Result = ModelBindingResult.Success(typedValues);
+ }
+ else
+ {
+ var value = valueProviderResult.FirstValue;
+
+ if (value != null)
+ {
+ var splitValues = value.Split(',', StringSplitOptions.RemoveEmptyEntries);
+ var typedValues = GetParsedResult(splitValues, elementType, converter);
+ bindingContext.Result = ModelBindingResult.Success(typedValues);
+ }
+ else
+ {
+ var emptyResult = Array.CreateInstance(elementType, 0);
+ bindingContext.Result = ModelBindingResult.Success(emptyResult);
+ }
+ }
+
+ return Task.CompletedTask;
+ }
+
+ private Array GetParsedResult(IReadOnlyList values, Type elementType, TypeConverter converter)
+ {
+ var parsedValues = new object?[values.Count];
+ var convertedCount = 0;
+ for (var i = 0; i < values.Count; i++)
+ {
+ try
+ {
+ parsedValues[i] = converter.ConvertFromString(values[i].Trim());
+ convertedCount++;
+ }
+ catch (FormatException e)
+ {
+ _logger.LogWarning(e, "Error converting value.");
+ }
+ }
+
+ var typedValues = Array.CreateInstance(elementType, convertedCount);
+ var typedValueIndex = 0;
+ for (var i = 0; i < parsedValues.Length; i++)
+ {
+ if (parsedValues[i] != null)
+ {
+ typedValues.SetValue(parsedValues[i], typedValueIndex);
+ typedValueIndex++;
+ }
+ }
+
+ return typedValues;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Models/LibraryDtos/LibraryOptionsResultDto.cs b/Jellyfin.Api/Models/LibraryDtos/LibraryOptionsResultDto.cs
index 33eda33cb9..7de44aa659 100644
--- a/Jellyfin.Api/Models/LibraryDtos/LibraryOptionsResultDto.cs
+++ b/Jellyfin.Api/Models/LibraryDtos/LibraryOptionsResultDto.cs
@@ -1,4 +1,5 @@
-using System.Diagnostics.CodeAnalysis;
+using System;
+using System.Collections.Generic;
namespace Jellyfin.Api.Models.LibraryDtos
{
@@ -10,25 +11,21 @@ namespace Jellyfin.Api.Models.LibraryDtos
///
/// Gets or sets the metadata savers.
///
- [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "MetadataSavers", Justification = "Imported from ServiceStack")]
- public LibraryOptionInfoDto[] MetadataSavers { get; set; } = null!;
+ public IReadOnlyList MetadataSavers { get; set; } = Array.Empty();
///
/// Gets or sets the metadata readers.
///
- [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "MetadataReaders", Justification = "Imported from ServiceStack")]
- public LibraryOptionInfoDto[] MetadataReaders { get; set; } = null!;
+ public IReadOnlyList MetadataReaders { get; set; } = Array.Empty();
///
/// Gets or sets the subtitle fetchers.
///
- [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "SubtitleFetchers", Justification = "Imported from ServiceStack")]
- public LibraryOptionInfoDto[] SubtitleFetchers { get; set; } = null!;
+ public IReadOnlyList SubtitleFetchers { get; set; } = Array.Empty();
///
/// Gets or sets the type options.
///
- [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "TypeOptions", Justification = "Imported from ServiceStack")]
- public LibraryTypeOptionsDto[] TypeOptions { get; set; } = null!;
+ public IReadOnlyList TypeOptions { get; set; } = Array.Empty();
}
}
diff --git a/Jellyfin.Api/Models/LibraryDtos/LibraryTypeOptionsDto.cs b/Jellyfin.Api/Models/LibraryDtos/LibraryTypeOptionsDto.cs
index ad031e95e5..20f45196d2 100644
--- a/Jellyfin.Api/Models/LibraryDtos/LibraryTypeOptionsDto.cs
+++ b/Jellyfin.Api/Models/LibraryDtos/LibraryTypeOptionsDto.cs
@@ -1,4 +1,5 @@
-using System.Diagnostics.CodeAnalysis;
+using System;
+using System.Collections.Generic;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
@@ -17,25 +18,21 @@ namespace Jellyfin.Api.Models.LibraryDtos
///
/// Gets or sets the metadata fetchers.
///
- [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "MetadataFetchers", Justification = "Imported from ServiceStack")]
- public LibraryOptionInfoDto[] MetadataFetchers { get; set; } = null!;
+ public IReadOnlyList MetadataFetchers { get; set; } = Array.Empty();
///
/// Gets or sets the image fetchers.
///
- [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "ImageFetchers", Justification = "Imported from ServiceStack")]
- public LibraryOptionInfoDto[] ImageFetchers { get; set; } = null!;
+ public IReadOnlyList ImageFetchers { get; set; } = Array.Empty();
///
/// Gets or sets the supported image types.
///
- [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "SupportedImageTypes", Justification = "Imported from ServiceStack")]
- public ImageType[] SupportedImageTypes { get; set; } = null!;
+ public IReadOnlyList SupportedImageTypes { get; set; } = Array.Empty();
///
/// Gets or sets the default image options.
///
- [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "DefaultImageOptions", Justification = "Imported from ServiceStack")]
- public ImageOption[] DefaultImageOptions { get; set; } = null!;
+ public IReadOnlyList DefaultImageOptions { get; set; } = Array.Empty();
}
}
diff --git a/Jellyfin.Api/Models/LiveTvDtos/ChannelMappingOptionsDto.cs b/Jellyfin.Api/Models/LiveTvDtos/ChannelMappingOptionsDto.cs
index 970d8acdbc..f43822da77 100644
--- a/Jellyfin.Api/Models/LiveTvDtos/ChannelMappingOptionsDto.cs
+++ b/Jellyfin.Api/Models/LiveTvDtos/ChannelMappingOptionsDto.cs
@@ -1,4 +1,5 @@
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.Dto;
@@ -25,8 +26,7 @@ namespace Jellyfin.Api.Models.LiveTvDtos
///
/// Gets or sets list of mappings.
///
- [SuppressMessage("Microsoft.Performance", "CA1819:DontReturnArrays", MessageId = "Mappings", Justification = "Imported from ServiceStack")]
- public NameValuePair[] Mappings { get; set; } = null!;
+ public IReadOnlyList Mappings { get; set; } = Array.Empty();
///
/// Gets or sets provider name.
diff --git a/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs b/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs
index d7eaab30de..5ca4408d18 100644
--- a/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs
+++ b/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs
@@ -1,4 +1,10 @@
using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json.Serialization;
+using MediaBrowser.Common.Json.Converters;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Querying;
namespace Jellyfin.Api.Models.LiveTvDtos
{
@@ -137,7 +143,8 @@ namespace Jellyfin.Api.Models.LiveTvDtos
/// Gets or sets the image types to include in the output.
/// Optional.
///
- public string? EnableImageTypes { get; set; }
+ [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))]
+ public IReadOnlyList EnableImageTypes { get; set; } = Array.Empty();
///
/// Gets or sets include user data.
@@ -161,6 +168,7 @@ namespace Jellyfin.Api.Models.LiveTvDtos
/// Gets or sets 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.
/// Optional.
///
- public string? Fields { get; set; }
+ [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))]
+ public IReadOnlyList Fields { get; set; } = Array.Empty();
}
}
diff --git a/Jellyfin.Api/Models/MediaInfoDtos/OpenLiveStreamDto.cs b/Jellyfin.Api/Models/MediaInfoDtos/OpenLiveStreamDto.cs
index f797a38076..b0b3de8553 100644
--- a/Jellyfin.Api/Models/MediaInfoDtos/OpenLiveStreamDto.cs
+++ b/Jellyfin.Api/Models/MediaInfoDtos/OpenLiveStreamDto.cs
@@ -1,4 +1,5 @@
-using System.Diagnostics.CodeAnalysis;
+using System;
+using System.Collections.Generic;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.MediaInfo;
@@ -17,8 +18,6 @@ namespace Jellyfin.Api.Models.MediaInfoDtos
///
/// Gets or sets the device play protocols.
///
- [SuppressMessage("Microsoft.Performance", "CA1819:DontReturnArrays", MessageId = "DevicePlayProtocols", Justification = "Imported from ServiceStack")]
- [SuppressMessage("Microsoft.Performance", "SA1011:ClosingBracketsSpace", MessageId = "DevicePlayProtocols", Justification = "Imported from ServiceStack")]
- public MediaProtocol[]? DirectPlayProtocols { get; set; }
+ public IReadOnlyList DirectPlayProtocols { get; set; } = Array.Empty();
}
}
diff --git a/Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs b/Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs
index b9507a4e50..9edc19bb6d 100644
--- a/Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs
+++ b/Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs
@@ -196,7 +196,7 @@ namespace Jellyfin.Api.Models.PlaybackDtos
/// Start kill timer.
///
/// Callback action.
- public void StartKillTimer(Action
-
-
+
+
diff --git a/Jellyfin.Data/Queries/ActivityLogQuery.cs b/Jellyfin.Data/Queries/ActivityLogQuery.cs
new file mode 100644
index 0000000000..92919d3a51
--- /dev/null
+++ b/Jellyfin.Data/Queries/ActivityLogQuery.cs
@@ -0,0 +1,30 @@
+using System;
+
+namespace Jellyfin.Data.Queries
+{
+ ///
+ /// A class representing a query to the activity logs.
+ ///
+ public class ActivityLogQuery
+ {
+ ///
+ /// Gets or sets the index to start at.
+ ///
+ public int? StartIndex { get; set; }
+
+ ///
+ /// Gets or sets the maximum number of items to include.
+ ///
+ public int? Limit { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether to take entries with a user id.
+ ///
+ public bool? HasUserId { get; set; }
+
+ ///
+ /// Gets or sets the minimum date to query for.
+ ///
+ public DateTime? MinDate { get; set; }
+ }
+}
diff --git a/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj b/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj
index f86b142449..466a12e676 100644
--- a/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj
+++ b/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj
@@ -6,7 +6,7 @@
- netstandard2.1
+ net5.0
false
true
true
@@ -18,8 +18,8 @@
-
-
+
+
diff --git a/Jellyfin.Drawing.Skia/SkiaEncoder.cs b/Jellyfin.Drawing.Skia/SkiaEncoder.cs
index a1caa751b1..ee60748c71 100644
--- a/Jellyfin.Drawing.Skia/SkiaEncoder.cs
+++ b/Jellyfin.Drawing.Skia/SkiaEncoder.cs
@@ -4,6 +4,7 @@ using System.Globalization;
using System.IO;
using BlurHashSharp.SkiaSharp;
using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Extensions;
using MediaBrowser.Model.Drawing;
@@ -227,8 +228,8 @@ namespace Jellyfin.Drawing.Skia
}
var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + Path.GetExtension(path));
-
- Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
+ var directory = Path.GetDirectoryName(tempPath) ?? throw new ResourceNotFoundException($"Provided path ({tempPath}) is not valid.");
+ Directory.CreateDirectory(directory);
File.Copy(path, tempPath, true);
return tempPath;
@@ -493,7 +494,8 @@ namespace Jellyfin.Drawing.Skia
// If all we're doing is resizing then we can stop now
if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
{
- Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
+ var outputDirectory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
+ Directory.CreateDirectory(outputDirectory);
using var outputStream = new SKFileWStream(outputPath);
using var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels());
resizedBitmap.Encode(outputStream, skiaOutputFormat, quality);
@@ -540,7 +542,8 @@ namespace Jellyfin.Drawing.Skia
DrawIndicator(canvas, width, height, options);
}
- Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
+ var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
+ Directory.CreateDirectory(directory);
using (var outputStream = new SKFileWStream(outputPath))
{
using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()))
@@ -553,13 +556,13 @@ namespace Jellyfin.Drawing.Skia
}
///
- public void CreateImageCollage(ImageCollageOptions options)
+ public void CreateImageCollage(ImageCollageOptions options, string? libraryName)
{
double ratio = (double)options.Width / options.Height;
if (ratio >= 1.4)
{
- new StripCollageBuilder(this).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
+ new StripCollageBuilder(this).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height, libraryName);
}
else if (ratio >= .9)
{
diff --git a/Jellyfin.Drawing.Skia/StripCollageBuilder.cs b/Jellyfin.Drawing.Skia/StripCollageBuilder.cs
index 10bb59648f..0e94f87f6a 100644
--- a/Jellyfin.Drawing.Skia/StripCollageBuilder.cs
+++ b/Jellyfin.Drawing.Skia/StripCollageBuilder.cs
@@ -82,48 +82,62 @@ namespace Jellyfin.Drawing.Skia
/// The path at which to place the resulting image.
/// The desired width of the collage.
/// The desired height of the collage.
- public void BuildThumbCollage(string[] paths, string outputPath, int width, int height)
+ /// The name of the library to draw on the collage.
+ public void BuildThumbCollage(string[] paths, string outputPath, int width, int height, string? libraryName)
{
- using var bitmap = BuildThumbCollageBitmap(paths, width, height);
+ using var bitmap = BuildThumbCollageBitmap(paths, width, height, libraryName);
using var outputStream = new SKFileWStream(outputPath);
using var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels());
pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90);
}
- private SKBitmap BuildThumbCollageBitmap(string[] paths, int width, int height)
+ private SKBitmap BuildThumbCollageBitmap(string[] paths, int width, int height, string? libraryName)
{
var bitmap = new SKBitmap(width, height);
using var canvas = new SKCanvas(bitmap);
canvas.Clear(SKColors.Black);
- // number of images used in the thumbnail
- var iCount = 3;
-
- // determine sizes for each image that will composited into the final image
- var iSlice = Convert.ToInt32(width / iCount);
- int iHeight = Convert.ToInt32(height * 1.00);
- int imageIndex = 0;
- for (int i = 0; i < iCount; i++)
+ using var backdrop = GetNextValidImage(paths, 0, out _);
+ if (backdrop == null)
{
- using var currentBitmap = GetNextValidImage(paths, imageIndex, out int newIndex);
- imageIndex = newIndex;
- if (currentBitmap == null)
- {
- continue;
- }
-
- // resize to the same aspect as the original
- int iWidth = Math.Abs(iHeight * currentBitmap.Width / currentBitmap.Height);
- using var resizedImage = SkiaEncoder.ResizeImage(currentBitmap, new SKImageInfo(iWidth, iHeight, currentBitmap.ColorType, currentBitmap.AlphaType, currentBitmap.ColorSpace));
-
- // crop image
- int ix = Math.Abs((iWidth - iSlice) / 2);
- using var subset = resizedImage.Subset(SKRectI.Create(ix, 0, iSlice, iHeight));
- // draw image onto canvas
- canvas.DrawImage(subset ?? resizedImage, iSlice * i, 0);
+ return bitmap;
}
+ // resize to the same aspect as the original
+ var backdropHeight = Math.Abs(width * backdrop.Height / backdrop.Width);
+ using var residedBackdrop = SkiaEncoder.ResizeImage(backdrop, new SKImageInfo(width, backdropHeight, backdrop.ColorType, backdrop.AlphaType, backdrop.ColorSpace));
+ // draw the backdrop
+ canvas.DrawImage(residedBackdrop, 0, 0);
+
+ // draw shadow rectangle
+ var paintColor = new SKPaint
+ {
+ Color = SKColors.Black.WithAlpha(0x78),
+ Style = SKPaintStyle.Fill
+ };
+ canvas.DrawRect(0, 0, width, height, paintColor);
+
+ // draw library name
+ var textPaint = new SKPaint
+ {
+ Color = SKColors.White,
+ Style = SKPaintStyle.Fill,
+ TextSize = 112,
+ TextAlign = SKTextAlign.Center,
+ Typeface = SKTypeface.FromFamilyName("sans-serif", SKFontStyleWeight.Bold, SKFontStyleWidth.Normal, SKFontStyleSlant.Upright),
+ IsAntialias = true
+ };
+
+ // scale down text to 90% of the width if text is larger than 95% of the width
+ var textWidth = textPaint.MeasureText(libraryName);
+ if (textWidth > width * 0.95)
+ {
+ textPaint.TextSize = 0.9f * width * textPaint.TextSize / textWidth;
+ }
+
+ canvas.DrawText(libraryName, width / 2f, (height / 2f) + (textPaint.FontMetrics.XHeight / 2), textPaint);
+
return bitmap;
}
diff --git a/Jellyfin.Server.Implementations/Activity/ActivityManager.cs b/Jellyfin.Server.Implementations/Activity/ActivityManager.cs
index abdd290d45..7bde4f35be 100644
--- a/Jellyfin.Server.Implementations/Activity/ActivityManager.cs
+++ b/Jellyfin.Server.Implementations/Activity/ActivityManager.cs
@@ -3,8 +3,10 @@ using System.Linq;
using System.Threading.Tasks;
using Jellyfin.Data.Entities;
using Jellyfin.Data.Events;
+using Jellyfin.Data.Queries;
using MediaBrowser.Model.Activity;
using MediaBrowser.Model.Querying;
+using Microsoft.EntityFrameworkCore;
namespace Jellyfin.Server.Implementations.Activity
{
@@ -39,39 +41,47 @@ namespace Jellyfin.Server.Implementations.Activity
}
///
- public QueryResult GetPagedResult(
- Func, IQueryable> func,
- int? startIndex,
- int? limit)
+ public async Task> GetPagedResultAsync(ActivityLogQuery query)
{
- using var dbContext = _provider.CreateContext();
+ await using var dbContext = _provider.CreateContext();
- var query = func(dbContext.ActivityLogs.OrderByDescending(entry => entry.DateCreated));
+ IQueryable entries = dbContext.ActivityLogs
+ .AsQueryable()
+ .OrderByDescending(entry => entry.DateCreated);
- if (startIndex.HasValue)
+ if (query.MinDate.HasValue)
{
- query = query.Skip(startIndex.Value);
+ entries = entries.Where(entry => entry.DateCreated >= query.MinDate);
}
- if (limit.HasValue)
+ if (query.HasUserId.HasValue)
{
- query = query.Take(limit.Value);
+ entries = entries.Where(entry => entry.UserId != Guid.Empty == query.HasUserId.Value );
}
- // This converts the objects from the new database model to the old for compatibility with the existing API.
- var list = query.Select(ConvertToOldModel).ToList();
-
return new QueryResult
{
- Items = list,
- TotalRecordCount = func(dbContext.ActivityLogs).Count()
+ Items = await entries
+ .Skip(query.StartIndex ?? 0)
+ .Take(query.Limit ?? 100)
+ .AsAsyncEnumerable()
+ .Select(ConvertToOldModel)
+ .ToListAsync()
+ .ConfigureAwait(false),
+ TotalRecordCount = await entries.CountAsync().ConfigureAwait(false)
};
}
- ///
- public QueryResult GetPagedResult(int? startIndex, int? limit)
+ ///
+ public async Task CleanAsync(DateTime startDate)
{
- return GetPagedResult(logs => logs, startIndex, limit);
+ await using var dbContext = _provider.CreateContext();
+ var entries = dbContext.ActivityLogs
+ .AsQueryable()
+ .Where(entry => entry.DateCreated <= startDate);
+
+ dbContext.RemoveRange(entries);
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
}
private static ActivityLogEntry ConvertToOldModel(ActivityLog entry)
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/System/TaskCompletedNotifier.cs b/Jellyfin.Server.Implementations/Events/Consumers/System/TaskCompletedNotifier.cs
index 80ed56cd8f..0993c6df7b 100644
--- a/Jellyfin.Server.Implementations/Events/Consumers/System/TaskCompletedNotifier.cs
+++ b/Jellyfin.Server.Implementations/Events/Consumers/System/TaskCompletedNotifier.cs
@@ -2,6 +2,7 @@
using System.Threading.Tasks;
using MediaBrowser.Controller.Events;
using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
using MediaBrowser.Model.Tasks;
namespace Jellyfin.Server.Implementations.Events.Consumers.System
@@ -25,7 +26,7 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.System
///
public async Task OnEvent(TaskCompletionEventArgs eventArgs)
{
- await _sessionManager.SendMessageToAdminSessions("ScheduledTaskEnded", eventArgs.Result, CancellationToken.None).ConfigureAwait(false);
+ await _sessionManager.SendMessageToAdminSessions(SessionMessageType.ScheduledTaskEnded, eventArgs.Result, CancellationToken.None).ConfigureAwait(false);
}
}
}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationCancelledNotifier.cs b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationCancelledNotifier.cs
index 1c600683a9..1d790da6b2 100644
--- a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationCancelledNotifier.cs
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationCancelledNotifier.cs
@@ -3,6 +3,7 @@ using System.Threading.Tasks;
using MediaBrowser.Controller.Events;
using MediaBrowser.Controller.Events.Updates;
using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
{
@@ -25,7 +26,7 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
///
public async Task OnEvent(PluginInstallationCancelledEventArgs eventArgs)
{
- await _sessionManager.SendMessageToAdminSessions("PackageInstallationCancelled", eventArgs.Argument, CancellationToken.None).ConfigureAwait(false);
+ await _sessionManager.SendMessageToAdminSessions(SessionMessageType.PackageInstallationCancelled, eventArgs.Argument, CancellationToken.None).ConfigureAwait(false);
}
}
}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationFailedNotifier.cs b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationFailedNotifier.cs
index ea0c878d42..a1faf18fc4 100644
--- a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationFailedNotifier.cs
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallationFailedNotifier.cs
@@ -3,6 +3,7 @@ using System.Threading.Tasks;
using MediaBrowser.Common.Updates;
using MediaBrowser.Controller.Events;
using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
{
@@ -25,7 +26,7 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
///
public async Task OnEvent(InstallationFailedEventArgs eventArgs)
{
- await _sessionManager.SendMessageToAdminSessions("PackageInstallationFailed", eventArgs.InstallationInfo, CancellationToken.None).ConfigureAwait(false);
+ await _sessionManager.SendMessageToAdminSessions(SessionMessageType.PackageInstallationFailed, eventArgs.InstallationInfo, CancellationToken.None).ConfigureAwait(false);
}
}
}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstalledNotifier.cs b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstalledNotifier.cs
index 3dda5a04c4..bd1a714045 100644
--- a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstalledNotifier.cs
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstalledNotifier.cs
@@ -3,6 +3,7 @@ using System.Threading.Tasks;
using MediaBrowser.Controller.Events;
using MediaBrowser.Controller.Events.Updates;
using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
{
@@ -25,7 +26,7 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
///
public async Task OnEvent(PluginInstalledEventArgs eventArgs)
{
- await _sessionManager.SendMessageToAdminSessions("PackageInstallationCompleted", eventArgs.Argument, CancellationToken.None).ConfigureAwait(false);
+ await _sessionManager.SendMessageToAdminSessions(SessionMessageType.PackageInstallationCompleted, eventArgs.Argument, CancellationToken.None).ConfigureAwait(false);
}
}
}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallingNotifier.cs b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallingNotifier.cs
index f691d11a7d..b513ac64ae 100644
--- a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallingNotifier.cs
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginInstallingNotifier.cs
@@ -3,6 +3,7 @@ using System.Threading.Tasks;
using MediaBrowser.Controller.Events;
using MediaBrowser.Controller.Events.Updates;
using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
{
@@ -25,7 +26,7 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
///
public async Task OnEvent(PluginInstallingEventArgs eventArgs)
{
- await _sessionManager.SendMessageToAdminSessions("PackageInstalling", eventArgs.Argument, CancellationToken.None).ConfigureAwait(false);
+ await _sessionManager.SendMessageToAdminSessions(SessionMessageType.PackageInstalling, eventArgs.Argument, CancellationToken.None).ConfigureAwait(false);
}
}
}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUninstalledNotifier.cs b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUninstalledNotifier.cs
index 709692f6bb..1fd7b9adfc 100644
--- a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUninstalledNotifier.cs
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUninstalledNotifier.cs
@@ -3,6 +3,7 @@ using System.Threading.Tasks;
using MediaBrowser.Controller.Events;
using MediaBrowser.Controller.Events.Updates;
using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
{
@@ -25,7 +26,7 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.Updates
///
public async Task OnEvent(PluginUninstalledEventArgs eventArgs)
{
- await _sessionManager.SendMessageToAdminSessions("PluginUninstalled", eventArgs.Argument, CancellationToken.None).ConfigureAwait(false);
+ await _sessionManager.SendMessageToAdminSessions(SessionMessageType.PackageUninstalled, eventArgs.Argument, CancellationToken.None).ConfigureAwait(false);
}
}
}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Users/UserDeletedNotifier.cs b/Jellyfin.Server.Implementations/Events/Consumers/Users/UserDeletedNotifier.cs
index 10367a939b..303e886210 100644
--- a/Jellyfin.Server.Implementations/Events/Consumers/Users/UserDeletedNotifier.cs
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Users/UserDeletedNotifier.cs
@@ -6,6 +6,7 @@ using System.Threading.Tasks;
using Jellyfin.Data.Events.Users;
using MediaBrowser.Controller.Events;
using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
namespace Jellyfin.Server.Implementations.Events.Consumers.Users
{
@@ -30,7 +31,7 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.Users
{
await _sessionManager.SendMessageToUserSessions(
new List { eventArgs.Argument.Id },
- "UserDeleted",
+ SessionMessageType.UserDeleted,
eventArgs.Argument.Id.ToString("N", CultureInfo.InvariantCulture),
CancellationToken.None).ConfigureAwait(false);
}
diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Users/UserUpdatedNotifier.cs b/Jellyfin.Server.Implementations/Events/Consumers/Users/UserUpdatedNotifier.cs
index 6081dd044f..a14911b94a 100644
--- a/Jellyfin.Server.Implementations/Events/Consumers/Users/UserUpdatedNotifier.cs
+++ b/Jellyfin.Server.Implementations/Events/Consumers/Users/UserUpdatedNotifier.cs
@@ -6,6 +6,7 @@ using Jellyfin.Data.Events.Users;
using MediaBrowser.Controller.Events;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Session;
namespace Jellyfin.Server.Implementations.Events.Consumers.Users
{
@@ -33,7 +34,7 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.Users
{
await _sessionManager.SendMessageToUserSessions(
new List { e.Argument.Id },
- "UserUpdated",
+ SessionMessageType.UserUpdated,
_userManager.GetUserDto(e.Argument),
CancellationToken.None).ConfigureAwait(false);
}
diff --git a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj
index 4e79dd8d6c..e663798da0 100644
--- a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj
+++ b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj
@@ -1,7 +1,7 @@
- netcoreapp3.1
+ net5.0
false
true
true
@@ -24,11 +24,12 @@
-
+
+
all
runtime; build; native; contentfiles; analyzers; buildtransitive
-
+
all
runtime; build; native; contentfiles; analyzers; buildtransitive
diff --git a/Jellyfin.Server.Implementations/Migrations/20201004171403_AddMaxActiveSessions.Designer.cs b/Jellyfin.Server.Implementations/Migrations/20201004171403_AddMaxActiveSessions.Designer.cs
new file mode 100644
index 0000000000..e5c326a326
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20201004171403_AddMaxActiveSessions.Designer.cs
@@ -0,0 +1,464 @@
+#pragma warning disable CS1591
+
+//
+using System;
+using Jellyfin.Server.Implementations;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ [DbContext(typeof(JellyfinDb))]
+ [Migration("20201004171403_AddMaxActiveSessions")]
+ partial class AddMaxActiveSessions
+ {
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasDefaultSchema("jellyfin")
+ .HasAnnotation("ProductVersion", "3.1.8");
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("DayOfWeek")
+ .HasColumnType("INTEGER");
+
+ b.Property("EndHour")
+ .HasColumnType("REAL");
+
+ b.Property("StartHour")
+ .HasColumnType("REAL");
+
+ b.Property("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("AccessSchedules");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ActivityLog", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("DateCreated")
+ .HasColumnType("TEXT");
+
+ b.Property("ItemId")
+ .HasColumnType("TEXT")
+ .HasMaxLength(256);
+
+ b.Property("LogSeverity")
+ .HasColumnType("INTEGER");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property("Overview")
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property("ShortOverview")
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property("Type")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(256);
+
+ b.Property("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("ActivityLogs");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("ChromecastVersion")
+ .HasColumnType("INTEGER");
+
+ b.Property("Client")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(32);
+
+ b.Property("DashboardTheme")
+ .HasColumnType("TEXT")
+ .HasMaxLength(32);
+
+ b.Property("EnableNextVideoInfoOverlay")
+ .HasColumnType("INTEGER");
+
+ b.Property("IndexBy")
+ .HasColumnType("INTEGER");
+
+ b.Property("ScrollDirection")
+ .HasColumnType("INTEGER");
+
+ b.Property("ShowBackdrop")
+ .HasColumnType("INTEGER");
+
+ b.Property("ShowSidebar")
+ .HasColumnType("INTEGER");
+
+ b.Property("SkipBackwardLength")
+ .HasColumnType("INTEGER");
+
+ b.Property("SkipForwardLength")
+ .HasColumnType("INTEGER");
+
+ b.Property("TvHome")
+ .HasColumnType("TEXT")
+ .HasMaxLength(32);
+
+ b.Property("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.HasIndex("UserId", "Client")
+ .IsUnique();
+
+ b.ToTable("DisplayPreferences");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.HomeSection", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("DisplayPreferencesId")
+ .HasColumnType("INTEGER");
+
+ b.Property("Order")
+ .HasColumnType("INTEGER");
+
+ b.Property("Type")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("DisplayPreferencesId");
+
+ b.ToTable("HomeSection");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property("Path")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(512);
+
+ b.Property("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId")
+ .IsUnique();
+
+ b.ToTable("ImageInfos");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("Client")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(32);
+
+ b.Property("IndexBy")
+ .HasColumnType("INTEGER");
+
+ b.Property("ItemId")
+ .HasColumnType("TEXT");
+
+ b.Property("RememberIndexing")
+ .HasColumnType("INTEGER");
+
+ b.Property("RememberSorting")
+ .HasColumnType("INTEGER");
+
+ b.Property("SortBy")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(64);
+
+ b.Property("SortOrder")
+ .HasColumnType("INTEGER");
+
+ b.Property("UserId")
+ .HasColumnType("TEXT");
+
+ b.Property("ViewType")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("ItemDisplayPreferences");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("Kind")
+ .HasColumnType("INTEGER");
+
+ b.Property("Permission_Permissions_Guid")
+ .HasColumnType("TEXT");
+
+ b.Property("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property("Value")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Permission_Permissions_Guid");
+
+ b.ToTable("Permissions");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("Kind")
+ .HasColumnType("INTEGER");
+
+ b.Property("Preference_Preferences_Guid")
+ .HasColumnType("TEXT");
+
+ b.Property("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property("Value")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(65535);
+
+ b.HasKey("Id");
+
+ b.HasIndex("Preference_Preferences_Guid");
+
+ b.ToTable("Preferences");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.User", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property("AudioLanguagePreference")
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.Property("AuthenticationProviderId")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.Property("DisplayCollectionsView")
+ .HasColumnType("INTEGER");
+
+ b.Property("DisplayMissingEpisodes")
+ .HasColumnType("INTEGER");
+
+ b.Property("EasyPassword")
+ .HasColumnType("TEXT")
+ .HasMaxLength(65535);
+
+ b.Property("EnableAutoLogin")
+ .HasColumnType("INTEGER");
+
+ b.Property("EnableLocalPassword")
+ .HasColumnType("INTEGER");
+
+ b.Property("EnableNextEpisodeAutoPlay")
+ .HasColumnType("INTEGER");
+
+ b.Property("EnableUserPreferenceAccess")
+ .HasColumnType("INTEGER");
+
+ b.Property("HidePlayedInLatest")
+ .HasColumnType("INTEGER");
+
+ b.Property("InternalId")
+ .HasColumnType("INTEGER");
+
+ b.Property("InvalidLoginAttemptCount")
+ .HasColumnType("INTEGER");
+
+ b.Property("LastActivityDate")
+ .HasColumnType("TEXT");
+
+ b.Property("LastLoginDate")
+ .HasColumnType("TEXT");
+
+ b.Property("LoginAttemptsBeforeLockout")
+ .HasColumnType("INTEGER");
+
+ b.Property("MaxActiveSessions")
+ .HasColumnType("INTEGER");
+
+ b.Property("MaxParentalAgeRating")
+ .HasColumnType("INTEGER");
+
+ b.Property("MustUpdatePassword")
+ .HasColumnType("INTEGER");
+
+ b.Property("Password")
+ .HasColumnType("TEXT")
+ .HasMaxLength(65535);
+
+ b.Property("PasswordResetProviderId")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.Property("PlayDefaultAudioTrack")
+ .HasColumnType("INTEGER");
+
+ b.Property("RememberAudioSelections")
+ .HasColumnType("INTEGER");
+
+ b.Property("RememberSubtitleSelections")
+ .HasColumnType("INTEGER");
+
+ b.Property("RemoteClientBitrateLimit")
+ .HasColumnType("INTEGER");
+
+ b.Property("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property("SubtitleLanguagePreference")
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.Property("SubtitleMode")
+ .HasColumnType("INTEGER");
+
+ b.Property("SyncPlayAccess")
+ .HasColumnType("INTEGER");
+
+ b.Property("Username")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasMaxLength(255);
+
+ b.HasKey("Id");
+
+ b.ToTable("Users");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("AccessSchedules")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithOne("DisplayPreferences")
+ .HasForeignKey("Jellyfin.Data.Entities.DisplayPreferences", "UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.HomeSection", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.DisplayPreferences", null)
+ .WithMany("HomeSections")
+ .HasForeignKey("DisplayPreferencesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithOne("ProfileImage")
+ .HasForeignKey("Jellyfin.Data.Entities.ImageInfo", "UserId");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("ItemDisplayPreferences")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Permissions")
+ .HasForeignKey("Permission_Permissions_Guid");
+ });
+
+ modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b =>
+ {
+ b.HasOne("Jellyfin.Data.Entities.User", null)
+ .WithMany("Preferences")
+ .HasForeignKey("Preference_Preferences_Guid");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/20201004171403_AddMaxActiveSessions.cs b/Jellyfin.Server.Implementations/Migrations/20201004171403_AddMaxActiveSessions.cs
new file mode 100644
index 0000000000..10acb4defb
--- /dev/null
+++ b/Jellyfin.Server.Implementations/Migrations/20201004171403_AddMaxActiveSessions.cs
@@ -0,0 +1,28 @@
+#pragma warning disable CS1591
+#pragma warning disable SA1601
+
+using Microsoft.EntityFrameworkCore.Migrations;
+
+namespace Jellyfin.Server.Implementations.Migrations
+{
+ public partial class AddMaxActiveSessions : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AddColumn(
+ name: "MaxActiveSessions",
+ schema: "jellyfin",
+ table: "Users",
+ nullable: false,
+ defaultValue: 0);
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropColumn(
+ name: "MaxActiveSessions",
+ schema: "jellyfin",
+ table: "Users");
+ }
+ }
+}
diff --git a/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs b/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs
index ccfcf96b1f..16d62f4826 100644
--- a/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs
+++ b/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs
@@ -15,7 +15,7 @@ namespace Jellyfin.Server.Implementations.Migrations
#pragma warning disable 612, 618
modelBuilder
.HasDefaultSchema("jellyfin")
- .HasAnnotation("ProductVersion", "3.1.7");
+ .HasAnnotation("ProductVersion", "3.1.8");
modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b =>
{
@@ -344,6 +344,9 @@ namespace Jellyfin.Server.Implementations.Migrations
b.Property("LoginAttemptsBeforeLockout")
.HasColumnType("INTEGER");
+ b.Property("MaxActiveSessions")
+ .HasColumnType("INTEGER");
+
b.Property("MaxParentalAgeRating")
.HasColumnType("INTEGER");
diff --git a/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs b/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs
index 6cb13cd23e..334f27f859 100644
--- a/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs
+++ b/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs
@@ -57,7 +57,8 @@ namespace Jellyfin.Server.Implementations.Users
SerializablePasswordReset spr;
await using (var str = File.OpenRead(resetFile))
{
- spr = await JsonSerializer.DeserializeAsync(str).ConfigureAwait(false);
+ spr = await JsonSerializer.DeserializeAsync(str).ConfigureAwait(false)
+ ?? throw new ResourceNotFoundException($"Provided path ({resetFile}) is not valid.");
}
if (spr.ExpirationDate < DateTime.UtcNow)
diff --git a/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs b/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs
index 46f1c618f2..76f9433854 100644
--- a/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs
+++ b/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs
@@ -61,6 +61,7 @@ namespace Jellyfin.Server.Implementations.Users
public IList ListItemDisplayPreferences(Guid userId, string client)
{
return _dbContext.ItemDisplayPreferences
+ .AsQueryable()
.Where(prefs => prefs.UserId == userId && prefs.ItemId != Guid.Empty && string.Equals(prefs.Client, client))
.ToList();
}
diff --git a/Jellyfin.Server.Implementations/Users/InvalidAuthProvider.cs b/Jellyfin.Server.Implementations/Users/InvalidAuthProvider.cs
index e38cd07f0e..5f32479e1d 100644
--- a/Jellyfin.Server.Implementations/Users/InvalidAuthProvider.cs
+++ b/Jellyfin.Server.Implementations/Users/InvalidAuthProvider.cs
@@ -15,7 +15,7 @@ namespace Jellyfin.Server.Implementations.Users
public string Name => "InvalidOrMissingAuthenticationProvider";
///
- public bool IsEnabled => true;
+ public bool IsEnabled => false;
///
public Task Authenticate(string username, string password)
diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs
index 8f04baa089..f684d151d6 100644
--- a/Jellyfin.Server.Implementations/Users/UserManager.cs
+++ b/Jellyfin.Server.Implementations/Users/UserManager.cs
@@ -2,6 +2,7 @@
#pragma warning disable CA1307
using System;
+using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
@@ -48,6 +49,8 @@ namespace Jellyfin.Server.Implementations.Users
private readonly DefaultAuthenticationProvider _defaultAuthenticationProvider;
private readonly DefaultPasswordResetProvider _defaultPasswordResetProvider;
+ private readonly IDictionary _users;
+
///
/// Initializes a new instance of the class.
///
@@ -81,37 +84,28 @@ namespace Jellyfin.Server.Implementations.Users
_invalidAuthProvider = _authenticationProviders.OfType().First();
_defaultAuthenticationProvider = _authenticationProviders.OfType().First();
_defaultPasswordResetProvider = _passwordResetProviders.OfType().First();
+
+ _users = new ConcurrentDictionary();
+ using var dbContext = _dbProvider.CreateContext();
+ foreach (var user in dbContext.Users
+ .Include(user => user.Permissions)
+ .Include(user => user.Preferences)
+ .Include(user => user.AccessSchedules)
+ .Include(user => user.ProfileImage)
+ .AsEnumerable())
+ {
+ _users.Add(user.Id, user);
+ }
}
///
public event EventHandler>? OnUserUpdated;
///
- public IEnumerable Users
- {
- get
- {
- using var dbContext = _dbProvider.CreateContext();
- return dbContext.Users
- .Include(user => user.Permissions)
- .Include(user => user.Preferences)
- .Include(user => user.AccessSchedules)
- .Include(user => user.ProfileImage)
- .ToList();
- }
- }
+ public IEnumerable Users => _users.Values;
///
- public IEnumerable UsersIds
- {
- get
- {
- using var dbContext = _dbProvider.CreateContext();
- return dbContext.Users
- .Select(user => user.Id)
- .ToList();
- }
- }
+ public IEnumerable UsersIds => _users.Keys;
///
public User? GetUserById(Guid id)
@@ -121,13 +115,8 @@ namespace Jellyfin.Server.Implementations.Users
throw new ArgumentException("Guid can't be empty", nameof(id));
}
- using var dbContext = _dbProvider.CreateContext();
- return dbContext.Users
- .Include(user => user.Permissions)
- .Include(user => user.Preferences)
- .Include(user => user.AccessSchedules)
- .Include(user => user.ProfileImage)
- .FirstOrDefault(user => user.Id == id);
+ _users.TryGetValue(id, out var user);
+ return user;
}
///
@@ -138,14 +127,7 @@ namespace Jellyfin.Server.Implementations.Users
throw new ArgumentException("Invalid username", nameof(name));
}
- using var dbContext = _dbProvider.CreateContext();
- return dbContext.Users
- .Include(user => user.Permissions)
- .Include(user => user.Preferences)
- .Include(user => user.AccessSchedules)
- .Include(user => user.ProfileImage)
- .AsEnumerable()
- .FirstOrDefault(u => string.Equals(u.Username, name, StringComparison.OrdinalIgnoreCase));
+ return _users.Values.FirstOrDefault(u => string.Equals(u.Username, name, StringComparison.OrdinalIgnoreCase));
}
///
@@ -176,7 +158,6 @@ namespace Jellyfin.Server.Implementations.Users
user.Username = newName;
await UpdateUserAsync(user).ConfigureAwait(false);
-
OnUserUpdated?.Invoke(this, new GenericEventArgs(user));
}
@@ -185,6 +166,7 @@ namespace Jellyfin.Server.Implementations.Users
{
using var dbContext = _dbProvider.CreateContext();
dbContext.Users.Update(user);
+ _users[user.Id] = user;
dbContext.SaveChanges();
}
@@ -193,24 +175,28 @@ namespace Jellyfin.Server.Implementations.Users
{
await using var dbContext = _dbProvider.CreateContext();
dbContext.Users.Update(user);
-
+ _users[user.Id] = user;
await dbContext.SaveChangesAsync().ConfigureAwait(false);
}
internal async Task CreateUserInternalAsync(string name, JellyfinDb dbContext)
{
// TODO: Remove after user item data is migrated.
- var max = await dbContext.Users.AnyAsync().ConfigureAwait(false)
- ? await dbContext.Users.Select(u => u.InternalId).MaxAsync().ConfigureAwait(false)
+ var max = await dbContext.Users.AsQueryable().AnyAsync().ConfigureAwait(false)
+ ? await dbContext.Users.AsQueryable().Select(u => u.InternalId).MaxAsync().ConfigureAwait(false)
: 0;
- return new User(
+ var user = new User(
name,
_defaultAuthenticationProvider.GetType().FullName,
_defaultPasswordResetProvider.GetType().FullName)
{
InternalId = max + 1
};
+
+ _users.Add(user.Id, user);
+
+ return user;
}
///
@@ -221,7 +207,7 @@ namespace Jellyfin.Server.Implementations.Users
throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
}
- using var dbContext = _dbProvider.CreateContext();
+ await using var dbContext = _dbProvider.CreateContext();
var newUser = await CreateUserInternalAsync(name, dbContext).ConfigureAwait(false);
@@ -236,28 +222,12 @@ namespace Jellyfin.Server.Implementations.Users
///
public void DeleteUser(Guid userId)
{
- using var dbContext = _dbProvider.CreateContext();
- var user = dbContext.Users
- .Include(u => u.Permissions)
- .Include(u => u.Preferences)
- .Include(u => u.AccessSchedules)
- .Include(u => u.ProfileImage)
- .FirstOrDefault(u => u.Id == userId);
- if (user == null)
+ if (!_users.TryGetValue(userId, out var user))
{
throw new ResourceNotFoundException(nameof(userId));
}
- if (dbContext.Users.Find(user.Id) == null)
- {
- throw new ArgumentException(string.Format(
- CultureInfo.InvariantCulture,
- "The user cannot be deleted because there is no user with the Name {0} and Id {1}.",
- user.Username,
- user.Id));
- }
-
- if (dbContext.Users.Count() == 1)
+ if (_users.Count == 1)
{
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
@@ -276,6 +246,8 @@ namespace Jellyfin.Server.Implementations.Users
nameof(userId));
}
+ using var dbContext = _dbProvider.CreateContext();
+
// Clear all entities related to the user from the database.
if (user.ProfileImage != null)
{
@@ -287,6 +259,7 @@ namespace Jellyfin.Server.Implementations.Users
dbContext.RemoveRange(user.AccessSchedules);
dbContext.Users.Remove(user);
dbContext.SaveChanges();
+ _users.Remove(userId);
_eventManager.Publish(new UserDeletedEventArgs(user));
}
@@ -379,6 +352,7 @@ namespace Jellyfin.Server.Implementations.Users
PasswordResetProviderId = user.PasswordResetProviderId,
InvalidLoginAttemptCount = user.InvalidLoginAttemptCount,
LoginAttemptsBeforeLockout = user.LoginAttemptsBeforeLockout ?? -1,
+ MaxActiveSessions = user.MaxActiveSessions,
IsAdministrator = user.HasPermission(PermissionKind.IsAdministrator),
IsHidden = user.HasPermission(PermissionKind.IsHidden),
IsDisabled = user.HasPermission(PermissionKind.IsDisabled),
@@ -458,11 +432,9 @@ namespace Jellyfin.Server.Implementations.Users
// the authentication provider might have created it
user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase));
- if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy)
+ if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy && user != null)
{
- UpdatePolicy(user.Id, hasNewUserPolicy.GetNewUserPolicy());
-
- await UpdateUserAsync(user).ConfigureAwait(false);
+ await UpdatePolicyAsync(user.Id, hasNewUserPolicy.GetNewUserPolicy()).ConfigureAwait(false);
}
}
}
@@ -587,9 +559,7 @@ namespace Jellyfin.Server.Implementations.Users
public async Task InitializeAsync()
{
// TODO: Refactor the startup wizard so that it doesn't require a user to already exist.
- using var dbContext = _dbProvider.CreateContext();
-
- if (await dbContext.Users.AnyAsync().ConfigureAwait(false))
+ if (_users.Any())
{
return;
}
@@ -602,6 +572,7 @@ namespace Jellyfin.Server.Implementations.Users
_logger.LogWarning("No users, creating one with username {UserName}", defaultName);
+ await using var dbContext = _dbProvider.CreateContext();
var newUser = await CreateUserInternalAsync(defaultName, dbContext).ConfigureAwait(false);
newUser.SetPermission(PermissionKind.IsAdministrator, true);
newUser.SetPermission(PermissionKind.EnableContentDeletion, true);
@@ -642,9 +613,9 @@ namespace Jellyfin.Server.Implementations.Users
}
///
- public void UpdateConfiguration(Guid userId, UserConfiguration config)
+ public async Task UpdateConfigurationAsync(Guid userId, UserConfiguration config)
{
- using var dbContext = _dbProvider.CreateContext();
+ await using var dbContext = _dbProvider.CreateContext();
var user = dbContext.Users
.Include(u => u.Permissions)
.Include(u => u.Preferences)
@@ -671,13 +642,14 @@ namespace Jellyfin.Server.Implementations.Users
user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes);
dbContext.Update(user);
- dbContext.SaveChanges();
+ _users[user.Id] = user;
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
}
///
- public void UpdatePolicy(Guid userId, UserPolicy policy)
+ public async Task UpdatePolicyAsync(Guid userId, UserPolicy policy)
{
- using var dbContext = _dbProvider.CreateContext();
+ await using var dbContext = _dbProvider.CreateContext();
var user = dbContext.Users
.Include(u => u.Permissions)
.Include(u => u.Preferences)
@@ -701,6 +673,7 @@ namespace Jellyfin.Server.Implementations.Users
user.PasswordResetProviderId = policy.PasswordResetProviderId;
user.InvalidLoginAttemptCount = policy.InvalidLoginAttemptCount;
user.LoginAttemptsBeforeLockout = maxLoginAttempts;
+ user.MaxActiveSessions = policy.MaxActiveSessions;
user.SyncPlayAccess = policy.SyncPlayAccess;
user.SetPermission(PermissionKind.IsAdministrator, policy.IsAdministrator);
user.SetPermission(PermissionKind.IsHidden, policy.IsHidden);
@@ -741,15 +714,18 @@ namespace Jellyfin.Server.Implementations.Users
user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders);
dbContext.Update(user);
- dbContext.SaveChanges();
+ _users[user.Id] = user;
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
}
///
- public void ClearProfileImage(User user)
+ public async Task ClearProfileImageAsync(User user)
{
- using var dbContext = _dbProvider.CreateContext();
+ await using var dbContext = _dbProvider.CreateContext();
dbContext.Remove(user.ProfileImage);
- dbContext.SaveChanges();
+ await dbContext.SaveChangesAsync().ConfigureAwait(false);
+ user.ProfileImage = null;
+ _users[user.Id] = user;
}
private static bool IsValidUsername(string name)
@@ -799,7 +775,7 @@ namespace Jellyfin.Server.Implementations.Users
private IList GetPasswordResetProviders(User user)
{
- var passwordResetProviderId = user?.PasswordResetProviderId;
+ var passwordResetProviderId = user.PasswordResetProviderId;
var providers = _passwordResetProviders.Where(i => i.IsEnabled).ToArray();
if (!string.IsNullOrEmpty(passwordResetProviderId))
diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs
index 8d569a779a..c44736447f 100644
--- a/Jellyfin.Server/CoreAppHost.cs
+++ b/Jellyfin.Server/CoreAppHost.cs
@@ -4,6 +4,8 @@ using System.IO;
using System.Reflection;
using Emby.Drawing;
using Emby.Server.Implementations;
+using Emby.Server.Implementations.Session;
+using Jellyfin.Api.WebSocketListeners;
using Jellyfin.Drawing.Skia;
using Jellyfin.Server.Implementations;
using Jellyfin.Server.Implementations.Activity;
@@ -14,6 +16,7 @@ using MediaBrowser.Controller;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Events;
using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Activity;
using MediaBrowser.Model.IO;
using Microsoft.EntityFrameworkCore;
@@ -80,6 +83,14 @@ namespace Jellyfin.Server
ServiceCollection.AddSingleton();
ServiceCollection.AddSingleton();
+ ServiceCollection.AddScoped();
+ ServiceCollection.AddScoped();
+ ServiceCollection.AddScoped();
+ ServiceCollection.AddScoped();
+
+ // TODO fix circular dependency on IWebSocketManager
+ ServiceCollection.AddScoped(serviceProvider => new Lazy>(serviceProvider.GetRequiredService>));
+
base.RegisterServices();
}
diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
index 5bcf6d5f07..cc98955df7 100644
--- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
+++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
@@ -4,6 +4,7 @@ using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
+using Emby.Server.Implementations;
using Jellyfin.Api.Auth;
using Jellyfin.Api.Auth.DefaultAuthorizationPolicy;
using Jellyfin.Api.Auth.DownloadPolicy;
@@ -27,6 +28,8 @@ using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.OpenApi.Any;
+using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using AuthenticationSchemes = Jellyfin.Api.Constants.AuthenticationSchemes;
@@ -209,7 +212,19 @@ namespace Jellyfin.Server.Extensions
{
return serviceCollection.AddSwaggerGen(c =>
{
- c.SwaggerDoc("api-docs", new OpenApiInfo { Title = "Jellyfin API", Version = "v1" });
+ c.SwaggerDoc("api-docs", new OpenApiInfo
+ {
+ Title = "Jellyfin API",
+ Version = "v1",
+ Extensions = new Dictionary
+ {
+ {
+ "x-jellyfin-version",
+ new OpenApiString(typeof(ApplicationHost).Assembly.GetName().Version?.ToString())
+ }
+ }
+ });
+
c.AddSecurityDefinition(AuthenticationSchemes.CustomAuthentication, new OpenApiSecurityScheme
{
Type = SecuritySchemeType.ApiKey,
@@ -260,6 +275,7 @@ namespace Jellyfin.Server.Extensions
c.AddSwaggerTypeMappings();
c.OperationFilter();
+ c.DocumentFilter();
});
}
diff --git a/Jellyfin.Server/Filters/FileResponseFilter.cs b/Jellyfin.Server/Filters/FileResponseFilter.cs
index 8ea35c2818..7ad9466c17 100644
--- a/Jellyfin.Server/Filters/FileResponseFilter.cs
+++ b/Jellyfin.Server/Filters/FileResponseFilter.cs
@@ -26,22 +26,22 @@ namespace Jellyfin.Server.Filters
if (attribute is ProducesFileAttribute producesFileAttribute)
{
// Get operation response values.
- var (_, value) = operation.Responses
+ var response = operation.Responses
.FirstOrDefault(o => o.Key.Equals(SuccessCode, StringComparison.Ordinal));
// Operation doesn't have a response.
- if (value == null)
+ if (response.Value == null)
{
continue;
}
// Clear existing responses.
- value.Content.Clear();
+ response.Value.Content.Clear();
// Add all content-types as file.
foreach (var contentType in producesFileAttribute.GetContentTypes())
{
- value.Content.Add(contentType, _openApiMediaType);
+ response.Value.Content.Add(contentType, _openApiMediaType);
}
break;
diff --git a/Jellyfin.Server/Filters/WebsocketModelFilter.cs b/Jellyfin.Server/Filters/WebsocketModelFilter.cs
new file mode 100644
index 0000000000..2488028576
--- /dev/null
+++ b/Jellyfin.Server/Filters/WebsocketModelFilter.cs
@@ -0,0 +1,30 @@
+using MediaBrowser.Common.Plugins;
+using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Session;
+using MediaBrowser.Model.SyncPlay;
+using Microsoft.OpenApi.Models;
+using Swashbuckle.AspNetCore.SwaggerGen;
+
+namespace Jellyfin.Server.Filters
+{
+ ///
+ /// Add models used in websocket messaging.
+ ///
+ public class WebsocketModelFilter : IDocumentFilter
+ {
+ ///
+ public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
+ {
+ context.SchemaGenerator.GenerateSchema(typeof(LibraryUpdateInfo), context.SchemaRepository);
+ context.SchemaGenerator.GenerateSchema(typeof(IPlugin), context.SchemaRepository);
+ context.SchemaGenerator.GenerateSchema(typeof(PlayRequest), context.SchemaRepository);
+ context.SchemaGenerator.GenerateSchema(typeof(PlaystateRequest), context.SchemaRepository);
+ context.SchemaGenerator.GenerateSchema(typeof(TimerEventInfo), context.SchemaRepository);
+ context.SchemaGenerator.GenerateSchema(typeof(SendCommand), context.SchemaRepository);
+ context.SchemaGenerator.GenerateSchema(typeof(GeneralCommandType), context.SchemaRepository);
+
+ context.SchemaGenerator.GenerateSchema(typeof(GroupUpdate), context.SchemaRepository);
+ }
+ }
+}
diff --git a/Jellyfin.Server/Formatters/CssOutputFormatter.cs b/Jellyfin.Server/Formatters/CssOutputFormatter.cs
index b3771b7fe6..e8dd48e4e6 100644
--- a/Jellyfin.Server/Formatters/CssOutputFormatter.cs
+++ b/Jellyfin.Server/Formatters/CssOutputFormatter.cs
@@ -30,7 +30,8 @@ namespace Jellyfin.Server.Formatters
/// Write stream task.
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
{
- return context.HttpContext.Response.WriteAsync(context.Object?.ToString());
+ var stringResponse = context.Object?.ToString();
+ return stringResponse == null ? Task.CompletedTask : context.HttpContext.Response.WriteAsync(stringResponse);
}
}
}
diff --git a/Jellyfin.Server/Formatters/XmlOutputFormatter.cs b/Jellyfin.Server/Formatters/XmlOutputFormatter.cs
index 01d99d7c87..be0baea2d2 100644
--- a/Jellyfin.Server/Formatters/XmlOutputFormatter.cs
+++ b/Jellyfin.Server/Formatters/XmlOutputFormatter.cs
@@ -26,7 +26,8 @@ namespace Jellyfin.Server.Formatters
///
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
{
- return context.HttpContext.Response.WriteAsync(context.Object?.ToString());
+ var stringResponse = context.Object?.ToString();
+ return stringResponse == null ? Task.CompletedTask : context.HttpContext.Response.WriteAsync(stringResponse);
}
}
}
diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj
index 648172fbf7..03d06fdff3 100644
--- a/Jellyfin.Server/Jellyfin.Server.csproj
+++ b/Jellyfin.Server/Jellyfin.Server.csproj
@@ -1,4 +1,4 @@
-
+
@@ -8,11 +8,12 @@
jellyfin
Exe
- netcoreapp3.1
+ net5.0
false
true
true
enable
+ true
@@ -23,10 +24,6 @@
-
-
-
-
@@ -41,19 +38,19 @@
-
-
-
-
-
-
+
+
+
+
+
+
-
+
diff --git a/Jellyfin.Server/Middleware/ExceptionMiddleware.cs b/Jellyfin.Server/Middleware/ExceptionMiddleware.cs
index fb1ee3b2bb..f6c76e4d9e 100644
--- a/Jellyfin.Server/Middleware/ExceptionMiddleware.cs
+++ b/Jellyfin.Server/Middleware/ExceptionMiddleware.cs
@@ -125,8 +125,8 @@ namespace Jellyfin.Server.Middleware
switch (ex)
{
case ArgumentException _: return StatusCodes.Status400BadRequest;
- case AuthenticationException _:
- case SecurityException _: return StatusCodes.Status401Unauthorized;
+ case AuthenticationException _: return StatusCodes.Status401Unauthorized;
+ case SecurityException _: return StatusCodes.Status403Forbidden;
case DirectoryNotFoundException _:
case FileNotFoundException _:
case ResourceNotFoundException _: return StatusCodes.Status404NotFound;
diff --git a/Jellyfin.Server/Migrations/MigrationRunner.cs b/Jellyfin.Server/Migrations/MigrationRunner.cs
index 844dae61f6..aca1654084 100644
--- a/Jellyfin.Server/Migrations/MigrationRunner.cs
+++ b/Jellyfin.Server/Migrations/MigrationRunner.cs
@@ -23,7 +23,8 @@ namespace Jellyfin.Server.Migrations
typeof(Routines.AddDefaultPluginRepository),
typeof(Routines.MigrateUserDb),
typeof(Routines.ReaddDefaultPluginRepository),
- typeof(Routines.MigrateDisplayPreferencesDb)
+ typeof(Routines.MigrateDisplayPreferencesDb),
+ typeof(Routines.RemoveDownloadImagesInAdvance)
};
///
diff --git a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs
index 7f57358ec0..8992c281db 100644
--- a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs
+++ b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs
@@ -9,6 +9,7 @@ using Jellyfin.Data.Entities;
using Jellyfin.Data.Enums;
using Jellyfin.Server.Implementations;
using MediaBrowser.Controller;
+using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Entities;
using Microsoft.Extensions.Logging;
using SQLitePCL.pretty;
@@ -26,6 +27,7 @@ namespace Jellyfin.Server.Migrations.Routines
private readonly IServerApplicationPaths _paths;
private readonly JellyfinDbProvider _provider;
private readonly JsonSerializerOptions _jsonOptions;
+ private readonly IUserManager _userManager;
///
/// Initializes a new instance of the class.
@@ -33,11 +35,17 @@ namespace Jellyfin.Server.Migrations.Routines
/// The logger.
/// The server application paths.
/// The database provider.
- public MigrateDisplayPreferencesDb(ILogger logger, IServerApplicationPaths paths, JellyfinDbProvider provider)
+ /// The user manager.
+ public MigrateDisplayPreferencesDb(
+ ILogger logger,
+ IServerApplicationPaths paths,
+ JellyfinDbProvider provider,
+ IUserManager userManager)
{
_logger = logger;
_paths = paths;
_provider = provider;
+ _userManager = userManager;
_jsonOptions = new JsonSerializerOptions();
_jsonOptions.Converters.Add(new JsonStringEnumConverter());
}
@@ -86,11 +94,19 @@ namespace Jellyfin.Server.Migrations.Routines
continue;
}
+ var dtoUserId = new Guid(result[1].ToBlob());
+ var existingUser = _userManager.GetUserById(dtoUserId);
+ if (existingUser == null)
+ {
+ _logger.LogWarning("User with ID {UserId} does not exist in the database, skipping migration.", dtoUserId);
+ continue;
+ }
+
var chromecastVersion = dto.CustomPrefs.TryGetValue("chromecastVersion", out var version)
? chromecastDict[version]
: ChromecastVersion.Stable;
- var displayPreferences = new DisplayPreferences(new Guid(result[1].ToBlob()), result[2].ToString())
+ var displayPreferences = new DisplayPreferences(dtoUserId, result[2].ToString())
{
IndexBy = Enum.TryParse(dto.IndexBy, true, out var indexBy) ? indexBy : (IndexingKind?)null,
ShowBackdrop = dto.ShowBackdrop,
diff --git a/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs b/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs
new file mode 100644
index 0000000000..42b87ec5f5
--- /dev/null
+++ b/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs
@@ -0,0 +1,46 @@
+using System;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Library;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Migrations.Routines
+{
+ ///
+ /// Removes the old 'RemoveDownloadImagesInAdvance' from library options.
+ ///
+ internal class RemoveDownloadImagesInAdvance : IMigrationRoutine
+ {
+ private readonly ILogger _logger;
+ private readonly ILibraryManager _libraryManager;
+
+ public RemoveDownloadImagesInAdvance(ILogger logger, ILibraryManager libraryManager)
+ {
+ _logger = logger;
+ _libraryManager = libraryManager;
+ }
+
+ ///
+ public Guid Id => Guid.Parse("{A81F75E0-8F43-416F-A5E8-516CCAB4D8CC}");
+
+ ///
+ public string Name => "RemoveDownloadImagesInAdvance";
+
+ ///
+ public bool PerformOnNewInstall => false;
+
+ ///
+ public void Perform()
+ {
+ var virtualFolders = _libraryManager.GetVirtualFolders(false);
+ _logger.LogInformation("Removing 'RemoveDownloadImagesInAdvance' settings in all the libraries");
+ foreach (var virtualFolder in virtualFolders)
+ {
+ var libraryOptions = virtualFolder.LibraryOptions;
+ var collectionFolder = (CollectionFolder)_libraryManager.GetItemById(virtualFolder.ItemId);
+ // The property no longer exists in LibraryOptions, so we just re-save the options to get old data removed.
+ collectionFolder.UpdateLibraryOptions(libraryOptions);
+ _logger.LogInformation("Removed from '{VirtualFolder}'", virtualFolder.Name);
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs
index c933d679f4..97a51c202b 100644
--- a/Jellyfin.Server/Program.cs
+++ b/Jellyfin.Server/Program.cs
@@ -290,23 +290,19 @@ namespace Jellyfin.Server
{
_logger.LogInformation("Kestrel listening on {IpAddress}", address);
options.Listen(address, appHost.HttpPort);
+
if (appHost.ListenWithHttps)
{
- options.Listen(address, appHost.HttpsPort, listenOptions =>
- {
- listenOptions.UseHttps(appHost.Certificate);
- listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
- });
+ options.Listen(
+ address,
+ appHost.HttpsPort,
+ listenOptions => listenOptions.UseHttps(appHost.Certificate));
}
else if (builderContext.HostingEnvironment.IsDevelopment())
{
try
{
- options.Listen(address, appHost.HttpsPort, listenOptions =>
- {
- listenOptions.UseHttps();
- listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
- });
+ options.Listen(address, appHost.HttpsPort, listenOptions => listenOptions.UseHttps());
}
catch (InvalidOperationException ex)
{
@@ -322,21 +318,15 @@ namespace Jellyfin.Server
if (appHost.ListenWithHttps)
{
- options.ListenAnyIP(appHost.HttpsPort, listenOptions =>
- {
- listenOptions.UseHttps(appHost.Certificate);
- listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
- });
+ options.ListenAnyIP(
+ appHost.HttpsPort,
+ listenOptions => listenOptions.UseHttps(appHost.Certificate));
}
else if (builderContext.HostingEnvironment.IsDevelopment())
{
try
{
- options.ListenAnyIP(appHost.HttpsPort, listenOptions =>
- {
- listenOptions.UseHttps();
- listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
- });
+ options.ListenAnyIP(appHost.HttpsPort, listenOptions => listenOptions.UseHttps());
}
catch (InvalidOperationException ex)
{
@@ -378,7 +368,7 @@ namespace Jellyfin.Server
.ConfigureServices(services =>
{
// Merge the external ServiceCollection into ASP.NET DI
- services.TryAdd(serviceCollection);
+ services.Add(serviceCollection);
})
.UseStartup();
}
diff --git a/Jellyfin.Server/Properties/launchSettings.json b/Jellyfin.Server/Properties/launchSettings.json
index b6e2bcf976..20d432afc4 100644
--- a/Jellyfin.Server/Properties/launchSettings.json
+++ b/Jellyfin.Server/Properties/launchSettings.json
@@ -2,6 +2,8 @@
"profiles": {
"Jellyfin.Server": {
"commandName": "Project",
+ "launchBrowser": true,
+ "applicationUrl": "http://localhost:8096",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
@@ -12,6 +14,16 @@
"ASPNETCORE_ENVIRONMENT": "Development"
},
"commandLineArgs": "--nowebclient"
+ },
+ "Jellyfin.Server (API Docs)": {
+ "commandName": "Project",
+ "launchBrowser": true,
+ "launchUrl": "api-docs/swagger",
+ "applicationUrl": "http://localhost:8096",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ },
+ "commandLineArgs": "--nowebclient"
}
}
}
diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs
index 2f4620aa63..62ffe174cd 100644
--- a/Jellyfin.Server/Startup.cs
+++ b/Jellyfin.Server/Startup.cs
@@ -1,6 +1,7 @@
using System;
using System.ComponentModel;
using System.Net.Http.Headers;
+using System.Net.Mime;
using Jellyfin.Api.TypeConverters;
using Jellyfin.Server.Extensions;
using Jellyfin.Server.Implementations;
@@ -11,6 +12,7 @@ using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
@@ -123,10 +125,15 @@ namespace Jellyfin.Server
mainApp.UseStaticFiles();
if (appConfig.HostWebClient())
{
+ var extensionProvider = new FileExtensionContentTypeProvider();
+
+ // subtitles octopus requires .data files.
+ extensionProvider.Mappings.Add(".data", MediaTypeNames.Application.Octet);
mainApp.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(_serverConfigurationManager.ApplicationPaths.WebPath),
- RequestPath = "/web"
+ RequestPath = "/web",
+ ContentTypeProvider = extensionProvider
});
}
diff --git a/Jellyfin.Server/StartupOptions.cs b/Jellyfin.Server/StartupOptions.cs
index 41a1430d26..b634340927 100644
--- a/Jellyfin.Server/StartupOptions.cs
+++ b/Jellyfin.Server/StartupOptions.cs
@@ -63,10 +63,6 @@ namespace Jellyfin.Server
[Option("service", Required = false, HelpText = "Run as headless service.")]
public bool IsService { get; set; }
- ///
- [Option("noautorunwebapp", Required = false, HelpText = "Run headless if startup wizard is complete.")]
- public bool NoAutoRunWebApp { get; set; }
-
///
[Option("package-name", Required = false, HelpText = "Used when packaging Jellyfin (example, synology).")]
public string? PackageName { get; set; }
diff --git a/MediaBrowser.Common/Configuration/IConfigurationManager.cs b/MediaBrowser.Common/Configuration/IConfigurationManager.cs
index fe726090d6..fc63d93503 100644
--- a/MediaBrowser.Common/Configuration/IConfigurationManager.cs
+++ b/MediaBrowser.Common/Configuration/IConfigurationManager.cs
@@ -46,6 +46,13 @@ namespace MediaBrowser.Common.Configuration
/// The new configuration.
void ReplaceConfiguration(BaseApplicationConfiguration newConfiguration);
+ ///
+ /// Manually pre-loads a factory so that it is available pre system initialisation.
+ ///
+ /// Class to register.
+ void RegisterConfiguration()
+ where T : IConfigurationFactory;
+
///
/// Gets the configuration.
///
diff --git a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs
new file mode 100644
index 0000000000..06a29a0dbe
--- /dev/null
+++ b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs
@@ -0,0 +1,74 @@
+using System;
+using System.ComponentModel;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.Common.Json.Converters
+{
+ ///
+ /// Convert comma delimited string to array of type.
+ ///
+ /// Type to convert to.
+ public class JsonCommaDelimitedArrayConverter : JsonConverter
+ {
+ private readonly TypeConverter _typeConverter;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public JsonCommaDelimitedArrayConverter()
+ {
+ _typeConverter = TypeDescriptor.GetConverter(typeof(T));
+ }
+
+ ///
+ public override T[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ if (reader.TokenType == JsonTokenType.String)
+ {
+ var stringEntries = reader.GetString()?.Split(',', StringSplitOptions.RemoveEmptyEntries);
+ if (stringEntries == null || stringEntries.Length == 0)
+ {
+ return Array.Empty();
+ }
+
+ var parsedValues = new object[stringEntries.Length];
+ var convertedCount = 0;
+ for (var i = 0; i < stringEntries.Length; i++)
+ {
+ try
+ {
+ parsedValues[i] = _typeConverter.ConvertFrom(stringEntries[i].Trim());
+ convertedCount++;
+ }
+ catch (FormatException)
+ {
+ // TODO log when upgraded to .Net5
+ // _logger.LogWarning(e, "Error converting value.");
+ }
+ }
+
+ var typedValues = new T[convertedCount];
+ var typedValueIndex = 0;
+ for (var i = 0; i < stringEntries.Length; i++)
+ {
+ if (parsedValues[i] != null)
+ {
+ typedValues.SetValue(parsedValues[i], typedValueIndex);
+ typedValueIndex++;
+ }
+ }
+
+ return typedValues;
+ }
+
+ return JsonSerializer.Deserialize(ref reader, options);
+ }
+
+ ///
+ public override void Write(Utf8JsonWriter writer, T[] value, JsonSerializerOptions options)
+ {
+ JsonSerializer.Serialize(writer, value, options);
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs
new file mode 100644
index 0000000000..24ed3ea19e
--- /dev/null
+++ b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs
@@ -0,0 +1,28 @@
+using System;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.Common.Json.Converters
+{
+ ///
+ /// Json comma delimited array converter factory.
+ ///
+ ///
+ /// This must be applied as an attribute, adding to the JsonConverter list causes stack overflow.
+ ///
+ public class JsonCommaDelimitedArrayConverterFactory : JsonConverterFactory
+ {
+ ///
+ public override bool CanConvert(Type typeToConvert)
+ {
+ return true;
+ }
+
+ ///
+ public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
+ {
+ var structType = typeToConvert.GetElementType() ?? typeToConvert.GenericTypeArguments[0];
+ return (JsonConverter)Activator.CreateInstance(typeof(JsonCommaDelimitedArrayConverter<>).MakeGenericType(structType));
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Json/Converters/JsonNullableStructConverter.cs b/MediaBrowser.Common/Json/Converters/JsonNullableStructConverter.cs
index cffc41ba34..0501f7b2a1 100644
--- a/MediaBrowser.Common/Json/Converters/JsonNullableStructConverter.cs
+++ b/MediaBrowser.Common/Json/Converters/JsonNullableStructConverter.cs
@@ -8,37 +8,38 @@ namespace MediaBrowser.Common.Json.Converters
/// Converts a nullable struct or value to/from JSON.
/// Required - some clients send an empty string.
///
- /// The struct type.
- public class JsonNullableStructConverter : JsonConverter
- where T : struct
+ /// The struct type.
+ public class JsonNullableStructConverter : JsonConverter
+ where TStruct : struct
{
- private readonly JsonConverter _baseJsonConverter;
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The base json converter.
- public JsonNullableStructConverter(JsonConverter baseJsonConverter)
- {
- _baseJsonConverter = baseJsonConverter;
- }
-
///
- public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ public override TStruct? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
- // Handle empty string.
+ if (reader.TokenType == JsonTokenType.Null)
+ {
+ return null;
+ }
+
+ // Token is empty string.
if (reader.TokenType == JsonTokenType.String && ((reader.HasValueSequence && reader.ValueSequence.IsEmpty) || reader.ValueSpan.IsEmpty))
{
return null;
}
- return _baseJsonConverter.Read(ref reader, typeToConvert, options);
+ return JsonSerializer.Deserialize(ref reader, options);
}
///
- public override void Write(Utf8JsonWriter writer, T? value, JsonSerializerOptions options)
+ public override void Write(Utf8JsonWriter writer, TStruct? value, JsonSerializerOptions options)
{
- _baseJsonConverter.Write(writer, value, options);
+ if (value.HasValue)
+ {
+ JsonSerializer.Serialize(writer, value.Value, options);
+ }
+ else
+ {
+ writer.WriteNullValue();
+ }
}
}
}
diff --git a/MediaBrowser.Common/Json/Converters/JsonNullableStructConverterFactory.cs b/MediaBrowser.Common/Json/Converters/JsonNullableStructConverterFactory.cs
new file mode 100644
index 0000000000..d5b54e3ca8
--- /dev/null
+++ b/MediaBrowser.Common/Json/Converters/JsonNullableStructConverterFactory.cs
@@ -0,0 +1,27 @@
+using System;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.Common.Json.Converters
+{
+ ///
+ /// Json nullable struct converter factory.
+ ///
+ public class JsonNullableStructConverterFactory : JsonConverterFactory
+ {
+ ///
+ public override bool CanConvert(Type typeToConvert)
+ {
+ return typeToConvert.IsGenericType
+ && typeToConvert.GetGenericTypeDefinition() == typeof(Nullable<>)
+ && typeToConvert.GenericTypeArguments[0].IsValueType;
+ }
+
+ ///
+ public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
+ {
+ var structType = typeToConvert.GenericTypeArguments[0];
+ return (JsonConverter)Activator.CreateInstance(typeof(JsonNullableStructConverter<>).MakeGenericType(structType));
+ }
+ }
+}
\ No newline at end of file
diff --git a/MediaBrowser.Common/Json/JsonDefaults.cs b/MediaBrowser.Common/Json/JsonDefaults.cs
index 67f7e8f14a..6605ae9624 100644
--- a/MediaBrowser.Common/Json/JsonDefaults.cs
+++ b/MediaBrowser.Common/Json/JsonDefaults.cs
@@ -39,14 +39,9 @@ namespace MediaBrowser.Common.Json
NumberHandling = JsonNumberHandling.AllowReadingFromString
};
- // Get built-in converters for fallback converting.
- var baseNullableInt32Converter = (JsonConverter)options.GetConverter(typeof(int?));
- var baseNullableInt64Converter = (JsonConverter)options.GetConverter(typeof(long?));
-
options.Converters.Add(new JsonGuidConverter());
options.Converters.Add(new JsonStringEnumConverter());
- options.Converters.Add(new JsonNullableStructConverter(baseNullableInt32Converter));
- options.Converters.Add(new JsonNullableStructConverter(baseNullableInt64Converter));
+ options.Converters.Add(new JsonNullableStructConverterFactory());
return options;
}
diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj
index 322740cca8..c2145aec5a 100644
--- a/MediaBrowser.Common/MediaBrowser.Common.csproj
+++ b/MediaBrowser.Common/MediaBrowser.Common.csproj
@@ -1,4 +1,4 @@
-
+
@@ -18,8 +18,8 @@
-
-
+
+
@@ -29,7 +29,7 @@
- netstandard2.1
+ net5.0
false
true
true
diff --git a/MediaBrowser.Common/Net/DefaultHttpClientHandler.cs b/MediaBrowser.Common/Net/DefaultHttpClientHandler.cs
index e189d6e706..f1c5f24772 100644
--- a/MediaBrowser.Common/Net/DefaultHttpClientHandler.cs
+++ b/MediaBrowser.Common/Net/DefaultHttpClientHandler.cs
@@ -13,8 +13,7 @@ namespace MediaBrowser.Common.Net
///
public DefaultHttpClientHandler()
{
- // TODO change to DecompressionMethods.All with .NET5
- AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
+ AutomaticDecompression = DecompressionMethods.All;
}
}
}
diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs
index d9debeee35..e030416cac 100644
--- a/MediaBrowser.Common/Plugins/BasePlugin.cs
+++ b/MediaBrowser.Common/Plugins/BasePlugin.cs
@@ -83,16 +83,6 @@ namespace MediaBrowser.Common.Plugins
{
}
- ///
- public virtual void RegisterServices(IServiceCollection serviceCollection)
- {
- }
-
- ///
- public virtual void UnregisterServices(IServiceCollection serviceCollection)
- {
- }
-
///
public void SetAttributes(string assemblyFilePath, string dataFolderPath, Version assemblyVersion)
{
@@ -185,6 +175,11 @@ namespace MediaBrowser.Common.Plugins
/// The type of the configuration.
public Type ConfigurationType => typeof(TConfigurationType);
+ ///
+ /// Gets or sets the event handler that is triggered when this configuration changes.
+ ///
+ public EventHandler ConfigurationChanged { get; set; }
+
///
/// Gets the name the assembly file.
///
@@ -296,6 +291,8 @@ namespace MediaBrowser.Common.Plugins
Configuration = (TConfigurationType)configuration;
SaveConfiguration(Configuration);
+
+ ConfigurationChanged?.Invoke(this, configuration);
}
///
diff --git a/MediaBrowser.Common/Plugins/IPlugin.cs b/MediaBrowser.Common/Plugins/IPlugin.cs
index 1844eb124f..d583a58878 100644
--- a/MediaBrowser.Common/Plugins/IPlugin.cs
+++ b/MediaBrowser.Common/Plugins/IPlugin.cs
@@ -62,18 +62,6 @@ namespace MediaBrowser.Common.Plugins
/// Called when just before the plugin is uninstalled from the server.
///
void OnUninstalling();
-
- ///
- /// Registers the plugin's services to the service collection.
- ///
- /// The service collection.
- void RegisterServices(IServiceCollection serviceCollection);
-
- ///
- /// Unregisters the plugin's services from the service collection.
- ///
- /// The service collection.
- void UnregisterServices(IServiceCollection serviceCollection);
}
public interface IHasPluginConfiguration
diff --git a/MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs b/MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs
new file mode 100644
index 0000000000..3afe874c52
--- /dev/null
+++ b/MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs
@@ -0,0 +1,19 @@
+namespace MediaBrowser.Common.Plugins
+{
+ using Microsoft.Extensions.DependencyInjection;
+
+ ///
+ /// Defines the .
+ ///
+ public interface IPluginServiceRegistrator
+ {
+ ///
+ /// Registers the plugin's services with the service collection.
+ ///
+ ///
+ /// This interface is only used for service registration and requires a parameterless constructor.
+ ///
+ /// The service collection.
+ void RegisterServices(IServiceCollection serviceCollection);
+ }
+}
diff --git a/MediaBrowser.Common/Plugins/LocalPlugin.cs b/MediaBrowser.Common/Plugins/LocalPlugin.cs
new file mode 100644
index 0000000000..7927c663d4
--- /dev/null
+++ b/MediaBrowser.Common/Plugins/LocalPlugin.cs
@@ -0,0 +1,113 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+
+namespace MediaBrowser.Common.Plugins
+{
+ ///
+ /// Local plugin struct.
+ ///
+ public class LocalPlugin : IEquatable
+ {
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The plugin id.
+ /// The plugin name.
+ /// The plugin version.
+ /// The plugin path.
+ public LocalPlugin(Guid id, string name, Version version, string path)
+ {
+ Id = id;
+ Name = name;
+ Version = version;
+ Path = path;
+ DllFiles = new List();
+ }
+
+ ///
+ /// Gets the plugin id.
+ ///
+ public Guid Id { get; }
+
+ ///
+ /// Gets the plugin name.
+ ///
+ public string Name { get; }
+
+ ///
+ /// Gets the plugin version.
+ ///
+ public Version Version { get; }
+
+ ///
+ /// Gets the plugin path.
+ ///
+ public string Path { get; }
+
+ ///
+ /// Gets the list of dll files for this plugin.
+ ///
+ public List DllFiles { get; }
+
+ ///
+ /// == operator.
+ ///
+ /// Left item.
+ /// Right item.
+ /// Comparison result.
+ public static bool operator ==(LocalPlugin left, LocalPlugin right)
+ {
+ return left.Equals(right);
+ }
+
+ ///
+ /// != operator.
+ ///
+ /// Left item.
+ /// Right item.
+ /// Comparison result.
+ public static bool operator !=(LocalPlugin left, LocalPlugin right)
+ {
+ return !left.Equals(right);
+ }
+
+ ///
+ /// Compare two .
+ ///
+ /// The first item.
+ /// The second item.
+ /// Comparison result.
+ public static int Compare(LocalPlugin a, LocalPlugin b)
+ {
+ var compare = string.Compare(a.Name, b.Name, true, CultureInfo.InvariantCulture);
+
+ // Id is not equal but name is.
+ if (a.Id != b.Id && compare == 0)
+ {
+ compare = a.Id.CompareTo(b.Id);
+ }
+
+ return compare == 0 ? a.Version.CompareTo(b.Version) : compare;
+ }
+
+ ///
+ public override bool Equals(object obj)
+ {
+ return obj is LocalPlugin other && this.Equals(other);
+ }
+
+ ///
+ public override int GetHashCode()
+ {
+ return Name.GetHashCode(StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ public bool Equals(LocalPlugin other)
+ {
+ return Name.Equals(other.Name, StringComparison.OrdinalIgnoreCase)
+ && Id.Equals(other.Id);
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Updates/IInstallationManager.cs b/MediaBrowser.Common/Updates/IInstallationManager.cs
index 169aca2ca0..6aa16fea74 100644
--- a/MediaBrowser.Common/Updates/IInstallationManager.cs
+++ b/MediaBrowser.Common/Updates/IInstallationManager.cs
@@ -11,29 +11,6 @@ namespace MediaBrowser.Common.Updates
{
public interface IInstallationManager : IDisposable
{
- event EventHandler PackageInstalling;
-
- event EventHandler PackageInstallationCompleted;
-
- event EventHandler PackageInstallationFailed;
-
- event EventHandler PackageInstallationCancelled;
-
- ///
- /// Occurs when a plugin is uninstalled.
- ///
- event EventHandler PluginUninstalled;
-
- ///
- /// Occurs when a plugin is updated.
- ///
- event EventHandler PluginUpdated;
-
- ///
- /// Occurs when a plugin is installed.
- ///
- event EventHandler PluginInstalled;
-
///
/// Gets the completed installations.
///
diff --git a/MediaBrowser.Controller/Channels/InternalChannelFeatures.cs b/MediaBrowser.Controller/Channels/InternalChannelFeatures.cs
index 1074ce435e..137f5d095b 100644
--- a/MediaBrowser.Controller/Channels/InternalChannelFeatures.cs
+++ b/MediaBrowser.Controller/Channels/InternalChannelFeatures.cs
@@ -42,6 +42,7 @@ namespace MediaBrowser.Controller.Channels
/// Indicates if a sort ascending/descending toggle is supported or not.
///
public bool SupportsSortOrderToggle { get; set; }
+
///
/// Gets or sets the automatic refresh levels.
///
@@ -53,6 +54,7 @@ namespace MediaBrowser.Controller.Channels
///
/// The daily download limit.
public int? DailyDownloadLimit { get; set; }
+
///
/// Gets or sets a value indicating whether [supports downloading].
///
diff --git a/MediaBrowser.Controller/Drawing/IImageEncoder.cs b/MediaBrowser.Controller/Drawing/IImageEncoder.cs
index f9b2e6fef3..770c6dc2d2 100644
--- a/MediaBrowser.Controller/Drawing/IImageEncoder.cs
+++ b/MediaBrowser.Controller/Drawing/IImageEncoder.cs
@@ -1,4 +1,5 @@
#pragma warning disable CS1591
+#nullable enable
using System;
using System.Collections.Generic;
@@ -63,6 +64,7 @@ namespace MediaBrowser.Controller.Drawing
/// Create an image collage.
///
/// The options to use when creating the collage.
- void CreateImageCollage(ImageCollageOptions options);
+ /// Optional.
+ void CreateImageCollage(ImageCollageOptions options, string? libraryName);
}
}
diff --git a/MediaBrowser.Controller/Drawing/IImageProcessor.cs b/MediaBrowser.Controller/Drawing/IImageProcessor.cs
index b7edb10524..935a790312 100644
--- a/MediaBrowser.Controller/Drawing/IImageProcessor.cs
+++ b/MediaBrowser.Controller/Drawing/IImageProcessor.cs
@@ -1,4 +1,5 @@
#pragma warning disable CS1591
+#nullable enable
using System;
using System.Collections.Generic;
@@ -75,7 +76,7 @@ namespace MediaBrowser.Controller.Drawing
///
/// The options.
/// Task.
- Task<(string path, string mimeType, DateTime dateModified)> ProcessImage(ImageProcessingOptions options);
+ Task<(string path, string? mimeType, DateTime dateModified)> ProcessImage(ImageProcessingOptions options);
///
/// Gets the supported image output formats.
@@ -87,7 +88,8 @@ namespace MediaBrowser.Controller.Drawing
/// Creates the image collage.
///
/// The options.
- void CreateImageCollage(ImageCollageOptions options);
+ /// The library name to draw onto the collage.
+ void CreateImageCollage(ImageCollageOptions options, string? libraryName);
bool SupportsTransparency(string path);
}
diff --git a/MediaBrowser.Controller/Dto/DtoOptions.cs b/MediaBrowser.Controller/Dto/DtoOptions.cs
index 76f20ace2a..3567837507 100644
--- a/MediaBrowser.Controller/Dto/DtoOptions.cs
+++ b/MediaBrowser.Controller/Dto/DtoOptions.cs
@@ -1,6 +1,7 @@
#pragma warning disable CS1591
using System;
+using System.Collections.Generic;
using System.Linq;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Querying;
@@ -15,9 +16,9 @@ namespace MediaBrowser.Controller.Dto
ItemFields.RefreshState
};
- public ItemFields[] Fields { get; set; }
+ public IReadOnlyList Fields { get; set; }
- public ImageType[] ImageTypes { get; set; }
+ public IReadOnlyList ImageTypes { get; set; }
public int ImageTypeLimit { get; set; }
diff --git a/MediaBrowser.Controller/Entities/Audio/Audio.cs b/MediaBrowser.Controller/Entities/Audio/Audio.cs
index 2c6dea02cd..8220464b39 100644
--- a/MediaBrowser.Controller/Entities/Audio/Audio.cs
+++ b/MediaBrowser.Controller/Entities/Audio/Audio.cs
@@ -90,7 +90,6 @@ namespace MediaBrowser.Controller.Entities.Audio
var songKey = IndexNumber.HasValue ? IndexNumber.Value.ToString("0000") : string.Empty;
-
if (ParentIndexNumber.HasValue)
{
songKey = ParentIndexNumber.Value.ToString("0000") + "-" + songKey;
diff --git a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs
index 397a68ff7e..c5e50cf45d 100644
--- a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs
+++ b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs
@@ -56,7 +56,7 @@ namespace MediaBrowser.Controller.Entities.Audio
{
if (query.IncludeItemTypes.Length == 0)
{
- query.IncludeItemTypes = new[] { typeof(Audio).Name, typeof(MusicVideo).Name, typeof(MusicAlbum).Name };
+ query.IncludeItemTypes = new[] { nameof(Audio), nameof(MusicVideo), nameof(MusicAlbum) };
query.ArtistIds = new[] { Id };
}
diff --git a/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs b/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs
index 5a117a6b15..f0c076108e 100644
--- a/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs
+++ b/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs
@@ -64,7 +64,7 @@ namespace MediaBrowser.Controller.Entities.Audio
public IList GetTaggedItems(InternalItemsQuery query)
{
query.GenreIds = new[] { Id };
- query.IncludeItemTypes = new[] { typeof(MusicVideo).Name, typeof(Audio).Name, typeof(MusicAlbum).Name, typeof(MusicArtist).Name };
+ query.IncludeItemTypes = new[] { nameof(MusicVideo), nameof(Audio), nameof(MusicAlbum), nameof(MusicArtist) };
return LibraryManager.GetItemList(query);
}
diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs
index 68126bd8a8..1d44a55114 100644
--- a/MediaBrowser.Controller/Entities/BaseItem.cs
+++ b/MediaBrowser.Controller/Entities/BaseItem.cs
@@ -87,6 +87,8 @@ namespace MediaBrowser.Controller.Entities
public const string InterviewFolderName = "interviews";
public const string SceneFolderName = "scenes";
public const string SampleFolderName = "samples";
+ public const string ShortsFolderName = "shorts";
+ public const string FeaturettesFolderName = "featurettes";
public static readonly string[] AllExtrasTypesFolderNames = {
ExtrasFolderName,
@@ -94,7 +96,9 @@ namespace MediaBrowser.Controller.Entities
DeletedScenesFolderName,
InterviewFolderName,
SceneFolderName,
- SampleFolderName
+ SampleFolderName,
+ ShortsFolderName,
+ FeaturettesFolderName
};
[JsonIgnore]
@@ -197,6 +201,7 @@ namespace MediaBrowser.Controller.Entities
public virtual bool SupportsRemoteImageDownloading => true;
private string _name;
+
///
/// Gets or sets the name.
///
@@ -661,6 +666,7 @@ namespace MediaBrowser.Controller.Entities
}
private string _forcedSortName;
+
///
/// Gets or sets the name of the forced sort.
///
diff --git a/MediaBrowser.Controller/Entities/BaseItemExtensions.cs b/MediaBrowser.Controller/Entities/BaseItemExtensions.cs
index 8a69971d0f..c65477d39a 100644
--- a/MediaBrowser.Controller/Entities/BaseItemExtensions.cs
+++ b/MediaBrowser.Controller/Entities/BaseItemExtensions.cs
@@ -45,7 +45,8 @@ namespace MediaBrowser.Controller.Entities
{
if (file.StartsWith("http", System.StringComparison.OrdinalIgnoreCase))
{
- item.SetImage(new ItemImageInfo
+ item.SetImage(
+ new ItemImageInfo
{
Path = file,
Type = imageType
diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs
index 11542c1cad..a76c8a376b 100644
--- a/MediaBrowser.Controller/Entities/Folder.cs
+++ b/MediaBrowser.Controller/Entities/Folder.cs
@@ -255,7 +255,8 @@ namespace MediaBrowser.Controller.Entities
var id = child.Id;
if (dictionary.ContainsKey(id))
{
- Logger.LogError("Found folder containing items with duplicate id. Path: {path}, Child Name: {ChildName}",
+ Logger.LogError(
+ "Found folder containing items with duplicate id. Path: {path}, Child Name: {ChildName}",
Path ?? Name,
child.Path ?? child.Name);
}
@@ -722,7 +723,7 @@ namespace MediaBrowser.Controller.Entities
private bool RequiresPostFiltering2(InternalItemsQuery query)
{
- if (query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], typeof(BoxSet).Name, StringComparison.OrdinalIgnoreCase))
+ if (query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], nameof(BoxSet), StringComparison.OrdinalIgnoreCase))
{
Logger.LogDebug("Query requires post-filtering due to BoxSet query");
return true;
@@ -812,7 +813,7 @@ namespace MediaBrowser.Controller.Entities
if (query.IsPlayed.HasValue)
{
- if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(typeof(Series).Name))
+ if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(nameof(Series)))
{
Logger.LogDebug("Query requires post-filtering due to IsPlayed");
return true;
@@ -984,7 +985,8 @@ namespace MediaBrowser.Controller.Entities
return items;
}
- private static bool CollapseBoxSetItems(InternalItemsQuery query,
+ private static bool CollapseBoxSetItems(
+ InternalItemsQuery query,
BaseItem queryParent,
User user,
IServerConfigurationManager configurationManager)
@@ -1386,7 +1388,6 @@ namespace MediaBrowser.Controller.Entities
}
}
-
///
/// Gets the linked children.
///
@@ -1594,7 +1595,8 @@ namespace MediaBrowser.Controller.Entities
/// The date played.
/// if set to true [reset position].
/// Task.
- public override void MarkPlayed(User user,
+ public override void MarkPlayed(
+ User user,
DateTime? datePlayed,
bool resetPosition)
{
diff --git a/MediaBrowser.Controller/Entities/Genre.cs b/MediaBrowser.Controller/Entities/Genre.cs
index db6c85caf7..74a1702040 100644
--- a/MediaBrowser.Controller/Entities/Genre.cs
+++ b/MediaBrowser.Controller/Entities/Genre.cs
@@ -59,7 +59,13 @@ namespace MediaBrowser.Controller.Entities
public IList GetTaggedItems(InternalItemsQuery query)
{
query.GenreIds = new[] { Id };
- query.ExcludeItemTypes = new[] { typeof(MusicVideo).Name, typeof(Audio.Audio).Name, typeof(MusicAlbum).Name, typeof(MusicArtist).Name };
+ query.ExcludeItemTypes = new[]
+ {
+ nameof(MusicVideo),
+ nameof(Entities.Audio.Audio),
+ nameof(MusicAlbum),
+ nameof(MusicArtist)
+ };
return LibraryManager.GetItemList(query);
}
diff --git a/MediaBrowser.Controller/Entities/IHasMediaSources.cs b/MediaBrowser.Controller/Entities/IHasMediaSources.cs
index a7b60d1688..0f612262a8 100644
--- a/MediaBrowser.Controller/Entities/IHasMediaSources.cs
+++ b/MediaBrowser.Controller/Entities/IHasMediaSources.cs
@@ -21,7 +21,5 @@ namespace MediaBrowser.Controller.Entities
List GetMediaSources(bool enablePathSubstitution);
List GetMediaStreams();
-
-
}
}
diff --git a/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs b/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs
index 4e09ee5736..5b96a5af65 100644
--- a/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs
+++ b/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs
@@ -1,6 +1,7 @@
#pragma warning disable CS1591
using System;
+using Jellyfin.Data.Entities;
namespace MediaBrowser.Controller.Entities
{
@@ -23,6 +24,10 @@ namespace MediaBrowser.Controller.Entities
public string NameContains { get; set; }
+ public User User { get; set; }
+
+ public bool? IsFavorite { get; set; }
+
public InternalPeopleQuery()
{
PersonTypes = Array.Empty();
diff --git a/MediaBrowser.Controller/Entities/Photo.cs b/MediaBrowser.Controller/Entities/Photo.cs
index 1485d4c792..2fc66176f6 100644
--- a/MediaBrowser.Controller/Entities/Photo.cs
+++ b/MediaBrowser.Controller/Entities/Photo.cs
@@ -16,7 +16,6 @@ namespace MediaBrowser.Controller.Entities
[JsonIgnore]
public override Folder LatestItemsIndexContainer => AlbumEntity;
-
[JsonIgnore]
public PhotoAlbum AlbumEntity
{
diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs
index 72c696c1ae..e8afa9a490 100644
--- a/MediaBrowser.Controller/Entities/TV/Series.cs
+++ b/MediaBrowser.Controller/Entities/TV/Series.cs
@@ -151,7 +151,7 @@ namespace MediaBrowser.Controller.Entities.TV
if (query.IncludeItemTypes.Length == 0)
{
- query.IncludeItemTypes = new[] { typeof(Episode).Name };
+ query.IncludeItemTypes = new[] { nameof(Episode) };
}
query.IsVirtualItem = false;
@@ -207,7 +207,7 @@ namespace MediaBrowser.Controller.Entities.TV
query.AncestorWithPresentationUniqueKey = null;
query.SeriesPresentationUniqueKey = seriesKey;
- query.IncludeItemTypes = new[] { typeof(Season).Name };
+ query.IncludeItemTypes = new[] { nameof(Season) };
query.OrderBy = new[] { ItemSortBy.SortName }.Select(i => new ValueTuple(i, SortOrder.Ascending)).ToArray();
if (user != null && !user.DisplayMissingEpisodes)
@@ -233,7 +233,7 @@ namespace MediaBrowser.Controller.Entities.TV
if (query.IncludeItemTypes.Length == 0)
{
- query.IncludeItemTypes = new[] { typeof(Episode).Name, typeof(Season).Name };
+ query.IncludeItemTypes = new[] { nameof(Episode), nameof(Season) };
}
query.IsVirtualItem = false;
@@ -253,7 +253,7 @@ namespace MediaBrowser.Controller.Entities.TV
{
AncestorWithPresentationUniqueKey = null,
SeriesPresentationUniqueKey = seriesKey,
- IncludeItemTypes = new[] { typeof(Episode).Name, typeof(Season).Name },
+ IncludeItemTypes = new[] { nameof(Episode), nameof(Season) },
OrderBy = new[] { ItemSortBy.SortName }.Select(i => new ValueTuple(i, SortOrder.Ascending)).ToArray(),
DtoOptions = options
};
@@ -364,7 +364,7 @@ namespace MediaBrowser.Controller.Entities.TV
{
AncestorWithPresentationUniqueKey = queryFromSeries ? null : seriesKey,
SeriesPresentationUniqueKey = queryFromSeries ? seriesKey : null,
- IncludeItemTypes = new[] { typeof(Episode).Name },
+ IncludeItemTypes = new[] { nameof(Episode) },
OrderBy = new[] { ItemSortBy.SortName }.Select(i => new ValueTuple(i, SortOrder.Ascending)).ToArray(),
DtoOptions = options
};
@@ -450,7 +450,6 @@ namespace MediaBrowser.Controller.Entities.TV
});
}
-
protected override bool GetBlockUnratedValue(User user)
{
return user.GetPreference(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Series.ToString());
diff --git a/MediaBrowser.Controller/Entities/UserViewBuilder.cs b/MediaBrowser.Controller/Entities/UserViewBuilder.cs
index b384b27d1a..a262fee15d 100644
--- a/MediaBrowser.Controller/Entities/UserViewBuilder.cs
+++ b/MediaBrowser.Controller/Entities/UserViewBuilder.cs
@@ -142,7 +142,7 @@ namespace MediaBrowser.Controller.Entities
if (query.IncludeItemTypes.Length == 0)
{
- query.IncludeItemTypes = new[] { typeof(Movie).Name };
+ query.IncludeItemTypes = new[] { nameof(Movie) };
}
return parent.QueryRecursive(query);
@@ -167,7 +167,7 @@ namespace MediaBrowser.Controller.Entities
query.Parent = parent;
query.SetUser(user);
query.IsFavorite = true;
- query.IncludeItemTypes = new[] { typeof(Movie).Name };
+ query.IncludeItemTypes = new[] { nameof(Movie) };
return _libraryManager.GetItemsResult(query);
}
@@ -178,7 +178,7 @@ namespace MediaBrowser.Controller.Entities
query.Parent = parent;
query.SetUser(user);
query.IsFavorite = true;
- query.IncludeItemTypes = new[] { typeof(Series).Name };
+ query.IncludeItemTypes = new[] { nameof(Series) };
return _libraryManager.GetItemsResult(query);
}
@@ -189,7 +189,7 @@ namespace MediaBrowser.Controller.Entities
query.Parent = parent;
query.SetUser(user);
query.IsFavorite = true;
- query.IncludeItemTypes = new[] { typeof(Episode).Name };
+ query.IncludeItemTypes = new[] { nameof(Episode) };
return _libraryManager.GetItemsResult(query);
}
@@ -200,7 +200,7 @@ namespace MediaBrowser.Controller.Entities
query.Parent = parent;
query.SetUser(user);
- query.IncludeItemTypes = new[] { typeof(Movie).Name };
+ query.IncludeItemTypes = new[] { nameof(Movie) };
return _libraryManager.GetItemsResult(query);
}
@@ -208,7 +208,7 @@ namespace MediaBrowser.Controller.Entities
private QueryResult GetMovieCollections(Folder parent, User user, InternalItemsQuery query)
{
query.Parent = null;
- query.IncludeItemTypes = new[] { typeof(BoxSet).Name };
+ query.IncludeItemTypes = new[] { nameof(BoxSet) };
query.SetUser(user);
query.Recursive = true;
@@ -223,7 +223,7 @@ namespace MediaBrowser.Controller.Entities
query.Parent = parent;
query.SetUser(user);
query.Limit = GetSpecialItemsLimit();
- query.IncludeItemTypes = new[] { typeof(Movie).Name };
+ query.IncludeItemTypes = new[] { nameof(Movie) };
return ConvertToResult(_libraryManager.GetItemList(query));
}
@@ -236,7 +236,7 @@ namespace MediaBrowser.Controller.Entities
query.Parent = parent;
query.SetUser(user);
query.Limit = GetSpecialItemsLimit();
- query.IncludeItemTypes = new[] { typeof(Movie).Name };
+ query.IncludeItemTypes = new[] { nameof(Movie) };
return ConvertToResult(_libraryManager.GetItemList(query));
}
@@ -255,10 +255,9 @@ namespace MediaBrowser.Controller.Entities
{
var genres = parent.QueryRecursive(new InternalItemsQuery(user)
{
- IncludeItemTypes = new[] { typeof(Movie).Name },
+ IncludeItemTypes = new[] { nameof(Movie) },
Recursive = true,
EnableTotalRecordCount = false
-
}).Items
.SelectMany(i => i.Genres)
.DistinctNames()
@@ -287,7 +286,7 @@ namespace MediaBrowser.Controller.Entities
query.GenreIds = new[] { displayParent.Id };
query.SetUser(user);
- query.IncludeItemTypes = new[] { typeof(Movie).Name };
+ query.IncludeItemTypes = new[] { nameof(Movie) };
return _libraryManager.GetItemsResult(query);
}
@@ -334,7 +333,7 @@ namespace MediaBrowser.Controller.Entities
query.Parent = parent;
query.SetUser(user);
query.Limit = GetSpecialItemsLimit();
- query.IncludeItemTypes = new[] { typeof(Episode).Name };
+ query.IncludeItemTypes = new[] { nameof(Episode) };
query.IsVirtualItem = false;
return ConvertToResult(_libraryManager.GetItemList(query));
@@ -344,7 +343,8 @@ namespace MediaBrowser.Controller.Entities
{
var parentFolders = GetMediaFolders(parent, query.User, new[] { CollectionType.TvShows, string.Empty });
- var result = _tvSeriesManager.GetNextUp(new NextUpQuery
+ var result = _tvSeriesManager.GetNextUp(
+ new NextUpQuery
{
Limit = query.Limit,
StartIndex = query.StartIndex,
@@ -362,7 +362,7 @@ namespace MediaBrowser.Controller.Entities
query.Parent = parent;
query.SetUser(user);
query.Limit = GetSpecialItemsLimit();
- query.IncludeItemTypes = new[] { typeof(Episode).Name };
+ query.IncludeItemTypes = new[] { nameof(Episode) };
return ConvertToResult(_libraryManager.GetItemList(query));
}
@@ -373,7 +373,7 @@ namespace MediaBrowser.Controller.Entities
query.Parent = parent;
query.SetUser(user);
- query.IncludeItemTypes = new[] { typeof(Series).Name };
+ query.IncludeItemTypes = new[] { nameof(Series) };
return _libraryManager.GetItemsResult(query);
}
@@ -382,7 +382,7 @@ namespace MediaBrowser.Controller.Entities
{
var genres = parent.QueryRecursive(new InternalItemsQuery(user)
{
- IncludeItemTypes = new[] { typeof(Series).Name },
+ IncludeItemTypes = new[] { nameof(Series) },
Recursive = true,
EnableTotalRecordCount = false
}).Items
@@ -413,7 +413,7 @@ namespace MediaBrowser.Controller.Entities
query.GenreIds = new[] { displayParent.Id };
query.SetUser(user);
- query.IncludeItemTypes = new[] { typeof(Series).Name };
+ query.IncludeItemTypes = new[] { nameof(Series) };
return _libraryManager.GetItemsResult(query);
}
@@ -444,7 +444,8 @@ namespace MediaBrowser.Controller.Entities
return Filter(item, query.User, query, BaseItem.UserDataManager, BaseItem.LibraryManager);
}
- public static QueryResult PostFilterAndSort(IEnumerable items,
+ public static QueryResult PostFilterAndSort(
+ IEnumerable items,
BaseItem queryParent,
int? totalRecordLimit,
InternalItemsQuery query,
diff --git a/MediaBrowser.Controller/IDisplayPreferencesManager.cs b/MediaBrowser.Controller/IDisplayPreferencesManager.cs
index b35f830960..6658269bdb 100644
--- a/MediaBrowser.Controller/IDisplayPreferencesManager.cs
+++ b/MediaBrowser.Controller/IDisplayPreferencesManager.cs
@@ -12,6 +12,9 @@ namespace MediaBrowser.Controller
///
/// Gets the display preferences for the user and client.
///
+ ///
+ /// This will create the display preferences if it does not exist, but it will not save automatically.
+ ///
/// The user's id.
/// The client string.
/// The associated display preferences.
@@ -20,6 +23,9 @@ namespace MediaBrowser.Controller
///
/// Gets the default item display preferences for the user and client.
///
+ ///
+ /// This will create the item display preferences if it does not exist, but it will not save automatically.
+ ///
/// The user id.
/// The item id.
/// The client string.
diff --git a/MediaBrowser.Controller/IO/FileData.cs b/MediaBrowser.Controller/IO/FileData.cs
index 9bc4cac39d..3db60ae0bb 100644
--- a/MediaBrowser.Controller/IO/FileData.cs
+++ b/MediaBrowser.Controller/IO/FileData.cs
@@ -111,5 +111,4 @@ namespace MediaBrowser.Controller.IO
return returnResult;
}
}
-
}
diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs
index cfad17fb72..ffbb147b0d 100644
--- a/MediaBrowser.Controller/IServerApplicationHost.cs
+++ b/MediaBrowser.Controller/IServerApplicationHost.cs
@@ -6,8 +6,8 @@ using System.Net;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common;
+using MediaBrowser.Common.Plugins;
using MediaBrowser.Model.System;
-using Microsoft.AspNetCore.Http;
namespace MediaBrowser.Controller
{
@@ -56,10 +56,11 @@ namespace MediaBrowser.Controller
///
/// Gets the system info.
///
+ /// A cancellation token that can be used to cancel the task.
/// SystemInfo.
- Task GetSystemInfo(CancellationToken cancellationToken);
+ Task GetSystemInfo(CancellationToken cancellationToken = default);
- Task GetPublicSystemInfo(CancellationToken cancellationToken);
+ Task GetPublicSystemInfo(CancellationToken cancellationToken = default);
///
/// Gets all the local IP addresses of this API instance. Each address is validated by sending a 'ping' request
@@ -67,7 +68,7 @@ namespace MediaBrowser.Controller
///
/// A cancellation token that can be used to cancel the task.
/// A list containing all the local IP addresses of the server.
- Task> GetLocalIpAddresses(CancellationToken cancellationToken);
+ Task> GetLocalIpAddresses(CancellationToken cancellationToken = default);
///
/// Gets a local (LAN) URL that can be used to access the API. The hostname used is the first valid configured
@@ -75,7 +76,7 @@ namespace MediaBrowser.Controller
///
/// A cancellation token that can be used to cancel the task.
/// The server URL.
- Task GetLocalApiUrl(CancellationToken cancellationToken);
+ Task GetLocalApiUrl(CancellationToken cancellationToken = default);
///
/// Gets a localhost URL that can be used to access the API using the loop-back IP address (127.0.0.1)
@@ -119,5 +120,13 @@ namespace MediaBrowser.Controller
string ExpandVirtualPath(string path);
string ReverseVirtualPath(string path);
+
+ ///
+ /// Gets the list of local plugins.
+ ///
+ /// Plugin base directory.
+ /// Cleanup old plugins.
+ /// Enumerable of local plugins.
+ IEnumerable GetLocalPlugins(string path, bool cleanup = true);
}
}
diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs
index 804170d5c9..c7c79df76d 100644
--- a/MediaBrowser.Controller/Library/ILibraryManager.cs
+++ b/MediaBrowser.Controller/Library/ILibraryManager.cs
@@ -77,6 +77,7 @@ namespace MediaBrowser.Controller.Library
MusicArtist GetArtist(string name);
MusicArtist GetArtist(string name, DtoOptions options);
+
///
/// Gets a Studio.
///
@@ -234,6 +235,7 @@ namespace MediaBrowser.Controller.Library
/// Occurs when [item updated].
///
event EventHandler ItemUpdated;
+
///
/// Occurs when [item removed].
///
@@ -564,8 +566,11 @@ namespace MediaBrowser.Controller.Library
int GetCount(InternalItemsQuery query);
- void AddExternalSubtitleStreams(List streams,
+ void AddExternalSubtitleStreams(
+ List streams,
string videoPath,
string[] files);
+
+ BaseItem GetParentItem(string parentId, Guid? userId);
}
}
diff --git a/MediaBrowser.Controller/Library/IMediaSourceManager.cs b/MediaBrowser.Controller/Library/IMediaSourceManager.cs
index 9e7b1e6085..21c6ef2af1 100644
--- a/MediaBrowser.Controller/Library/IMediaSourceManager.cs
+++ b/MediaBrowser.Controller/Library/IMediaSourceManager.cs
@@ -28,12 +28,14 @@ namespace MediaBrowser.Controller.Library
/// The item identifier.
/// IEnumerable<MediaStream>.
List GetMediaStreams(Guid itemId);
+
///
/// Gets the media streams.
///
/// The media source identifier.
/// IEnumerable<MediaStream>.
List GetMediaStreams(string mediaSourceId);
+
///
/// Gets the media streams.
///
@@ -113,5 +115,7 @@ namespace MediaBrowser.Controller.Library
public interface IDirectStreamProvider
{
Task CopyToAsync(Stream stream, CancellationToken cancellationToken);
+
+ string GetFilePath();
}
}
diff --git a/MediaBrowser.Controller/Library/IUserManager.cs b/MediaBrowser.Controller/Library/IUserManager.cs
index 6a4f5cf679..8fd3b8c347 100644
--- a/MediaBrowser.Controller/Library/IUserManager.cs
+++ b/MediaBrowser.Controller/Library/IUserManager.cs
@@ -158,7 +158,8 @@ namespace MediaBrowser.Controller.Library
///
/// The user's Id.
/// The request containing the new user configuration.
- void UpdateConfiguration(Guid userId, UserConfiguration config);
+ /// A task representing the update.
+ Task UpdateConfigurationAsync(Guid userId, UserConfiguration config);
///
/// This method updates the user's policy.
@@ -167,12 +168,14 @@ namespace MediaBrowser.Controller.Library
///
/// The user's Id.
/// The request containing the new user policy.
- void UpdatePolicy(Guid userId, UserPolicy policy);
+ /// A task representing the update.
+ Task UpdatePolicyAsync(Guid userId, UserPolicy policy);
///
/// Clears the user's profile image.
///
/// The user.
- void ClearProfileImage(User user);
+ /// A task representing the clearing of the profile image.
+ Task ClearProfileImageAsync(User user);
}
}
diff --git a/MediaBrowser.Controller/Library/ItemResolveArgs.cs b/MediaBrowser.Controller/Library/ItemResolveArgs.cs
index 6a0dbeba2f..12a311dc33 100644
--- a/MediaBrowser.Controller/Library/ItemResolveArgs.cs
+++ b/MediaBrowser.Controller/Library/ItemResolveArgs.cs
@@ -156,6 +156,7 @@ namespace MediaBrowser.Controller.Library
}
// REVIEW: @bond
+
///
/// Gets the physical locations.
///
diff --git a/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs b/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs
index 55c3309317..54495c1c40 100644
--- a/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs
+++ b/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs
@@ -225,12 +225,13 @@ namespace MediaBrowser.Controller.LiveTv
/// The fields.
/// The user.
/// Task.
- Task AddInfoToProgramDto(IReadOnlyCollection<(BaseItem, BaseItemDto)> programs, ItemFields[] fields, User user = null);
+ Task AddInfoToProgramDto(IReadOnlyCollection<(BaseItem, BaseItemDto)> programs, IReadOnlyList fields, User user = null);
///
/// Saves the tuner host.
///
Task SaveTunerHost(TunerHostInfo info, bool dataSourceChanged = true);
+
///
/// Saves the listing provider.
///
diff --git a/MediaBrowser.Controller/LiveTv/ITunerHost.cs b/MediaBrowser.Controller/LiveTv/ITunerHost.cs
index ff92bf856c..abca8f2390 100644
--- a/MediaBrowser.Controller/LiveTv/ITunerHost.cs
+++ b/MediaBrowser.Controller/LiveTv/ITunerHost.cs
@@ -56,7 +56,6 @@ namespace MediaBrowser.Controller.LiveTv
Task> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken);
Task> DiscoverDevices(int discoveryDurationMs, CancellationToken cancellationToken);
-
}
public interface IConfigurableTunerHost
diff --git a/MediaBrowser.Controller/LiveTv/LiveTvServiceStatusInfo.cs b/MediaBrowser.Controller/LiveTv/LiveTvServiceStatusInfo.cs
index 02178297b1..b629749049 100644
--- a/MediaBrowser.Controller/LiveTv/LiveTvServiceStatusInfo.cs
+++ b/MediaBrowser.Controller/LiveTv/LiveTvServiceStatusInfo.cs
@@ -42,6 +42,7 @@ namespace MediaBrowser.Controller.LiveTv
///
/// The tuners.
public List Tuners { get; set; }
+
///
/// Gets or sets a value indicating whether this instance is visible.
///
diff --git a/MediaBrowser.Controller/LiveTv/ProgramInfo.cs b/MediaBrowser.Controller/LiveTv/ProgramInfo.cs
index bdcffd5cae..f9f559ee96 100644
--- a/MediaBrowser.Controller/LiveTv/ProgramInfo.cs
+++ b/MediaBrowser.Controller/LiveTv/ProgramInfo.cs
@@ -35,6 +35,7 @@ namespace MediaBrowser.Controller.LiveTv
///
/// The overview.
public string Overview { get; set; }
+
///
/// Gets or sets the short overview.
///
@@ -169,31 +170,37 @@ namespace MediaBrowser.Controller.LiveTv
///
/// The production year.
public int? ProductionYear { get; set; }
+
///
/// Gets or sets the home page URL.
///
/// The home page URL.
public string HomePageUrl { get; set; }
+
///
/// Gets or sets the series identifier.
///
/// The series identifier.
public string SeriesId { get; set; }
+
///
/// Gets or sets the show identifier.
///
/// The show identifier.
public string ShowId { get; set; }
+
///
/// Gets or sets the season number.
///
/// The season number.
public int? SeasonNumber { get; set; }
+
///
/// Gets or sets the episode number.
///
/// The episode number.
public int? EpisodeNumber { get; set; }
+
///
/// Gets or sets the etag.
///
diff --git a/MediaBrowser.Controller/LiveTv/RecordingInfo.cs b/MediaBrowser.Controller/LiveTv/RecordingInfo.cs
index 303882b7ef..69190694ff 100644
--- a/MediaBrowser.Controller/LiveTv/RecordingInfo.cs
+++ b/MediaBrowser.Controller/LiveTv/RecordingInfo.cs
@@ -187,6 +187,7 @@ namespace MediaBrowser.Controller.LiveTv
///
/// null if [has image] contains no value, true if [has image]; otherwise, false.
public bool? HasImage { get; set; }
+
///
/// Gets or sets the show identifier.
///
diff --git a/MediaBrowser.Controller/LiveTv/TimerInfo.cs b/MediaBrowser.Controller/LiveTv/TimerInfo.cs
index bcef4666d2..aa5170617d 100644
--- a/MediaBrowser.Controller/LiveTv/TimerInfo.cs
+++ b/MediaBrowser.Controller/LiveTv/TimerInfo.cs
@@ -113,6 +113,7 @@ namespace MediaBrowser.Controller.LiveTv
// Program properties
public int? SeasonNumber { get; set; }
+
///
/// Gets or sets the episode number.
///
diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj
index 6544704065..9acc98dcec 100644
--- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj
+++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj
@@ -14,8 +14,8 @@
-
-
+
+
@@ -29,7 +29,7 @@
- netstandard2.1
+ net5.0
false
true
true
diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
index 2c30ca4588..5846a603a2 100644
--- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
+++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs
@@ -70,15 +70,15 @@ namespace MediaBrowser.Controller.MediaEncoding
var codecMap = new Dictionary(StringComparer.OrdinalIgnoreCase)
{
- {"qsv", hwEncoder + "_qsv"},
- {hwEncoder + "_qsv", hwEncoder + "_qsv"},
- {"nvenc", hwEncoder + "_nvenc"},
- {"amf", hwEncoder + "_amf"},
- {"omx", hwEncoder + "_omx"},
- {hwEncoder + "_v4l2m2m", hwEncoder + "_v4l2m2m"},
- {"mediacodec", hwEncoder + "_mediacodec"},
- {"vaapi", hwEncoder + "_vaapi"},
- {"videotoolbox", hwEncoder + "_videotoolbox"}
+ { "qsv", hwEncoder + "_qsv" },
+ { hwEncoder + "_qsv", hwEncoder + "_qsv" },
+ { "nvenc", hwEncoder + "_nvenc" },
+ { "amf", hwEncoder + "_amf" },
+ { "omx", hwEncoder + "_omx" },
+ { hwEncoder + "_v4l2m2m", hwEncoder + "_v4l2m2m" },
+ { "mediacodec", hwEncoder + "_mediacodec" },
+ { "vaapi", hwEncoder + "_vaapi" },
+ { "videotoolbox", hwEncoder + "_videotoolbox" }
};
if (!string.IsNullOrEmpty(hwType)
@@ -109,7 +109,6 @@ namespace MediaBrowser.Controller.MediaEncoding
}
return _mediaEncoder.SupportsHwaccel("vaapi");
-
}
///
@@ -452,11 +451,13 @@ namespace MediaBrowser.Controller.MediaEncoding
var arg = new StringBuilder();
var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, encodingOptions) ?? string.Empty;
var outputVideoCodec = GetVideoEncoder(state, encodingOptions) ?? string.Empty;
+ var isSwDecoder = string.IsNullOrEmpty(videoDecoder);
+ var isD3d11vaDecoder = videoDecoder.IndexOf("d3d11va", StringComparison.OrdinalIgnoreCase) != -1;
var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
var isVaapiEncoder = outputVideoCodec.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
var isQsvDecoder = videoDecoder.IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1;
var isQsvEncoder = outputVideoCodec.IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1;
- var isNvencHevcDecoder = videoDecoder.IndexOf("hevc_cuvid", StringComparison.OrdinalIgnoreCase) != -1;
+ var isNvdecHevcDecoder = videoDecoder.IndexOf("hevc_cuvid", StringComparison.OrdinalIgnoreCase) != -1;
var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
var isMacOS = RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
@@ -508,6 +509,7 @@ namespace MediaBrowser.Controller.MediaEncoding
arg.Append("-hwaccel qsv ");
}
}
+
// While using SW decoder
else
{
@@ -517,11 +519,12 @@ namespace MediaBrowser.Controller.MediaEncoding
}
if (state.IsVideoRequest
- && string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase))
+ && (string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && isNvdecHevcDecoder || isSwDecoder)
+ || (string.Equals(encodingOptions.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase) && isD3d11vaDecoder || isSwDecoder))
{
var isColorDepth10 = IsColorDepth10(state);
- if (isNvencHevcDecoder && isColorDepth10
+ if (isColorDepth10
&& _mediaEncoder.SupportsHwaccel("opencl")
&& encodingOptions.EnableTonemapping
&& !string.IsNullOrEmpty(state.VideoStream.VideoRange)
@@ -880,6 +883,19 @@ namespace MediaBrowser.Controller.MediaEncoding
param += "-quality speed";
break;
}
+
+ var videoStream = state.VideoStream;
+ var isColorDepth10 = IsColorDepth10(state);
+
+ if (isColorDepth10
+ && _mediaEncoder.SupportsHwaccel("opencl")
+ && encodingOptions.EnableTonemapping
+ && !string.IsNullOrEmpty(videoStream.VideoRange)
+ && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase))
+ {
+ // Enhance workload when tone mapping with AMF on some APUs
+ param += " -preanalysis true";
+ }
}
else if (string.Equals(videoEncoder, "libvpx", StringComparison.OrdinalIgnoreCase)) // webm
{
@@ -1023,19 +1039,19 @@ namespace MediaBrowser.Controller.MediaEncoding
&& !string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
{
param = "-pix_fmt yuv420p " + param;
}
- if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase))
{
- var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, encodingOptions) ?? string.Empty;
var videoStream = state.VideoStream;
var isColorDepth10 = IsColorDepth10(state);
- if (videoDecoder.IndexOf("hevc_cuvid", StringComparison.OrdinalIgnoreCase) != -1
- && isColorDepth10
+ if (isColorDepth10
&& _mediaEncoder.SupportsHwaccel("opencl")
&& encodingOptions.EnableTonemapping
&& !string.IsNullOrEmpty(videoStream.VideoRange)
@@ -1364,24 +1380,40 @@ namespace MediaBrowser.Controller.MediaEncoding
public int? GetAudioBitrateParam(BaseEncodingJobOptions request, MediaStream audioStream)
{
+ if (audioStream == null)
+ {
+ return null;
+ }
+
if (request.AudioBitRate.HasValue)
{
// Don't encode any higher than this
return Math.Min(384000, request.AudioBitRate.Value);
}
- return null;
+ // Empty bitrate area is not allow on iOS
+ // Default audio bitrate to 128K if it is not being requested
+ // https://ffmpeg.org/ffmpeg-codecs.html#toc-Codec-Options
+ return 128000;
}
public int? GetAudioBitrateParam(int? audioBitRate, MediaStream audioStream)
{
+ if (audioStream == null)
+ {
+ return null;
+ }
+
if (audioBitRate.HasValue)
{
// Don't encode any higher than this
return Math.Min(384000, audioBitRate.Value);
}
- return null;
+ // Empty bitrate area is not allow on iOS
+ // Default audio bitrate to 128K if it is not being requested
+ // https://ffmpeg.org/ffmpeg-codecs.html#toc-Codec-Options
+ return 128000;
}
public string GetAudioFilterParam(EncodingJobInfo state, EncodingOptions encodingOptions, bool isHls)
@@ -1441,7 +1473,6 @@ namespace MediaBrowser.Controller.MediaEncoding
var codec = outputAudioCodec ?? string.Empty;
-
int? transcoderChannelLimit;
if (codec.IndexOf("wma", StringComparison.OrdinalIgnoreCase) != -1)
{
@@ -1652,47 +1683,7 @@ namespace MediaBrowser.Controller.MediaEncoding
var outputSizeParam = ReadOnlySpan.Empty;
var request = state.BaseRequest;
- outputSizeParam = GetOutputSizeParam(state, options, outputVideoCodec).TrimEnd('"');
-
- // All possible beginning of video filters
- // Don't break the order
- string[] beginOfOutputSizeParam = new[]
- {
- // for tonemap_opencl
- "hwupload,tonemap_opencl",
-
- // hwupload=extra_hw_frames=64,vpp_qsv (for overlay_qsv on linux)
- "hwupload=extra_hw_frames",
-
- // vpp_qsv
- "vpp",
-
- // hwdownload,format=p010le (hardware decode + software encode for vaapi)
- "hwdownload",
-
- // format=nv12|vaapi,hwupload,scale_vaapi
- "format",
-
- // bwdif,scale=expr
- "bwdif",
-
- // yadif,scale=expr
- "yadif",
-
- // scale=expr
- "scale"
- };
-
- var index = -1;
- foreach (var param in beginOfOutputSizeParam)
- {
- index = outputSizeParam.IndexOf(param, StringComparison.OrdinalIgnoreCase);
- if (index != -1)
- {
- outputSizeParam = outputSizeParam.Slice(index);
- break;
- }
- }
+ outputSizeParam = GetOutputSizeParamInternal(state, options, outputVideoCodec);
var videoSizeParam = string.Empty;
var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, options) ?? string.Empty;
@@ -1823,7 +1814,8 @@ namespace MediaBrowser.Controller.MediaEncoding
return (Convert.ToInt32(outputWidth), Convert.ToInt32(outputHeight));
}
- public List GetScalingFilters(EncodingJobInfo state,
+ public List GetScalingFilters(
+ EncodingJobInfo state,
int? videoWidth,
int? videoHeight,
Video3DFormat? threedFormat,
@@ -2083,10 +2075,19 @@ namespace MediaBrowser.Controller.MediaEncoding
return string.Format(CultureInfo.InvariantCulture, filter, widthParam, heightParam);
}
+ public string GetOutputSizeParam(
+ EncodingJobInfo state,
+ EncodingOptions options,
+ string outputVideoCodec)
+ {
+ string filters = GetOutputSizeParamInternal(state, options, outputVideoCodec);
+ return string.IsNullOrEmpty(filters) ? string.Empty : " -vf \"" + filters + "\"";
+ }
+
///
/// If we're going to put a fixed size on the command line, this will calculate it.
///
- public string GetOutputSizeParam(
+ public string GetOutputSizeParamInternal(
EncodingJobInfo state,
EncodingOptions options,
string outputVideoCodec)
@@ -2102,6 +2103,8 @@ namespace MediaBrowser.Controller.MediaEncoding
var inputHeight = videoStream?.Height;
var threeDFormat = state.MediaSource.Video3DFormat;
+ var isSwDecoder = string.IsNullOrEmpty(videoDecoder);
+ var isD3d11vaDecoder = videoDecoder.IndexOf("d3d11va", StringComparison.OrdinalIgnoreCase) != -1;
var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
var isVaapiH264Encoder = outputVideoCodec.IndexOf("h264_vaapi", StringComparison.OrdinalIgnoreCase) != -1;
var isQsvH264Encoder = outputVideoCodec.IndexOf("h264_qsv", StringComparison.OrdinalIgnoreCase) != -1;
@@ -2117,47 +2120,77 @@ namespace MediaBrowser.Controller.MediaEncoding
// If double rate deinterlacing is enabled and the input framerate is 30fps or below, otherwise the output framerate will be too high for many devices
var doubleRateDeinterlace = options.DeinterlaceDoubleRate && (videoStream?.RealFrameRate ?? 60) <= 30;
- // Currently only with the use of NVENC decoder can we get a decent performance.
- // Currently only the HEVC/H265 format is supported.
- // NVIDIA Pascal and Turing or higher are recommended.
- if (isNvdecHevcDecoder && isColorDepth10
- && _mediaEncoder.SupportsHwaccel("opencl")
- && options.EnableTonemapping
- && !string.IsNullOrEmpty(videoStream.VideoRange)
- && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase))
+ var isScalingInAdvance = false;
+ var isDeinterlaceH264 = state.DeInterlace("h264", true) || state.DeInterlace("avc", true);
+ var isDeinterlaceHevc = state.DeInterlace("h265", true) || state.DeInterlace("hevc", true);
+
+ if ((string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && isNvdecHevcDecoder || isSwDecoder)
+ || (string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase) && isD3d11vaDecoder || isSwDecoder))
{
- var parameters = "tonemap_opencl=format=nv12:primaries=bt709:transfer=bt709:matrix=bt709:tonemap={0}:desat={1}:threshold={2}:peak={3}";
-
- if (options.TonemappingParam != 0)
+ // Currently only with the use of NVENC decoder can we get a decent performance.
+ // Currently only the HEVC/H265 format is supported with NVDEC decoder.
+ // NVIDIA Pascal and Turing or higher are recommended.
+ // AMD Polaris and Vega or higher are recommended.
+ if (isColorDepth10
+ && _mediaEncoder.SupportsHwaccel("opencl")
+ && options.EnableTonemapping
+ && !string.IsNullOrEmpty(videoStream.VideoRange)
+ && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase))
{
- parameters += ":param={4}";
- }
+ var parameters = "tonemap_opencl=format=nv12:primaries=bt709:transfer=bt709:matrix=bt709:tonemap={0}:desat={1}:threshold={2}:peak={3}";
- if (!string.Equals(options.TonemappingRange, "auto", StringComparison.OrdinalIgnoreCase))
- {
- parameters += ":range={5}";
- }
+ if (options.TonemappingParam != 0)
+ {
+ parameters += ":param={4}";
+ }
- // Upload the HDR10 or HLG data to the OpenCL device,
- // use tonemap_opencl filter for tone mapping,
- // and then download the SDR data to memory.
- filters.Add("hwupload");
- filters.Add(
- string.Format(
- CultureInfo.InvariantCulture,
- parameters,
- options.TonemappingAlgorithm,
- options.TonemappingDesat,
- options.TonemappingThreshold,
- options.TonemappingPeak,
- options.TonemappingParam,
- options.TonemappingRange));
- filters.Add("hwdownload");
+ if (!string.Equals(options.TonemappingRange, "auto", StringComparison.OrdinalIgnoreCase))
+ {
+ parameters += ":range={5}";
+ }
- if (hasGraphicalSubs || state.DeInterlace("h265", true) || state.DeInterlace("hevc", true)
- || string.Equals(outputVideoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
- {
- filters.Add("format=nv12");
+ if (isSwDecoder || isD3d11vaDecoder)
+ {
+ isScalingInAdvance = true;
+ // Add zscale filter before tone mapping filter for performance.
+ var (width, height) = GetFixedOutputSize(inputWidth, inputHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
+ if (width.HasValue && height.HasValue)
+ {
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "zscale=s={0}x{1}",
+ width.Value,
+ height.Value));
+ }
+
+ // Convert to hardware pixel format p010 when using SW decoder.
+ filters.Add("format=p010");
+ }
+
+ // Upload the HDR10 or HLG data to the OpenCL device,
+ // use tonemap_opencl filter for tone mapping,
+ // and then download the SDR data to memory.
+ filters.Add("hwupload");
+ filters.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ parameters,
+ options.TonemappingAlgorithm,
+ options.TonemappingDesat,
+ options.TonemappingThreshold,
+ options.TonemappingPeak,
+ options.TonemappingParam,
+ options.TonemappingRange));
+ filters.Add("hwdownload");
+
+ if (isLibX264Encoder
+ || hasGraphicalSubs
+ || (isNvdecHevcDecoder && isDeinterlaceHevc)
+ || (!isNvdecHevcDecoder && isDeinterlaceH264 || isDeinterlaceHevc))
+ {
+ filters.Add("format=nv12");
+ }
}
}
@@ -2202,7 +2235,7 @@ namespace MediaBrowser.Controller.MediaEncoding
}
// Add hardware deinterlace filter before scaling filter
- if (state.DeInterlace("h264", true) || state.DeInterlace("avc", true))
+ if (isDeinterlaceH264)
{
if (isVaapiH264Encoder)
{
@@ -2215,10 +2248,7 @@ namespace MediaBrowser.Controller.MediaEncoding
}
// Add software deinterlace filter before scaling filter
- if ((state.DeInterlace("h264", true)
- || state.DeInterlace("avc", true)
- || state.DeInterlace("h265", true)
- || state.DeInterlace("hevc", true))
+ if ((isDeinterlaceH264 || isDeinterlaceHevc)
&& !isVaapiH264Encoder
&& !isQsvH264Encoder
&& !isNvdecH264Decoder)
@@ -2242,7 +2272,21 @@ namespace MediaBrowser.Controller.MediaEncoding
}
// Add scaling filter: scale_*=format=nv12 or scale_*=w=*:h=*:format=nv12 or scale=expr
- filters.AddRange(GetScalingFilters(state, inputWidth, inputHeight, threeDFormat, videoDecoder, outputVideoCodec, request.Width, request.Height, request.MaxWidth, request.MaxHeight));
+ if (!isScalingInAdvance)
+ {
+ filters.AddRange(
+ GetScalingFilters(
+ state,
+ inputWidth,
+ inputHeight,
+ threeDFormat,
+ videoDecoder,
+ outputVideoCodec,
+ request.Width,
+ request.Height,
+ request.MaxWidth,
+ request.MaxHeight));
+ }
// Add parameters to use VAAPI with burn-in text subtitles (GH issue #642)
if (isVaapiH264Encoder)
@@ -2275,7 +2319,7 @@ namespace MediaBrowser.Controller.MediaEncoding
{
output += string.Format(
CultureInfo.InvariantCulture,
- " -vf \"{0}\"",
+ "{0}",
string.Join(",", filters));
}
@@ -2511,7 +2555,6 @@ namespace MediaBrowser.Controller.MediaEncoding
return inputModifier;
}
-
public void AttachMediaSourceInfo(
EncodingJobInfo state,
MediaSourceInfo mediaSource,
@@ -2632,9 +2675,10 @@ namespace MediaBrowser.Controller.MediaEncoding
state.MediaSource = mediaSource;
var request = state.BaseRequest;
- if (!string.IsNullOrWhiteSpace(request.AudioCodec))
+ var supportedAudioCodecs = state.SupportedAudioCodecs;
+ if (request != null && supportedAudioCodecs != null && supportedAudioCodecs.Length > 0)
{
- var supportedAudioCodecsList = request.AudioCodec.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
+ var supportedAudioCodecsList = supportedAudioCodecs.ToList();
ShiftAudioCodecsIfNeeded(supportedAudioCodecsList, state.AudioStream);
@@ -3041,7 +3085,7 @@ namespace MediaBrowser.Controller.MediaEncoding
}
}
- var whichCodec = videoStream.Codec.ToLowerInvariant();
+ var whichCodec = videoStream.Codec?.ToLowerInvariant();
switch (whichCodec)
{
case "avc":
@@ -3069,21 +3113,31 @@ namespace MediaBrowser.Controller.MediaEncoding
var isWindows8orLater = Environment.OSVersion.Version.Major > 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor > 1);
var isDxvaSupported = _mediaEncoder.SupportsHwaccel("dxva2") || _mediaEncoder.SupportsHwaccel("d3d11va");
- if ((isDxvaSupported || IsVaapiSupported(state)) && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase))
+ if (string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase))
{
- if (isLinux)
+ // Currently there is no AMF decoder on Linux, only have h264 encoder.
+ if (isDxvaSupported && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase))
{
- return "-hwaccel vaapi";
- }
+ if (isWindows && isWindows8orLater)
+ {
+ return "-hwaccel d3d11va";
+ }
- if (isWindows && isWindows8orLater)
- {
- return "-hwaccel d3d11va";
+ if (isWindows && !isWindows8orLater)
+ {
+ return "-hwaccel dxva2";
+ }
}
+ }
- if (isWindows && !isWindows8orLater)
+ if (string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
+ {
+ if (IsVaapiSupported(state) && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase))
{
- return "-hwaccel dxva2";
+ if (isLinux)
+ {
+ return "-hwaccel vaapi";
+ }
}
}
diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs
index 68bc502a0f..db72fa56cc 100644
--- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs
+++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs
@@ -287,6 +287,11 @@ namespace MediaBrowser.Controller.MediaEncoding
return BaseRequest.AudioChannels;
}
+ if (BaseRequest.TranscodingMaxAudioChannels.HasValue)
+ {
+ return BaseRequest.TranscodingMaxAudioChannels;
+ }
+
if (!string.IsNullOrEmpty(codec))
{
var value = BaseRequest.GetOption(codec, "audiochannels");
@@ -342,7 +347,8 @@ namespace MediaBrowser.Controller.MediaEncoding
{
var size = new ImageDimensions(VideoStream.Width.Value, VideoStream.Height.Value);
- var newSize = DrawingUtils.Resize(size,
+ var newSize = DrawingUtils.Resize(
+ size,
BaseRequest.Width ?? 0,
BaseRequest.Height ?? 0,
BaseRequest.MaxWidth ?? 0,
@@ -368,7 +374,8 @@ namespace MediaBrowser.Controller.MediaEncoding
{
var size = new ImageDimensions(VideoStream.Width.Value, VideoStream.Height.Value);
- var newSize = DrawingUtils.Resize(size,
+ var newSize = DrawingUtils.Resize(
+ size,
BaseRequest.Width ?? 0,
BaseRequest.Height ?? 0,
BaseRequest.MaxWidth ?? 0,
@@ -402,7 +409,7 @@ namespace MediaBrowser.Controller.MediaEncoding
{
// Don't exceed what the encoder supports
// Seeing issues of attempting to encode to 88200
- return Math.Min(44100, BaseRequest.AudioSampleRate.Value);
+ return BaseRequest.AudioSampleRate.Value;
}
return null;
@@ -697,10 +704,12 @@ namespace MediaBrowser.Controller.MediaEncoding
/// The progressive.
///
Progressive,
+
///
/// The HLS.
///
Hls,
+
///
/// The dash.
///
diff --git a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs
index 17d6dc5d27..f6bc1f4de9 100644
--- a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs
+++ b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs
@@ -68,7 +68,8 @@ namespace MediaBrowser.Controller.MediaEncoding
///
/// Extracts the video images on interval.
///
- Task ExtractVideoImagesOnInterval(string[] inputFiles,
+ Task ExtractVideoImagesOnInterval(
+ string[] inputFiles,
string container,
MediaStream videoStream,
MediaProtocol protocol,
diff --git a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs
index ac520c5c44..cc8820f393 100644
--- a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs
+++ b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs
@@ -93,7 +93,7 @@ namespace MediaBrowser.Controller.MediaEncoding
}
else if (part.StartsWith("fps=", StringComparison.OrdinalIgnoreCase))
{
- var rate = part.Split(new[] { '=' }, 2)[^1];
+ var rate = part.Split('=', 2)[^1];
if (float.TryParse(rate, NumberStyles.Any, _usCulture, out var val))
{
@@ -103,7 +103,7 @@ namespace MediaBrowser.Controller.MediaEncoding
else if (state.RunTimeTicks.HasValue &&
part.StartsWith("time=", StringComparison.OrdinalIgnoreCase))
{
- var time = part.Split(new[] { '=' }, 2).Last();
+ var time = part.Split('=', 2)[^1];
if (TimeSpan.TryParse(time, _usCulture, out var val))
{
@@ -116,7 +116,7 @@ namespace MediaBrowser.Controller.MediaEncoding
}
else if (part.StartsWith("size=", StringComparison.OrdinalIgnoreCase))
{
- var size = part.Split(new[] { '=' }, 2).Last();
+ var size = part.Split('=', 2)[^1];
int? scale = null;
if (size.IndexOf("kb", StringComparison.OrdinalIgnoreCase) != -1)
@@ -135,7 +135,7 @@ namespace MediaBrowser.Controller.MediaEncoding
}
else if (part.StartsWith("bitrate=", StringComparison.OrdinalIgnoreCase))
{
- var rate = part.Split(new[] { '=' }, 2).Last();
+ var rate = part.Split('=', 2)[^1];
int? scale = null;
if (rate.IndexOf("kbits/s", StringComparison.OrdinalIgnoreCase) != -1)
diff --git a/MediaBrowser.Controller/Net/AuthorizationInfo.cs b/MediaBrowser.Controller/Net/AuthorizationInfo.cs
index 735c46ef86..0194c596f1 100644
--- a/MediaBrowser.Controller/Net/AuthorizationInfo.cs
+++ b/MediaBrowser.Controller/Net/AuthorizationInfo.cs
@@ -1,10 +1,11 @@
-#pragma warning disable CS1591
-
using System;
using Jellyfin.Data.Entities;
namespace MediaBrowser.Controller.Net
{
+ ///
+ /// The request authorization info.
+ ///
public class AuthorizationInfo
{
///
@@ -43,6 +44,19 @@ namespace MediaBrowser.Controller.Net
/// The token.
public string Token { get; set; }
+ ///
+ /// Gets or sets a value indicating whether the authorization is from an api key.
+ ///
+ public bool IsApiKey { get; set; }
+
+ ///
+ /// Gets or sets the user making the request.
+ ///
public User User { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether the token is authenticated.
+ ///
+ public bool IsAuthenticated { get; set; }
}
}
diff --git a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs
index 916dea58be..28227603b2 100644
--- a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs
+++ b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs
@@ -8,6 +8,7 @@ using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Net;
+using MediaBrowser.Model.Session;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Controller.Net
@@ -28,10 +29,22 @@ namespace MediaBrowser.Controller.Net
new List>();
///
- /// Gets the name.
+ /// Gets the type used for the messages sent to the client.
///
- /// The name.
- protected abstract string Name { get; }
+ /// The type.
+ protected abstract SessionMessageType Type { get; }
+
+ ///
+ /// Gets the message type received from the client to start sending messages.
+ ///
+ /// The type.
+ protected abstract SessionMessageType StartType { get; }
+
+ ///
+ /// Gets the message type received from the client to stop sending messages.
+ ///
+ /// The type.
+ protected abstract SessionMessageType StopType { get; }
///
/// Gets the data to send.
@@ -66,12 +79,12 @@ namespace MediaBrowser.Controller.Net
throw new ArgumentNullException(nameof(message));
}
- if (string.Equals(message.MessageType, Name + "Start", StringComparison.OrdinalIgnoreCase))
+ if (message.MessageType == StartType)
{
Start(message);
}
- if (string.Equals(message.MessageType, Name + "Stop", StringComparison.OrdinalIgnoreCase))
+ if (message.MessageType == StopType)
{
Stop(message);
}
@@ -159,7 +172,7 @@ namespace MediaBrowser.Controller.Net
new WebSocketMessage
{
MessageId = Guid.NewGuid(),
- MessageType = Name,
+ MessageType = Type,
Data = data
},
cancellationToken).ConfigureAwait(false);
@@ -176,7 +189,7 @@ namespace MediaBrowser.Controller.Net
}
catch (Exception ex)
{
- Logger.LogError(ex, "Error sending web socket message {Name}", Name);
+ Logger.LogError(ex, "Error sending web socket message {Name}", Type);
DisposeConnection(tuple);
}
}
diff --git a/MediaBrowser.Controller/Net/IWebSocketManager.cs b/MediaBrowser.Controller/Net/IWebSocketManager.cs
index e9f00ae88b..ce74173e70 100644
--- a/MediaBrowser.Controller/Net/IWebSocketManager.cs
+++ b/MediaBrowser.Controller/Net/IWebSocketManager.cs
@@ -16,12 +16,6 @@ namespace MediaBrowser.Controller.Net
///
event EventHandler> WebSocketConnected;
- ///
- /// Inits this instance.
- ///
- /// The websocket listeners.
- void Init(IEnumerable listeners);
-
///
/// The HTTP request handler.
///
diff --git a/MediaBrowser.Controller/Persistence/IItemRepository.cs b/MediaBrowser.Controller/Persistence/IItemRepository.cs
index ebc37bd1f3..45c6805f0e 100644
--- a/MediaBrowser.Controller/Persistence/IItemRepository.cs
+++ b/MediaBrowser.Controller/Persistence/IItemRepository.cs
@@ -100,6 +100,7 @@ namespace MediaBrowser.Controller.Persistence
/// The query.
/// IEnumerable<Guid>.
QueryResult GetItemIds(InternalItemsQuery query);
+
///
/// Gets the items.
///
diff --git a/MediaBrowser.Controller/Playlists/Playlist.cs b/MediaBrowser.Controller/Playlists/Playlist.cs
index 216dd27098..e8b7be7e20 100644
--- a/MediaBrowser.Controller/Playlists/Playlist.cs
+++ b/MediaBrowser.Controller/Playlists/Playlist.cs
@@ -160,7 +160,7 @@ namespace MediaBrowser.Controller.Playlists
return LibraryManager.GetItemList(new InternalItemsQuery(user)
{
Recursive = true,
- IncludeItemTypes = new[] { typeof(Audio).Name },
+ IncludeItemTypes = new[] { nameof(Audio) },
GenreIds = new[] { musicGenre.Id },
OrderBy = new[] { ItemSortBy.AlbumArtist, ItemSortBy.Album, ItemSortBy.SortName }.Select(i => new ValueTuple(i, SortOrder.Ascending)).ToArray(),
DtoOptions = options
@@ -172,7 +172,7 @@ namespace MediaBrowser.Controller.Playlists
return LibraryManager.GetItemList(new InternalItemsQuery(user)
{
Recursive = true,
- IncludeItemTypes = new[] { typeof(Audio).Name },
+ IncludeItemTypes = new[] { nameof(Audio) },
ArtistIds = new[] { musicArtist.Id },
OrderBy = new[] { ItemSortBy.AlbumArtist, ItemSortBy.Album, ItemSortBy.SortName }.Select(i => new ValueTuple(i, SortOrder.Ascending)).ToArray(),
DtoOptions = options
diff --git a/MediaBrowser.Controller/Providers/DirectoryService.cs b/MediaBrowser.Controller/Providers/DirectoryService.cs
index f77455485a..16fd1d42b0 100644
--- a/MediaBrowser.Controller/Providers/DirectoryService.cs
+++ b/MediaBrowser.Controller/Providers/DirectoryService.cs
@@ -1,6 +1,7 @@
#pragma warning disable CS1591
using System;
+using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using MediaBrowser.Model.IO;
@@ -11,11 +12,11 @@ namespace MediaBrowser.Controller.Providers
{
private readonly IFileSystem _fileSystem;
- private readonly Dictionary _cache = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ private readonly ConcurrentDictionary _cache = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase);
- private readonly Dictionary _fileCache = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ private readonly ConcurrentDictionary _fileCache = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase);
- private readonly Dictionary> _filePathCache = new Dictionary>(StringComparer.OrdinalIgnoreCase);
+ private readonly ConcurrentDictionary> _filePathCache = new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase);
public DirectoryService(IFileSystem fileSystem)
{
@@ -24,14 +25,7 @@ namespace MediaBrowser.Controller.Providers
public FileSystemMetadata[] GetFileSystemEntries(string path)
{
- if (!_cache.TryGetValue(path, out FileSystemMetadata[] entries))
- {
- entries = _fileSystem.GetFileSystemEntries(path).ToArray();
-
- _cache[path] = entries;
- }
-
- return entries;
+ return _cache.GetOrAdd(path, p => _fileSystem.GetFileSystemEntries(p).ToArray());
}
public List GetFiles(string path)
@@ -51,21 +45,19 @@ namespace MediaBrowser.Controller.Providers
public FileSystemMetadata GetFile(string path)
{
- if (!_fileCache.TryGetValue(path, out FileSystemMetadata file))
+ var result = _fileCache.GetOrAdd(path, p =>
{
- file = _fileSystem.GetFileInfo(path);
+ var file = _fileSystem.GetFileInfo(p);
+ return file != null && file.Exists ? file : null;
+ });
- if (file != null && file.Exists)
- {
- _fileCache[path] = file;
- }
- else
- {
- return null;
- }
+ if (result == null)
+ {
+ // lets not store null results in the cache
+ _fileCache.TryRemove(path, out _);
}
- return file;
+ return result;
}
public IReadOnlyList GetFilePaths(string path)
@@ -73,14 +65,12 @@ namespace MediaBrowser.Controller.Providers
public IReadOnlyList GetFilePaths(string path, bool clearCache)
{
- if (clearCache || !_filePathCache.TryGetValue(path, out List result))
+ if (clearCache)
{
- result = _fileSystem.GetFilePaths(path).ToList();
-
- _filePathCache[path] = result;
+ _filePathCache.TryRemove(path, out _);
}
- return result;
+ return _filePathCache.GetOrAdd(path, p => _fileSystem.GetFilePaths(p).ToList());
}
}
}
diff --git a/MediaBrowser.Controller/Resolvers/IItemResolver.cs b/MediaBrowser.Controller/Resolvers/IItemResolver.cs
index b99c468435..75286eadc0 100644
--- a/MediaBrowser.Controller/Resolvers/IItemResolver.cs
+++ b/MediaBrowser.Controller/Resolvers/IItemResolver.cs
@@ -19,6 +19,7 @@ namespace MediaBrowser.Controller.Resolvers
/// The args.
/// BaseItem.
BaseItem ResolvePath(ItemResolveArgs args);
+
///
/// Gets the priority.
///
@@ -28,7 +29,8 @@ namespace MediaBrowser.Controller.Resolvers
public interface IMultiItemResolver
{
- MultiItemResolverResult ResolveMultiple(Folder parent,
+ MultiItemResolverResult ResolveMultiple(
+ Folder parent,
List files,
string collectionType,
IDirectoryService directoryService);
diff --git a/MediaBrowser.Controller/Session/ISessionController.cs b/MediaBrowser.Controller/Session/ISessionController.cs
index 22d6e2a04e..bc4ccd44ca 100644
--- a/MediaBrowser.Controller/Session/ISessionController.cs
+++ b/MediaBrowser.Controller/Session/ISessionController.cs
@@ -3,6 +3,7 @@
using System;
using System.Threading;
using System.Threading.Tasks;
+using MediaBrowser.Model.Session;
namespace MediaBrowser.Controller.Session
{
@@ -23,6 +24,6 @@ namespace MediaBrowser.Controller.Session
///
/// Sends the message.
///
- Task SendMessage(string name, Guid messageId, T data, CancellationToken cancellationToken);
+ Task SendMessage(SessionMessageType name, Guid messageId, T data, CancellationToken cancellationToken);
}
}
diff --git a/MediaBrowser.Controller/Session/ISessionManager.cs b/MediaBrowser.Controller/Session/ISessionManager.cs
index 228b2331dc..04c3004ee6 100644
--- a/MediaBrowser.Controller/Session/ISessionManager.cs
+++ b/MediaBrowser.Controller/Session/ISessionManager.cs
@@ -188,16 +188,16 @@ namespace MediaBrowser.Controller.Session
/// The data.
/// The cancellation token.
/// Task.
- Task SendMessageToAdminSessions(string name, T data, CancellationToken cancellationToken);
+ Task SendMessageToAdminSessions(SessionMessageType name, T data, CancellationToken cancellationToken);
///
/// Sends the message to user sessions.
///
///
/// Task.
- Task SendMessageToUserSessions(List userIds, string name, T data, CancellationToken cancellationToken);
+ Task SendMessageToUserSessions(List userIds, SessionMessageType name, T data, CancellationToken cancellationToken);
- Task SendMessageToUserSessions(List userIds, string name, Func dataFn, CancellationToken cancellationToken);
+ Task SendMessageToUserSessions(List userIds, SessionMessageType name, Func dataFn, CancellationToken cancellationToken);
///
/// Sends the message to user device sessions.
@@ -208,7 +208,7 @@ namespace MediaBrowser.Controller.Session
/// The data.
/// The cancellation token.
/// Task.
- Task SendMessageToUserDeviceSessions(string deviceId, string name, T data, CancellationToken cancellationToken);
+ Task SendMessageToUserDeviceSessions(string deviceId, SessionMessageType name, T data, CancellationToken cancellationToken);
///
/// Sends the restart required message.
diff --git a/MediaBrowser.Controller/Session/SessionInfo.cs b/MediaBrowser.Controller/Session/SessionInfo.cs
index 054fd33d9d..ce58a60b9a 100644
--- a/MediaBrowser.Controller/Session/SessionInfo.cs
+++ b/MediaBrowser.Controller/Session/SessionInfo.cs
@@ -22,7 +22,6 @@ namespace MediaBrowser.Controller.Session
private readonly ISessionManager _sessionManager;
private readonly ILogger _logger;
-
private readonly object _progressLock = new object();
private Timer _progressTimer;
private PlaybackProgressInfo _lastProgressInfo;
@@ -231,8 +230,8 @@ namespace MediaBrowser.Controller.Session
/// Gets or sets the supported commands.
///
/// The supported commands.
- public string[] SupportedCommands
- => Capabilities == null ? Array.Empty() : Capabilities.SupportedCommands;
+ public GeneralCommandType[] SupportedCommands
+ => Capabilities == null ? Array.Empty() : Capabilities.SupportedCommands;
public Tuple EnsureController(Func factory)
{
diff --git a/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs b/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs
index f43d523a63..feb26bc101 100644
--- a/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs
+++ b/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs
@@ -2,6 +2,7 @@
using System;
using System.Collections.Generic;
+using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Entities;
@@ -52,6 +53,14 @@ namespace MediaBrowser.Controller.Subtitles
///
Task DownloadSubtitles(Video video, LibraryOptions libraryOptions, string subtitleId, CancellationToken cancellationToken);
+ ///
+ /// Upload new subtitle.
+ ///
+ /// The video the subtitle belongs to.
+ /// The subtitle response.
+ /// A representing the asynchronous operation.
+ Task UploadSubtitle(Video video, SubtitleResponse response);
+
///
/// Gets the remote subtitles.
///
diff --git a/MediaBrowser.Controller/SyncPlay/GroupInfo.cs b/MediaBrowser.Controller/SyncPlay/GroupInfo.cs
index e742df5179..a1cada25cc 100644
--- a/MediaBrowser.Controller/SyncPlay/GroupInfo.cs
+++ b/MediaBrowser.Controller/SyncPlay/GroupInfo.cs
@@ -14,12 +14,12 @@ namespace MediaBrowser.Controller.SyncPlay
public class GroupInfo
{
///
- /// Gets the default ping value used for sessions.
+ /// The default ping value used for sessions.
///
- public long DefaultPing { get; } = 500;
+ public const long DefaultPing = 500;
///
- /// Gets or sets the group identifier.
+ /// Gets the group identifier.
///
/// The group identifier.
public Guid GroupId { get; } = Guid.NewGuid();
@@ -58,7 +58,8 @@ namespace MediaBrowser.Controller.SyncPlay
///
/// Checks if a session is in this group.
///
- /// true if the session is in this group; false otherwise.
+ /// The session id to check.
+ /// true if the session is in this group; false otherwise.
public bool ContainsSession(string sessionId)
{
return Participants.ContainsKey(sessionId);
@@ -70,16 +71,14 @@ namespace MediaBrowser.Controller.SyncPlay
/// The session.
public void AddSession(SessionInfo session)
{
- if (ContainsSession(session.Id))
- {
- return;
- }
-
- var member = new GroupMember();
- member.Session = session;
- member.Ping = DefaultPing;
- member.IsBuffering = false;
- Participants[session.Id] = member;
+ Participants.TryAdd(
+ session.Id,
+ new GroupMember
+ {
+ Session = session,
+ Ping = DefaultPing,
+ IsBuffering = false
+ });
}
///
@@ -88,12 +87,7 @@ namespace MediaBrowser.Controller.SyncPlay
/// The session.
public void RemoveSession(SessionInfo session)
{
- if (!ContainsSession(session.Id))
- {
- return;
- }
-
- Participants.Remove(session.Id, out _);
+ Participants.Remove(session.Id);
}
///
@@ -103,18 +97,16 @@ namespace MediaBrowser.Controller.SyncPlay
/// The ping.
public void UpdatePing(SessionInfo session, long ping)
{
- if (!ContainsSession(session.Id))
+ if (Participants.TryGetValue(session.Id, out GroupMember value))
{
- return;
+ value.Ping = ping;
}
-
- Participants[session.Id].Ping = ping;
}
///
/// Gets the highest ping in the group.
///
- /// The highest ping in the group.
+ /// The highest ping in the group.
public long GetHighestPing()
{
long max = long.MinValue;
@@ -133,18 +125,16 @@ namespace MediaBrowser.Controller.SyncPlay
/// The state.
public void SetBuffering(SessionInfo session, bool isBuffering)
{
- if (!ContainsSession(session.Id))
+ if (Participants.TryGetValue(session.Id, out GroupMember value))
{
- return;
+ value.IsBuffering = isBuffering;
}
-
- Participants[session.Id].IsBuffering = isBuffering;
}
///
/// Gets the group buffering state.
///
- /// true if there is a session buffering in the group; false otherwise.
+ /// true if there is a session buffering in the group; false otherwise.
public bool IsBuffering()
{
foreach (var session in Participants.Values)
@@ -161,7 +151,7 @@ namespace MediaBrowser.Controller.SyncPlay
///
/// Checks if the group is empty.
///
- /// true if the group is empty; false otherwise.
+ /// true if the group is empty; false otherwise.
public bool IsEmpty()
{
return Participants.Count == 0;
diff --git a/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs b/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs
index 914db53059..84c3ed8b0b 100644
--- a/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs
+++ b/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs
@@ -486,7 +486,7 @@ namespace MediaBrowser.LocalMetadata.Images
return false;
}
- private FileSystemMetadata GetImage(IEnumerable files, string name)
+ private FileSystemMetadata? GetImage(IEnumerable files, string name)
{
return files.FirstOrDefault(i => !i.IsDirectory && string.Equals(name, _fileSystem.GetFileNameWithoutExtension(i), StringComparison.OrdinalIgnoreCase) && i.Length > 0);
}
diff --git a/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj b/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj
index 529e7065cd..3ce9ff4cc4 100644
--- a/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj
+++ b/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj
@@ -11,7 +11,7 @@
- netstandard2.1
+ net5.0
false
true
true
diff --git a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs
index 4ac2498400..5d3ab30d39 100644
--- a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs
+++ b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs
@@ -683,7 +683,7 @@ namespace MediaBrowser.LocalMetadata.Parsers
default:
{
string readerName = reader.Name;
- if (_validProviderIds!.TryGetValue(readerName, out string providerIdValue))
+ if (_validProviderIds!.TryGetValue(readerName, out string? providerIdValue))
{
var id = reader.ReadElementContentAsString();
if (!string.IsNullOrWhiteSpace(id))
diff --git a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs
index 7a4823e1b8..396206658d 100644
--- a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs
+++ b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs
@@ -5,6 +5,7 @@ using System.Linq;
using System.Text;
using System.Threading;
using System.Xml;
+using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
@@ -127,7 +128,8 @@ namespace MediaBrowser.LocalMetadata.Savers
private void SaveToFile(Stream stream, string path)
{
- Directory.CreateDirectory(Path.GetDirectoryName(path));
+ var directory = Path.GetDirectoryName(path) ?? throw new ArgumentException($"Provided path ({path}) is not valid.", nameof(path));
+ Directory.CreateDirectory(directory);
// On Windows, savint the file will fail if the file is hidden or readonly
FileSystem.SetAttributes(path, false, false);
diff --git a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs
index 21b5d0c5be..bc940d0b8d 100644
--- a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs
+++ b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs
@@ -178,7 +178,7 @@ namespace MediaBrowser.MediaEncoding.Attachments
process.Start();
- var ranToCompletion = await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
+ var ranToCompletion = await ProcessExtensions.WaitForExitAsync(process, cancellationToken).ConfigureAwait(false);
if (!ranToCompletion)
{
diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
index 3287f9814e..92f16ab95c 100644
--- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
@@ -25,6 +25,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
"ac3",
"aac",
"mp3",
+ "flac",
"h264_qsv",
"hevc_qsv",
"mpeg2_qsv",
@@ -71,6 +72,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
"libmp3lame",
"libopus",
"libvorbis",
+ "flac",
"srt",
"h264_amf",
"hevc_amf",
diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj
index 6ead93e09b..7bb2a7d03f 100644
--- a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj
+++ b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj
@@ -6,7 +6,7 @@
- netstandard2.1
+ net5.0
false
true
true
@@ -25,7 +25,7 @@
-
+
diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
index 22537a4d95..15a70e2e7d 100644
--- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
+++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
@@ -149,7 +149,7 @@ namespace MediaBrowser.MediaEncoding.Probing
var iTunEXTC = FFProbeHelpers.GetDictionaryValue(tags, "iTunEXTC");
if (!string.IsNullOrWhiteSpace(iTunEXTC))
{
- var parts = iTunEXTC.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
+ var parts = iTunEXTC.Split('|', StringSplitOptions.RemoveEmptyEntries);
// Example
// mpaa|G|100|For crude humor
if (parts.Length > 1)
@@ -666,6 +666,16 @@ namespace MediaBrowser.MediaEncoding.Probing
stream.AverageFrameRate = GetFrameRate(streamInfo.AverageFrameRate);
stream.RealFrameRate = GetFrameRate(streamInfo.RFrameRate);
+ // Interlaced video streams in Matroska containers return the field rate instead of the frame rate
+ // as both the average and real frame rate, so we half the returned frame rates to get the correct values
+ //
+ // https://gitlab.com/mbunkus/mkvtoolnix/-/wikis/Wrong-frame-rate-displayed
+ if (stream.IsInterlaced && formatInfo.FormatName.Contains("matroska", StringComparison.OrdinalIgnoreCase))
+ {
+ stream.AverageFrameRate /= 2;
+ stream.RealFrameRate /= 2;
+ }
+
if (isAudio || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) ||
string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase))
{
@@ -1129,7 +1139,7 @@ namespace MediaBrowser.MediaEncoding.Probing
return null;
}
- return value.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
+ return value.Split('/', StringSplitOptions.RemoveEmptyEntries)
.Select(i => i.Trim())
.FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
}
diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs
index 0a9958b9eb..b61b8a0e04 100644
--- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs
+++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs
@@ -758,9 +758,9 @@ namespace MediaBrowser.MediaEncoding.Subtitles
case MediaProtocol.Http:
{
using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
- .GetAsync(path, cancellationToken)
+ .GetAsync(new Uri(path), cancellationToken)
.ConfigureAwait(false);
- return await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ return await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
}
case MediaProtocol.File:
diff --git a/MediaBrowser.Model/Activity/IActivityManager.cs b/MediaBrowser.Model/Activity/IActivityManager.cs
index d5344494e8..28073fb8d7 100644
--- a/MediaBrowser.Model/Activity/IActivityManager.cs
+++ b/MediaBrowser.Model/Activity/IActivityManager.cs
@@ -1,10 +1,10 @@
#pragma warning disable CS1591
using System;
-using System.Linq;
using System.Threading.Tasks;
using Jellyfin.Data.Entities;
using Jellyfin.Data.Events;
+using Jellyfin.Data.Queries;
using MediaBrowser.Model.Querying;
namespace MediaBrowser.Model.Activity
@@ -15,11 +15,13 @@ namespace MediaBrowser.Model.Activity
Task CreateAsync(ActivityLog entry);
- QueryResult GetPagedResult(int? startIndex, int? limit);
+ Task> GetPagedResultAsync(ActivityLogQuery query);
- QueryResult GetPagedResult(
- Func, IQueryable> func,
- int? startIndex,
- int? limit);
+ ///
+ /// Remove all activity logs before the specified date.
+ ///
+ /// Activity log start date.
+ /// A representing the asynchronous operation.
+ Task CleanAsync(DateTime startDate);
}
}
diff --git a/MediaBrowser.Model/Configuration/EncodingOptions.cs b/MediaBrowser.Model/Configuration/EncodingOptions.cs
index 2cd637c5b0..c348256677 100644
--- a/MediaBrowser.Model/Configuration/EncodingOptions.cs
+++ b/MediaBrowser.Model/Configuration/EncodingOptions.cs
@@ -9,6 +9,10 @@ namespace MediaBrowser.Model.Configuration
public string TranscodingTempPath { get; set; }
+ public string FallbackFontPath { get; set; }
+
+ public bool EnableFallbackFont { get; set; }
+
public double DownMixAudioBoost { get; set; }
public int MaxMuxingQueueSize { get; set; }
@@ -69,6 +73,7 @@ namespace MediaBrowser.Model.Configuration
public EncodingOptions()
{
+ EnableFallbackFont = false;
DownMixAudioBoost = 2;
MaxMuxingQueueSize = 2048;
EnableThrottling = false;
diff --git a/MediaBrowser.Model/Configuration/LibraryOptions.cs b/MediaBrowser.Model/Configuration/LibraryOptions.cs
index 890469d361..77ac11d69f 100644
--- a/MediaBrowser.Model/Configuration/LibraryOptions.cs
+++ b/MediaBrowser.Model/Configuration/LibraryOptions.cs
@@ -17,16 +17,12 @@ namespace MediaBrowser.Model.Configuration
public bool ExtractChapterImagesDuringLibraryScan { get; set; }
- public bool DownloadImagesInAdvance { get; set; }
-
public MediaPathInfo[] PathInfos { get; set; }
public bool SaveLocalMetadata { get; set; }
public bool EnableInternetProviders { get; set; }
- public bool ImportMissingEpisodes { get; set; }
-
public bool EnableAutomaticSeriesGrouping { get; set; }
public bool EnableEmbeddedTitles { get; set; }
diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs
index 48d1a7346a..23a5201f7a 100644
--- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs
+++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs
@@ -83,8 +83,6 @@ namespace MediaBrowser.Model.Configuration
///
public bool QuickConnectAvailable { get; set; }
- public bool AutoRunWebApp { get; set; }
-
public bool EnableRemoteAccess { get; set; }
///
@@ -273,6 +271,11 @@ namespace MediaBrowser.Model.Configuration
///
public string[] KnownProxies { get; set; }
+ ///
+ /// Gets or sets the number of days we should retain activity logs.
+ ///
+ public int? ActivityLogRetentionDays { get; set; }
+
///
/// Initializes a new instance of the class.
///
@@ -306,7 +309,6 @@ namespace MediaBrowser.Model.Configuration
DisableLiveTvChannelUserDataName = true;
EnableNewOmdbSupport = true;
- AutoRunWebApp = true;
EnableRemoteAccess = true;
QuickConnectAvailable = false;
@@ -384,6 +386,7 @@ namespace MediaBrowser.Model.Configuration
SlowResponseThresholdMs = 500;
CorsHosts = new[] { "*" };
KnownProxies = Array.Empty();
+ ActivityLogRetentionDays = 30;
}
}
diff --git a/MediaBrowser.Model/Dlna/AudioOptions.cs b/MediaBrowser.Model/Dlna/AudioOptions.cs
index 67e4ffe03e..bbb8bf4263 100644
--- a/MediaBrowser.Model/Dlna/AudioOptions.cs
+++ b/MediaBrowser.Model/Dlna/AudioOptions.cs
@@ -49,7 +49,7 @@ namespace MediaBrowser.Model.Dlna
///
/// The application's configured quality setting.
///
- public long? MaxBitrate { get; set; }
+ public int? MaxBitrate { get; set; }
///
/// Gets or sets the context.
@@ -67,7 +67,7 @@ namespace MediaBrowser.Model.Dlna
/// Gets the maximum bitrate.
///
/// System.Nullable<System.Int32>.
- public long? GetMaxBitrate(bool isAudio)
+ public int? GetMaxBitrate(bool isAudio)
{
if (MaxBitrate.HasValue)
{
diff --git a/MediaBrowser.Model/Dlna/ContainerProfile.cs b/MediaBrowser.Model/Dlna/ContainerProfile.cs
index f77d9b2675..09afa64bbd 100644
--- a/MediaBrowser.Model/Dlna/ContainerProfile.cs
+++ b/MediaBrowser.Model/Dlna/ContainerProfile.cs
@@ -34,7 +34,7 @@ namespace MediaBrowser.Model.Dlna
return Array.Empty();
}
- return value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
+ return value.Split(',', StringSplitOptions.RemoveEmptyEntries);
}
public bool ContainsContainer(string container)
diff --git a/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs b/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs
index 93e60753ae..50e3374f77 100644
--- a/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs
+++ b/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs
@@ -38,7 +38,8 @@ namespace MediaBrowser.Model.Dlna
";DLNA.ORG_FLAGS={0}",
DlnaMaps.FlagsToString(flagValue));
- ResponseProfile mediaProfile = _profile.GetImageMediaProfile(container,
+ ResponseProfile mediaProfile = _profile.GetImageMediaProfile(
+ container,
width,
height);
@@ -160,7 +161,8 @@ namespace MediaBrowser.Model.Dlna
string dlnaflags = string.Format(CultureInfo.InvariantCulture, ";DLNA.ORG_FLAGS={0}",
DlnaMaps.FlagsToString(flagValue));
- ResponseProfile mediaProfile = _profile.GetVideoMediaProfile(container,
+ ResponseProfile mediaProfile = _profile.GetVideoMediaProfile(
+ container,
audioCodec,
videoCodec,
width,
@@ -184,7 +186,7 @@ namespace MediaBrowser.Model.Dlna
if (mediaProfile != null && !string.IsNullOrEmpty(mediaProfile.OrgPn))
{
- orgPnValues.AddRange(mediaProfile.OrgPn.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
+ orgPnValues.AddRange(mediaProfile.OrgPn.Split(',', StringSplitOptions.RemoveEmptyEntries));
}
else
{
@@ -221,7 +223,8 @@ namespace MediaBrowser.Model.Dlna
private static string GetImageOrgPnValue(string container, int? width, int? height)
{
MediaFormatProfile? format = new MediaFormatProfileResolver()
- .ResolveImageFormat(container,
+ .ResolveImageFormat(
+ container,
width,
height);
@@ -231,7 +234,8 @@ namespace MediaBrowser.Model.Dlna
private static string GetAudioOrgPnValue(string container, int? audioBitrate, int? audioSampleRate, int? audioChannels)
{
MediaFormatProfile? format = new MediaFormatProfileResolver()
- .ResolveAudioFormat(container,
+ .ResolveAudioFormat(
+ container,
audioBitrate,
audioSampleRate,
audioChannels);
diff --git a/MediaBrowser.Model/Dlna/DeviceIdentification.cs b/MediaBrowser.Model/Dlna/DeviceIdentification.cs
index 43407383a8..c511801f4f 100644
--- a/MediaBrowser.Model/Dlna/DeviceIdentification.cs
+++ b/MediaBrowser.Model/Dlna/DeviceIdentification.cs
@@ -11,59 +11,54 @@ namespace MediaBrowser.Model.Dlna
/// Gets or sets the name of the friendly.
///
/// The name of the friendly.
- public string FriendlyName { get; set; }
+ public string FriendlyName { get; set; } = string.Empty;
///
/// Gets or sets the model number.
///
/// The model number.
- public string ModelNumber { get; set; }
+ public string ModelNumber { get; set; } = string.Empty;
///
/// Gets or sets the serial number.
///
/// The serial number.
- public string SerialNumber { get; set; }
+ public string SerialNumber { get; set; } = string.Empty;
///
/// Gets or sets the name of the model.
///
/// The name of the model.
- public string ModelName { get; set; }
+ public string ModelName { get; set; } = string.Empty;
///
/// Gets or sets the model description.
///
/// The model description.
- public string ModelDescription { get; set; }
+ public string ModelDescription { get; set; } = string.Empty;
///
/// Gets or sets the model URL.
///
/// The model URL.
- public string ModelUrl { get; set; }
+ public string ModelUrl { get; set; } = string.Empty;
///
/// Gets or sets the manufacturer.
///
/// The manufacturer.
- public string Manufacturer { get; set; }
+ public string Manufacturer { get; set; } = string.Empty;
///
/// Gets or sets the manufacturer URL.
///
/// The manufacturer URL.
- public string ManufacturerUrl { get; set; }
+ public string ManufacturerUrl { get; set; } = string.Empty;
///
/// Gets or sets the headers.
///
/// The headers.
- public HttpHeaderInfo[] Headers { get; set; }
-
- public DeviceIdentification()
- {
- Headers = Array.Empty();
- }
+ public HttpHeaderInfo[] Headers { get; set; } = Array.Empty();
}
}
diff --git a/MediaBrowser.Model/Dlna/DeviceProfile.cs b/MediaBrowser.Model/Dlna/DeviceProfile.cs
index 7e921b1fdf..ff51866587 100644
--- a/MediaBrowser.Model/Dlna/DeviceProfile.cs
+++ b/MediaBrowser.Model/Dlna/DeviceProfile.cs
@@ -1,6 +1,5 @@
#nullable disable
-#pragma warning disable CS1591
-
+#pragma warning disable CA1819 // Properties should not return arrays
using System;
using System.Linq;
using System.Xml.Serialization;
@@ -8,107 +7,15 @@ using MediaBrowser.Model.MediaInfo;
namespace MediaBrowser.Model.Dlna
{
+ ///
+ /// Defines the .
+ ///
[XmlRoot("Profile")]
public class DeviceProfile
{
///
- /// Gets or sets the name.
+ /// Initializes a new instance of the class.
///
- /// The name.
- public string Name { get; set; }
-
- [XmlIgnore]
- public string Id { get; set; }
-
- ///
- /// Gets or sets the identification.
- ///
- /// The identification.
- public DeviceIdentification Identification { get; set; }
-
- public string FriendlyName { get; set; }
-
- public string Manufacturer { get; set; }
-
- public string ManufacturerUrl { get; set; }
-
- public string ModelName { get; set; }
-
- public string ModelDescription { get; set; }
-
- public string ModelNumber { get; set; }
-
- public string ModelUrl { get; set; }
-
- public string SerialNumber { get; set; }
-
- public bool EnableAlbumArtInDidl { get; set; }
-
- public bool EnableSingleAlbumArtLimit { get; set; }
-
- public bool EnableSingleSubtitleLimit { get; set; }
-
- public string SupportedMediaTypes { get; set; }
-
- public string UserId { get; set; }
-
- public string AlbumArtPn { get; set; }
-
- public int MaxAlbumArtWidth { get; set; }
-
- public int MaxAlbumArtHeight { get; set; }
-
- public int? MaxIconWidth { get; set; }
-
- public int? MaxIconHeight { get; set; }
-
- public long? MaxStreamingBitrate { get; set; }
-
- public long? MaxStaticBitrate { get; set; }
-
- public int? MusicStreamingTranscodingBitrate { get; set; }
-
- public int? MaxStaticMusicBitrate { get; set; }
-
- ///
- /// Controls the content of the aggregationFlags element in the urn:schemas-sonycom:av namespace.
- ///
- public string SonyAggregationFlags { get; set; }
-
- public string ProtocolInfo { get; set; }
-
- public int TimelineOffsetSeconds { get; set; }
-
- public bool RequiresPlainVideoItems { get; set; }
-
- public bool RequiresPlainFolders { get; set; }
-
- public bool EnableMSMediaReceiverRegistrar { get; set; }
-
- public bool IgnoreTranscodeByteRangeRequests { get; set; }
-
- public XmlAttribute[] XmlRootAttributes { get; set; }
-
- ///
- /// Gets or sets the direct play profiles.
- ///
- /// The direct play profiles.
- public DirectPlayProfile[] DirectPlayProfiles { get; set; }
-
- ///
- /// Gets or sets the transcoding profiles.
- ///
- /// The transcoding profiles.
- public TranscodingProfile[] TranscodingProfiles { get; set; }
-
- public ContainerProfile[] ContainerProfiles { get; set; }
-
- public CodecProfile[] CodecProfiles { get; set; }
-
- public ResponseProfile[] ResponseProfiles { get; set; }
-
- public SubtitleProfile[] SubtitleProfiles { get; set; }
-
public DeviceProfile()
{
DirectPlayProfiles = Array.Empty();
@@ -126,11 +33,217 @@ namespace MediaBrowser.Model.Dlna
MusicStreamingTranscodingBitrate = 128000;
}
+ ///
+ /// Gets or sets the Name.
+ ///
+ public string Name { get; set; }
+
+ ///
+ /// Gets or sets the Id.
+ ///
+ [XmlIgnore]
+ public string Id { get; set; }
+
+ ///
+ /// Gets or sets the Identification.
+ ///
+ public DeviceIdentification Identification { get; set; }
+
+ ///
+ /// Gets or sets the FriendlyName.
+ ///
+ public string FriendlyName { get; set; }
+
+ ///
+ /// Gets or sets the Manufacturer.
+ ///
+ public string Manufacturer { get; set; }
+
+ ///
+ /// Gets or sets the ManufacturerUrl.
+ ///
+ public string ManufacturerUrl { get; set; }
+
+ ///
+ /// Gets or sets the ModelName.
+ ///
+ public string ModelName { get; set; }
+
+ ///
+ /// Gets or sets the ModelDescription.
+ ///
+ public string ModelDescription { get; set; }
+
+ ///
+ /// Gets or sets the ModelNumber.
+ ///
+ public string ModelNumber { get; set; }
+
+ ///
+ /// Gets or sets the ModelUrl.
+ ///
+ public string ModelUrl { get; set; }
+
+ ///
+ /// Gets or sets the SerialNumber.
+ ///
+ public string SerialNumber { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether EnableAlbumArtInDidl.
+ ///
+ public bool EnableAlbumArtInDidl { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether EnableSingleAlbumArtLimit.
+ ///
+ public bool EnableSingleAlbumArtLimit { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether EnableSingleSubtitleLimit.
+ ///
+ public bool EnableSingleSubtitleLimit { get; set; }
+
+ ///
+ /// Gets or sets the SupportedMediaTypes.
+ ///
+ public string SupportedMediaTypes { get; set; }
+
+ ///
+ /// Gets or sets the UserId.
+ ///
+ public string UserId { get; set; }
+
+ ///
+ /// Gets or sets the AlbumArtPn.
+ ///
+ public string AlbumArtPn { get; set; }
+
+ ///
+ /// Gets or sets the MaxAlbumArtWidth.
+ ///
+ public int MaxAlbumArtWidth { get; set; }
+
+ ///
+ /// Gets or sets the MaxAlbumArtHeight.
+ ///
+ public int MaxAlbumArtHeight { get; set; }
+
+ ///
+ /// Gets or sets the MaxIconWidth.
+ ///
+ public int? MaxIconWidth { get; set; }
+
+ ///
+ /// Gets or sets the MaxIconHeight.
+ ///
+ public int? MaxIconHeight { get; set; }
+
+ ///
+ /// Gets or sets the MaxStreamingBitrate.
+ ///
+ public int? MaxStreamingBitrate { get; set; }
+
+ ///
+ /// Gets or sets the MaxStaticBitrate.
+ ///
+ public int? MaxStaticBitrate { get; set; }
+
+ ///
+ /// Gets or sets the MusicStreamingTranscodingBitrate.
+ ///
+ public int? MusicStreamingTranscodingBitrate { get; set; }
+
+ ///
+ /// Gets or sets the MaxStaticMusicBitrate.
+ ///
+ public int? MaxStaticMusicBitrate { get; set; }
+
+ ///
+ /// Gets or sets the content of the aggregationFlags element in the urn:schemas-sonycom:av namespace.
+ ///
+ public string SonyAggregationFlags { get; set; }
+
+ ///
+ /// Gets or sets the ProtocolInfo.
+ ///
+ public string ProtocolInfo { get; set; }
+
+ ///
+ /// Gets or sets the TimelineOffsetSeconds.
+ ///
+ public int TimelineOffsetSeconds { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether RequiresPlainVideoItems.
+ ///
+ public bool RequiresPlainVideoItems { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether RequiresPlainFolders.
+ ///
+ public bool RequiresPlainFolders { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether EnableMSMediaReceiverRegistrar.
+ ///
+ public bool EnableMSMediaReceiverRegistrar { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether IgnoreTranscodeByteRangeRequests.
+ ///
+ public bool IgnoreTranscodeByteRangeRequests { get; set; }
+
+ ///
+ /// Gets or sets the XmlRootAttributes.
+ ///
+ public XmlAttribute[] XmlRootAttributes { get; set; }
+
+ ///
+ /// Gets or sets the direct play profiles.
+ ///
+ public DirectPlayProfile[] DirectPlayProfiles { get; set; }
+
+ ///
+ /// Gets or sets the transcoding profiles.
+ ///
+ public TranscodingProfile[] TranscodingProfiles { get; set; }
+
+ ///
+ /// Gets or sets the ContainerProfiles.
+ ///
+ public ContainerProfile[] ContainerProfiles { get; set; }
+
+ ///
+ /// Gets or sets the CodecProfiles.
+ ///
+ public CodecProfile[] CodecProfiles { get; set; }
+
+ ///
+ /// Gets or sets the ResponseProfiles.
+ ///
+ public ResponseProfile[] ResponseProfiles { get; set; }
+
+ ///
+ /// Gets or sets the SubtitleProfiles.
+ ///
+ public SubtitleProfile[] SubtitleProfiles { get; set; }
+
+ ///
+ /// The GetSupportedMediaTypes.
+ ///
+ /// The .
public string[] GetSupportedMediaTypes()
{
return ContainerProfile.SplitValue(SupportedMediaTypes);
}
+ ///
+ /// Gets the audio transcoding profile.
+ ///
+ /// The container.
+ /// The audio Codec.
+ /// A .
public TranscodingProfile GetAudioTranscodingProfile(string container, string audioCodec)
{
container = (container ?? string.Empty).TrimStart('.');
@@ -158,6 +271,13 @@ namespace MediaBrowser.Model.Dlna
return null;
}
+ ///
+ /// Gets the video transcoding profile.
+ ///
+ /// The container.
+ /// The audio Codec.
+ /// The video Codec.
+ /// The .
public TranscodingProfile GetVideoTranscodingProfile(string container, string audioCodec, string videoCodec)
{
container = (container ?? string.Empty).TrimStart('.');
@@ -190,6 +310,16 @@ namespace MediaBrowser.Model.Dlna
return null;
}
+ ///
+ /// Gets the audio media profile.
+ ///
+ /// The container.
+ /// The audio codec.
+ /// The audio channels.
+ /// The audio bitrate.
+ /// The audio sample rate.
+ /// The audio bit depth.
+ /// The .
public ResponseProfile GetAudioMediaProfile(string container, string audioCodec, int? audioChannels, int? audioBitrate, int? audioSampleRate, int? audioBitDepth)
{
foreach (var i in ResponseProfiles)
@@ -231,6 +361,11 @@ namespace MediaBrowser.Model.Dlna
return null;
}
+ ///
+ /// Gets the model profile condition.
+ ///
+ /// The c.
+ /// The .
private ProfileCondition GetModelProfileCondition(ProfileCondition c)
{
return new ProfileCondition
@@ -242,6 +377,13 @@ namespace MediaBrowser.Model.Dlna
};
}
+ ///
+ /// Gets the image media profile.
+ ///
+ /// The container.
+ /// The width.
+ /// The height.
+ /// The .
public ResponseProfile GetImageMediaProfile(string container, int? width, int? height)
{
foreach (var i in ResponseProfiles)
@@ -277,7 +419,31 @@ namespace MediaBrowser.Model.Dlna
return null;
}
- public ResponseProfile GetVideoMediaProfile(string container,
+ ///
+ /// Gets the video media profile.
+ ///
+ /// The container.
+ /// The audio codec.
+ /// The video codec.
+ /// The width.
+ /// The height.
+ /// The bit depth.
+ /// The video bitrate.
+ /// The video profile.
+ /// The video level.
+ /// The video framerate.
+ /// The packet length.
+ /// The timestamp.
+ /// True if anamorphic.
+ /// True if interlaced.
+ /// The ref frames.
+ /// The number of video streams.
+ /// The number of audio streams.
+ /// The video Codec tag.
+ /// True if Avc.
+ /// The .
+ public ResponseProfile GetVideoMediaProfile(
+ string container,
string audioCodec,
string videoCodec,
int? width,
diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs
index cfe862f5a9..43d1f3b443 100644
--- a/MediaBrowser.Model/Dlna/StreamBuilder.cs
+++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs
@@ -455,9 +455,11 @@ namespace MediaBrowser.Model.Dlna
if (directPlayProfile == null)
{
- _logger.LogInformation("Profile: {0}, No direct play profiles found for Path: {1}",
+ _logger.LogInformation(
+ "Profile: {0}, No audio direct play profiles found for {1} with codec {2}",
options.Profile.Name ?? "Unknown Profile",
- item.Path ?? "Unknown path");
+ item.Path ?? "Unknown path",
+ audioStream.Codec ?? "Unknown codec");
return (Enumerable.Empty(), GetTranscodeReasonsFromDirectPlayProfile(item, null, audioStream, options.Profile.DirectPlayProfiles));
}
@@ -498,7 +500,6 @@ namespace MediaBrowser.Model.Dlna
}
}
-
if (playMethods.Count > 0)
{
transcodeReasons.Clear();
@@ -679,7 +680,8 @@ namespace MediaBrowser.Model.Dlna
bool isEligibleForDirectPlay = options.EnableDirectPlay && (options.ForceDirectPlay || directPlayEligibilityResult.Item1);
bool isEligibleForDirectStream = options.EnableDirectStream && (options.ForceDirectStream || directStreamEligibilityResult.Item1);
- _logger.LogInformation("Profile: {0}, Path: {1}, isEligibleForDirectPlay: {2}, isEligibleForDirectStream: {3}",
+ _logger.LogInformation(
+ "Profile: {0}, Path: {1}, isEligibleForDirectPlay: {2}, isEligibleForDirectStream: {3}",
options.Profile.Name ?? "Unknown Profile",
item.Path ?? "Unknown path",
isEligibleForDirectPlay,
@@ -973,9 +975,11 @@ namespace MediaBrowser.Model.Dlna
if (directPlay == null)
{
- _logger.LogInformation("Profile: {0}, No direct play profiles found for Path: {1}",
+ _logger.LogInformation(
+ "Profile: {0}, No video direct play profiles found for {1} with codec {2}",
profile.Name ?? "Unknown Profile",
- mediaSource.Path ?? "Unknown path");
+ mediaSource.Path ?? "Unknown path",
+ videoStream.Codec ?? "Unknown codec");
return (null, GetTranscodeReasonsFromDirectPlayProfile(mediaSource, videoStream, audioStream, profile.DirectPlayProfiles));
}
@@ -1136,7 +1140,8 @@ namespace MediaBrowser.Model.Dlna
private void LogConditionFailure(DeviceProfile profile, string type, ProfileCondition condition, MediaSourceInfo mediaSource)
{
- _logger.LogInformation("Profile: {0}, DirectPlay=false. Reason={1}.{2} Condition: {3}. ConditionValue: {4}. IsRequired: {5}. Path: {6}",
+ _logger.LogInformation(
+ "Profile: {0}, DirectPlay=false. Reason={1}.{2} Condition: {3}. ConditionValue: {4}. IsRequired: {5}. Path: {6}",
type,
profile.Name ?? "Unknown Profile",
condition.Property,
@@ -1341,7 +1346,8 @@ namespace MediaBrowser.Model.Dlna
if (itemBitrate > requestedMaxBitrate)
{
- _logger.LogInformation("Bitrate exceeds {PlayBackMethod} limit: media bitrate: {MediaBitrate}, max bitrate: {MaxBitrate}",
+ _logger.LogInformation(
+ "Bitrate exceeds {PlayBackMethod} limit: media bitrate: {MediaBitrate}, max bitrate: {MaxBitrate}",
playMethod, itemBitrate, requestedMaxBitrate);
return false;
}
@@ -1431,6 +1437,33 @@ namespace MediaBrowser.Model.Dlna
break;
}
+
+ case ProfileConditionValue.AudioSampleRate:
+ {
+ if (!enableNonQualifiedConditions)
+ {
+ continue;
+ }
+
+ if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var num))
+ {
+ if (condition.Condition == ProfileConditionType.Equals)
+ {
+ item.AudioSampleRate = num;
+ }
+ else if (condition.Condition == ProfileConditionType.LessThanEqual)
+ {
+ item.AudioSampleRate = Math.Min(num, item.AudioSampleRate ?? num);
+ }
+ else if (condition.Condition == ProfileConditionType.GreaterThanEqual)
+ {
+ item.AudioSampleRate = Math.Max(num, item.AudioSampleRate ?? num);
+ }
+ }
+
+ break;
+ }
+
case ProfileConditionValue.AudioChannels:
{
if (string.IsNullOrEmpty(qualifier))
@@ -1466,6 +1499,7 @@ namespace MediaBrowser.Model.Dlna
break;
}
+
case ProfileConditionValue.IsAvc:
{
if (!enableNonQualifiedConditions)
@@ -1487,6 +1521,7 @@ namespace MediaBrowser.Model.Dlna
break;
}
+
case ProfileConditionValue.IsAnamorphic:
{
if (!enableNonQualifiedConditions)
@@ -1508,6 +1543,7 @@ namespace MediaBrowser.Model.Dlna
break;
}
+
case ProfileConditionValue.IsInterlaced:
{
if (string.IsNullOrEmpty(qualifier))
@@ -1539,6 +1575,7 @@ namespace MediaBrowser.Model.Dlna
break;
}
+
case ProfileConditionValue.AudioProfile:
case ProfileConditionValue.Has64BitOffsets:
case ProfileConditionValue.PacketLength:
@@ -1550,6 +1587,7 @@ namespace MediaBrowser.Model.Dlna
// Not supported yet
break;
}
+
case ProfileConditionValue.RefFrames:
{
if (string.IsNullOrEmpty(qualifier))
@@ -1585,6 +1623,7 @@ namespace MediaBrowser.Model.Dlna
break;
}
+
case ProfileConditionValue.VideoBitDepth:
{
if (string.IsNullOrEmpty(qualifier))
@@ -1620,6 +1659,7 @@ namespace MediaBrowser.Model.Dlna
break;
}
+
case ProfileConditionValue.VideoProfile:
{
if (string.IsNullOrEmpty(qualifier))
@@ -1633,7 +1673,7 @@ namespace MediaBrowser.Model.Dlna
// strip spaces to avoid having to encode
var values = value
- .Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
+ .Split('|', StringSplitOptions.RemoveEmptyEntries);
if (condition.Condition == ProfileConditionType.Equals || condition.Condition == ProfileConditionType.EqualsAny)
{
@@ -1643,6 +1683,7 @@ namespace MediaBrowser.Model.Dlna
break;
}
+
case ProfileConditionValue.Height:
{
if (!enableNonQualifiedConditions)
@@ -1668,6 +1709,7 @@ namespace MediaBrowser.Model.Dlna
break;
}
+
case ProfileConditionValue.VideoBitrate:
{
if (!enableNonQualifiedConditions)
@@ -1693,6 +1735,7 @@ namespace MediaBrowser.Model.Dlna
break;
}
+
case ProfileConditionValue.VideoFramerate:
{
if (!enableNonQualifiedConditions)
@@ -1718,6 +1761,7 @@ namespace MediaBrowser.Model.Dlna
break;
}
+
case ProfileConditionValue.VideoLevel:
{
if (string.IsNullOrEmpty(qualifier))
@@ -1743,6 +1787,7 @@ namespace MediaBrowser.Model.Dlna
break;
}
+
case ProfileConditionValue.Width:
{
if (!enableNonQualifiedConditions)
diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs
index 94d53ab70e..93ea82c1c5 100644
--- a/MediaBrowser.Model/Dlna/StreamInfo.cs
+++ b/MediaBrowser.Model/Dlna/StreamInfo.cs
@@ -110,6 +110,8 @@ namespace MediaBrowser.Model.Dlna
public int? AudioBitrate { get; set; }
+ public int? AudioSampleRate { get; set; }
+
public int? VideoBitrate { get; set; }
public int? MaxWidth { get; set; }
@@ -183,8 +185,10 @@ namespace MediaBrowser.Model.Dlna
continue;
}
+ // Be careful, IsDirectStream==true by default (Static != false or not in query).
+ // See initialization of StreamingRequestDto in AudioController.GetAudioStream() method : Static = @static ?? true.
if (string.Equals(pair.Name, "Static", StringComparison.OrdinalIgnoreCase) &&
- string.Equals(pair.Value, "false", StringComparison.OrdinalIgnoreCase))
+ string.Equals(pair.Value, "true", StringComparison.OrdinalIgnoreCase))
{
continue;
}
@@ -250,6 +254,7 @@ namespace MediaBrowser.Model.Dlna
list.Add(new NameValuePair("SubtitleStreamIndex", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod != SubtitleDeliveryMethod.External ? item.SubtitleStreamIndex.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
list.Add(new NameValuePair("VideoBitrate", item.VideoBitrate.HasValue ? item.VideoBitrate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
list.Add(new NameValuePair("AudioBitrate", item.AudioBitrate.HasValue ? item.AudioBitrate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
+ list.Add(new NameValuePair("AudioSampleRate", item.AudioSampleRate.HasValue ? item.AudioSampleRate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
list.Add(new NameValuePair("MaxFramerate", item.MaxFramerate.HasValue ? item.MaxFramerate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
list.Add(new NameValuePair("MaxWidth", item.MaxWidth.HasValue ? item.MaxWidth.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
@@ -276,7 +281,6 @@ namespace MediaBrowser.Model.Dlna
list.Add(new NameValuePair("SubtitleMethod", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod != SubtitleDeliveryMethod.External ? item.SubtitleDeliveryMethod.ToString() : string.Empty));
-
if (!item.IsDirectStream)
{
if (item.RequireNonAnamorphic)
@@ -522,7 +526,9 @@ namespace MediaBrowser.Model.Dlna
get
{
var stream = TargetAudioStream;
- return stream == null ? null : stream.SampleRate;
+ return AudioSampleRate.HasValue && !IsDirectStream
+ ? AudioSampleRate
+ : stream == null ? null : stream.SampleRate;
}
}
diff --git a/MediaBrowser.Model/Dlna/XmlAttribute.cs b/MediaBrowser.Model/Dlna/XmlAttribute.cs
index 3a8939a797..03bb2e4b11 100644
--- a/MediaBrowser.Model/Dlna/XmlAttribute.cs
+++ b/MediaBrowser.Model/Dlna/XmlAttribute.cs
@@ -5,11 +5,20 @@ using System.Xml.Serialization;
namespace MediaBrowser.Model.Dlna
{
+ ///
+ /// Defines the .
+ ///
public class XmlAttribute
{
+ ///
+ /// Gets or sets the name of the attribute.
+ ///
[XmlAttribute("name")]
public string Name { get; set; }
+ ///
+ /// Gets or sets the value of the attribute.
+ ///
[XmlAttribute("value")]
public string Value { get; set; }
}
diff --git a/MediaBrowser.Model/Dto/BaseItemDto.cs b/MediaBrowser.Model/Dto/BaseItemDto.cs
index af3d83adec..fac7541773 100644
--- a/MediaBrowser.Model/Dto/BaseItemDto.cs
+++ b/MediaBrowser.Model/Dto/BaseItemDto.cs
@@ -429,6 +429,7 @@ namespace MediaBrowser.Model.Dto
///
/// The album id.
public Guid AlbumId { get; set; }
+
///
/// Gets or sets the album image tag.
///
@@ -599,11 +600,13 @@ namespace MediaBrowser.Model.Dto
///
/// The trailer count.
public int? TrailerCount { get; set; }
+
///
/// Gets or sets the movie count.
///
/// The movie count.
public int? MovieCount { get; set; }
+
///
/// Gets or sets the series count.
///
@@ -611,16 +614,19 @@ namespace MediaBrowser.Model.Dto
public int? SeriesCount { get; set; }
public int? ProgramCount { get; set; }
+
///
/// Gets or sets the episode count.
///
/// The episode count.
public int? EpisodeCount { get; set; }
+
///
/// Gets or sets the song count.
///
/// The song count.
public int? SongCount { get; set; }
+
///
/// Gets or sets the album count.
///
@@ -628,6 +634,7 @@ namespace MediaBrowser.Model.Dto
public int? AlbumCount { get; set; }
public int? ArtistCount { get; set; }
+
///
/// Gets or sets the music video count.
///
@@ -768,6 +775,7 @@ namespace MediaBrowser.Model.Dto
///
/// The timer identifier.
public string TimerId { get; set; }
+
///
/// Gets or sets the current program.
///
diff --git a/MediaBrowser.Model/Entities/MediaStream.cs b/MediaBrowser.Model/Entities/MediaStream.cs
index 2d37618c27..ca0b93c30f 100644
--- a/MediaBrowser.Model/Entities/MediaStream.cs
+++ b/MediaBrowser.Model/Entities/MediaStream.cs
@@ -191,6 +191,11 @@ namespace MediaBrowser.Model.Entities
attributes.Add(Codec.ToUpperInvariant());
}
+ if (!string.IsNullOrEmpty(VideoRange))
+ {
+ attributes.Add(VideoRange.ToUpperInvariant());
+ }
+
if (!string.IsNullOrEmpty(Title))
{
var result = new StringBuilder(Title);
@@ -451,11 +456,13 @@ namespace MediaBrowser.Model.Entities
///
/// The method.
public SubtitleDeliveryMethod? DeliveryMethod { get; set; }
+
///
/// Gets or sets the delivery URL.
///
/// The delivery URL.
public string DeliveryUrl { get; set; }
+
///
/// Gets or sets a value indicating whether this instance is external URL.
///
diff --git a/MediaBrowser.Model/Entities/MetadataProvider.cs b/MediaBrowser.Model/Entities/MetadataProvider.cs
index 7fecf67b8e..e9c098021d 100644
--- a/MediaBrowser.Model/Entities/MetadataProvider.cs
+++ b/MediaBrowser.Model/Entities/MetadataProvider.cs
@@ -11,18 +11,22 @@ namespace MediaBrowser.Model.Entities
/// The imdb.
///
Imdb = 2,
+
///
/// The TMDB.
///
Tmdb = 3,
+
///
/// The TVDB.
///
Tvdb = 4,
+
///
/// The tvcom.
///
Tvcom = 5,
+
///
/// Tmdb Collection Id.
///
diff --git a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs
index 9c11fe0ad2..1782b42e21 100644
--- a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs
+++ b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs
@@ -48,7 +48,7 @@ namespace MediaBrowser.Model.Entities
return null;
}
- instance.ProviderIds.TryGetValue(name, out string id);
+ instance.ProviderIds.TryGetValue(name, out string? id);
return id;
}
diff --git a/MediaBrowser.Model/Extensions/EnumerableExtensions.cs b/MediaBrowser.Model/Extensions/EnumerableExtensions.cs
new file mode 100644
index 0000000000..712fa381ee
--- /dev/null
+++ b/MediaBrowser.Model/Extensions/EnumerableExtensions.cs
@@ -0,0 +1,46 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using MediaBrowser.Model.Providers;
+
+namespace MediaBrowser.Model.Extensions
+{
+ ///
+ /// Extension methods for .
+ ///
+ public static class EnumerableExtensions
+ {
+ ///
+ /// Orders by requested language in descending order, prioritizing "en" over other non-matches.
+ ///
+ /// The remote image infos.
+ /// The requested language for the images.
+ /// The ordered remote image infos.
+ public static IEnumerable OrderByLanguageDescending(this IEnumerable remoteImageInfos, string requestedLanguage)
+ {
+ var isRequestedLanguageEn = string.Equals(requestedLanguage, "en", StringComparison.OrdinalIgnoreCase);
+
+ return remoteImageInfos.OrderByDescending(i =>
+ {
+ if (string.Equals(requestedLanguage, i.Language, StringComparison.OrdinalIgnoreCase))
+ {
+ return 3;
+ }
+
+ if (!isRequestedLanguageEn && string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
+ {
+ return 2;
+ }
+
+ if (string.IsNullOrEmpty(i.Language))
+ {
+ return isRequestedLanguageEn ? 3 : 2;
+ }
+
+ return 0;
+ })
+ .ThenByDescending(i => i.CommunityRating ?? 0)
+ .ThenByDescending(i => i.VoteCount ?? 0);
+ }
+ }
+}
diff --git a/MediaBrowser.Model/Extensions/StringHelper.cs b/MediaBrowser.Model/Extensions/StringHelper.cs
index 8ffa3c4ba6..2d9a6c4dbc 100644
--- a/MediaBrowser.Model/Extensions/StringHelper.cs
+++ b/MediaBrowser.Model/Extensions/StringHelper.cs
@@ -22,11 +22,6 @@ namespace MediaBrowser.Model.Extensions
return str;
}
-#if NETSTANDARD2_0
- char[] a = str.ToCharArray();
- a[0] = char.ToUpperInvariant(a[0]);
- return new string(a);
-#else
return string.Create(
str.Length,
str,
@@ -38,7 +33,6 @@ namespace MediaBrowser.Model.Extensions
chars[i] = buf[i];
}
});
-#endif
}
}
}
diff --git a/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs b/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs
index ab74aff28b..bcba344cc5 100644
--- a/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs
+++ b/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs
@@ -84,6 +84,7 @@ namespace MediaBrowser.Model.LiveTv
///
/// null if [is kids] contains no value, true if [is kids]; otherwise, false.
public bool? IsKids { get; set; }
+
///
/// Gets or sets a value indicating whether this instance is sports.
///
diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj
index 2646810907..b86187f9be 100644
--- a/MediaBrowser.Model/MediaBrowser.Model.csproj
+++ b/MediaBrowser.Model/MediaBrowser.Model.csproj
@@ -14,7 +14,7 @@
- netstandard2.0;netstandard2.1
+ net5.0
false
true
true
@@ -32,11 +32,11 @@
-
+
-
+
-
+
diff --git a/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs b/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs
index 83bda5d569..36a2407067 100644
--- a/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs
+++ b/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs
@@ -2,6 +2,7 @@
#pragma warning disable CS1591
using System;
+using System.Collections.Generic;
using MediaBrowser.Model.Dlna;
namespace MediaBrowser.Model.MediaInfo
@@ -37,7 +38,7 @@ namespace MediaBrowser.Model.MediaInfo
public string PlaySessionId { get; set; }
- public long? MaxStreamingBitrate { get; set; }
+ public int? MaxStreamingBitrate { get; set; }
public long? StartTimeTicks { get; set; }
@@ -55,6 +56,6 @@ namespace MediaBrowser.Model.MediaInfo
public bool EnableDirectStream { get; set; }
- public MediaProtocol[] DirectPlayProtocols { get; set; }
+ public IReadOnlyList DirectPlayProtocols { get; set; }
}
}
diff --git a/MediaBrowser.Model/Net/HttpException.cs b/MediaBrowser.Model/Net/HttpException.cs
deleted file mode 100644
index 48ff5d51cc..0000000000
--- a/MediaBrowser.Model/Net/HttpException.cs
+++ /dev/null
@@ -1,42 +0,0 @@
-using System;
-using System.Net;
-
-namespace MediaBrowser.Model.Net
-{
- ///
- /// Class HttpException.
- ///
- public class HttpException : Exception
- {
- ///
- /// Gets or sets the status code.
- ///
- /// The status code.
- public HttpStatusCode? StatusCode { get; set; }
-
- ///
- /// Gets or sets a value indicating whether this instance is timed out.
- ///
- /// true if this instance is timed out; otherwise, false.
- public bool IsTimedOut { get; set; }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The message.
- /// The inner exception.
- public HttpException(string message, Exception innerException)
- : base(message, innerException)
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The message.
- public HttpException(string message)
- : base(message)
- {
- }
- }
-}
diff --git a/MediaBrowser.Model/Net/MimeTypes.cs b/MediaBrowser.Model/Net/MimeTypes.cs
index afe7351d32..902db1e9e5 100644
--- a/MediaBrowser.Model/Net/MimeTypes.cs
+++ b/MediaBrowser.Model/Net/MimeTypes.cs
@@ -177,7 +177,7 @@ namespace MediaBrowser.Model.Net
var ext = Path.GetExtension(path);
- if (_mimeTypeLookup.TryGetValue(ext, out string result))
+ if (_mimeTypeLookup.TryGetValue(ext, out string? result))
{
return result;
}
@@ -210,9 +210,9 @@ namespace MediaBrowser.Model.Net
return enableStreamDefault ? "application/octet-stream" : null;
}
- public static string? ToExtension(string mimeType)
+ public static string? ToExtension(string? mimeType)
{
- if (mimeType.Length == 0)
+ if (string.IsNullOrEmpty(mimeType))
{
throw new ArgumentException("String can't be empty.", nameof(mimeType));
}
@@ -220,7 +220,7 @@ namespace MediaBrowser.Model.Net
// handle text/html; charset=UTF-8
mimeType = mimeType.Split(';')[0];
- if (_extensionLookup.TryGetValue(mimeType, out string result))
+ if (_extensionLookup.TryGetValue(mimeType, out string? result))
{
return result;
}
diff --git a/MediaBrowser.Model/Net/WebSocketMessage.cs b/MediaBrowser.Model/Net/WebSocketMessage.cs
index 660eebeda6..bffbbe612d 100644
--- a/MediaBrowser.Model/Net/WebSocketMessage.cs
+++ b/MediaBrowser.Model/Net/WebSocketMessage.cs
@@ -2,6 +2,7 @@
#pragma warning disable CS1591
using System;
+using MediaBrowser.Model.Session;
namespace MediaBrowser.Model.Net
{
@@ -15,7 +16,7 @@ namespace MediaBrowser.Model.Net
/// Gets or sets the type of the message.
///
/// The type of the message.
- public string MessageType { get; set; }
+ public SessionMessageType MessageType { get; set; }
public Guid MessageId { get; set; }
diff --git a/MediaBrowser.Model/Providers/RemoteImageInfo.cs b/MediaBrowser.Model/Providers/RemoteImageInfo.cs
index 78ab6c706c..fb25999e0a 100644
--- a/MediaBrowser.Model/Providers/RemoteImageInfo.cs
+++ b/MediaBrowser.Model/Providers/RemoteImageInfo.cs
@@ -68,5 +68,4 @@ namespace MediaBrowser.Model.Providers
/// The type of the rating.
public RatingType RatingType { get; set; }
}
-
}
diff --git a/MediaBrowser.Model/Providers/RemoteSearchResult.cs b/MediaBrowser.Model/Providers/RemoteSearchResult.cs
index 989741c01a..a29e7ad1c5 100644
--- a/MediaBrowser.Model/Providers/RemoteSearchResult.cs
+++ b/MediaBrowser.Model/Providers/RemoteSearchResult.cs
@@ -50,6 +50,5 @@ namespace MediaBrowser.Model.Providers
public RemoteSearchResult AlbumArtist { get; set; }
public RemoteSearchResult[] Artists { get; set; }
-
}
}
diff --git a/MediaBrowser.Model/Querying/ItemFields.cs b/MediaBrowser.Model/Querying/ItemFields.cs
index 731d22aaf8..ef4698f3f9 100644
--- a/MediaBrowser.Model/Querying/ItemFields.cs
+++ b/MediaBrowser.Model/Querying/ItemFields.cs
@@ -168,6 +168,7 @@ namespace MediaBrowser.Model.Querying
Studios,
BasicSyncInfo,
+
///
/// The synchronize information.
///
diff --git a/MediaBrowser.Model/Querying/UpcomingEpisodesQuery.cs b/MediaBrowser.Model/Querying/UpcomingEpisodesQuery.cs
index 2ef6f7c60b..eb62394605 100644
--- a/MediaBrowser.Model/Querying/UpcomingEpisodesQuery.cs
+++ b/MediaBrowser.Model/Querying/UpcomingEpisodesQuery.cs
@@ -37,16 +37,19 @@ namespace MediaBrowser.Model.Querying
///
/// The fields.
public ItemFields[] Fields { get; set; }
+
///
/// Gets or sets a value indicating whether [enable images].
///
/// null if [enable images] contains no value, true if [enable images]; otherwise, false.
public bool? EnableImages { get; set; }
+
///
/// Gets or sets the image type limit.
///
/// The image type limit.
public int? ImageTypeLimit { get; set; }
+
///
/// Gets or sets the enable image types.
///
diff --git a/MediaBrowser.Model/Session/ClientCapabilities.cs b/MediaBrowser.Model/Session/ClientCapabilities.cs
index d3878ca308..a85e6ff2a4 100644
--- a/MediaBrowser.Model/Session/ClientCapabilities.cs
+++ b/MediaBrowser.Model/Session/ClientCapabilities.cs
@@ -10,7 +10,7 @@ namespace MediaBrowser.Model.Session
{
public string[] PlayableMediaTypes { get; set; }
- public string[] SupportedCommands { get; set; }
+ public GeneralCommandType[] SupportedCommands { get; set; }
public bool SupportsMediaControl { get; set; }
@@ -31,7 +31,7 @@ namespace MediaBrowser.Model.Session
public ClientCapabilities()
{
PlayableMediaTypes = Array.Empty();
- SupportedCommands = Array.Empty();
+ SupportedCommands = Array.Empty();
SupportsPersistentIdentifier = true;
}
}
diff --git a/MediaBrowser.Model/Session/GeneralCommandType.cs b/MediaBrowser.Model/Session/GeneralCommandType.cs
index 5a9042d5f9..c58fa9a6b9 100644
--- a/MediaBrowser.Model/Session/GeneralCommandType.cs
+++ b/MediaBrowser.Model/Session/GeneralCommandType.cs
@@ -43,6 +43,11 @@ namespace MediaBrowser.Model.Session
Guide = 32,
ToggleStats = 33,
PlayMediaSource = 34,
- PlayTrailers = 35
+ PlayTrailers = 35,
+ SetShuffleQueue = 36,
+ PlayState = 37,
+ PlayNext = 38,
+ ToggleOsdMenu = 39,
+ Play = 40
}
}
diff --git a/MediaBrowser.Model/Session/PlaybackProgressInfo.cs b/MediaBrowser.Model/Session/PlaybackProgressInfo.cs
index 21bcabf1d9..73dbe6a2da 100644
--- a/MediaBrowser.Model/Session/PlaybackProgressInfo.cs
+++ b/MediaBrowser.Model/Session/PlaybackProgressInfo.cs
@@ -88,16 +88,19 @@ namespace MediaBrowser.Model.Session
///
/// The play method.
public PlayMethod PlayMethod { get; set; }
+
///
/// Gets or sets the live stream identifier.
///
/// The live stream identifier.
public string LiveStreamId { get; set; }
+
///
/// Gets or sets the play session identifier.
///
/// The play session identifier.
public string PlaySessionId { get; set; }
+
///
/// Gets or sets the repeat mode.
///
diff --git a/MediaBrowser.Model/Session/SessionMessageType.cs b/MediaBrowser.Model/Session/SessionMessageType.cs
new file mode 100644
index 0000000000..23c41026dc
--- /dev/null
+++ b/MediaBrowser.Model/Session/SessionMessageType.cs
@@ -0,0 +1,50 @@
+#pragma warning disable CS1591
+
+namespace MediaBrowser.Model.Session
+{
+ ///
+ /// The different kinds of messages that are used in the WebSocket api.
+ ///
+ public enum SessionMessageType
+ {
+ // Server -> Client
+ ForceKeepAlive,
+ GeneralCommand,
+ UserDataChanged,
+ Sessions,
+ Play,
+ SyncPlayCommand,
+ SyncPlayGroupUpdate,
+ PlayState,
+ RestartRequired,
+ ServerShuttingDown,
+ ServerRestarting,
+ LibraryChanged,
+ UserDeleted,
+ UserUpdated,
+ SeriesTimerCreated,
+ TimerCreated,
+ SeriesTimerCancelled,
+ TimerCancelled,
+ RefreshProgress,
+ ScheduledTaskEnded,
+ PackageInstallationCancelled,
+ PackageInstallationFailed,
+ PackageInstallationCompleted,
+ PackageInstalling,
+ PackageUninstalled,
+ ActivityLogEntry,
+ ScheduledTasksInfo,
+
+ // Client -> Server
+ ActivityLogEntryStart,
+ ActivityLogEntryStop,
+ SessionsStart,
+ SessionsStop,
+ ScheduledTasksInfoStart,
+ ScheduledTasksInfoStop,
+
+ // Shared
+ KeepAlive,
+ }
+}
diff --git a/MediaBrowser.Model/Subtitles/FontFile.cs b/MediaBrowser.Model/Subtitles/FontFile.cs
new file mode 100644
index 0000000000..115c492957
--- /dev/null
+++ b/MediaBrowser.Model/Subtitles/FontFile.cs
@@ -0,0 +1,34 @@
+using System;
+
+namespace MediaBrowser.Model.Subtitles
+{
+ ///
+ /// Class FontFile.
+ ///
+ public class FontFile
+ {
+ ///
+ /// Gets or sets the name.
+ ///
+ /// The name.
+ public string? Name { get; set; }
+
+ ///
+ /// Gets or sets the size.
+ ///
+ /// The size.
+ public long Size { get; set; }
+
+ ///
+ /// Gets or sets the date created.
+ ///
+ /// The date created.
+ public DateTime DateCreated { get; set; }
+
+ ///
+ /// Gets or sets the date modified.
+ ///
+ /// The date modified.
+ public DateTime DateModified { get; set; }
+ }
+}
diff --git a/MediaBrowser.Model/Sync/SyncCategory.cs b/MediaBrowser.Model/Sync/SyncCategory.cs
index 80ad5f56ec..1248c2f739 100644
--- a/MediaBrowser.Model/Sync/SyncCategory.cs
+++ b/MediaBrowser.Model/Sync/SyncCategory.cs
@@ -8,10 +8,12 @@ namespace MediaBrowser.Model.Sync
/// The latest.
///
Latest = 0,
+
///
/// The next up.
///
NextUp = 1,
+
///
/// The resume.
///
diff --git a/MediaBrowser.Model/System/PublicSystemInfo.cs b/MediaBrowser.Model/System/PublicSystemInfo.cs
index d2f7556a51..53030843ae 100644
--- a/MediaBrowser.Model/System/PublicSystemInfo.cs
+++ b/MediaBrowser.Model/System/PublicSystemInfo.cs
@@ -43,7 +43,10 @@ namespace MediaBrowser.Model.System
///
/// Gets or sets a value indicating whether the startup wizard is completed.
///
- /// The startup completion status.
- public bool StartupWizardCompleted { get; set; }
+ ///
+ /// Nullable for OpenAPI specification only to retain backwards compatibility in apiclients.
+ ///
+ /// The startup completion status.]
+ public bool? StartupWizardCompleted { get; set; }
}
}
diff --git a/MediaBrowser.Model/System/SystemInfo.cs b/MediaBrowser.Model/System/SystemInfo.cs
index 18ca74ee30..4b83fb7e61 100644
--- a/MediaBrowser.Model/System/SystemInfo.cs
+++ b/MediaBrowser.Model/System/SystemInfo.cs
@@ -14,13 +14,16 @@ namespace MediaBrowser.Model.System
{
/// No path to FFmpeg found.
NotFound,
+
/// Path supplied via command line using switch --ffmpeg.
SetByArgument,
+
/// User has supplied path via Transcoding UI page.
Custom,
+
/// FFmpeg tool found on system $PATH.
System
- };
+ }
///
/// Class SystemInfo.
diff --git a/MediaBrowser.Model/Tasks/IConfigurableScheduledTask.cs b/MediaBrowser.Model/Tasks/IConfigurableScheduledTask.cs
index fbfaed22ef..6212d76f78 100644
--- a/MediaBrowser.Model/Tasks/IConfigurableScheduledTask.cs
+++ b/MediaBrowser.Model/Tasks/IConfigurableScheduledTask.cs
@@ -9,6 +9,7 @@ namespace MediaBrowser.Model.Tasks
///
/// true if this instance is hidden; otherwise, false.
bool IsHidden { get; }
+
///
/// Gets a value indicating whether this instance is enabled.
///
diff --git a/MediaBrowser.Model/Updates/PackageInfo.cs b/MediaBrowser.Model/Updates/PackageInfo.cs
index d9eb1386ef..98b151d551 100644
--- a/MediaBrowser.Model/Updates/PackageInfo.cs
+++ b/MediaBrowser.Model/Updates/PackageInfo.cs
@@ -52,6 +52,16 @@ namespace MediaBrowser.Model.Updates
/// The versions.
public IReadOnlyList versions { get; set; }
+ ///
+ /// Gets or sets the repository name.
+ ///
+ public string repositoryName { get; set; }
+
+ ///
+ /// Gets or sets the repository url.
+ ///
+ public string repositoryUrl { get; set; }
+
///
/// Initializes a new instance of the class.
///
diff --git a/MediaBrowser.Model/Users/UserPolicy.cs b/MediaBrowser.Model/Users/UserPolicy.cs
index a1f01f7e8e..363b2633fd 100644
--- a/MediaBrowser.Model/Users/UserPolicy.cs
+++ b/MediaBrowser.Model/Users/UserPolicy.cs
@@ -92,6 +92,8 @@ namespace MediaBrowser.Model.Users
public int LoginAttemptsBeforeLockout { get; set; }
+ public int MaxActiveSessions { get; set; }
+
public bool EnablePublicSharing { get; set; }
public Guid[] BlockedMediaFolders { get; set; }
@@ -144,6 +146,8 @@ namespace MediaBrowser.Model.Users
LoginAttemptsBeforeLockout = -1;
+ MaxActiveSessions = 0;
+
EnableAllChannels = true;
EnabledChannels = Array.Empty();
diff --git a/MediaBrowser.Providers/Manager/ItemImageProvider.cs b/MediaBrowser.Providers/Manager/ItemImageProvider.cs
index d0bdbd7c95..ffc6889fa2 100644
--- a/MediaBrowser.Providers/Manager/ItemImageProvider.cs
+++ b/MediaBrowser.Providers/Manager/ItemImageProvider.cs
@@ -5,6 +5,7 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
+using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Entities;
@@ -468,7 +469,7 @@ namespace MediaBrowser.Providers.Manager
try
{
using var response = await provider.GetImageResponse(url, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
await _providerManager.SaveImage(
item,
@@ -481,7 +482,7 @@ namespace MediaBrowser.Providers.Manager
result.UpdateType |= ItemUpdateType.ImageUpdate;
return true;
}
- catch (HttpException ex)
+ catch (HttpRequestException ex)
{
// Sometimes providers send back bad url's. Just move to the next image
if (ex.StatusCode.HasValue
@@ -517,13 +518,8 @@ namespace MediaBrowser.Providers.Manager
return true;
}
}
-
- if (libraryOptions.DownloadImagesInAdvance)
- {
- return false;
- }
-
- return true;
+ // We always want to use prefetched images
+ return false;
}
private void SaveImageStub(BaseItem item, ImageType imageType, IEnumerable urls)
@@ -590,7 +586,7 @@ namespace MediaBrowser.Providers.Manager
}
}
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
await _providerManager.SaveImage(
item,
stream,
@@ -600,7 +596,7 @@ namespace MediaBrowser.Providers.Manager
cancellationToken).ConfigureAwait(false);
result.UpdateType = result.UpdateType | ItemUpdateType.ImageUpdate;
}
- catch (HttpException ex)
+ catch (HttpRequestException ex)
{
// Sometimes providers send back bad urls. Just move onto the next image
if (ex.StatusCode.HasValue
diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs
index f110eafa5a..dca8acb7d8 100644
--- a/MediaBrowser.Providers/Manager/MetadataService.cs
+++ b/MediaBrowser.Providers/Manager/MetadataService.cs
@@ -252,7 +252,13 @@ namespace MediaBrowser.Providers.Manager
if (!string.IsNullOrWhiteSpace(person.ImageUrl) && !personEntity.HasImage(ImageType.Primary))
{
- await AddPersonImageAsync(personEntity, libraryOptions, person.ImageUrl, cancellationToken).ConfigureAwait(false);
+ personEntity.SetImage(
+ new ItemImageInfo
+ {
+ Path = person.ImageUrl,
+ Type = ImageType.Primary
+ },
+ 0);
saveEntity = true;
updateType |= ItemUpdateType.ImageUpdate;
@@ -266,30 +272,6 @@ namespace MediaBrowser.Providers.Manager
}
}
- private async Task AddPersonImageAsync(Person personEntity, LibraryOptions libraryOptions, string imageUrl, CancellationToken cancellationToken)
- {
- if (libraryOptions.DownloadImagesInAdvance)
- {
- try
- {
- await ProviderManager.SaveImage(personEntity, imageUrl, ImageType.Primary, null, cancellationToken).ConfigureAwait(false);
- return;
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error in AddPersonImage");
- }
- }
-
- personEntity.SetImage(
- new ItemImageInfo
- {
- Path = imageUrl,
- Type = ImageType.Primary
- },
- 0);
- }
-
protected virtual Task AfterMetadataRefresh(TItemType item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken)
{
item.AfterMetadataRefresh();
diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs
index b6fb4267f4..58ca88a5be 100644
--- a/MediaBrowser.Providers/Manager/ProviderManager.cs
+++ b/MediaBrowser.Providers/Manager/ProviderManager.cs
@@ -158,6 +158,11 @@ namespace MediaBrowser.Providers.Manager
var httpClient = _httpClientFactory.CreateClient(NamedClient.Default);
using var response = await httpClient.GetAsync(url, cancellationToken).ConfigureAwait(false);
+ if (response.StatusCode != HttpStatusCode.OK)
+ {
+ throw new HttpRequestException("Invalid image received.", null, response.StatusCode);
+ }
+
var contentType = response.Content.Headers.ContentType.MediaType;
// Workaround for tvheadend channel icons
@@ -173,13 +178,10 @@ namespace MediaBrowser.Providers.Manager
// thetvdb 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 HttpException("Invalid image received.")
- {
- StatusCode = HttpStatusCode.NotFound
- };
+ throw new HttpRequestException("Invalid image received.", null, HttpStatusCode.NotFound);
}
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
await SaveImage(
item,
stream,
diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj
index 51ca26361d..accdea36e4 100644
--- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj
+++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj
@@ -16,16 +16,17 @@
-
-
-
-
-
-
+
+
+
+
+
+
+
- netstandard2.1
+ net5.0
false
true
true
diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs b/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs
index d231bfa2fc..9804ec3bb4 100644
--- a/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs
+++ b/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs
@@ -214,7 +214,7 @@ namespace MediaBrowser.Providers.MediaInfo
return new[]
{
// Every so often
- new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks}
+ new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks }
};
}
}
diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs
index e6d89e6880..6536b303fe 100644
--- a/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs
+++ b/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs
@@ -175,7 +175,7 @@ namespace MediaBrowser.Providers.Plugins.AudioDb
Directory.CreateDirectory(Path.GetDirectoryName(path));
using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
await using var xmlFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true);
await stream.CopyToAsync(xmlFileStream, cancellationToken).ConfigureAwait(false);
}
diff --git a/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs
index 72dad8a25a..85c92fa7b9 100644
--- a/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs
+++ b/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs
@@ -156,7 +156,7 @@ namespace MediaBrowser.Providers.Plugins.AudioDb
var path = GetArtistInfoPath(_config.ApplicationPaths, musicBrainzId);
using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
Directory.CreateDirectory(Path.GetDirectoryName(path));
diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/ArtistProvider.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/ArtistProvider.cs
index 781b716406..dc755b600b 100644
--- a/MediaBrowser.Providers/Plugins/MusicBrainz/ArtistProvider.cs
+++ b/MediaBrowser.Providers/Plugins/MusicBrainz/ArtistProvider.cs
@@ -38,7 +38,7 @@ namespace MediaBrowser.Providers.Music
var url = "/ws/2/artist/?query=arid:{0}" + musicBrainzId.ToString(CultureInfo.InvariantCulture);
using var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
return GetResultsFromResponse(stream);
}
else
@@ -49,7 +49,7 @@ namespace MediaBrowser.Providers.Music
var url = string.Format(CultureInfo.InvariantCulture, "/ws/2/artist/?query=\"{0}\"&dismax=true", UrlEncode(nameToSearch));
using (var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false))
- await using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
+ await using (var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false))
{
var results = GetResultsFromResponse(stream).ToList();
@@ -65,7 +65,7 @@ namespace MediaBrowser.Providers.Music
url = string.Format(CultureInfo.InvariantCulture, "/ws/2/artist/?query=artistaccent:\"{0}\"", UrlEncode(nameToSearch));
using var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
return GetResultsFromResponse(stream);
}
}
@@ -198,6 +198,7 @@ namespace MediaBrowser.Providers.Music
result.Name = reader.ReadElementContentAsString();
break;
}
+
case "annotation":
{
result.Overview = reader.ReadElementContentAsString();
diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs
index 46f8988f27..93178d64a8 100644
--- a/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs
+++ b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs
@@ -46,6 +46,7 @@ namespace MediaBrowser.Providers.Music
private readonly string _musicBrainzBaseUrl;
+ private SemaphoreSlim _apiRequestLock = new SemaphoreSlim(1, 1);
private Stopwatch _stopWatchMusicBrainz = new Stopwatch();
public MusicBrainzAlbumProvider(
@@ -124,7 +125,7 @@ namespace MediaBrowser.Providers.Music
if (!string.IsNullOrWhiteSpace(url))
{
using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
return GetResultsFromResponse(stream);
}
@@ -283,7 +284,7 @@ namespace MediaBrowser.Providers.Music
artistId);
using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
using var oReader = new StreamReader(stream, Encoding.UTF8);
var settings = new XmlReaderSettings
{
@@ -306,7 +307,7 @@ namespace MediaBrowser.Providers.Music
WebUtility.UrlEncode(artistName));
using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
using var oReader = new StreamReader(stream, Encoding.UTF8);
var settings = new XmlReaderSettings()
{
@@ -444,6 +445,7 @@ namespace MediaBrowser.Providers.Music
result.Title = reader.ReadElementContentAsString();
break;
}
+
case "date":
{
var val = reader.ReadElementContentAsString();
@@ -454,17 +456,20 @@ namespace MediaBrowser.Providers.Music
break;
}
+
case "annotation":
{
result.Overview = reader.ReadElementContentAsString();
break;
}
+
case "release-group":
{
result.ReleaseGroupId = reader.GetAttribute("id");
reader.Skip();
break;
}
+
case "artist-credit":
{
using (var subReader = reader.ReadSubtree())
@@ -617,7 +622,7 @@ namespace MediaBrowser.Providers.Music
var url = "/ws/2/release?release-group=" + releaseGroupId.ToString(CultureInfo.InvariantCulture);
using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
using var oReader = new StreamReader(stream, Encoding.UTF8);
var settings = new XmlReaderSettings
{
@@ -644,7 +649,7 @@ namespace MediaBrowser.Providers.Music
var url = "/ws/2/release-group/?query=reid:" + releaseEntryId.ToString(CultureInfo.InvariantCulture);
using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
using var oReader = new StreamReader(stream, Encoding.UTF8);
var settings = new XmlReaderSettings
{
@@ -738,48 +743,58 @@ namespace MediaBrowser.Providers.Music
///
internal async Task GetMusicBrainzResponse(string url, CancellationToken cancellationToken)
{
- using var options = new HttpRequestMessage(HttpMethod.Get, _musicBrainzBaseUrl.TrimEnd('/') + url);
+ await _apiRequestLock.WaitAsync(cancellationToken).ConfigureAwait(false);
- // MusicBrainz request a contact email address is supplied, as comment, in user agent field:
- // https://musicbrainz.org/doc/XML_Web_Service/Rate_Limiting#User-Agent
- options.Headers.UserAgent.ParseAdd(string.Format(
- CultureInfo.InvariantCulture,
- "{0} ( {1} )",
- _appHost.ApplicationUserAgent,
- _appHost.ApplicationUserAgentAddress));
-
- HttpResponseMessage response;
- var attempts = 0u;
-
- do
+ try
{
- attempts++;
+ HttpResponseMessage response;
+ var attempts = 0u;
+ var requestUrl = _musicBrainzBaseUrl.TrimEnd('/') + url;
- if (_stopWatchMusicBrainz.ElapsedMilliseconds < _musicBrainzQueryIntervalMs)
+ do
{
- // MusicBrainz is extremely adamant about limiting to one request per second
- var delayMs = _musicBrainzQueryIntervalMs - _stopWatchMusicBrainz.ElapsedMilliseconds;
- await Task.Delay((int)delayMs, cancellationToken).ConfigureAwait(false);
+ attempts++;
+
+ if (_stopWatchMusicBrainz.ElapsedMilliseconds < _musicBrainzQueryIntervalMs)
+ {
+ // MusicBrainz is extremely adamant about limiting to one request per second.
+ var delayMs = _musicBrainzQueryIntervalMs - _stopWatchMusicBrainz.ElapsedMilliseconds;
+ await Task.Delay((int)delayMs, cancellationToken).ConfigureAwait(false);
+ }
+
+ // Write time since last request to debug log as evidence we're meeting rate limit
+ // requirement, before resetting stopwatch back to zero.
+ _logger.LogDebug("GetMusicBrainzResponse: Time since previous request: {0} ms", _stopWatchMusicBrainz.ElapsedMilliseconds);
+ _stopWatchMusicBrainz.Restart();
+
+ using var request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
+
+ // MusicBrainz request a contact email address is supplied, as comment, in user agent field:
+ // https://musicbrainz.org/doc/XML_Web_Service/Rate_Limiting#User-Agent .
+ request.Headers.UserAgent.ParseAdd(string.Format(
+ CultureInfo.InvariantCulture,
+ "{0} ( {1} )",
+ _appHost.ApplicationUserAgent,
+ _appHost.ApplicationUserAgentAddress));
+
+ response = await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(request).ConfigureAwait(false);
+
+ // We retry a finite number of times, and only whilst MB is indicating 503 (throttling).
+ }
+ while (attempts < MusicBrainzQueryAttempts && response.StatusCode == HttpStatusCode.ServiceUnavailable);
+
+ // Log error if unable to query MB database due to throttling.
+ if (attempts == MusicBrainzQueryAttempts && response.StatusCode == HttpStatusCode.ServiceUnavailable)
+ {
+ _logger.LogError("GetMusicBrainzResponse: 503 Service Unavailable (throttled) response received {0} times whilst requesting {1}", attempts, requestUrl);
}
- // Write time since last request to debug log as evidence we're meeting rate limit
- // requirement, before resetting stopwatch back to zero.
- _logger.LogDebug("GetMusicBrainzResponse: Time since previous request: {0} ms", _stopWatchMusicBrainz.ElapsedMilliseconds);
- _stopWatchMusicBrainz.Restart();
-
- response = await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options).ConfigureAwait(false);
-
- // We retry a finite number of times, and only whilst MB is indicating 503 (throttling)
+ return response;
}
- while (attempts < MusicBrainzQueryAttempts && response.StatusCode == HttpStatusCode.ServiceUnavailable);
-
- // Log error if unable to query MB database due to throttling
- if (attempts == MusicBrainzQueryAttempts && response.StatusCode == HttpStatusCode.ServiceUnavailable)
+ finally
{
- _logger.LogError("GetMusicBrainzResponse: 503 Service Unavailable (throttled) response received {0} times whilst requesting {1}", attempts, options.RequestUri);
+ _apiRequestLock.Release();
}
-
- return response;
}
///
diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs
index 705359d2c7..43d8af75f0 100644
--- a/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs
@@ -133,7 +133,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb
var url = OmdbProvider.GetOmdbUrl(urlQuery);
using var response = await OmdbProvider.GetOmdbResponse(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
var resultList = new List();
if (isSearch)
diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs
index 32dab60a6b..6af52b591c 100644
--- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs
@@ -298,7 +298,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb
imdbParam));
using var response = await GetOmdbResponse(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
var rootObject = await _jsonSerializer.DeserializeFromStreamAsync(stream).ConfigureAwait(false);
Directory.CreateDirectory(Path.GetDirectoryName(path));
_jsonSerializer.SerializeToFile(rootObject, path);
@@ -336,7 +336,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb
seasonId));
using var response = await GetOmdbResponse(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
var rootObject = await _jsonSerializer.DeserializeFromStreamAsync(stream).ConfigureAwait(false);
Directory.CreateDirectory(Path.GetDirectoryName(path));
_jsonSerializer.SerializeToFile(rootObject, path);
@@ -391,7 +391,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb
item.Genres = Array.Empty();
foreach (var genre in result.Genre
- .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
+ .Split(',', StringSplitOptions.RemoveEmptyEntries)
.Select(i => i.Trim())
.Where(i => !string.IsNullOrWhiteSpace(i)))
{
diff --git a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbClientManager.cs b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbClientManager.cs
index f22d484abc..ce0dab701d 100644
--- a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbClientManager.cs
+++ b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbClientManager.cs
@@ -80,32 +80,6 @@ namespace MediaBrowser.Providers.Plugins.TheTvdb
return TryGetValue(cacheKey, language, () => TvDbClient.Episodes.GetAsync(episodeTvdbId, cancellationToken));
}
- public async Task> GetAllEpisodesAsync(int tvdbId, string language,
- CancellationToken cancellationToken)
- {
- // Traverse all episode pages and join them together
- var episodes = new List();
- var episodePage = await GetEpisodesPageAsync(tvdbId, new EpisodeQuery(), language, cancellationToken)
- .ConfigureAwait(false);
- episodes.AddRange(episodePage.Data);
- if (!episodePage.Links.Next.HasValue || !episodePage.Links.Last.HasValue)
- {
- return episodes;
- }
-
- int next = episodePage.Links.Next.Value;
- int last = episodePage.Links.Last.Value;
-
- for (var page = next; page <= last; ++page)
- {
- episodePage = await GetEpisodesPageAsync(tvdbId, page, new EpisodeQuery(), language, cancellationToken)
- .ConfigureAwait(false);
- episodes.AddRange(episodePage.Data);
- }
-
- return episodes;
- }
-
public Task> GetSeriesByImdbIdAsync(
string imdbId,
string language,
@@ -176,7 +150,8 @@ namespace MediaBrowser.Providers.Plugins.TheTvdb
string language,
CancellationToken cancellationToken)
{
- searchInfo.SeriesProviderIds.TryGetValue(nameof(MetadataProvider.Tvdb),
+ searchInfo.SeriesProviderIds.TryGetValue(
+ nameof(MetadataProvider.Tvdb),
out var seriesTvdbId);
var episodeQuery = new EpisodeQuery();
diff --git a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbEpisodeImageProvider.cs b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbEpisodeImageProvider.cs
index de2f6875f8..50a876d6c5 100644
--- a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbEpisodeImageProvider.cs
+++ b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbEpisodeImageProvider.cs
@@ -57,21 +57,28 @@ namespace MediaBrowser.Providers.Plugins.TheTvdb
// Process images
try
{
- var episodeInfo = new EpisodeInfo
+ string episodeTvdbId = null;
+
+ if (episode.IndexNumber.HasValue && episode.ParentIndexNumber.HasValue)
{
- IndexNumber = episode.IndexNumber.Value,
- ParentIndexNumber = episode.ParentIndexNumber.Value,
- SeriesProviderIds = series.ProviderIds,
- SeriesDisplayOrder = series.DisplayOrder
- };
- string episodeTvdbId = await _tvdbClientManager
- .GetEpisodeTvdbId(episodeInfo, language, cancellationToken).ConfigureAwait(false);
+ var episodeInfo = new EpisodeInfo
+ {
+ IndexNumber = episode.IndexNumber.Value,
+ ParentIndexNumber = episode.ParentIndexNumber.Value,
+ SeriesProviderIds = series.ProviderIds,
+ SeriesDisplayOrder = series.DisplayOrder
+ };
+
+ episodeTvdbId = await _tvdbClientManager
+ .GetEpisodeTvdbId(episodeInfo, language, cancellationToken).ConfigureAwait(false);
+ }
+
if (string.IsNullOrEmpty(episodeTvdbId))
{
_logger.LogError(
"Episode {SeasonNumber}x{EpisodeNumber} not found for series {SeriesTvdbId}",
- episodeInfo.ParentIndexNumber,
- episodeInfo.IndexNumber,
+ episode.ParentIndexNumber,
+ episode.IndexNumber,
series.GetProviderId(MetadataProvider.Tvdb));
return imageResult;
}
diff --git a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbEpisodeProvider.cs b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbEpisodeProvider.cs
index 5fa8a3e1ca..fd72ea4a81 100644
--- a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbEpisodeProvider.cs
+++ b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbEpisodeProvider.cs
@@ -106,7 +106,8 @@ namespace MediaBrowser.Providers.Plugins.TheTvdb
.ConfigureAwait(false);
if (string.IsNullOrEmpty(episodeTvdbId))
{
- _logger.LogError("Episode {SeasonNumber}x{EpisodeNumber} not found for series {SeriesTvdbId}",
+ _logger.LogError(
+ "Episode {SeasonNumber}x{EpisodeNumber} not found for series {SeriesTvdbId}",
searchInfo.ParentIndexNumber, searchInfo.IndexNumber, seriesTvdbId);
return result;
}
diff --git a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbPersonImageProvider.cs b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbPersonImageProvider.cs
index dc3c60dee0..a5cd425f6d 100644
--- a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbPersonImageProvider.cs
+++ b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbPersonImageProvider.cs
@@ -54,7 +54,7 @@ namespace MediaBrowser.Providers.Plugins.TheTvdb
{
var seriesWithPerson = _libraryManager.GetItemList(new InternalItemsQuery
{
- IncludeItemTypes = new[] { typeof(Series).Name },
+ IncludeItemTypes = new[] { nameof(Series) },
PersonIds = new[] { item.Id },
DtoOptions = new DtoOptions(false)
{
diff --git a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeriesProvider.cs b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeriesProvider.cs
index ca9b1d738f..e5a3e9a6a3 100644
--- a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeriesProvider.cs
+++ b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeriesProvider.cs
@@ -2,6 +2,7 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Text;
@@ -123,7 +124,7 @@ namespace MediaBrowser.Providers.Plugins.TheTvdb
await _tvdbClientManager
.GetSeriesByIdAsync(Convert.ToInt32(tvdbId), metadataLanguage, cancellationToken)
.ConfigureAwait(false);
- MapSeriesToResult(result, seriesResult.Data, metadataLanguage);
+ await MapSeriesToResult(result, seriesResult.Data, metadataLanguage).ConfigureAwait(false);
}
catch (TvDbServerException e)
{
@@ -169,7 +170,7 @@ namespace MediaBrowser.Providers.Plugins.TheTvdb
_logger.LogError(e, "Failed to retrieve series with remote id {RemoteId}", id);
}
- return result?.Data.First().Id.ToString();
+ return result?.Data[0].Id.ToString(CultureInfo.InvariantCulture);
}
///
@@ -297,7 +298,7 @@ namespace MediaBrowser.Providers.Plugins.TheTvdb
return name.Trim();
}
- private void MapSeriesToResult(MetadataResult result, TvDbSharper.Dto.Series tvdbSeries, string metadataLanguage)
+ private async Task MapSeriesToResult(MetadataResult result, TvDbSharper.Dto.Series tvdbSeries, string metadataLanguage)
{
Series series = result.Item;
series.SetProviderId(MetadataProvider.Tvdb, tvdbSeries.Id.ToString());
@@ -340,20 +341,21 @@ namespace MediaBrowser.Providers.Plugins.TheTvdb
{
try
{
- var episodeSummary = _tvdbClientManager
- .GetSeriesEpisodeSummaryAsync(tvdbSeries.Id, metadataLanguage, CancellationToken.None).Result.Data;
- var maxSeasonNumber = episodeSummary.AiredSeasons.Select(s => Convert.ToInt32(s)).Max();
- var episodeQuery = new EpisodeQuery
+ var episodeSummary = await _tvdbClientManager.GetSeriesEpisodeSummaryAsync(tvdbSeries.Id, metadataLanguage, CancellationToken.None).ConfigureAwait(false);
+
+ if (episodeSummary.Data.AiredSeasons.Length != 0)
{
- AiredSeason = maxSeasonNumber
- };
- var episodesPage =
- _tvdbClientManager.GetEpisodesPageAsync(tvdbSeries.Id, episodeQuery, metadataLanguage, CancellationToken.None).Result.Data;
- result.Item.EndDate = episodesPage.Select(e =>
+ var maxSeasonNumber = episodeSummary.Data.AiredSeasons.Max(s => Convert.ToInt32(s, CultureInfo.InvariantCulture));
+ var episodeQuery = new EpisodeQuery
{
- DateTime.TryParse(e.FirstAired, out var firstAired);
- return firstAired;
- }).Max();
+ AiredSeason = maxSeasonNumber
+ };
+ var episodesPage = await _tvdbClientManager.GetEpisodesPageAsync(tvdbSeries.Id, episodeQuery, metadataLanguage, CancellationToken.None).ConfigureAwait(false);
+
+ result.Item.EndDate = episodesPage.Data
+ .Select(e => DateTime.TryParse(e.FirstAired, out var firstAired) ? firstAired : (DateTime?)null)
+ .Max();
+ }
}
catch (TvDbServerException e)
{
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetImageProvider.cs
index f6592afe46..df1e12240d 100644
--- a/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetImageProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetImageProvider.cs
@@ -2,6 +2,7 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Threading;
@@ -12,25 +13,25 @@ using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.Collections;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.General;
-using MediaBrowser.Providers.Plugins.Tmdb.Movies;
namespace MediaBrowser.Providers.Plugins.Tmdb.BoxSets
{
public class TmdbBoxSetImageProvider : IRemoteImageProvider, IHasOrder
{
private readonly IHttpClientFactory _httpClientFactory;
+ private readonly TmdbClientManager _tmdbClientManager;
- public TmdbBoxSetImageProvider(IHttpClientFactory httpClientFactory)
+ public TmdbBoxSetImageProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
{
_httpClientFactory = httpClientFactory;
+ _tmdbClientManager = tmdbClientManager;
}
- public string Name => ProviderName;
+ public string Name => TmdbUtils.ProviderName;
- public static string ProviderName => TmdbUtils.ProviderName;
+ public int Order => 0;
public bool Supports(BaseItem item)
{
@@ -48,112 +49,60 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.BoxSets
public async Task> GetImages(BaseItem item, CancellationToken cancellationToken)
{
- var tmdbId = item.GetProviderId(MetadataProvider.Tmdb);
+ var tmdbId = Convert.ToInt32(item.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
- if (!string.IsNullOrEmpty(tmdbId))
+ if (tmdbId <= 0)
{
- var language = item.GetPreferredMetadataLanguage();
-
- var mainResult = await TmdbBoxSetProvider.Current.GetMovieDbResult(tmdbId, null, cancellationToken).ConfigureAwait(false);
-
- if (mainResult != null)
- {
- var tmdbSettings = await TmdbMovieProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- return GetImages(mainResult, language, tmdbImageUrl);
- }
+ return Enumerable.Empty();
}
- return new List();
- }
+ var language = item.GetPreferredMetadataLanguage();
- private IEnumerable GetImages(CollectionResult obj, string language, string baseUrl)
- {
- var list = new List();
+ var collection = await _tmdbClientManager.GetCollectionAsync(tmdbId, language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken).ConfigureAwait(false);
- var images = obj.Images ?? new CollectionImages();
-
- list.AddRange(GetPosters(images).Select(i => new RemoteImageInfo
+ if (collection?.Images == null)
{
- Url = baseUrl + i.File_Path,
- CommunityRating = i.Vote_Average,
- VoteCount = i.Vote_Count,
- Width = i.Width,
- Height = i.Height,
- Language = TmdbMovieProvider.AdjustImageLanguage(i.Iso_639_1, language),
- ProviderName = Name,
- Type = ImageType.Primary,
- RatingType = RatingType.Score
- }));
+ return Enumerable.Empty();
+ }
- list.AddRange(GetBackdrops(images).Select(i => new RemoteImageInfo
+ var remoteImages = new List();
+
+ for (var i = 0; i < collection.Images.Posters.Count; i++)
{
- Url = baseUrl + i.File_Path,
- CommunityRating = i.Vote_Average,
- VoteCount = i.Vote_Count,
- Width = i.Width,
- Height = i.Height,
- ProviderName = Name,
- Type = ImageType.Backdrop,
- RatingType = RatingType.Score
- }));
+ var poster = collection.Images.Posters[i];
+ remoteImages.Add(new RemoteImageInfo
+ {
+ Url = _tmdbClientManager.GetPosterUrl(poster.FilePath),
+ CommunityRating = poster.VoteAverage,
+ VoteCount = poster.VoteCount,
+ Width = poster.Width,
+ Height = poster.Height,
+ Language = TmdbUtils.AdjustImageLanguage(poster.Iso_639_1, language),
+ ProviderName = Name,
+ Type = ImageType.Primary,
+ RatingType = RatingType.Score
+ });
+ }
- var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
-
- return list.OrderByDescending(i =>
+ for (var i = 0; i < collection.Images.Backdrops.Count; i++)
{
- if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
+ var backdrop = collection.Images.Backdrops[i];
+ remoteImages.Add(new RemoteImageInfo
{
- return 3;
- }
+ Url = _tmdbClientManager.GetBackdropUrl(backdrop.FilePath),
+ CommunityRating = backdrop.VoteAverage,
+ VoteCount = backdrop.VoteCount,
+ Width = backdrop.Width,
+ Height = backdrop.Height,
+ ProviderName = Name,
+ Type = ImageType.Backdrop,
+ RatingType = RatingType.Score
+ });
+ }
- if (!isLanguageEn)
- {
- if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 2;
- }
- }
-
- if (string.IsNullOrEmpty(i.Language))
- {
- return isLanguageEn ? 3 : 2;
- }
-
- return 0;
- })
- .ThenByDescending(i => i.CommunityRating ?? 0)
- .ThenByDescending(i => i.VoteCount ?? 0);
+ return remoteImages.OrderByLanguageDescending(language);
}
- ///
- /// Gets the posters.
- ///
- /// The images.
- /// IEnumerable{MovieDbProvider.Poster}.
- private IEnumerable GetPosters(CollectionImages images)
- {
- return images.Posters ?? new List();
- }
-
- ///
- /// Gets the backdrops.
- ///
- /// The images.
- /// IEnumerable{MovieDbProvider.Backdrop}.
- private IEnumerable GetBackdrops(CollectionImages images)
- {
- var eligibleBackdrops = images.Backdrops == null ? new List() :
- images.Backdrops;
-
- return eligibleBackdrops.OrderByDescending(i => i.Vote_Average)
- .ThenByDescending(i => i.Vote_Count);
- }
-
- public int Order => 0;
-
public Task GetImageResponse(string url, CancellationToken cancellationToken)
{
return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetProvider.cs
index e7328b5535..fcd8e614c1 100644
--- a/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetProvider.cs
@@ -3,270 +3,118 @@
using System;
using System.Collections.Generic;
using System.Globalization;
-using System.IO;
using System.Linq;
using System.Net.Http;
-using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.Movies;
-using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.Collections;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.General;
-using MediaBrowser.Providers.Plugins.Tmdb.Movies;
-using Microsoft.Extensions.Logging;
namespace MediaBrowser.Providers.Plugins.Tmdb.BoxSets
{
public class TmdbBoxSetProvider : IRemoteMetadataProvider
{
- private const string GetCollectionInfo3 = TmdbUtils.BaseTmdbApiUrl + @"3/collection/{0}?api_key={1}&append_to_response=images";
-
- internal static TmdbBoxSetProvider Current;
-
- private readonly ILogger _logger;
- private readonly IJsonSerializer _json;
- private readonly IServerConfigurationManager _config;
- private readonly IFileSystem _fileSystem;
private readonly IHttpClientFactory _httpClientFactory;
- private readonly ILibraryManager _libraryManager;
+ private readonly TmdbClientManager _tmdbClientManager;
- public TmdbBoxSetProvider(
- ILogger logger,
- IJsonSerializer json,
- IServerConfigurationManager config,
- IFileSystem fileSystem,
- IHttpClientFactory httpClientFactory,
- ILibraryManager libraryManager)
+ public TmdbBoxSetProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
{
- _logger = logger;
- _json = json;
- _config = config;
- _fileSystem = fileSystem;
_httpClientFactory = httpClientFactory;
- _libraryManager = libraryManager;
- Current = this;
+ _tmdbClientManager = tmdbClientManager;
}
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
+ public string Name => TmdbUtils.ProviderName;
public async Task> GetSearchResults(BoxSetInfo searchInfo, CancellationToken cancellationToken)
{
- var tmdbId = searchInfo.GetProviderId(MetadataProvider.Tmdb);
+ var tmdbId = Convert.ToInt32(searchInfo.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
+ var language = searchInfo.MetadataLanguage;
- if (!string.IsNullOrEmpty(tmdbId))
+ if (tmdbId > 0)
{
- await EnsureInfo(tmdbId, searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false);
+ var collection = await _tmdbClientManager.GetCollectionAsync(tmdbId, language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken).ConfigureAwait(false);
- var dataFilePath = GetDataFilePath(_config.ApplicationPaths, tmdbId, searchInfo.MetadataLanguage);
- var info = _json.DeserializeFromFile(dataFilePath);
-
- var images = (info.Images ?? new CollectionImages()).Posters ?? new List();
-
- var tmdbSettings = await TmdbMovieProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
+ if (collection == null)
+ {
+ return Enumerable.Empty();
+ }
var result = new RemoteSearchResult
{
- Name = info.Name,
- SearchProviderName = Name,
- ImageUrl = images.Count == 0 ? null : (tmdbImageUrl + images[0].File_Path)
+ Name = collection.Name,
+ SearchProviderName = Name
};
- result.SetProviderId(MetadataProvider.Tmdb, info.Id.ToString(_usCulture));
+ if (collection.Images != null)
+ {
+ result.ImageUrl = _tmdbClientManager.GetPosterUrl(collection.PosterPath);
+ }
+
+ result.SetProviderId(MetadataProvider.Tmdb, collection.Id.ToString(CultureInfo.InvariantCulture));
return new[] { result };
}
- return await new TmdbSearch(_logger, _json, _libraryManager).GetSearchResults(searchInfo, cancellationToken).ConfigureAwait(false);
+ var collectionSearchResults = await _tmdbClientManager.SearchCollectionAsync(searchInfo.Name, language, cancellationToken).ConfigureAwait(false);
+
+ var collections = new List();
+ for (var i = 0; i < collectionSearchResults.Count; i++)
+ {
+ var collection = new RemoteSearchResult
+ {
+ Name = collectionSearchResults[i].Name,
+ SearchProviderName = Name
+ };
+ collection.SetProviderId(MetadataProvider.Tmdb, collectionSearchResults[i].Id.ToString(CultureInfo.InvariantCulture));
+
+ collections.Add(collection);
+ }
+
+ return collections;
}
public async Task> GetMetadata(BoxSetInfo id, CancellationToken cancellationToken)
{
- var tmdbId = id.GetProviderId(MetadataProvider.Tmdb);
-
+ var tmdbId = Convert.ToInt32(id.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
+ var language = id.MetadataLanguage;
// We don't already have an Id, need to fetch it
- if (string.IsNullOrEmpty(tmdbId))
+ if (tmdbId <= 0)
{
- var searchResults = await new TmdbSearch(_logger, _json, _libraryManager).GetSearchResults(id, cancellationToken).ConfigureAwait(false);
+ var searchResults = await _tmdbClientManager.SearchCollectionAsync(id.Name, language, cancellationToken).ConfigureAwait(false);
- var searchResult = searchResults.FirstOrDefault();
-
- if (searchResult != null)
+ if (searchResults != null && searchResults.Count > 0)
{
- tmdbId = searchResult.GetProviderId(MetadataProvider.Tmdb);
+ tmdbId = searchResults[0].Id;
}
}
var result = new MetadataResult();
- if (!string.IsNullOrEmpty(tmdbId))
+ if (tmdbId > 0)
{
- var mainResult = await GetMovieDbResult(tmdbId, id.MetadataLanguage, cancellationToken).ConfigureAwait(false);
+ var collection = await _tmdbClientManager.GetCollectionAsync(tmdbId, language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken).ConfigureAwait(false);
- if (mainResult != null)
+ if (collection != null)
{
+ var item = new BoxSet
+ {
+ Name = collection.Name,
+ Overview = collection.Overview
+ };
+
+ item.SetProviderId(MetadataProvider.Tmdb, collection.Id.ToString(CultureInfo.InvariantCulture));
+
result.HasMetadata = true;
- result.Item = GetItem(mainResult);
+ result.Item = item;
}
}
return result;
}
- internal async Task GetMovieDbResult(string tmdbId, string language, CancellationToken cancellationToken)
- {
- if (string.IsNullOrEmpty(tmdbId))
- {
- throw new ArgumentNullException(nameof(tmdbId));
- }
-
- await EnsureInfo(tmdbId, language, cancellationToken).ConfigureAwait(false);
-
- var dataFilePath = GetDataFilePath(_config.ApplicationPaths, tmdbId, language);
-
- if (!string.IsNullOrEmpty(dataFilePath))
- {
- return _json.DeserializeFromFile(dataFilePath);
- }
-
- return null;
- }
-
- private BoxSet GetItem(CollectionResult obj)
- {
- var item = new BoxSet
- {
- Name = obj.Name,
- Overview = obj.Overview
- };
-
- item.SetProviderId(MetadataProvider.Tmdb, obj.Id.ToString(_usCulture));
-
- return item;
- }
-
- private async Task DownloadInfo(string tmdbId, string preferredMetadataLanguage, CancellationToken cancellationToken)
- {
- var mainResult = await FetchMainResult(tmdbId, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
-
- if (mainResult == null)
- {
- return;
- }
-
- var dataFilePath = GetDataFilePath(_config.ApplicationPaths, tmdbId, preferredMetadataLanguage);
-
- Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
-
- _json.SerializeToFile(mainResult, dataFilePath);
- }
-
- private async Task FetchMainResult(string id, string language, CancellationToken cancellationToken)
- {
- var url = string.Format(CultureInfo.InvariantCulture, GetCollectionInfo3, id, TmdbUtils.ApiKey);
-
- if (!string.IsNullOrEmpty(language))
- {
- url += string.Format(CultureInfo.InvariantCulture, "&language={0}", TmdbMovieProvider.NormalizeLanguage(language));
-
- // Get images in english and with no language
- url += "&include_image_language=" + TmdbMovieProvider.GetImageLanguagesParam(language);
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- using var requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
- foreach (var header in TmdbUtils.AcceptHeaders)
- {
- requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(header));
- }
-
- using var mainResponse = await TmdbMovieProvider.Current.GetMovieDbResponse(requestMessage, cancellationToken).ConfigureAwait(false);
- await using var stream = await mainResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
- var mainResult = await _json.DeserializeFromStreamAsync(stream).ConfigureAwait(false);
-
- cancellationToken.ThrowIfCancellationRequested();
-
- if (mainResult != null && string.IsNullOrEmpty(mainResult.Name))
- {
- if (!string.IsNullOrEmpty(language) && !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
- {
- url = string.Format(CultureInfo.InvariantCulture, GetCollectionInfo3, id, TmdbUtils.ApiKey) + "&language=en";
-
- if (!string.IsNullOrEmpty(language))
- {
- // Get images in english and with no language
- url += "&include_image_language=" + TmdbMovieProvider.GetImageLanguagesParam(language);
- }
-
- using var langRequestMessage = new HttpRequestMessage(HttpMethod.Get, url);
- foreach (var header in TmdbUtils.AcceptHeaders)
- {
- langRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(header));
- }
-
- await using var langStream = await mainResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
- mainResult = await _json.DeserializeFromStreamAsync(langStream).ConfigureAwait(false);
- }
- }
-
- return mainResult;
- }
-
- internal Task EnsureInfo(string tmdbId, string preferredMetadataLanguage, CancellationToken cancellationToken)
- {
- var path = GetDataFilePath(_config.ApplicationPaths, tmdbId, preferredMetadataLanguage);
-
- var fileInfo = _fileSystem.GetFileSystemInfo(path);
-
- if (fileInfo.Exists)
- {
- // If it's recent or automatic updates are enabled, don't re-download
- if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
- {
- return Task.CompletedTask;
- }
- }
-
- return DownloadInfo(tmdbId, preferredMetadataLanguage, cancellationToken);
- }
-
- public string Name => TmdbUtils.ProviderName;
-
- private static string GetDataFilePath(IApplicationPaths appPaths, string tmdbId, string preferredLanguage)
- {
- var path = GetDataPath(appPaths, tmdbId);
-
- var filename = string.Format(CultureInfo.InvariantCulture, "all-{0}.json", preferredLanguage ?? string.Empty);
-
- return Path.Combine(path, filename);
- }
-
- private static string GetDataPath(IApplicationPaths appPaths, string tmdbId)
- {
- var dataPath = GetCollectionsDataPath(appPaths);
-
- return Path.Combine(dataPath, tmdbId);
- }
-
- private static string GetCollectionsDataPath(IApplicationPaths appPaths)
- {
- var dataPath = Path.Combine(appPaths.CachePath, "tmdb-collections");
-
- return dataPath;
- }
-
public Task GetImageResponse(string url, CancellationToken cancellationToken)
{
return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Models/Collections/CollectionImages.cs b/MediaBrowser.Providers/Plugins/Tmdb/Models/Collections/CollectionImages.cs
deleted file mode 100644
index 0a8994d540..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Models/Collections/CollectionImages.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-#pragma warning disable CS1591
-
-using System.Collections.Generic;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.General;
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Models.Collections
-{
- public class CollectionImages
- {
- public List Backdrops { get; set; }
-
- public List Posters { get; set; }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Models/Collections/CollectionResult.cs b/MediaBrowser.Providers/Plugins/Tmdb/Models/Collections/CollectionResult.cs
deleted file mode 100644
index c6b851c237..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Models/Collections/CollectionResult.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-#pragma warning disable CS1591
-
-using System.Collections.Generic;
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Models.Collections
-{
- public class CollectionResult
- {
- public int Id { get; set; }
-
- public string Name { get; set; }
-
- public string Overview { get; set; }
-
- public string Poster_Path { get; set; }
-
- public string Backdrop_Path { get; set; }
-
- public List Parts { get; set; }
-
- public CollectionImages Images { get; set; }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Models/Collections/Part.cs b/MediaBrowser.Providers/Plugins/Tmdb/Models/Collections/Part.cs
deleted file mode 100644
index a48124b3e1..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Models/Collections/Part.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-#pragma warning disable CS1591
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Models.Collections
-{
- public class Part
- {
- public string Title { get; set; }
-
- public int Id { get; set; }
-
- public string Release_Date { get; set; }
-
- public string Poster_Path { get; set; }
-
- public string Backdrop_Path { get; set; }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Backdrop.cs b/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Backdrop.cs
deleted file mode 100644
index 5b7627f6e8..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Backdrop.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-#pragma warning disable CS1591
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Models.General
-{
- public class Backdrop
- {
- public double Aspect_Ratio { get; set; }
-
- public string File_Path { get; set; }
-
- public int Height { get; set; }
-
- public string Iso_639_1 { get; set; }
-
- public double Vote_Average { get; set; }
-
- public int Vote_Count { get; set; }
-
- public int Width { get; set; }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Crew.cs b/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Crew.cs
deleted file mode 100644
index 339ecb6285..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Crew.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-#pragma warning disable CS1591
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Models.General
-{
- public class Crew
- {
- public int Id { get; set; }
-
- public string Credit_Id { get; set; }
-
- public string Name { get; set; }
-
- public string Department { get; set; }
-
- public string Job { get; set; }
-
- public string Profile_Path { get; set; }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/ExternalIds.cs b/MediaBrowser.Providers/Plugins/Tmdb/Models/General/ExternalIds.cs
deleted file mode 100644
index aac4420e8b..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/ExternalIds.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-#pragma warning disable CS1591
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Models.General
-{
- public class ExternalIds
- {
- public string Imdb_Id { get; set; }
-
- public object Freebase_Id { get; set; }
-
- public string Freebase_Mid { get; set; }
-
- public int? Tvdb_Id { get; set; }
-
- public int? Tvrage_Id { get; set; }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Genre.cs b/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Genre.cs
deleted file mode 100644
index 9ba1c15c65..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Genre.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-#pragma warning disable CS1591
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Models.General
-{
- public class Genre
- {
- public int Id { get; set; }
-
- public string Name { get; set; }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Images.cs b/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Images.cs
deleted file mode 100644
index 0538cf174d..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Images.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-#pragma warning disable CS1591
-
-using System.Collections.Generic;
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Models.General
-{
- public class Images
- {
- public List Backdrops { get; set; }
-
- public List Posters { get; set; }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Keyword.cs b/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Keyword.cs
deleted file mode 100644
index fff86931be..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Keyword.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-#pragma warning disable CS1591
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Models.General
-{
- public class Keyword
- {
- public int Id { get; set; }
-
- public string Name { get; set; }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Keywords.cs b/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Keywords.cs
deleted file mode 100644
index 235ecb5682..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Keywords.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-#pragma warning disable CS1591
-
-using System.Collections.Generic;
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Models.General
-{
- public class Keywords
- {
- public List Results { get; set; }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Poster.cs b/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Poster.cs
deleted file mode 100644
index 4f61e978be..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Poster.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-#pragma warning disable CS1591
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Models.General
-{
- public class Poster
- {
- public double Aspect_Ratio { get; set; }
-
- public string File_Path { get; set; }
-
- public int Height { get; set; }
-
- public string Iso_639_1 { get; set; }
-
- public double Vote_Average { get; set; }
-
- public int Vote_Count { get; set; }
-
- public int Width { get; set; }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Profile.cs b/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Profile.cs
deleted file mode 100644
index 0a1f8843eb..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Profile.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-#pragma warning disable CS1591
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Models.General
-{
- public class Profile
- {
- public string File_Path { get; set; }
-
- public int Width { get; set; }
-
- public int Height { get; set; }
-
- public object Iso_639_1 { get; set; }
-
- public double Aspect_Ratio { get; set; }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Still.cs b/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Still.cs
deleted file mode 100644
index 61de819b93..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Still.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-#pragma warning disable CS1591
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Models.General
-{
- public class Still
- {
- public double Aspect_Ratio { get; set; }
-
- public string File_Path { get; set; }
-
- public int Height { get; set; }
-
- public string Id { get; set; }
-
- public string Iso_639_1 { get; set; }
-
- public double Vote_Average { get; set; }
-
- public int Vote_Count { get; set; }
-
- public int Width { get; set; }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/StillImages.cs b/MediaBrowser.Providers/Plugins/Tmdb/Models/General/StillImages.cs
deleted file mode 100644
index 59ab18b7bf..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/StillImages.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-#pragma warning disable CS1591
-
-using System.Collections.Generic;
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Models.General
-{
- public class StillImages
- {
- public List Stills { get; set; }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Video.cs b/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Video.cs
deleted file mode 100644
index ebd5c7acee..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Video.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-#pragma warning disable CS1591
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Models.General
-{
- public class Video
- {
- public string Id { get; set; }
-
- public string Iso_639_1 { get; set; }
-
- public string Iso_3166_1 { get; set; }
-
- public string Key { get; set; }
-
- public string Name { get; set; }
-
- public string Site { get; set; }
-
- public string Size { get; set; }
-
- public string Type { get; set; }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Videos.cs b/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Videos.cs
deleted file mode 100644
index 1c673fdbd6..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Models/General/Videos.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-#pragma warning disable CS1591
-
-using System.Collections.Generic;
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Models.General
-{
- public class Videos
- {
- public IReadOnlyList
public class TmdbMovieProvider : IRemoteMetadataProvider, IHasOrder
{
- private const string TmdbConfigUrl = TmdbUtils.BaseTmdbApiUrl + "3/configuration?api_key={0}";
- private const string GetMovieInfo3 = TmdbUtils.BaseTmdbApiUrl + @"3/movie/{0}?api_key={1}&append_to_response=casts,releases,images,keywords,trailers";
-
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- private readonly IJsonSerializer _jsonSerializer;
private readonly IHttpClientFactory _httpClientFactory;
- private readonly IFileSystem _fileSystem;
- private readonly IServerConfigurationManager _configurationManager;
- private readonly ILogger _logger;
private readonly ILibraryManager _libraryManager;
- private readonly IApplicationHost _appHost;
-
- ///
- /// The _TMDB settings task.
- ///
- private TmdbSettingsResult _tmdbSettings;
+ private readonly TmdbClientManager _tmdbClientManager;
public TmdbMovieProvider(
- IJsonSerializer jsonSerializer,
- IHttpClientFactory httpClientFactory,
- IFileSystem fileSystem,
- IServerConfigurationManager configurationManager,
- ILogger logger,
ILibraryManager libraryManager,
- IApplicationHost appHost)
+ TmdbClientManager tmdbClientManager,
+ IHttpClientFactory httpClientFactory)
{
- _jsonSerializer = jsonSerializer;
- _httpClientFactory = httpClientFactory;
- _fileSystem = fileSystem;
- _configurationManager = configurationManager;
- _logger = logger;
_libraryManager = libraryManager;
- _appHost = appHost;
- Current = this;
+ _tmdbClientManager = tmdbClientManager;
+ _httpClientFactory = httpClientFactory;
}
- internal static TmdbMovieProvider Current { get; private set; }
-
- ///
public string Name => TmdbUtils.ProviderName;
///
public int Order => 1;
- public Task> GetSearchResults(MovieInfo searchInfo, CancellationToken cancellationToken)
+ public async Task> GetSearchResults(MovieInfo searchInfo, CancellationToken cancellationToken)
{
- return GetMovieSearchResults(searchInfo, cancellationToken);
+ var tmdbId = Convert.ToInt32(searchInfo.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
+
+ if (tmdbId == 0)
+ {
+ var movieResults = await _tmdbClientManager
+ .SearchMovieAsync(searchInfo.Name, searchInfo.MetadataLanguage, cancellationToken)
+ .ConfigureAwait(false);
+ var remoteSearchResults = new List();
+ for (var i = 0; i < movieResults.Count; i++)
+ {
+ var movieResult = movieResults[i];
+ var remoteSearchResult = new RemoteSearchResult
+ {
+ Name = movieResult.Title ?? movieResult.OriginalTitle,
+ ImageUrl = _tmdbClientManager.GetPosterUrl(movieResult.PosterPath),
+ Overview = movieResult.Overview,
+ SearchProviderName = Name
+ };
+
+ var releaseDate = movieResult.ReleaseDate?.ToUniversalTime();
+ remoteSearchResult.PremiereDate = releaseDate;
+ remoteSearchResult.ProductionYear = releaseDate?.Year;
+
+ remoteSearchResult.SetProviderId(MetadataProvider.Tmdb, movieResult.Id.ToString(CultureInfo.InvariantCulture));
+ remoteSearchResults.Add(remoteSearchResult);
+ }
+
+ return remoteSearchResults;
+ }
+
+ var movie = await _tmdbClientManager
+ .GetMovieAsync(tmdbId, searchInfo.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(searchInfo.MetadataLanguage), cancellationToken)
+ .ConfigureAwait(false);
+
+ var remoteResult = new RemoteSearchResult
+ {
+ Name = movie.Title ?? movie.OriginalTitle,
+ SearchProviderName = Name,
+ ImageUrl = _tmdbClientManager.GetPosterUrl(movie.PosterPath),
+ Overview = movie.Overview
+ };
+
+ if (movie.ReleaseDate != null)
+ {
+ var releaseDate = movie.ReleaseDate.Value.ToUniversalTime();
+ remoteResult.PremiereDate = releaseDate;
+ remoteResult.ProductionYear = releaseDate.Year;
+ }
+
+ remoteResult.SetProviderId(MetadataProvider.Tmdb, movie.Id.ToString(CultureInfo.InvariantCulture));
+
+ if (!string.IsNullOrWhiteSpace(movie.ImdbId))
+ {
+ remoteResult.SetProviderId(MetadataProvider.Imdb, movie.ImdbId);
+ }
+
+ return new[] { remoteResult };
}
- public async Task> GetMovieSearchResults(ItemLookupInfo searchInfo, CancellationToken cancellationToken)
+ public async Task> GetMetadata(MovieInfo info, CancellationToken cancellationToken)
{
- var tmdbId = searchInfo.GetProviderId(MetadataProvider.Tmdb);
+ var tmdbId = info.GetProviderId(MetadataProvider.Tmdb);
+ var imdbId = info.GetProviderId(MetadataProvider.Imdb);
- if (!string.IsNullOrEmpty(tmdbId))
+ if (string.IsNullOrEmpty(tmdbId) && string.IsNullOrEmpty(imdbId))
{
- cancellationToken.ThrowIfCancellationRequested();
+ // ParseName is required here.
+ // Caller provides the filename with extension stripped and NOT the parsed filename
+ var parsedName = _libraryManager.ParseName(info.Name);
+ var searchResults = await _tmdbClientManager.SearchMovieAsync(parsedName.Name, parsedName.Year ?? 0, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);
- await EnsureMovieInfo(tmdbId, searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false);
-
- var dataFilePath = GetDataFilePath(tmdbId, searchInfo.MetadataLanguage);
-
- var obj = _jsonSerializer.DeserializeFromFile(dataFilePath);
-
- var tmdbSettings = await GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- var remoteResult = new RemoteSearchResult
+ if (searchResults.Count > 0)
{
- Name = obj.GetTitle(),
- SearchProviderName = Name,
- ImageUrl = string.IsNullOrWhiteSpace(obj.Poster_Path) ? null : tmdbImageUrl + obj.Poster_Path
+ tmdbId = searchResults[0].Id.ToString(CultureInfo.InvariantCulture);
+ }
+ }
+
+ if (string.IsNullOrEmpty(tmdbId))
+ {
+ return new MetadataResult();
+ }
+
+ var movieResult = await _tmdbClientManager
+ .GetMovieAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken)
+ .ConfigureAwait(false);
+
+ var movie = new Movie
+ {
+ Name = movieResult.Title ?? movieResult.OriginalTitle,
+ Overview = movieResult.Overview?.Replace("\n\n", "\n", StringComparison.InvariantCulture),
+ Tagline = movieResult.Tagline,
+ ProductionLocations = movieResult.ProductionCountries.Select(pc => pc.Name).ToArray()
+ };
+ var metadataResult = new MetadataResult
+ {
+ HasMetadata = true,
+ ResultLanguage = info.MetadataLanguage,
+ Item = movie
+ };
+
+ movie.SetProviderId(MetadataProvider.Tmdb, tmdbId);
+ movie.SetProviderId(MetadataProvider.Imdb, movieResult.ImdbId);
+ if (movieResult.BelongsToCollection != null)
+ {
+ movie.SetProviderId(MetadataProvider.TmdbCollection, movieResult.BelongsToCollection.Id.ToString(CultureInfo.InvariantCulture));
+ movie.CollectionName = movieResult.BelongsToCollection.Name;
+ }
+
+ movie.CommunityRating = Convert.ToSingle(movieResult.VoteAverage);
+
+ if (movieResult.Releases?.Countries != null)
+ {
+ var releases = movieResult.Releases.Countries.Where(i => !string.IsNullOrWhiteSpace(i.Certification)).ToList();
+
+ var ourRelease = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, info.MetadataCountryCode, StringComparison.OrdinalIgnoreCase));
+ var usRelease = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, "US", StringComparison.OrdinalIgnoreCase));
+
+ if (ourRelease != null)
+ {
+ var ratingPrefix = string.Equals(info.MetadataCountryCode, "us", StringComparison.OrdinalIgnoreCase) ? string.Empty : info.MetadataCountryCode + "-";
+ var newRating = ratingPrefix + ourRelease.Certification;
+
+ newRating = newRating.Replace("de-", "FSK-", StringComparison.OrdinalIgnoreCase);
+
+ movie.OfficialRating = newRating;
+ }
+ else if (usRelease != null)
+ {
+ movie.OfficialRating = usRelease.Certification;
+ }
+ }
+
+ movie.PremiereDate = movieResult.ReleaseDate;
+ movie.ProductionYear = movieResult.ReleaseDate?.Year;
+
+ if (movieResult.ProductionCompanies != null)
+ {
+ movie.SetStudios(movieResult.ProductionCompanies.Select(c => c.Name));
+ }
+
+ var genres = movieResult.Genres;
+
+ foreach (var genre in genres.Select(g => g.Name))
+ {
+ movie.AddGenre(genre);
+ }
+
+ if (movieResult.Keywords?.Keywords != null)
+ {
+ for (var i = 0; i < movieResult.Keywords.Keywords.Count; i++)
+ {
+ movie.AddTag(movieResult.Keywords.Keywords[i].Name);
+ }
+ }
+
+ if (movieResult.Credits?.Cast != null)
+ {
+ // TODO configurable
+ foreach (var actor in movieResult.Credits.Cast.OrderBy(a => a.Order).Take(TmdbUtils.MaxCastMembers))
+ {
+ var personInfo = new PersonInfo
+ {
+ Name = actor.Name.Trim(),
+ Role = actor.Character,
+ Type = PersonType.Actor,
+ SortOrder = actor.Order
+ };
+
+ if (!string.IsNullOrWhiteSpace(actor.ProfilePath))
+ {
+ personInfo.ImageUrl = _tmdbClientManager.GetProfileUrl(actor.ProfilePath);
+ }
+
+ if (actor.Id > 0)
+ {
+ personInfo.SetProviderId(MetadataProvider.Tmdb, actor.Id.ToString(CultureInfo.InvariantCulture));
+ }
+
+ metadataResult.AddPerson(personInfo);
+ }
+ }
+
+ if (movieResult.Credits?.Crew != null)
+ {
+ var keepTypes = new[]
+ {
+ PersonType.Director,
+ PersonType.Writer,
+ PersonType.Producer
};
- if (!string.IsNullOrWhiteSpace(obj.Release_Date))
+ foreach (var person in movieResult.Credits.Crew)
{
- // These dates are always in this exact format
- if (DateTime.TryParse(obj.Release_Date, _usCulture, DateTimeStyles.None, out var r))
+ // Normalize this
+ var type = TmdbUtils.MapCrewToPersonType(person);
+
+ if (!keepTypes.Contains(type, StringComparer.OrdinalIgnoreCase) &&
+ !keepTypes.Contains(person.Job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
{
- remoteResult.PremiereDate = r.ToUniversalTime();
- remoteResult.ProductionYear = remoteResult.PremiereDate.Value.Year;
+ continue;
}
+
+ var personInfo = new PersonInfo
+ {
+ Name = person.Name.Trim(),
+ Role = person.Job,
+ Type = type
+ };
+
+ if (!string.IsNullOrWhiteSpace(person.ProfilePath))
+ {
+ personInfo.ImageUrl = _tmdbClientManager.GetPosterUrl(person.ProfilePath);
+ }
+
+ if (person.Id > 0)
+ {
+ personInfo.SetProviderId(MetadataProvider.Tmdb, person.Id.ToString(CultureInfo.InvariantCulture));
+ }
+
+ metadataResult.AddPerson(personInfo);
}
+ }
- remoteResult.SetProviderId(MetadataProvider.Tmdb, obj.Id.ToString(_usCulture));
- if (!string.IsNullOrWhiteSpace(obj.Imdb_Id))
+ if (movieResult.Videos?.Results != null)
+ {
+ var trailers = new List();
+ for (var i = 0; i < movieResult.Videos.Results.Count; i++)
{
- remoteResult.SetProviderId(MetadataProvider.Imdb, obj.Imdb_Id);
+ var video = movieResult.Videos.Results[0];
+ if (!TmdbUtils.IsTrailerType(video))
+ {
+ continue;
+ }
+
+ trailers.Add(new MediaUrl
+ {
+ Url = string.Format(CultureInfo.InvariantCulture, "https://www.youtube.com/watch?v={0}", video.Key),
+ Name = video.Name
+ });
}
- return new[] { remoteResult };
+ movie.RemoteTrailers = trailers;
}
- return await new TmdbSearch(_logger, _jsonSerializer, _libraryManager).GetMovieSearchResults(searchInfo, cancellationToken).ConfigureAwait(false);
- }
-
- public Task> GetMetadata(MovieInfo info, CancellationToken cancellationToken)
- {
- return GetItemMetadata(info, cancellationToken);
- }
-
- public Task> GetItemMetadata(ItemLookupInfo id, CancellationToken cancellationToken)
- where T : BaseItem, new()
- {
- var movieDb = new GenericTmdbMovieInfo(_logger, _jsonSerializer, _libraryManager, _fileSystem);
-
- return movieDb.GetMetadata(id, cancellationToken);
- }
-
- ///
- /// Gets the TMDB settings.
- ///
- /// Task{TmdbSettingsResult}.
- internal async Task GetTmdbSettings(CancellationToken cancellationToken)
- {
- if (_tmdbSettings != null)
- {
- return _tmdbSettings;
- }
-
- using var requestMessage = new HttpRequestMessage(HttpMethod.Get, string.Format(CultureInfo.InvariantCulture, TmdbConfigUrl, TmdbUtils.ApiKey));
- foreach (var header in TmdbUtils.AcceptHeaders)
- {
- requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(header));
- }
-
- using var response = await GetMovieDbResponse(requestMessage, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
- _tmdbSettings = await _jsonSerializer.DeserializeFromStreamAsync(stream).ConfigureAwait(false);
- return _tmdbSettings;
- }
-
- ///
- /// Gets the movie data path.
- ///
- /// The app paths.
- /// The TMDB id.
- /// System.String.
- internal static string GetMovieDataPath(IApplicationPaths appPaths, string tmdbId)
- {
- var dataPath = GetMoviesDataPath(appPaths);
-
- return Path.Combine(dataPath, tmdbId);
- }
-
- internal static string GetMoviesDataPath(IApplicationPaths appPaths)
- {
- var dataPath = Path.Combine(appPaths.CachePath, "tmdb-movies2");
-
- return dataPath;
- }
-
- ///
- /// Downloads the movie info.
- ///
- /// The id.
- /// The preferred metadata language.
- /// The cancellation token.
- /// Task.
- internal async Task DownloadMovieInfo(string id, string preferredMetadataLanguage, CancellationToken cancellationToken)
- {
- var mainResult = await FetchMainResult(id, true, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
-
- if (mainResult == null)
- {
- return;
- }
-
- var dataFilePath = GetDataFilePath(id, preferredMetadataLanguage);
-
- Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
-
- _jsonSerializer.SerializeToFile(mainResult, dataFilePath);
- }
-
- internal Task EnsureMovieInfo(string tmdbId, string language, CancellationToken cancellationToken)
- {
- if (string.IsNullOrEmpty(tmdbId))
- {
- throw new ArgumentNullException(nameof(tmdbId));
- }
-
- var path = GetDataFilePath(tmdbId, language);
-
- var fileInfo = _fileSystem.GetFileSystemInfo(path);
-
- if (fileInfo.Exists)
- {
- // If it's recent or automatic updates are enabled, don't re-download
- if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
- {
- return Task.CompletedTask;
- }
- }
-
- return DownloadMovieInfo(tmdbId, language, cancellationToken);
- }
-
- internal string GetDataFilePath(string tmdbId, string preferredLanguage)
- {
- if (string.IsNullOrEmpty(tmdbId))
- {
- throw new ArgumentNullException(nameof(tmdbId));
- }
-
- var path = GetMovieDataPath(_configurationManager.ApplicationPaths, tmdbId);
-
- if (string.IsNullOrWhiteSpace(preferredLanguage))
- {
- preferredLanguage = "alllang";
- }
-
- var filename = string.Format(CultureInfo.InvariantCulture, "all-{0}.json", preferredLanguage);
-
- return Path.Combine(path, filename);
- }
-
- public static string GetImageLanguagesParam(string preferredLanguage)
- {
- var languages = new List();
-
- if (!string.IsNullOrEmpty(preferredLanguage))
- {
- preferredLanguage = NormalizeLanguage(preferredLanguage);
-
- languages.Add(preferredLanguage);
-
- if (preferredLanguage.Length == 5) // like en-US
- {
- // Currenty, TMDB supports 2-letter language codes only
- // They are planning to change this in the future, thus we're
- // supplying both codes if we're having a 5-letter code.
- languages.Add(preferredLanguage.Substring(0, 2));
- }
- }
-
- languages.Add("null");
-
- if (!string.Equals(preferredLanguage, "en", StringComparison.OrdinalIgnoreCase))
- {
- languages.Add("en");
- }
-
- return string.Join(',', languages);
- }
-
- public static string NormalizeLanguage(string language)
- {
- if (!string.IsNullOrEmpty(language))
- {
- // They require this to be uppercase
- // Everything after the hyphen must be written in uppercase due to a way TMDB wrote their api.
- // See here: https://www.themoviedb.org/talk/5119221d760ee36c642af4ad?page=3#56e372a0c3a3685a9e0019ab
- var parts = language.Split('-');
-
- if (parts.Length == 2)
- {
- language = parts[0] + "-" + parts[1].ToUpperInvariant();
- }
- }
-
- return language;
- }
-
- public static string AdjustImageLanguage(string imageLanguage, string requestLanguage)
- {
- if (!string.IsNullOrEmpty(imageLanguage)
- && !string.IsNullOrEmpty(requestLanguage)
- && requestLanguage.Length > 2
- && imageLanguage.Length == 2
- && requestLanguage.StartsWith(imageLanguage, StringComparison.OrdinalIgnoreCase))
- {
- return requestLanguage;
- }
-
- return imageLanguage;
- }
-
- ///
- /// Fetches the main result.
- ///
- /// The id.
- /// if set to true [is TMDB identifier].
- /// The language.
- /// The cancellation token.
- /// Task{CompleteMovieData}.
- internal async Task FetchMainResult(string id, bool isTmdbId, string language, CancellationToken cancellationToken)
- {
- var url = string.Format(CultureInfo.InvariantCulture, GetMovieInfo3, id, TmdbUtils.ApiKey);
-
- if (!string.IsNullOrEmpty(language))
- {
- url += string.Format(CultureInfo.InvariantCulture, "&language={0}", NormalizeLanguage(language));
-
- // Get images in english and with no language
- url += "&include_image_language=" + GetImageLanguagesParam(language);
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- using var requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
- foreach (var header in TmdbUtils.AcceptHeaders)
- {
- requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(header));
- }
-
- using var mainResponse = await GetMovieDbResponse(requestMessage, cancellationToken).ConfigureAwait(false);
- if (mainResponse.StatusCode == HttpStatusCode.NotFound)
- {
- return null;
- }
-
- await using var stream = await mainResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
- var mainResult = await _jsonSerializer.DeserializeFromStreamAsync(stream).ConfigureAwait(false);
-
- cancellationToken.ThrowIfCancellationRequested();
-
- // If the language preference isn't english, then have the overview fallback to english if it's blank
- if (mainResult != null &&
- string.IsNullOrEmpty(mainResult.Overview) &&
- !string.IsNullOrEmpty(language) &&
- !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
- {
- _logger.LogInformation("MovieDbProvider couldn't find meta for language " + language + ". Trying English...");
-
- url = string.Format(CultureInfo.InvariantCulture, GetMovieInfo3, id, TmdbUtils.ApiKey) + "&language=en";
-
- if (!string.IsNullOrEmpty(language))
- {
- // Get images in english and with no language
- url += "&include_image_language=" + GetImageLanguagesParam(language);
- }
-
- using var langRequestMessage = new HttpRequestMessage(HttpMethod.Get, url);
- foreach (var header in TmdbUtils.AcceptHeaders)
- {
- langRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(header));
- }
-
- using var langResponse = await GetMovieDbResponse(langRequestMessage, cancellationToken).ConfigureAwait(false);
-
- await using var langStream = await langResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
- var langResult = await _jsonSerializer.DeserializeFromStreamAsync(stream).ConfigureAwait(false);
- mainResult.Overview = langResult.Overview;
- }
-
- return mainResult;
- }
-
- ///
- /// Gets the movie db response.
- ///
- /// A representing the asynchronous operation.
- internal Task GetMovieDbResponse(HttpRequestMessage message, CancellationToken cancellationToken = default)
- {
- message.Headers.UserAgent.ParseAdd(_appHost.ApplicationUserAgent);
- return _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(message, cancellationToken);
+ return metadataResult;
}
///
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbSearch.cs b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbSearch.cs
deleted file mode 100644
index 36a4eef8a3..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbSearch.cs
+++ /dev/null
@@ -1,302 +0,0 @@
-#pragma warning disable CS1591
-
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Net;
-using System.Net.Http;
-using System.Net.Http.Headers;
-using System.Text.RegularExpressions;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.Search;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Movies
-{
- public class TmdbSearch
- {
- private const string SearchUrl = TmdbUtils.BaseTmdbApiUrl + @"3/search/{3}?api_key={1}&query={0}&language={2}";
- private const string SearchUrlTvWithYear = TmdbUtils.BaseTmdbApiUrl + @"3/search/tv?api_key={1}&query={0}&language={2}&first_air_date_year={3}";
- private const string SearchUrlMovieWithYear = TmdbUtils.BaseTmdbApiUrl + @"3/search/movie?api_key={1}&query={0}&language={2}&primary_release_year={3}";
-
- private static readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- private static readonly Regex _cleanEnclosed = new Regex(@"\p{Ps}.*\p{Pe}", RegexOptions.Compiled);
- private static readonly Regex _cleanNonWord = new Regex(@"[\W_]+", RegexOptions.Compiled);
- private static readonly Regex _cleanStopWords = new Regex(
- @"\b( # Start at word boundary
- 19[0-9]{2}|20[0-9]{2}| # 1900-2099
- S[0-9]{2}| # Season
- E[0-9]{2}| # Episode
- (2160|1080|720|576|480)[ip]?| # Resolution
- [xh]?264| # Encoding
- (web|dvd|bd|hdtv|hd)rip| # *Rip
- web|hdtv|mp4|bluray|ktr|dl|single|imageset|internal|doku|dubbed|retail|xxx|flac
- ).* # Match rest of string",
- RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
-
- private readonly ILogger _logger;
- private readonly IJsonSerializer _json;
- private readonly ILibraryManager _libraryManager;
-
- public TmdbSearch(ILogger logger, IJsonSerializer json, ILibraryManager libraryManager)
- {
- _logger = logger;
- _json = json;
- _libraryManager = libraryManager;
- }
-
- public Task> GetSearchResults(SeriesInfo idInfo, CancellationToken cancellationToken)
- {
- return GetSearchResults(idInfo, "tv", cancellationToken);
- }
-
- public Task> GetMovieSearchResults(ItemLookupInfo idInfo, CancellationToken cancellationToken)
- {
- return GetSearchResults(idInfo, "movie", cancellationToken);
- }
-
- public Task> GetSearchResults(BoxSetInfo idInfo, CancellationToken cancellationToken)
- {
- return GetSearchResults(idInfo, "collection", cancellationToken);
- }
-
- private async Task> GetSearchResults(ItemLookupInfo idInfo, string searchType, CancellationToken cancellationToken)
- {
- var name = idInfo.Name;
- var year = idInfo.Year;
-
- if (string.IsNullOrWhiteSpace(name))
- {
- return new List();
- }
-
- var tmdbSettings = await TmdbMovieProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- // ParseName is required here.
- // Caller provides the filename with extension stripped and NOT the parsed filename
- var parsedName = _libraryManager.ParseName(name);
- var yearInName = parsedName.Year;
- name = parsedName.Name;
- year ??= yearInName;
-
- var language = idInfo.MetadataLanguage.ToLowerInvariant();
-
- // Replace sequences of non-word characters with space
- // TMDB expects a space separated list of words make sure that is the case
- name = _cleanNonWord.Replace(name, " ").Trim();
-
- _logger.LogInformation("TmdbSearch: Finding id for item: {0} ({1})", name, year);
- var results = await GetSearchResults(name, searchType, year, language, tmdbImageUrl, cancellationToken).ConfigureAwait(false);
-
- if (results.Count == 0)
- {
- // try in english if wasn't before
- if (!string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
- {
- results = await GetSearchResults(name, searchType, year, "en", tmdbImageUrl, cancellationToken).ConfigureAwait(false);
- }
- }
-
- // TODO: retrying alternatives should be done outside the search
- // provider so that the retry logic can be common for all search
- // providers
- if (results.Count == 0)
- {
- var name2 = parsedName.Name;
-
- // Remove things enclosed in []{}() etc
- name2 = _cleanEnclosed.Replace(name2, string.Empty);
-
- // Replace sequences of non-word characters with space
- name2 = _cleanNonWord.Replace(name2, " ");
-
- // Clean based on common stop words / tokens
- name2 = _cleanStopWords.Replace(name2, string.Empty);
-
- // Trim whitespace
- name2 = name2.Trim();
-
- // Search again if the new name is different
- if (!string.Equals(name2, name, StringComparison.Ordinal) && !string.IsNullOrWhiteSpace(name2))
- {
- _logger.LogInformation("TmdbSearch: Finding id for item: {0} ({1})", name2, year);
- results = await GetSearchResults(name2, searchType, year, language, tmdbImageUrl, cancellationToken).ConfigureAwait(false);
-
- if (results.Count == 0 && !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
- {
- // one more time, in english
- results = await GetSearchResults(name2, searchType, year, "en", tmdbImageUrl, cancellationToken).ConfigureAwait(false);
- }
- }
- }
-
- return results.Where(i =>
- {
- if (year.HasValue && i.ProductionYear.HasValue)
- {
- // Allow one year tolerance
- return Math.Abs(year.Value - i.ProductionYear.Value) <= 1;
- }
-
- return true;
- });
- }
-
- private Task> GetSearchResults(string name, string type, int? year, string language, string baseImageUrl, CancellationToken cancellationToken)
- {
- switch (type)
- {
- case "tv":
- return GetSearchResultsTv(name, year, language, baseImageUrl, cancellationToken);
- default:
- return GetSearchResultsGeneric(name, type, year, language, baseImageUrl, cancellationToken);
- }
- }
-
- private async Task> GetSearchResultsGeneric(string name, string type, int? year, string language, string baseImageUrl, CancellationToken cancellationToken)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- throw new ArgumentException("String can't be null or empty.", nameof(name));
- }
-
- string url3;
- if (year != null && string.Equals(type, "movie", StringComparison.OrdinalIgnoreCase))
- {
- url3 = string.Format(
- CultureInfo.InvariantCulture,
- SearchUrlMovieWithYear,
- WebUtility.UrlEncode(name),
- TmdbUtils.ApiKey,
- language,
- year);
- }
- else
- {
- url3 = string.Format(
- CultureInfo.InvariantCulture,
- SearchUrl,
- WebUtility.UrlEncode(name),
- TmdbUtils.ApiKey,
- language,
- type);
- }
-
- using var requestMessage = new HttpRequestMessage(HttpMethod.Get, url3);
- foreach (var header in TmdbUtils.AcceptHeaders)
- {
- requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(header));
- }
-
- using var response = await TmdbMovieProvider.Current.GetMovieDbResponse(requestMessage, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
- var searchResults = await _json.DeserializeFromStreamAsync>(stream).ConfigureAwait(false);
-
- var results = searchResults.Results ?? new List();
-
- return results
- .Select(i =>
- {
- var remoteResult = new RemoteSearchResult
- {
- SearchProviderName = TmdbMovieProvider.Current.Name,
- Name = i.Title ?? i.Name ?? i.Original_Title,
- ImageUrl = string.IsNullOrWhiteSpace(i.Poster_Path) ? null : baseImageUrl + i.Poster_Path
- };
-
- if (!string.IsNullOrWhiteSpace(i.Release_Date))
- {
- // These dates are always in this exact format
- if (DateTime.TryParseExact(i.Release_Date, "yyyy-MM-dd", _usCulture, DateTimeStyles.None, out var r))
- {
- remoteResult.PremiereDate = r.ToUniversalTime();
- remoteResult.ProductionYear = remoteResult.PremiereDate.Value.Year;
- }
- }
-
- remoteResult.SetProviderId(MetadataProvider.Tmdb, i.Id.ToString(_usCulture));
-
- return remoteResult;
- })
- .ToList();
- }
-
- private async Task> GetSearchResultsTv(string name, int? year, string language, string baseImageUrl, CancellationToken cancellationToken)
- {
- if (string.IsNullOrWhiteSpace(name))
- {
- throw new ArgumentException("String can't be null or empty.", nameof(name));
- }
-
- string url3;
- if (year == null)
- {
- url3 = string.Format(
- CultureInfo.InvariantCulture,
- SearchUrl,
- WebUtility.UrlEncode(name),
- TmdbUtils.ApiKey,
- language,
- "tv");
- }
- else
- {
- url3 = string.Format(
- CultureInfo.InvariantCulture,
- SearchUrlTvWithYear,
- WebUtility.UrlEncode(name),
- TmdbUtils.ApiKey,
- language,
- year);
- }
-
- using var requestMessage = new HttpRequestMessage(HttpMethod.Get, url3);
- foreach (var header in TmdbUtils.AcceptHeaders)
- {
- requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(header));
- }
-
- using var response = await TmdbMovieProvider.Current.GetMovieDbResponse(requestMessage, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
- var searchResults = await _json.DeserializeFromStreamAsync>(stream).ConfigureAwait(false);
-
- var results = searchResults.Results ?? new List();
-
- return results
- .Select(i =>
- {
- var remoteResult = new RemoteSearchResult
- {
- SearchProviderName = TmdbMovieProvider.Current.Name,
- Name = i.Name ?? i.Original_Name,
- ImageUrl = string.IsNullOrWhiteSpace(i.Poster_Path) ? null : baseImageUrl + i.Poster_Path
- };
-
- if (!string.IsNullOrWhiteSpace(i.First_Air_Date))
- {
- // These dates are always in this exact format
- if (DateTime.TryParseExact(i.First_Air_Date, "yyyy-MM-dd", _usCulture, DateTimeStyles.None, out var r))
- {
- remoteResult.PremiereDate = r.ToUniversalTime();
- remoteResult.ProductionYear = remoteResult.PremiereDate.Value.Year;
- }
- }
-
- remoteResult.SetProviderId(MetadataProvider.Tmdb, i.Id.ToString(_usCulture));
-
- return remoteResult;
- })
- .ToList();
- }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbSettingsResult.cs b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbSettingsResult.cs
deleted file mode 100644
index c7ba974386..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbSettingsResult.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-#pragma warning disable CS1591
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Movies
-{
- internal class TmdbSettingsResult
- {
- public TmdbImageSettings images { get; set; }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Music/TmdbMusicVideoProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/Music/TmdbMusicVideoProvider.cs
deleted file mode 100644
index b88ecce87f..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Music/TmdbMusicVideoProvider.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-#pragma warning disable CS1591
-
-using System;
-using System.Collections.Generic;
-using System.Net.Http;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Providers.Plugins.Tmdb.Movies;
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Music
-{
- public class TmdbMusicVideoProvider : IRemoteMetadataProvider
- {
- public string Name => TmdbMovieProvider.Current.Name;
-
- public Task> GetMetadata(MusicVideoInfo info, CancellationToken cancellationToken)
- {
- return TmdbMovieProvider.Current.GetItemMetadata(info, cancellationToken);
- }
-
- public Task> GetSearchResults(MusicVideoInfo searchInfo, CancellationToken cancellationToken)
- {
- return Task.FromResult((IEnumerable)new List());
- }
-
- public Task GetImageResponse(string url, CancellationToken cancellationToken)
- {
- throw new NotImplementedException();
- }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs
index f2d2c8120e..3f57c4bc4c 100644
--- a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs
@@ -2,40 +2,33 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.General;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.People;
-using MediaBrowser.Providers.Plugins.Tmdb.Movies;
namespace MediaBrowser.Providers.Plugins.Tmdb.People
{
public class TmdbPersonImageProvider : IRemoteImageProvider, IHasOrder
{
- private readonly IServerConfigurationManager _config;
- private readonly IJsonSerializer _jsonSerializer;
private readonly IHttpClientFactory _httpClientFactory;
+ private readonly TmdbClientManager _tmdbClientManager;
- public TmdbPersonImageProvider(IServerConfigurationManager config, IJsonSerializer jsonSerializer, IHttpClientFactory httpClientFactory)
+ public TmdbPersonImageProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
{
- _config = config;
- _jsonSerializer = jsonSerializer;
_httpClientFactory = httpClientFactory;
+ _tmdbClientManager = tmdbClientManager;
}
- public static string ProviderName => TmdbUtils.ProviderName;
-
///
- public string Name => ProviderName;
+ public string Name => TmdbUtils.ProviderName;
///
public int Order => 0;
@@ -56,78 +49,37 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.People
public async Task> GetImages(BaseItem item, CancellationToken cancellationToken)
{
var person = (Person)item;
- var id = person.GetProviderId(MetadataProvider.Tmdb);
+ var personTmdbId = Convert.ToInt32(person.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
- if (!string.IsNullOrEmpty(id))
+ if (personTmdbId > 0)
{
- await TmdbPersonProvider.Current.EnsurePersonInfo(id, cancellationToken).ConfigureAwait(false);
-
- var dataFilePath = TmdbPersonProvider.GetPersonDataFilePath(_config.ApplicationPaths, id);
-
- var result = _jsonSerializer.DeserializeFromFile(dataFilePath);
-
- var images = result.Images ?? new PersonImages();
-
- var tmdbSettings = await TmdbMovieProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- return GetImages(images, item.GetPreferredMetadataLanguage(), tmdbImageUrl);
- }
-
- return new List();
- }
-
- private IEnumerable GetImages(PersonImages images, string preferredLanguage, string baseImageUrl)
- {
- var list = new List();
-
- if (images.Profiles != null)
- {
- list.AddRange(images.Profiles.Select(i => new RemoteImageInfo
+ var personResult = await _tmdbClientManager.GetPersonAsync(personTmdbId, cancellationToken).ConfigureAwait(false);
+ if (personResult?.Images?.Profiles == null)
{
- ProviderName = Name,
- Type = ImageType.Primary,
- Width = i.Width,
- Height = i.Height,
- Language = GetLanguage(i),
- Url = baseImageUrl + i.File_Path
- }));
- }
-
- var language = preferredLanguage;
-
- var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
-
- return list.OrderByDescending(i =>
- {
- if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
+ return Enumerable.Empty();
}
- if (!isLanguageEn)
+ var remoteImages = new List();
+ var language = item.GetPreferredMetadataLanguage();
+
+ for (var i = 0; i < personResult.Images.Profiles.Count; i++)
{
- if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
+ var image = personResult.Images.Profiles[i];
+ remoteImages.Add(new RemoteImageInfo
{
- return 2;
- }
+ ProviderName = Name,
+ Type = ImageType.Primary,
+ Width = image.Width,
+ Height = image.Height,
+ Language = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, language),
+ Url = _tmdbClientManager.GetProfileUrl(image.FilePath)
+ });
}
- if (string.IsNullOrEmpty(i.Language))
- {
- return isLanguageEn ? 3 : 2;
- }
+ return remoteImages.OrderByLanguageDescending(language);
+ }
- return 0;
- })
- .ThenByDescending(i => i.CommunityRating ?? 0)
- .ThenByDescending(i => i.VoteCount ?? 0);
- }
-
- private string GetLanguage(Profile profile)
- {
- return profile.Iso_639_1?.ToString();
+ return Enumerable.Empty();
}
public Task GetImageResponse(string url, CancellationToken cancellationToken)
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs
index 777ebce492..4384c203e5 100644
--- a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs
@@ -3,198 +3,130 @@
using System;
using System.Collections.Generic;
using System.Globalization;
-using System.IO;
using System.Linq;
-using System.Net;
using System.Net.Http;
-using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.General;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.People;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.Search;
-using MediaBrowser.Providers.Plugins.Tmdb.Movies;
-using Microsoft.Extensions.Logging;
namespace MediaBrowser.Providers.Plugins.Tmdb.People
{
public class TmdbPersonProvider : IRemoteMetadataProvider
{
- private const string DataFileName = "info.json";
-
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IFileSystem _fileSystem;
- private readonly IServerConfigurationManager _configurationManager;
private readonly IHttpClientFactory _httpClientFactory;
+ private readonly TmdbClientManager _tmdbClientManager;
- public TmdbPersonProvider(
- IFileSystem fileSystem,
- IServerConfigurationManager configurationManager,
- IJsonSerializer jsonSerializer,
- IHttpClientFactory httpClientFactory)
+ public TmdbPersonProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
{
- _fileSystem = fileSystem;
- _configurationManager = configurationManager;
- _jsonSerializer = jsonSerializer;
_httpClientFactory = httpClientFactory;
- Current = this;
+ _tmdbClientManager = tmdbClientManager;
}
- internal static TmdbPersonProvider Current { get; private set; }
-
public string Name => TmdbUtils.ProviderName;
public async Task> GetSearchResults(PersonLookupInfo searchInfo, CancellationToken cancellationToken)
{
- var tmdbId = searchInfo.GetProviderId(MetadataProvider.Tmdb);
+ var personTmdbId = Convert.ToInt32(searchInfo.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
- var tmdbSettings = await TmdbMovieProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- if (!string.IsNullOrEmpty(tmdbId))
+ if (personTmdbId <= 0)
{
- await EnsurePersonInfo(tmdbId, cancellationToken).ConfigureAwait(false);
+ var personResult = await _tmdbClientManager.GetPersonAsync(personTmdbId, cancellationToken).ConfigureAwait(false);
- var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, tmdbId);
- var info = _jsonSerializer.DeserializeFromFile(dataFilePath);
-
- IReadOnlyList images = info.Images?.Profiles ?? Array.Empty();
-
- var result = new RemoteSearchResult
+ if (personResult != null)
{
- Name = info.Name,
+ var result = new RemoteSearchResult
+ {
+ Name = personResult.Name,
+ SearchProviderName = Name,
+ Overview = personResult.Biography
+ };
- SearchProviderName = Name,
+ if (personResult.Images?.Profiles != null && personResult.Images.Profiles.Count > 0)
+ {
+ result.ImageUrl = _tmdbClientManager.GetProfileUrl(personResult.Images.Profiles[0].FilePath);
+ }
- ImageUrl = images.Count == 0 ? null : (tmdbImageUrl + images[0].File_Path)
- };
+ result.SetProviderId(MetadataProvider.Tmdb, personResult.Id.ToString(CultureInfo.InvariantCulture));
+ result.SetProviderId(MetadataProvider.Imdb, personResult.ExternalIds.ImdbId);
- result.SetProviderId(MetadataProvider.Tmdb, info.Id.ToString(_usCulture));
- result.SetProviderId(MetadataProvider.Imdb, info.Imdb_Id);
-
- return new[] { result };
+ return new[] { result };
+ }
}
+ // TODO why? Because of the old rate limit?
if (searchInfo.IsAutomated)
{
// Don't hammer moviedb searching by name
- return Array.Empty();
+ return Enumerable.Empty();
}
- var url = string.Format(
- CultureInfo.InvariantCulture,
- TmdbUtils.BaseTmdbApiUrl + @"3/search/person?api_key={1}&query={0}",
- WebUtility.UrlEncode(searchInfo.Name),
- TmdbUtils.ApiKey);
+ var personSearchResult = await _tmdbClientManager.SearchPersonAsync(searchInfo.Name, cancellationToken).ConfigureAwait(false);
- using var requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
- foreach (var header in TmdbUtils.AcceptHeaders)
+ var remoteSearchResults = new List();
+ for (var i = 0; i < personSearchResult.Count; i++)
{
- requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(header));
+ var person = personSearchResult[i];
+ var remoteSearchResult = new RemoteSearchResult
+ {
+ SearchProviderName = Name,
+ Name = person.Name,
+ ImageUrl = _tmdbClientManager.GetProfileUrl(person.ProfilePath)
+ };
+
+ remoteSearchResult.SetProviderId(MetadataProvider.Tmdb, person.Id.ToString(CultureInfo.InvariantCulture));
+ remoteSearchResults.Add(remoteSearchResult);
}
- var response = await TmdbMovieProvider.Current.GetMovieDbResponse(requestMessage, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
-
- var result2 = await _jsonSerializer.DeserializeFromStreamAsync>(stream).ConfigureAwait(false)
- ?? new TmdbSearchResult();
-
- return result2.Results.Select(i => GetSearchResult(i, tmdbImageUrl));
- }
-
- private RemoteSearchResult GetSearchResult(PersonSearchResult i, string baseImageUrl)
- {
- var result = new RemoteSearchResult
- {
- SearchProviderName = Name,
-
- Name = i.Name,
-
- ImageUrl = string.IsNullOrEmpty(i.Profile_Path) ? null : baseImageUrl + i.Profile_Path
- };
-
- result.SetProviderId(MetadataProvider.Tmdb, i.Id.ToString(_usCulture));
-
- return result;
+ return remoteSearchResults;
}
public async Task> GetMetadata(PersonLookupInfo id, CancellationToken cancellationToken)
{
- var tmdbId = id.GetProviderId(MetadataProvider.Tmdb);
+ var personTmdbId = Convert.ToInt32(id.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
// We don't already have an Id, need to fetch it
- if (string.IsNullOrEmpty(tmdbId))
+ if (personTmdbId <= 0)
{
- tmdbId = await GetTmdbId(id, cancellationToken).ConfigureAwait(false);
+ var personSearchResults = await _tmdbClientManager.SearchPersonAsync(id.Name, cancellationToken).ConfigureAwait(false);
+ if (personSearchResults.Count > 0)
+ {
+ personTmdbId = personSearchResults[0].Id;
+ }
}
var result = new MetadataResult();
- if (!string.IsNullOrEmpty(tmdbId))
+ if (personTmdbId > 0)
{
- try
- {
- await EnsurePersonInfo(tmdbId, cancellationToken).ConfigureAwait(false);
- }
- catch (HttpException ex)
- {
- if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
- {
- return result;
- }
+ var person = await _tmdbClientManager.GetPersonAsync(personTmdbId, cancellationToken).ConfigureAwait(false);
- throw;
- }
-
- var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, tmdbId);
-
- var info = _jsonSerializer.DeserializeFromFile(dataFilePath);
-
- var item = new Person();
result.HasMetadata = true;
- // Take name from incoming info, don't rename the person
- // TODO: This should go in PersonMetadataService, not each person provider
- item.Name = id.Name;
-
- // item.HomePageUrl = info.homepage;
-
- if (!string.IsNullOrWhiteSpace(info.Place_Of_Birth))
+ var item = new Person
{
- item.ProductionLocations = new string[] { info.Place_Of_Birth };
+ // Take name from incoming info, don't rename the person
+ // TODO: This should go in PersonMetadataService, not each person provider
+ Name = id.Name,
+ HomePageUrl = person.Homepage,
+ Overview = person.Biography,
+ PremiereDate = person.Birthday?.ToUniversalTime(),
+ EndDate = person.Deathday?.ToUniversalTime()
+ };
+
+ if (!string.IsNullOrWhiteSpace(person.PlaceOfBirth))
+ {
+ item.ProductionLocations = new[] { person.PlaceOfBirth };
}
- item.Overview = info.Biography;
+ item.SetProviderId(MetadataProvider.Tmdb, person.Id.ToString(CultureInfo.InvariantCulture));
- if (DateTime.TryParseExact(info.Birthday, "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.None, out var date))
+ if (!string.IsNullOrEmpty(person.ImdbId))
{
- item.PremiereDate = date.ToUniversalTime();
- }
-
- if (DateTime.TryParseExact(info.Deathday, "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.None, out date))
- {
- item.EndDate = date.ToUniversalTime();
- }
-
- item.SetProviderId(MetadataProvider.Tmdb, info.Id.ToString(_usCulture));
-
- if (!string.IsNullOrEmpty(info.Imdb_Id))
- {
- item.SetProviderId(MetadataProvider.Imdb, info.Imdb_Id);
+ item.SetProviderId(MetadataProvider.Imdb, person.ImdbId);
}
result.HasMetadata = true;
@@ -204,65 +136,6 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.People
return result;
}
- ///
- /// Gets the TMDB id.
- ///
- /// The information.
- /// The cancellation token.
- /// Task{System.String}.
- private async Task GetTmdbId(PersonLookupInfo info, CancellationToken cancellationToken)
- {
- var results = await GetSearchResults(info, cancellationToken).ConfigureAwait(false);
-
- return results.Select(i => i.GetProviderId(MetadataProvider.Tmdb)).FirstOrDefault();
- }
-
- internal async Task EnsurePersonInfo(string id, CancellationToken cancellationToken)
- {
- var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, id);
-
- var fileInfo = _fileSystem.GetFileSystemInfo(dataFilePath);
-
- if (fileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
- {
- return;
- }
-
- var url = string.Format(
- CultureInfo.InvariantCulture,
- TmdbUtils.BaseTmdbApiUrl + @"3/person/{1}?api_key={0}&append_to_response=credits,images,external_ids",
- TmdbUtils.ApiKey,
- id);
-
- using var requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
- foreach (var header in TmdbUtils.AcceptHeaders)
- {
- requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(header));
- }
-
- using var response = await TmdbMovieProvider.Current.GetMovieDbResponse(requestMessage, cancellationToken).ConfigureAwait(false);
- Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
- await using var fs = new FileStream(dataFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true);
- await response.Content.CopyToAsync(fs).ConfigureAwait(false);
- }
-
- private static string GetPersonDataPath(IApplicationPaths appPaths, string tmdbId)
- {
- var letter = tmdbId.GetMD5().ToString().AsSpan().Slice(0, 1);
-
- return Path.Join(GetPersonsDataPath(appPaths), letter, tmdbId);
- }
-
- internal static string GetPersonDataFilePath(IApplicationPaths appPaths, string tmdbId)
- {
- return Path.Combine(GetPersonDataPath(appPaths, tmdbId), DataFileName);
- }
-
- private static string GetPersonsDataPath(IApplicationPaths appPaths)
- {
- return Path.Combine(appPaths.CachePath, "tmdb-people");
- }
-
public Task GetImageResponse(string url, CancellationToken cancellationToken)
{
return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs
index c56774f8e7..3b7a0b254e 100644
--- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs
@@ -2,40 +2,37 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.General;
-using MediaBrowser.Providers.Plugins.Tmdb.Movies;
-using Microsoft.Extensions.Logging;
namespace MediaBrowser.Providers.Plugins.Tmdb.TV
{
- public class TmdbEpisodeImageProvider :
- TmdbEpisodeProviderBase,
- IRemoteImageProvider,
- IHasOrder
+ public class TmdbEpisodeImageProvider : IRemoteImageProvider, IHasOrder
{
- public TmdbEpisodeImageProvider(IHttpClientFactory httpClientFactory, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILoggerFactory loggerFactory)
- : base(httpClientFactory, configurationManager, jsonSerializer, fileSystem, localization, loggerFactory)
- {
- }
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly TmdbClientManager _tmdbClientManager;
- public string Name => TmdbUtils.ProviderName;
+ public TmdbEpisodeImageProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
+ {
+ _httpClientFactory = httpClientFactory;
+ _tmdbClientManager = tmdbClientManager;
+ }
// After TheTvDb
public int Order => 1;
+ public string Name => TmdbUtils.ProviderName;
+
public IEnumerable GetSupportedImages(BaseItem item)
{
return new List
@@ -49,13 +46,11 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV
var episode = (Controller.Entities.TV.Episode)item;
var series = episode.Series;
- var seriesId = series?.GetProviderId(MetadataProvider.Tmdb);
+ var seriesTmdbId = Convert.ToInt32(series?.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
- var list = new List();
-
- if (string.IsNullOrEmpty(seriesId))
+ if (seriesTmdbId <= 0)
{
- return list;
+ return Enumerable.Empty();
}
var seasonNumber = episode.ParentIndexNumber;
@@ -63,71 +58,45 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV
if (!seasonNumber.HasValue || !episodeNumber.HasValue)
{
- return list;
+ return Enumerable.Empty();
}
var language = item.GetPreferredMetadataLanguage();
- var response = await GetEpisodeInfo(
- seriesId,
- seasonNumber.Value,
- episodeNumber.Value,
- language,
- cancellationToken).ConfigureAwait(false);
+ var episodeResult = await _tmdbClientManager
+ .GetEpisodeAsync(seriesTmdbId, seasonNumber.Value, episodeNumber.Value, language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken)
+ .ConfigureAwait(false);
- var tmdbSettings = await TmdbMovieProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- list.AddRange(GetPosters(response.Images).Select(i => new RemoteImageInfo
+ var stills = episodeResult?.Images?.Stills;
+ if (stills == null)
{
- Url = tmdbImageUrl + i.File_Path,
- CommunityRating = i.Vote_Average,
- VoteCount = i.Vote_Count,
- Width = i.Width,
- Height = i.Height,
- Language = TmdbMovieProvider.AdjustImageLanguage(i.Iso_639_1, language),
- ProviderName = Name,
- Type = ImageType.Primary,
- RatingType = RatingType.Score
- }));
+ return Enumerable.Empty();
+ }
- var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
-
- return list.OrderByDescending(i =>
+ var remoteImages = new RemoteImageInfo[stills.Count];
+ for (var i = 0; i < stills.Count; i++)
{
- if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
+ var image = stills[i];
+ remoteImages[i] = new RemoteImageInfo
{
- return 3;
- }
+ Url = _tmdbClientManager.GetStillUrl(image.FilePath),
+ CommunityRating = image.VoteAverage,
+ VoteCount = image.VoteCount,
+ Width = image.Width,
+ Height = image.Height,
+ Language = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, language),
+ ProviderName = Name,
+ Type = ImageType.Primary,
+ RatingType = RatingType.Score
+ };
+ }
- if (!isLanguageEn)
- {
- if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 2;
- }
- }
-
- if (string.IsNullOrEmpty(i.Language))
- {
- return isLanguageEn ? 3 : 2;
- }
-
- return 0;
- })
- .ThenByDescending(i => i.CommunityRating ?? 0)
- .ThenByDescending(i => i.VoteCount ?? 0);
- }
-
- private IEnumerable GetPosters(StillImages images)
- {
- return images.Stills ?? new List();
+ return remoteImages.OrderByLanguageDescending(language);
}
public Task GetImageResponse(string url, CancellationToken cancellationToken)
{
- return GetResponse(url, cancellationToken);
+ return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
}
public bool Supports(BaseItem item)
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs
index a7e3a03fe3..93998a1102 100644
--- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs
@@ -4,32 +4,27 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
-using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using Microsoft.Extensions.Logging;
namespace MediaBrowser.Providers.Plugins.Tmdb.TV
{
- public class TmdbEpisodeProvider :
- TmdbEpisodeProviderBase,
- IRemoteMetadataProvider,
- IHasOrder
+ public class TmdbEpisodeProvider : IRemoteMetadataProvider, IHasOrder
{
- public TmdbEpisodeProvider(IHttpClientFactory httpClientFactory, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILoggerFactory loggerFactory)
- : base(httpClientFactory, configurationManager, jsonSerializer, fileSystem, localization, loggerFactory)
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly TmdbClientManager _tmdbClientManager;
+
+ public TmdbEpisodeProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
{
+ _httpClientFactory = httpClientFactory;
+ _tmdbClientManager = tmdbClientManager;
}
// After TheTvDb
@@ -39,21 +34,24 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV
public async Task> GetSearchResults(EpisodeInfo searchInfo, CancellationToken cancellationToken)
{
- var list = new List();
-
// The search query must either provide an episode number or date
if (!searchInfo.IndexNumber.HasValue || !searchInfo.ParentIndexNumber.HasValue)
{
- return list;
+ return Enumerable.Empty();
}
var metadataResult = await GetMetadata(searchInfo, cancellationToken).ConfigureAwait(false);
- if (metadataResult.HasMetadata)
+ if (!metadataResult.HasMetadata)
{
- var item = metadataResult.Item;
+ return Enumerable.Empty();
+ }
- list.Add(new RemoteSearchResult
+ var item = metadataResult.Item;
+
+ return new[]
+ {
+ new RemoteSearchResult
{
IndexNumber = item.IndexNumber,
Name = item.Name,
@@ -63,27 +61,26 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV
ProviderIds = item.ProviderIds,
SearchProviderName = Name,
IndexNumberEnd = item.IndexNumberEnd
- });
- }
-
- return list;
+ }
+ };
}
public async Task> GetMetadata(EpisodeInfo info, CancellationToken cancellationToken)
{
- var result = new MetadataResult();
+ var metadataResult = new MetadataResult();
// Allowing this will dramatically increase scan times
if (info.IsMissingEpisode)
{
- return result;
+ return metadataResult;
}
- info.SeriesProviderIds.TryGetValue(MetadataProvider.Tmdb.ToString(), out string seriesTmdbId);
+ info.SeriesProviderIds.TryGetValue(MetadataProvider.Tmdb.ToString(), out string tmdbId);
- if (string.IsNullOrEmpty(seriesTmdbId))
+ var seriesTmdbId = Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture);
+ if (seriesTmdbId <= 0)
{
- return result;
+ return metadataResult;
}
var seasonNumber = info.ParentIndexNumber;
@@ -91,125 +88,120 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV
if (!seasonNumber.HasValue || !episodeNumber.HasValue)
{
- return result;
+ return metadataResult;
}
- try
+ var episodeResult = await _tmdbClientManager
+ .GetEpisodeAsync(seriesTmdbId, seasonNumber.Value, episodeNumber.Value, info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken)
+ .ConfigureAwait(false);
+
+ if (episodeResult == null)
{
- var response = await GetEpisodeInfo(seriesTmdbId, seasonNumber.Value, episodeNumber.Value, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);
-
- result.HasMetadata = true;
- result.QueriedById = true;
-
- if (!string.IsNullOrEmpty(response.Overview))
- {
- // if overview is non-empty, we can assume that localized data was returned
- result.ResultLanguage = info.MetadataLanguage;
- }
-
- var item = new Episode();
- result.Item = item;
-
- item.Name = info.Name;
- item.IndexNumber = info.IndexNumber;
- item.ParentIndexNumber = info.ParentIndexNumber;
- item.IndexNumberEnd = info.IndexNumberEnd;
-
- if (response.External_Ids != null && response.External_Ids.Tvdb_Id > 0)
- {
- item.SetProviderId(MetadataProvider.Tvdb, response.External_Ids.Tvdb_Id.Value.ToString(CultureInfo.InvariantCulture));
- }
-
- item.PremiereDate = response.Air_Date;
- item.ProductionYear = result.Item.PremiereDate.Value.Year;
-
- item.Name = response.Name;
- item.Overview = response.Overview;
-
- item.CommunityRating = (float)response.Vote_Average;
-
- if (response.Videos?.Results != null)
- {
- foreach (var video in response.Videos.Results)
- {
- if (video.Type.Equals("trailer", System.StringComparison.OrdinalIgnoreCase)
- || video.Type.Equals("clip", System.StringComparison.OrdinalIgnoreCase))
- {
- if (video.Site.Equals("youtube", System.StringComparison.OrdinalIgnoreCase))
- {
- var videoUrl = string.Format(CultureInfo.InvariantCulture, "http://www.youtube.com/watch?v={0}", video.Key);
- item.AddTrailerUrl(videoUrl);
- }
- }
- }
- }
-
- result.ResetPeople();
-
- var credits = response.Credits;
- if (credits != null)
- {
- // Actors, Directors, Writers - all in People
- // actors come from cast
- if (credits.Cast != null)
- {
- foreach (var actor in credits.Cast.OrderBy(a => a.Order))
- {
- result.AddPerson(new PersonInfo { Name = actor.Name.Trim(), Role = actor.Character, Type = PersonType.Actor, SortOrder = actor.Order });
- }
- }
-
- // guest stars
- if (credits.Guest_Stars != null)
- {
- foreach (var guest in credits.Guest_Stars.OrderBy(a => a.Order))
- {
- result.AddPerson(new PersonInfo { Name = guest.Name.Trim(), Role = guest.Character, Type = PersonType.GuestStar, SortOrder = guest.Order });
- }
- }
-
- // and the rest from crew
- if (credits.Crew != null)
- {
- var keepTypes = new[]
- {
- PersonType.Director,
- PersonType.Writer,
- PersonType.Producer
- };
-
- foreach (var person in credits.Crew)
- {
- // Normalize this
- var type = TmdbUtils.MapCrewToPersonType(person);
-
- if (!keepTypes.Contains(type, StringComparer.OrdinalIgnoreCase) &&
- !keepTypes.Contains(person.Job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
- {
- continue;
- }
-
- result.AddPerson(new PersonInfo { Name = person.Name.Trim(), Role = person.Job, Type = type });
- }
- }
- }
+ return metadataResult;
}
- catch (HttpException ex)
+
+ metadataResult.HasMetadata = true;
+ metadataResult.QueriedById = true;
+
+ if (!string.IsNullOrEmpty(episodeResult.Overview))
{
- if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
- {
- return result;
- }
-
- throw;
+ // if overview is non-empty, we can assume that localized data was returned
+ metadataResult.ResultLanguage = info.MetadataLanguage;
}
- return result;
+ var item = new Episode
+ {
+ Name = info.Name,
+ IndexNumber = info.IndexNumber,
+ ParentIndexNumber = info.ParentIndexNumber,
+ IndexNumberEnd = info.IndexNumberEnd
+ };
+
+ if (!string.IsNullOrEmpty(episodeResult.ExternalIds?.TvdbId))
+ {
+ item.SetProviderId(MetadataProvider.Tvdb, episodeResult.ExternalIds.TvdbId);
+ }
+
+ item.PremiereDate = episodeResult.AirDate;
+ item.ProductionYear = episodeResult.AirDate?.Year;
+
+ item.Name = episodeResult.Name;
+ item.Overview = episodeResult.Overview;
+
+ item.CommunityRating = Convert.ToSingle(episodeResult.VoteAverage);
+
+ if (episodeResult.Videos?.Results != null)
+ {
+ foreach (var video in episodeResult.Videos.Results)
+ {
+ if (TmdbUtils.IsTrailerType(video))
+ {
+ item.AddTrailerUrl("https://www.youtube.com/watch?v=" + video.Key);
+ }
+ }
+ }
+
+ var credits = episodeResult.Credits;
+
+ if (credits?.Cast != null)
+ {
+ foreach (var actor in credits.Cast.OrderBy(a => a.Order).Take(TmdbUtils.MaxCastMembers))
+ {
+ metadataResult.AddPerson(new PersonInfo
+ {
+ Name = actor.Name.Trim(),
+ Role = actor.Character,
+ Type = PersonType.Actor,
+ SortOrder = actor.Order
+ });
+ }
+ }
+
+ if (credits?.GuestStars != null)
+ {
+ foreach (var guest in credits.GuestStars.OrderBy(a => a.Order).Take(TmdbUtils.MaxCastMembers))
+ {
+ metadataResult.AddPerson(new PersonInfo
+ {
+ Name = guest.Name.Trim(),
+ Role = guest.Character,
+ Type = PersonType.GuestStar,
+ SortOrder = guest.Order
+ });
+ }
+ }
+
+ // and the rest from crew
+ if (credits?.Crew != null)
+ {
+ foreach (var person in credits.Crew)
+ {
+ // Normalize this
+ var type = TmdbUtils.MapCrewToPersonType(person);
+
+ if (!TmdbUtils.WantedCrewTypes.Contains(type, StringComparer.OrdinalIgnoreCase)
+ && !TmdbUtils.WantedCrewTypes.Contains(person.Job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
+ {
+ continue;
+ }
+
+ metadataResult.AddPerson(new PersonInfo
+ {
+ Name = person.Name.Trim(),
+ Role = person.Job,
+ Type = type
+ });
+ }
+ }
+
+ metadataResult.Item = item;
+
+ return metadataResult;
}
public Task GetImageResponse(string url, CancellationToken cancellationToken)
{
- return GetResponse(url, cancellationToken);
+ return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
}
}
}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProviderBase.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProviderBase.cs
deleted file mode 100644
index 34d2424a34..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProviderBase.cs
+++ /dev/null
@@ -1,156 +0,0 @@
-#pragma warning disable CS1591
-
-using System;
-using System.Globalization;
-using System.IO;
-using System.Net.Http;
-using System.Net.Http.Headers;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.TV;
-using MediaBrowser.Providers.Plugins.Tmdb.Movies;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.TV
-{
- public abstract class TmdbEpisodeProviderBase
- {
- private const string EpisodeUrlPattern = TmdbUtils.BaseTmdbApiUrl + @"3/tv/{0}/season/{1}/episode/{2}?api_key={3}&append_to_response=images,external_ids,credits,videos";
-
- private readonly IHttpClientFactory _httpClientFactory;
- private readonly IServerConfigurationManager _configurationManager;
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IFileSystem _fileSystem;
- private readonly ILogger _logger;
-
- protected TmdbEpisodeProviderBase(IHttpClientFactory httpClientFactory, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IFileSystem fileSystem, ILocalizationManager localization, ILoggerFactory loggerFactory)
- {
- _httpClientFactory = httpClientFactory;
- _configurationManager = configurationManager;
- _jsonSerializer = jsonSerializer;
- _fileSystem = fileSystem;
- _logger = loggerFactory.CreateLogger();
- }
-
- protected ILogger Logger => _logger;
-
- protected async Task GetEpisodeInfo(
- string seriesTmdbId,
- int season,
- int episodeNumber,
- string preferredMetadataLanguage,
- CancellationToken cancellationToken)
- {
- await EnsureEpisodeInfo(seriesTmdbId, season, episodeNumber, preferredMetadataLanguage, cancellationToken)
- .ConfigureAwait(false);
-
- var dataFilePath = GetDataFilePath(seriesTmdbId, season, episodeNumber, preferredMetadataLanguage);
-
- return _jsonSerializer.DeserializeFromFile(dataFilePath);
- }
-
- internal Task EnsureEpisodeInfo(string tmdbId, int seasonNumber, int episodeNumber, string language, CancellationToken cancellationToken)
- {
- if (string.IsNullOrEmpty(tmdbId))
- {
- throw new ArgumentNullException(nameof(tmdbId));
- }
-
- if (string.IsNullOrEmpty(language))
- {
- throw new ArgumentNullException(nameof(language));
- }
-
- var path = GetDataFilePath(tmdbId, seasonNumber, episodeNumber, language);
-
- var fileInfo = _fileSystem.GetFileSystemInfo(path);
-
- if (fileInfo.Exists)
- {
- // If it's recent or automatic updates are enabled, don't re-download
- if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
- {
- return Task.CompletedTask;
- }
- }
-
- return DownloadEpisodeInfo(tmdbId, seasonNumber, episodeNumber, language, cancellationToken);
- }
-
- internal string GetDataFilePath(string tmdbId, int seasonNumber, int episodeNumber, string preferredLanguage)
- {
- if (string.IsNullOrEmpty(tmdbId))
- {
- throw new ArgumentNullException(nameof(tmdbId));
- }
-
- if (string.IsNullOrEmpty(preferredLanguage))
- {
- throw new ArgumentNullException(nameof(preferredLanguage));
- }
-
- var path = TmdbSeriesProvider.GetSeriesDataPath(_configurationManager.ApplicationPaths, tmdbId);
-
- var filename = string.Format(
- CultureInfo.InvariantCulture,
- "season-{0}-episode-{1}-{2}.json",
- seasonNumber.ToString(CultureInfo.InvariantCulture),
- episodeNumber.ToString(CultureInfo.InvariantCulture),
- preferredLanguage);
-
- return Path.Combine(path, filename);
- }
-
- internal async Task DownloadEpisodeInfo(string id, int seasonNumber, int episodeNumber, string preferredMetadataLanguage, CancellationToken cancellationToken)
- {
- var mainResult = await FetchMainResult(EpisodeUrlPattern, id, seasonNumber, episodeNumber, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
-
- var dataFilePath = GetDataFilePath(id, seasonNumber, episodeNumber, preferredMetadataLanguage);
-
- Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
- _jsonSerializer.SerializeToFile(mainResult, dataFilePath);
- }
-
- internal async Task FetchMainResult(string urlPattern, string id, int seasonNumber, int episodeNumber, string language, CancellationToken cancellationToken)
- {
- var url = string.Format(
- CultureInfo.InvariantCulture,
- urlPattern,
- id,
- seasonNumber.ToString(CultureInfo.InvariantCulture),
- episodeNumber,
- TmdbUtils.ApiKey);
-
- if (!string.IsNullOrEmpty(language))
- {
- url += string.Format(CultureInfo.InvariantCulture, "&language={0}", language);
- }
-
- var includeImageLanguageParam = TmdbMovieProvider.GetImageLanguagesParam(language);
- // Get images in english and with no language
- url += "&include_image_language=" + includeImageLanguageParam;
-
- cancellationToken.ThrowIfCancellationRequested();
-
- using var requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
- foreach (var header in TmdbUtils.AcceptHeaders)
- {
- requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(header));
- }
-
- using var response = await TmdbMovieProvider.Current.GetMovieDbResponse(requestMessage, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
- return await _jsonSerializer.DeserializeFromStreamAsync(stream).ConfigureAwait(false);
- }
-
- protected Task GetResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
- }
- }
-}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonImageProvider.cs
index dcc7f87002..f4ed480aef 100644
--- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonImageProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonImageProvider.cs
@@ -2,7 +2,7 @@
using System;
using System.Collections.Generic;
-using System.IO;
+using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Threading;
@@ -13,29 +13,25 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.General;
-using MediaBrowser.Providers.Plugins.Tmdb.Movies;
namespace MediaBrowser.Providers.Plugins.Tmdb.TV
{
public class TmdbSeasonImageProvider : IRemoteImageProvider, IHasOrder
{
- private readonly IJsonSerializer _jsonSerializer;
private readonly IHttpClientFactory _httpClientFactory;
+ private readonly TmdbClientManager _tmdbClientManager;
- public TmdbSeasonImageProvider(IJsonSerializer jsonSerializer, IHttpClientFactory httpClientFactory)
+ public TmdbSeasonImageProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
{
- _jsonSerializer = jsonSerializer;
_httpClientFactory = httpClientFactory;
+ _tmdbClientManager = tmdbClientManager;
}
public int Order => 1;
- public string Name => ProviderName;
-
- public static string ProviderName => TmdbUtils.ProviderName;
+ public string Name => TmdbUtils.ProviderName;
public Task GetImageResponse(string url, CancellationToken cancellationToken)
{
@@ -45,87 +41,46 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV
public async Task> GetImages(BaseItem item, CancellationToken cancellationToken)
{
var season = (Season)item;
- var series = season.Series;
+ var series = season?.Series;
- var seriesId = series?.GetProviderId(MetadataProvider.Tmdb);
+ var seriesTmdbId = Convert.ToInt32(series?.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
- if (string.IsNullOrEmpty(seriesId))
- {
- return Enumerable.Empty();
- }
-
- var seasonNumber = season.IndexNumber;
-
- if (!seasonNumber.HasValue)
+ if (seriesTmdbId <= 0 || season?.IndexNumber == null)
{
return Enumerable.Empty();
}
var language = item.GetPreferredMetadataLanguage();
- var results = await FetchImages(season, seriesId, language, cancellationToken).ConfigureAwait(false);
+ var seasonResult = await _tmdbClientManager
+ .GetSeasonAsync(seriesTmdbId, season.IndexNumber.Value, language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken)
+ .ConfigureAwait(false);
- var tmdbSettings = await TmdbMovieProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- var list = results.Select(i => new RemoteImageInfo
+ var posters = seasonResult?.Images?.Posters;
+ if (posters == null)
{
- Url = tmdbImageUrl + i.File_Path,
- CommunityRating = i.Vote_Average,
- VoteCount = i.Vote_Count,
- Width = i.Width,
- Height = i.Height,
- Language = TmdbMovieProvider.AdjustImageLanguage(i.Iso_639_1, language),
- ProviderName = Name,
- Type = ImageType.Primary,
- RatingType = RatingType.Score
- });
-
- var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
-
- return list.OrderByDescending(i =>
- {
- if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
-
- if (!isLanguageEn)
- {
- if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 2;
- }
- }
-
- if (string.IsNullOrEmpty(i.Language))
- {
- return isLanguageEn ? 3 : 2;
- }
-
- return 0;
- })
- .ThenByDescending(i => i.CommunityRating ?? 0)
- .ThenByDescending(i => i.VoteCount ?? 0);
- }
-
- private async Task> FetchImages(Season item, string tmdbId, string language, CancellationToken cancellationToken)
- {
- var seasonNumber = item.IndexNumber.GetValueOrDefault();
- await TmdbSeasonProvider.Current.EnsureSeasonInfo(tmdbId, seasonNumber, language, cancellationToken).ConfigureAwait(false);
-
- var path = TmdbSeasonProvider.Current.GetDataFilePath(tmdbId, seasonNumber, language);
-
- if (!string.IsNullOrEmpty(path))
- {
- if (File.Exists(path))
- {
- return _jsonSerializer.DeserializeFromFile(path).Images.Posters;
- }
+ return Enumerable.Empty();
}
- return null;
+ var remoteImages = new RemoteImageInfo[posters.Count];
+ for (var i = 0; i < posters.Count; i++)
+ {
+ var image = posters[i];
+ remoteImages[i] = new RemoteImageInfo
+ {
+ Url = _tmdbClientManager.GetPosterUrl(image.FilePath),
+ CommunityRating = image.VoteAverage,
+ VoteCount = image.VoteCount,
+ Width = image.Width,
+ Height = image.Height,
+ Language = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, language),
+ ProviderName = Name,
+ Type = ImageType.Primary,
+ RatingType = RatingType.Score
+ };
+ }
+
+ return remoteImages.OrderByLanguageDescending(language);
}
public IEnumerable GetSupportedImages(BaseItem item)
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonProvider.cs
index c9b257fcc2..6ca462474a 100644
--- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonProvider.cs
@@ -3,53 +3,28 @@
using System;
using System.Collections.Generic;
using System.Globalization;
-using System.IO;
-using System.Net;
+using System.Linq;
using System.Net.Http;
-using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Net;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.TV;
-using MediaBrowser.Providers.Plugins.Tmdb.Movies;
-using Microsoft.Extensions.Logging;
-using Season = MediaBrowser.Controller.Entities.TV.Season;
namespace MediaBrowser.Providers.Plugins.Tmdb.TV
{
public class TmdbSeasonProvider : IRemoteMetadataProvider
{
- private const string GetTvInfo3 = TmdbUtils.BaseTmdbApiUrl + @"3/tv/{0}/season/{1}?api_key={2}&append_to_response=images,keywords,external_ids,credits,videos";
-
private readonly IHttpClientFactory _httpClientFactory;
- private readonly IServerConfigurationManager _configurationManager;
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IFileSystem _fileSystem;
- private readonly ILogger _logger;
+ private readonly TmdbClientManager _tmdbClientManager;
- internal static TmdbSeasonProvider Current { get; private set; }
-
- public TmdbSeasonProvider(
- IHttpClientFactory httpClientFactory,
- IServerConfigurationManager configurationManager,
- IFileSystem fileSystem,
- IJsonSerializer jsonSerializer,
- ILogger logger)
+ public TmdbSeasonProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
{
_httpClientFactory = httpClientFactory;
- _configurationManager = configurationManager;
- _fileSystem = fileSystem;
- _jsonSerializer = jsonSerializer;
- _logger = logger;
- Current = this;
+ _tmdbClientManager = tmdbClientManager;
}
public string Name => TmdbUtils.ProviderName;
@@ -62,180 +37,86 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV
var seasonNumber = info.IndexNumber;
- if (!string.IsNullOrWhiteSpace(seriesTmdbId) && seasonNumber.HasValue)
+ if (string.IsNullOrWhiteSpace(seriesTmdbId) || !seasonNumber.HasValue)
{
- try
+ return result;
+ }
+
+ var seasonResult = await _tmdbClientManager
+ .GetSeasonAsync(Convert.ToInt32(seriesTmdbId, CultureInfo.InvariantCulture), seasonNumber.Value, info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken)
+ .ConfigureAwait(false);
+
+ if (seasonResult == null)
+ {
+ return result;
+ }
+
+ result.HasMetadata = true;
+ result.Item = new Season
+ {
+ Name = info.Name,
+ IndexNumber = seasonNumber,
+ Overview = seasonResult?.Overview
+ };
+
+ if (!string.IsNullOrEmpty(seasonResult.ExternalIds?.TvdbId))
+ {
+ result.Item.SetProviderId(MetadataProvider.Tvdb, seasonResult.ExternalIds.TvdbId);
+ }
+
+ // TODO why was this disabled?
+ var credits = seasonResult.Credits;
+ if (credits?.Cast != null)
+ {
+ var cast = credits.Cast.OrderBy(c => c.Order).Take(TmdbUtils.MaxCastMembers).ToList();
+ for (var i = 0; i < cast.Count; i++)
{
- var seasonInfo = await GetSeasonInfo(seriesTmdbId, seasonNumber.Value, info.MetadataLanguage, cancellationToken)
- .ConfigureAwait(false);
-
- result.HasMetadata = true;
- result.Item = new Season();
-
- // Don't use moviedb season names for now until if/when we have field-level configuration
- // result.Item.Name = seasonInfo.name;
-
- result.Item.Name = info.Name;
-
- result.Item.IndexNumber = seasonNumber;
-
- result.Item.Overview = seasonInfo.Overview;
-
- if (seasonInfo.External_Ids != null && seasonInfo.External_Ids.Tvdb_Id > 0)
+ result.AddPerson(new PersonInfo
{
- result.Item.SetProviderId(MetadataProvider.Tvdb, seasonInfo.External_Ids.Tvdb_Id.Value.ToString(CultureInfo.InvariantCulture));
- }
-
- var credits = seasonInfo.Credits;
- if (credits != null)
- {
- // Actors, Directors, Writers - all in People
- // actors come from cast
- if (credits.Cast != null)
- {
- // foreach (var actor in credits.cast.OrderBy(a => a.order)) result.Item.AddPerson(new PersonInfo { Name = actor.name.Trim(), Role = actor.character, Type = PersonType.Actor, SortOrder = actor.order });
- }
-
- // and the rest from crew
- if (credits.Crew != null)
- {
- // foreach (var person in credits.crew) result.Item.AddPerson(new PersonInfo { Name = person.name.Trim(), Role = person.job, Type = person.department });
- }
- }
-
- result.Item.PremiereDate = seasonInfo.Air_Date;
- result.Item.ProductionYear = result.Item.PremiereDate.Value.Year;
- }
- catch (HttpException ex)
- {
- _logger.LogError(ex, "No metadata found for {0}", seasonNumber.Value);
-
- if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
- {
- return result;
- }
-
- throw;
+ Name = cast[i].Name.Trim(),
+ Role = cast[i].Character,
+ Type = PersonType.Actor,
+ SortOrder = cast[i].Order
+ });
}
}
+ if (credits?.Crew != null)
+ {
+ foreach (var person in credits.Crew)
+ {
+ // Normalize this
+ var type = TmdbUtils.MapCrewToPersonType(person);
+
+ if (!TmdbUtils.WantedCrewTypes.Contains(type, StringComparer.OrdinalIgnoreCase)
+ && !TmdbUtils.WantedCrewTypes.Contains(person.Job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
+ {
+ continue;
+ }
+
+ result.AddPerson(new PersonInfo
+ {
+ Name = person.Name.Trim(),
+ Role = person.Job,
+ Type = type
+ });
+ }
+ }
+
+ result.Item.PremiereDate = seasonResult.AirDate;
+ result.Item.ProductionYear = seasonResult.AirDate?.Year;
+
return result;
}
public Task> GetSearchResults(SeasonInfo searchInfo, CancellationToken cancellationToken)
{
- return Task.FromResult>(new List());
+ return Task.FromResult(Enumerable.Empty());
}
public Task GetImageResponse(string url, CancellationToken cancellationToken)
{
return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
}
-
- private async Task GetSeasonInfo(
- string seriesTmdbId,
- int season,
- string preferredMetadataLanguage,
- CancellationToken cancellationToken)
- {
- await EnsureSeasonInfo(seriesTmdbId, season, preferredMetadataLanguage, cancellationToken)
- .ConfigureAwait(false);
-
- var dataFilePath = GetDataFilePath(seriesTmdbId, season, preferredMetadataLanguage);
-
- return _jsonSerializer.DeserializeFromFile(dataFilePath);
- }
-
- internal Task EnsureSeasonInfo(string tmdbId, int seasonNumber, string language, CancellationToken cancellationToken)
- {
- if (string.IsNullOrEmpty(tmdbId))
- {
- throw new ArgumentNullException(nameof(tmdbId));
- }
-
- if (string.IsNullOrEmpty(language))
- {
- throw new ArgumentNullException(nameof(language));
- }
-
- var path = GetDataFilePath(tmdbId, seasonNumber, language);
-
- var fileInfo = _fileSystem.GetFileSystemInfo(path);
-
- if (fileInfo.Exists)
- {
- // If it's recent or automatic updates are enabled, don't re-download
- if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
- {
- return Task.CompletedTask;
- }
- }
-
- return DownloadSeasonInfo(tmdbId, seasonNumber, language, cancellationToken);
- }
-
- internal string GetDataFilePath(string tmdbId, int seasonNumber, string preferredLanguage)
- {
- if (string.IsNullOrEmpty(tmdbId))
- {
- throw new ArgumentNullException(nameof(tmdbId));
- }
-
- if (string.IsNullOrEmpty(preferredLanguage))
- {
- throw new ArgumentNullException(nameof(preferredLanguage));
- }
-
- var path = TmdbSeriesProvider.GetSeriesDataPath(_configurationManager.ApplicationPaths, tmdbId);
-
- var filename = string.Format(
- CultureInfo.InvariantCulture,
- "season-{0}-{1}.json",
- seasonNumber.ToString(CultureInfo.InvariantCulture),
- preferredLanguage);
-
- return Path.Combine(path, filename);
- }
-
- internal async Task DownloadSeasonInfo(string id, int seasonNumber, string preferredMetadataLanguage, CancellationToken cancellationToken)
- {
- var mainResult = await FetchMainResult(id, seasonNumber, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
-
- var dataFilePath = GetDataFilePath(id, seasonNumber, preferredMetadataLanguage);
-
- Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
- _jsonSerializer.SerializeToFile(mainResult, dataFilePath);
- }
-
- internal async Task FetchMainResult(string id, int seasonNumber, string language, CancellationToken cancellationToken)
- {
- var url = string.Format(
- CultureInfo.InvariantCulture,
- GetTvInfo3,
- id,
- seasonNumber.ToString(CultureInfo.InvariantCulture),
- TmdbUtils.ApiKey);
-
- if (!string.IsNullOrEmpty(language))
- {
- url += string.Format(CultureInfo.InvariantCulture, "&language={0}", TmdbMovieProvider.NormalizeLanguage(language));
- }
-
- var includeImageLanguageParam = TmdbMovieProvider.GetImageLanguagesParam(language);
- // Get images in english and with no language
- url += "&include_image_language=" + includeImageLanguageParam;
-
- cancellationToken.ThrowIfCancellationRequested();
-
- using var requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
- foreach (var header in TmdbUtils.AcceptHeaders)
- {
- requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(header));
- }
-
- using var response = await TmdbMovieProvider.Current.GetMovieDbResponse(requestMessage, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
- return await _jsonSerializer.DeserializeFromStreamAsync(stream).ConfigureAwait(false);
- }
}
}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs
index 179ceb825d..d0c6b8b886 100644
--- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs
@@ -2,7 +2,7 @@
using System;
using System.Collections.Generic;
-using System.IO;
+using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Threading;
@@ -13,28 +13,23 @@ using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.General;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.TV;
-using MediaBrowser.Providers.Plugins.Tmdb.Movies;
namespace MediaBrowser.Providers.Plugins.Tmdb.TV
{
public class TmdbSeriesImageProvider : IRemoteImageProvider, IHasOrder
{
- private readonly IJsonSerializer _jsonSerializer;
private readonly IHttpClientFactory _httpClientFactory;
+ private readonly TmdbClientManager _tmdbClientManager;
- public TmdbSeriesImageProvider(IJsonSerializer jsonSerializer, IHttpClientFactory httpClientFactory)
+ public TmdbSeriesImageProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager)
{
- _jsonSerializer = jsonSerializer;
_httpClientFactory = httpClientFactory;
+ _tmdbClientManager = tmdbClientManager;
}
- public string Name => ProviderName;
-
- public static string ProviderName => TmdbUtils.ProviderName;
+ public string Name => TmdbUtils.ProviderName;
// After tvdb and fanart
public int Order => 2;
@@ -54,107 +49,6 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV
}
public async Task> GetImages(BaseItem item, CancellationToken cancellationToken)
- {
- var list = new List();
-
- var results = await FetchImages(item, null, cancellationToken).ConfigureAwait(false);
-
- if (results == null)
- {
- return list;
- }
-
- var tmdbSettings = await TmdbMovieProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
-
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- var language = item.GetPreferredMetadataLanguage();
-
- list.AddRange(GetPosters(results).Select(i => new RemoteImageInfo
- {
- Url = tmdbImageUrl + i.File_Path,
- CommunityRating = i.Vote_Average,
- VoteCount = i.Vote_Count,
- Width = i.Width,
- Height = i.Height,
- Language = TmdbMovieProvider.AdjustImageLanguage(i.Iso_639_1, language),
- ProviderName = Name,
- Type = ImageType.Primary,
- RatingType = RatingType.Score
- }));
-
- list.AddRange(GetBackdrops(results).Select(i => new RemoteImageInfo
- {
- Url = tmdbImageUrl + i.File_Path,
- CommunityRating = i.Vote_Average,
- VoteCount = i.Vote_Count,
- Width = i.Width,
- Height = i.Height,
- ProviderName = Name,
- Type = ImageType.Backdrop,
- RatingType = RatingType.Score
- }));
-
- var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
-
- return list.OrderByDescending(i =>
- {
- if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 3;
- }
-
- if (!isLanguageEn)
- {
- if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
- {
- return 2;
- }
- }
-
- if (string.IsNullOrEmpty(i.Language))
- {
- return isLanguageEn ? 3 : 2;
- }
-
- return 0;
- })
- .ThenByDescending(i => i.CommunityRating ?? 0)
- .ThenByDescending(i => i.VoteCount ?? 0);
- }
-
- ///
- /// Gets the posters.
- ///
- /// The images.
- private IEnumerable GetPosters(Images images)
- {
- return images.Posters ?? new List();
- }
-
- ///
- /// Gets the backdrops.
- ///
- /// The images.
- private IEnumerable GetBackdrops(Images images)
- {
- var eligibleBackdrops = images.Backdrops ?? new List();
-
- return eligibleBackdrops.OrderByDescending(i => i.Vote_Average)
- .ThenByDescending(i => i.Vote_Count);
- }
-
- ///
- /// Fetches the images.
- ///
- /// The item.
- /// The language.
- /// The cancellation token.
- /// Task{MovieImages}.
- private async Task FetchImages(
- BaseItem item,
- string language,
- CancellationToken cancellationToken)
{
var tmdbId = item.GetProviderId(MetadataProvider.Tmdb);
@@ -163,16 +57,56 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV
return null;
}
- await TmdbSeriesProvider.Current.EnsureSeriesInfo(tmdbId, language, cancellationToken).ConfigureAwait(false);
+ var language = item.GetPreferredMetadataLanguage();
- var path = TmdbSeriesProvider.Current.GetDataFilePath(tmdbId, language);
+ var series = await _tmdbClientManager
+ .GetSeriesAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken)
+ .ConfigureAwait(false);
- if (!string.IsNullOrEmpty(path) && File.Exists(path))
+ if (series?.Images == null)
{
- return _jsonSerializer.DeserializeFromFile(path).Images;
+ return Enumerable.Empty();
}
- return null;
+ var posters = series.Images.Posters;
+ var backdrops = series.Images.Backdrops;
+
+ var remoteImages = new RemoteImageInfo[posters.Count + backdrops.Count];
+
+ for (var i = 0; i < posters.Count; i++)
+ {
+ var poster = posters[i];
+ remoteImages[i] = new RemoteImageInfo
+ {
+ Url = _tmdbClientManager.GetPosterUrl(poster.FilePath),
+ CommunityRating = poster.VoteAverage,
+ VoteCount = poster.VoteCount,
+ Width = poster.Width,
+ Height = poster.Height,
+ Language = TmdbUtils.AdjustImageLanguage(poster.Iso_639_1, language),
+ ProviderName = Name,
+ Type = ImageType.Primary,
+ RatingType = RatingType.Score
+ };
+ }
+
+ for (var i = 0; i < backdrops.Count; i++)
+ {
+ var backdrop = series.Images.Backdrops[i];
+ remoteImages[posters.Count + i] = new RemoteImageInfo
+ {
+ Url = _tmdbClientManager.GetBackdropUrl(backdrop.FilePath),
+ CommunityRating = backdrop.VoteAverage,
+ VoteCount = backdrop.VoteCount,
+ Width = backdrop.Width,
+ Height = backdrop.Height,
+ ProviderName = Name,
+ Type = ImageType.Backdrop,
+ RatingType = RatingType.Score
+ };
+ }
+
+ return remoteImages.OrderByLanguageDescending(language);
}
public Task GetImageResponse(string url, CancellationToken cancellationToken)
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs
index 287ebca8c9..942c85b90d 100644
--- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs
@@ -3,107 +3,81 @@
using System;
using System.Collections.Generic;
using System.Globalization;
-using System.IO;
using System.Linq;
using System.Net.Http;
-using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Providers;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.Search;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.TV;
-using MediaBrowser.Providers.Plugins.Tmdb.Movies;
-using Microsoft.Extensions.Logging;
+using TMDbLib.Objects.Find;
+using TMDbLib.Objects.Search;
+using TMDbLib.Objects.TvShows;
namespace MediaBrowser.Providers.Plugins.Tmdb.TV
{
public class TmdbSeriesProvider : IRemoteMetadataProvider, IHasOrder
{
- private const string GetTvInfo3 = TmdbUtils.BaseTmdbApiUrl + @"3/tv/{0}?api_key={1}&append_to_response=credits,images,keywords,external_ids,videos,content_ratings";
-
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IServerConfigurationManager _configurationManager;
- private readonly ILogger _logger;
private readonly IHttpClientFactory _httpClientFactory;
- private readonly ILibraryManager _libraryManager;
-
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
+ private readonly TmdbClientManager _tmdbClientManager;
public TmdbSeriesProvider(
- IJsonSerializer jsonSerializer,
- IServerConfigurationManager configurationManager,
- ILogger logger,
IHttpClientFactory httpClientFactory,
- ILibraryManager libraryManager)
+ TmdbClientManager tmdbClientManager)
{
- _jsonSerializer = jsonSerializer;
- _configurationManager = configurationManager;
- _logger = logger;
_httpClientFactory = httpClientFactory;
- _libraryManager = libraryManager;
+ _tmdbClientManager = tmdbClientManager;
Current = this;
}
- internal static TmdbSeriesProvider Current { get; private set; }
-
public string Name => TmdbUtils.ProviderName;
// After TheTVDB
public int Order => 1;
+ internal static TmdbSeriesProvider Current { get; private set; }
+
public async Task> GetSearchResults(SeriesInfo searchInfo, CancellationToken cancellationToken)
{
var tmdbId = searchInfo.GetProviderId(MetadataProvider.Tmdb);
if (!string.IsNullOrEmpty(tmdbId))
{
- cancellationToken.ThrowIfCancellationRequested();
+ var series = await _tmdbClientManager
+ .GetSeriesAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), searchInfo.MetadataLanguage, searchInfo.MetadataLanguage, cancellationToken)
+ .ConfigureAwait(false);
- await EnsureSeriesInfo(tmdbId, searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false);
-
- var dataFilePath = GetDataFilePath(tmdbId, searchInfo.MetadataLanguage);
-
- var obj = _jsonSerializer.DeserializeFromFile(dataFilePath);
-
- var tmdbSettings = await TmdbMovieProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
-
- var remoteResult = new RemoteSearchResult
+ if (series != null)
{
- Name = obj.Name,
- SearchProviderName = Name,
- ImageUrl = string.IsNullOrWhiteSpace(obj.Poster_Path) ? null : tmdbImageUrl + obj.Poster_Path
- };
+ var remoteResult = MapTvShowToRemoteSearchResult(series);
- remoteResult.SetProviderId(MetadataProvider.Tmdb, obj.Id.ToString(_usCulture));
- remoteResult.SetProviderId(MetadataProvider.Imdb, obj.External_Ids.Imdb_Id);
-
- if (obj.External_Ids != null && obj.External_Ids.Tvdb_Id > 0)
- {
- remoteResult.SetProviderId(MetadataProvider.Tvdb, obj.External_Ids.Tvdb_Id.Value.ToString(_usCulture));
+ return new[] { remoteResult };
}
-
- return new[] { remoteResult };
}
var imdbId = searchInfo.GetProviderId(MetadataProvider.Imdb);
if (!string.IsNullOrEmpty(imdbId))
{
- var searchResult = await FindByExternalId(imdbId, "imdb_id", cancellationToken).ConfigureAwait(false);
+ var findResult = await _tmdbClientManager
+ .FindByExternalIdAsync(imdbId, FindExternalSource.Imdb, searchInfo.MetadataLanguage, cancellationToken)
+ .ConfigureAwait(false);
- if (searchResult != null)
+ var tvResults = findResult?.TvResults;
+ if (tvResults != null)
{
- return new[] { searchResult };
+ var imdbIdResults = new RemoteSearchResult[tvResults.Count];
+ for (var i = 0; i < tvResults.Count; i++)
+ {
+ var remoteResult = MapSearchTvToRemoteSearchResult(tvResults[i]);
+ remoteResult.SetProviderId(MetadataProvider.Imdb, imdbId);
+ imdbIdResults[i] = remoteResult;
+ }
+
+ return imdbIdResults;
}
}
@@ -111,15 +85,80 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV
if (!string.IsNullOrEmpty(tvdbId))
{
- var searchResult = await FindByExternalId(tvdbId, "tvdb_id", cancellationToken).ConfigureAwait(false);
+ var findResult = await _tmdbClientManager
+ .FindByExternalIdAsync(tvdbId, FindExternalSource.TvDb, searchInfo.MetadataLanguage, cancellationToken)
+ .ConfigureAwait(false);
- if (searchResult != null)
+ var tvResults = findResult?.TvResults;
+ if (tvResults != null)
{
- return new[] { searchResult };
+ var tvIdResults = new RemoteSearchResult[tvResults.Count];
+ for (var i = 0; i < tvResults.Count; i++)
+ {
+ var remoteResult = MapSearchTvToRemoteSearchResult(tvResults[i]);
+ remoteResult.SetProviderId(MetadataProvider.Tvdb, tvdbId);
+ tvIdResults[i] = remoteResult;
+ }
+
+ return tvIdResults;
}
}
- return await new TmdbSearch(_logger, _jsonSerializer, _libraryManager).GetSearchResults(searchInfo, cancellationToken).ConfigureAwait(false);
+ var tvSearchResults = await _tmdbClientManager.SearchSeriesAsync(searchInfo.Name, searchInfo.MetadataLanguage, cancellationToken)
+ .ConfigureAwait(false);
+
+ var remoteResults = new RemoteSearchResult[tvSearchResults.Count];
+ for (var i = 0; i < tvSearchResults.Count; i++)
+ {
+ remoteResults[i] = MapSearchTvToRemoteSearchResult(tvSearchResults[i]);
+ }
+
+ return remoteResults;
+ }
+
+ private RemoteSearchResult MapTvShowToRemoteSearchResult(TvShow series)
+ {
+ var remoteResult = new RemoteSearchResult
+ {
+ Name = series.Name ?? series.OriginalName,
+ SearchProviderName = Name,
+ ImageUrl = _tmdbClientManager.GetPosterUrl(series.PosterPath),
+ Overview = series.Overview
+ };
+
+ remoteResult.SetProviderId(MetadataProvider.Tmdb, series.Id.ToString(CultureInfo.InvariantCulture));
+ if (series.ExternalIds != null)
+ {
+ if (!string.IsNullOrEmpty(series.ExternalIds.ImdbId))
+ {
+ remoteResult.SetProviderId(MetadataProvider.Imdb, series.ExternalIds.ImdbId);
+ }
+
+ if (!string.IsNullOrEmpty(series.ExternalIds.TvdbId))
+ {
+ remoteResult.SetProviderId(MetadataProvider.Tvdb, series.ExternalIds.TvdbId);
+ }
+ }
+
+ remoteResult.PremiereDate = series.FirstAirDate?.ToUniversalTime();
+
+ return remoteResult;
+ }
+
+ private RemoteSearchResult MapSearchTvToRemoteSearchResult(SearchTv series)
+ {
+ var remoteResult = new RemoteSearchResult
+ {
+ Name = series.Name ?? series.OriginalName,
+ SearchProviderName = Name,
+ ImageUrl = _tmdbClientManager.GetPosterUrl(series.PosterPath),
+ Overview = series.Overview
+ };
+
+ remoteResult.SetProviderId(MetadataProvider.Tmdb, series.Id.ToString(CultureInfo.InvariantCulture));
+ remoteResult.PremiereDate = series.FirstAirDate?.ToUniversalTime();
+
+ return remoteResult;
}
public async Task> GetMetadata(SeriesInfo info, CancellationToken cancellationToken)
@@ -137,11 +176,11 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV
if (!string.IsNullOrEmpty(imdbId))
{
- var searchResult = await FindByExternalId(imdbId, "imdb_id", cancellationToken).ConfigureAwait(false);
+ var searchResult = await _tmdbClientManager.FindByExternalIdAsync(imdbId, FindExternalSource.Imdb, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);
if (searchResult != null)
{
- tmdbId = searchResult.GetProviderId(MetadataProvider.Tmdb);
+ tmdbId = searchResult.TvResults.FirstOrDefault()?.Id.ToString(CultureInfo.InvariantCulture);
}
}
}
@@ -152,11 +191,11 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV
if (!string.IsNullOrEmpty(tvdbId))
{
- var searchResult = await FindByExternalId(tvdbId, "tvdb_id", cancellationToken).ConfigureAwait(false);
+ var searchResult = await _tmdbClientManager.FindByExternalIdAsync(tvdbId, FindExternalSource.TvDb, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);
if (searchResult != null)
{
- tmdbId = searchResult.GetProviderId(MetadataProvider.Tmdb);
+ tmdbId = searchResult.TvResults.FirstOrDefault()?.Id.ToString(CultureInfo.InvariantCulture);
}
}
}
@@ -164,13 +203,11 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV
if (string.IsNullOrEmpty(tmdbId))
{
result.QueriedById = false;
- var searchResults = await new TmdbSearch(_logger, _jsonSerializer, _libraryManager).GetSearchResults(info, cancellationToken).ConfigureAwait(false);
+ var searchResults = await _tmdbClientManager.SearchSeriesAsync(info.Name, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);
- var searchResult = searchResults.FirstOrDefault();
-
- if (searchResult != null)
+ if (searchResults.Count > 0)
{
- tmdbId = searchResult.GetProviderId(MetadataProvider.Tmdb);
+ tmdbId = searchResults[0].Id.ToString(CultureInfo.InvariantCulture);
}
}
@@ -178,7 +215,20 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV
{
cancellationToken.ThrowIfCancellationRequested();
- result = await FetchMovieData(tmdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false);
+ var tvShow = await _tmdbClientManager
+ .GetSeriesAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken)
+ .ConfigureAwait(false);
+
+ result = new MetadataResult
+ {
+ Item = MapTvShowToSeries(tvShow, info.MetadataCountryCode),
+ ResultLanguage = info.MetadataLanguage ?? tvShow.OriginalLanguage
+ };
+
+ foreach (var person in GetPersons(tvShow))
+ {
+ result.AddPerson(person);
+ }
result.HasMetadata = result.Item != null;
}
@@ -186,99 +236,74 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV
return result;
}
- private async Task> FetchMovieData(string tmdbId, string language, string preferredCountryCode, CancellationToken cancellationToken)
+ private Series MapTvShowToSeries(TvShow seriesResult, string preferredCountryCode)
{
- SeriesResult seriesInfo = await FetchMainResult(tmdbId, language, cancellationToken).ConfigureAwait(false);
-
- if (seriesInfo == null)
+ var series = new Series
{
- return null;
- }
-
- tmdbId = seriesInfo.Id.ToString(_usCulture);
-
- string dataFilePath = GetDataFilePath(tmdbId, language);
- Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
- _jsonSerializer.SerializeToFile(seriesInfo, dataFilePath);
-
- await EnsureSeriesInfo(tmdbId, language, cancellationToken).ConfigureAwait(false);
-
- var result = new MetadataResult
- {
- Item = new Series(),
- ResultLanguage = seriesInfo.ResultLanguage
+ Name = seriesResult.Name,
+ OriginalTitle = seriesResult.OriginalName
};
- var settings = await TmdbMovieProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
+ series.SetProviderId(MetadataProvider.Tmdb, seriesResult.Id.ToString(CultureInfo.InvariantCulture));
- ProcessMainInfo(result, seriesInfo, preferredCountryCode, settings);
+ series.CommunityRating = Convert.ToSingle(seriesResult.VoteAverage);
- return result;
- }
+ series.Overview = seriesResult.Overview;
- private void ProcessMainInfo(MetadataResult seriesResult, SeriesResult seriesInfo, string preferredCountryCode, TmdbSettingsResult settings)
- {
- var series = seriesResult.Item;
-
- series.Name = seriesInfo.Name;
- series.OriginalTitle = seriesInfo.Original_Name;
- series.SetProviderId(MetadataProvider.Tmdb, seriesInfo.Id.ToString(_usCulture));
-
- string voteAvg = seriesInfo.Vote_Average.ToString(CultureInfo.InvariantCulture);
-
- if (float.TryParse(voteAvg, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out float rating))
+ if (seriesResult.Networks != null)
{
- series.CommunityRating = rating;
+ series.Studios = seriesResult.Networks.Select(i => i.Name).ToArray();
}
- series.Overview = seriesInfo.Overview;
-
- if (seriesInfo.Networks != null)
+ if (seriesResult.Genres != null)
{
- series.Studios = seriesInfo.Networks.Select(i => i.Name).ToArray();
+ series.Genres = seriesResult.Genres.Select(i => i.Name).ToArray();
}
- if (seriesInfo.Genres != null)
+ if (seriesResult.Keywords?.Results != null)
{
- series.Genres = seriesInfo.Genres.Select(i => i.Name).ToArray();
+ for (var i = 0; i < seriesResult.Keywords.Results.Count; i++)
+ {
+ series.AddTag(seriesResult.Keywords.Results[i].Name);
+ }
}
- series.HomePageUrl = seriesInfo.Homepage;
+ series.HomePageUrl = seriesResult.Homepage;
- series.RunTimeTicks = seriesInfo.Episode_Run_Time.Select(i => TimeSpan.FromMinutes(i).Ticks).FirstOrDefault();
+ series.RunTimeTicks = seriesResult.EpisodeRunTime.Select(i => TimeSpan.FromMinutes(i).Ticks).FirstOrDefault();
- if (string.Equals(seriesInfo.Status, "Ended", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(seriesResult.Status, "Ended", StringComparison.OrdinalIgnoreCase))
{
series.Status = SeriesStatus.Ended;
- series.EndDate = seriesInfo.Last_Air_Date;
+ series.EndDate = seriesResult.LastAirDate;
}
else
{
series.Status = SeriesStatus.Continuing;
}
- series.PremiereDate = seriesInfo.First_Air_Date;
+ series.PremiereDate = seriesResult.FirstAirDate;
- var ids = seriesInfo.External_Ids;
+ var ids = seriesResult.ExternalIds;
if (ids != null)
{
- if (!string.IsNullOrWhiteSpace(ids.Imdb_Id))
+ if (!string.IsNullOrWhiteSpace(ids.ImdbId))
{
- series.SetProviderId(MetadataProvider.Imdb, ids.Imdb_Id);
+ series.SetProviderId(MetadataProvider.Imdb, ids.ImdbId);
}
- if (ids.Tvrage_Id > 0)
+ if (!string.IsNullOrEmpty(ids.TvrageId))
{
- series.SetProviderId(MetadataProvider.TvRage, ids.Tvrage_Id.Value.ToString(_usCulture));
+ series.SetProviderId(MetadataProvider.TvRage, ids.TvrageId);
}
- if (ids.Tvdb_Id > 0)
+ if (!string.IsNullOrEmpty(ids.TvdbId))
{
- series.SetProviderId(MetadataProvider.Tvdb, ids.Tvdb_Id.Value.ToString(_usCulture));
+ series.SetProviderId(MetadataProvider.Tvdb, ids.TvdbId);
}
}
- var contentRatings = (seriesInfo.Content_Ratings ?? new ContentRatings()).Results ?? new List();
+ var contentRatings = seriesResult.ContentRatings.Results ?? new List();
var ourRelease = contentRatings.FirstOrDefault(c => string.Equals(c.Iso_3166_1, preferredCountryCode, StringComparison.OrdinalIgnoreCase));
var usRelease = contentRatings.FirstOrDefault(c => string.Equals(c.Iso_3166_1, "US", StringComparison.OrdinalIgnoreCase));
@@ -297,254 +322,72 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV
series.OfficialRating = minimumRelease.Rating;
}
- if (seriesInfo.Videos != null && seriesInfo.Videos.Results != null)
+ if (seriesResult.Videos?.Results != null)
{
- foreach (var video in seriesInfo.Videos.Results)
+ foreach (var video in seriesResult.Videos.Results)
{
- if ((video.Type.Equals("trailer", StringComparison.OrdinalIgnoreCase)
- || video.Type.Equals("clip", StringComparison.OrdinalIgnoreCase))
- && video.Site.Equals("youtube", StringComparison.OrdinalIgnoreCase))
+ if (TmdbUtils.IsTrailerType(video))
{
- series.AddTrailerUrl($"http://www.youtube.com/watch?v={video.Key}");
+ series.AddTrailerUrl("https://www.youtube.com/watch?v=" + video.Key);
}
}
}
- seriesResult.ResetPeople();
- var tmdbImageUrl = settings.images.GetImageUrl("original");
+ return series;
+ }
- if (seriesInfo.Credits != null)
+ private IEnumerable GetPersons(TvShow seriesResult)
+ {
+ if (seriesResult.Credits?.Cast != null)
{
- if (seriesInfo.Credits.Cast != null)
+ foreach (var actor in seriesResult.Credits.Cast.OrderBy(a => a.Order).Take(TmdbUtils.MaxCastMembers))
{
- foreach (var actor in seriesInfo.Credits.Cast.OrderBy(a => a.Order))
+ var personInfo = new PersonInfo
{
- var personInfo = new PersonInfo
- {
- Name = actor.Name.Trim(),
- Role = actor.Character,
- Type = PersonType.Actor,
- SortOrder = actor.Order
- };
-
- if (!string.IsNullOrWhiteSpace(actor.Profile_Path))
- {
- personInfo.ImageUrl = tmdbImageUrl + actor.Profile_Path;
- }
-
- if (actor.Id > 0)
- {
- personInfo.SetProviderId(MetadataProvider.Tmdb, actor.Id.ToString(CultureInfo.InvariantCulture));
- }
-
- seriesResult.AddPerson(personInfo);
- }
- }
-
- if (seriesInfo.Credits.Crew != null)
- {
- var keepTypes = new[]
- {
- PersonType.Director,
- PersonType.Writer,
- PersonType.Producer
+ Name = actor.Name.Trim(),
+ Role = actor.Character,
+ Type = PersonType.Actor,
+ SortOrder = actor.Order,
+ ImageUrl = _tmdbClientManager.GetPosterUrl(actor.ProfilePath)
};
- foreach (var person in seriesInfo.Credits.Crew)
+ if (actor.Id > 0)
{
- // Normalize this
- var type = TmdbUtils.MapCrewToPersonType(person);
-
- if (!keepTypes.Contains(type, StringComparer.OrdinalIgnoreCase)
- && !keepTypes.Contains(person.Job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
- {
- continue;
- }
-
- seriesResult.AddPerson(new PersonInfo
- {
- Name = person.Name.Trim(),
- Role = person.Job,
- Type = type
- });
+ personInfo.SetProviderId(MetadataProvider.Tmdb, actor.Id.ToString(CultureInfo.InvariantCulture));
}
- }
- }
- }
- internal static string GetSeriesDataPath(IApplicationPaths appPaths, string tmdbId)
- {
- var dataPath = GetSeriesDataPath(appPaths);
-
- return Path.Combine(dataPath, tmdbId);
- }
-
- internal static string GetSeriesDataPath(IApplicationPaths appPaths)
- {
- var dataPath = Path.Combine(appPaths.CachePath, "tmdb-tv");
-
- return dataPath;
- }
-
- internal async Task DownloadSeriesInfo(string id, string preferredMetadataLanguage, CancellationToken cancellationToken)
- {
- SeriesResult mainResult = await FetchMainResult(id, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
-
- if (mainResult == null)
- {
- return;
- }
-
- var dataFilePath = GetDataFilePath(id, preferredMetadataLanguage);
-
- Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
-
- _jsonSerializer.SerializeToFile(mainResult, dataFilePath);
- }
-
- internal async Task FetchMainResult(string id, string language, CancellationToken cancellationToken)
- {
- var url = string.Format(CultureInfo.InvariantCulture, GetTvInfo3, id, TmdbUtils.ApiKey);
-
- if (!string.IsNullOrEmpty(language))
- {
- url += "&language=" + TmdbMovieProvider.NormalizeLanguage(language)
- + "&include_image_language=" + TmdbMovieProvider.GetImageLanguagesParam(language); // Get images in english and with no language
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- using var mainRequestMessage = new HttpRequestMessage(HttpMethod.Get, url);
- foreach (var header in TmdbUtils.AcceptHeaders)
- {
- mainRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(header));
- }
-
- using var mainResponse = await TmdbMovieProvider.Current.GetMovieDbResponse(mainRequestMessage, cancellationToken).ConfigureAwait(false);
- await using var mainStream = await mainResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
- var mainResult = await _jsonSerializer.DeserializeFromStreamAsync(mainStream).ConfigureAwait(false);
-
- if (!string.IsNullOrEmpty(language))
- {
- mainResult.ResultLanguage = language;
- }
-
- cancellationToken.ThrowIfCancellationRequested();
-
- // If the language preference isn't english, then have the overview fallback to english if it's blank
- if (mainResult != null &&
- string.IsNullOrEmpty(mainResult.Overview) &&
- !string.IsNullOrEmpty(language) &&
- !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
- {
- _logger.LogInformation("MovieDbSeriesProvider couldn't find meta for language {Language}. Trying English...", language);
-
- url = string.Format(CultureInfo.InvariantCulture, GetTvInfo3, id, TmdbUtils.ApiKey) + "&language=en";
-
- if (!string.IsNullOrEmpty(language))
- {
- // Get images in english and with no language
- url += "&include_image_language=" + TmdbMovieProvider.GetImageLanguagesParam(language);
- }
-
- using var requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
- foreach (var header in TmdbUtils.AcceptHeaders)
- {
- mainRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(header));
- }
-
- using var response = await TmdbMovieProvider.Current.GetMovieDbResponse(requestMessage, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
- var englishResult = await _jsonSerializer.DeserializeFromStreamAsync(stream).ConfigureAwait(false);
-
- mainResult.Overview = englishResult.Overview;
- mainResult.ResultLanguage = "en";
- }
-
- return mainResult;
- }
-
- internal Task EnsureSeriesInfo(string tmdbId, string language, CancellationToken cancellationToken)
- {
- if (string.IsNullOrEmpty(tmdbId))
- {
- throw new ArgumentNullException(nameof(tmdbId));
- }
-
- var path = GetDataFilePath(tmdbId, language);
-
- var fileInfo = new FileInfo(path);
- if (fileInfo.Exists)
- {
- // If it's recent or automatic updates are enabled, don't re-download
- if ((DateTime.UtcNow - fileInfo.LastWriteTimeUtc).TotalDays <= 2)
- {
- return Task.CompletedTask;
+ yield return personInfo;
}
}
- return DownloadSeriesInfo(tmdbId, language, cancellationToken);
- }
-
- internal string GetDataFilePath(string tmdbId, string preferredLanguage)
- {
- if (string.IsNullOrEmpty(tmdbId))
+ if (seriesResult.Credits?.Crew != null)
{
- throw new ArgumentNullException(nameof(tmdbId));
- }
-
- var path = GetSeriesDataPath(_configurationManager.ApplicationPaths, tmdbId);
-
- var filename = string.Format(CultureInfo.InvariantCulture, "series-{0}.json", preferredLanguage ?? string.Empty);
-
- return Path.Combine(path, filename);
- }
-
- private async Task FindByExternalId(string id, string externalSource, CancellationToken cancellationToken)
- {
- var url = string.Format(
- CultureInfo.InvariantCulture,
- TmdbUtils.BaseTmdbApiUrl + @"3/find/{0}?api_key={1}&external_source={2}",
- id,
- TmdbUtils.ApiKey,
- externalSource);
-
- using var requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
- foreach (var header in TmdbUtils.AcceptHeaders)
- {
- requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(header));
- }
-
- using var response = await TmdbMovieProvider.Current.GetMovieDbResponse(requestMessage, cancellationToken).ConfigureAwait(false);
- await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
-
- var result = await _jsonSerializer.DeserializeFromStreamAsync(stream).ConfigureAwait(false);
-
- if (result != null && result.Tv_Results != null)
- {
- var tv = result.Tv_Results.FirstOrDefault();
-
- if (tv != null)
+ var keepTypes = new[]
{
- var tmdbSettings = await TmdbMovieProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
- var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
+ PersonType.Director,
+ PersonType.Writer,
+ PersonType.Producer
+ };
- var remoteResult = new RemoteSearchResult
+ foreach (var person in seriesResult.Credits.Crew)
+ {
+ // Normalize this
+ var type = TmdbUtils.MapCrewToPersonType(person);
+
+ if (!keepTypes.Contains(type, StringComparer.OrdinalIgnoreCase)
+ && !keepTypes.Contains(person.Job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
{
- Name = tv.Name,
- SearchProviderName = Name,
- ImageUrl = string.IsNullOrWhiteSpace(tv.Poster_Path)
- ? null
- : tmdbImageUrl + tv.Poster_Path
+ continue;
+ }
+
+ yield return new PersonInfo
+ {
+ Name = person.Name.Trim(),
+ Role = person.Job,
+ Type = type
};
-
- remoteResult.SetProviderId(MetadataProvider.Tmdb, tv.Id.ToString(_usCulture));
-
- return remoteResult;
}
}
-
- return null;
}
public Task GetImageResponse(string url, CancellationToken cancellationToken)
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs
new file mode 100644
index 0000000000..2dc5cd55da
--- /dev/null
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs
@@ -0,0 +1,469 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.Extensions.Caching.Memory;
+using TMDbLib.Client;
+using TMDbLib.Objects.Collections;
+using TMDbLib.Objects.Find;
+using TMDbLib.Objects.General;
+using TMDbLib.Objects.Movies;
+using TMDbLib.Objects.People;
+using TMDbLib.Objects.Search;
+using TMDbLib.Objects.TvShows;
+
+namespace MediaBrowser.Providers.Plugins.Tmdb
+{
+ ///
+ /// Manager class for abstracting the TMDb API client library.
+ ///
+ public class TmdbClientManager
+ {
+ private const int CacheDurationInHours = 1;
+
+ private readonly IMemoryCache _memoryCache;
+ private readonly TMDbClient _tmDbClient;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// An instance of .
+ public TmdbClientManager(IMemoryCache memoryCache)
+ {
+ _memoryCache = memoryCache;
+ _tmDbClient = new TMDbClient(TmdbUtils.ApiKey);
+ // Not really interested in NotFoundException
+ _tmDbClient.ThrowApiExceptions = false;
+ }
+
+ ///
+ /// Gets a movie from the TMDb API based on its TMDb id.
+ ///
+ /// The movie's TMDb id.
+ /// The movie's language.
+ /// A comma-separated list of image languages.
+ /// The cancellation token.
+ /// The TMDb movie or null if not found.
+ public async Task GetMovieAsync(int tmdbId, string language, string imageLanguages, CancellationToken cancellationToken)
+ {
+ var key = $"movie-{tmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
+ if (_memoryCache.TryGetValue(key, out Movie movie))
+ {
+ return movie;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ movie = await _tmDbClient.GetMovieAsync(
+ tmdbId,
+ TmdbUtils.NormalizeLanguage(language),
+ imageLanguages,
+ MovieMethods.Credits | MovieMethods.Releases | MovieMethods.Images | MovieMethods.Keywords | MovieMethods.Videos,
+ cancellationToken).ConfigureAwait(false);
+
+ if (movie != null)
+ {
+ _memoryCache.Set(key, movie, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return movie;
+ }
+
+ ///
+ /// Gets a collection from the TMDb API based on its TMDb id.
+ ///
+ /// The collection's TMDb id.
+ /// The collection's language.
+ /// A comma-separated list of image languages.
+ /// The cancellation token.
+ /// The TMDb collection or null if not found.
+ public async Task GetCollectionAsync(int tmdbId, string language, string imageLanguages, CancellationToken cancellationToken)
+ {
+ var key = $"collection-{tmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
+ if (_memoryCache.TryGetValue(key, out Collection collection))
+ {
+ return collection;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ collection = await _tmDbClient.GetCollectionAsync(
+ tmdbId,
+ TmdbUtils.NormalizeLanguage(language),
+ imageLanguages,
+ CollectionMethods.Images,
+ cancellationToken).ConfigureAwait(false);
+
+ if (collection != null)
+ {
+ _memoryCache.Set(key, collection, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return collection;
+ }
+
+ ///
+ /// Gets a tv show from the TMDb API based on its TMDb id.
+ ///
+ /// The tv show's TMDb id.
+ /// The tv show's language.
+ /// A comma-separated list of image languages.
+ /// The cancellation token.
+ /// The TMDb tv show information or null if not found.
+ public async Task GetSeriesAsync(int tmdbId, string language, string imageLanguages, CancellationToken cancellationToken)
+ {
+ var key = $"series-{tmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
+ if (_memoryCache.TryGetValue(key, out TvShow series))
+ {
+ return series;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ series = await _tmDbClient.GetTvShowAsync(
+ tmdbId,
+ language: TmdbUtils.NormalizeLanguage(language),
+ includeImageLanguage: imageLanguages,
+ extraMethods: TvShowMethods.Credits | TvShowMethods.Images | TvShowMethods.Keywords | TvShowMethods.ExternalIds | TvShowMethods.Videos | TvShowMethods.ContentRatings,
+ cancellationToken: cancellationToken).ConfigureAwait(false);
+
+ if (series != null)
+ {
+ _memoryCache.Set(key, series, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return series;
+ }
+
+ ///
+ /// Gets a tv season from the TMDb API based on the tv show's TMDb id.
+ ///
+ /// The tv season's TMDb id.
+ /// The season number.
+ /// The tv season's language.
+ /// A comma-separated list of image languages.
+ /// The cancellation token.
+ /// The TMDb tv season information or null if not found.
+ public async Task GetSeasonAsync(int tvShowId, int seasonNumber, string language, string imageLanguages, CancellationToken cancellationToken)
+ {
+ var key = $"season-{tvShowId.ToString(CultureInfo.InvariantCulture)}-s{seasonNumber.ToString(CultureInfo.InvariantCulture)}-{language}";
+ if (_memoryCache.TryGetValue(key, out TvSeason season))
+ {
+ return season;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ season = await _tmDbClient.GetTvSeasonAsync(
+ tvShowId,
+ seasonNumber,
+ language: TmdbUtils.NormalizeLanguage(language),
+ includeImageLanguage: imageLanguages,
+ extraMethods: TvSeasonMethods.Credits | TvSeasonMethods.Images | TvSeasonMethods.ExternalIds | TvSeasonMethods.Videos,
+ cancellationToken: cancellationToken).ConfigureAwait(false);
+
+ if (season != null)
+ {
+ _memoryCache.Set(key, season, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return season;
+ }
+
+ ///
+ /// Gets a movie from the TMDb API based on the tv show's TMDb id.
+ ///
+ /// The tv show's TMDb id.
+ /// The season number.
+ /// The episode number.
+ /// The episode's language.
+ /// A comma-separated list of image languages.
+ /// The cancellation token.
+ /// The TMDb tv episode information or null if not found.
+ public async Task GetEpisodeAsync(int tvShowId, int seasonNumber, int episodeNumber, string language, string imageLanguages, CancellationToken cancellationToken)
+ {
+ var key = $"episode-{tvShowId.ToString(CultureInfo.InvariantCulture)}-s{seasonNumber.ToString(CultureInfo.InvariantCulture)}e{episodeNumber.ToString(CultureInfo.InvariantCulture)}-{language}";
+ if (_memoryCache.TryGetValue(key, out TvEpisode episode))
+ {
+ return episode;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ episode = await _tmDbClient.GetTvEpisodeAsync(
+ tvShowId,
+ seasonNumber,
+ episodeNumber,
+ language: TmdbUtils.NormalizeLanguage(language),
+ includeImageLanguage: imageLanguages,
+ extraMethods: TvEpisodeMethods.Credits | TvEpisodeMethods.Images | TvEpisodeMethods.ExternalIds | TvEpisodeMethods.Videos,
+ cancellationToken: cancellationToken).ConfigureAwait(false);
+
+ if (episode != null)
+ {
+ _memoryCache.Set(key, episode, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return episode;
+ }
+
+ ///
+ /// Gets a person eg. cast or crew member from the TMDb API based on its TMDb id.
+ ///
+ /// The person's TMDb id.
+ /// The cancellation token.
+ /// The TMDb person information or null if not found.
+ public async Task GetPersonAsync(int personTmdbId, CancellationToken cancellationToken)
+ {
+ var key = $"person-{personTmdbId.ToString(CultureInfo.InvariantCulture)}";
+ if (_memoryCache.TryGetValue(key, out Person person))
+ {
+ return person;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ person = await _tmDbClient.GetPersonAsync(
+ personTmdbId,
+ PersonMethods.TvCredits | PersonMethods.MovieCredits | PersonMethods.Images | PersonMethods.ExternalIds,
+ cancellationToken).ConfigureAwait(false);
+
+ if (person != null)
+ {
+ _memoryCache.Set(key, person, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return person;
+ }
+
+ ///
+ /// Gets an item from the TMDb API based on its id from an external service eg. IMDb id, TvDb id.
+ ///
+ /// The item's external id.
+ /// The source of the id eg. IMDb.
+ /// The item's language.
+ /// The cancellation token.
+ /// The TMDb item or null if not found.
+ public async Task FindByExternalIdAsync(
+ string externalId,
+ FindExternalSource source,
+ string language,
+ CancellationToken cancellationToken)
+ {
+ var key = $"find-{source.ToString()}-{externalId.ToString(CultureInfo.InvariantCulture)}-{language}";
+ if (_memoryCache.TryGetValue(key, out FindContainer result))
+ {
+ return result;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ result = await _tmDbClient.FindAsync(
+ source,
+ externalId,
+ TmdbUtils.NormalizeLanguage(language),
+ cancellationToken).ConfigureAwait(false);
+
+ if (result != null)
+ {
+ _memoryCache.Set(key, result, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return result;
+ }
+
+ ///
+ /// Searches for a tv show using the TMDb API based on its name.
+ ///
+ /// The name of the tv show.
+ /// The tv show's language.
+ /// The cancellation token.
+ /// The TMDb tv show information.
+ public async Task> SearchSeriesAsync(string name, string language, CancellationToken cancellationToken)
+ {
+ var key = $"searchseries-{name}-{language}";
+ if (_memoryCache.TryGetValue(key, out SearchContainer series))
+ {
+ return series.Results;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ var searchResults = await _tmDbClient
+ .SearchTvShowAsync(name, TmdbUtils.NormalizeLanguage(language), cancellationToken: cancellationToken)
+ .ConfigureAwait(false);
+
+ if (searchResults.Results.Count > 0)
+ {
+ _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return searchResults.Results;
+ }
+
+ ///
+ /// Searches for a person based on their name using the TMDb API.
+ ///
+ /// The name of the person.
+ /// The cancellation token.
+ /// The TMDb person information.
+ public async Task> SearchPersonAsync(string name, CancellationToken cancellationToken)
+ {
+ var key = $"searchperson-{name}";
+ if (_memoryCache.TryGetValue(key, out SearchContainer person))
+ {
+ return person.Results;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ var searchResults = await _tmDbClient
+ .SearchPersonAsync(name, cancellationToken: cancellationToken)
+ .ConfigureAwait(false);
+
+ if (searchResults.Results.Count > 0)
+ {
+ _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return searchResults.Results;
+ }
+
+ ///
+ /// Searches for a movie based on its name using the TMDb API.
+ ///
+ /// The name of the movie.
+ /// The movie's language.
+ /// The cancellation token.
+ /// The TMDb movie information.
+ public Task> SearchMovieAsync(string name, string language, CancellationToken cancellationToken)
+ {
+ return SearchMovieAsync(name, 0, language, cancellationToken);
+ }
+
+ ///
+ /// Searches for a movie based on its name using the TMDb API.
+ ///
+ /// The name of the movie.
+ /// The release year of the movie.
+ /// The movie's language.
+ /// The cancellation token.
+ /// The TMDb movie information.
+ public async Task> SearchMovieAsync(string name, int year, string language, CancellationToken cancellationToken)
+ {
+ var key = $"moviesearch-{name}-{year.ToString(CultureInfo.InvariantCulture)}-{language}";
+ if (_memoryCache.TryGetValue(key, out SearchContainer movies))
+ {
+ return movies.Results;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ var searchResults = await _tmDbClient
+ .SearchMovieAsync(name, TmdbUtils.NormalizeLanguage(language), year: year, cancellationToken: cancellationToken)
+ .ConfigureAwait(false);
+
+ if (searchResults.Results.Count > 0)
+ {
+ _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return searchResults.Results;
+ }
+
+ ///
+ /// Searches for a collection based on its name using the TMDb API.
+ ///
+ /// The name of the collection.
+ /// The collection's language.
+ /// The cancellation token.
+ /// The TMDb collection information.
+ public async Task> SearchCollectionAsync(string name, string language, CancellationToken cancellationToken)
+ {
+ var key = $"collectionsearch-{name}-{language}";
+ if (_memoryCache.TryGetValue(key, out SearchContainer collections))
+ {
+ return collections.Results;
+ }
+
+ await EnsureClientConfigAsync().ConfigureAwait(false);
+
+ var searchResults = await _tmDbClient
+ .SearchCollectionAsync(name, TmdbUtils.NormalizeLanguage(language), cancellationToken: cancellationToken)
+ .ConfigureAwait(false);
+
+ if (searchResults.Results.Count > 0)
+ {
+ _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
+ }
+
+ return searchResults.Results;
+ }
+
+ ///
+ /// Gets the absolute URL of the poster.
+ ///
+ /// The relative URL of the poster.
+ /// The absolute URL.
+ public string GetPosterUrl(string posterPath)
+ {
+ if (string.IsNullOrEmpty(posterPath))
+ {
+ return null;
+ }
+
+ return _tmDbClient.GetImageUrl(_tmDbClient.Config.Images.PosterSizes[^1], posterPath).ToString();
+ }
+
+ ///
+ /// Gets the absolute URL of the backdrop image.
+ ///
+ /// The relative URL of the backdrop image.
+ /// The absolute URL.
+ public string GetBackdropUrl(string posterPath)
+ {
+ if (string.IsNullOrEmpty(posterPath))
+ {
+ return null;
+ }
+
+ return _tmDbClient.GetImageUrl(_tmDbClient.Config.Images.BackdropSizes[^1], posterPath).ToString();
+ }
+
+ ///
+ /// Gets the absolute URL of the profile image.
+ ///
+ /// The relative URL of the profile image.
+ /// The absolute URL.
+ public string GetProfileUrl(string actorProfilePath)
+ {
+ if (string.IsNullOrEmpty(actorProfilePath))
+ {
+ return null;
+ }
+
+ return _tmDbClient.GetImageUrl(_tmDbClient.Config.Images.ProfileSizes[^1], actorProfilePath).ToString();
+ }
+
+ ///
+ /// Gets the absolute URL of the still image.
+ ///
+ /// The relative URL of the still image.
+ /// The absolute URL.
+ public string GetStillUrl(string filePath)
+ {
+ if (string.IsNullOrEmpty(filePath))
+ {
+ return null;
+ }
+
+ return _tmDbClient.GetImageUrl(_tmDbClient.Config.Images.StillSizes[^1], filePath).ToString();
+ }
+
+ private Task EnsureClientConfigAsync()
+ {
+ return !_tmDbClient.HasConfig ? _tmDbClient.GetConfigAsync() : Task.CompletedTask;
+ }
+ }
+}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs
index 1415d69761..b754a07953 100644
--- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs
@@ -1,7 +1,9 @@
+#nullable enable
+
using System;
-using System.Net.Mime;
+using System.Collections.Generic;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Providers.Plugins.Tmdb.Models.General;
+using TMDbLib.Objects.General;
namespace MediaBrowser.Providers.Plugins.Tmdb
{
@@ -15,11 +17,6 @@ namespace MediaBrowser.Providers.Plugins.Tmdb
///
public const string BaseTmdbUrl = "https://www.themoviedb.org/";
- ///
- /// URL of the TMDB API instance to use.
- ///
- public const string BaseTmdbApiUrl = "https://api.themoviedb.org/";
-
///
/// Name of the provider.
///
@@ -31,9 +28,19 @@ namespace MediaBrowser.Providers.Plugins.Tmdb
public const string ApiKey = "4219e299c89411838049ab0dab19ebd5";
///
- /// Value of the Accept header for requests to the provider.
+ /// Maximum number of cast members to pull.
///
- public static readonly string[] AcceptHeaders = { MediaTypeNames.Application.Json, "image/*" };
+ public const int MaxCastMembers = 15;
+
+ ///
+ /// The crew types to keep.
+ ///
+ public static readonly string[] WantedCrewTypes =
+ {
+ PersonType.Director,
+ PersonType.Writer,
+ PersonType.Producer
+ };
///
/// Maps the TMDB provided roles for crew members to Jellyfin roles.
@@ -59,7 +66,98 @@ namespace MediaBrowser.Providers.Plugins.Tmdb
return PersonType.Writer;
}
- return null;
+ return string.Empty;
+ }
+
+ ///
+ /// Determines whether a video is a trailer.
+ ///
+ /// The TMDb video.
+ /// A boolean indicating whether the video is a trailer.
+ public static bool IsTrailerType(Video video)
+ {
+ return video.Site.Equals("youtube", StringComparison.OrdinalIgnoreCase)
+ && (!video.Type.Equals("trailer", StringComparison.OrdinalIgnoreCase)
+ || !video.Type.Equals("teaser", StringComparison.OrdinalIgnoreCase));
+ }
+
+ ///
+ /// Normalizes a language string for use with TMDb's include image language parameter.
+ ///
+ /// The preferred language as either a 2 letter code with or without country code.
+ /// The comma separated language string.
+ public static string GetImageLanguagesParam(string preferredLanguage)
+ {
+ var languages = new List();
+
+ if (!string.IsNullOrEmpty(preferredLanguage))
+ {
+ preferredLanguage = NormalizeLanguage(preferredLanguage);
+
+ languages.Add(preferredLanguage);
+
+ if (preferredLanguage.Length == 5) // like en-US
+ {
+ // Currenty, TMDB supports 2-letter language codes only
+ // They are planning to change this in the future, thus we're
+ // supplying both codes if we're having a 5-letter code.
+ languages.Add(preferredLanguage.Substring(0, 2));
+ }
+ }
+
+ languages.Add("null");
+
+ if (!string.Equals(preferredLanguage, "en", StringComparison.OrdinalIgnoreCase))
+ {
+ languages.Add("en");
+ }
+
+ return string.Join(',', languages);
+ }
+
+ ///
+ /// Normalizes a language string for use with TMDb's language parameter.
+ ///
+ /// The language code.
+ /// The normalized language code.
+ public static string NormalizeLanguage(string language)
+ {
+ if (string.IsNullOrEmpty(language))
+ {
+ return language;
+ }
+
+ // They require this to be uppercase
+ // Everything after the hyphen must be written in uppercase due to a way TMDB wrote their api.
+ // See here: https://www.themoviedb.org/talk/5119221d760ee36c642af4ad?page=3#56e372a0c3a3685a9e0019ab
+ var parts = language.Split('-');
+
+ if (parts.Length == 2)
+ {
+ language = parts[0] + "-" + parts[1].ToUpperInvariant();
+ }
+
+ return language;
+ }
+
+ ///
+ /// Adjusts the image's language code preferring the 5 letter language code eg. en-US.
+ ///
+ /// The image's actual language code.
+ /// The requested language code.
+ /// The language code.
+ public static string AdjustImageLanguage(string imageLanguage, string requestLanguage)
+ {
+ if (!string.IsNullOrEmpty(imageLanguage)
+ && !string.IsNullOrEmpty(requestLanguage)
+ && requestLanguage.Length > 2
+ && imageLanguage.Length == 2
+ && requestLanguage.StartsWith(imageLanguage, StringComparison.OrdinalIgnoreCase))
+ {
+ return requestLanguage;
+ }
+
+ return imageLanguage;
}
}
}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Trailers/TmdbTrailerProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/Trailers/TmdbTrailerProvider.cs
deleted file mode 100644
index 613dc17e31..0000000000
--- a/MediaBrowser.Providers/Plugins/Tmdb/Trailers/TmdbTrailerProvider.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-#pragma warning disable CS1591
-
-using System.Collections.Generic;
-using System.Net.Http;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Providers;
-using MediaBrowser.Providers.Plugins.Tmdb.Movies;
-
-namespace MediaBrowser.Providers.Plugins.Tmdb.Trailers
-{
- public class TmdbTrailerProvider : IHasOrder, IRemoteMetadataProvider
- {
- private readonly IHttpClientFactory _httpClientFactory;
-
- public TmdbTrailerProvider(IHttpClientFactory httpClientFactory)
- {
- _httpClientFactory = httpClientFactory;
- }
-
- public string Name => TmdbMovieProvider.Current.Name;
-
- public int Order => 0;
-
- public Task> GetSearchResults(TrailerInfo searchInfo, CancellationToken cancellationToken)
- {
- return TmdbMovieProvider.Current.GetMovieSearchResults(searchInfo, cancellationToken);
- }
-
- public Task> GetMetadata(TrailerInfo info, CancellationToken cancellationToken)
- {
- return TmdbMovieProvider.Current.GetItemMetadata(info, cancellationToken);
- }
-
- public Task GetImageResponse(string url, CancellationToken cancellationToken)
- {
- return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
- }
- }
-}
diff --git a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs
index f25d3d5ee7..47e9d5ee8c 100644
--- a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs
+++ b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs
@@ -147,40 +147,14 @@ namespace MediaBrowser.Providers.Subtitles
string subtitleId,
CancellationToken cancellationToken)
{
- var parts = subtitleId.Split(new[] { '_' }, 2);
+ var parts = subtitleId.Split('_', 2);
var provider = GetProvider(parts[0]);
- var saveInMediaFolder = libraryOptions.SaveSubtitlesWithMedia;
-
try
{
var response = await GetRemoteSubtitles(subtitleId, cancellationToken).ConfigureAwait(false);
- using (var stream = response.Stream)
- using (var memoryStream = new MemoryStream())
- {
- await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
- memoryStream.Position = 0;
-
- var savePaths = new List();
- var saveFileName = Path.GetFileNameWithoutExtension(video.Path) + "." + response.Language.ToLowerInvariant();
-
- if (response.IsForced)
- {
- saveFileName += ".forced";
- }
-
- saveFileName += "." + response.Format.ToLowerInvariant();
-
- if (saveInMediaFolder)
- {
- savePaths.Add(Path.Combine(video.ContainingFolderPath, saveFileName));
- }
-
- savePaths.Add(Path.Combine(video.GetInternalMetadataPath(), saveFileName));
-
- await TrySaveToFiles(memoryStream, savePaths).ConfigureAwait(false);
- }
+ await TrySaveSubtitle(video, libraryOptions, response).ConfigureAwait(false);
}
catch (RateLimitExceededException)
{
@@ -199,6 +173,47 @@ namespace MediaBrowser.Providers.Subtitles
}
}
+ ///
+ public Task UploadSubtitle(Video video, SubtitleResponse response)
+ {
+ var libraryOptions = BaseItem.LibraryManager.GetLibraryOptions(video);
+ return TrySaveSubtitle(video, libraryOptions, response);
+ }
+
+ private async Task TrySaveSubtitle(
+ Video video,
+ LibraryOptions libraryOptions,
+ SubtitleResponse response)
+ {
+ var saveInMediaFolder = libraryOptions.SaveSubtitlesWithMedia;
+
+ using (var stream = response.Stream)
+ using (var memoryStream = new MemoryStream())
+ {
+ await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
+ memoryStream.Position = 0;
+
+ var savePaths = new List();
+ var saveFileName = Path.GetFileNameWithoutExtension(video.Path) + "." + response.Language.ToLowerInvariant();
+
+ if (response.IsForced)
+ {
+ saveFileName += ".forced";
+ }
+
+ saveFileName += "." + response.Format.ToLowerInvariant();
+
+ if (saveInMediaFolder)
+ {
+ savePaths.Add(Path.Combine(video.ContainingFolderPath, saveFileName));
+ }
+
+ savePaths.Add(Path.Combine(video.GetInternalMetadataPath(), saveFileName));
+
+ await TrySaveToFiles(memoryStream, savePaths).ConfigureAwait(false);
+ }
+ }
+
private async Task TrySaveToFiles(Stream stream, List savePaths)
{
Exception exceptionToThrow = null;
@@ -314,7 +329,7 @@ namespace MediaBrowser.Providers.Subtitles
Index = index,
ItemId = item.Id,
Type = MediaStreamType.Subtitle
- }).First();
+ })[0];
var path = stream.Path;
_monitor.ReportFileSystemChangeBeginning(path);
@@ -334,10 +349,10 @@ namespace MediaBrowser.Providers.Subtitles
///
public Task GetRemoteSubtitles(string id, CancellationToken cancellationToken)
{
- var parts = id.Split(new[] { '_' }, 2);
+ var parts = id.Split('_', 2);
var provider = GetProvider(parts[0]);
- id = parts.Last();
+ id = parts[^1];
return provider.GetSubtitles(id, cancellationToken);
}
diff --git a/MediaBrowser.Providers/TV/DummySeasonProvider.cs b/MediaBrowser.Providers/TV/DummySeasonProvider.cs
deleted file mode 100644
index a0f7f6cfd7..0000000000
--- a/MediaBrowser.Providers/TV/DummySeasonProvider.cs
+++ /dev/null
@@ -1,230 +0,0 @@
-#pragma warning disable CS1591
-
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Providers.TV
-{
- public class DummySeasonProvider
- {
- private readonly ILogger _logger;
- private readonly ILocalizationManager _localization;
- private readonly ILibraryManager _libraryManager;
- private readonly IFileSystem _fileSystem;
-
- public DummySeasonProvider(
- ILogger logger,
- ILocalizationManager localization,
- ILibraryManager libraryManager,
- IFileSystem fileSystem)
- {
- _logger = logger;
- _localization = localization;
- _libraryManager = libraryManager;
- _fileSystem = fileSystem;
- }
-
- public async Task Run(Series series, CancellationToken cancellationToken)
- {
- var seasonsRemoved = RemoveObsoleteSeasons(series);
-
- var hasNewSeasons = await AddDummySeasonFolders(series, cancellationToken).ConfigureAwait(false);
-
- if (hasNewSeasons)
- {
- // var directoryService = new DirectoryService(_fileSystem);
-
- // await series.RefreshMetadata(new MetadataRefreshOptions(directoryService), cancellationToken).ConfigureAwait(false);
-
- // await series.ValidateChildren(new SimpleProgress(), cancellationToken, new MetadataRefreshOptions(directoryService))
- // .ConfigureAwait(false);
- }
-
- return seasonsRemoved || hasNewSeasons;
- }
-
- private async Task AddDummySeasonFolders(Series series, CancellationToken cancellationToken)
- {
- var episodesInSeriesFolder = series.GetRecursiveChildren(i => i is Episode)
- .Cast()
- .Where(i => !i.IsInSeasonFolder)
- .ToList();
-
- var hasChanges = false;
-
- List seasons = null;
-
- // Loop through the unique season numbers
- foreach (var seasonNumber in episodesInSeriesFolder.Select(i => i.ParentIndexNumber ?? -1)
- .Where(i => i >= 0)
- .Distinct()
- .ToList())
- {
- if (seasons == null)
- {
- seasons = series.Children.OfType().ToList();
- }
-
- var existingSeason = seasons
- .FirstOrDefault(i => i.IndexNumber.HasValue && i.IndexNumber.Value == seasonNumber);
-
- if (existingSeason == null)
- {
- await AddSeason(series, seasonNumber, false, cancellationToken).ConfigureAwait(false);
- hasChanges = true;
- seasons = null;
- }
- else if (existingSeason.IsVirtualItem)
- {
- existingSeason.IsVirtualItem = false;
- await existingSeason.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false);
- seasons = null;
- }
- }
-
- // Unknown season - create a dummy season to put these under
- if (episodesInSeriesFolder.Any(i => !i.ParentIndexNumber.HasValue))
- {
- if (seasons == null)
- {
- seasons = series.Children.OfType().ToList();
- }
-
- var existingSeason = seasons
- .FirstOrDefault(i => !i.IndexNumber.HasValue);
-
- if (existingSeason == null)
- {
- await AddSeason(series, null, false, cancellationToken).ConfigureAwait(false);
-
- hasChanges = true;
- seasons = null;
- }
- else if (existingSeason.IsVirtualItem)
- {
- existingSeason.IsVirtualItem = false;
- await existingSeason.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false);
- seasons = null;
- }
- }
-
- return hasChanges;
- }
-
- ///
- /// Adds the season.
- ///
- public async Task AddSeason(
- Series series,
- int? seasonNumber,
- bool isVirtualItem,
- CancellationToken cancellationToken)
- {
- string seasonName;
- if (seasonNumber == null)
- {
- seasonName = _localization.GetLocalizedString("NameSeasonUnknown");
- }
- else if (seasonNumber == 0)
- {
- seasonName = _libraryManager.GetLibraryOptions(series).SeasonZeroDisplayName;
- }
- else
- {
- seasonName = string.Format(
- CultureInfo.InvariantCulture,
- _localization.GetLocalizedString("NameSeasonNumber"),
- seasonNumber.Value);
- }
-
- _logger.LogInformation("Creating Season {0} entry for {1}", seasonName, series.Name);
-
- var season = new Season
- {
- Name = seasonName,
- IndexNumber = seasonNumber,
- Id = _libraryManager.GetNewItemId(
- series.Id + (seasonNumber ?? -1).ToString(CultureInfo.InvariantCulture) + seasonName,
- typeof(Season)),
- IsVirtualItem = isVirtualItem,
- SeriesId = series.Id,
- SeriesName = series.Name
- };
-
- season.SetParent(series);
-
- series.AddChild(season, cancellationToken);
-
- await season.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_fileSystem)), cancellationToken).ConfigureAwait(false);
-
- return season;
- }
-
- private bool RemoveObsoleteSeasons(Series series)
- {
- var existingSeasons = series.Children.OfType().ToList();
-
- var physicalSeasons = existingSeasons
- .Where(i => i.LocationType != LocationType.Virtual)
- .ToList();
-
- var virtualSeasons = existingSeasons
- .Where(i => i.LocationType == LocationType.Virtual)
- .ToList();
-
- var seasonsToRemove = virtualSeasons
- .Where(i =>
- {
- if (i.IndexNumber.HasValue)
- {
- var seasonNumber = i.IndexNumber.Value;
-
- // If there's a physical season with the same number, delete it
- if (physicalSeasons.Any(p => p.IndexNumber.HasValue && (p.IndexNumber.Value == seasonNumber)))
- {
- return true;
- }
- }
-
- // If there are no episodes with this season number, delete it
- if (!i.GetEpisodes().Any())
- {
- return true;
- }
-
- return false;
- })
- .ToList();
-
- var hasChanges = false;
-
- foreach (var seasonToRemove in seasonsToRemove)
- {
- _logger.LogInformation("Removing virtual season {0} {1}", series.Name, seasonToRemove.IndexNumber);
-
- _libraryManager.DeleteItem(
- seasonToRemove,
- new DeleteOptions
- {
- DeleteFileLocation = true
-
- },
- false);
-
- hasChanges = true;
- }
-
- return hasChanges;
- }
- }
-}
diff --git a/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs b/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs
deleted file mode 100644
index c833b12271..0000000000
--- a/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs
+++ /dev/null
@@ -1,404 +0,0 @@
-#pragma warning disable CS1591
-
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Entities.TV;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Providers;
-using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Providers.Plugins.TheTvdb;
-using Microsoft.Extensions.Logging;
-
-namespace MediaBrowser.Providers.TV
-{
- public class MissingEpisodeProvider
- {
- private const double UnairedEpisodeThresholdDays = 2;
-
- private readonly IServerConfigurationManager _config;
- private readonly ILogger _logger;
- private readonly ILibraryManager _libraryManager;
- private readonly ILocalizationManager _localization;
- private readonly IFileSystem _fileSystem;
- private readonly TvdbClientManager _tvdbClientManager;
-
- public MissingEpisodeProvider(
- ILogger logger,
- IServerConfigurationManager config,
- ILibraryManager libraryManager,
- ILocalizationManager localization,
- IFileSystem fileSystem,
- TvdbClientManager tvdbClientManager)
- {
- _logger = logger;
- _config = config;
- _libraryManager = libraryManager;
- _localization = localization;
- _fileSystem = fileSystem;
- _tvdbClientManager = tvdbClientManager;
- }
-
- public async Task Run(Series series, bool addNewItems, CancellationToken cancellationToken)
- {
- var tvdbIdString = series.GetProviderId(MetadataProvider.Tvdb);
- if (string.IsNullOrEmpty(tvdbIdString))
- {
- return false;
- }
-
- var episodes = await _tvdbClientManager.GetAllEpisodesAsync(
- int.Parse(tvdbIdString, CultureInfo.InvariantCulture),
- series.GetPreferredMetadataLanguage(),
- cancellationToken).ConfigureAwait(false);
-
- var episodeLookup = episodes
- .Select(i =>
- {
- if (!DateTime.TryParse(i.FirstAired, out var firstAired))
- {
- firstAired = default;
- }
-
- var seasonNumber = i.AiredSeason.GetValueOrDefault(-1);
- var episodeNumber = i.AiredEpisodeNumber.GetValueOrDefault(-1);
- return (seasonNumber, episodeNumber, firstAired);
- })
- .Where(i => i.seasonNumber != -1 && i.episodeNumber != -1)
- .OrderBy(i => i.seasonNumber)
- .ThenBy(i => i.episodeNumber)
- .ToList();
-
- var allRecursiveChildren = series.GetRecursiveChildren();
-
- var hasBadData = HasInvalidContent(allRecursiveChildren);
-
- // Be conservative here to avoid creating missing episodes for ones they already have
- var addMissingEpisodes = !hasBadData && _libraryManager.GetLibraryOptions(series).ImportMissingEpisodes;
-
- var anySeasonsRemoved = RemoveObsoleteOrMissingSeasons(allRecursiveChildren, episodeLookup);
-
- if (anySeasonsRemoved)
- {
- // refresh this
- allRecursiveChildren = series.GetRecursiveChildren();
- }
-
- var anyEpisodesRemoved = RemoveObsoleteOrMissingEpisodes(allRecursiveChildren, episodeLookup, addMissingEpisodes);
-
- if (anyEpisodesRemoved)
- {
- // refresh this
- allRecursiveChildren = series.GetRecursiveChildren();
- }
-
- var hasNewEpisodes = false;
-
- if (addNewItems && series.IsMetadataFetcherEnabled(_libraryManager.GetLibraryOptions(series), TvdbSeriesProvider.Current.Name))
- {
- hasNewEpisodes = await AddMissingEpisodes(series, allRecursiveChildren, addMissingEpisodes, episodeLookup, cancellationToken)
- .ConfigureAwait(false);
- }
-
- if (hasNewEpisodes || anySeasonsRemoved || anyEpisodesRemoved)
- {
- return true;
- }
-
- return false;
- }
-
- ///
- /// Returns true if a series has any seasons or episodes without season or episode numbers
- /// If this data is missing no virtual items will be added in order to prevent possible duplicates.
- ///
- private bool HasInvalidContent(IList allItems)
- {
- return allItems.OfType().Any(i => !i.IndexNumber.HasValue) ||
- allItems.OfType().Any(i =>
- {
- if (!i.ParentIndexNumber.HasValue)
- {
- return true;
- }
-
- // You could have episodes under season 0 with no number
- return false;
- });
- }
-
- private async Task AddMissingEpisodes(
- Series series,
- IEnumerable allItems,
- bool addMissingEpisodes,
- IReadOnlyCollection<(int seasonNumber, int episodenumber, DateTime firstAired)> episodeLookup,
- CancellationToken cancellationToken)
- {
- var existingEpisodes = allItems.OfType().ToList();
-
- var seasonCounts = episodeLookup.GroupBy(e => e.seasonNumber).ToDictionary(g => g.Key, g => g.Count());
-
- var hasChanges = false;
-
- foreach (var tuple in episodeLookup)
- {
- if (tuple.seasonNumber <= 0 || tuple.episodenumber <= 0)
- {
- // Ignore episode/season zeros
- continue;
- }
-
- var existingEpisode = GetExistingEpisode(existingEpisodes, seasonCounts, tuple);
-
- if (existingEpisode != null)
- {
- continue;
- }
-
- var airDate = tuple.firstAired;
-
- var now = DateTime.UtcNow.AddDays(-UnairedEpisodeThresholdDays);
-
- if ((airDate < now && addMissingEpisodes) || airDate > now)
- {
- // tvdb has a lot of nearly blank episodes
- _logger.LogInformation("Creating virtual missing/unaired episode {0} {1}x{2}", series.Name, tuple.seasonNumber, tuple.episodenumber);
- await AddEpisode(series, tuple.seasonNumber, tuple.episodenumber, cancellationToken).ConfigureAwait(false);
-
- hasChanges = true;
- }
- }
-
- return hasChanges;
- }
-
- ///
- /// Removes the virtual entry after a corresponding physical version has been added.
- ///
- private bool RemoveObsoleteOrMissingEpisodes(
- IEnumerable allRecursiveChildren,
- IEnumerable<(int seasonNumber, int episodeNumber, DateTime firstAired)> episodeLookup,
- bool allowMissingEpisodes)
- {
- var existingEpisodes = allRecursiveChildren.OfType();
-
- var physicalEpisodes = new List();
- var virtualEpisodes = new List();
- foreach (var episode in existingEpisodes)
- {
- if (episode.LocationType == LocationType.Virtual)
- {
- virtualEpisodes.Add(episode);
- }
- else
- {
- physicalEpisodes.Add(episode);
- }
- }
-
- var episodesToRemove = virtualEpisodes
- .Where(i =>
- {
- if (!i.IndexNumber.HasValue || !i.ParentIndexNumber.HasValue)
- {
- return true;
- }
-
- var seasonNumber = i.ParentIndexNumber.Value;
- var episodeNumber = i.IndexNumber.Value;
-
- // If there's a physical episode with the same season and episode number, delete it
- if (physicalEpisodes.Any(p =>
- p.ParentIndexNumber.HasValue && p.ParentIndexNumber.Value == seasonNumber &&
- p.ContainsEpisodeNumber(episodeNumber)))
- {
- return true;
- }
-
- // If the episode no longer exists in the remote lookup, delete it
- if (!episodeLookup.Any(e => e.seasonNumber == seasonNumber && e.episodeNumber == episodeNumber))
- {
- return true;
- }
-
- // If it's missing, but not unaired, remove it
- return !allowMissingEpisodes && i.IsMissingEpisode &&
- (!i.PremiereDate.HasValue ||
- i.PremiereDate.Value.ToLocalTime().Date.AddDays(UnairedEpisodeThresholdDays) <
- DateTime.Now.Date);
- });
-
- var hasChanges = false;
-
- foreach (var episodeToRemove in episodesToRemove)
- {
- _libraryManager.DeleteItem(
- episodeToRemove,
- new DeleteOptions
- {
- DeleteFileLocation = true
- },
- false);
-
- hasChanges = true;
- }
-
- return hasChanges;
- }
-
- ///
- /// Removes the obsolete or missing seasons.
- ///
- /// All recursive children.
- /// The episode lookup.
- /// .
- private bool RemoveObsoleteOrMissingSeasons(
- IList allRecursiveChildren,
- IEnumerable<(int seasonNumber, int episodeNumber, DateTime firstAired)> episodeLookup)
- {
- var existingSeasons = allRecursiveChildren.OfType().ToList();
-
- var physicalSeasons = new List();
- var virtualSeasons = new List();
- foreach (var season in existingSeasons)
- {
- if (season.LocationType == LocationType.Virtual)
- {
- virtualSeasons.Add(season);
- }
- else
- {
- physicalSeasons.Add(season);
- }
- }
-
- var allEpisodes = allRecursiveChildren.OfType().ToList();
-
- var seasonsToRemove = virtualSeasons
- .Where(i =>
- {
- if (i.IndexNumber.HasValue)
- {
- var seasonNumber = i.IndexNumber.Value;
-
- // If there's a physical season with the same number, delete it
- if (physicalSeasons.Any(p => p.IndexNumber.HasValue && p.IndexNumber.Value == seasonNumber && string.Equals(p.Series.PresentationUniqueKey, i.Series.PresentationUniqueKey, StringComparison.Ordinal)))
- {
- return true;
- }
-
- // If the season no longer exists in the remote lookup, delete it, but only if an existing episode doesn't require it
- return episodeLookup.All(e => e.seasonNumber != seasonNumber) && allEpisodes.All(s => s.ParentIndexNumber != seasonNumber || s.IsInSeasonFolder);
- }
-
- // Season does not have a number
- // Remove if there are no episodes directly in series without a season number
- return allEpisodes.All(s => s.ParentIndexNumber.HasValue || s.IsInSeasonFolder);
- });
-
- var hasChanges = false;
-
- foreach (var seasonToRemove in seasonsToRemove)
- {
- _libraryManager.DeleteItem(
- seasonToRemove,
- new DeleteOptions
- {
- DeleteFileLocation = true
- },
- false);
-
- hasChanges = true;
- }
-
- return hasChanges;
- }
-
- ///
- /// Adds the episode.
- ///
- /// The series.
- /// The season number.
- /// The episode number.
- /// The cancellation token.
- /// Task.
- private async Task AddEpisode(Series series, int seasonNumber, int episodeNumber, CancellationToken cancellationToken)
- {
- var season = series.Children.OfType()
- .FirstOrDefault(i => i.IndexNumber.HasValue && i.IndexNumber.Value == seasonNumber);
-
- if (season == null)
- {
- var provider = new DummySeasonProvider(_logger, _localization, _libraryManager, _fileSystem);
- season = await provider.AddSeason(series, seasonNumber, true, cancellationToken).ConfigureAwait(false);
- }
-
- var name = "Episode " + episodeNumber.ToString(CultureInfo.InvariantCulture);
-
- var episode = new Episode
- {
- Name = name,
- IndexNumber = episodeNumber,
- ParentIndexNumber = seasonNumber,
- Id = _libraryManager.GetNewItemId(
- series.Id + seasonNumber.ToString(CultureInfo.InvariantCulture) + name,
- typeof(Episode)),
- IsVirtualItem = true,
- SeasonId = season?.Id ?? Guid.Empty,
- SeriesId = series.Id
- };
-
- season.AddChild(episode, cancellationToken);
-
- await episode.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_fileSystem)), cancellationToken).ConfigureAwait(false);
- }
-
- ///
- /// Gets the existing episode.
- ///
- /// The existing episodes.
- ///
- ///
- /// Episode.
- private Episode GetExistingEpisode(
- IEnumerable existingEpisodes,
- IReadOnlyDictionary seasonCounts,
- (int seasonNumber, int episodeNumber, DateTime firstAired) episodeTuple)
- {
- var seasonNumber = episodeTuple.seasonNumber;
- var episodeNumber = episodeTuple.episodeNumber;
-
- while (true)
- {
- var episode = GetExistingEpisode(existingEpisodes, seasonNumber, episodeNumber);
- if (episode != null)
- {
- return episode;
- }
-
- seasonNumber--;
-
- if (seasonCounts.ContainsKey(seasonNumber))
- {
- episodeNumber += seasonCounts[seasonNumber];
- }
- else
- {
- break;
- }
- }
-
- return null;
- }
-
- private Episode GetExistingEpisode(IEnumerable existingEpisodes, int season, int episode)
- => existingEpisodes.FirstOrDefault(i => i.ParentIndexNumber == season && i.ContainsEpisodeNumber(episode));
- }
-}
diff --git a/MediaBrowser.Providers/TV/SeriesMetadataService.cs b/MediaBrowser.Providers/TV/SeriesMetadataService.cs
index a2c0e62c19..c8fc568a22 100644
--- a/MediaBrowser.Providers/TV/SeriesMetadataService.cs
+++ b/MediaBrowser.Providers/TV/SeriesMetadataService.cs
@@ -1,65 +1,26 @@
#pragma warning disable CS1591
-using System;
-using System.Threading;
-using System.Threading.Tasks;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
using MediaBrowser.Providers.Manager;
-using MediaBrowser.Providers.Plugins.TheTvdb;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.Providers.TV
{
public class SeriesMetadataService : MetadataService
{
- private readonly ILocalizationManager _localization;
- private readonly TvdbClientManager _tvdbClientManager;
-
public SeriesMetadataService(
IServerConfigurationManager serverConfigurationManager,
ILogger logger,
IProviderManager providerManager,
IFileSystem fileSystem,
- ILibraryManager libraryManager,
- ILocalizationManager localization,
- TvdbClientManager tvdbClientManager)
+ ILibraryManager libraryManager)
: base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager)
{
- _localization = localization;
- _tvdbClientManager = tvdbClientManager;
- }
-
- ///
- protected override async Task AfterMetadataRefresh(Series item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken)
- {
- await base.AfterMetadataRefresh(item, refreshOptions, cancellationToken).ConfigureAwait(false);
-
- var seasonProvider = new DummySeasonProvider(Logger, _localization, LibraryManager, FileSystem);
- await seasonProvider.Run(item, cancellationToken).ConfigureAwait(false);
-
- // TODO why does it not register this itself omg
- var provider = new MissingEpisodeProvider(
- Logger,
- ServerConfigurationManager,
- LibraryManager,
- _localization,
- FileSystem,
- _tvdbClientManager);
-
- try
- {
- await provider.Run(item, true, CancellationToken.None).ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error in DummySeasonProvider for {ItemPath}", item.Path);
- }
}
///
diff --git a/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj b/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj
index 45fd9add92..87d1e9464c 100644
--- a/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj
+++ b/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj
@@ -15,7 +15,7 @@
- netstandard2.1
+ net5.0
false
true
true
diff --git a/README.md b/README.md
index 435e709b33..1ab246f84f 100644
--- a/README.md
+++ b/README.md
@@ -81,7 +81,7 @@ These instructions will help you get set up with a local development environment
### Prerequisites
-Before the project can be built, you must first install the [.NET Core 3.1 SDK](https://dotnet.microsoft.com/download) on your system.
+Before the project can be built, you must first install the [.NET 5.0 SDK](https://dotnet.microsoft.com/download) on your system.
Instructions to run this project from the command line are included here, but you will also need to install an IDE if you want to debug the server while it is running. Any IDE that supports .NET Core development will work, but two options are recent versions of [Visual Studio](https://visualstudio.microsoft.com/downloads/) (at least 2017) and [Visual Studio Code](https://code.visualstudio.com/Download).
@@ -142,7 +142,7 @@ A second option is to build the project and then run the resulting executable fi
```bash
dotnet build # Build the project
- cd bin/Debug/netcoreapp3.1 # Change into the build output directory
+ cd bin/Debug/net5.0 # Change into the build output directory
```
2. Execute the build output. On Linux, Mac, etc. use `./jellyfin` and on Windows use `jellyfin.exe`.
diff --git a/RSSDP/HttpParserBase.cs b/RSSDP/HttpParserBase.cs
index a40612bc29..11202940e1 100644
--- a/RSSDP/HttpParserBase.cs
+++ b/RSSDP/HttpParserBase.cs
@@ -119,7 +119,7 @@ namespace Rssdp.Infrastructure
}
else
{
- headersToAddTo.TryAddWithoutValidation(headerName, values.First());
+ headersToAddTo.TryAddWithoutValidation(headerName, values[0]);
}
}
@@ -151,7 +151,7 @@ namespace Rssdp.Infrastructure
return lineIndex;
}
- private IList ParseValues(string headerValue)
+ private List ParseValues(string headerValue)
{
// This really should be better and match the HTTP 1.1 spec,
// but this should actually be good enough for SSDP implementations
@@ -160,7 +160,7 @@ namespace Rssdp.Infrastructure
if (headerValue == "\"\"")
{
- values.Add(String.Empty);
+ values.Add(string.Empty);
return values;
}
@@ -172,7 +172,7 @@ namespace Rssdp.Infrastructure
else
{
var segments = headerValue.Split(SeparatorCharacters);
- if (headerValue.Contains("\""))
+ if (headerValue.Contains('"'))
{
for (int segmentIndex = 0; segmentIndex < segments.Length; segmentIndex++)
{
diff --git a/RSSDP/RSSDP.csproj b/RSSDP/RSSDP.csproj
index 664663bd76..d0962e82c8 100644
--- a/RSSDP/RSSDP.csproj
+++ b/RSSDP/RSSDP.csproj
@@ -10,7 +10,7 @@
- netstandard2.1
+ net5.0
false
true
diff --git a/apiclient/.openapi-generator-ignore b/apiclient/.openapi-generator-ignore
new file mode 100644
index 0000000000..f3802cf541
--- /dev/null
+++ b/apiclient/.openapi-generator-ignore
@@ -0,0 +1,2 @@
+# Prevent generator from creating these files:
+git_push.sh
diff --git a/apiclient/templates/typescript/axios/generate.sh b/apiclient/templates/typescript/axios/generate.sh
new file mode 100644
index 0000000000..9599f85dbd
--- /dev/null
+++ b/apiclient/templates/typescript/axios/generate.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+
+artifactsDirectory="${1}"
+
+java -jar openapi-generator-cli.jar generate \
+ --input-spec ${artifactsDirectory}/openapispec/openapi.json \
+ --generator-name typescript-axios \
+ --output ./apiclient/generated/typescript/axios \
+ --template-dir ./apiclient/templates/typescript/axios \
+ --ignore-file-override ./apiclient/.openapi-generator-ignore \
+ --additional-properties=useSingleRequestParameter="true",withSeparateModelsAndApi="true",modelPackage="models",apiPackage="api",npmName="axios"
diff --git a/apiclient/templates/typescript/axios/package.mustache b/apiclient/templates/typescript/axios/package.mustache
new file mode 100644
index 0000000000..7bfab08cbb
--- /dev/null
+++ b/apiclient/templates/typescript/axios/package.mustache
@@ -0,0 +1,30 @@
+{
+ "name": "@jellyfin/client-axios",
+ "version": "10.7.0{{snapshotVersion}}",
+ "description": "Jellyfin api client using axios",
+ "author": "Jellyfin Contributors",
+ "keywords": [
+ "axios",
+ "typescript",
+ "jellyfin"
+ ],
+ "license": "GPL-3.0-only",
+ "main": "./dist/index.js",
+ "typings": "./dist/index.d.ts",
+ "scripts": {
+ "build": "tsc --outDir dist/",
+ "prepublishOnly": "npm run build"
+ },
+ "dependencies": {
+ "axios": "^0.19.2"
+ },
+ "devDependencies": {
+ "@types/node": "^12.11.5",
+ "typescript": "^3.6.4"
+ }{{#npmRepository}},{{/npmRepository}}
+{{#npmRepository}}
+ "publishConfig": {
+ "registry": "{{npmRepository}}"
+ }
+{{/npmRepository}}
+}
diff --git a/benches/Jellyfin.Common.Benches/Jellyfin.Common.Benches.csproj b/benches/Jellyfin.Common.Benches/Jellyfin.Common.Benches.csproj
index 47aeed05ef..c564e86e9e 100644
--- a/benches/Jellyfin.Common.Benches/Jellyfin.Common.Benches.csproj
+++ b/benches/Jellyfin.Common.Benches/Jellyfin.Common.Benches.csproj
@@ -2,7 +2,7 @@
Exe
- netcoreapp3.1
+ net5.0
diff --git a/debian/control b/debian/control
index 39c2aa055b..9675d36ca6 100644
--- a/debian/control
+++ b/debian/control
@@ -3,7 +3,7 @@ Section: misc
Priority: optional
Maintainer: Jellyfin Team
Build-Depends: debhelper (>= 9),
- dotnet-sdk-3.1,
+ dotnet-sdk-5.0,
libc6-dev,
libcurl4-openssl-dev,
libfontconfig1-dev,
@@ -20,7 +20,6 @@ Breaks: jellyfin (<<10.6.0)
Architecture: any
Depends: at,
libsqlite3-0,
- jellyfin-ffmpeg (>= 4.2.1-2),
libfontconfig1,
libfreetype6,
libssl1.1
diff --git a/debian/postrm b/debian/postrm
index 1d00a984ec..3d56a5f1e8 100644
--- a/debian/postrm
+++ b/debian/postrm
@@ -25,7 +25,7 @@ case "$1" in
purge)
echo PURGE | debconf-communicate $NAME > /dev/null 2>&1 || true
- if [[ -x "/etc/init.d/jellyfin" ]] || [[ -e "/etc/init/jellyfin.connf" ]]; then
+ if [[ -x "/etc/init.d/jellyfin" ]] || [[ -e "/etc/init/jellyfin.conf" ]]; then
update-rc.d jellyfin remove >/dev/null 2>&1 || true
fi
@@ -54,7 +54,7 @@ case "$1" in
rm -rf $PROGRAMDATA
fi
# Remove binary symlink
- [[ -f /usr/bin/jellyfin ]] && rm /usr/bin/jellyfin
+ rm -f /usr/bin/jellyfin
# Remove sudoers config
[[ -f /etc/sudoers.d/jellyfin-sudoers ]] && rm /etc/sudoers.d/jellyfin-sudoers
# Remove anything at the default locations; catches situations where the user moved the defaults
diff --git a/deployment/Dockerfile.centos.amd64 b/deployment/Dockerfile.centos.amd64
index 39788cc0ee..01fc1aaac2 100644
--- a/deployment/Dockerfile.centos.amd64
+++ b/deployment/Dockerfile.centos.amd64
@@ -2,7 +2,7 @@ FROM centos:7
# Docker build arguments
ARG SOURCE_DIR=/jellyfin
ARG ARTIFACT_DIR=/dist
-ARG SDK_VERSION=3.1
+ARG SDK_VERSION=5.0
# Docker run environment
ENV SOURCE_DIR=/jellyfin
ENV ARTIFACT_DIR=/dist
diff --git a/deployment/Dockerfile.debian.amd64 b/deployment/Dockerfile.debian.amd64
index 7202c58838..f0d9188c17 100644
--- a/deployment/Dockerfile.debian.amd64
+++ b/deployment/Dockerfile.debian.amd64
@@ -2,7 +2,7 @@ FROM debian:10
# Docker build arguments
ARG SOURCE_DIR=/jellyfin
ARG ARTIFACT_DIR=/dist
-ARG SDK_VERSION=3.1
+ARG SDK_VERSION=5.0
# Docker run environment
ENV SOURCE_DIR=/jellyfin
ENV ARTIFACT_DIR=/dist
@@ -16,7 +16,7 @@ RUN apt-get update \
# Install dotnet repository
# https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current
-RUN wget https://download.visualstudio.microsoft.com/download/pr/f01e3d97-c1c3-4635-bc77-0c893be36820/6ec6acabc22468c6cc68b61625b14a7d/dotnet-sdk-3.1.402-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
+RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
&& mkdir -p dotnet-sdk \
&& tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \
&& ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet
diff --git a/deployment/Dockerfile.debian.arm64 b/deployment/Dockerfile.debian.arm64
index e9f30213f4..8132ee8873 100644
--- a/deployment/Dockerfile.debian.arm64
+++ b/deployment/Dockerfile.debian.arm64
@@ -2,7 +2,7 @@ FROM debian:10
# Docker build arguments
ARG SOURCE_DIR=/jellyfin
ARG ARTIFACT_DIR=/dist
-ARG SDK_VERSION=3.1
+ARG SDK_VERSION=5.0
# Docker run environment
ENV SOURCE_DIR=/jellyfin
ENV ARTIFACT_DIR=/dist
@@ -16,7 +16,7 @@ RUN apt-get update \
# Install dotnet repository
# https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current
-RUN wget https://download.visualstudio.microsoft.com/download/pr/f01e3d97-c1c3-4635-bc77-0c893be36820/6ec6acabc22468c6cc68b61625b14a7d/dotnet-sdk-3.1.402-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
+RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
&& mkdir -p dotnet-sdk \
&& tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \
&& ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet
diff --git a/deployment/Dockerfile.debian.armhf b/deployment/Dockerfile.debian.armhf
index 91a8a6e7a1..31f534838b 100644
--- a/deployment/Dockerfile.debian.armhf
+++ b/deployment/Dockerfile.debian.armhf
@@ -2,7 +2,7 @@ FROM debian:10
# Docker build arguments
ARG SOURCE_DIR=/jellyfin
ARG ARTIFACT_DIR=/dist
-ARG SDK_VERSION=3.1
+ARG SDK_VERSION=5.0
# Docker run environment
ENV SOURCE_DIR=/jellyfin
ENV ARTIFACT_DIR=/dist
@@ -16,7 +16,7 @@ RUN apt-get update \
# Install dotnet repository
# https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current
-RUN wget https://download.visualstudio.microsoft.com/download/pr/f01e3d97-c1c3-4635-bc77-0c893be36820/6ec6acabc22468c6cc68b61625b14a7d/dotnet-sdk-3.1.402-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
+RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
&& mkdir -p dotnet-sdk \
&& tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \
&& ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet
diff --git a/deployment/Dockerfile.docker.amd64 b/deployment/Dockerfile.docker.amd64
index e04442606e..0b1a57014f 100644
--- a/deployment/Dockerfile.docker.amd64
+++ b/deployment/Dockerfile.docker.amd64
@@ -1,6 +1,6 @@
-ARG DOTNET_VERSION=3.1
+ARG DOTNET_VERSION=5.0
-FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster
+FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION}-buster-slim
ARG SOURCE_DIR=/src
ARG ARTIFACT_DIR=/jellyfin
diff --git a/deployment/Dockerfile.docker.arm64 b/deployment/Dockerfile.docker.arm64
index a7ac40492a..583f53ca09 100644
--- a/deployment/Dockerfile.docker.arm64
+++ b/deployment/Dockerfile.docker.arm64
@@ -1,6 +1,6 @@
-ARG DOTNET_VERSION=3.1
+ARG DOTNET_VERSION=5.0
-FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster
+FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION}-buster-slim
ARG SOURCE_DIR=/src
ARG ARTIFACT_DIR=/jellyfin
diff --git a/deployment/Dockerfile.docker.armhf b/deployment/Dockerfile.docker.armhf
index b5a42f55ff..177c117134 100644
--- a/deployment/Dockerfile.docker.armhf
+++ b/deployment/Dockerfile.docker.armhf
@@ -1,6 +1,6 @@
-ARG DOTNET_VERSION=3.1
+ARG DOTNET_VERSION=5.0
-FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster
+FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION}-buster-slim
ARG SOURCE_DIR=/src
ARG ARTIFACT_DIR=/jellyfin
diff --git a/deployment/Dockerfile.fedora.amd64 b/deployment/Dockerfile.fedora.amd64
index 01b99deb6d..2549f25ee7 100644
--- a/deployment/Dockerfile.fedora.amd64
+++ b/deployment/Dockerfile.fedora.amd64
@@ -1,8 +1,8 @@
-FROM fedora:31
+FROM fedora:33
# Docker build arguments
ARG SOURCE_DIR=/jellyfin
ARG ARTIFACT_DIR=/dist
-ARG SDK_VERSION=3.1
+ARG SDK_VERSION=5.0
# Docker run environment
ENV SOURCE_DIR=/jellyfin
ENV ARTIFACT_DIR=/dist
@@ -10,7 +10,7 @@ ENV IS_DOCKER=YES
# Prepare Fedora environment
RUN dnf update -y \
- && dnf install -y @buildsys-build rpmdevtools git dnf-plugins-core libcurl-devel fontconfig-devel freetype-devel openssl-devel glibc-devel libicu-devel
+ && dnf install -y @buildsys-build rpmdevtools git dnf-plugins-core libcurl-devel fontconfig-devel freetype-devel openssl-devel glibc-devel libicu-devel systemd
# Install DotNET SDK
RUN rpm --import https://packages.microsoft.com/keys/microsoft.asc \
diff --git a/deployment/Dockerfile.linux.amd64 b/deployment/Dockerfile.linux.amd64
index 828d5c2cf9..2bedafcc5a 100644
--- a/deployment/Dockerfile.linux.amd64
+++ b/deployment/Dockerfile.linux.amd64
@@ -2,7 +2,7 @@ FROM debian:10
# Docker build arguments
ARG SOURCE_DIR=/jellyfin
ARG ARTIFACT_DIR=/dist
-ARG SDK_VERSION=3.1
+ARG SDK_VERSION=5.0
# Docker run environment
ENV SOURCE_DIR=/jellyfin
ENV ARTIFACT_DIR=/dist
@@ -16,7 +16,7 @@ RUN apt-get update \
# Install dotnet repository
# https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current
-RUN wget https://download.visualstudio.microsoft.com/download/pr/f01e3d97-c1c3-4635-bc77-0c893be36820/6ec6acabc22468c6cc68b61625b14a7d/dotnet-sdk-3.1.402-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
+RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
&& mkdir -p dotnet-sdk \
&& tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \
&& ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet
diff --git a/deployment/Dockerfile.macos b/deployment/Dockerfile.macos
index 0b2a0fe5fa..d470f9b749 100644
--- a/deployment/Dockerfile.macos
+++ b/deployment/Dockerfile.macos
@@ -2,7 +2,7 @@ FROM debian:10
# Docker build arguments
ARG SOURCE_DIR=/jellyfin
ARG ARTIFACT_DIR=/dist
-ARG SDK_VERSION=3.1
+ARG SDK_VERSION=5.0
# Docker run environment
ENV SOURCE_DIR=/jellyfin
ENV ARTIFACT_DIR=/dist
@@ -16,7 +16,7 @@ RUN apt-get update \
# Install dotnet repository
# https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current
-RUN wget https://download.visualstudio.microsoft.com/download/pr/f01e3d97-c1c3-4635-bc77-0c893be36820/6ec6acabc22468c6cc68b61625b14a7d/dotnet-sdk-3.1.402-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
+RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
&& mkdir -p dotnet-sdk \
&& tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \
&& ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet
diff --git a/deployment/Dockerfile.portable b/deployment/Dockerfile.portable
index 7d5de230fa..d2007c0751 100644
--- a/deployment/Dockerfile.portable
+++ b/deployment/Dockerfile.portable
@@ -2,7 +2,7 @@ FROM debian:10
# Docker build arguments
ARG SOURCE_DIR=/jellyfin
ARG ARTIFACT_DIR=/dist
-ARG SDK_VERSION=3.1
+ARG SDK_VERSION=5.0
# Docker run environment
ENV SOURCE_DIR=/jellyfin
ENV ARTIFACT_DIR=/dist
@@ -15,7 +15,7 @@ RUN apt-get update \
# Install dotnet repository
# https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current
-RUN wget https://download.visualstudio.microsoft.com/download/pr/f01e3d97-c1c3-4635-bc77-0c893be36820/6ec6acabc22468c6cc68b61625b14a7d/dotnet-sdk-3.1.402-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
+RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
&& mkdir -p dotnet-sdk \
&& tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \
&& ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet
diff --git a/deployment/Dockerfile.ubuntu.amd64 b/deployment/Dockerfile.ubuntu.amd64
index 9c63f43dfa..084159d459 100644
--- a/deployment/Dockerfile.ubuntu.amd64
+++ b/deployment/Dockerfile.ubuntu.amd64
@@ -2,7 +2,7 @@ FROM ubuntu:bionic
# Docker build arguments
ARG SOURCE_DIR=/jellyfin
ARG ARTIFACT_DIR=/dist
-ARG SDK_VERSION=3.1
+ARG SDK_VERSION=5.0
# Docker run environment
ENV SOURCE_DIR=/jellyfin
ENV ARTIFACT_DIR=/dist
@@ -16,7 +16,7 @@ RUN apt-get update \
# Install dotnet repository
# https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current
-RUN wget https://download.visualstudio.microsoft.com/download/pr/f01e3d97-c1c3-4635-bc77-0c893be36820/6ec6acabc22468c6cc68b61625b14a7d/dotnet-sdk-3.1.402-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
+RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
&& mkdir -p dotnet-sdk \
&& tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \
&& ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet
diff --git a/deployment/Dockerfile.ubuntu.arm64 b/deployment/Dockerfile.ubuntu.arm64
index 51612dd443..c2caf4cf8e 100644
--- a/deployment/Dockerfile.ubuntu.arm64
+++ b/deployment/Dockerfile.ubuntu.arm64
@@ -2,7 +2,7 @@ FROM ubuntu:bionic
# Docker build arguments
ARG SOURCE_DIR=/jellyfin
ARG ARTIFACT_DIR=/dist
-ARG SDK_VERSION=3.1
+ARG SDK_VERSION=5.0
# Docker run environment
ENV SOURCE_DIR=/jellyfin
ENV ARTIFACT_DIR=/dist
@@ -16,7 +16,7 @@ RUN apt-get update \
# Install dotnet repository
# https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current
-RUN wget https://download.visualstudio.microsoft.com/download/pr/f01e3d97-c1c3-4635-bc77-0c893be36820/6ec6acabc22468c6cc68b61625b14a7d/dotnet-sdk-3.1.402-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
+RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
&& mkdir -p dotnet-sdk \
&& tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \
&& ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet
diff --git a/deployment/Dockerfile.ubuntu.armhf b/deployment/Dockerfile.ubuntu.armhf
index 4ed7f86872..719b3a85b6 100644
--- a/deployment/Dockerfile.ubuntu.armhf
+++ b/deployment/Dockerfile.ubuntu.armhf
@@ -2,7 +2,7 @@ FROM ubuntu:bionic
# Docker build arguments
ARG SOURCE_DIR=/jellyfin
ARG ARTIFACT_DIR=/dist
-ARG SDK_VERSION=3.1
+ARG SDK_VERSION=5.0
# Docker run environment
ENV SOURCE_DIR=/jellyfin
ENV ARTIFACT_DIR=/dist
@@ -16,7 +16,7 @@ RUN apt-get update \
# Install dotnet repository
# https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current
-RUN wget https://download.visualstudio.microsoft.com/download/pr/f01e3d97-c1c3-4635-bc77-0c893be36820/6ec6acabc22468c6cc68b61625b14a7d/dotnet-sdk-3.1.402-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
+RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
&& mkdir -p dotnet-sdk \
&& tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \
&& ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet
diff --git a/deployment/Dockerfile.windows.amd64 b/deployment/Dockerfile.windows.amd64
index 5671cc598a..e6905c906d 100644
--- a/deployment/Dockerfile.windows.amd64
+++ b/deployment/Dockerfile.windows.amd64
@@ -2,7 +2,7 @@ FROM debian:10
# Docker build arguments
ARG SOURCE_DIR=/jellyfin
ARG ARTIFACT_DIR=/dist
-ARG SDK_VERSION=3.1
+ARG SDK_VERSION=5.0
# Docker run environment
ENV SOURCE_DIR=/jellyfin
ENV ARTIFACT_DIR=/dist
@@ -15,7 +15,7 @@ RUN apt-get update \
# Install dotnet repository
# https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current
-RUN wget https://download.visualstudio.microsoft.com/download/pr/f01e3d97-c1c3-4635-bc77-0c893be36820/6ec6acabc22468c6cc68b61625b14a7d/dotnet-sdk-3.1.402-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
+RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \
&& mkdir -p dotnet-sdk \
&& tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \
&& ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet
diff --git a/deployment/build.debian.amd64 b/deployment/build.debian.amd64
index 012e1cebf6..145e28d871 100755
--- a/deployment/build.debian.amd64
+++ b/deployment/build.debian.amd64
@@ -9,9 +9,9 @@ set -o xtrace
pushd ${SOURCE_DIR}
if [[ ${IS_DOCKER} == YES ]]; then
- # Remove build-dep for dotnet-sdk-3.1, since it's installed manually
+ # Remove build-dep for dotnet-sdk-5.0, since it's installed manually
cp -a debian/control /tmp/control.orig
- sed -i '/dotnet-sdk-3.1,/d' debian/control
+ sed -i '/dotnet-sdk-5.0,/d' debian/control
fi
# Modify changelog to unstable configuration if IS_UNSTABLE
diff --git a/deployment/build.debian.arm64 b/deployment/build.debian.arm64
index 12ce3e874d..5699133a01 100755
--- a/deployment/build.debian.arm64
+++ b/deployment/build.debian.arm64
@@ -9,9 +9,9 @@ set -o xtrace
pushd ${SOURCE_DIR}
if [[ ${IS_DOCKER} == YES ]]; then
- # Remove build-dep for dotnet-sdk-3.1, since it's installed manually
+ # Remove build-dep for dotnet-sdk-5.0, since it's installed manually
cp -a debian/control /tmp/control.orig
- sed -i '/dotnet-sdk-3.1,/d' debian/control
+ sed -i '/dotnet-sdk-5.0,/d' debian/control
fi
# Modify changelog to unstable configuration if IS_UNSTABLE
diff --git a/deployment/build.debian.armhf b/deployment/build.debian.armhf
index 3089eab585..20af2ddfbe 100755
--- a/deployment/build.debian.armhf
+++ b/deployment/build.debian.armhf
@@ -9,9 +9,9 @@ set -o xtrace
pushd ${SOURCE_DIR}
if [[ ${IS_DOCKER} == YES ]]; then
- # Remove build-dep for dotnet-sdk-3.1, since it's installed manually
+ # Remove build-dep for dotnet-sdk-5.0, since it's installed manually
cp -a debian/control /tmp/control.orig
- sed -i '/dotnet-sdk-3.1,/d' debian/control
+ sed -i '/dotnet-sdk-5.0,/d' debian/control
fi
# Modify changelog to unstable configuration if IS_UNSTABLE
diff --git a/deployment/build.ubuntu.amd64 b/deployment/build.ubuntu.amd64
index 0eac9cdd10..0c29286c02 100755
--- a/deployment/build.ubuntu.amd64
+++ b/deployment/build.ubuntu.amd64
@@ -9,9 +9,9 @@ set -o xtrace
pushd ${SOURCE_DIR}
if [[ ${IS_DOCKER} == YES ]]; then
- # Remove build-dep for dotnet-sdk-3.1, since it's installed manually
+ # Remove build-dep for dotnet-sdk-5.0, since it's installed manually
cp -a debian/control /tmp/control.orig
- sed -i '/dotnet-sdk-3.1,/d' debian/control
+ sed -i '/dotnet-sdk-5.0,/d' debian/control
fi
# Modify changelog to unstable configuration if IS_UNSTABLE
diff --git a/deployment/build.ubuntu.arm64 b/deployment/build.ubuntu.arm64
index 5b11fd543b..65d67f80f7 100755
--- a/deployment/build.ubuntu.arm64
+++ b/deployment/build.ubuntu.arm64
@@ -9,9 +9,9 @@ set -o xtrace
pushd ${SOURCE_DIR}
if [[ ${IS_DOCKER} == YES ]]; then
- # Remove build-dep for dotnet-sdk-3.1, since it's installed manually
+ # Remove build-dep for dotnet-sdk-5.0, since it's installed manually
cp -a debian/control /tmp/control.orig
- sed -i '/dotnet-sdk-3.1,/d' debian/control
+ sed -i '/dotnet-sdk-5.0,/d' debian/control
fi
# Modify changelog to unstable configuration if IS_UNSTABLE
diff --git a/deployment/build.ubuntu.armhf b/deployment/build.ubuntu.armhf
index 4734cf6588..370370abc1 100755
--- a/deployment/build.ubuntu.armhf
+++ b/deployment/build.ubuntu.armhf
@@ -9,9 +9,9 @@ set -o xtrace
pushd ${SOURCE_DIR}
if [[ ${IS_DOCKER} == YES ]]; then
- # Remove build-dep for dotnet-sdk-3.1, since it's installed manually
+ # Remove build-dep for dotnet-sdk-5.0, since it's installed manually
cp -a debian/control /tmp/control.orig
- sed -i '/dotnet-sdk-3.1,/d' debian/control
+ sed -i '/dotnet-sdk-5.0,/d' debian/control
fi
# Modify changelog to unstable configuration if IS_UNSTABLE
diff --git a/deployment/build.windows.amd64 b/deployment/build.windows.amd64
index afe4905769..a9daa6a239 100755
--- a/deployment/build.windows.amd64
+++ b/deployment/build.windows.amd64
@@ -35,10 +35,6 @@ unzip ${addin_build_dir}/jellyfin-ffmpeg.zip -d ${addin_build_dir}/jellyfin-ffmp
cp ${addin_build_dir}/jellyfin-ffmpeg/* ${output_dir}
rm -rf ${addin_build_dir}
-# Prepare scripts
-cp ${SOURCE_DIR}/windows/legacy/install-jellyfin.ps1 ${output_dir}/install-jellyfin.ps1
-cp ${SOURCE_DIR}/windows/legacy/install.bat ${output_dir}/install.bat
-
# Create zip package
pushd dist
zip -qr jellyfin-server_${version}.portable.zip jellyfin-server_${version}
diff --git a/fedora/jellyfin.spec b/fedora/jellyfin.spec
index bfb2b3be29..13305488e2 100644
--- a/fedora/jellyfin.spec
+++ b/fedora/jellyfin.spec
@@ -27,7 +27,7 @@ BuildRequires: libcurl-devel, fontconfig-devel, freetype-devel, openssl-devel,
# Requirements not packaged in main repos
# COPR @dotnet-sig/dotnet or
# https://packages.microsoft.com/rhel/7/prod/
-BuildRequires: dotnet-runtime-3.1, dotnet-sdk-3.1
+BuildRequires: dotnet-runtime-5.0, dotnet-sdk-5.0
Requires: %{name}-server = %{version}-%{release}, %{name}-web >= 10.6, %{name}-web < 10.7
# Disable Automatic Dependency Processing
AutoReqProv: no
@@ -79,18 +79,9 @@ EOF
%files server
%attr(755,root,root) %{_bindir}/jellyfin
-%{_libdir}/jellyfin/*.json
-%{_libdir}/jellyfin/*.dll
-%{_libdir}/jellyfin/*.so
-%{_libdir}/jellyfin/*.a
-%{_libdir}/jellyfin/createdump
-%{_libdir}/jellyfin/*.xml
-%{_libdir}/jellyfin/wwwroot/api-docs/*
-%{_libdir}/jellyfin/wwwroot/api-docs/redoc/*
-%{_libdir}/jellyfin/wwwroot/api-docs/swagger/*
+%{_libdir}/jellyfin/*
# Needs 755 else only root can run it since binary build by dotnet is 722
%attr(755,root,root) %{_libdir}/jellyfin/jellyfin
-%{_libdir}/jellyfin/SOS_README.md
%{_unitdir}/jellyfin.service
%{_libexecdir}/jellyfin/restart.sh
%{_prefix}/lib/firewalld/services/jellyfin.xml
diff --git a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs
index 4ea5094b66..90c4916668 100644
--- a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs
+++ b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs
@@ -8,6 +8,7 @@ using Jellyfin.Api.Auth;
using Jellyfin.Api.Constants;
using Jellyfin.Data.Entities;
using Jellyfin.Data.Enums;
+using MediaBrowser.Controller.Authentication;
using MediaBrowser.Controller.Net;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
@@ -68,19 +69,19 @@ namespace Jellyfin.Api.Tests.Auth
}
[Fact]
- public async Task HandleAuthenticateAsyncShouldFailOnSecurityException()
+ public async Task HandleAuthenticateAsyncShouldFailOnAuthenticationException()
{
var errorMessage = _fixture.Create();
_jellyfinAuthServiceMock.Setup(
a => a.Authenticate(
It.IsAny()))
- .Throws(new SecurityException(errorMessage));
+ .Throws(new AuthenticationException(errorMessage));
var authenticateResult = await _sut.AuthenticateAsync();
Assert.False(authenticateResult.Succeeded);
- Assert.Equal(errorMessage, authenticateResult.Failure.Message);
+ Assert.Equal(errorMessage, authenticateResult.Failure?.Message);
}
[Fact]
@@ -99,7 +100,7 @@ namespace Jellyfin.Api.Tests.Auth
var authorizationInfo = SetupUser();
var authenticateResult = await _sut.AuthenticateAsync();
- Assert.True(authenticateResult.Principal.HasClaim(ClaimTypes.Name, authorizationInfo.User.Username));
+ Assert.True(authenticateResult.Principal?.HasClaim(ClaimTypes.Name, authorizationInfo.User.Username));
}
[Theory]
@@ -111,7 +112,7 @@ namespace Jellyfin.Api.Tests.Auth
var authenticateResult = await _sut.AuthenticateAsync();
var expectedRole = authorizationInfo.User.HasPermission(PermissionKind.IsAdministrator) ? UserRoles.Administrator : UserRoles.User;
- Assert.True(authenticateResult.Principal.HasClaim(ClaimTypes.Role, expectedRole));
+ Assert.True(authenticateResult.Principal?.HasClaim(ClaimTypes.Role, expectedRole));
}
[Fact]
@@ -120,7 +121,7 @@ namespace Jellyfin.Api.Tests.Auth
SetupUser();
var authenticatedResult = await _sut.AuthenticateAsync();
- Assert.Equal(_scheme.Name, authenticatedResult.Ticket.AuthenticationScheme);
+ Assert.Equal(_scheme.Name, authenticatedResult.Ticket?.AuthenticationScheme);
}
private AuthorizationInfo SetupUser(bool isAdmin = false)
@@ -128,6 +129,7 @@ namespace Jellyfin.Api.Tests.Auth
var authorizationInfo = _fixture.Create();
authorizationInfo.User = _fixture.Create();
authorizationInfo.User.SetPermission(PermissionKind.IsAdministrator, isAdmin);
+ authorizationInfo.IsApiKey = false;
_jellyfinAuthServiceMock.Setup(
a => a.Authenticate(
diff --git a/tests/Jellyfin.Api.Tests/BrandingServiceTests.cs b/tests/Jellyfin.Api.Tests/BrandingServiceTests.cs
index 6fc287420b..1cbe94c5b9 100644
--- a/tests/Jellyfin.Api.Tests/BrandingServiceTests.cs
+++ b/tests/Jellyfin.Api.Tests/BrandingServiceTests.cs
@@ -25,7 +25,7 @@ namespace Jellyfin.Api.Tests
// Assert
response.EnsureSuccessStatusCode();
- Assert.Equal("application/json; charset=utf-8", response.Content.Headers.ContentType.ToString());
+ Assert.Equal("application/json; charset=utf-8", response.Content.Headers.ContentType?.ToString());
var responseBody = await response.Content.ReadAsStreamAsync();
_ = await JsonSerializer.DeserializeAsync(responseBody);
}
@@ -43,7 +43,7 @@ namespace Jellyfin.Api.Tests
// Assert
response.EnsureSuccessStatusCode();
- Assert.Equal("text/css; charset=utf-8", response.Content.Headers.ContentType.ToString());
+ Assert.Equal("text/css; charset=utf-8", response.Content.Headers.ContentType?.ToString());
}
}
}
diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj
index e3a7a54286..14eed30e03 100644
--- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj
+++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj
@@ -6,23 +6,23 @@
- netcoreapp3.1
+ net5.0
false
true
enable
-
-
-
-
-
-
+
+
+
+
+
+
-
+
diff --git a/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs b/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs
index 77f1640fa3..bd3d356870 100644
--- a/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs
+++ b/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs
@@ -47,8 +47,7 @@ namespace Jellyfin.Api.Tests
// Specify the startup command line options
var commandLineOpts = new StartupOptions
{
- NoWebClient = true,
- NoAutoRunWebApp = true
+ NoWebClient = true
};
// Use a temporary directory for the application paths
diff --git a/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs b/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs
new file mode 100644
index 0000000000..3ae6ae5bdd
--- /dev/null
+++ b/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs
@@ -0,0 +1,226 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Threading.Tasks;
+using Jellyfin.Api.ModelBinders;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+using Microsoft.Extensions.Logging.Abstractions;
+using Microsoft.Extensions.Primitives;
+using Moq;
+using Xunit;
+
+namespace Jellyfin.Api.Tests.ModelBinders
+{
+ public sealed class CommaDelimitedArrayModelBinderTests
+ {
+ [Fact]
+ public async Task BindModelAsync_CorrectlyBindsValidCommaDelimitedStringArrayQuery()
+ {
+ var queryParamName = "test";
+ IReadOnlyList queryParamValues = new[] { "lol", "xd" };
+ var queryParamString = "lol,xd";
+ var queryParamType = typeof(string[]);
+
+ var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger());
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary { { queryParamName, new StringValues(queryParamString) } }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Equal((IReadOnlyList?)bindingContextMock.Object?.Result.Model, queryParamValues);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_CorrectlyBindsValidCommaDelimitedIntArrayQuery()
+ {
+ var queryParamName = "test";
+ IReadOnlyList queryParamValues = new[] { 42, 0 };
+ var queryParamString = "42,0";
+ var queryParamType = typeof(int[]);
+
+ var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger());
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary { { queryParamName, new StringValues(queryParamString) } }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Equal((IReadOnlyList?)bindingContextMock.Object.Result.Model, queryParamValues);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_CorrectlyBindsValidCommaDelimitedEnumArrayQuery()
+ {
+ var queryParamName = "test";
+ IReadOnlyList queryParamValues = new[] { TestType.How, TestType.Much };
+ var queryParamString = "How,Much";
+ var queryParamType = typeof(TestType[]);
+
+ var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger());
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary { { queryParamName, new StringValues(queryParamString) } }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Equal((IReadOnlyList?)bindingContextMock.Object.Result.Model, queryParamValues);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_CorrectlyBindsValidCommaDelimitedEnumArrayQueryWithDoubleCommas()
+ {
+ var queryParamName = "test";
+ IReadOnlyList queryParamValues = new[] { TestType.How, TestType.Much };
+ var queryParamString = "How,,Much";
+ var queryParamType = typeof(TestType[]);
+
+ var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger());
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary { { queryParamName, new StringValues(queryParamString) } }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Equal((IReadOnlyList?)bindingContextMock.Object.Result.Model, queryParamValues);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_CorrectlyBindsValidEnumArrayQuery()
+ {
+ var queryParamName = "test";
+ IReadOnlyList queryParamValues = new[] { TestType.How, TestType.Much };
+ var queryParamString1 = "How";
+ var queryParamString2 = "Much";
+ var queryParamType = typeof(TestType[]);
+
+ var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger());
+
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary
+ {
+ { queryParamName, new StringValues(new[] { queryParamString1, queryParamString2 }) },
+ }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Equal((IReadOnlyList?)bindingContextMock.Object.Result.Model, queryParamValues);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_CorrectlyBindsEmptyEnumArrayQuery()
+ {
+ var queryParamName = "test";
+ IReadOnlyList queryParamValues = Array.Empty();
+ var queryParamType = typeof(TestType[]);
+
+ var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger());
+
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary
+ {
+ { queryParamName, new StringValues(value: null) },
+ }),
+ CultureInfo.InvariantCulture);
+ var bindingContextMock = new Mock();
+ bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider);
+ bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName);
+ bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType);
+ bindingContextMock.SetupProperty(b => b.Result);
+
+ await modelBinder.BindModelAsync(bindingContextMock.Object);
+
+ Assert.True(bindingContextMock.Object.Result.IsModelSet);
+ Assert.Equal((IReadOnlyList?)bindingContextMock.Object.Result.Model, queryParamValues);
+ }
+
+ [Fact]
+ public async Task BindModelAsync_EnumArrayQuery_BindValidOnly()
+ {
+ var queryParamName = "test";
+ var queryParamString = "🔥,😢";
+ var queryParamType = typeof(IReadOnlyList);
+
+ var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger());
+ var valueProvider = new QueryStringValueProvider(
+ new BindingSource(string.Empty, string.Empty, false, false),
+ new QueryCollection(new Dictionary