diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml
index 46db0d9fe5..46c478b08d 100644
--- a/.ci/azure-pipelines.yml
+++ b/.ci/azure-pipelines.yml
@@ -2,7 +2,7 @@ name: $(Date:yyyyMMdd)$(Rev:.r)
variables:
- name: TestProjects
- value: 'Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj'
+ value: 'tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj'
- name: RestoreBuildProjects
value: 'Jellyfin.Server/Jellyfin.Server.csproj'
@@ -28,29 +28,43 @@ jobs:
- checkout: self
clean: true
submodules: true
- persistCredentials: false
+ persistCredentials: true
- - task: DotNetCoreCLI@2
- displayName: Restore
+ - task: CmdLine@2
+ displayName: "Check out web"
+ condition: and(succeeded(), or(contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI', 'BuildCompletion'))
inputs:
- command: restore
- projects: '$(RestoreBuildProjects)'
- enabled: false
+ script: 'git clone --single-branch --branch $(Build.SourceBranchName) --depth=1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web'
- - task: DotNetCoreCLI@2
- displayName: Build
+ - task: CmdLine@2
+ displayName: "Check out web (PR)"
+ condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest'))
inputs:
- projects: '$(RestoreBuildProjects)'
- arguments: '--configuration $(BuildConfiguration)'
- enabled: false
+ script: 'git clone --single-branch --branch $(System.PullRequest.TargetBranch) --depth 1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web'
- - task: DotNetCoreCLI@2
- displayName: Test
+ - task: NodeTool@0
+ displayName: 'Install Node.js'
+ condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion'))
inputs:
- command: test
- projects: '$(RestoreBuildProjects)'
- arguments: '--configuration $(BuildConfiguration)'
- enabled: false
+ versionSpec: '10.x'
+
+ - task: CmdLine@2
+ displayName: "Build Web UI"
+ condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion'))
+ inputs:
+ script: yarn install
+ workingDirectory: $(Agent.TempDirectory)/jellyfin-web
+
+ - task: CopyFiles@2
+ displayName: Copy the web UI
+ condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion'))
+ inputs:
+ sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist # Optional
+ contents: '**'
+ targetFolder: $(Build.SourcesDirectory)/MediaBrowser.WebDashboard/jellyfin-web
+ cleanTargetFolder: true # Optional
+ overWrite: true # Optional
+ flattenFolders: false # Optional
- task: DotNetCoreCLI@2
displayName: Publish
@@ -61,13 +75,6 @@ jobs:
arguments: '--configuration $(BuildConfiguration) --output $(build.artifactstagingdirectory)'
zipAfterPublish: false
- # - task: PublishBuildArtifacts@1
- # displayName: 'Publish Artifact'
- # inputs:
- # PathtoPublish: '$(build.artifactstagingdirectory)'
- # artifactName: 'jellyfin-build-$(BuildConfiguration)'
- # zipAfterPublish: true
-
- task: PublishPipelineArtifact@0
displayName: 'Publish Artifact Naming'
condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded())
@@ -96,6 +103,173 @@ jobs:
targetPath: '$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Common.dll'
artifactName: 'Jellyfin.Common'
+ - job: main_test
+ displayName: Main Test
+ pool:
+ vmImage: windows-latest
+ steps:
+ - checkout: self
+ clean: true
+ submodules: true
+ persistCredentials: false
+
+ - task: DotNetCoreCLI@2
+ displayName: Build
+ inputs:
+ command: build
+ publishWebProjects: false
+ projects: '$(TestProjects)'
+ arguments: '--configuration $(BuildConfiguration)'
+ zipAfterPublish: false
+
+ - task: VisualStudioTestPlatformInstaller@1
+ inputs:
+ packageFeedSelector: 'nugetOrg' # Options: nugetOrg, customFeed, netShare
+ versionSelector: 'latestPreRelease' # Required when packageFeedSelector == NugetOrg || PackageFeedSelector == CustomFeed# Options: latestPreRelease, latestStable, specificVersion
+
+ - task: VSTest@2
+ inputs:
+ testSelector: 'testAssemblies' # Options: testAssemblies, testPlan, testRun
+ testAssemblyVer2: | # Required when testSelector == TestAssemblies
+ **\bin\$(BuildConfiguration)\**\*test*.dll
+ !**\obj\**
+ !**\xunit.runner.visualstudio.testadapter.dll
+ !**\xunit.runner.visualstudio.dotnetcore.testadapter.dll
+ #testPlan: # Required when testSelector == TestPlan
+ #testSuite: # Required when testSelector == TestPlan
+ #testConfiguration: # Required when testSelector == TestPlan
+ #tcmTestRun: '$(test.RunId)' # Optional
+ searchFolder: '$(System.DefaultWorkingDirectory)'
+ #testFiltercriteria: # Optional
+ #runOnlyImpactedTests: False # Optional
+ #runAllTestsAfterXBuilds: '50' # Optional
+ #uiTests: false # Optional
+ #vstestLocationMethod: 'version' # Optional. Options: version, location
+ #vsTestVersion: 'latest' # Optional. Options: latest, 16.0, 15.0, 14.0, toolsInstaller
+ #vstestLocation: # Optional
+ #runSettingsFile: # Optional
+ #overrideTestrunParameters: # Optional
+ #pathtoCustomTestAdapters: # Optional
+ runInParallel: True # Optional
+ runTestsInIsolation: True # Optional
+ codeCoverageEnabled: True # Optional
+ #otherConsoleOptions: # Optional
+ #distributionBatchType: 'basedOnTestCases' # Optional. Options: basedOnTestCases, basedOnExecutionTime, basedOnAssembly
+ #batchingBasedOnAgentsOption: 'autoBatchSize' # Optional. Options: autoBatchSize, customBatchSize
+ #customBatchSizeValue: '10' # Required when distributionBatchType == BasedOnTestCases && BatchingBasedOnAgentsOption == CustomBatchSize
+ #batchingBasedOnExecutionTimeOption: 'autoBatchSize' # Optional. Options: autoBatchSize, customTimeBatchSize
+ #customRunTimePerBatchValue: '60' # Required when distributionBatchType == BasedOnExecutionTime && BatchingBasedOnExecutionTimeOption == CustomTimeBatchSize
+ #dontDistribute: False # Optional
+ #testRunTitle: # Optional
+ #platform: # Optional
+ configuration: 'Debug' # Optional
+ publishRunAttachments: true # Optional
+ #diagnosticsEnabled: false # Optional
+ #collectDumpOn: 'onAbortOnly' # Optional. Options: onAbortOnly, always, never
+ #rerunFailedTests: False # Optional
+ #rerunType: 'basedOnTestFailurePercentage' # Optional. Options: basedOnTestFailurePercentage, basedOnTestFailureCount
+ #rerunFailedThreshold: '30' # Optional
+ #rerunFailedTestCasesMaxLimit: '5' # Optional
+ #rerunMaxAttempts: '3' # Optional
+
+ # - task: PublishTestResults@2
+ # inputs:
+ # testResultsFormat: 'VSTest' # Options: JUnit, NUnit, VSTest, xUnit, cTest
+ # testResultsFiles: '**/*.trx'
+ # #searchFolder: '$(System.DefaultWorkingDirectory)' # Optional
+ # mergeTestResults: true # Optional
+ # #failTaskOnFailedTests: false # Optional
+ # #testRunTitle: # Optional
+ # #buildPlatform: # Optional
+ # #buildConfiguration: # Optional
+ # #publishRunAttachments: true # Optional
+
+ - job: main_build_win
+ displayName: Main Build Windows
+ pool:
+ vmImage: windows-latest
+ strategy:
+ matrix:
+ release:
+ BuildConfiguration: Release
+ maxParallel: 2
+ steps:
+ - checkout: self
+ clean: true
+ submodules: true
+ persistCredentials: true
+
+ - task: CmdLine@2
+ displayName: "Check out web"
+ condition: and(succeeded(), or(contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI', 'BuildCompletion'))
+ inputs:
+ script: 'git clone --single-branch --branch $(Build.SourceBranchName) --depth=1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web'
+
+ - task: CmdLine@2
+ displayName: "Check out web (PR)"
+ condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest'))
+ inputs:
+ script: 'git clone --single-branch --branch $(System.PullRequest.TargetBranch) --depth 1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web'
+
+ - task: NodeTool@0
+ displayName: 'Install Node.js'
+ condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion'))
+ inputs:
+ versionSpec: '10.x'
+
+ - task: CmdLine@2
+ displayName: "Build Web UI"
+ condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion'))
+ inputs:
+ script: yarn install
+ workingDirectory: $(Agent.TempDirectory)/jellyfin-web
+
+ - task: CopyFiles@2
+ displayName: Copy the web UI
+ condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion'))
+ inputs:
+ sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist # Optional
+ contents: '**'
+ targetFolder: $(Build.SourcesDirectory)/MediaBrowser.WebDashboard/jellyfin-web
+ cleanTargetFolder: true # Optional
+ overWrite: true # Optional
+ flattenFolders: false # Optional
+
+ - task: CmdLine@2
+ displayName: Clone the UX repository
+ inputs:
+ script: git clone --depth=1 https://github.com/jellyfin/jellyfin-ux $(Agent.TempDirectory)\jellyfin-ux
+
+ - task: PowerShell@2
+ displayName: Build the NSIS Installer
+ inputs:
+ targetType: 'filePath' # Optional. Options: filePath, inline
+ filePath: ./deployment/windows/build-jellyfin.ps1 # Required when targetType == FilePath
+ arguments: -InstallFFMPEG -InstallNSSM -MakeNSIS -UXLocation $(Agent.TempDirectory)\jellyfin-ux -InstallLocation $(build.artifactstagingdirectory)
+ #script: '# Write your PowerShell commands here.Write-Host Hello World' # Required when targetType == Inline
+ errorActionPreference: 'stop' # Optional. Options: stop, continue, silentlyContinue
+ #failOnStderr: false # Optional
+ #ignoreLASTEXITCODE: false # Optional
+ #pwsh: false # Optional
+ workingDirectory: $(Build.SourcesDirectory) # Optional
+
+ - task: CopyFiles@2
+ displayName: Copy the NSIS Installer to the artifact directory
+ inputs:
+ sourceFolder: $(Build.SourcesDirectory)/deployment/windows/ # Optional
+ contents: 'jellyfin*.exe'
+ targetFolder: $(System.ArtifactsDirectory)/setup
+ cleanTargetFolder: true # Optional
+ overWrite: true # Optional
+ flattenFolders: true # Optional
+
+ - task: PublishPipelineArtifact@0
+ displayName: 'Publish Setup Artifact'
+ condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded())
+ inputs:
+ targetPath: '$(build.artifactstagingdirectory)/setup'
+ artifactName: 'Jellyfin Server Setup'
+
- job: dotnet_compat
displayName: Compatibility Check
pool:
diff --git a/.ci/publish-nightly.yml b/.ci/publish-nightly.yml
new file mode 100644
index 0000000000..a693e10f6c
--- /dev/null
+++ b/.ci/publish-nightly.yml
@@ -0,0 +1,46 @@
+name: Nightly-$(date:yyyyMMdd).$(rev:r)
+
+variables:
+ - name: Version
+ value: '1.0.0'
+
+trigger: none
+pr: none
+
+jobs:
+ - job: publish_artifacts_nightly
+ displayName: Publish Artifacts Nightly
+ pool:
+ vmImage: ubuntu-latest
+ steps:
+ - checkout: none
+ - task: DownloadPipelineArtifact@2
+ displayName: Download the Windows Setup Artifact
+ inputs:
+ source: 'specific' # Options: current, specific
+ artifact: 'Jellyfin Server Setup' # Optional
+ path: '$(System.ArtifactsDirectory)/win-installer'
+ project: '$(System.TeamProjectId)' # Required when source == Specific
+ pipelineId: 1 # Required when source == Specific
+ runVersion: 'latestFromBranch' # Required when source == Specific. Options: latest, latestFromBranch, specific
+ runBranch: 'refs/heads/master' # Required when source == Specific && runVersion == LatestFromBranch
+
+ - task: SSH@0
+ displayName: 'Create Drop directory'
+ inputs:
+ sshEndpoint: 'Jellyfin Build Server'
+ commands: 'mkdir -p /srv/incoming/jellyfin_$(Version)/win-installer && ln -s /srv/incoming/jellyfin_$(Version) /srv/incoming/jellyfin_nightly_azure_upload'
+
+ - task: CopyFilesOverSSH@0
+ displayName: 'Copy the Windows Setup to the Repo'
+ inputs:
+ sshEndpoint: 'Jellyfin Build Server'
+ sourceFolder: '$(System.ArtifactsDirectory)/win-installer'
+ contents: 'jellyfin_*.exe'
+ targetFolder: '/srv/incoming/jellyfin_nightly_azure_upload/win-installer'
+
+ - task: SSH@0
+ displayName: 'Clean up SCP symlink'
+ inputs:
+ sshEndpoint: 'Jellyfin Build Server'
+ commands: 'rm -f /srv/incoming/jellyfin_nightly_azure_upload'
diff --git a/.ci/publish-release.yml b/.ci/publish-release.yml
new file mode 100644
index 0000000000..57e77ae5aa
--- /dev/null
+++ b/.ci/publish-release.yml
@@ -0,0 +1,48 @@
+name: Release-$(Version)-$(date:yyyyMMdd).$(rev:r)
+
+variables:
+ - name: Version
+ value: '1.0.0'
+ - name: UsedRunId
+ value: 0
+
+trigger: none
+pr: none
+
+jobs:
+ - job: publish_artifacts_release
+ displayName: Publish Artifacts Release
+ pool:
+ vmImage: ubuntu-latest
+ steps:
+ - checkout: none
+ - task: DownloadPipelineArtifact@2
+ displayName: Download the Windows Setup Artifact
+ inputs:
+ source: 'specific' # Options: current, specific
+ artifact: 'Jellyfin Server Setup' # Optional
+ path: '$(System.ArtifactsDirectory)/win-installer'
+ project: '$(System.TeamProjectId)' # Required when source == Specific
+ pipelineId: 1 # Required when source == Specific
+ runVersion: 'specific' # Required when source == Specific. Options: latest, latestFromBranch, specific
+ runId: $(UsedRunId)
+
+ - task: SSH@0
+ displayName: 'Create Drop directory'
+ inputs:
+ sshEndpoint: 'Jellyfin Build Server'
+ commands: 'mkdir -p /srv/incoming/jellyfin_$(Version)/win-installer && ln -s /srv/incoming/jellyfin_$(Version) /srv/incoming/jellyfin_release_azure_upload'
+
+ - task: CopyFilesOverSSH@0
+ displayName: 'Copy the Windows Setup to the Repo'
+ inputs:
+ sshEndpoint: 'Jellyfin Build Server'
+ sourceFolder: '$(System.ArtifactsDirectory)/win-installer'
+ contents: 'jellyfin_*.exe'
+ targetFolder: '/srv/incoming/jellyfin_release_azure_upload/win-installer'
+
+ - task: SSH@0
+ displayName: 'Clean up SCP symlink'
+ inputs:
+ sshEndpoint: 'Jellyfin Build Server'
+ commands: 'rm -f /srv/incoming/jellyfin_release_azure_upload'
diff --git a/.gitattributes b/.gitattributes
index d78b0459d8..8ae5997258 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,3 +1,5 @@
* text=auto eol=lf
+*.png binary
+*.jpg binary
CONTRIBUTORS.md merge=union
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 967be0fb73..dc93d2c84e 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -1,6 +1,6 @@
**Changes**
diff --git a/.github/stale.yml b/.github/stale.yml
index 011f763177..9ea0e3796a 100644
--- a/.github/stale.yml
+++ b/.github/stale.yml
@@ -1,7 +1,7 @@
# Number of days of inactivity before an issue becomes stale
-daysUntilStale: 60
+daysUntilStale: 90
# Number of days of inactivity before a stale issue is closed
-daysUntilClose: 7
+daysUntilClose: 14
# Issues with these labels will never be considered stale
exemptLabels:
- regression
@@ -15,8 +15,8 @@ exemptLabels:
staleLabel: stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
- Issues go stale after 60d of inactivity. Mark the issue as fresh by adding a comment or commit. Stale issues close after an additional 7d of inactivity.
+ Issues go stale after 90d of inactivity. Mark the issue as fresh by adding a comment or commit. Stale issues close after an additional 14d of inactivity.
If this issue is safe to close now please do so.
- If you have any questions you can reach us on [Matrix or Social Media](https://jellyfin.readthedocs.io/en/latest/getting-help/).
+ If you have any questions you can reach us on [Matrix or Social Media](https://docs.jellyfin.org/general/getting-help.html).
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false
diff --git a/.gitignore b/.gitignore
index 2ce41d76e7..34cf1a84c2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -264,3 +264,7 @@ ci/
# Doxygen
doc/
+
+# Deployment artifacts
+dist
+*.exe
diff --git a/.gitmodules b/.gitmodules
deleted file mode 100644
index 2b97b13311..0000000000
--- a/.gitmodules
+++ /dev/null
@@ -1,4 +0,0 @@
-[submodule "MediaBrowser.WebDashboard/jellyfin-web"]
- path = MediaBrowser.WebDashboard/jellyfin-web
- url = https://github.com/jellyfin/jellyfin-web.git
- branch = .
diff --git a/.vscode/launch.json b/.vscode/launch.json
index 21b8323ea0..e2a09c0f15 100644
--- a/.vscode/launch.json
+++ b/.vscode/launch.json
@@ -10,7 +10,7 @@
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
- "program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/netcoreapp2.1/jellyfin.dll",
+ "program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/netcoreapp3.0/jellyfin.dll",
"args": [],
"cwd": "${workspaceFolder}/Jellyfin.Server",
// For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window
@@ -25,4 +25,4 @@
"processId": "${command:pickProcess}"
}
,]
-}
\ No newline at end of file
+}
diff --git a/BDInfo/BDInfo.csproj b/BDInfo/BDInfo.csproj
index b2c752d0c8..9dbaa9e2f0 100644
--- a/BDInfo/BDInfo.csproj
+++ b/BDInfo/BDInfo.csproj
@@ -11,6 +11,7 @@
netstandard2.0
false
+ true
diff --git a/BDInfo/BDROM.cs b/BDInfo/BDROM.cs
index 6759ed55ad..3a0c14ffda 100644
--- a/BDInfo/BDROM.cs
+++ b/BDInfo/BDROM.cs
@@ -212,7 +212,6 @@ namespace BDInfo
public void Scan()
{
- var errorStreamClipFiles = new List();
foreach (var streamClipFile in StreamClipFiles.Values)
{
try
@@ -221,7 +220,6 @@ namespace BDInfo
}
catch (Exception ex)
{
- errorStreamClipFiles.Add(streamClipFile);
if (StreamClipFileScanError != null)
{
if (StreamClipFileScanError(streamClipFile, ex))
@@ -250,7 +248,6 @@ namespace BDInfo
StreamFiles.Values.CopyTo(streamFiles, 0);
Array.Sort(streamFiles, CompareStreamFiles);
- var errorPlaylistFiles = new List();
foreach (var playlistFile in PlaylistFiles.Values)
{
try
@@ -259,7 +256,6 @@ namespace BDInfo
}
catch (Exception ex)
{
- errorPlaylistFiles.Add(playlistFile);
if (PlaylistFileScanError != null)
{
if (PlaylistFileScanError(playlistFile, ex))
@@ -275,7 +271,6 @@ namespace BDInfo
}
}
- var errorStreamFiles = new List();
foreach (var streamFile in streamFiles)
{
try
@@ -296,7 +291,6 @@ namespace BDInfo
}
catch (Exception ex)
{
- errorStreamFiles.Add(streamFile);
if (StreamFileScanError != null)
{
if (StreamFileScanError(streamFile, ex))
@@ -431,7 +425,7 @@ namespace BDInfo
{
return 1;
}
- else if ((x != null || x.FileInfo != null) && (y == null || y.FileInfo == null))
+ else if ((x != null && x.FileInfo != null) && (y == null || y.FileInfo == null))
{
return -1;
}
@@ -451,6 +445,5 @@ namespace BDInfo
}
}
}
-
}
}
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index c96228f31d..f22944a8b6 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -28,6 +28,8 @@
- [DrPandemic](https://github.com/drpandemic)
- [joern-h](https://github.com/joern-h)
- [Khinenw](https://github.com/HelloWorld017)
+ - [fhriley](https://github.com/fhriley)
+ - [nevado](https://github.com/nevado)
# Emby Contributors
diff --git a/Dockerfile b/Dockerfile
index 1644a8967d..afa8152ff9 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,34 +1,48 @@
-ARG DOTNET_VERSION=2.2
+ARG DOTNET_VERSION=3.0
+ARG FFMPEG_VERSION=latest
+
+FROM node:alpine as web-builder
+ARG JELLYFIN_WEB_VERSION=master
+RUN apk add curl \
+ && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \
+ && cd jellyfin-web-* \
+ && yarn install \
+ && yarn build \
+ && mv dist /dist
FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION} as builder
WORKDIR /repo
COPY . .
ENV DOTNET_CLI_TELEMETRY_OPTOUT=1
-RUN bash -c "source deployment/common.build.sh && \
- build_jellyfin Jellyfin.Server Release linux-x64 /jellyfin"
+RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" --self-contained --runtime linux-x64 "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none"
+
+FROM jellyfin/ffmpeg:${FFMPEG_VERSION} as ffmpeg
+FROM debian:stretch-slim
-FROM jellyfin/ffmpeg as ffmpeg
-FROM mcr.microsoft.com/dotnet/core/runtime:${DOTNET_VERSION}
-# libfontconfig1 is required for Skia
+COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg
+COPY --from=builder /jellyfin /jellyfin
+COPY --from=web-builder /dist /jellyfin/jellyfin-web
+# Install dependencies:
+# libfontconfig1: needed for Skia
+# libgomp1: needed for ffmpeg
+# libva-drm2: needed for ffmpeg
+# mesa-va-drivers: needed for VAAPI
RUN apt-get update \
&& apt-get install --no-install-recommends --no-install-suggests -y \
- libfontconfig1 \
+ libfontconfig1 libgomp1 libva-drm2 mesa-va-drivers \
&& apt-get clean autoclean \
&& apt-get autoremove \
&& rm -rf /var/lib/apt/lists/* \
&& mkdir -p /cache /config /media \
- && chmod 777 /cache /config /media
-COPY --from=ffmpeg / /
-COPY --from=builder /jellyfin /jellyfin
+ && chmod 777 /cache /config /media \
+ && ln -s /opt/ffmpeg/bin/ffmpeg /usr/local/bin \
+ && ln -s /opt/ffmpeg/bin/ffprobe /usr/local/bin
-ARG JELLYFIN_WEB_VERSION=v10.3.7
-RUN curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \
- && rm -rf /jellyfin/jellyfin-web \
- && mv jellyfin-web-${JELLYFIN_WEB_VERSION} /jellyfin/jellyfin-web
+ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1
EXPOSE 8096
VOLUME /cache /config /media
-ENTRYPOINT dotnet /jellyfin/jellyfin.dll \
+ENTRYPOINT ./jellyfin/jellyfin \
--datadir /config \
--cachedir /cache \
--ffmpeg /usr/local/bin/ffmpeg
diff --git a/Dockerfile.arm b/Dockerfile.arm
index b0cf7a8a46..f8c8511ae5 100644
--- a/Dockerfile.arm
+++ b/Dockerfile.arm
@@ -3,21 +3,28 @@
ARG DOTNET_VERSION=3.0
+FROM node:alpine as web-builder
+ARG JELLYFIN_WEB_VERSION=master
+RUN apk add curl \
+ && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \
+ && cd jellyfin-web-* \
+ && yarn install \
+ && yarn build \
+ && mv dist /dist
+
+
FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION} as builder
WORKDIR /repo
COPY . .
ENV DOTNET_CLI_TELEMETRY_OPTOUT=1
-# TODO Remove or update the sed line when we update dotnet version.
-RUN find . -type f -exec sed -i 's/netcoreapp2.1/netcoreapp3.0/g' {} \;
# Discard objs - may cause failures if exists
RUN find . -type d -name obj | xargs -r rm -r
# Build
-RUN bash -c "source deployment/common.build.sh && \
- build_jellyfin Jellyfin.Server Release linux-arm /jellyfin"
+RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" --self-contained --runtime linux-arm "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none"
FROM multiarch/qemu-user-static:x86_64-arm as qemu
-FROM mcr.microsoft.com/dotnet/core/runtime:${DOTNET_VERSION}-stretch-slim-arm32v7
+FROM debian:stretch-slim-arm32v7
COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin
RUN apt-get update \
&& apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \
@@ -25,15 +32,13 @@ RUN apt-get update \
&& mkdir -p /cache /config /media \
&& chmod 777 /cache /config /media
COPY --from=builder /jellyfin /jellyfin
+COPY --from=web-builder /dist /jellyfin/jellyfin-web
-ARG JELLYFIN_WEB_VERSION=v10.3.7
-RUN curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \
- && rm -rf /jellyfin/jellyfin-web \
- && mv jellyfin-web-${JELLYFIN_WEB_VERSION} /jellyfin/jellyfin-web
+ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1
EXPOSE 8096
VOLUME /cache /config /media
-ENTRYPOINT dotnet /jellyfin/jellyfin.dll \
+ENTRYPOINT ./jellyfin/jellyfin \
--datadir /config \
--cachedir /cache \
--ffmpeg /usr/bin/ffmpeg
diff --git a/Dockerfile.arm64 b/Dockerfile.arm64
index f8ff0612b9..9b343659f8 100644
--- a/Dockerfile.arm64
+++ b/Dockerfile.arm64
@@ -3,21 +3,28 @@
ARG DOTNET_VERSION=3.0
+FROM node:alpine as web-builder
+ARG JELLYFIN_WEB_VERSION=master
+RUN apk add curl \
+ && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \
+ && cd jellyfin-web-* \
+ && yarn install \
+ && yarn build \
+ && mv dist /dist
+
+
FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION} as builder
WORKDIR /repo
COPY . .
ENV DOTNET_CLI_TELEMETRY_OPTOUT=1
-# TODO Remove or update the sed line when we update dotnet version.
-RUN find . -type f -exec sed -i 's/netcoreapp2.1/netcoreapp3.0/g' {} \;
# Discard objs - may cause failures if exists
RUN find . -type d -name obj | xargs -r rm -r
# Build
-RUN bash -c "source deployment/common.build.sh && \
- build_jellyfin Jellyfin.Server Release linux-arm64 /jellyfin"
+RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" --self-contained --runtime linux-arm64 "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none"
FROM multiarch/qemu-user-static:x86_64-aarch64 as qemu
-FROM mcr.microsoft.com/dotnet/core/runtime:${DOTNET_VERSION}-stretch-slim-arm64v8
+FROM debian:stretch-slim-arm64v8
COPY --from=qemu /usr/bin/qemu-aarch64-static /usr/bin
RUN apt-get update \
&& apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \
@@ -25,15 +32,13 @@ RUN apt-get update \
&& mkdir -p /cache /config /media \
&& chmod 777 /cache /config /media
COPY --from=builder /jellyfin /jellyfin
+COPY --from=web-builder /dist /jellyfin/jellyfin-web
-ARG JELLYFIN_WEB_VERSION=v10.3.7
-RUN curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \
- && rm -rf /jellyfin/jellyfin-web \
- && mv jellyfin-web-${JELLYFIN_WEB_VERSION} /jellyfin/jellyfin-web
+ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1
EXPOSE 8096
VOLUME /cache /config /media
-ENTRYPOINT dotnet /jellyfin/jellyfin.dll \
+ENTRYPOINT ./jellyfin/jellyfin \
--datadir /config \
--cachedir /cache \
--ffmpeg /usr/bin/ffmpeg
diff --git a/Doxyfile b/Doxyfile
deleted file mode 100644
index c859737cac..0000000000
--- a/Doxyfile
+++ /dev/null
@@ -1,2565 +0,0 @@
-# Doxyfile 1.8.15
-
-# This file describes the settings to be used by the documentation system
-# doxygen (www.doxygen.org) for a project.
-#
-# All text after a double hash (##) is considered a comment and is placed in
-# front of the TAG it is preceding.
-#
-# All text after a single hash (#) is considered a comment and will be ignored.
-# The format is:
-# TAG = value [value, ...]
-# For lists, items can also be appended using:
-# TAG += value [value, ...]
-# Values that contain spaces should be placed between quotes (\" \").
-
-#---------------------------------------------------------------------------
-# Project related configuration options
-#---------------------------------------------------------------------------
-
-# This tag specifies the encoding used for all characters in the configuration
-# file that follow. The default is UTF-8 which is also the encoding used for all
-# text before the first occurrence of this tag. Doxygen uses libiconv (or the
-# iconv built into libc) for the transcoding. See
-# https://www.gnu.org/software/libiconv/ for the list of possible encodings.
-# The default value is: UTF-8.
-
-DOXYFILE_ENCODING = UTF-8
-
-# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
-# double-quotes, unless you are using Doxywizard) that should identify the
-# project for which the documentation is generated. This name is used in the
-# title of most generated pages and in a few other places.
-# The default value is: My Project.
-
-PROJECT_NAME = Jellyfin
-
-# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
-# could be handy for archiving the generated documentation or if some version
-# control system is used.
-
-PROJECT_NUMBER =
-
-# Using the PROJECT_BRIEF tag one can provide an optional one line description
-# for a project that appears at the top of each page and should give viewer a
-# quick idea about the purpose of the project. Keep the description short.
-
-PROJECT_BRIEF = "The Free Software Media System"
-
-# With the PROJECT_LOGO tag one can specify a logo or an icon that is included
-# in the documentation. The maximum height of the logo should not exceed 55
-# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy
-# the logo to the output directory.
-
-PROJECT_LOGO =
-
-# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
-# into which the generated documentation will be written. If a relative path is
-# entered, it will be relative to the location where doxygen was started. If
-# left blank the current directory will be used.
-
-OUTPUT_DIRECTORY = doc
-
-# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub-
-# directories (in 2 levels) under the output directory of each output format and
-# will distribute the generated files over these directories. Enabling this
-# option can be useful when feeding doxygen a huge amount of source files, where
-# putting all generated files in the same directory would otherwise causes
-# performance problems for the file system.
-# The default value is: NO.
-
-CREATE_SUBDIRS = NO
-
-# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII
-# characters to appear in the names of generated files. If set to NO, non-ASCII
-# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode
-# U+3044.
-# The default value is: NO.
-
-ALLOW_UNICODE_NAMES = NO
-
-# The OUTPUT_LANGUAGE tag is used to specify the language in which all
-# documentation generated by doxygen is written. Doxygen will use this
-# information to generate all constant output in the proper language.
-# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,
-# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),
-# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,
-# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),
-# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,
-# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,
-# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,
-# Ukrainian and Vietnamese.
-# The default value is: English.
-
-OUTPUT_LANGUAGE = English
-
-# The OUTPUT_TEXT_DIRECTION tag is used to specify the direction in which all
-# documentation generated by doxygen is written. Doxygen will use this
-# information to generate all generated output in the proper direction.
-# Possible values are: None, LTR, RTL and Context.
-# The default value is: None.
-
-OUTPUT_TEXT_DIRECTION = None
-
-# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member
-# descriptions after the members that are listed in the file and class
-# documentation (similar to Javadoc). Set to NO to disable this.
-# The default value is: YES.
-
-BRIEF_MEMBER_DESC = YES
-
-# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief
-# description of a member or function before the detailed description
-#
-# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
-# brief descriptions will be completely suppressed.
-# The default value is: YES.
-
-REPEAT_BRIEF = YES
-
-# This tag implements a quasi-intelligent brief description abbreviator that is
-# used to form the text in various listings. Each string in this list, if found
-# as the leading text of the brief description, will be stripped from the text
-# and the result, after processing the whole list, is used as the annotated
-# text. Otherwise, the brief description is used as-is. If left blank, the
-# following values are used ($name is automatically replaced with the name of
-# the entity):The $name class, The $name widget, The $name file, is, provides,
-# specifies, contains, represents, a, an and the.
-
-ABBREVIATE_BRIEF = "The $name class" \
- "The $name widget" \
- "The $name file" \
- is \
- provides \
- specifies \
- contains \
- represents \
- a \
- an \
- the
-
-# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
-# doxygen will generate a detailed section even if there is only a brief
-# description.
-# The default value is: NO.
-
-ALWAYS_DETAILED_SEC = NO
-
-# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
-# inherited members of a class in the documentation of that class as if those
-# members were ordinary class members. Constructors, destructors and assignment
-# operators of the base classes will not be shown.
-# The default value is: NO.
-
-INLINE_INHERITED_MEMB = NO
-
-# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path
-# before files name in the file list and in the header files. If set to NO the
-# shortest path that makes the file name unique will be used
-# The default value is: YES.
-
-FULL_PATH_NAMES = YES
-
-# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
-# Stripping is only done if one of the specified strings matches the left-hand
-# part of the path. The tag can be used to show relative paths in the file list.
-# If left blank the directory from which doxygen is run is used as the path to
-# strip.
-#
-# Note that you can specify absolute paths here, but also relative paths, which
-# will be relative from the directory where doxygen is started.
-# This tag requires that the tag FULL_PATH_NAMES is set to YES.
-
-STRIP_FROM_PATH =
-
-# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
-# path mentioned in the documentation of a class, which tells the reader which
-# header file to include in order to use a class. If left blank only the name of
-# the header file containing the class definition is used. Otherwise one should
-# specify the list of include paths that are normally passed to the compiler
-# using the -I flag.
-
-STRIP_FROM_INC_PATH =
-
-# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
-# less readable) file names. This can be useful is your file systems doesn't
-# support long names like on DOS, Mac, or CD-ROM.
-# The default value is: NO.
-
-SHORT_NAMES = NO
-
-# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
-# first line (until the first dot) of a Javadoc-style comment as the brief
-# description. If set to NO, the Javadoc-style will behave just like regular Qt-
-# style comments (thus requiring an explicit @brief command for a brief
-# description.)
-# The default value is: NO.
-
-JAVADOC_AUTOBRIEF = NO
-
-# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
-# line (until the first dot) of a Qt-style comment as the brief description. If
-# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
-# requiring an explicit \brief command for a brief description.)
-# The default value is: NO.
-
-QT_AUTOBRIEF = NO
-
-# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
-# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
-# a brief description. This used to be the default behavior. The new default is
-# to treat a multi-line C++ comment block as a detailed description. Set this
-# tag to YES if you prefer the old behavior instead.
-#
-# Note that setting this tag to YES also means that rational rose comments are
-# not recognized any more.
-# The default value is: NO.
-
-MULTILINE_CPP_IS_BRIEF = NO
-
-# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
-# documentation from any documented member that it re-implements.
-# The default value is: YES.
-
-INHERIT_DOCS = YES
-
-# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new
-# page for each member. If set to NO, the documentation of a member will be part
-# of the file/class/namespace that contains it.
-# The default value is: NO.
-
-SEPARATE_MEMBER_PAGES = NO
-
-# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
-# uses this value to replace tabs by spaces in code fragments.
-# Minimum value: 1, maximum value: 16, default value: 4.
-
-TAB_SIZE = 4
-
-# This tag can be used to specify a number of aliases that act as commands in
-# the documentation. An alias has the form:
-# name=value
-# For example adding
-# "sideeffect=@par Side Effects:\n"
-# will allow you to put the command \sideeffect (or @sideeffect) in the
-# documentation, which will result in a user-defined paragraph with heading
-# "Side Effects:". You can put \n's in the value part of an alias to insert
-# newlines (in the resulting output). You can put ^^ in the value part of an
-# alias to insert a newline as if a physical newline was in the original file.
-# When you need a literal { or } or , in the value part of an alias you have to
-# escape them by means of a backslash (\), this can lead to conflicts with the
-# commands \{ and \} for these it is advised to use the version @{ and @} or use
-# a double escape (\\{ and \\})
-
-ALIASES =
-
-# This tag can be used to specify a number of word-keyword mappings (TCL only).
-# A mapping has the form "name=value". For example adding "class=itcl::class"
-# will allow you to use the command class in the itcl::class meaning.
-
-TCL_SUBST =
-
-# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
-# only. Doxygen will then generate output that is more tailored for C. For
-# instance, some of the names that are used will be different. The list of all
-# members will be omitted, etc.
-# The default value is: NO.
-
-OPTIMIZE_OUTPUT_FOR_C = NO
-
-# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
-# Python sources only. Doxygen will then generate output that is more tailored
-# for that language. For instance, namespaces will be presented as packages,
-# qualified scopes will look different, etc.
-# The default value is: NO.
-
-OPTIMIZE_OUTPUT_JAVA = YES
-
-# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
-# sources. Doxygen will then generate output that is tailored for Fortran.
-# The default value is: NO.
-
-OPTIMIZE_FOR_FORTRAN = NO
-
-# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
-# sources. Doxygen will then generate output that is tailored for VHDL.
-# The default value is: NO.
-
-OPTIMIZE_OUTPUT_VHDL = NO
-
-# Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice
-# sources only. Doxygen will then generate output that is more tailored for that
-# language. For instance, namespaces will be presented as modules, types will be
-# separated into more groups, etc.
-# The default value is: NO.
-
-OPTIMIZE_OUTPUT_SLICE = NO
-
-# Doxygen selects the parser to use depending on the extension of the files it
-# parses. With this tag you can assign which parser to use for a given
-# extension. Doxygen has a built-in mapping, but you can override or extend it
-# using this tag. The format is ext=language, where ext is a file extension, and
-# language is one of the parsers supported by doxygen: IDL, Java, Javascript,
-# Csharp (C#), C, C++, D, PHP, md (Markdown), Objective-C, Python, Slice,
-# Fortran (fixed format Fortran: FortranFixed, free formatted Fortran:
-# FortranFree, unknown formatted Fortran: Fortran. In the later case the parser
-# tries to guess whether the code is fixed or free formatted code, this is the
-# default for Fortran type files), VHDL, tcl. For instance to make doxygen treat
-# .inc files as Fortran files (default is PHP), and .f files as C (default is
-# Fortran), use: inc=Fortran f=C.
-#
-# Note: For files without extension you can use no_extension as a placeholder.
-#
-# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
-# the files are not read by doxygen.
-
-EXTENSION_MAPPING =
-
-# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
-# according to the Markdown format, which allows for more readable
-# documentation. See https://daringfireball.net/projects/markdown/ for details.
-# The output of markdown processing is further processed by doxygen, so you can
-# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
-# case of backward compatibilities issues.
-# The default value is: YES.
-
-MARKDOWN_SUPPORT = YES
-
-# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up
-# to that level are automatically included in the table of contents, even if
-# they do not have an id attribute.
-# Note: This feature currently applies only to Markdown headings.
-# Minimum value: 0, maximum value: 99, default value: 0.
-# This tag requires that the tag MARKDOWN_SUPPORT is set to YES.
-
-TOC_INCLUDE_HEADINGS = 0
-
-# When enabled doxygen tries to link words that correspond to documented
-# classes, or namespaces to their corresponding documentation. Such a link can
-# be prevented in individual cases by putting a % sign in front of the word or
-# globally by setting AUTOLINK_SUPPORT to NO.
-# The default value is: YES.
-
-AUTOLINK_SUPPORT = YES
-
-# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
-# to include (a tag file for) the STL sources as input, then you should set this
-# tag to YES in order to let doxygen match functions declarations and
-# definitions whose arguments contain STL classes (e.g. func(std::string);
-# versus func(std::string) {}). This also make the inheritance and collaboration
-# diagrams that involve STL classes more complete and accurate.
-# The default value is: NO.
-
-BUILTIN_STL_SUPPORT = NO
-
-# If you use Microsoft's C++/CLI language, you should set this option to YES to
-# enable parsing support.
-# The default value is: NO.
-
-CPP_CLI_SUPPORT = NO
-
-# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
-# https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen
-# will parse them like normal C++ but will assume all classes use public instead
-# of private inheritance when no explicit protection keyword is present.
-# The default value is: NO.
-
-SIP_SUPPORT = NO
-
-# For Microsoft's IDL there are propget and propput attributes to indicate
-# getter and setter methods for a property. Setting this option to YES will make
-# doxygen to replace the get and set methods by a property in the documentation.
-# This will only work if the methods are indeed getting or setting a simple
-# type. If this is not the case, or you want to show the methods anyway, you
-# should set this option to NO.
-# The default value is: YES.
-
-IDL_PROPERTY_SUPPORT = YES
-
-# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
-# tag is set to YES then doxygen will reuse the documentation of the first
-# member in the group (if any) for the other members of the group. By default
-# all members of a group must be documented explicitly.
-# The default value is: NO.
-
-DISTRIBUTE_GROUP_DOC = NO
-
-# If one adds a struct or class to a group and this option is enabled, then also
-# any nested class or struct is added to the same group. By default this option
-# is disabled and one has to add nested compounds explicitly via \ingroup.
-# The default value is: NO.
-
-GROUP_NESTED_COMPOUNDS = NO
-
-# Set the SUBGROUPING tag to YES to allow class member groups of the same type
-# (for instance a group of public functions) to be put as a subgroup of that
-# type (e.g. under the Public Functions section). Set it to NO to prevent
-# subgrouping. Alternatively, this can be done per class using the
-# \nosubgrouping command.
-# The default value is: YES.
-
-SUBGROUPING = YES
-
-# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
-# are shown inside the group in which they are included (e.g. using \ingroup)
-# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
-# and RTF).
-#
-# Note that this feature does not work in combination with
-# SEPARATE_MEMBER_PAGES.
-# The default value is: NO.
-
-INLINE_GROUPED_CLASSES = NO
-
-# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
-# with only public data fields or simple typedef fields will be shown inline in
-# the documentation of the scope in which they are defined (i.e. file,
-# namespace, or group documentation), provided this scope is documented. If set
-# to NO, structs, classes, and unions are shown on a separate page (for HTML and
-# Man pages) or section (for LaTeX and RTF).
-# The default value is: NO.
-
-INLINE_SIMPLE_STRUCTS = NO
-
-# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
-# enum is documented as struct, union, or enum with the name of the typedef. So
-# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
-# with name TypeT. When disabled the typedef will appear as a member of a file,
-# namespace, or class. And the struct will be named TypeS. This can typically be
-# useful for C code in case the coding convention dictates that all compound
-# types are typedef'ed and only the typedef is referenced, never the tag name.
-# The default value is: NO.
-
-TYPEDEF_HIDES_STRUCT = NO
-
-# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
-# cache is used to resolve symbols given their name and scope. Since this can be
-# an expensive process and often the same symbol appears multiple times in the
-# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
-# doxygen will become slower. If the cache is too large, memory is wasted. The
-# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
-# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
-# symbols. At the end of a run doxygen will report the cache usage and suggest
-# the optimal cache size from a speed point of view.
-# Minimum value: 0, maximum value: 9, default value: 0.
-
-LOOKUP_CACHE_SIZE = 0
-
-#---------------------------------------------------------------------------
-# Build related configuration options
-#---------------------------------------------------------------------------
-
-# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in
-# documentation are documented, even if no documentation was available. Private
-# class members and static file members will be hidden unless the
-# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
-# Note: This will also disable the warnings about undocumented members that are
-# normally produced when WARNINGS is set to YES.
-# The default value is: NO.
-
-EXTRACT_ALL = YES
-
-# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will
-# be included in the documentation.
-# The default value is: NO.
-
-EXTRACT_PRIVATE = NO
-
-# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal
-# scope will be included in the documentation.
-# The default value is: NO.
-
-EXTRACT_PACKAGE = NO
-
-# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be
-# included in the documentation.
-# The default value is: NO.
-
-EXTRACT_STATIC = NO
-
-# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined
-# locally in source files will be included in the documentation. If set to NO,
-# only classes defined in header files are included. Does not have any effect
-# for Java sources.
-# The default value is: YES.
-
-EXTRACT_LOCAL_CLASSES = YES
-
-# This flag is only useful for Objective-C code. If set to YES, local methods,
-# which are defined in the implementation section but not in the interface are
-# included in the documentation. If set to NO, only methods in the interface are
-# included.
-# The default value is: NO.
-
-EXTRACT_LOCAL_METHODS = NO
-
-# If this flag is set to YES, the members of anonymous namespaces will be
-# extracted and appear in the documentation as a namespace called
-# 'anonymous_namespace{file}', where file will be replaced with the base name of
-# the file that contains the anonymous namespace. By default anonymous namespace
-# are hidden.
-# The default value is: NO.
-
-EXTRACT_ANON_NSPACES = NO
-
-# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
-# undocumented members inside documented classes or files. If set to NO these
-# members will be included in the various overviews, but no documentation
-# section is generated. This option has no effect if EXTRACT_ALL is enabled.
-# The default value is: NO.
-
-HIDE_UNDOC_MEMBERS = NO
-
-# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
-# undocumented classes that are normally visible in the class hierarchy. If set
-# to NO, these classes will be included in the various overviews. This option
-# has no effect if EXTRACT_ALL is enabled.
-# The default value is: NO.
-
-HIDE_UNDOC_CLASSES = NO
-
-# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
-# (class|struct|union) declarations. If set to NO, these declarations will be
-# included in the documentation.
-# The default value is: NO.
-
-HIDE_FRIEND_COMPOUNDS = NO
-
-# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
-# documentation blocks found inside the body of a function. If set to NO, these
-# blocks will be appended to the function's detailed documentation block.
-# The default value is: NO.
-
-HIDE_IN_BODY_DOCS = NO
-
-# The INTERNAL_DOCS tag determines if documentation that is typed after a
-# \internal command is included. If the tag is set to NO then the documentation
-# will be excluded. Set it to YES to include the internal documentation.
-# The default value is: NO.
-
-INTERNAL_DOCS = NO
-
-# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file
-# names in lower-case letters. If set to YES, upper-case letters are also
-# allowed. This is useful if you have classes or files whose names only differ
-# in case and if your file system supports case sensitive file names. Windows
-# and Mac users are advised to set this option to NO.
-# The default value is: system dependent.
-
-CASE_SENSE_NAMES = NO
-
-# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
-# their full class and namespace scopes in the documentation. If set to YES, the
-# scope will be hidden.
-# The default value is: NO.
-
-HIDE_SCOPE_NAMES = NO
-
-# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will
-# append additional text to a page's title, such as Class Reference. If set to
-# YES the compound reference will be hidden.
-# The default value is: NO.
-
-HIDE_COMPOUND_REFERENCE= NO
-
-# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
-# the files that are included by a file in the documentation of that file.
-# The default value is: YES.
-
-SHOW_INCLUDE_FILES = YES
-
-# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each
-# grouped member an include statement to the documentation, telling the reader
-# which file to include in order to use the member.
-# The default value is: NO.
-
-SHOW_GROUPED_MEMB_INC = NO
-
-# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
-# files with double quotes in the documentation rather than with sharp brackets.
-# The default value is: NO.
-
-FORCE_LOCAL_INCLUDES = NO
-
-# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
-# documentation for inline members.
-# The default value is: YES.
-
-INLINE_INFO = YES
-
-# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
-# (detailed) documentation of file and class members alphabetically by member
-# name. If set to NO, the members will appear in declaration order.
-# The default value is: YES.
-
-SORT_MEMBER_DOCS = YES
-
-# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
-# descriptions of file, namespace and class members alphabetically by member
-# name. If set to NO, the members will appear in declaration order. Note that
-# this will also influence the order of the classes in the class list.
-# The default value is: NO.
-
-SORT_BRIEF_DOCS = NO
-
-# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
-# (brief and detailed) documentation of class members so that constructors and
-# destructors are listed first. If set to NO the constructors will appear in the
-# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
-# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
-# member documentation.
-# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
-# detailed member documentation.
-# The default value is: NO.
-
-SORT_MEMBERS_CTORS_1ST = NO
-
-# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
-# of group names into alphabetical order. If set to NO the group names will
-# appear in their defined order.
-# The default value is: NO.
-
-SORT_GROUP_NAMES = NO
-
-# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
-# fully-qualified names, including namespaces. If set to NO, the class list will
-# be sorted only by class name, not including the namespace part.
-# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
-# Note: This option applies only to the class list, not to the alphabetical
-# list.
-# The default value is: NO.
-
-SORT_BY_SCOPE_NAME = NO
-
-# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
-# type resolution of all parameters of a function it will reject a match between
-# the prototype and the implementation of a member function even if there is
-# only one candidate or it is obvious which candidate to choose by doing a
-# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
-# accept a match between prototype and implementation in such cases.
-# The default value is: NO.
-
-STRICT_PROTO_MATCHING = NO
-
-# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo
-# list. This list is created by putting \todo commands in the documentation.
-# The default value is: YES.
-
-GENERATE_TODOLIST = YES
-
-# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test
-# list. This list is created by putting \test commands in the documentation.
-# The default value is: YES.
-
-GENERATE_TESTLIST = YES
-
-# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug
-# list. This list is created by putting \bug commands in the documentation.
-# The default value is: YES.
-
-GENERATE_BUGLIST = YES
-
-# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO)
-# the deprecated list. This list is created by putting \deprecated commands in
-# the documentation.
-# The default value is: YES.
-
-GENERATE_DEPRECATEDLIST= YES
-
-# The ENABLED_SECTIONS tag can be used to enable conditional documentation
-# sections, marked by \if ... \endif and \cond
-# ... \endcond blocks.
-
-ENABLED_SECTIONS =
-
-# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
-# initial value of a variable or macro / define can have for it to appear in the
-# documentation. If the initializer consists of more lines than specified here
-# it will be hidden. Use a value of 0 to hide initializers completely. The
-# appearance of the value of individual variables and macros / defines can be
-# controlled using \showinitializer or \hideinitializer command in the
-# documentation regardless of this setting.
-# Minimum value: 0, maximum value: 10000, default value: 30.
-
-MAX_INITIALIZER_LINES = 30
-
-# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
-# the bottom of the documentation of classes and structs. If set to YES, the
-# list will mention the files that were used to generate the documentation.
-# The default value is: YES.
-
-SHOW_USED_FILES = YES
-
-# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
-# will remove the Files entry from the Quick Index and from the Folder Tree View
-# (if specified).
-# The default value is: YES.
-
-SHOW_FILES = YES
-
-# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
-# page. This will remove the Namespaces entry from the Quick Index and from the
-# Folder Tree View (if specified).
-# The default value is: YES.
-
-SHOW_NAMESPACES = YES
-
-# The FILE_VERSION_FILTER tag can be used to specify a program or script that
-# doxygen should invoke to get the current version for each file (typically from
-# the version control system). Doxygen will invoke the program by executing (via
-# popen()) the command command input-file, where command is the value of the
-# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
-# by doxygen. Whatever the program writes to standard output is used as the file
-# version. For an example see the documentation.
-
-FILE_VERSION_FILTER =
-
-# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
-# by doxygen. The layout file controls the global structure of the generated
-# output files in an output format independent way. To create the layout file
-# that represents doxygen's defaults, run doxygen with the -l option. You can
-# optionally specify a file name after the option, if omitted DoxygenLayout.xml
-# will be used as the name of the layout file.
-#
-# Note that if you run doxygen from a directory containing a file called
-# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
-# tag is left empty.
-
-LAYOUT_FILE =
-
-# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
-# the reference definitions. This must be a list of .bib files. The .bib
-# extension is automatically appended if omitted. This requires the bibtex tool
-# to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info.
-# For LaTeX the style of the bibliography can be controlled using
-# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
-# search path. See also \cite for info how to create references.
-
-CITE_BIB_FILES =
-
-#---------------------------------------------------------------------------
-# Configuration options related to warning and progress messages
-#---------------------------------------------------------------------------
-
-# The QUIET tag can be used to turn on/off the messages that are generated to
-# standard output by doxygen. If QUIET is set to YES this implies that the
-# messages are off.
-# The default value is: NO.
-
-QUIET = NO
-
-# The WARNINGS tag can be used to turn on/off the warning messages that are
-# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES
-# this implies that the warnings are on.
-#
-# Tip: Turn warnings on while writing the documentation.
-# The default value is: YES.
-
-WARNINGS = YES
-
-# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate
-# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
-# will automatically be disabled.
-# The default value is: YES.
-
-WARN_IF_UNDOCUMENTED = YES
-
-# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
-# potential errors in the documentation, such as not documenting some parameters
-# in a documented function, or documenting parameters that don't exist or using
-# markup commands wrongly.
-# The default value is: YES.
-
-WARN_IF_DOC_ERROR = YES
-
-# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
-# are documented, but have no documentation for their parameters or return
-# value. If set to NO, doxygen will only warn about wrong or incomplete
-# parameter documentation, but not about the absence of documentation. If
-# EXTRACT_ALL is set to YES then this flag will automatically be disabled.
-# The default value is: NO.
-
-WARN_NO_PARAMDOC = NO
-
-# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when
-# a warning is encountered.
-# The default value is: NO.
-
-WARN_AS_ERROR = NO
-
-# The WARN_FORMAT tag determines the format of the warning messages that doxygen
-# can produce. The string should contain the $file, $line, and $text tags, which
-# will be replaced by the file and line number from which the warning originated
-# and the warning text. Optionally the format may contain $version, which will
-# be replaced by the version of the file (if it could be obtained via
-# FILE_VERSION_FILTER)
-# The default value is: $file:$line: $text.
-
-WARN_FORMAT = "$file:$line: $text"
-
-# The WARN_LOGFILE tag can be used to specify a file to which warning and error
-# messages should be written. If left blank the output is written to standard
-# error (stderr).
-
-WARN_LOGFILE =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the input files
-#---------------------------------------------------------------------------
-
-# The INPUT tag is used to specify the files and/or directories that contain
-# documented source files. You may enter file names like myfile.cpp or
-# directories like /usr/src/myproject. Separate the files or directories with
-# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING
-# Note: If this tag is empty the current directory is searched.
-
-INPUT =
-
-# This tag can be used to specify the character encoding of the source files
-# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
-# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
-# documentation (see: https://www.gnu.org/software/libiconv/) for the list of
-# possible encodings.
-# The default value is: UTF-8.
-
-INPUT_ENCODING = UTF-8
-
-# If the value of the INPUT tag contains directories, you can use the
-# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
-# *.h) to filter out the source-files in the directories.
-#
-# Note that for custom extensions or not directly supported extensions you also
-# need to set EXTENSION_MAPPING for the extension otherwise the files are not
-# read by doxygen.
-#
-# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp,
-# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h,
-# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc,
-# *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f95, *.f03, *.f08,
-# *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf, *.qsf and *.ice.
-
-FILE_PATTERNS = *.c \
- *.cc \
- *.cxx \
- *.cpp \
- *.c++ \
- *.java \
- *.ii \
- *.ixx \
- *.ipp \
- *.i++ \
- *.inl \
- *.idl \
- *.ddl \
- *.odl \
- *.h \
- *.hh \
- *.hxx \
- *.hpp \
- *.h++ \
- *.cs \
- *.d \
- *.php \
- *.php4 \
- *.php5 \
- *.phtml \
- *.inc \
- *.m \
- *.markdown \
- *.md \
- *.mm \
- *.dox \
- *.py \
- *.pyw \
- *.f90 \
- *.f95 \
- *.f03 \
- *.f08 \
- *.f \
- *.for \
- *.tcl \
- *.vhd \
- *.vhdl \
- *.ucf \
- *.qsf \
- *.ice
-
-# The RECURSIVE tag can be used to specify whether or not subdirectories should
-# be searched for input files as well.
-# The default value is: NO.
-
-RECURSIVE = YES
-
-# The EXCLUDE tag can be used to specify files and/or directories that should be
-# excluded from the INPUT source files. This way you can easily exclude a
-# subdirectory from a directory tree whose root is specified with the INPUT tag.
-#
-# Note that relative paths are relative to the directory from which doxygen is
-# run.
-
-EXCLUDE =
-
-# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
-# directories that are symbolic links (a Unix file system feature) are excluded
-# from the input.
-# The default value is: NO.
-
-EXCLUDE_SYMLINKS = NO
-
-# If the value of the INPUT tag contains directories, you can use the
-# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
-# certain files from those directories.
-#
-# Note that the wildcards are matched against the file with absolute path, so to
-# exclude all test directories for example use the pattern */test/*
-
-EXCLUDE_PATTERNS =
-
-# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
-# (namespaces, classes, functions, etc.) that should be excluded from the
-# output. The symbol name can be a fully qualified name, a word, or if the
-# wildcard * is used, a substring. Examples: ANamespace, AClass,
-# AClass::ANamespace, ANamespace::*Test
-#
-# Note that the wildcards are matched against the file with absolute path, so to
-# exclude all test directories use the pattern */test/*
-
-EXCLUDE_SYMBOLS =
-
-# The EXAMPLE_PATH tag can be used to specify one or more files or directories
-# that contain example code fragments that are included (see the \include
-# command).
-
-EXAMPLE_PATH =
-
-# If the value of the EXAMPLE_PATH tag contains directories, you can use the
-# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
-# *.h) to filter out the source-files in the directories. If left blank all
-# files are included.
-
-EXAMPLE_PATTERNS = *
-
-# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
-# searched for input files to be used with the \include or \dontinclude commands
-# irrespective of the value of the RECURSIVE tag.
-# The default value is: NO.
-
-EXAMPLE_RECURSIVE = NO
-
-# The IMAGE_PATH tag can be used to specify one or more files or directories
-# that contain images that are to be included in the documentation (see the
-# \image command).
-
-IMAGE_PATH =
-
-# The INPUT_FILTER tag can be used to specify a program that doxygen should
-# invoke to filter for each input file. Doxygen will invoke the filter program
-# by executing (via popen()) the command:
-#
-#
-#
-# where is the value of the INPUT_FILTER tag, and is the
-# name of an input file. Doxygen will then use the output that the filter
-# program writes to standard output. If FILTER_PATTERNS is specified, this tag
-# will be ignored.
-#
-# Note that the filter must not add or remove lines; it is applied before the
-# code is scanned, but not when the output code is generated. If lines are added
-# or removed, the anchors will not be placed correctly.
-#
-# Note that for custom extensions or not directly supported extensions you also
-# need to set EXTENSION_MAPPING for the extension otherwise the files are not
-# properly processed by doxygen.
-
-INPUT_FILTER =
-
-# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
-# basis. Doxygen will compare the file name with each pattern and apply the
-# filter if there is a match. The filters are a list of the form: pattern=filter
-# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
-# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
-# patterns match the file name, INPUT_FILTER is applied.
-#
-# Note that for custom extensions or not directly supported extensions you also
-# need to set EXTENSION_MAPPING for the extension otherwise the files are not
-# properly processed by doxygen.
-
-FILTER_PATTERNS =
-
-# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
-# INPUT_FILTER) will also be used to filter the input files that are used for
-# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
-# The default value is: NO.
-
-FILTER_SOURCE_FILES = NO
-
-# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
-# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
-# it is also possible to disable source filtering for a specific pattern using
-# *.ext= (so without naming a filter).
-# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
-
-FILTER_SOURCE_PATTERNS =
-
-# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
-# is part of the input, its contents will be placed on the main page
-# (index.html). This can be useful if you have a project on for instance GitHub
-# and want to reuse the introduction page also for the doxygen output.
-
-USE_MDFILE_AS_MAINPAGE = ./README.md
-
-#---------------------------------------------------------------------------
-# Configuration options related to source browsing
-#---------------------------------------------------------------------------
-
-# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
-# generated. Documented entities will be cross-referenced with these sources.
-#
-# Note: To get rid of all source code in the generated output, make sure that
-# also VERBATIM_HEADERS is set to NO.
-# The default value is: NO.
-
-SOURCE_BROWSER = YES
-
-# Setting the INLINE_SOURCES tag to YES will include the body of functions,
-# classes and enums directly into the documentation.
-# The default value is: NO.
-
-INLINE_SOURCES = NO
-
-# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
-# special comment blocks from generated source code fragments. Normal C, C++ and
-# Fortran comments will always remain visible.
-# The default value is: YES.
-
-STRIP_CODE_COMMENTS = YES
-
-# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
-# entity all documented functions referencing it will be listed.
-# The default value is: NO.
-
-REFERENCED_BY_RELATION = NO
-
-# If the REFERENCES_RELATION tag is set to YES then for each documented function
-# all documented entities called/used by that function will be listed.
-# The default value is: NO.
-
-REFERENCES_RELATION = NO
-
-# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
-# to YES then the hyperlinks from functions in REFERENCES_RELATION and
-# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
-# link to the documentation.
-# The default value is: YES.
-
-REFERENCES_LINK_SOURCE = YES
-
-# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
-# source code will show a tooltip with additional information such as prototype,
-# brief description and links to the definition and documentation. Since this
-# will make the HTML file larger and loading of large files a bit slower, you
-# can opt to disable this feature.
-# The default value is: YES.
-# This tag requires that the tag SOURCE_BROWSER is set to YES.
-
-SOURCE_TOOLTIPS = YES
-
-# If the USE_HTAGS tag is set to YES then the references to source code will
-# point to the HTML generated by the htags(1) tool instead of doxygen built-in
-# source browser. The htags tool is part of GNU's global source tagging system
-# (see https://www.gnu.org/software/global/global.html). You will need version
-# 4.8.6 or higher.
-#
-# To use it do the following:
-# - Install the latest version of global
-# - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file
-# - Make sure the INPUT points to the root of the source tree
-# - Run doxygen as normal
-#
-# Doxygen will invoke htags (and that will in turn invoke gtags), so these
-# tools must be available from the command line (i.e. in the search path).
-#
-# The result: instead of the source browser generated by doxygen, the links to
-# source code will now point to the output of htags.
-# The default value is: NO.
-# This tag requires that the tag SOURCE_BROWSER is set to YES.
-
-USE_HTAGS = NO
-
-# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
-# verbatim copy of the header file for each class for which an include is
-# specified. Set to NO to disable this.
-# See also: Section \class.
-# The default value is: YES.
-
-VERBATIM_HEADERS = YES
-
-# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the
-# clang parser (see: http://clang.llvm.org/) for more accurate parsing at the
-# cost of reduced performance. This can be particularly helpful with template
-# rich C++ code for which doxygen's built-in parser lacks the necessary type
-# information.
-# Note: The availability of this option depends on whether or not doxygen was
-# generated with the -Duse_libclang=ON option for CMake.
-# The default value is: NO.
-
-CLANG_ASSISTED_PARSING = NO
-
-# If clang assisted parsing is enabled you can provide the compiler with command
-# line options that you would normally use when invoking the compiler. Note that
-# the include paths will already be set by doxygen for the files and directories
-# specified with INPUT and INCLUDE_PATH.
-# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.
-
-CLANG_OPTIONS =
-
-# If clang assisted parsing is enabled you can provide the clang parser with the
-# path to the compilation database (see:
-# http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html) used when the files
-# were built. This is equivalent to specifying the "-p" option to a clang tool,
-# such as clang-check. These options will then be passed to the parser.
-# Note: The availability of this option depends on whether or not doxygen was
-# generated with the -Duse_libclang=ON option for CMake.
-
-CLANG_DATABASE_PATH =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the alphabetical class index
-#---------------------------------------------------------------------------
-
-# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
-# compounds will be generated. Enable this if the project contains a lot of
-# classes, structs, unions or interfaces.
-# The default value is: YES.
-
-ALPHABETICAL_INDEX = YES
-
-# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
-# which the alphabetical index list will be split.
-# Minimum value: 1, maximum value: 20, default value: 5.
-# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
-
-COLS_IN_ALPHA_INDEX = 5
-
-# In case all classes in a project start with a common prefix, all classes will
-# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag
-# can be used to specify a prefix (or a list of prefixes) that should be ignored
-# while generating the index headers.
-# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
-
-IGNORE_PREFIX =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the HTML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output
-# The default value is: YES.
-
-GENERATE_HTML = YES
-
-# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it.
-# The default directory is: html.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_OUTPUT = html
-
-# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
-# generated HTML page (for example: .htm, .php, .asp).
-# The default value is: .html.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_FILE_EXTENSION = .html
-
-# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
-# each generated HTML page. If the tag is left blank doxygen will generate a
-# standard header.
-#
-# To get valid HTML the header file that includes any scripts and style sheets
-# that doxygen needs, which is dependent on the configuration options used (e.g.
-# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
-# default header using
-# doxygen -w html new_header.html new_footer.html new_stylesheet.css
-# YourConfigFile
-# and then modify the file new_header.html. See also section "Doxygen usage"
-# for information on how to generate the default header that doxygen normally
-# uses.
-# Note: The header is subject to change so you typically have to regenerate the
-# default header when upgrading to a newer version of doxygen. For a description
-# of the possible markers and block names see the documentation.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_HEADER =
-
-# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
-# generated HTML page. If the tag is left blank doxygen will generate a standard
-# footer. See HTML_HEADER for more information on how to generate a default
-# footer and what special commands can be used inside the footer. See also
-# section "Doxygen usage" for information on how to generate the default footer
-# that doxygen normally uses.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_FOOTER =
-
-# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
-# sheet that is used by each HTML page. It can be used to fine-tune the look of
-# the HTML output. If left blank doxygen will generate a default style sheet.
-# See also section "Doxygen usage" for information on how to generate the style
-# sheet that doxygen normally uses.
-# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
-# it is more robust and this tag (HTML_STYLESHEET) will in the future become
-# obsolete.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_STYLESHEET =
-
-# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined
-# cascading style sheets that are included after the standard style sheets
-# created by doxygen. Using this option one can overrule certain style aspects.
-# This is preferred over using HTML_STYLESHEET since it does not replace the
-# standard style sheet and is therefore more robust against future updates.
-# Doxygen will copy the style sheet files to the output directory.
-# Note: The order of the extra style sheet files is of importance (e.g. the last
-# style sheet in the list overrules the setting of the previous ones in the
-# list). For an example see the documentation.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_EXTRA_STYLESHEET =
-
-# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
-# other source files which should be copied to the HTML output directory. Note
-# that these files will be copied to the base HTML output directory. Use the
-# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
-# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
-# files will be copied as-is; there are no commands or markers available.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_EXTRA_FILES =
-
-# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
-# will adjust the colors in the style sheet and background images according to
-# this color. Hue is specified as an angle on a colorwheel, see
-# https://en.wikipedia.org/wiki/Hue for more information. For instance the value
-# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
-# purple, and 360 is red again.
-# Minimum value: 0, maximum value: 359, default value: 220.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_COLORSTYLE_HUE = 195
-
-# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
-# in the HTML output. For a value of 0 the output will use grayscales only. A
-# value of 255 will produce the most vivid colors.
-# Minimum value: 0, maximum value: 255, default value: 100.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_COLORSTYLE_SAT = 100
-
-# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
-# luminance component of the colors in the HTML output. Values below 100
-# gradually make the output lighter, whereas values above 100 make the output
-# darker. The value divided by 100 is the actual gamma applied, so 80 represents
-# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
-# change the gamma.
-# Minimum value: 40, maximum value: 240, default value: 80.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_COLORSTYLE_GAMMA = 86
-
-# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
-# page will contain the date and time when the page was generated. Setting this
-# to YES can help to show when doxygen was last run and thus if the
-# documentation is up to date.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_TIMESTAMP = NO
-
-# If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML
-# documentation will contain a main index with vertical navigation menus that
-# are dynamically created via Javascript. If disabled, the navigation index will
-# consists of multiple levels of tabs that are statically embedded in every HTML
-# page. Disable this option to support browsers that do not have Javascript,
-# like the Qt help browser.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_DYNAMIC_MENUS = YES
-
-# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
-# documentation will contain sections that can be hidden and shown after the
-# page has loaded.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_DYNAMIC_SECTIONS = NO
-
-# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
-# shown in the various tree structured indices initially; the user can expand
-# and collapse entries dynamically later on. Doxygen will expand the tree to
-# such a level that at most the specified number of entries are visible (unless
-# a fully collapsed tree already exceeds this amount). So setting the number of
-# entries 1 will produce a full collapsed tree by default. 0 is a special value
-# representing an infinite number of entries and will result in a full expanded
-# tree by default.
-# Minimum value: 0, maximum value: 9999, default value: 100.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_INDEX_NUM_ENTRIES = 100
-
-# If the GENERATE_DOCSET tag is set to YES, additional index files will be
-# generated that can be used as input for Apple's Xcode 3 integrated development
-# environment (see: https://developer.apple.com/xcode/), introduced with OSX
-# 10.5 (Leopard). To create a documentation set, doxygen will generate a
-# Makefile in the HTML output directory. Running make will produce the docset in
-# that directory and running make install will install the docset in
-# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
-# startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy
-# genXcode/_index.html for more information.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_DOCSET = NO
-
-# This tag determines the name of the docset feed. A documentation feed provides
-# an umbrella under which multiple documentation sets from a single provider
-# (such as a company or product suite) can be grouped.
-# The default value is: Doxygen generated docs.
-# This tag requires that the tag GENERATE_DOCSET is set to YES.
-
-DOCSET_FEEDNAME = "Doxygen generated docs"
-
-# This tag specifies a string that should uniquely identify the documentation
-# set bundle. This should be a reverse domain-name style string, e.g.
-# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
-# The default value is: org.doxygen.Project.
-# This tag requires that the tag GENERATE_DOCSET is set to YES.
-
-DOCSET_BUNDLE_ID = org.doxygen.Project
-
-# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
-# the documentation publisher. This should be a reverse domain-name style
-# string, e.g. com.mycompany.MyDocSet.documentation.
-# The default value is: org.doxygen.Publisher.
-# This tag requires that the tag GENERATE_DOCSET is set to YES.
-
-DOCSET_PUBLISHER_ID = org.doxygen.Publisher
-
-# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
-# The default value is: Publisher.
-# This tag requires that the tag GENERATE_DOCSET is set to YES.
-
-DOCSET_PUBLISHER_NAME = Publisher
-
-# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
-# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
-# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
-# (see: https://www.microsoft.com/en-us/download/details.aspx?id=21138) on
-# Windows.
-#
-# The HTML Help Workshop contains a compiler that can convert all HTML output
-# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
-# files are now used as the Windows 98 help format, and will replace the old
-# Windows help format (.hlp) on all Windows platforms in the future. Compressed
-# HTML files also contain an index, a table of contents, and you can search for
-# words in the documentation. The HTML workshop also contains a viewer for
-# compressed HTML files.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_HTMLHELP = NO
-
-# The CHM_FILE tag can be used to specify the file name of the resulting .chm
-# file. You can add a path in front of the file if the result should not be
-# written to the html output directory.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-CHM_FILE =
-
-# The HHC_LOCATION tag can be used to specify the location (absolute path
-# including file name) of the HTML help compiler (hhc.exe). If non-empty,
-# doxygen will try to run the HTML help compiler on the generated index.hhp.
-# The file has to be specified with full path.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-HHC_LOCATION =
-
-# The GENERATE_CHI flag controls if a separate .chi index file is generated
-# (YES) or that it should be included in the master .chm file (NO).
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-GENERATE_CHI = NO
-
-# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc)
-# and project file content.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-CHM_INDEX_ENCODING =
-
-# The BINARY_TOC flag controls whether a binary table of contents is generated
-# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it
-# enables the Previous and Next buttons.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-BINARY_TOC = NO
-
-# The TOC_EXPAND flag can be set to YES to add extra items for group members to
-# the table of contents of the HTML help documentation and to the tree view.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-TOC_EXPAND = NO
-
-# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
-# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
-# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
-# (.qch) of the generated HTML documentation.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_QHP = NO
-
-# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
-# the file name of the resulting .qch file. The path specified is relative to
-# the HTML output folder.
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QCH_FILE =
-
-# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
-# Project output. For more information please see Qt Help Project / Namespace
-# (see: http://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace).
-# The default value is: org.doxygen.Project.
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_NAMESPACE = org.doxygen.Project
-
-# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
-# Help Project output. For more information please see Qt Help Project / Virtual
-# Folders (see: http://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual-
-# folders).
-# The default value is: doc.
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_VIRTUAL_FOLDER = doc
-
-# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
-# filter to add. For more information please see Qt Help Project / Custom
-# Filters (see: http://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-
-# filters).
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_CUST_FILTER_NAME =
-
-# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
-# custom filter to add. For more information please see Qt Help Project / Custom
-# Filters (see: http://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-
-# filters).
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_CUST_FILTER_ATTRS =
-
-# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
-# project's filter section matches. Qt Help Project / Filter Attributes (see:
-# http://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes).
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_SECT_FILTER_ATTRS =
-
-# The QHG_LOCATION tag can be used to specify the location of Qt's
-# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the
-# generated .qhp file.
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHG_LOCATION =
-
-# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
-# generated, together with the HTML files, they form an Eclipse help plugin. To
-# install this plugin and make it available under the help contents menu in
-# Eclipse, the contents of the directory containing the HTML and XML files needs
-# to be copied into the plugins directory of eclipse. The name of the directory
-# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
-# After copying Eclipse needs to be restarted before the help appears.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_ECLIPSEHELP = NO
-
-# A unique identifier for the Eclipse help plugin. When installing the plugin
-# the directory name containing the HTML and XML files should also have this
-# name. Each documentation set should have its own identifier.
-# The default value is: org.doxygen.Project.
-# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
-
-ECLIPSE_DOC_ID = org.doxygen.Project
-
-# If you want full control over the layout of the generated HTML pages it might
-# be necessary to disable the index and replace it with your own. The
-# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
-# of each HTML page. A value of NO enables the index and the value YES disables
-# it. Since the tabs in the index contain the same information as the navigation
-# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-DISABLE_INDEX = NO
-
-# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
-# structure should be generated to display hierarchical information. If the tag
-# value is set to YES, a side panel will be generated containing a tree-like
-# index structure (just like the one that is generated for HTML Help). For this
-# to work a browser that supports JavaScript, DHTML, CSS and frames is required
-# (i.e. any modern browser). Windows users are probably better off using the
-# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can
-# further fine-tune the look of the index. As an example, the default style
-# sheet generated by doxygen has an example that shows how to put an image at
-# the root of the tree instead of the PROJECT_NAME. Since the tree basically has
-# the same information as the tab index, you could consider setting
-# DISABLE_INDEX to YES when enabling this option.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_TREEVIEW = YES
-
-# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
-# doxygen will group on one line in the generated HTML documentation.
-#
-# Note that a value of 0 will completely suppress the enum values from appearing
-# in the overview section.
-# Minimum value: 0, maximum value: 20, default value: 4.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-ENUM_VALUES_PER_LINE = 4
-
-# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
-# to set the initial width (in pixels) of the frame in which the tree is shown.
-# Minimum value: 0, maximum value: 1500, default value: 250.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-TREEVIEW_WIDTH = 250
-
-# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to
-# external symbols imported via tag files in a separate window.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-EXT_LINKS_IN_WINDOW = NO
-
-# Use this tag to change the font size of LaTeX formulas included as images in
-# the HTML documentation. When you change the font size after a successful
-# doxygen run you need to manually remove any form_*.png images from the HTML
-# output directory to force them to be regenerated.
-# Minimum value: 8, maximum value: 50, default value: 10.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-FORMULA_FONTSIZE = 10
-
-# Use the FORMULA_TRANSPARENT tag to determine whether or not the images
-# generated for formulas are transparent PNGs. Transparent PNGs are not
-# supported properly for IE 6.0, but are supported on all modern browsers.
-#
-# Note that when changing this option you need to delete any form_*.png files in
-# the HTML output directory before the changes have effect.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-FORMULA_TRANSPARENT = YES
-
-# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
-# https://www.mathjax.org) which uses client side Javascript for the rendering
-# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX
-# installed or if you want to formulas look prettier in the HTML output. When
-# enabled you may also need to install MathJax separately and configure the path
-# to it using the MATHJAX_RELPATH option.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-USE_MATHJAX = NO
-
-# When MathJax is enabled you can set the default output format to be used for
-# the MathJax output. See the MathJax site (see:
-# http://docs.mathjax.org/en/latest/output.html) for more details.
-# Possible values are: HTML-CSS (which is slower, but has the best
-# compatibility), NativeMML (i.e. MathML) and SVG.
-# The default value is: HTML-CSS.
-# This tag requires that the tag USE_MATHJAX is set to YES.
-
-MATHJAX_FORMAT = HTML-CSS
-
-# When MathJax is enabled you need to specify the location relative to the HTML
-# output directory using the MATHJAX_RELPATH option. The destination directory
-# should contain the MathJax.js script. For instance, if the mathjax directory
-# is located at the same level as the HTML output directory, then
-# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
-# Content Delivery Network so you can quickly see the result without installing
-# MathJax. However, it is strongly recommended to install a local copy of
-# MathJax from https://www.mathjax.org before deployment.
-# The default value is: https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/.
-# This tag requires that the tag USE_MATHJAX is set to YES.
-
-MATHJAX_RELPATH = https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/
-
-# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
-# extension names that should be enabled during MathJax rendering. For example
-# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
-# This tag requires that the tag USE_MATHJAX is set to YES.
-
-MATHJAX_EXTENSIONS =
-
-# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
-# of code that will be used on startup of the MathJax code. See the MathJax site
-# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an
-# example see the documentation.
-# This tag requires that the tag USE_MATHJAX is set to YES.
-
-MATHJAX_CODEFILE =
-
-# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
-# the HTML output. The underlying search engine uses javascript and DHTML and
-# should work on any modern browser. Note that when using HTML help
-# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
-# there is already a search function so this one should typically be disabled.
-# For large projects the javascript based search engine can be slow, then
-# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
-# search using the keyboard; to jump to the search box use + S
-# (what the is depends on the OS and browser, but it is typically
-# , /, or both). Inside the search box use the to jump into the search results window, the results can be navigated
-# using the . Press to select an item or to cancel
-# the search. The filter options can be selected when the cursor is inside the
-# search box by pressing +. Also here use the
-# to select a filter and or to activate or cancel the filter
-# option.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-SEARCHENGINE = YES
-
-# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
-# implemented using a web server instead of a web client using Javascript. There
-# are two flavors of web server based searching depending on the EXTERNAL_SEARCH
-# setting. When disabled, doxygen will generate a PHP script for searching and
-# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing
-# and searching needs to be provided by external tools. See the section
-# "External Indexing and Searching" for details.
-# The default value is: NO.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-SERVER_BASED_SEARCH = NO
-
-# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
-# script for searching. Instead the search results are written to an XML file
-# which needs to be processed by an external indexer. Doxygen will invoke an
-# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
-# search results.
-#
-# Doxygen ships with an example indexer (doxyindexer) and search engine
-# (doxysearch.cgi) which are based on the open source search engine library
-# Xapian (see: https://xapian.org/).
-#
-# See the section "External Indexing and Searching" for details.
-# The default value is: NO.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-EXTERNAL_SEARCH = NO
-
-# The SEARCHENGINE_URL should point to a search engine hosted by a web server
-# which will return the search results when EXTERNAL_SEARCH is enabled.
-#
-# Doxygen ships with an example indexer (doxyindexer) and search engine
-# (doxysearch.cgi) which are based on the open source search engine library
-# Xapian (see: https://xapian.org/). See the section "External Indexing and
-# Searching" for details.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-SEARCHENGINE_URL =
-
-# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
-# search data is written to a file for indexing by an external tool. With the
-# SEARCHDATA_FILE tag the name of this file can be specified.
-# The default file is: searchdata.xml.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-SEARCHDATA_FILE = searchdata.xml
-
-# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
-# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
-# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
-# projects and redirect the results back to the right project.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-EXTERNAL_SEARCH_ID =
-
-# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
-# projects other than the one defined by this configuration file, but that are
-# all added to the same external search index. Each project needs to have a
-# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
-# to a relative location where the documentation can be found. The format is:
-# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-EXTRA_SEARCH_MAPPINGS =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the LaTeX output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output.
-# The default value is: YES.
-
-GENERATE_LATEX = NO
-
-# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it.
-# The default directory is: latex.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_OUTPUT = latex
-
-# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
-# invoked.
-#
-# Note that when not enabling USE_PDFLATEX the default is latex when enabling
-# USE_PDFLATEX the default is pdflatex and when in the later case latex is
-# chosen this is overwritten by pdflatex. For specific output languages the
-# default can have been set differently, this depends on the implementation of
-# the output language.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_CMD_NAME =
-
-# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
-# index for LaTeX.
-# Note: This tag is used in the Makefile / make.bat.
-# See also: LATEX_MAKEINDEX_CMD for the part in the generated output file
-# (.tex).
-# The default file is: makeindex.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-MAKEINDEX_CMD_NAME = makeindex
-
-# The LATEX_MAKEINDEX_CMD tag can be used to specify the command name to
-# generate index for LaTeX.
-# Note: This tag is used in the generated output file (.tex).
-# See also: MAKEINDEX_CMD_NAME for the part in the Makefile / make.bat.
-# The default value is: \makeindex.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_MAKEINDEX_CMD = \makeindex
-
-# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX
-# documents. This may be useful for small projects and may help to save some
-# trees in general.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-COMPACT_LATEX = NO
-
-# The PAPER_TYPE tag can be used to set the paper type that is used by the
-# printer.
-# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
-# 14 inches) and executive (7.25 x 10.5 inches).
-# The default value is: a4.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-PAPER_TYPE = a4
-
-# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
-# that should be included in the LaTeX output. The package can be specified just
-# by its name or with the correct syntax as to be used with the LaTeX
-# \usepackage command. To get the times font for instance you can specify :
-# EXTRA_PACKAGES=times or EXTRA_PACKAGES={times}
-# To use the option intlimits with the amsmath package you can specify:
-# EXTRA_PACKAGES=[intlimits]{amsmath}
-# If left blank no extra packages will be included.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-EXTRA_PACKAGES =
-
-# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the
-# generated LaTeX document. The header should contain everything until the first
-# chapter. If it is left blank doxygen will generate a standard header. See
-# section "Doxygen usage" for information on how to let doxygen write the
-# default header to a separate file.
-#
-# Note: Only use a user-defined header if you know what you are doing! The
-# following commands have a special meaning inside the header: $title,
-# $datetime, $date, $doxygenversion, $projectname, $projectnumber,
-# $projectbrief, $projectlogo. Doxygen will replace $title with the empty
-# string, for the replacement values of the other commands the user is referred
-# to HTML_HEADER.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_HEADER =
-
-# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the
-# generated LaTeX document. The footer should contain everything after the last
-# chapter. If it is left blank doxygen will generate a standard footer. See
-# LATEX_HEADER for more information on how to generate a default footer and what
-# special commands can be used inside the footer.
-#
-# Note: Only use a user-defined footer if you know what you are doing!
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_FOOTER =
-
-# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined
-# LaTeX style sheets that are included after the standard style sheets created
-# by doxygen. Using this option one can overrule certain style aspects. Doxygen
-# will copy the style sheet files to the output directory.
-# Note: The order of the extra style sheet files is of importance (e.g. the last
-# style sheet in the list overrules the setting of the previous ones in the
-# list).
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_EXTRA_STYLESHEET =
-
-# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
-# other source files which should be copied to the LATEX_OUTPUT output
-# directory. Note that the files will be copied as-is; there are no commands or
-# markers available.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_EXTRA_FILES =
-
-# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
-# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will
-# contain links (just like the HTML output) instead of page references. This
-# makes the output suitable for online browsing using a PDF viewer.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-PDF_HYPERLINKS = YES
-
-# If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate
-# the PDF file directly from the LaTeX files. Set this option to YES, to get a
-# higher quality PDF documentation.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-USE_PDFLATEX = YES
-
-# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
-# command to the generated LaTeX files. This will instruct LaTeX to keep running
-# if errors occur, instead of asking the user for help. This option is also used
-# when generating formulas in HTML.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_BATCHMODE = NO
-
-# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
-# index chapters (such as File Index, Compound Index, etc.) in the output.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_HIDE_INDICES = NO
-
-# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source
-# code with syntax highlighting in the LaTeX output.
-#
-# Note that which sources are shown also depends on other settings such as
-# SOURCE_BROWSER.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_SOURCE_CODE = NO
-
-# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
-# bibliography, e.g. plainnat, or ieeetr. See
-# https://en.wikipedia.org/wiki/BibTeX and \cite for more info.
-# The default value is: plain.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_BIB_STYLE = plain
-
-# If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated
-# page will contain the date and time when the page was generated. Setting this
-# to NO can help when comparing the output of multiple runs.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_TIMESTAMP = NO
-
-# The LATEX_EMOJI_DIRECTORY tag is used to specify the (relative or absolute)
-# path from which the emoji images will be read. If a relative path is entered,
-# it will be relative to the LATEX_OUTPUT directory. If left blank the
-# LATEX_OUTPUT directory will be used.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_EMOJI_DIRECTORY =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the RTF output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The
-# RTF output is optimized for Word 97 and may not look too pretty with other RTF
-# readers/editors.
-# The default value is: NO.
-
-GENERATE_RTF = NO
-
-# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it.
-# The default directory is: rtf.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_OUTPUT = rtf
-
-# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF
-# documents. This may be useful for small projects and may help to save some
-# trees in general.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-COMPACT_RTF = NO
-
-# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will
-# contain hyperlink fields. The RTF file will contain links (just like the HTML
-# output) instead of page references. This makes the output suitable for online
-# browsing using Word or some other Word compatible readers that support those
-# fields.
-#
-# Note: WordPad (write) and others do not support links.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_HYPERLINKS = NO
-
-# Load stylesheet definitions from file. Syntax is similar to doxygen's
-# configuration file, i.e. a series of assignments. You only have to provide
-# replacements, missing definitions are set to their default value.
-#
-# See also section "Doxygen usage" for information on how to generate the
-# default style sheet that doxygen normally uses.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_STYLESHEET_FILE =
-
-# Set optional variables used in the generation of an RTF document. Syntax is
-# similar to doxygen's configuration file. A template extensions file can be
-# generated using doxygen -e rtf extensionFile.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_EXTENSIONS_FILE =
-
-# If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code
-# with syntax highlighting in the RTF output.
-#
-# Note that which sources are shown also depends on other settings such as
-# SOURCE_BROWSER.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_SOURCE_CODE = NO
-
-#---------------------------------------------------------------------------
-# Configuration options related to the man page output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for
-# classes and files.
-# The default value is: NO.
-
-GENERATE_MAN = NO
-
-# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it. A directory man3 will be created inside the directory specified by
-# MAN_OUTPUT.
-# The default directory is: man.
-# This tag requires that the tag GENERATE_MAN is set to YES.
-
-MAN_OUTPUT = man
-
-# The MAN_EXTENSION tag determines the extension that is added to the generated
-# man pages. In case the manual section does not start with a number, the number
-# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
-# optional.
-# The default value is: .3.
-# This tag requires that the tag GENERATE_MAN is set to YES.
-
-MAN_EXTENSION = .3
-
-# The MAN_SUBDIR tag determines the name of the directory created within
-# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by
-# MAN_EXTENSION with the initial . removed.
-# This tag requires that the tag GENERATE_MAN is set to YES.
-
-MAN_SUBDIR =
-
-# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it
-# will generate one additional man file for each entity documented in the real
-# man page(s). These additional files only source the real man page, but without
-# them the man command would be unable to find the correct page.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_MAN is set to YES.
-
-MAN_LINKS = NO
-
-#---------------------------------------------------------------------------
-# Configuration options related to the XML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that
-# captures the structure of the code including all documentation.
-# The default value is: NO.
-
-GENERATE_XML = NO
-
-# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it.
-# The default directory is: xml.
-# This tag requires that the tag GENERATE_XML is set to YES.
-
-XML_OUTPUT = xml
-
-# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program
-# listings (including syntax highlighting and cross-referencing information) to
-# the XML output. Note that enabling this will significantly increase the size
-# of the XML output.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_XML is set to YES.
-
-XML_PROGRAMLISTING = YES
-
-# If the XML_NS_MEMB_FILE_SCOPE tag is set to YES, doxygen will include
-# namespace members in file scope as well, matching the HTML output.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_XML is set to YES.
-
-XML_NS_MEMB_FILE_SCOPE = NO
-
-#---------------------------------------------------------------------------
-# Configuration options related to the DOCBOOK output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files
-# that can be used to generate PDF.
-# The default value is: NO.
-
-GENERATE_DOCBOOK = NO
-
-# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
-# front of it.
-# The default directory is: docbook.
-# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
-
-DOCBOOK_OUTPUT = docbook
-
-# If the DOCBOOK_PROGRAMLISTING tag is set to YES, doxygen will include the
-# program listings (including syntax highlighting and cross-referencing
-# information) to the DOCBOOK output. Note that enabling this will significantly
-# increase the size of the DOCBOOK output.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
-
-DOCBOOK_PROGRAMLISTING = NO
-
-#---------------------------------------------------------------------------
-# Configuration options for the AutoGen Definitions output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an
-# AutoGen Definitions (see http://autogen.sourceforge.net/) file that captures
-# the structure of the code including all documentation. Note that this feature
-# is still experimental and incomplete at the moment.
-# The default value is: NO.
-
-GENERATE_AUTOGEN_DEF = NO
-
-#---------------------------------------------------------------------------
-# Configuration options related to the Perl module output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module
-# file that captures the structure of the code including all documentation.
-#
-# Note that this feature is still experimental and incomplete at the moment.
-# The default value is: NO.
-
-GENERATE_PERLMOD = NO
-
-# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary
-# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI
-# output from the Perl module output.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_PERLMOD is set to YES.
-
-PERLMOD_LATEX = NO
-
-# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely
-# formatted so it can be parsed by a human reader. This is useful if you want to
-# understand what is going on. On the other hand, if this tag is set to NO, the
-# size of the Perl module output will be much smaller and Perl will parse it
-# just the same.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_PERLMOD is set to YES.
-
-PERLMOD_PRETTY = YES
-
-# The names of the make variables in the generated doxyrules.make file are
-# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful
-# so different doxyrules.make files included by the same Makefile don't
-# overwrite each other's variables.
-# This tag requires that the tag GENERATE_PERLMOD is set to YES.
-
-PERLMOD_MAKEVAR_PREFIX =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the preprocessor
-#---------------------------------------------------------------------------
-
-# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all
-# C-preprocessor directives found in the sources and include files.
-# The default value is: YES.
-
-ENABLE_PREPROCESSING = YES
-
-# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names
-# in the source code. If set to NO, only conditional compilation will be
-# performed. Macro expansion can be done in a controlled way by setting
-# EXPAND_ONLY_PREDEF to YES.
-# The default value is: NO.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-MACRO_EXPANSION = NO
-
-# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
-# the macro expansion is limited to the macros specified with the PREDEFINED and
-# EXPAND_AS_DEFINED tags.
-# The default value is: NO.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-EXPAND_ONLY_PREDEF = NO
-
-# If the SEARCH_INCLUDES tag is set to YES, the include files in the
-# INCLUDE_PATH will be searched if a #include is found.
-# The default value is: YES.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-SEARCH_INCLUDES = YES
-
-# The INCLUDE_PATH tag can be used to specify one or more directories that
-# contain include files that are not input files but should be processed by the
-# preprocessor.
-# This tag requires that the tag SEARCH_INCLUDES is set to YES.
-
-INCLUDE_PATH =
-
-# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
-# patterns (like *.h and *.hpp) to filter out the header-files in the
-# directories. If left blank, the patterns specified with FILE_PATTERNS will be
-# used.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-INCLUDE_FILE_PATTERNS =
-
-# The PREDEFINED tag can be used to specify one or more macro names that are
-# defined before the preprocessor is started (similar to the -D option of e.g.
-# gcc). The argument of the tag is a list of macros of the form: name or
-# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
-# is assumed. To prevent a macro definition from being undefined via #undef or
-# recursively expanded use the := operator instead of the = operator.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-PREDEFINED =
-
-# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
-# tag can be used to specify a list of macro names that should be expanded. The
-# macro definition that is found in the sources will be used. Use the PREDEFINED
-# tag if you want to use a different macro definition that overrules the
-# definition found in the source code.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-EXPAND_AS_DEFINED =
-
-# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
-# remove all references to function-like macros that are alone on a line, have
-# an all uppercase name, and do not end with a semicolon. Such function macros
-# are typically used for boiler-plate code, and will confuse the parser if not
-# removed.
-# The default value is: YES.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-SKIP_FUNCTION_MACROS = YES
-
-#---------------------------------------------------------------------------
-# Configuration options related to external references
-#---------------------------------------------------------------------------
-
-# The TAGFILES tag can be used to specify one or more tag files. For each tag
-# file the location of the external documentation should be added. The format of
-# a tag file without this location is as follows:
-# TAGFILES = file1 file2 ...
-# Adding location for the tag files is done as follows:
-# TAGFILES = file1=loc1 "file2 = loc2" ...
-# where loc1 and loc2 can be relative or absolute paths or URLs. See the
-# section "Linking to external documentation" for more information about the use
-# of tag files.
-# Note: Each tag file must have a unique name (where the name does NOT include
-# the path). If a tag file is not located in the directory in which doxygen is
-# run, you must also specify the path to the tagfile here.
-
-TAGFILES =
-
-# When a file name is specified after GENERATE_TAGFILE, doxygen will create a
-# tag file that is based on the input files it reads. See section "Linking to
-# external documentation" for more information about the usage of tag files.
-
-GENERATE_TAGFILE =
-
-# If the ALLEXTERNALS tag is set to YES, all external class will be listed in
-# the class index. If set to NO, only the inherited external classes will be
-# listed.
-# The default value is: NO.
-
-ALLEXTERNALS = NO
-
-# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed
-# in the modules index. If set to NO, only the current project's groups will be
-# listed.
-# The default value is: YES.
-
-EXTERNAL_GROUPS = YES
-
-# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in
-# the related pages index. If set to NO, only the current project's pages will
-# be listed.
-# The default value is: YES.
-
-EXTERNAL_PAGES = YES
-
-# The PERL_PATH should be the absolute path and name of the perl script
-# interpreter (i.e. the result of 'which perl').
-# The default file (with absolute path) is: /usr/bin/perl.
-
-PERL_PATH = /usr/bin/perl
-
-#---------------------------------------------------------------------------
-# Configuration options related to the dot tool
-#---------------------------------------------------------------------------
-
-# If the CLASS_DIAGRAMS tag is set to YES, doxygen will generate a class diagram
-# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to
-# NO turns the diagrams off. Note that this option also works with HAVE_DOT
-# disabled, but it is recommended to install and use dot, since it yields more
-# powerful graphs.
-# The default value is: YES.
-
-CLASS_DIAGRAMS = YES
-
-# You can define message sequence charts within doxygen comments using the \msc
-# command. Doxygen will then run the mscgen tool (see:
-# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the
-# documentation. The MSCGEN_PATH tag allows you to specify the directory where
-# the mscgen tool resides. If left empty the tool is assumed to be found in the
-# default search path.
-
-MSCGEN_PATH =
-
-# You can include diagrams made with dia in doxygen documentation. Doxygen will
-# then run dia to produce the diagram and insert it in the documentation. The
-# DIA_PATH tag allows you to specify the directory where the dia binary resides.
-# If left empty dia is assumed to be found in the default search path.
-
-DIA_PATH =
-
-# If set to YES the inheritance and collaboration graphs will hide inheritance
-# and usage relations if the target is undocumented or is not a class.
-# The default value is: YES.
-
-HIDE_UNDOC_RELATIONS = YES
-
-# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
-# available from the path. This tool is part of Graphviz (see:
-# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
-# Bell Labs. The other options in this section have no effect if this option is
-# set to NO
-# The default value is: NO.
-
-HAVE_DOT = NO
-
-# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
-# to run in parallel. When set to 0 doxygen will base this on the number of
-# processors available in the system. You can set it explicitly to a value
-# larger than 0 to get control over the balance between CPU load and processing
-# speed.
-# Minimum value: 0, maximum value: 32, default value: 0.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_NUM_THREADS = 0
-
-# When you want a differently looking font in the dot files that doxygen
-# generates you can specify the font name using DOT_FONTNAME. You need to make
-# sure dot is able to find the font, which can be done by putting it in a
-# standard location or by setting the DOTFONTPATH environment variable or by
-# setting DOT_FONTPATH to the directory containing the font.
-# The default value is: Helvetica.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_FONTNAME = Helvetica
-
-# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of
-# dot graphs.
-# Minimum value: 4, maximum value: 24, default value: 10.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_FONTSIZE = 10
-
-# By default doxygen will tell dot to use the default font as specified with
-# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set
-# the path where dot can find it using this tag.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_FONTPATH =
-
-# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for
-# each documented class showing the direct and indirect inheritance relations.
-# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-CLASS_GRAPH = YES
-
-# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
-# graph for each documented class showing the direct and indirect implementation
-# dependencies (inheritance, containment, and class references variables) of the
-# class with other documented classes.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-COLLABORATION_GRAPH = YES
-
-# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
-# groups, showing the direct groups dependencies.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-GROUP_GRAPHS = YES
-
-# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and
-# collaboration diagrams in a style similar to the OMG's Unified Modeling
-# Language.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-UML_LOOK = NO
-
-# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
-# class node. If there are many fields or methods and many nodes the graph may
-# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
-# number of items for each type to make the size more manageable. Set this to 0
-# for no limit. Note that the threshold may be exceeded by 50% before the limit
-# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
-# but if the number exceeds 15, the total amount of fields shown is limited to
-# 10.
-# Minimum value: 0, maximum value: 100, default value: 10.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-UML_LIMIT_NUM_FIELDS = 10
-
-# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
-# collaboration graphs will show the relations between templates and their
-# instances.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-TEMPLATE_RELATIONS = NO
-
-# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
-# YES then doxygen will generate a graph for each documented file showing the
-# direct and indirect include dependencies of the file with other documented
-# files.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-INCLUDE_GRAPH = YES
-
-# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
-# set to YES then doxygen will generate a graph for each documented file showing
-# the direct and indirect include dependencies of the file with other documented
-# files.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-INCLUDED_BY_GRAPH = YES
-
-# If the CALL_GRAPH tag is set to YES then doxygen will generate a call
-# dependency graph for every global function or class method.
-#
-# Note that enabling this option will significantly increase the time of a run.
-# So in most cases it will be better to enable call graphs for selected
-# functions only using the \callgraph command. Disabling a call graph can be
-# accomplished by means of the command \hidecallgraph.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-CALL_GRAPH = NO
-
-# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller
-# dependency graph for every global function or class method.
-#
-# Note that enabling this option will significantly increase the time of a run.
-# So in most cases it will be better to enable caller graphs for selected
-# functions only using the \callergraph command. Disabling a caller graph can be
-# accomplished by means of the command \hidecallergraph.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-CALLER_GRAPH = NO
-
-# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
-# hierarchy of all classes instead of a textual one.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-GRAPHICAL_HIERARCHY = YES
-
-# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
-# dependencies a directory has on other directories in a graphical way. The
-# dependency relations are determined by the #include relations between the
-# files in the directories.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DIRECTORY_GRAPH = YES
-
-# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
-# generated by dot. For an explanation of the image formats see the section
-# output formats in the documentation of the dot tool (Graphviz (see:
-# http://www.graphviz.org/)).
-# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
-# to make the SVG files visible in IE 9+ (other browsers do not have this
-# requirement).
-# Possible values are: png, jpg, gif, svg, png:gd, png:gd:gd, png:cairo,
-# png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and
-# png:gdiplus:gdiplus.
-# The default value is: png.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_IMAGE_FORMAT = png
-
-# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
-# enable generation of interactive SVG images that allow zooming and panning.
-#
-# Note that this requires a modern browser other than Internet Explorer. Tested
-# and working are Firefox, Chrome, Safari, and Opera.
-# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
-# the SVG files visible. Older versions of IE do not have SVG support.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-INTERACTIVE_SVG = NO
-
-# The DOT_PATH tag can be used to specify the path where the dot tool can be
-# found. If left blank, it is assumed the dot tool can be found in the path.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_PATH =
-
-# The DOTFILE_DIRS tag can be used to specify one or more directories that
-# contain dot files that are included in the documentation (see the \dotfile
-# command).
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOTFILE_DIRS =
-
-# The MSCFILE_DIRS tag can be used to specify one or more directories that
-# contain msc files that are included in the documentation (see the \mscfile
-# command).
-
-MSCFILE_DIRS =
-
-# The DIAFILE_DIRS tag can be used to specify one or more directories that
-# contain dia files that are included in the documentation (see the \diafile
-# command).
-
-DIAFILE_DIRS =
-
-# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the
-# path where java can find the plantuml.jar file. If left blank, it is assumed
-# PlantUML is not used or called during a preprocessing step. Doxygen will
-# generate a warning when it encounters a \startuml command in this case and
-# will not generate output for the diagram.
-
-PLANTUML_JAR_PATH =
-
-# When using plantuml, the PLANTUML_CFG_FILE tag can be used to specify a
-# configuration file for plantuml.
-
-PLANTUML_CFG_FILE =
-
-# When using plantuml, the specified paths are searched for files specified by
-# the !include statement in a plantuml block.
-
-PLANTUML_INCLUDE_PATH =
-
-# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes
-# that will be shown in the graph. If the number of nodes in a graph becomes
-# larger than this value, doxygen will truncate the graph, which is visualized
-# by representing a node as a red box. Note that doxygen if the number of direct
-# children of the root node in a graph is already larger than
-# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that
-# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
-# Minimum value: 0, maximum value: 10000, default value: 50.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_GRAPH_MAX_NODES = 50
-
-# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs
-# generated by dot. A depth value of 3 means that only nodes reachable from the
-# root by following a path via at most 3 edges will be shown. Nodes that lay
-# further from the root node will be omitted. Note that setting this option to 1
-# or 2 may greatly reduce the computation time needed for large code bases. Also
-# note that the size of a graph can be further restricted by
-# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
-# Minimum value: 0, maximum value: 1000, default value: 0.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-MAX_DOT_GRAPH_DEPTH = 0
-
-# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
-# background. This is disabled by default, because dot on Windows does not seem
-# to support this out of the box.
-#
-# Warning: Depending on the platform used, enabling this option may lead to
-# badly anti-aliased labels on the edges of a graph (i.e. they become hard to
-# read).
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_TRANSPARENT = NO
-
-# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output
-# files in one run (i.e. multiple -o and -T options on the command line). This
-# makes dot run faster, but since only newer versions of dot (>1.8.10) support
-# this, this feature is disabled by default.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_MULTI_TARGETS = NO
-
-# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
-# explaining the meaning of the various boxes and arrows in the dot generated
-# graphs.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-GENERATE_LEGEND = YES
-
-# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate dot
-# files that are used to generate the various graphs.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_CLEANUP = YES
diff --git a/DvdLib/DvdLib.csproj b/DvdLib/DvdLib.csproj
index b2c752d0c8..9dbaa9e2f0 100644
--- a/DvdLib/DvdLib.csproj
+++ b/DvdLib/DvdLib.csproj
@@ -11,6 +11,7 @@
netstandard2.0
false
+ true
diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs
index 4f8c89e485..d22fc21774 100644
--- a/Emby.Dlna/ContentDirectory/ControlHandler.cs
+++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs
@@ -289,7 +289,7 @@ namespace Emby.Dlna.ContentDirectory
var childrenResult = GetUserItems(item, serverItem.StubType, user, sortCriteria, start, requestedCount);
totalCount = childrenResult.TotalRecordCount;
- provided = childrenResult.Items.Length;
+ provided = childrenResult.Items.Count;
foreach (var i in childrenResult.Items)
{
@@ -309,6 +309,7 @@ namespace Emby.Dlna.ContentDirectory
}
}
}
+
writer.WriteFullEndElement();
//writer.WriteEndDocument();
}
@@ -386,7 +387,7 @@ namespace Emby.Dlna.ContentDirectory
totalCount = childrenResult.TotalRecordCount;
- provided = childrenResult.Items.Length;
+ provided = childrenResult.Items.Count;
var dlnaOptions = _config.GetDlnaConfiguration();
@@ -677,7 +678,7 @@ namespace Emby.Dlna.ContentDirectory
return new QueryResult
{
- Items = list.ToArray(),
+ Items = list,
TotalRecordCount = list.Count
};
}
@@ -755,7 +756,7 @@ namespace Emby.Dlna.ContentDirectory
return new QueryResult
{
- Items = list.ToArray(),
+ Items = list,
TotalRecordCount = list.Count
};
}
@@ -860,7 +861,7 @@ namespace Emby.Dlna.ContentDirectory
return new QueryResult
{
- Items = list.ToArray(),
+ Items = list,
TotalRecordCount = list.Count
};
}
diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs
index a21aff9f91..85ef9d4829 100644
--- a/Emby.Dlna/Didl/DidlBuilder.cs
+++ b/Emby.Dlna/Didl/DidlBuilder.cs
@@ -158,7 +158,7 @@ namespace Emby.Dlna.Didl
AddGeneralProperties(item, null, context, writer, filter);
- AddSamsungBookmarkInfo(item, user, writer);
+ AddSamsungBookmarkInfo(item, user, writer, streamInfo);
// refID?
// storeAttribute(itemNode, object, ClassProperties.REF_ID, false);
@@ -581,7 +581,7 @@ namespace Emby.Dlna.Didl
writer.WriteFullEndElement();
}
- private void AddSamsungBookmarkInfo(BaseItem item, User user, XmlWriter writer)
+ private void AddSamsungBookmarkInfo(BaseItem item, User user, XmlWriter writer, StreamInfo streamInfo)
{
if (!item.SupportsPositionTicksResume || item is Folder)
{
@@ -605,10 +605,11 @@ namespace Emby.Dlna.Didl
}
var userdata = _userDataManager.GetUserData(user, item);
+ var playbackPositionTicks = (streamInfo != null && streamInfo.StartPositionTicks > 0) ? streamInfo.StartPositionTicks : userdata.PlaybackPositionTicks;
- if (userdata.PlaybackPositionTicks > 0)
+ if (playbackPositionTicks > 0)
{
- var elementValue = string.Format("BM={0}", Convert.ToInt32(TimeSpan.FromTicks(userdata.PlaybackPositionTicks).TotalSeconds).ToString(_usCulture));
+ var elementValue = string.Format("BM={0}", Convert.ToInt32(TimeSpan.FromTicks(playbackPositionTicks).TotalSeconds).ToString(_usCulture));
AddValue(writer, "sec", "dcmInfo", elementValue, secAttribute.Value);
}
}
@@ -1082,7 +1083,7 @@ namespace Emby.Dlna.Didl
public static string GetClientId(Guid idValue, StubType? stubType)
{
- var id = idValue.ToString("N");
+ var id = idValue.ToString("N", CultureInfo.InvariantCulture);
if (stubType.HasValue)
{
@@ -1096,7 +1097,7 @@ namespace Emby.Dlna.Didl
{
var url = string.Format("{0}/Items/{1}/Images/{2}/0/{3}/{4}/{5}/{6}/0/0",
_serverAddress,
- info.ItemId.ToString("N"),
+ info.ItemId.ToString("N", CultureInfo.InvariantCulture),
info.Type,
info.ImageTag,
format,
diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs
index 2b76d27025..d5d788021d 100644
--- a/Emby.Dlna/DlnaManager.cs
+++ b/Emby.Dlna/DlnaManager.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
@@ -300,7 +301,7 @@ namespace Emby.Dlna
profile = ReserializeProfile(tempProfile);
- profile.Id = path.ToLowerInvariant().GetMD5().ToString("N");
+ profile.Id = path.ToLowerInvariant().GetMD5().ToString("N", CultureInfo.InvariantCulture);
_profiles[path] = new Tuple(GetInternalProfileInfo(_fileSystem.GetFileInfo(path), type), profile);
@@ -352,7 +353,7 @@ namespace Emby.Dlna
Info = new DeviceProfileInfo
{
- Id = file.FullName.ToLowerInvariant().GetMD5().ToString("N"),
+ Id = file.FullName.ToLowerInvariant().GetMD5().ToString("N", CultureInfo.InvariantCulture),
Name = _fileSystem.GetFileNameWithoutExtension(file),
Type = type
}
diff --git a/Emby.Dlna/Emby.Dlna.csproj b/Emby.Dlna/Emby.Dlna.csproj
index 4c07087c53..34b49120bb 100644
--- a/Emby.Dlna/Emby.Dlna.csproj
+++ b/Emby.Dlna/Emby.Dlna.csproj
@@ -14,6 +14,7 @@
netstandard2.0
false
+ true
diff --git a/Emby.Dlna/Eventing/EventManager.cs b/Emby.Dlna/Eventing/EventManager.cs
index b4ff3ec1d5..4b542a820c 100644
--- a/Emby.Dlna/Eventing/EventManager.cs
+++ b/Emby.Dlna/Eventing/EventManager.cs
@@ -55,7 +55,7 @@ namespace Emby.Dlna.Eventing
public EventSubscriptionResponse CreateEventSubscription(string notificationType, string requestedTimeoutString, string callbackUrl)
{
var timeout = ParseTimeout(requestedTimeoutString) ?? 300;
- var id = "uuid:" + Guid.NewGuid().ToString("N");
+ var id = "uuid:" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
// Remove logging for now because some devices are sending this very frequently
// TODO re-enable with dlna debug logging setting
diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs
index 206a873e1d..77bde0ca24 100644
--- a/Emby.Dlna/Main/DlnaEntryPoint.cs
+++ b/Emby.Dlna/Main/DlnaEntryPoint.cs
@@ -1,5 +1,6 @@
using System;
using System.Net.Sockets;
+using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Emby.Dlna.PlayTo;
@@ -307,7 +308,7 @@ namespace Emby.Dlna.Main
{
guid = text.GetMD5();
}
- return guid.ToString("N");
+ return guid.ToString("N", CultureInfo.InvariantCulture);
}
private void SetProperies(SsdpDevice device, string fullDeviceType)
diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs
index c0a4418711..a3a013096c 100644
--- a/Emby.Dlna/PlayTo/PlayToManager.cs
+++ b/Emby.Dlna/PlayTo/PlayToManager.cs
@@ -1,4 +1,5 @@
using System;
+using System.Globalization;
using System.Linq;
using System.Net;
using System.Threading;
@@ -141,7 +142,7 @@ namespace Emby.Dlna.PlayTo
return usn;
}
- return usn.GetMD5().ToString("N");
+ return usn.GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
private async Task AddDevice(UpnpDeviceInfo info, string location, CancellationToken cancellationToken)
@@ -156,7 +157,7 @@ namespace Emby.Dlna.PlayTo
}
else
{
- uuid = location.GetMD5().ToString("N");
+ uuid = location.GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
var sessionInfo = _sessionManager.LogSessionActivity("DLNA", _appHost.ApplicationVersion, uuid, null, uri.OriginalString, null);
diff --git a/Emby.Dlna/PlayTo/SsdpHttpClient.cs b/Emby.Dlna/PlayTo/SsdpHttpClient.cs
index 22aaa68858..66c634150a 100644
--- a/Emby.Dlna/PlayTo/SsdpHttpClient.cs
+++ b/Emby.Dlna/PlayTo/SsdpHttpClient.cs
@@ -16,6 +16,8 @@ namespace Emby.Dlna.PlayTo
private const string USERAGENT = "Microsoft-Windows/6.2 UPnP/1.0 Microsoft-DLNA DLNADOC/1.50";
private const string FriendlyName = "Jellyfin";
+ private readonly CultureInfo _usCulture = new CultureInfo("en-US");
+
private readonly IHttpClient _httpClient;
private readonly IServerConfigurationManager _config;
@@ -25,7 +27,8 @@ namespace Emby.Dlna.PlayTo
_config = config;
}
- public async Task SendCommandAsync(string baseUrl,
+ public async Task SendCommandAsync(
+ string baseUrl,
DeviceService service,
string command,
string postData,
@@ -35,12 +38,20 @@ namespace Emby.Dlna.PlayTo
var cancellationToken = CancellationToken.None;
var url = NormalizeServiceUrl(baseUrl, service.ControlUrl);
- using (var response = await PostSoapDataAsync(url, '\"' + service.ServiceType + '#' + command + '\"', postData, header, logRequest, cancellationToken)
+ using (var response = await PostSoapDataAsync(
+ url,
+ $"\"{service.ServiceType}#{command}\"",
+ postData,
+ header,
+ logRequest,
+ cancellationToken)
.ConfigureAwait(false))
using (var stream = response.Content)
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
- return XDocument.Parse(reader.ReadToEnd(), LoadOptions.PreserveWhitespace);
+ return XDocument.Parse(
+ await reader.ReadToEndAsync().ConfigureAwait(false),
+ LoadOptions.PreserveWhitespace);
}
}
@@ -58,9 +69,8 @@ namespace Emby.Dlna.PlayTo
return baseUrl + serviceUrl;
}
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
- public async Task SubscribeAsync(string url,
+ public async Task SubscribeAsync(
+ string url,
string ip,
int port,
string localIp,
@@ -73,9 +83,6 @@ namespace Emby.Dlna.PlayTo
UserAgent = USERAGENT,
LogErrorResponseBody = true,
BufferContent = false,
-
- // The periodic requests may keep some devices awake
- LogRequestAsDebug = true
};
options.RequestHeaders["HOST"] = ip + ":" + port.ToString(_usCulture);
@@ -98,23 +105,18 @@ namespace Emby.Dlna.PlayTo
LogErrorResponseBody = true,
BufferContent = false,
- // The periodic requests may keep some devices awake
- LogRequestAsDebug = true,
-
CancellationToken = cancellationToken
};
options.RequestHeaders["FriendlyName.DLNA.ORG"] = FriendlyName;
using (var response = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false))
+ using (var stream = response.Content)
+ using (var reader = new StreamReader(stream, Encoding.UTF8))
{
- using (var stream = response.Content)
- {
- using (var reader = new StreamReader(stream, Encoding.UTF8))
- {
- return XDocument.Parse(reader.ReadToEnd(), LoadOptions.PreserveWhitespace);
- }
- }
+ return XDocument.Parse(
+ await reader.ReadToEndAsync().ConfigureAwait(false),
+ LoadOptions.PreserveWhitespace);
}
}
@@ -128,20 +130,16 @@ namespace Emby.Dlna.PlayTo
{
if (soapAction[0] != '\"')
{
- soapAction = '\"' + soapAction + '\"';
+ soapAction = $"\"{soapAction}\"";
}
var options = new HttpRequestOptions
{
Url = url,
UserAgent = USERAGENT,
- LogRequest = logRequest || _config.GetDlnaConfiguration().EnableDebugLog,
LogErrorResponseBody = true,
BufferContent = false,
- // The periodic requests may keep some devices awake
- LogRequestAsDebug = true,
-
CancellationToken = cancellationToken
};
diff --git a/Emby.Drawing/Emby.Drawing.csproj b/Emby.Drawing/Emby.Drawing.csproj
index 9f97baf772..2e539f2c7f 100644
--- a/Emby.Drawing/Emby.Drawing.csproj
+++ b/Emby.Drawing/Emby.Drawing.csproj
@@ -3,6 +3,8 @@
netstandard2.0
false
+ true
+ true
@@ -15,4 +17,9 @@
+
+
+ latest
+
+
diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs
index 6d209d8d01..ce8089e59c 100644
--- a/Emby.Drawing/ImageProcessor.cs
+++ b/Emby.Drawing/ImageProcessor.cs
@@ -22,42 +22,47 @@ using Microsoft.Extensions.Logging;
namespace Emby.Drawing
{
///
- /// Class ImageProcessor
+ /// Class ImageProcessor.
///
public class ImageProcessor : IImageProcessor, IDisposable
{
- ///
- /// The us culture
- ///
- protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
+ // Increment this when there's a change requiring caches to be invalidated
+ private const string Version = "3";
- ///
- /// Gets the list of currently registered image processors
- /// Image processors are specialized metadata providers that run after the normal ones
- ///
- /// The image enhancers.
- public IImageEnhancer[] ImageEnhancers { get; private set; }
+ private static readonly HashSet _transparentImageTypes
+ = new HashSet(StringComparer.OrdinalIgnoreCase) { ".png", ".webp", ".gif" };
///
/// The _logger
///
private readonly ILogger _logger;
-
private readonly IFileSystem _fileSystem;
private readonly IServerApplicationPaths _appPaths;
private IImageEncoder _imageEncoder;
private readonly Func _libraryManager;
private readonly Func _mediaEncoder;
+ private readonly Dictionary _locks = new Dictionary();
+ private bool _disposed = false;
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
public ImageProcessor(
- ILoggerFactory loggerFactory,
+ ILogger logger,
IServerApplicationPaths appPaths,
IFileSystem fileSystem,
IImageEncoder imageEncoder,
Func libraryManager,
Func mediaEncoder)
{
- _logger = loggerFactory.CreateLogger(nameof(ImageProcessor));
+ _logger = logger;
_fileSystem = fileSystem;
_imageEncoder = imageEncoder;
_libraryManager = libraryManager;
@@ -69,20 +74,11 @@ namespace Emby.Drawing
ImageHelper.ImageProcessor = this;
}
- public IImageEncoder ImageEncoder
- {
- get => _imageEncoder;
- set
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value));
- }
+ private string ResizedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "resized-images");
- _imageEncoder = value;
- }
- }
+ private string EnhancedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "enhanced-images");
+ ///
public IReadOnlyCollection SupportedInputFormats =>
new HashSet(StringComparer.OrdinalIgnoreCase)
{
@@ -115,18 +111,20 @@ namespace Emby.Drawing
"wbmp"
};
+ ///
+ public IReadOnlyCollection ImageEnhancers { get; set; }
+ ///
public bool SupportsImageCollageCreation => _imageEncoder.SupportsImageCollageCreation;
- private string ResizedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "resized-images");
-
- private string EnhancedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "enhanced-images");
-
- public void AddParts(IEnumerable enhancers)
+ ///
+ public IImageEncoder ImageEncoder
{
- ImageEnhancers = enhancers.ToArray();
+ get => _imageEncoder;
+ set => _imageEncoder = value ?? throw new ArgumentNullException(nameof(value));
}
+ ///
public async Task ProcessImage(ImageProcessingOptions options, Stream toStream)
{
var file = await ProcessImage(options).ConfigureAwait(false);
@@ -137,15 +135,15 @@ namespace Emby.Drawing
}
}
+ ///
public IReadOnlyCollection GetSupportedImageOutputFormats()
=> _imageEncoder.SupportedOutputFormats;
- private static readonly HashSet TransparentImageTypes
- = new HashSet(StringComparer.OrdinalIgnoreCase) { ".png", ".webp", ".gif" };
-
+ ///
public bool SupportsTransparency(string path)
- => TransparentImageTypes.Contains(Path.GetExtension(path));
+ => _transparentImageTypes.Contains(Path.GetExtension(path));
+ ///
public async Task<(string path, string mimeType, DateTime dateModified)> ProcessImage(ImageProcessingOptions options)
{
if (options == null)
@@ -187,9 +185,9 @@ namespace Emby.Drawing
}
dateModified = supportedImageInfo.dateModified;
- bool requiresTransparency = TransparentImageTypes.Contains(Path.GetExtension(originalImagePath));
+ bool requiresTransparency = _transparentImageTypes.Contains(Path.GetExtension(originalImagePath));
- if (options.Enhancers.Length > 0)
+ if (options.Enhancers.Count > 0)
{
if (item == null)
{
@@ -279,7 +277,7 @@ namespace Emby.Drawing
}
}
- private ImageFormat GetOutputFormat(ImageFormat[] clientSupportedFormats, bool requiresTransparency)
+ private ImageFormat GetOutputFormat(IReadOnlyCollection clientSupportedFormats, bool requiresTransparency)
{
var serverFormats = GetSupportedImageOutputFormats();
@@ -320,11 +318,6 @@ namespace Emby.Drawing
}
}
- ///
- /// Increment this when there's a change requiring caches to be invalidated
- ///
- private const string Version = "3";
-
///
/// Gets the cache file path based on a set of parameters
///
@@ -372,9 +365,11 @@ namespace Emby.Drawing
return GetCachePath(ResizedImageCachePath, filename, "." + format.ToString().ToLowerInvariant());
}
+ ///
public ImageDimensions GetImageDimensions(BaseItem item, ItemImageInfo info)
=> GetImageDimensions(item, info, true);
+ ///
public ImageDimensions GetImageDimensions(BaseItem item, ItemImageInfo info, bool updateItem)
{
int width = info.Width;
@@ -400,26 +395,19 @@ namespace Emby.Drawing
return size;
}
- ///
- /// Gets the size of the image.
- ///
+ ///
public ImageDimensions GetImageDimensions(string path)
=> _imageEncoder.GetImageSize(path);
- ///
- /// Gets the image cache tag.
- ///
- /// The item.
- /// The image.
- /// Guid.
- /// item
+ ///
public string GetImageCacheTag(BaseItem item, ItemImageInfo image)
{
- var supportedEnhancers = GetSupportedEnhancers(item, image.Type);
+ var supportedEnhancers = GetSupportedEnhancers(item, image.Type).ToArray();
return GetImageCacheTag(item, image, supportedEnhancers);
}
+ ///
public string GetImageCacheTag(BaseItem item, ChapterInfo chapter)
{
try
@@ -437,31 +425,24 @@ namespace Emby.Drawing
}
}
- ///
- /// Gets the image cache tag.
- ///
- /// The item.
- /// The image.
- /// The image enhancers.
- /// Guid.
- /// item
- public string GetImageCacheTag(BaseItem item, ItemImageInfo image, IImageEnhancer[] imageEnhancers)
+ ///
+ public string GetImageCacheTag(BaseItem item, ItemImageInfo image, IReadOnlyCollection imageEnhancers)
{
string originalImagePath = image.Path;
DateTime dateModified = image.DateModified;
ImageType imageType = image.Type;
// Optimization
- if (imageEnhancers.Length == 0)
+ if (imageEnhancers.Count == 0)
{
- return (originalImagePath + dateModified.Ticks).GetMD5().ToString("N");
+ return (originalImagePath + dateModified.Ticks).GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
// Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
cacheKeys.Add(originalImagePath + dateModified.Ticks);
- return string.Join("|", cacheKeys).GetMD5().ToString("N");
+ return string.Join("|", cacheKeys).GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
private async Task<(string path, DateTime dateModified)> GetSupportedImage(string originalImagePath, DateTime dateModified)
@@ -480,7 +461,7 @@ namespace Emby.Drawing
{
try
{
- string filename = (originalImagePath + dateModified.Ticks.ToString(UsCulture)).GetMD5().ToString("N");
+ string filename = (originalImagePath + dateModified.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("N", CultureInfo.InvariantCulture);
string cacheExtension = _mediaEncoder().SupportsEncoder("libwebp") ? ".webp" : ".png";
var outputPath = Path.Combine(_appPaths.ImageCachePath, "converted-images", filename + cacheExtension);
@@ -507,16 +488,10 @@ namespace Emby.Drawing
return (originalImagePath, dateModified);
}
- ///
- /// Gets the enhanced image.
- ///
- /// The item.
- /// Type of the image.
- /// Index of the image.
- /// Task{System.String}.
+ ///
public async Task GetEnhancedImage(BaseItem item, ImageType imageType, int imageIndex)
{
- var enhancers = GetSupportedEnhancers(item, imageType);
+ var enhancers = GetSupportedEnhancers(item, imageType).ToArray();
ItemImageInfo imageInfo = item.GetImageInfo(imageType, imageIndex);
@@ -532,7 +507,7 @@ namespace Emby.Drawing
bool inputImageSupportsTransparency,
BaseItem item,
int imageIndex,
- IImageEnhancer[] enhancers,
+ IReadOnlyCollection enhancers,
CancellationToken cancellationToken)
{
var originalImagePath = image.Path;
@@ -573,6 +548,7 @@ namespace Emby.Drawing
/// Index of the image.
/// The supported enhancers.
/// The cache unique identifier.
+ /// The cancellation token.
/// Task<System.String>.
///
/// originalImagePath
@@ -584,9 +560,9 @@ namespace Emby.Drawing
BaseItem item,
ImageType imageType,
int imageIndex,
- IImageEnhancer[] supportedEnhancers,
+ IReadOnlyCollection supportedEnhancers,
string cacheGuid,
- CancellationToken cancellationToken)
+ CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(originalImagePath))
{
@@ -680,6 +656,7 @@ namespace Emby.Drawing
{
throw new ArgumentNullException(nameof(path));
}
+
if (string.IsNullOrEmpty(uniqueName))
{
throw new ArgumentNullException(nameof(uniqueName));
@@ -722,6 +699,7 @@ namespace Emby.Drawing
return Path.Combine(path, prefix, filename);
}
+ ///
public void CreateImageCollage(ImageCollageOptions options)
{
_logger.LogInformation("Creating image collage and saving to {Path}", options.OutputPath);
@@ -731,38 +709,25 @@ namespace Emby.Drawing
_logger.LogInformation("Completed creation of image collage and saved to {Path}", options.OutputPath);
}
- public IImageEnhancer[] GetSupportedEnhancers(BaseItem item, ImageType imageType)
+ ///
+ public IEnumerable GetSupportedEnhancers(BaseItem item, ImageType imageType)
{
- List list = null;
-
foreach (var i in ImageEnhancers)
{
- try
- {
- if (i.Supports(item, imageType))
- {
- if (list == null)
- {
- list = new List();
- }
- list.Add(i);
- }
- }
- catch (Exception ex)
+ if (i.Supports(item, imageType))
{
- _logger.LogError(ex, "Error in image enhancer: {0}", i.GetType().Name);
+ yield return i;
}
}
-
- return list == null ? Array.Empty() : list.ToArray();
}
- private Dictionary _locks = new Dictionary();
+
private class LockInfo
{
public SemaphoreSlim Lock = new SemaphoreSlim(1, 1);
public int Count = 1;
}
+
private LockInfo GetLock(string key)
{
lock (_locks)
@@ -795,7 +760,7 @@ namespace Emby.Drawing
}
}
- private bool _disposed;
+ ///
public void Dispose()
{
_disposed = true;
diff --git a/Emby.Drawing/NullImageEncoder.cs b/Emby.Drawing/NullImageEncoder.cs
index fc4a5af9fc..5af7f16225 100644
--- a/Emby.Drawing/NullImageEncoder.cs
+++ b/Emby.Drawing/NullImageEncoder.cs
@@ -5,36 +5,40 @@ using MediaBrowser.Model.Drawing;
namespace Emby.Drawing
{
+ ///
+ /// A fallback implementation of .
+ ///
public class NullImageEncoder : IImageEncoder
{
+ ///
public IReadOnlyCollection SupportedInputFormats
=> new HashSet(StringComparer.OrdinalIgnoreCase) { "png", "jpeg", "jpg" };
+ ///
public IReadOnlyCollection SupportedOutputFormats
=> new HashSet() { ImageFormat.Jpg, ImageFormat.Png };
- public void CropWhiteSpace(string inputPath, string outputPath)
- {
- throw new NotImplementedException();
- }
-
- public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
- {
- throw new NotImplementedException();
- }
-
- public void CreateImageCollage(ImageCollageOptions options)
- {
- throw new NotImplementedException();
- }
-
+ ///
public string Name => "Null Image Encoder";
+ ///
public bool SupportsImageCollageCreation => false;
+ ///
public bool SupportsImageEncoding => false;
+ ///
public ImageDimensions GetImageSize(string path)
+ => throw new NotImplementedException();
+
+ ///
+ public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
+ {
+ throw new NotImplementedException();
+ }
+
+ ///
+ public void CreateImageCollage(ImageCollageOptions options)
{
throw new NotImplementedException();
}
diff --git a/Emby.IsoMounting/.gitignore b/Emby.IsoMounting/.gitignore
deleted file mode 100644
index bdc3535f74..0000000000
--- a/Emby.IsoMounting/.gitignore
+++ /dev/null
@@ -1,108 +0,0 @@
-# Build Folders (you can keep bin if you'd like, to store dlls and pdbs)
-[Bb]in/
-[Oo]bj/
-
-# mstest test results
-TestResults
-
-## Ignore Visual Studio temporary files, build results, and
-## files generated by popular Visual Studio add-ons.
-
-# User-specific files
-*.suo
-*.user
-*.sln.docstates
-
-# Build results
-[Dd]ebug/
-[Rr]elease/
-x64/
-*_i.c
-*_p.c
-*.ilk
-*.meta
-*.obj
-*.pch
-*.pdb
-*.pgc
-*.pgd
-*.rsp
-*.sbr
-*.tlb
-*.tli
-*.tlh
-*.tmp
-*.log
-*.vspscc
-*.vssscc
-.builds
-
-# Visual C++ cache files
-ipch/
-*.aps
-*.ncb
-*.opensdf
-*.sdf
-
-# Visual Studio profiler
-*.psess
-*.vsp
-*.vspx
-
-# Guidance Automation Toolkit
-*.gpState
-
-# ReSharper is a .NET coding add-in
-_ReSharper*
-
-# NCrunch
-*.ncrunch*
-.*crunch*.local.xml
-
-# Installshield output folder
-[Ee]xpress
-
-# DocProject is a documentation generator add-in
-DocProject/buildhelp/
-DocProject/Help/*.HxT
-DocProject/Help/*.HxC
-DocProject/Help/*.hhc
-DocProject/Help/*.hhk
-DocProject/Help/*.hhp
-DocProject/Help/Html2
-DocProject/Help/html
-
-# Click-Once directory
-publish
-
-# Publish Web Output
-*.Publish.xml
-
-# NuGet Packages Directory
-packages
-
-# Windows Azure Build Output
-csx
-*.build.csdef
-
-# Windows Store app package directory
-AppPackages/
-
-# Others
-[Bb]in
-[Oo]bj
-sql
-TestResults
-[Tt]est[Rr]esult*
-*.Cache
-ClientBin
-[Ss]tyle[Cc]op.*
-~$*
-*.dbmdl
-Generated_Code #added for RIA/Silverlight projects
-
-# Backup & report files from converting an old project file to a newer
-# Visual Studio version. Backup files are not needed, because we have git ;-)
-_UpgradeReport_Files/
-Backup*/
-UpgradeLog*.XML
diff --git a/Emby.IsoMounting/IsoMounter.sln b/Emby.IsoMounting/IsoMounter.sln
deleted file mode 100644
index 55db1b1aec..0000000000
--- a/Emby.IsoMounting/IsoMounter.sln
+++ /dev/null
@@ -1,25 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 15
-VisualStudioVersion = 15.0.27004.2009
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IsoMounter", "IsoMounter\IsoMounter.csproj", "{B94C929C-6552-4620-9BE5-422DD9A151BA}"
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|Any CPU = Debug|Any CPU
- Release|Any CPU = Release|Any CPU
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {B94C929C-6552-4620-9BE5-422DD9A151BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {B94C929C-6552-4620-9BE5-422DD9A151BA}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {B94C929C-6552-4620-9BE5-422DD9A151BA}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {B94C929C-6552-4620-9BE5-422DD9A151BA}.Release|Any CPU.Build.0 = Release|Any CPU
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
- GlobalSection(ExtensibilityGlobals) = postSolution
- SolutionGuid = {C0E8EAD1-E4D7-44CD-B801-03BD12F30B1B}
- EndGlobalSection
-EndGlobal
diff --git a/Emby.IsoMounting/IsoMounter/Configuration/PluginConfiguration.cs b/Emby.IsoMounting/IsoMounter/Configuration/PluginConfiguration.cs
deleted file mode 100644
index 4755e4e824..0000000000
--- a/Emby.IsoMounting/IsoMounter/Configuration/PluginConfiguration.cs
+++ /dev/null
@@ -1,8 +0,0 @@
-using MediaBrowser.Model.Plugins;
-
-namespace IsoMounter.Configuration
-{
- public class PluginConfiguration : BasePluginConfiguration
- {
- }
-}
diff --git a/Emby.IsoMounting/IsoMounter/IsoMounter.csproj b/Emby.IsoMounting/IsoMounter/IsoMounter.csproj
deleted file mode 100644
index dafa51cd51..0000000000
--- a/Emby.IsoMounting/IsoMounter/IsoMounter.csproj
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
- netstandard2.0
- false
-
-
-
diff --git a/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs b/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs
deleted file mode 100644
index 2f0003be88..0000000000
--- a/Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs
+++ /dev/null
@@ -1,477 +0,0 @@
-using System;
-using System.IO;
-using System.Runtime.InteropServices;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Diagnostics;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.System;
-using Microsoft.Extensions.Logging;
-using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
-
-namespace IsoMounter
-{
- public class LinuxIsoManager : IIsoMounter
- {
- [DllImport("libc", SetLastError = true)]
- static extern uint getuid();
-
- #region Private Fields
-
- private readonly bool ExecutablesAvailable;
- private readonly ILogger _logger;
- private readonly string MountCommand;
- private readonly string MountPointRoot;
- private readonly IProcessFactory ProcessFactory;
- private readonly string SudoCommand;
- private readonly string UmountCommand;
-
- #endregion
-
- #region Constructor(s)
-
- public LinuxIsoManager(ILogger logger, IProcessFactory processFactory)
- {
- _logger = logger;
- ProcessFactory = processFactory;
-
- MountPointRoot = Path.DirectorySeparatorChar + "tmp" + Path.DirectorySeparatorChar + "Emby";
-
- _logger.LogDebug(
- "[{0}] System PATH is currently set to [{1}].",
- Name,
- Environment.GetEnvironmentVariable("PATH") ?? ""
- );
-
- _logger.LogDebug(
- "[{0}] System path separator is [{1}].",
- Name,
- Path.PathSeparator
- );
-
- _logger.LogDebug(
- "[{0}] Mount point root is [{1}].",
- Name,
- MountPointRoot
- );
-
- //
- // Get the location of the executables we need to support mounting/unmounting ISO images.
- //
-
- SudoCommand = GetFullPathForExecutable("sudo");
-
- _logger.LogInformation(
- "[{0}] Using version of [sudo] located at [{1}].",
- Name,
- SudoCommand
- );
-
- MountCommand = GetFullPathForExecutable("mount");
-
- _logger.LogInformation(
- "[{0}] Using version of [mount] located at [{1}].",
- Name,
- MountCommand
- );
-
- UmountCommand = GetFullPathForExecutable("umount");
-
- _logger.LogInformation(
- "[{0}] Using version of [umount] located at [{1}].",
- Name,
- UmountCommand
- );
-
- if (!string.IsNullOrEmpty(SudoCommand) && !string.IsNullOrEmpty(MountCommand) && !string.IsNullOrEmpty(UmountCommand))
- {
- ExecutablesAvailable = true;
- }
- else
- {
- ExecutablesAvailable = false;
- }
-
- }
-
- #endregion
-
- #region Interface Implementation for IIsoMounter
-
- public bool IsInstalled => true;
-
- public string Name => "LinuxMount";
-
- public bool RequiresInstallation => false;
-
- public bool CanMount(string path)
- {
-
- if (OperatingSystem.Id != OperatingSystemId.Linux)
- {
- return false;
- }
- _logger.LogInformation(
- "[{0}] Checking we can attempt to mount [{1}], Extension = [{2}], Operating System = [{3}], Executables Available = [{4}].",
- Name,
- path,
- Path.GetExtension(path),
- OperatingSystem.Name,
- ExecutablesAvailable
- );
-
- if (ExecutablesAvailable)
- {
- return string.Equals(Path.GetExtension(path), ".iso", StringComparison.OrdinalIgnoreCase);
- }
- else
- {
- return false;
- }
- }
-
- public Task Install(CancellationToken cancellationToken)
- {
- return Task.FromResult(false);
- }
-
- public Task Mount(string isoPath, CancellationToken cancellationToken)
- {
- if (MountISO(isoPath, out LinuxMount mountedISO))
- {
- return Task.FromResult(mountedISO);
- }
- else
- {
- throw new IOException(string.Format(
- "An error occurred trying to mount image [$0].",
- isoPath
- ));
- }
- }
-
- #endregion
-
- #region Interface Implementation for IDisposable
-
- // Flag: Has Dispose already been called?
- private bool disposed = false;
-
- public void Dispose()
- {
-
- // Dispose of unmanaged resources.
- Dispose(true);
-
- // Suppress finalization.
- GC.SuppressFinalize(this);
-
- }
-
- protected virtual void Dispose(bool disposing)
- {
-
- if (disposed)
- {
- return;
- }
-
- _logger.LogInformation(
- "[{0}] Disposing [{1}].",
- Name,
- disposing
- );
-
- if (disposing)
- {
-
- //
- // Free managed objects here.
- //
-
- }
-
- //
- // Free any unmanaged objects here.
- //
-
- disposed = true;
-
- }
-
- #endregion
-
- #region Private Methods
-
- private string GetFullPathForExecutable(string name)
- {
-
- foreach (string test in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator))
- {
- string path = test.Trim();
-
- if (!string.IsNullOrEmpty(path) && File.Exists(path = Path.Combine(path, name)))
- {
- return Path.GetFullPath(path);
- }
- }
-
- return string.Empty;
- }
-
- private uint GetUID()
- {
-
- var uid = getuid();
-
- _logger.LogDebug(
- "[{0}] GetUserId() returned [{2}].",
- Name,
- uid
- );
-
- return uid;
-
- }
-
- private bool ExecuteCommand(string cmdFilename, string cmdArguments)
- {
-
- bool processFailed = false;
-
- var process = ProcessFactory.Create(
- new ProcessOptions
- {
- CreateNoWindow = true,
- RedirectStandardOutput = true,
- RedirectStandardError = true,
- UseShellExecute = false,
- FileName = cmdFilename,
- Arguments = cmdArguments,
- IsHidden = true,
- ErrorDialog = false,
- EnableRaisingEvents = true
- }
- );
-
- try
- {
- process.Start();
-
- //StreamReader outputReader = process.StandardOutput.;
- //StreamReader errorReader = process.StandardError;
-
- _logger.LogDebug(
- "[{Name}] Standard output from process is [{Error}].",
- Name,
- process.StandardOutput.ReadToEnd()
- );
-
- _logger.LogDebug(
- "[{Name}] Standard error from process is [{Error}].",
- Name,
- process.StandardError.ReadToEnd()
- );
- }
- catch (Exception ex)
- {
- processFailed = true;
- _logger.LogDebug(ex, "[{Name}] Unhandled exception executing command.", Name);
- }
-
- if (!processFailed && process.ExitCode == 0)
- {
- return true;
- }
- else
- {
- return false;
- }
-
- }
-
- private bool MountISO(string isoPath, out LinuxMount mountedISO)
- {
-
- string cmdArguments;
- string cmdFilename;
- string mountPoint = Path.Combine(MountPointRoot, Guid.NewGuid().ToString());
-
- if (!string.IsNullOrEmpty(isoPath))
- {
-
- _logger.LogInformation(
- "[{Name}] Attempting to mount [{Path}].",
- Name,
- isoPath
- );
-
- _logger.LogDebug(
- "[{Name}] ISO will be mounted at [{Path}].",
- Name,
- mountPoint
- );
-
- }
- else
- {
-
- throw new ArgumentNullException(nameof(isoPath));
-
- }
-
- try
- {
- Directory.CreateDirectory(mountPoint);
- }
- catch (UnauthorizedAccessException)
- {
- throw new IOException("Unable to create mount point(Permission denied) for " + isoPath);
- }
- catch (Exception)
- {
- throw new IOException("Unable to create mount point for " + isoPath);
- }
-
- if (GetUID() == 0)
- {
- cmdFilename = MountCommand;
- cmdArguments = string.Format("\"{0}\" \"{1}\"", isoPath, mountPoint);
- }
- else
- {
- cmdFilename = SudoCommand;
- cmdArguments = string.Format("\"{0}\" \"{1}\" \"{2}\"", MountCommand, isoPath, mountPoint);
- }
-
- _logger.LogDebug(
- "[{0}] Mount command [{1}], mount arguments [{2}].",
- Name,
- cmdFilename,
- cmdArguments
- );
-
- if (ExecuteCommand(cmdFilename, cmdArguments))
- {
-
- _logger.LogInformation(
- "[{0}] ISO mount completed successfully.",
- Name
- );
-
- mountedISO = new LinuxMount(this, isoPath, mountPoint);
-
- }
- else
- {
-
- _logger.LogInformation(
- "[{0}] ISO mount completed with errors.",
- Name
- );
-
- try
- {
- Directory.Delete(mountPoint, false);
- }
- catch (Exception ex)
- {
- _logger.LogInformation(ex, "[{Name}] Unhandled exception removing mount point.", Name);
- }
-
- mountedISO = null;
-
- }
-
- return mountedISO != null;
-
- }
-
- private void UnmountISO(LinuxMount mount)
- {
-
- string cmdArguments;
- string cmdFilename;
-
- if (mount != null)
- {
-
- _logger.LogInformation(
- "[{0}] Attempting to unmount ISO [{1}] mounted on [{2}].",
- Name,
- mount.IsoPath,
- mount.MountedPath
- );
-
- }
- else
- {
-
- throw new ArgumentNullException(nameof(mount));
-
- }
-
- if (GetUID() == 0)
- {
- cmdFilename = UmountCommand;
- cmdArguments = string.Format("\"{0}\"", mount.MountedPath);
- }
- else
- {
- cmdFilename = SudoCommand;
- cmdArguments = string.Format("\"{0}\" \"{1}\"", UmountCommand, mount.MountedPath);
- }
-
- _logger.LogDebug(
- "[{0}] Umount command [{1}], umount arguments [{2}].",
- Name,
- cmdFilename,
- cmdArguments
- );
-
- if (ExecuteCommand(cmdFilename, cmdArguments))
- {
-
- _logger.LogInformation(
- "[{0}] ISO unmount completed successfully.",
- Name
- );
-
- }
- else
- {
-
- _logger.LogInformation(
- "[{0}] ISO unmount completed with errors.",
- Name
- );
-
- }
-
- try
- {
- Directory.Delete(mount.MountedPath, false);
- }
- catch (Exception ex)
- {
- _logger.LogInformation(ex, "[{Name}] Unhandled exception removing mount point.", Name);
- }
- }
-
- #endregion
-
- #region Internal Methods
-
- internal void OnUnmount(LinuxMount mount)
- {
-
- UnmountISO(mount);
-
- }
-
- #endregion
-
- }
-
-}
-
diff --git a/Emby.IsoMounting/IsoMounter/LinuxMount.cs b/Emby.IsoMounting/IsoMounter/LinuxMount.cs
deleted file mode 100644
index b8636822b6..0000000000
--- a/Emby.IsoMounting/IsoMounter/LinuxMount.cs
+++ /dev/null
@@ -1,83 +0,0 @@
-using System;
-using MediaBrowser.Model.IO;
-
-namespace IsoMounter
-{
- internal class LinuxMount : IIsoMount
- {
-
- #region Private Fields
-
- private readonly LinuxIsoManager linuxIsoManager;
-
- #endregion
-
- #region Constructor(s)
-
- internal LinuxMount(LinuxIsoManager isoManager, string isoPath, string mountFolder)
- {
-
- linuxIsoManager = isoManager;
-
- IsoPath = isoPath;
- MountedPath = mountFolder;
-
- }
-
- #endregion
-
- #region Interface Implementation for IDisposable
-
- // Flag: Has Dispose already been called?
- private bool disposed = false;
-
- public void Dispose()
- {
-
- // Dispose of unmanaged resources.
- Dispose(true);
-
- // Suppress finalization.
- GC.SuppressFinalize(this);
-
- }
-
- protected virtual void Dispose(bool disposing)
- {
-
- if (disposed)
- {
- return;
- }
-
- if (disposing)
- {
-
- //
- // Free managed objects here.
- //
-
- linuxIsoManager.OnUnmount(this);
-
- }
-
- //
- // Free any unmanaged objects here.
- //
-
- disposed = true;
-
- }
-
- #endregion
-
- #region Interface Implementation for IIsoMount
-
- public string IsoPath { get; private set; }
- public string MountedPath { get; private set; }
-
- #endregion
-
- }
-
-}
diff --git a/Emby.IsoMounting/IsoMounter/Plugin.cs b/Emby.IsoMounting/IsoMounter/Plugin.cs
deleted file mode 100644
index f45b39d3e4..0000000000
--- a/Emby.IsoMounting/IsoMounter/Plugin.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-using System;
-using IsoMounter.Configuration;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Plugins;
-using MediaBrowser.Model.Serialization;
-
-namespace IsoMounter
-{
- public class Plugin : BasePlugin
- {
- public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) : base(applicationPaths, xmlSerializer)
- {
- }
-
- private Guid _id = new Guid("4682DD4C-A675-4F1B-8E7C-79ADF137A8F8");
- public override Guid Id => _id;
-
- ///
- /// Gets the name of the plugin
- ///
- /// The name.
- public override string Name => "Iso Mounter";
-
- ///
- /// Gets the description.
- ///
- /// The description.
- public override string Description => "Mount and stream ISO contents";
- }
-}
diff --git a/Emby.IsoMounting/IsoMounter/Properties/AssemblyInfo.cs b/Emby.IsoMounting/IsoMounter/Properties/AssemblyInfo.cs
deleted file mode 100644
index 5956fc3b31..0000000000
--- a/Emby.IsoMounting/IsoMounter/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System.Reflection;
-using System.Resources;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("IsoMounter")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin Server")]
-[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-[assembly: NeutralResourcesLanguage("en")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
diff --git a/Emby.IsoMounting/LICENSE b/Emby.IsoMounting/LICENSE
deleted file mode 100644
index d7f1051397..0000000000
--- a/Emby.IsoMounting/LICENSE
+++ /dev/null
@@ -1,339 +0,0 @@
-GNU GENERAL PUBLIC LICENSE
- Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users. This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it. (Some other Free Software Foundation software is covered by
-the GNU Lesser General Public License instead.) You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. You must make sure that they, too, receive or can get the
-source code. And you must show them these terms so they know their
-rights.
-
- We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
- Finally, any free program is threatened constantly by software
-patents. We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary. To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- GNU GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License. The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language. (Hereinafter, translation is included without limitation in
-the term "modification".) Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
- 1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
- 2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) You must cause the modified files to carry prominent notices
- stating that you changed the files and the date of any change.
-
- b) You must cause any work that you distribute or publish, that in
- whole or in part contains or is derived from the Program or any
- part thereof, to be licensed as a whole at no charge to all third
- parties under the terms of this License.
-
- c) If the modified program normally reads commands interactively
- when run, you must cause it, when started running for such
- interactive use in the most ordinary way, to print or display an
- announcement including an appropriate copyright notice and a
- notice that there is no warranty (or else, saying that you provide
- a warranty) and that users may redistribute the program under
- these conditions, and telling the user how to view a copy of this
- License. (Exception: if the Program itself is interactive but
- does not normally print such an announcement, your work based on
- the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
- a) Accompany it with the complete corresponding machine-readable
- source code, which must be distributed under the terms of Sections
- 1 and 2 above on a medium customarily used for software interchange; or,
-
- b) Accompany it with a written offer, valid for at least three
- years, to give any third party, for a charge no more than your
- cost of physically performing source distribution, a complete
- machine-readable copy of the corresponding source code, to be
- distributed under the terms of Sections 1 and 2 above on a medium
- customarily used for software interchange; or,
-
- c) Accompany it with the information you received as to the offer
- to distribute corresponding source code. (This alternative is
- allowed only for noncommercial distribution and only if you
- received the program in object code or executable form with such
- an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it. For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable. However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License. Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
- 5. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Program or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
- 6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
- 7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all. For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded. In such case, this License incorporates
-the limitation as if written in the body of this License.
-
- 9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation. If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
- 10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission. For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this. Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
- NO WARRANTY
-
- 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
- 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- {description}
- Copyright (C) {year} {fullname}
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License along
- with this program; if not, write to the Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
- Gnomovision version 69, Copyright (C) year name of author
- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the program
- `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
- {signature of Ty Coon}, 1 April 1989
- Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs. If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License.
diff --git a/Emby.IsoMounting/README.md b/Emby.IsoMounting/README.md
deleted file mode 100644
index 78bab99364..0000000000
--- a/Emby.IsoMounting/README.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# MediaBrowser.IsoMounting.Linux
-This implements two core interfaces, IIsoManager, and IIsoMount.
-### IIsoManager
-The manager class can be used to create a mount, and also determine if the mounter is capable of mounting a given file.
-### IIsoMount
-IIsoMount then represents a mount instance, which will be unmounted on disposal.
-***
-This Linux version use sudo, mount and umount.
-
-You need to add this to your sudo file via visudo(change the username):
-
- Defaults:jsmith !requiretty
- jsmith ALL=(root) NOPASSWD: /bin/mount
- jsmith ALL=(root) NOPASSWD: /bin/umount
diff --git a/Emby.Naming/Emby.Naming.csproj b/Emby.Naming/Emby.Naming.csproj
index 9e2a4950f9..fca0aa1b38 100644
--- a/Emby.Naming/Emby.Naming.csproj
+++ b/Emby.Naming/Emby.Naming.csproj
@@ -1,7 +1,7 @@
- netstandard2.0
+ netstandard2.1
false
@@ -23,7 +23,7 @@
-
+
diff --git a/Emby.Naming/Extensions/StringExtensions.cs b/Emby.Naming/Extensions/StringExtensions.cs
deleted file mode 100644
index 5512127a80..0000000000
--- a/Emby.Naming/Extensions/StringExtensions.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-using System;
-using System.Text;
-
-namespace Emby.Naming.Extensions
-{
- public static class StringExtensions
- {
- // TODO: @bond remove this when moving to netstandard2.1
- public static string Replace(this string str, string oldValue, string newValue, StringComparison comparison)
- {
- var sb = new StringBuilder();
-
- var previousIndex = 0;
- var index = str.IndexOf(oldValue, comparison);
-
- while (index != -1)
- {
- sb.Append(str.Substring(previousIndex, index - previousIndex));
- sb.Append(newValue);
- index += oldValue.Length;
-
- previousIndex = index;
- index = str.IndexOf(oldValue, index, comparison);
- }
-
- sb.Append(str.Substring(previousIndex));
-
- return sb.ToString();
- }
- }
-}
diff --git a/Emby.Naming/TV/SeasonPathParser.cs b/Emby.Naming/TV/SeasonPathParser.cs
index e81b2bb349..9096ccaf5d 100644
--- a/Emby.Naming/TV/SeasonPathParser.cs
+++ b/Emby.Naming/TV/SeasonPathParser.cs
@@ -2,8 +2,6 @@ using System;
using System.Globalization;
using System.IO;
using System.Linq;
-using Emby.Naming.Common;
-using Emby.Naming.Extensions;
namespace Emby.Naming.TV
{
diff --git a/Emby.Notifications/Emby.Notifications.csproj b/Emby.Notifications/Emby.Notifications.csproj
index 5c68e48c8f..cbd3bde4f9 100644
--- a/Emby.Notifications/Emby.Notifications.csproj
+++ b/Emby.Notifications/Emby.Notifications.csproj
@@ -3,6 +3,7 @@
netstandard2.0
false
+ true
diff --git a/Emby.Notifications/NotificationManager.cs b/Emby.Notifications/NotificationManager.cs
index 3d1d4722dd..eecbbea071 100644
--- a/Emby.Notifications/NotificationManager.cs
+++ b/Emby.Notifications/NotificationManager.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -88,7 +89,7 @@ namespace Emby.Notifications
return _userManager.Users.Where(i => i.Policy.IsAdministrator)
.Select(i => i.Id);
case SendToUserType.All:
- return _userManager.Users.Select(i => i.Id);
+ return _userManager.UsersIds;
case SendToUserType.Custom:
return request.UserIds;
default:
@@ -101,7 +102,7 @@ namespace Emby.Notifications
var config = GetConfiguration();
return _userManager.Users
- .Where(i => config.IsEnabledToSendToUser(request.NotificationType, i.Id.ToString("N"), i.Policy))
+ .Where(i => config.IsEnabledToSendToUser(request.NotificationType, i.Id.ToString("N", CultureInfo.InvariantCulture), i.Policy))
.Select(i => i.Id);
}
@@ -197,7 +198,7 @@ namespace Emby.Notifications
return _services.Select(i => new NameIdPair
{
Name = i.Name,
- Id = i.Name.GetMD5().ToString("N")
+ Id = i.Name.GetMD5().ToString("N", CultureInfo.InvariantCulture)
}).OrderBy(i => i.Name);
}
diff --git a/Emby.Notifications/Notifications.cs b/Emby.Notifications/Notifications.cs
index ec08fd1935..7aa1e7ae89 100644
--- a/Emby.Notifications/Notifications.cs
+++ b/Emby.Notifications/Notifications.cs
@@ -209,47 +209,48 @@ namespace Emby.Notifications
public static string GetItemName(BaseItem item)
{
var name = item.Name;
- var episode = item as Episode;
- if (episode != null)
+ if (item is Episode episode)
{
if (episode.IndexNumber.HasValue)
{
- name = string.Format("Ep{0} - {1}", episode.IndexNumber.Value.ToString(CultureInfo.InvariantCulture), name);
+ name = string.Format(
+ CultureInfo.InvariantCulture,
+ "Ep{0} - {1}",
+ episode.IndexNumber.Value,
+ name);
}
if (episode.ParentIndexNumber.HasValue)
{
- name = string.Format("S{0}, {1}", episode.ParentIndexNumber.Value.ToString(CultureInfo.InvariantCulture), name);
+ name = string.Format(
+ CultureInfo.InvariantCulture,
+ "S{0}, {1}",
+ episode.ParentIndexNumber.Value,
+ name);
}
}
- var hasSeries = item as IHasSeries;
- if (hasSeries != null)
+ if (item is IHasSeries hasSeries)
{
name = hasSeries.SeriesName + " - " + name;
}
- var hasAlbumArtist = item as IHasAlbumArtist;
- if (hasAlbumArtist != null)
+ if (item is IHasAlbumArtist hasAlbumArtist)
{
var artists = hasAlbumArtist.AlbumArtists;
- if (artists.Length > 0)
+ if (artists.Count > 0)
{
name = artists[0] + " - " + name;
}
}
- else
+ else if (item is IHasArtist hasArtist)
{
- var hasArtist = item as IHasArtist;
- if (hasArtist != null)
- {
- var artists = hasArtist.Artists;
+ var artists = hasArtist.Artists;
- if (artists.Length > 0)
- {
- name = artists[0] + " - " + name;
- }
+ if (artists.Count > 0)
+ {
+ name = artists[0] + " - " + name;
}
}
diff --git a/Emby.Photos/Emby.Photos.csproj b/Emby.Photos/Emby.Photos.csproj
index c9830abc5f..b57b93a8c5 100644
--- a/Emby.Photos/Emby.Photos.csproj
+++ b/Emby.Photos/Emby.Photos.csproj
@@ -10,12 +10,25 @@
-
+
netstandard2.0
false
+ true
+ true
+
+
+
+
+
+
+
+
+
+
+ ../jellyfin.ruleset
diff --git a/Emby.Photos/PhotoProvider.cs b/Emby.Photos/PhotoProvider.cs
index 99a635e608..63631e512b 100644
--- a/Emby.Photos/PhotoProvider.cs
+++ b/Emby.Photos/PhotoProvider.cs
@@ -17,39 +17,50 @@ using TagLib.IFD.Tags;
namespace Emby.Photos
{
+ ///
+ /// Metadata provider for photos.
+ ///
public class PhotoProvider : ICustomMetadataProvider, IForcedProvider, IHasItemChangeMonitor
{
private readonly ILogger _logger;
private readonly IImageProcessor _imageProcessor;
// These are causing taglib to hang
- private string[] _includextensions = new string[] { ".jpg", ".jpeg", ".png", ".tiff", ".cr2" };
-
- public PhotoProvider(ILogger logger, IImageProcessor imageProcessor)
+ private readonly string[] _includeExtensions = new string[] { ".jpg", ".jpeg", ".png", ".tiff", ".cr2" };
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The logger.
+ /// The image processor.
+ public PhotoProvider(ILogger logger, IImageProcessor imageProcessor)
{
_logger = logger;
_imageProcessor = imageProcessor;
}
+ ///
public string Name => "Embedded Information";
+ ///
public bool HasChanged(BaseItem item, IDirectoryService directoryService)
{
if (item.IsFileProtocol)
{
var file = directoryService.GetFile(item.Path);
- return (file != null && file.LastWriteTimeUtc != item.DateModified);
+ return file != null && file.LastWriteTimeUtc != item.DateModified;
}
return false;
}
+ ///
public Task FetchAsync(Photo item, MetadataRefreshOptions options, CancellationToken cancellationToken)
{
item.SetImagePath(ImageType.Primary, item.Path);
// Examples: https://github.com/mono/taglib-sharp/blob/a5f6949a53d09ce63ee7495580d6802921a21f14/tests/fixtures/TagLib.Tests.Images/NullOrientationTest.cs
- if (_includextensions.Contains(Path.GetExtension(item.Path), StringComparer.OrdinalIgnoreCase))
+ if (_includeExtensions.Contains(Path.GetExtension(item.Path), StringComparer.OrdinalIgnoreCase))
{
try
{
@@ -88,14 +99,7 @@ namespace Emby.Photos
item.Height = image.Properties.PhotoHeight;
var rating = image.ImageTag.Rating;
- if (rating.HasValue)
- {
- item.CommunityRating = rating;
- }
- else
- {
- item.CommunityRating = null;
- }
+ item.CommunityRating = rating.HasValue ? rating : null;
item.Overview = image.ImageTag.Comment;
@@ -170,8 +174,8 @@ namespace Emby.Photos
}
}
- const ItemUpdateType result = ItemUpdateType.ImageUpdate | ItemUpdateType.MetadataImport;
- return Task.FromResult(result);
+ const ItemUpdateType Result = ItemUpdateType.ImageUpdate | ItemUpdateType.MetadataImport;
+ return Task.FromResult(Result);
}
}
}
diff --git a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs
index 0530a251cc..1514402d68 100644
--- a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs
+++ b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -75,7 +76,6 @@ namespace Emby.Server.Implementations.Activity
_sessionManager.AuthenticationFailed += OnAuthenticationFailed;
_sessionManager.AuthenticationSucceeded += OnAuthenticationSucceeded;
_sessionManager.SessionEnded += OnSessionEnded;
-
_sessionManager.PlaybackStart += OnPlaybackStart;
_sessionManager.PlaybackStopped += OnPlaybackStopped;
@@ -96,7 +96,10 @@ namespace Emby.Server.Implementations.Activity
{
CreateLogEntry(new ActivityLogEntry
{
- Name = string.Format(_localization.GetLocalizedString("CameraImageUploadedFrom"), e.Argument.Device.Name),
+ Name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("CameraImageUploadedFrom"),
+ e.Argument.Device.Name),
Type = NotificationType.CameraImageUploaded.ToString()
});
}
@@ -105,7 +108,10 @@ namespace Emby.Server.Implementations.Activity
{
CreateLogEntry(new ActivityLogEntry
{
- Name = string.Format(_localization.GetLocalizedString("UserLockedOutWithName"), e.Argument.Name),
+ Name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("UserLockedOutWithName"),
+ e.Argument.Name),
Type = NotificationType.UserLockedOut.ToString(),
UserId = e.Argument.Id
});
@@ -115,9 +121,13 @@ namespace Emby.Server.Implementations.Activity
{
CreateLogEntry(new ActivityLogEntry
{
- Name = string.Format(_localization.GetLocalizedString("SubtitleDownloadFailureFromForItem"), e.Provider, Notifications.Notifications.GetItemName(e.Item)),
+ Name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("SubtitleDownloadFailureFromForItem"),
+ e.Provider,
+ Notifications.Notifications.GetItemName(e.Item)),
Type = "SubtitleDownloadFailure",
- ItemId = e.Item.Id.ToString("N"),
+ ItemId = e.Item.Id.ToString("N", CultureInfo.InvariantCulture),
ShortOverview = e.Exception.Message
});
}
@@ -178,7 +188,12 @@ namespace Emby.Server.Implementations.Activity
CreateLogEntry(new ActivityLogEntry
{
- Name = string.Format(_localization.GetLocalizedString("UserStartedPlayingItemWithValues"), user.Name, GetItemName(item), e.DeviceName),
+ Name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("UserStartedPlayingItemWithValues"),
+ user.Name,
+ GetItemName(item),
+ e.DeviceName),
Type = GetPlaybackNotificationType(item.MediaType),
UserId = user.Id
});
@@ -193,7 +208,7 @@ namespace Emby.Server.Implementations.Activity
name = item.SeriesName + " - " + name;
}
- if (item.Artists != null && item.Artists.Length > 0)
+ if (item.Artists != null && item.Artists.Count > 0)
{
name = item.Artists[0] + " - " + name;
}
@@ -238,21 +253,31 @@ namespace Emby.Server.Implementations.Activity
if (string.IsNullOrEmpty(session.UserName))
{
- name = string.Format(_localization.GetLocalizedString("DeviceOfflineWithName"), session.DeviceName);
+ name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("DeviceOfflineWithName"),
+ session.DeviceName);
// Causing too much spam for now
return;
}
else
{
- name = string.Format(_localization.GetLocalizedString("UserOfflineFromDevice"), session.UserName, session.DeviceName);
+ name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("UserOfflineFromDevice"),
+ session.UserName,
+ session.DeviceName);
}
CreateLogEntry(new ActivityLogEntry
{
Name = name,
Type = "SessionEnded",
- ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), session.RemoteEndPoint),
+ ShortOverview = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("LabelIpAddressValue"),
+ session.RemoteEndPoint),
UserId = session.UserId
});
}
@@ -263,9 +288,15 @@ namespace Emby.Server.Implementations.Activity
CreateLogEntry(new ActivityLogEntry
{
- Name = string.Format(_localization.GetLocalizedString("AuthenticationSucceededWithUserName"), user.Name),
+ Name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("AuthenticationSucceededWithUserName"),
+ user.Name),
Type = "AuthenticationSucceeded",
- ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.SessionInfo.RemoteEndPoint),
+ ShortOverview = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("LabelIpAddressValue"),
+ e.Argument.SessionInfo.RemoteEndPoint),
UserId = user.Id
});
}
@@ -274,9 +305,15 @@ namespace Emby.Server.Implementations.Activity
{
CreateLogEntry(new ActivityLogEntry
{
- Name = string.Format(_localization.GetLocalizedString("FailedLoginAttemptWithUserName"), e.Argument.Username),
+ Name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("FailedLoginAttemptWithUserName"),
+ e.Argument.Username),
Type = "AuthenticationFailed",
- ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), e.Argument.RemoteEndPoint),
+ ShortOverview = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("LabelIpAddressValue"),
+ e.Argument.RemoteEndPoint),
Severity = LogLevel.Error
});
}
@@ -285,7 +322,10 @@ namespace Emby.Server.Implementations.Activity
{
CreateLogEntry(new ActivityLogEntry
{
- Name = string.Format(_localization.GetLocalizedString("UserPolicyUpdatedWithName"), e.Argument.Name),
+ Name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("UserPolicyUpdatedWithName"),
+ e.Argument.Name),
Type = "UserPolicyUpdated",
UserId = e.Argument.Id
});
@@ -295,7 +335,10 @@ namespace Emby.Server.Implementations.Activity
{
CreateLogEntry(new ActivityLogEntry
{
- Name = string.Format(_localization.GetLocalizedString("UserDeletedWithName"), e.Argument.Name),
+ Name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("UserDeletedWithName"),
+ e.Argument.Name),
Type = "UserDeleted"
});
}
@@ -304,7 +347,10 @@ namespace Emby.Server.Implementations.Activity
{
CreateLogEntry(new ActivityLogEntry
{
- Name = string.Format(_localization.GetLocalizedString("UserPasswordChangedWithName"), e.Argument.Name),
+ Name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("UserPasswordChangedWithName"),
+ e.Argument.Name),
Type = "UserPasswordChanged",
UserId = e.Argument.Id
});
@@ -314,7 +360,10 @@ namespace Emby.Server.Implementations.Activity
{
CreateLogEntry(new ActivityLogEntry
{
- Name = string.Format(_localization.GetLocalizedString("UserCreatedWithName"), e.Argument.Name),
+ Name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("UserCreatedWithName"),
+ e.Argument.Name),
Type = "UserCreated",
UserId = e.Argument.Id
});
@@ -327,32 +376,48 @@ namespace Emby.Server.Implementations.Activity
if (string.IsNullOrEmpty(session.UserName))
{
- name = string.Format(_localization.GetLocalizedString("DeviceOnlineWithName"), session.DeviceName);
+ name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("DeviceOnlineWithName"),
+ session.DeviceName);
// Causing too much spam for now
return;
}
else
{
- name = string.Format(_localization.GetLocalizedString("UserOnlineFromDevice"), session.UserName, session.DeviceName);
+ name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("UserOnlineFromDevice"),
+ session.UserName,
+ session.DeviceName);
}
CreateLogEntry(new ActivityLogEntry
{
Name = name,
Type = "SessionStarted",
- ShortOverview = string.Format(_localization.GetLocalizedString("LabelIpAddressValue"), session.RemoteEndPoint),
+ ShortOverview = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("LabelIpAddressValue"),
+ session.RemoteEndPoint),
UserId = session.UserId
});
}
- private void OnPluginUpdated(object sender, GenericEventArgs> e)
+ private void OnPluginUpdated(object sender, GenericEventArgs<(IPlugin, PackageVersionInfo)> e)
{
CreateLogEntry(new ActivityLogEntry
{
- Name = string.Format(_localization.GetLocalizedString("PluginUpdatedWithName"), e.Argument.Item1.Name),
+ Name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("PluginUpdatedWithName"),
+ e.Argument.Item1.Name),
Type = NotificationType.PluginUpdateInstalled.ToString(),
- ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), e.Argument.Item2.versionStr),
+ ShortOverview = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("VersionNumber"),
+ e.Argument.Item2.versionStr),
Overview = e.Argument.Item2.description
});
}
@@ -361,7 +426,10 @@ namespace Emby.Server.Implementations.Activity
{
CreateLogEntry(new ActivityLogEntry
{
- Name = string.Format(_localization.GetLocalizedString("PluginUninstalledWithName"), e.Argument.Name),
+ Name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("PluginUninstalledWithName"),
+ e.Argument.Name),
Type = NotificationType.PluginUninstalled.ToString()
});
}
@@ -370,9 +438,15 @@ namespace Emby.Server.Implementations.Activity
{
CreateLogEntry(new ActivityLogEntry
{
- Name = string.Format(_localization.GetLocalizedString("PluginInstalledWithName"), e.Argument.name),
+ Name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("PluginInstalledWithName"),
+ e.Argument.name),
Type = NotificationType.PluginInstalled.ToString(),
- ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), e.Argument.versionStr)
+ ShortOverview = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("VersionNumber"),
+ e.Argument.versionStr)
});
}
@@ -382,9 +456,15 @@ namespace Emby.Server.Implementations.Activity
CreateLogEntry(new ActivityLogEntry
{
- Name = string.Format(_localization.GetLocalizedString("NameInstallFailed"), installationInfo.Name),
+ Name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("NameInstallFailed"),
+ installationInfo.Name),
Type = NotificationType.InstallationFailed.ToString(),
- ShortOverview = string.Format(_localization.GetLocalizedString("VersionNumber"), installationInfo.Version),
+ ShortOverview = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("VersionNumber"),
+ installationInfo.Version),
Overview = e.Exception.Message
});
}
@@ -401,7 +481,10 @@ namespace Emby.Server.Implementations.Activity
}
var time = result.EndTimeUtc - result.StartTimeUtc;
- var runningTime = string.Format(_localization.GetLocalizedString("LabelRunningTimeValue"), ToUserFriendlyString(time));
+ var runningTime = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("LabelRunningTimeValue"),
+ ToUserFriendlyString(time));
if (result.Status == TaskCompletionStatus.Failed)
{
@@ -419,7 +502,10 @@ namespace Emby.Server.Implementations.Activity
CreateLogEntry(new ActivityLogEntry
{
- Name = string.Format(_localization.GetLocalizedString("ScheduledTaskFailedWithName"), task.Name),
+ Name = string.Format(
+ CultureInfo.InvariantCulture,
+ _localization.GetLocalizedString("ScheduledTaskFailedWithName"),
+ task.Name),
Type = NotificationType.TaskFailed.ToString(),
Overview = string.Join(Environment.NewLine, vals),
ShortOverview = runningTime,
@@ -534,8 +620,11 @@ namespace Emby.Server.Implementations.Activity
/// The name of this item (singular form)
private static string CreateValueString(int value, string description)
{
- return string.Format("{0:#,##0} {1}",
- value, value == 1 ? description : string.Format("{0}s", description));
+ return string.Format(
+ CultureInfo.InvariantCulture,
+ "{0:#,##0} {1}",
+ value,
+ value == 1 ? description : string.Format(CultureInfo.InvariantCulture, "{0}s", description));
}
}
}
diff --git a/Emby.Server.Implementations/Activity/ActivityRepository.cs b/Emby.Server.Implementations/Activity/ActivityRepository.cs
index de46ab9655..ffaeaa541a 100644
--- a/Emby.Server.Implementations/Activity/ActivityRepository.cs
+++ b/Emby.Server.Implementations/Activity/ActivityRepository.cs
@@ -102,7 +102,7 @@ namespace Emby.Server.Implementations.Activity
}
else
{
- statement.TryBind("@UserId", entry.UserId.ToString("N"));
+ statement.TryBind("@UserId", entry.UserId.ToString("N", CultureInfo.InvariantCulture));
}
statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue());
@@ -141,7 +141,7 @@ namespace Emby.Server.Implementations.Activity
}
else
{
- statement.TryBind("@UserId", entry.UserId.ToString("N"));
+ statement.TryBind("@UserId", entry.UserId.ToString("N", CultureInfo.InvariantCulture));
}
statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue());
@@ -155,94 +155,100 @@ namespace Emby.Server.Implementations.Activity
public QueryResult GetActivityLogEntries(DateTime? minDate, bool? hasUserId, int? startIndex, int? limit)
{
- using (var connection = GetConnection(true))
- {
- var commandText = BaseActivitySelectText;
- var whereClauses = new List();
+ var commandText = BaseActivitySelectText;
+ var whereClauses = new List();
- if (minDate.HasValue)
+ if (minDate.HasValue)
+ {
+ whereClauses.Add("DateCreated>=@DateCreated");
+ }
+ if (hasUserId.HasValue)
+ {
+ if (hasUserId.Value)
{
- whereClauses.Add("DateCreated>=@DateCreated");
+ whereClauses.Add("UserId not null");
}
- if (hasUserId.HasValue)
+ else
{
- if (hasUserId.Value)
- {
- whereClauses.Add("UserId not null");
- }
- else
- {
- whereClauses.Add("UserId is null");
- }
+ whereClauses.Add("UserId is null");
}
+ }
- var whereTextWithoutPaging = whereClauses.Count == 0 ?
- string.Empty :
- " where " + string.Join(" AND ", whereClauses.ToArray());
-
- if (startIndex.HasValue && startIndex.Value > 0)
- {
- var pagingWhereText = whereClauses.Count == 0 ?
- string.Empty :
- " where " + string.Join(" AND ", whereClauses.ToArray());
-
- whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM ActivityLog {0} ORDER BY DateCreated DESC LIMIT {1})",
- pagingWhereText,
- startIndex.Value.ToString(_usCulture)));
- }
+ var whereTextWithoutPaging = whereClauses.Count == 0 ?
+ string.Empty :
+ " where " + string.Join(" AND ", whereClauses.ToArray());
- var whereText = whereClauses.Count == 0 ?
+ if (startIndex.HasValue && startIndex.Value > 0)
+ {
+ var pagingWhereText = whereClauses.Count == 0 ?
string.Empty :
" where " + string.Join(" AND ", whereClauses.ToArray());
- commandText += whereText;
+ whereClauses.Add(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "Id NOT IN (SELECT Id FROM ActivityLog {0} ORDER BY DateCreated DESC LIMIT {1})",
+ pagingWhereText,
+ startIndex.Value));
+ }
- commandText += " ORDER BY DateCreated DESC";
+ var whereText = whereClauses.Count == 0 ?
+ string.Empty :
+ " where " + string.Join(" AND ", whereClauses.ToArray());
- if (limit.HasValue)
- {
- commandText += " LIMIT " + limit.Value.ToString(_usCulture);
- }
+ commandText += whereText;
- var statementTexts = new List();
- statementTexts.Add(commandText);
- statementTexts.Add("select count (Id) from ActivityLog" + whereTextWithoutPaging);
+ commandText += " ORDER BY DateCreated DESC";
- return connection.RunInTransaction(db =>
- {
- var list = new List();
- var result = new QueryResult();
+ if (limit.HasValue)
+ {
+ commandText += " LIMIT " + limit.Value.ToString(_usCulture);
+ }
+
+ var statementTexts = new[]
+ {
+ commandText,
+ "select count (Id) from ActivityLog" + whereTextWithoutPaging
+ };
- var statements = PrepareAll(db, statementTexts).ToList();
+ var list = new List();
+ var result = new QueryResult();
- using (var statement = statements[0])
+ using (var connection = GetConnection(true))
+ {
+ connection.RunInTransaction(
+ db =>
{
- if (minDate.HasValue)
- {
- statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue());
- }
+ var statements = PrepareAll(db, statementTexts).ToList();
- foreach (var row in statement.ExecuteQuery())
+ using (var statement = statements[0])
{
- list.Add(GetEntry(row));
+ if (minDate.HasValue)
+ {
+ statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue());
+ }
+
+ foreach (var row in statement.ExecuteQuery())
+ {
+ list.Add(GetEntry(row));
+ }
}
- }
- using (var statement = statements[1])
- {
- if (minDate.HasValue)
+ using (var statement = statements[1])
{
- statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue());
- }
+ if (minDate.HasValue)
+ {
+ statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue());
+ }
- result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
- }
-
- result.Items = list.ToArray();
- return result;
-
- }, ReadTransactionMode);
+ result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
+ }
+ },
+ ReadTransactionMode);
}
+
+ result.Items = list;
+ return result;
}
private static ActivityLogEntry GetEntry(IReadOnlyList reader)
diff --git a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs
index 00cfa0c9a9..c3cdcc2222 100644
--- a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs
+++ b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs
@@ -10,6 +10,8 @@ namespace Emby.Server.Implementations.AppBase
///
public abstract class BaseApplicationPaths : IApplicationPaths
{
+ private string _dataPath;
+
///
/// Initializes a new instance of the class.
///
@@ -30,36 +32,34 @@ namespace Emby.Server.Implementations.AppBase
}
///
- /// Gets the path to the program data folder
+ /// Gets the path to the program data folder.
///
/// The program data path.
- public string ProgramDataPath { get; private set; }
+ public string ProgramDataPath { get; }
///
- /// Gets the path to the web UI resources folder
+ /// Gets the path to the web UI resources folder.
///
/// The web UI resources path.
- public string WebPath { get; set; }
+ public string WebPath { get; }
///
- /// Gets the path to the system folder
+ /// Gets the path to the system folder.
///
+ /// The path to the system folder.
public string ProgramSystemPath { get; } = AppContext.BaseDirectory;
///
- /// Gets the folder path to the data directory
+ /// Gets the folder path to the data directory.
///
/// The data directory.
- private string _dataPath;
public string DataPath
{
get => _dataPath;
private set => _dataPath = Directory.CreateDirectory(value).FullName;
}
- ///
- /// Gets the magic strings used for virtual path manipulation.
- ///
+ ///
public string VirtualDataPath { get; } = "%AppDataPath%";
///
@@ -69,43 +69,43 @@ namespace Emby.Server.Implementations.AppBase
public string ImageCachePath => Path.Combine(CachePath, "images");
///
- /// Gets the path to the plugin directory
+ /// Gets the path to the plugin directory.
///
/// The plugins path.
public string PluginsPath => Path.Combine(ProgramDataPath, "plugins");
///
- /// Gets the path to the plugin configurations directory
+ /// Gets the path to the plugin configurations directory.
///
/// The plugin configurations path.
public string PluginConfigurationsPath => Path.Combine(PluginsPath, "configurations");
///
- /// Gets the path to the log directory
+ /// Gets the path to the log directory.
///
/// The log directory path.
- public string LogDirectoryPath { get; private set; }
+ public string LogDirectoryPath { get; }
///
- /// Gets the path to the application configuration root directory
+ /// Gets the path to the application configuration root directory.
///
/// The configuration directory path.
- public string ConfigurationDirectoryPath { get; private set; }
+ public string ConfigurationDirectoryPath { get; }
///
- /// Gets the path to the system configuration file
+ /// Gets the path to the system configuration file.
///
/// The system configuration file path.
public string SystemConfigurationFilePath => Path.Combine(ConfigurationDirectoryPath, "system.xml");
///
- /// Gets the folder path to the cache directory
+ /// Gets or sets the folder path to the cache directory.
///
/// The cache directory.
public string CachePath { get; set; }
///
- /// Gets the folder path to the temp directory within the cache folder
+ /// Gets the folder path to the temp directory within the cache folder.
///
/// The temp directory.
public string TempDirectory => Path.Combine(CachePath, "temp");
diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs
index af60a8dce4..4832c19c4e 100644
--- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs
+++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
@@ -19,11 +20,44 @@ namespace Emby.Server.Implementations.AppBase
///
public abstract class BaseConfigurationManager : IConfigurationManager
{
+ private readonly IFileSystem _fileSystem;
+
+ private readonly ConcurrentDictionary _configurations = new ConcurrentDictionary();
+
+ private ConfigurationStore[] _configurationStores = Array.Empty();
+ private IConfigurationFactory[] _configurationFactories = Array.Empty();
+
///
- /// Gets the type of the configuration.
+ /// The _configuration loaded.
///
- /// The type of the configuration.
- protected abstract Type ConfigurationType { get; }
+ private bool _configurationLoaded;
+
+ ///
+ /// The _configuration sync lock.
+ ///
+ private object _configurationSyncLock = new object();
+
+ ///
+ /// The _configuration.
+ ///
+ private BaseApplicationConfiguration _configuration;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The application paths.
+ /// The logger factory.
+ /// The XML serializer.
+ /// The file system
+ protected BaseConfigurationManager(IApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IXmlSerializer xmlSerializer, IFileSystem fileSystem)
+ {
+ CommonApplicationPaths = applicationPaths;
+ XmlSerializer = xmlSerializer;
+ _fileSystem = fileSystem;
+ Logger = loggerFactory.CreateLogger(GetType().Name);
+
+ UpdateCachePath();
+ }
///
/// Occurs when [configuration updated].
@@ -40,6 +74,12 @@ namespace Emby.Server.Implementations.AppBase
///
public event EventHandler NamedConfigurationUpdated;
+ ///
+ /// Gets the type of the configuration.
+ ///
+ /// The type of the configuration.
+ protected abstract Type ConfigurationType { get; }
+
///
/// Gets the logger.
///
@@ -56,20 +96,7 @@ namespace Emby.Server.Implementations.AppBase
///
/// The application paths.
public IApplicationPaths CommonApplicationPaths { get; private set; }
- public readonly IFileSystem FileSystem;
- ///
- /// The _configuration loaded
- ///
- private bool _configurationLoaded;
- ///
- /// The _configuration sync lock
- ///
- private object _configurationSyncLock = new object();
- ///
- /// The _configuration
- ///
- private BaseApplicationConfiguration _configuration;
///
/// Gets the system configuration
///
@@ -90,26 +117,6 @@ namespace Emby.Server.Implementations.AppBase
}
}
- private ConfigurationStore[] _configurationStores = { };
- private IConfigurationFactory[] _configurationFactories = { };
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The application paths.
- /// The logger factory.
- /// The XML serializer.
- /// The file system
- protected BaseConfigurationManager(IApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IXmlSerializer xmlSerializer, IFileSystem fileSystem)
- {
- CommonApplicationPaths = applicationPaths;
- XmlSerializer = xmlSerializer;
- FileSystem = fileSystem;
- Logger = loggerFactory.CreateLogger(GetType().Name);
-
- UpdateCachePath();
- }
-
public virtual void AddParts(IEnumerable factories)
{
_configurationFactories = factories.ToArray();
@@ -171,6 +178,7 @@ namespace Emby.Server.Implementations.AppBase
private void UpdateCachePath()
{
string cachePath;
+
// If the configuration file has no entry (i.e. not set in UI)
if (string.IsNullOrWhiteSpace(CommonConfiguration.CachePath))
{
@@ -207,12 +215,16 @@ namespace Emby.Server.Implementations.AppBase
var newPath = newConfig.CachePath;
if (!string.IsNullOrWhiteSpace(newPath)
- && !string.Equals(CommonConfiguration.CachePath ?? string.Empty, newPath))
+ && !string.Equals(CommonConfiguration.CachePath ?? string.Empty, newPath, StringComparison.Ordinal))
{
// Validate
if (!Directory.Exists(newPath))
{
- throw new FileNotFoundException(string.Format("{0} does not exist.", newPath));
+ throw new FileNotFoundException(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "{0} does not exist.",
+ newPath));
}
EnsureWriteAccess(newPath);
@@ -223,11 +235,9 @@ namespace Emby.Server.Implementations.AppBase
{
var file = Path.Combine(path, Guid.NewGuid().ToString());
File.WriteAllText(file, string.Empty);
- FileSystem.DeleteFile(file);
+ _fileSystem.DeleteFile(file);
}
- private readonly ConcurrentDictionary _configurations = new ConcurrentDictionary();
-
private string GetConfigurationFile(string key)
{
return Path.Combine(CommonApplicationPaths.ConfigurationDirectoryPath, key.ToLowerInvariant() + ".xml");
diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs
index ef2f59d303..04904fc4a5 100644
--- a/Emby.Server.Implementations/ApplicationHost.cs
+++ b/Emby.Server.Implementations/ApplicationHost.cs
@@ -1,3 +1,5 @@
+#pragma warning disable CS1591
+
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@@ -49,7 +51,6 @@ using MediaBrowser.Api;
using MediaBrowser.Common;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Events;
-using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Common.Updates;
@@ -108,19 +109,23 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
+using Microsoft.Extensions.Logging;
using ServiceStack;
using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
namespace Emby.Server.Implementations
{
///
- /// Class CompositionRoot
+ /// Class CompositionRoot.
///
public abstract class ApplicationHost : IServerApplicationHost, IDisposable
{
+ private SqliteUserRepository _userRepository;
+
+ private SqliteDisplayPreferencesRepository _displayPreferencesRepository;
+
///
/// Gets a value indicating whether this instance can self restart.
///
@@ -162,6 +167,7 @@ namespace Emby.Server.Implementations
/// true if this instance has pending application restart; otherwise, false .
public bool HasPendingRestart { get; private set; }
+ ///
public bool IsShuttingDown { get; private set; }
///
@@ -198,10 +204,10 @@ namespace Emby.Server.Implementations
/// Gets or sets all concrete types.
///
/// All concrete types.
- public Type[] AllConcreteTypes { get; protected set; }
+ private Type[] _allConcreteTypes;
///
- /// The disposable parts
+ /// The disposable parts.
///
private readonly List _disposableParts = new List();
@@ -213,6 +219,7 @@ namespace Emby.Server.Implementations
public IFileSystem FileSystemManager { get; set; }
+ ///
public PackageVersionClass SystemUpdateLevel
{
get
@@ -291,8 +298,6 @@ namespace Emby.Server.Implementations
/// The user data repository.
private IUserDataManager UserDataManager { get; set; }
- private IUserRepository UserRepository { get; set; }
-
internal SqliteItemRepository ItemRepository { get; set; }
private INotificationManager NotificationManager { get; set; }
@@ -313,8 +318,6 @@ namespace Emby.Server.Implementations
private IMediaSourceManager MediaSourceManager { get; set; }
- private IPlaylistManager PlaylistManager { get; set; }
-
private readonly IConfiguration _configuration;
///
@@ -323,14 +326,6 @@ namespace Emby.Server.Implementations
/// The installation manager.
protected IInstallationManager InstallationManager { get; private set; }
- ///
- /// Gets or sets the zip client.
- ///
- /// The zip client.
- protected IZipClient ZipClient { get; private set; }
-
- protected IHttpResultFactory HttpResultFactory { get; private set; }
-
protected IAuthService AuthService { get; private set; }
public IStartupOptions StartupOptions { get; }
@@ -386,7 +381,7 @@ namespace Emby.Server.Implementations
fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
- NetworkManager.NetworkChanged += NetworkManager_NetworkChanged;
+ NetworkManager.NetworkChanged += OnNetworkChanged;
}
public string ExpandVirtualPath(string path)
@@ -410,7 +405,7 @@ namespace Emby.Server.Implementations
return ServerConfigurationManager.Configuration.LocalNetworkSubnets;
}
- private void NetworkManager_NetworkChanged(object sender, EventArgs e)
+ private void OnNetworkChanged(object sender, EventArgs e)
{
_validAddressResults.Clear();
}
@@ -418,10 +413,10 @@ namespace Emby.Server.Implementations
public string ApplicationVersion { get; } = typeof(ApplicationHost).Assembly.GetName().Version.ToString(3);
///
- /// Gets the current application user agent
+ /// Gets the current application user agent.
///
/// The application user agent.
- public string ApplicationUserAgent => Name.Replace(' ','-') + '/' + ApplicationVersion;
+ public string ApplicationUserAgent => Name.Replace(' ', '-') + "/" + ApplicationVersion;
///
/// Gets the email address for use within a comment section of a user agent field.
@@ -429,14 +424,11 @@ namespace Emby.Server.Implementations
///
public string ApplicationUserAgentAddress { get; } = "team@jellyfin.org";
- private string _productName;
-
///
- /// Gets the current application name
+ /// Gets the current application name.
///
/// The application name.
- public string ApplicationProductName
- => _productName ?? (_productName = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName);
+ public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
private DeviceId _deviceId;
@@ -470,8 +462,8 @@ namespace Emby.Server.Implementations
///
/// Creates an instance of type and resolves all constructor dependencies
///
- /// /// The type
- /// T
+ /// /// The type.
+ /// T.
public T CreateInstance()
=> ActivatorUtilities.CreateInstance(_serviceProvider);
@@ -510,16 +502,11 @@ namespace Emby.Server.Implementations
{
var currentType = typeof(T);
- return AllConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
+ return _allConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
}
- ///
- /// Gets the exports.
- ///
- /// The type
- /// if set to true [manage lifetime].
- /// IEnumerable{``0}.
- public IEnumerable GetExports(bool manageLifetime = true)
+ ///
+ public IReadOnlyCollection GetExports(bool manageLifetime = true)
{
var parts = GetExportTypes()
.Select(CreateInstanceSafe)
@@ -541,6 +528,7 @@ namespace Emby.Server.Implementations
///
/// Runs the startup tasks.
///
+ /// .
public async Task RunStartupTasksAsync()
{
Logger.LogInformation("Running startup tasks");
@@ -553,7 +541,7 @@ namespace Emby.Server.Implementations
Logger.LogInformation("ServerId: {0}", SystemId);
- var entryPoints = GetExports().ToList();
+ var entryPoints = GetExports();
var stopWatch = new Stopwatch();
stopWatch.Start();
@@ -604,10 +592,15 @@ namespace Emby.Server.Implementations
foreach (var plugin in Plugins)
{
- pluginBuilder.AppendLine(string.Format("{0} {1}", plugin.Name, plugin.Version));
+ pluginBuilder.AppendLine(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "{0} {1}",
+ plugin.Name,
+ plugin.Version));
}
- Logger.LogInformation("Plugins: {plugins}", pluginBuilder.ToString());
+ Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString());
}
DiscoverTypes();
@@ -625,11 +618,34 @@ namespace Emby.Server.Implementations
var host = new WebHostBuilder()
.UseKestrel(options =>
{
- options.ListenAnyIP(HttpPort);
+ var addresses = ServerConfigurationManager
+ .Configuration
+ .LocalNetworkAddresses
+ .Select(NormalizeConfiguredLocalAddress)
+ .Where(i => i != null)
+ .ToList();
+ if (addresses.Any())
+ {
+ foreach (var address in addresses)
+ {
+ Logger.LogInformation("Kestrel listening on {ipaddr}", address);
+ options.Listen(address, HttpPort);
- if (EnableHttps && Certificate != null)
+ if (EnableHttps && Certificate != null)
+ {
+ options.Listen(address, HttpsPort, listenOptions => listenOptions.UseHttps(Certificate));
+ }
+ }
+ }
+ else
{
- options.ListenAnyIP(HttpsPort, listenOptions => { listenOptions.UseHttps(Certificate); });
+ Logger.LogInformation("Kestrel listening on all interfaces");
+ options.ListenAnyIP(HttpPort);
+
+ if (EnableHttps && Certificate != null)
+ {
+ options.ListenAnyIP(HttpsPort, listenOptions => listenOptions.UseHttps(Certificate));
+ }
}
})
.UseContentRoot(contentRoot)
@@ -643,13 +659,22 @@ namespace Emby.Server.Implementations
app.UseWebSockets();
app.UseResponseCompression();
+
// TODO app.UseMiddleware();
app.Use(ExecuteWebsocketHandlerAsync);
app.Use(ExecuteHttpHandlerAsync);
})
.Build();
- await host.StartAsync().ConfigureAwait(false);
+ try
+ {
+ await host.StartAsync().ConfigureAwait(false);
+ }
+ catch
+ {
+ Logger.LogError("Kestrel failed to start! This is most likely due to an invalid address or port bind - correct your bind configuration in system.xml and try again.");
+ throw;
+ }
}
private async Task ExecuteWebsocketHandlerAsync(HttpContext context, Func next)
@@ -676,11 +701,9 @@ namespace Emby.Server.Implementations
var localPath = context.Request.Path.ToString();
var req = new WebSocketSharpRequest(request, response, request.Path, Logger);
- await HttpServer.RequestHandler(req, request.GetDisplayUrl(), request.Host.ToString(), localPath, CancellationToken.None).ConfigureAwait(false);
+ await HttpServer.RequestHandler(req, request.GetDisplayUrl(), request.Host.ToString(), localPath, context.RequestAborted).ConfigureAwait(false);
}
- public static IStreamHelper StreamHelper { get; set; }
-
///
/// Registers resources that classes will depend on
///
@@ -724,8 +747,7 @@ namespace Emby.Server.Implementations
ProcessFactory = new ProcessFactory();
serviceCollection.AddSingleton(ProcessFactory);
- ApplicationHost.StreamHelper = new StreamHelper();
- serviceCollection.AddSingleton(StreamHelper);
+ serviceCollection.AddSingleton(typeof(IStreamHelper), typeof(StreamHelper));
serviceCollection.AddSingleton(typeof(ICryptoProvider), typeof(CryptographyProvider));
@@ -734,18 +756,16 @@ namespace Emby.Server.Implementations
serviceCollection.AddSingleton(typeof(IInstallationManager), typeof(InstallationManager));
- ZipClient = new ZipClient();
- serviceCollection.AddSingleton(ZipClient);
+ serviceCollection.AddSingleton(typeof(IZipClient), typeof(ZipClient));
- HttpResultFactory = new HttpResultFactory(LoggerFactory, FileSystemManager, JsonSerializer, StreamHelper);
- serviceCollection.AddSingleton(HttpResultFactory);
+ serviceCollection.AddSingleton(typeof(IHttpResultFactory), typeof(HttpResultFactory));
serviceCollection.AddSingleton(this);
serviceCollection.AddSingleton(ApplicationPaths);
serviceCollection.AddSingleton(ServerConfigurationManager);
- LocalizationManager = new LocalizationManager(ServerConfigurationManager, JsonSerializer, LoggerFactory);
+ LocalizationManager = new LocalizationManager(ServerConfigurationManager, JsonSerializer, LoggerFactory.CreateLogger());
await LocalizationManager.LoadAll().ConfigureAwait(false);
serviceCollection.AddSingleton(LocalizationManager);
@@ -754,18 +774,22 @@ namespace Emby.Server.Implementations
UserDataManager = new UserDataManager(LoggerFactory, ServerConfigurationManager, () => UserManager);
serviceCollection.AddSingleton(UserDataManager);
- var displayPreferencesRepo = new SqliteDisplayPreferencesRepository(LoggerFactory, JsonSerializer, ApplicationPaths, FileSystemManager);
- serviceCollection.AddSingleton(displayPreferencesRepo);
+ _displayPreferencesRepository = new SqliteDisplayPreferencesRepository(
+ LoggerFactory.CreateLogger(),
+ ApplicationPaths,
+ FileSystemManager);
+ serviceCollection.AddSingleton(_displayPreferencesRepository);
- ItemRepository = new SqliteItemRepository(ServerConfigurationManager, this, JsonSerializer, LoggerFactory, LocalizationManager);
+ ItemRepository = new SqliteItemRepository(ServerConfigurationManager, this, LoggerFactory.CreateLogger(), LocalizationManager);
serviceCollection.AddSingleton(ItemRepository);
AuthenticationRepository = GetAuthenticationRepository();
serviceCollection.AddSingleton(AuthenticationRepository);
- UserRepository = GetUserRepository();
+ _userRepository = GetUserRepository();
+
+ UserManager = new UserManager(LoggerFactory.CreateLogger(), _userRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager);
- UserManager = new UserManager(LoggerFactory, ServerConfigurationManager, UserRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager);
serviceCollection.AddSingleton(UserManager);
LibraryManager = new LibraryManager(this, LoggerFactory, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, () => UserViewManager);
@@ -785,7 +809,7 @@ namespace Emby.Server.Implementations
HttpServer = new HttpListenerHost(
this,
- LoggerFactory,
+ LoggerFactory.CreateLogger(),
ServerConfigurationManager,
_configuration,
NetworkManager,
@@ -798,7 +822,7 @@ namespace Emby.Server.Implementations
serviceCollection.AddSingleton(HttpServer);
- ImageProcessor = GetImageProcessor();
+ ImageProcessor = new ImageProcessor(LoggerFactory.CreateLogger(), ServerConfigurationManager.ApplicationPaths, FileSystemManager, ImageEncoder, () => LibraryManager, () => MediaEncoder);
serviceCollection.AddSingleton(ImageProcessor);
TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager, ServerConfigurationManager);
@@ -831,8 +855,7 @@ namespace Emby.Server.Implementations
CollectionManager = new CollectionManager(LibraryManager, ApplicationPaths, LocalizationManager, FileSystemManager, LibraryMonitor, LoggerFactory, ProviderManager);
serviceCollection.AddSingleton(CollectionManager);
- PlaylistManager = new PlaylistManager(LibraryManager, FileSystemManager, LibraryMonitor, LoggerFactory, UserManager, ProviderManager);
- serviceCollection.AddSingleton(PlaylistManager);
+ serviceCollection.AddSingleton(typeof(IPlaylistManager), typeof(PlaylistManager));
LiveTvManager = new LiveTvManager(this, ServerConfigurationManager, LoggerFactory, ItemRepository, ImageProcessor, UserDataManager, DtoService, UserManager, LibraryManager, TaskManager, LocalizationManager, JsonSerializer, FileSystemManager, () => ChannelManager);
serviceCollection.AddSingleton(LiveTvManager);
@@ -873,7 +896,7 @@ namespace Emby.Server.Implementations
serviceCollection.AddSingleton(authContext);
serviceCollection.AddSingleton(new SessionContext(UserManager, authContext, SessionManager));
- AuthService = new AuthService(UserManager, authContext, ServerConfigurationManager, SessionManager, NetworkManager);
+ AuthService = new AuthService(authContext, ServerConfigurationManager, SessionManager, NetworkManager);
serviceCollection.AddSingleton(AuthService);
SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LoggerFactory, ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory);
@@ -881,7 +904,7 @@ namespace Emby.Server.Implementations
serviceCollection.AddSingleton(typeof(IResourceFileManager), typeof(ResourceFileManager));
- displayPreferencesRepo.Initialize();
+ _displayPreferencesRepository.Initialize();
var userDataRepo = new SqliteUserDataRepository(LoggerFactory, ApplicationPaths);
@@ -950,18 +973,15 @@ namespace Emby.Server.Implementations
}
}
- private IImageProcessor GetImageProcessor()
- {
- return new ImageProcessor(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager, ImageEncoder, () => LibraryManager, () => MediaEncoder);
- }
-
///
/// Gets the user repository.
///
- /// Task{IUserRepository}.
- private IUserRepository GetUserRepository()
+ /// .
+ private SqliteUserRepository GetUserRepository()
{
- var repo = new SqliteUserRepository(LoggerFactory, ApplicationPaths, JsonSerializer);
+ var repo = new SqliteUserRepository(
+ LoggerFactory.CreateLogger(),
+ ApplicationPaths);
repo.Initialize();
@@ -1022,9 +1042,11 @@ namespace Emby.Server.Implementations
.Select(x => Assembly.LoadFrom(x))
.SelectMany(x => x.ExportedTypes)
.Where(x => x.IsClass && !x.IsAbstract && !x.IsInterface && !x.IsGenericType)
- .ToList();
+ .ToArray();
- types.AddRange(types);
+ int oldLen = _allConcreteTypes.Length;
+ Array.Resize(ref _allConcreteTypes, oldLen + types.Length);
+ types.CopyTo(_allConcreteTypes, oldLen);
var plugins = types.Where(x => x.IsAssignableFrom(typeof(IPlugin)))
.Select(CreateInstanceSafe)
@@ -1034,8 +1056,8 @@ namespace Emby.Server.Implementations
.Where(x => x != null)
.ToArray();
- int oldLen = _plugins.Length;
- Array.Resize(ref _plugins, _plugins.Length + plugins.Length);
+ oldLen = _plugins.Length;
+ Array.Resize(ref _plugins, oldLen + plugins.Length);
plugins.CopyTo(_plugins, oldLen);
var entries = types.Where(x => x.IsAssignableFrom(typeof(IServerEntryPoint)))
@@ -1044,8 +1066,8 @@ namespace Emby.Server.Implementations
.Cast()
.ToList();
- await Task.WhenAll(StartEntryPoints(entries, true));
- await Task.WhenAll(StartEntryPoints(entries, false));
+ await Task.WhenAll(StartEntryPoints(entries, true)).ConfigureAwait(false);
+ await Task.WhenAll(StartEntryPoints(entries, false)).ConfigureAwait(false);
}
///
@@ -1084,7 +1106,7 @@ namespace Emby.Server.Implementations
GetExports(),
GetExports());
- ImageProcessor.AddParts(GetExports());
+ ImageProcessor.ImageEnhancers = GetExports();
LiveTvManager.AddParts(GetExports(), GetExports(), GetExports());
@@ -1152,7 +1174,7 @@ namespace Emby.Server.Implementations
{
Logger.LogInformation("Loading assemblies");
- AllConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
+ _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
}
private IEnumerable GetTypes(IEnumerable assemblies)
@@ -1208,25 +1230,11 @@ namespace Emby.Server.Implementations
private CertificateInfo GetCertificateInfo(bool generateCertificate)
{
- if (!string.IsNullOrWhiteSpace(ServerConfigurationManager.Configuration.CertificatePath))
- {
- // Custom cert
- return new CertificateInfo
- {
- Path = ServerConfigurationManager.Configuration.CertificatePath,
- Password = ServerConfigurationManager.Configuration.CertificatePassword
- };
- }
-
- // Generate self-signed cert
- var certHost = GetHostnameFromExternalDns(ServerConfigurationManager.Configuration.WanDdns);
- var certPath = Path.Combine(ServerConfigurationManager.ApplicationPaths.ProgramDataPath, "ssl", "cert_" + (certHost + "2").GetMD5().ToString("N") + ".pfx");
- const string Password = "embycert";
-
+ // Custom cert
return new CertificateInfo
{
- Path = certPath,
- Password = Password
+ Path = ServerConfigurationManager.Configuration.CertificatePath,
+ Password = ServerConfigurationManager.Configuration.CertificatePassword
};
}
@@ -1413,17 +1421,6 @@ namespace Emby.Server.Implementations
{
var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
- string wanAddress;
-
- if (string.IsNullOrEmpty(ServerConfigurationManager.Configuration.WanDdns))
- {
- wanAddress = await GetWanApiUrlFromExternal(cancellationToken).ConfigureAwait(false);
- }
- else
- {
- wanAddress = GetWanApiUrl(ServerConfigurationManager.Configuration.WanDdns);
- }
-
return new SystemInfo
{
HasPendingRestart = HasPendingRestart,
@@ -1445,7 +1442,6 @@ namespace Emby.Server.Implementations
OperatingSystemDisplayName = OperatingSystem.Name,
CanSelfRestart = CanSelfRestart,
CanLaunchWebBrowser = CanLaunchWebBrowser,
- WanAddress = wanAddress,
HasUpdateAvailable = HasUpdateAvailable,
TranscodingTempPath = ApplicationPaths.TranscodingTempPath,
ServerName = FriendlyName,
@@ -1458,37 +1454,21 @@ namespace Emby.Server.Implementations
};
}
- public WakeOnLanInfo[] GetWakeOnLanInfo()
- {
- return NetworkManager.GetMacAddresses()
- .Select(i => new WakeOnLanInfo
- {
- MacAddress = i
- })
- .ToArray();
- }
+ public IEnumerable GetWakeOnLanInfo()
+ => NetworkManager.GetMacAddresses()
+ .Select(i => new WakeOnLanInfo(i))
+ .ToList();
public async Task GetPublicSystemInfo(CancellationToken cancellationToken)
{
var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
- string wanAddress;
-
- if (string.IsNullOrEmpty(ServerConfigurationManager.Configuration.WanDdns))
- {
- wanAddress = await GetWanApiUrlFromExternal(cancellationToken).ConfigureAwait(false);
- }
- else
- {
- wanAddress = GetWanApiUrl(ServerConfigurationManager.Configuration.WanDdns);
- }
return new PublicSystemInfo
{
Version = ApplicationVersion,
ProductName = ApplicationProductName,
Id = SystemId,
OperatingSystem = OperatingSystem.Id.ToString(),
- WanAddress = wanAddress,
ServerName = FriendlyName,
LocalAddress = localAddress
};
@@ -1520,33 +1500,6 @@ namespace Emby.Server.Implementations
return null;
}
- public async Task GetWanApiUrlFromExternal(CancellationToken cancellationToken)
- {
- const string Url = "http://ipv4.icanhazip.com";
- try
- {
- using (var response = await HttpClient.Get(new HttpRequestOptions
- {
- Url = Url,
- LogErrorResponseBody = false,
- LogErrors = false,
- LogRequest = false,
- BufferContent = false,
- CancellationToken = cancellationToken
- }).ConfigureAwait(false))
- {
- string res = await response.ReadToEndAsync().ConfigureAwait(false);
- return GetWanApiUrl(res.Trim());
- }
- }
- catch (Exception ex)
- {
- Logger.LogError(ex, "Error getting WAN Ip address information");
- }
-
- return null;
- }
-
///
/// Removes the scope id from IPv6 addresses.
///
@@ -1589,32 +1542,6 @@ namespace Emby.Server.Implementations
HttpPort.ToString(CultureInfo.InvariantCulture));
}
- public string GetWanApiUrl(IPAddress ipAddress)
- {
- if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
- {
- var str = RemoveScopeId(ipAddress.ToString());
-
- return GetWanApiUrl("[" + str + "]");
- }
-
- return GetWanApiUrl(ipAddress.ToString());
- }
-
- public string GetWanApiUrl(string host)
- {
- if (EnableHttps)
- {
- return string.Format("https://{0}:{1}",
- host,
- ServerConfigurationManager.Configuration.PublicHttpsPort.ToString(CultureInfo.InvariantCulture));
- }
-
- return string.Format("http://{0}:{1}",
- host,
- ServerConfigurationManager.Configuration.PublicPort.ToString(CultureInfo.InvariantCulture));
- }
-
public Task> GetLocalIpAddresses(CancellationToken cancellationToken)
{
return GetLocalIpAddressesInternal(true, 0, cancellationToken);
@@ -1682,8 +1609,8 @@ namespace Emby.Server.Implementations
private async Task IsIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken)
{
- if (address.Equals(IPAddress.Loopback) ||
- address.Equals(IPAddress.IPv6Loopback))
+ if (address.Equals(IPAddress.Loopback)
+ || address.Equals(IPAddress.IPv6Loopback))
{
return true;
}
@@ -1696,12 +1623,6 @@ namespace Emby.Server.Implementations
return cachedResult;
}
-#if DEBUG
- const bool LogPing = true;
-#else
- const bool LogPing = false;
-#endif
-
try
{
using (var response = await HttpClient.SendAsync(
@@ -1709,8 +1630,6 @@ namespace Emby.Server.Implementations
{
Url = apiUrl,
LogErrorResponseBody = false,
- LogErrors = LogPing,
- LogRequest = LogPing,
BufferContent = false,
CancellationToken = cancellationToken
}, HttpMethod.Post).ConfigureAwait(false))
@@ -1911,10 +1830,12 @@ namespace Emby.Server.Implementations
}
}
- UserRepository.Dispose();
+ _userRepository?.Dispose();
+ _displayPreferencesRepository.Dispose();
}
- UserRepository = null;
+ _userRepository = null;
+ _displayPreferencesRepository = null;
_disposed = true;
}
diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs
index e9961e8bd7..8e5f5b5617 100644
--- a/Emby.Server.Implementations/Channels/ChannelManager.cs
+++ b/Emby.Server.Implementations/Channels/ChannelManager.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
@@ -206,7 +207,7 @@ namespace Emby.Server.Implementations.Channels
try
{
- return GetChannelProvider(i).IsEnabledFor(user.Id.ToString("N"));
+ return GetChannelProvider(i).IsEnabledFor(user.Id.ToString("N", CultureInfo.InvariantCulture));
}
catch
{
@@ -511,7 +512,7 @@ namespace Emby.Server.Implementations.Channels
IncludeItemTypes = new[] { typeof(Channel).Name },
OrderBy = new ValueTuple[] { new ValueTuple(ItemSortBy.SortName, SortOrder.Ascending) }
- }).Select(i => GetChannelFeatures(i.ToString("N"))).ToArray();
+ }).Select(i => GetChannelFeatures(i.ToString("N", CultureInfo.InvariantCulture))).ToArray();
}
public ChannelFeatures GetChannelFeatures(string id)
@@ -552,7 +553,7 @@ namespace Emby.Server.Implementations.Channels
SupportsSortOrderToggle = features.SupportsSortOrderToggle,
SupportsLatestMedia = supportsLatest,
Name = channel.Name,
- Id = channel.Id.ToString("N"),
+ Id = channel.Id.ToString("N", CultureInfo.InvariantCulture),
SupportsContentDownloading = features.SupportsContentDownloading,
AutoRefreshLevels = features.AutoRefreshLevels
};
@@ -740,7 +741,7 @@ namespace Emby.Server.Implementations.Channels
bool sortDescending,
CancellationToken cancellationToken)
{
- var userId = user == null ? null : user.Id.ToString("N");
+ var userId = user == null ? null : user.Id.ToString("N", CultureInfo.InvariantCulture);
var cacheLength = CacheLength;
var cachePath = GetChannelDataCachePath(channel, userId, externalFolderId, sortField, sortDescending);
@@ -836,7 +837,7 @@ namespace Emby.Server.Implementations.Channels
ChannelItemSortField? sortField,
bool sortDescending)
{
- var channelId = GetInternalChannelId(channel.Name).ToString("N");
+ var channelId = GetInternalChannelId(channel.Name).ToString("N", CultureInfo.InvariantCulture);
var userCacheKey = string.Empty;
@@ -846,10 +847,10 @@ namespace Emby.Server.Implementations.Channels
userCacheKey = hasCacheKey.GetCacheKey(userId) ?? string.Empty;
}
- var filename = string.IsNullOrEmpty(externalFolderId) ? "root" : externalFolderId.GetMD5().ToString("N");
+ var filename = string.IsNullOrEmpty(externalFolderId) ? "root" : externalFolderId.GetMD5().ToString("N", CultureInfo.InvariantCulture);
filename += userCacheKey;
- var version = ((channel.DataVersion ?? string.Empty) + "2").GetMD5().ToString("N");
+ var version = ((channel.DataVersion ?? string.Empty) + "2").GetMD5().ToString("N", CultureInfo.InvariantCulture);
if (sortField.HasValue)
{
@@ -860,7 +861,7 @@ namespace Emby.Server.Implementations.Channels
filename += "-sortDescending";
}
- filename = filename.GetMD5().ToString("N");
+ filename = filename.GetMD5().ToString("N", CultureInfo.InvariantCulture);
return Path.Combine(_config.ApplicationPaths.CachePath,
"channels",
diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs
index 2b99e0ddfc..bb5057b1c2 100644
--- a/Emby.Server.Implementations/Collections/CollectionManager.cs
+++ b/Emby.Server.Implementations/Collections/CollectionManager.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
@@ -182,7 +183,7 @@ namespace Emby.Server.Implementations.Collections
public void AddToCollection(Guid collectionId, IEnumerable ids)
{
- AddToCollection(collectionId, ids.Select(i => i.ToString("N")), true, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)));
+ AddToCollection(collectionId, ids.Select(i => i.ToString("N", CultureInfo.InvariantCulture)), true, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)));
}
private void AddToCollection(Guid collectionId, IEnumerable ids, bool fireEvent, MetadataRefreshOptions refreshOptions)
diff --git a/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs b/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs
index c4fa68cac4..c7f92b80b6 100644
--- a/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs
+++ b/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs
@@ -66,7 +66,7 @@ namespace Emby.Server.Implementations.Configuration
{
base.AddParts(factories);
- UpdateTranscodingTempPath();
+ UpdateTranscodePath();
}
///
@@ -87,13 +87,13 @@ namespace Emby.Server.Implementations.Configuration
///
/// Updates the transcoding temporary path.
///
- private void UpdateTranscodingTempPath()
+ private void UpdateTranscodePath()
{
var encodingConfig = this.GetConfiguration("encoding");
((ServerApplicationPaths)ApplicationPaths).TranscodingTempPath = string.IsNullOrEmpty(encodingConfig.TranscodingTempPath) ?
null :
- Path.Combine(encodingConfig.TranscodingTempPath, "transcoding-temp");
+ Path.Combine(encodingConfig.TranscodingTempPath, "transcodes");
}
protected override void OnNamedConfigurationUpdated(string key, object configuration)
@@ -102,7 +102,7 @@ namespace Emby.Server.Implementations.Configuration
if (string.Equals(key, "encoding", StringComparison.OrdinalIgnoreCase))
{
- UpdateTranscodingTempPath();
+ UpdateTranscodePath();
}
}
diff --git a/Emby.Server.Implementations/ConfigurationOptions.cs b/Emby.Server.Implementations/ConfigurationOptions.cs
index 9bc60972a1..62408ee703 100644
--- a/Emby.Server.Implementations/ConfigurationOptions.cs
+++ b/Emby.Server.Implementations/ConfigurationOptions.cs
@@ -6,8 +6,8 @@ namespace Emby.Server.Implementations
{
public static readonly Dictionary Configuration = new Dictionary
{
- {"HttpListenerHost:DefaultRedirectPath", "web/index.html"},
- {"MusicBrainz:BaseUrl", "https://www.musicbrainz.org"}
+ { "HttpListenerHost:DefaultRedirectPath", "web/index.html" },
+ { "MusicBrainz:BaseUrl", "https://www.musicbrainz.org" }
};
}
}
diff --git a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs
index 6d7193ce20..23b77e2687 100644
--- a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs
+++ b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs
@@ -1,14 +1,12 @@
using System;
using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
using System.Security.Cryptography;
-using System.Text;
using MediaBrowser.Model.Cryptography;
+using static MediaBrowser.Common.Cryptography.Constants;
namespace Emby.Server.Implementations.Cryptography
{
- public class CryptographyProvider : ICryptoProvider
+ public class CryptographyProvider : ICryptoProvider, IDisposable
{
private static readonly HashSet _supportedHashMethods = new HashSet()
{
@@ -28,59 +26,28 @@ namespace Emby.Server.Implementations.Cryptography
"System.Security.Cryptography.SHA512"
};
- public string DefaultHashMethod => "PBKDF2";
-
private RandomNumberGenerator _randomNumberGenerator;
- private const int _defaultIterations = 1000;
+ private bool _disposed = false;
public CryptographyProvider()
{
- //FIXME: When we get DotNet Standard 2.1 we need to revisit how we do the crypto
- //Currently supported hash methods from https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.cryptoconfig?view=netcore-2.1
- //there might be a better way to autogenerate this list as dotnet updates, but I couldn't find one
- //Please note the default method of PBKDF2 is not included, it cannot be used to generate hashes cleanly as it is actually a pbkdf with sha1
+ // FIXME: When we get DotNet Standard 2.1 we need to revisit how we do the crypto
+ // Currently supported hash methods from https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.cryptoconfig?view=netcore-2.1
+ // there might be a better way to autogenerate this list as dotnet updates, but I couldn't find one
+ // Please note the default method of PBKDF2 is not included, it cannot be used to generate hashes cleanly as it is actually a pbkdf with sha1
_randomNumberGenerator = RandomNumberGenerator.Create();
}
- public Guid GetMD5(string str)
- {
- return new Guid(ComputeMD5(Encoding.Unicode.GetBytes(str)));
- }
-
- public byte[] ComputeSHA1(byte[] bytes)
- {
- using (var provider = SHA1.Create())
- {
- return provider.ComputeHash(bytes);
- }
- }
-
- public byte[] ComputeMD5(Stream str)
- {
- using (var provider = MD5.Create())
- {
- return provider.ComputeHash(str);
- }
- }
-
- public byte[] ComputeMD5(byte[] bytes)
- {
- using (var provider = MD5.Create())
- {
- return provider.ComputeHash(bytes);
- }
- }
+ public string DefaultHashMethod => "PBKDF2";
public IEnumerable GetSupportedHashMethods()
- {
- return _supportedHashMethods;
- }
+ => _supportedHashMethods;
private byte[] PBKDF2(string method, byte[] bytes, byte[] salt, int iterations)
{
- //downgrading for now as we need this library to be dotnetstandard compliant
- //with this downgrade we'll add a check to make sure we're on the downgrade method at the moment
+ // downgrading for now as we need this library to be dotnetstandard compliant
+ // with this downgrade we'll add a check to make sure we're on the downgrade method at the moment
if (method == DefaultHashMethod)
{
using (var r = new Rfc2898DeriveBytes(bytes, salt, iterations))
@@ -93,20 +60,16 @@ namespace Emby.Server.Implementations.Cryptography
}
public byte[] ComputeHash(string hashMethod, byte[] bytes)
- {
- return ComputeHash(hashMethod, bytes, Array.Empty());
- }
+ => ComputeHash(hashMethod, bytes, Array.Empty());
public byte[] ComputeHashWithDefaultMethod(byte[] bytes)
- {
- return ComputeHash(DefaultHashMethod, bytes);
- }
+ => ComputeHash(DefaultHashMethod, bytes);
public byte[] ComputeHash(string hashMethod, byte[] bytes, byte[] salt)
{
if (hashMethod == DefaultHashMethod)
{
- return PBKDF2(hashMethod, bytes, salt, _defaultIterations);
+ return PBKDF2(hashMethod, bytes, salt, DefaultIterations);
}
else if (_supportedHashMethods.Contains(hashMethod))
{
@@ -125,44 +88,46 @@ namespace Emby.Server.Implementations.Cryptography
}
}
}
- else
- {
- throw new CryptographicException($"Requested hash method is not supported: {hashMethod}");
- }
+
+ throw new CryptographicException($"Requested hash method is not supported: {hashMethod}");
+
}
public byte[] ComputeHashWithDefaultMethod(byte[] bytes, byte[] salt)
+ => PBKDF2(DefaultHashMethod, bytes, salt, DefaultIterations);
+
+ public byte[] GenerateSalt()
+ => GenerateSalt(DefaultSaltLength);
+
+ public byte[] GenerateSalt(int length)
+ {
+ byte[] salt = new byte[length];
+ _randomNumberGenerator.GetBytes(salt);
+ return salt;
+ }
+
+ ///
+ public void Dispose()
{
- return PBKDF2(DefaultHashMethod, bytes, salt, _defaultIterations);
+ Dispose(true);
+ GC.SuppressFinalize(this);
}
- public byte[] ComputeHash(PasswordHash hash)
+ protected virtual void Dispose(bool disposing)
{
- int iterations = _defaultIterations;
- if (!hash.Parameters.ContainsKey("iterations"))
+ if (_disposed)
{
- hash.Parameters.Add("iterations", _defaultIterations.ToString(CultureInfo.InvariantCulture));
+ return;
}
- else
+
+ if (disposing)
{
- try
- {
- iterations = int.Parse(hash.Parameters["iterations"]);
- }
- catch (Exception e)
- {
- throw new InvalidDataException($"Couldn't successfully parse iterations value from string: {hash.Parameters["iterations"]}", e);
- }
+ _randomNumberGenerator.Dispose();
}
- return PBKDF2(hash.Id, hash.HashBytes, hash.SaltBytes, iterations);
- }
+ _randomNumberGenerator = null;
- public byte[] GenerateSalt()
- {
- byte[] salt = new byte[64];
- _randomNumberGenerator.GetBytes(salt);
- return salt;
+ _disposed = true;
}
}
}
diff --git a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs
index 010ad63846..4e392f6c9c 100644
--- a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs
+++ b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs
@@ -53,10 +53,10 @@ namespace Emby.Server.Implementations.Data
protected virtual int? CacheSize => null;
///
- /// Gets the journal mode.
+ /// Gets the journal mode.
///
/// The journal mode.
- protected virtual string JournalMode => "WAL";
+ protected virtual string JournalMode => "TRUNCATE";
///
/// Gets the page size.
@@ -124,7 +124,7 @@ namespace Emby.Server.Implementations.Data
}
WriteConnection.Execute("PRAGMA temp_store=" + (int)TempStore);
-
+
// Configuration and pragmas can affect VACUUM so it needs to be last.
WriteConnection.Execute("VACUUM");
@@ -218,7 +218,7 @@ namespace Emby.Server.Implementations.Data
WriteLock.Wait();
try
{
- WriteConnection.Dispose();
+ WriteConnection?.Dispose();
}
finally
{
diff --git a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs
index 01ef9851dc..2cd4d65b3a 100644
--- a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs
+++ b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs
@@ -1,44 +1,45 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
+using System.Text.Json;
using System.Threading;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
+using MediaBrowser.Common.Json;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
using SQLitePCL.pretty;
namespace Emby.Server.Implementations.Data
{
///
- /// Class SQLiteDisplayPreferencesRepository
+ /// Class SQLiteDisplayPreferencesRepository.
///
public class SqliteDisplayPreferencesRepository : BaseSqliteRepository, IDisplayPreferencesRepository
{
private readonly IFileSystem _fileSystem;
- public SqliteDisplayPreferencesRepository(ILoggerFactory loggerFactory, IJsonSerializer jsonSerializer, IApplicationPaths appPaths, IFileSystem fileSystem)
- : base(loggerFactory.CreateLogger(nameof(SqliteDisplayPreferencesRepository)))
+ private readonly JsonSerializerOptions _jsonOptions;
+
+ public SqliteDisplayPreferencesRepository(ILogger logger, IApplicationPaths appPaths, IFileSystem fileSystem)
+ : base(logger)
{
- _jsonSerializer = jsonSerializer;
_fileSystem = fileSystem;
+
+ _jsonOptions = JsonDefaults.GetOptions();
+
DbFilePath = Path.Combine(appPaths.DataPath, "displaypreferences.db");
}
///
- /// Gets the name of the repository
+ /// Gets the name of the repository.
///
/// The name.
public string Name => "SQLite";
- ///
- /// The _json serializer
- ///
- private readonly IJsonSerializer _jsonSerializer;
-
public void Initialize()
{
try
@@ -61,14 +62,14 @@ namespace Emby.Server.Implementations.Data
/// Task.
private void InitializeInternal()
{
- using (var connection = GetConnection())
+ string[] queries =
{
- string[] queries = {
-
- "create table if not exists userdisplaypreferences (id GUID NOT NULL, userId GUID NOT NULL, client text NOT NULL, data BLOB NOT NULL)",
- "create unique index if not exists userdisplaypreferencesindex on userdisplaypreferences (id, userId, client)"
- };
+ "create table if not exists userdisplaypreferences (id GUID NOT NULL, userId GUID NOT NULL, client text NOT NULL, data BLOB NOT NULL)",
+ "create unique index if not exists userdisplaypreferencesindex on userdisplaypreferences (id, userId, client)"
+ };
+ using (var connection = GetConnection())
+ {
connection.RunQueries(queries);
}
}
@@ -80,7 +81,6 @@ namespace Emby.Server.Implementations.Data
/// The user id.
/// The client.
/// The cancellation token.
- /// Task.
/// item
public void SaveDisplayPreferences(DisplayPreferences displayPreferences, Guid userId, string client, CancellationToken cancellationToken)
{
@@ -98,16 +98,15 @@ namespace Emby.Server.Implementations.Data
using (var connection = GetConnection())
{
- connection.RunInTransaction(db =>
- {
- SaveDisplayPreferences(displayPreferences, userId, client, db);
- }, TransactionMode);
+ connection.RunInTransaction(
+ db => SaveDisplayPreferences(displayPreferences, userId, client, db),
+ TransactionMode);
}
}
private void SaveDisplayPreferences(DisplayPreferences displayPreferences, Guid userId, string client, IDatabaseConnection connection)
{
- var serialized = _jsonSerializer.SerializeToBytes(displayPreferences);
+ var serialized = JsonSerializer.SerializeToUtf8Bytes(displayPreferences, _jsonOptions);
using (var statement = connection.PrepareStatement("replace into userdisplaypreferences (id, userid, client, data) values (@id, @userId, @client, @data)"))
{
@@ -126,7 +125,6 @@ namespace Emby.Server.Implementations.Data
/// The display preferences.
/// The user id.
/// The cancellation token.
- /// Task.
/// item
public void SaveAllDisplayPreferences(IEnumerable displayPreferences, Guid userId, CancellationToken cancellationToken)
{
@@ -139,13 +137,15 @@ namespace Emby.Server.Implementations.Data
using (var connection = GetConnection())
{
- connection.RunInTransaction(db =>
- {
- foreach (var displayPreference in displayPreferences)
+ connection.RunInTransaction(
+ db =>
{
- SaveDisplayPreferences(displayPreference, userId, displayPreference.Client, db);
- }
- }, TransactionMode);
+ foreach (var displayPreference in displayPreferences)
+ {
+ SaveDisplayPreferences(displayPreference, userId, displayPreference.Client, db);
+ }
+ },
+ TransactionMode);
}
}
@@ -179,12 +179,12 @@ namespace Emby.Server.Implementations.Data
return Get(row);
}
}
-
- return new DisplayPreferences
- {
- Id = guidId.ToString("N")
- };
}
+
+ return new DisplayPreferences
+ {
+ Id = guidId.ToString("N", CultureInfo.InvariantCulture)
+ };
}
///
@@ -198,15 +198,13 @@ namespace Emby.Server.Implementations.Data
var list = new List();
using (var connection = GetConnection(true))
+ using (var statement = connection.PrepareStatement("select data from userdisplaypreferences where userId=@userId"))
{
- using (var statement = connection.PrepareStatement("select data from userdisplaypreferences where userId=@userId"))
- {
- statement.TryBind("@userId", userId.ToGuidBlob());
+ statement.TryBind("@userId", userId.ToGuidBlob());
- foreach (var row in statement.ExecuteQuery())
- {
- list.Add(Get(row));
- }
+ foreach (var row in statement.ExecuteQuery())
+ {
+ list.Add(Get(row));
}
}
@@ -214,22 +212,12 @@ namespace Emby.Server.Implementations.Data
}
private DisplayPreferences Get(IReadOnlyList row)
- {
- using (var stream = new MemoryStream(row[0].ToBlob()))
- {
- stream.Position = 0;
- return _jsonSerializer.DeserializeFromStream(stream);
- }
- }
+ => JsonSerializer.Deserialize(row[0].ToBlob(), _jsonOptions);
public void SaveDisplayPreferences(DisplayPreferences displayPreferences, string userId, string client, CancellationToken cancellationToken)
- {
- SaveDisplayPreferences(displayPreferences, new Guid(userId), client, cancellationToken);
- }
+ => SaveDisplayPreferences(displayPreferences, new Guid(userId), client, cancellationToken);
public DisplayPreferences GetDisplayPreferences(string displayPreferencesId, string userId, string client)
- {
- return GetDisplayPreferences(displayPreferencesId, new Guid(userId), client);
- }
+ => GetDisplayPreferences(displayPreferencesId, new Guid(userId), client);
}
}
diff --git a/Emby.Server.Implementations/Data/SqliteExtensions.cs b/Emby.Server.Implementations/Data/SqliteExtensions.cs
index c0f27b25aa..e7c394b548 100644
--- a/Emby.Server.Implementations/Data/SqliteExtensions.cs
+++ b/Emby.Server.Implementations/Data/SqliteExtensions.cs
@@ -18,10 +18,6 @@ namespace Emby.Server.Implementations.Data
connection.RunInTransaction(conn =>
{
- //foreach (var query in queries)
- //{
- // conn.Execute(query);
- //}
conn.ExecuteAll(string.Join(";", queries));
});
}
diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs
index 1cefcec7ca..31a661c5d9 100644
--- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs
+++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs
@@ -5,8 +5,11 @@ using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
+using System.Text.Json;
+using System.Text.Json.Serialization;
using System.Threading;
using Emby.Server.Implementations.Playlists;
+using MediaBrowser.Common.Json;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Configuration;
@@ -38,14 +41,6 @@ namespace Emby.Server.Implementations.Data
{
private const string ChaptersTableName = "Chapters2";
- private readonly TypeMapper _typeMapper;
-
- ///
- /// Gets the json serializer.
- ///
- /// The json serializer.
- private readonly IJsonSerializer _jsonSerializer;
-
///
/// The _app paths
///
@@ -53,33 +48,31 @@ namespace Emby.Server.Implementations.Data
private readonly IServerApplicationHost _appHost;
private readonly ILocalizationManager _localization;
+ private readonly TypeMapper _typeMapper;
+ private readonly JsonSerializerOptions _jsonOptions;
+
///
/// Initializes a new instance of the class.
///
public SqliteItemRepository(
IServerConfigurationManager config,
IServerApplicationHost appHost,
- IJsonSerializer jsonSerializer,
- ILoggerFactory loggerFactory,
+ ILogger logger,
ILocalizationManager localization)
- : base(loggerFactory.CreateLogger(nameof(SqliteItemRepository)))
+ : base(logger)
{
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
- if (jsonSerializer == null)
- {
- throw new ArgumentNullException(nameof(jsonSerializer));
- }
-
- _appHost = appHost;
_config = config;
- _jsonSerializer = jsonSerializer;
- _typeMapper = new TypeMapper();
+ _appHost = appHost;
_localization = localization;
+ _typeMapper = new TypeMapper();
+ _jsonOptions = JsonDefaults.GetOptions();
+
DbFilePath = Path.Combine(_config.ApplicationPaths.DataPath, "library.db");
}
@@ -99,35 +92,114 @@ namespace Emby.Server.Implementations.Data
///
public void Initialize(SqliteUserDataRepository userDataRepo, IUserManager userManager)
{
- using (var connection = GetConnection())
- {
- const string createMediaStreamsTableCommand
+ const string CreateMediaStreamsTableCommand
= "create table if not exists mediastreams (ItemId GUID, StreamIndex INT, StreamType TEXT, Codec TEXT, Language TEXT, ChannelLayout TEXT, Profile TEXT, AspectRatio TEXT, Path TEXT, IsInterlaced BIT, BitRate INT NULL, Channels INT NULL, SampleRate INT NULL, IsDefault BIT, IsForced BIT, IsExternal BIT, Height INT NULL, Width INT NULL, AverageFrameRate FLOAT NULL, RealFrameRate FLOAT NULL, Level FLOAT NULL, PixelFormat TEXT, BitDepth INT NULL, IsAnamorphic BIT NULL, RefFrames INT NULL, CodecTag TEXT NULL, Comment TEXT NULL, NalLengthSize TEXT NULL, IsAvc BIT NULL, Title TEXT NULL, TimeBase TEXT NULL, CodecTimeBase TEXT NULL, ColorPrimaries TEXT NULL, ColorSpace TEXT NULL, ColorTransfer TEXT NULL, PRIMARY KEY (ItemId, StreamIndex))";
- string[] queries = {
- "PRAGMA locking_mode=EXCLUSIVE",
+ string[] queries =
+ {
+ "PRAGMA locking_mode=EXCLUSIVE",
- "create table if not exists TypedBaseItems (guid GUID primary key NOT NULL, type TEXT NOT NULL, data BLOB NULL, ParentId GUID NULL, Path TEXT NULL)",
+ "create table if not exists TypedBaseItems (guid GUID primary key NOT NULL, type TEXT NOT NULL, data BLOB NULL, ParentId GUID NULL, Path TEXT NULL)",
- "create table if not exists AncestorIds (ItemId GUID NOT NULL, AncestorId GUID NOT NULL, AncestorIdText TEXT NOT NULL, PRIMARY KEY (ItemId, AncestorId))",
- "create index if not exists idx_AncestorIds1 on AncestorIds(AncestorId)",
- "create index if not exists idx_AncestorIds5 on AncestorIds(AncestorIdText,ItemId)",
+ "create table if not exists AncestorIds (ItemId GUID NOT NULL, AncestorId GUID NOT NULL, AncestorIdText TEXT NOT NULL, PRIMARY KEY (ItemId, AncestorId))",
+ "create index if not exists idx_AncestorIds1 on AncestorIds(AncestorId)",
+ "create index if not exists idx_AncestorIds5 on AncestorIds(AncestorIdText,ItemId)",
- "create table if not exists ItemValues (ItemId GUID NOT NULL, Type INT NOT NULL, Value TEXT NOT NULL, CleanValue TEXT NOT NULL)",
+ "create table if not exists ItemValues (ItemId GUID NOT NULL, Type INT NOT NULL, Value TEXT NOT NULL, CleanValue TEXT NOT NULL)",
- "create table if not exists People (ItemId GUID, Name TEXT NOT NULL, Role TEXT, PersonType TEXT, SortOrder int, ListOrder int)",
+ "create table if not exists People (ItemId GUID, Name TEXT NOT NULL, Role TEXT, PersonType TEXT, SortOrder int, ListOrder int)",
- "drop index if exists idxPeopleItemId",
- "create index if not exists idxPeopleItemId1 on People(ItemId,ListOrder)",
- "create index if not exists idxPeopleName on People(Name)",
+ "drop index if exists idxPeopleItemId",
+ "create index if not exists idxPeopleItemId1 on People(ItemId,ListOrder)",
+ "create index if not exists idxPeopleName on People(Name)",
- "create table if not exists " + ChaptersTableName + " (ItemId GUID, ChapterIndex INT NOT NULL, StartPositionTicks BIGINT NOT NULL, Name TEXT, ImagePath TEXT, PRIMARY KEY (ItemId, ChapterIndex))",
+ "create table if not exists " + ChaptersTableName + " (ItemId GUID, ChapterIndex INT NOT NULL, StartPositionTicks BIGINT NOT NULL, Name TEXT, ImagePath TEXT, PRIMARY KEY (ItemId, ChapterIndex))",
- createMediaStreamsTableCommand,
+ CreateMediaStreamsTableCommand,
+
+ "pragma shrink_memory"
+ };
- "pragma shrink_memory"
- };
+ string[] postQueries =
+ {
+ // obsolete
+ "drop index if exists idx_TypedBaseItems",
+ "drop index if exists idx_mediastreams",
+ "drop index if exists idx_mediastreams1",
+ "drop index if exists idx_"+ChaptersTableName,
+ "drop index if exists idx_UserDataKeys1",
+ "drop index if exists idx_UserDataKeys2",
+ "drop index if exists idx_TypeTopParentId3",
+ "drop index if exists idx_TypeTopParentId2",
+ "drop index if exists idx_TypeTopParentId4",
+ "drop index if exists idx_Type",
+ "drop index if exists idx_TypeTopParentId",
+ "drop index if exists idx_GuidType",
+ "drop index if exists idx_TopParentId",
+ "drop index if exists idx_TypeTopParentId6",
+ "drop index if exists idx_ItemValues2",
+ "drop index if exists Idx_ProviderIds",
+ "drop index if exists idx_ItemValues3",
+ "drop index if exists idx_ItemValues4",
+ "drop index if exists idx_ItemValues5",
+ "drop index if exists idx_UserDataKeys3",
+ "drop table if exists UserDataKeys",
+ "drop table if exists ProviderIds",
+ "drop index if exists Idx_ProviderIds1",
+ "drop table if exists Images",
+ "drop index if exists idx_Images",
+ "drop index if exists idx_TypeSeriesPresentationUniqueKey",
+ "drop index if exists idx_SeriesPresentationUniqueKey",
+ "drop index if exists idx_TypeSeriesPresentationUniqueKey2",
+ "drop index if exists idx_AncestorIds3",
+ "drop index if exists idx_AncestorIds4",
+ "drop index if exists idx_AncestorIds2",
+
+ "create index if not exists idx_PathTypedBaseItems on TypedBaseItems(Path)",
+ "create index if not exists idx_ParentIdTypedBaseItems on TypedBaseItems(ParentId)",
+
+ "create index if not exists idx_PresentationUniqueKey on TypedBaseItems(PresentationUniqueKey)",
+ "create index if not exists idx_GuidTypeIsFolderIsVirtualItem on TypedBaseItems(Guid,Type,IsFolder,IsVirtualItem)",
+ "create index if not exists idx_CleanNameType on TypedBaseItems(CleanName,Type)",
+
+ // covering index
+ "create index if not exists idx_TopParentIdGuid on TypedBaseItems(TopParentId,Guid)",
+
+ // series
+ "create index if not exists idx_TypeSeriesPresentationUniqueKey1 on TypedBaseItems(Type,SeriesPresentationUniqueKey,PresentationUniqueKey,SortName)",
+
+ // series counts
+ // seriesdateplayed sort order
+ "create index if not exists idx_TypeSeriesPresentationUniqueKey3 on TypedBaseItems(SeriesPresentationUniqueKey,Type,IsFolder,IsVirtualItem)",
+
+ // live tv programs
+ "create index if not exists idx_TypeTopParentIdStartDate on TypedBaseItems(Type,TopParentId,StartDate)",
+
+ // covering index for getitemvalues
+ "create index if not exists idx_TypeTopParentIdGuid on TypedBaseItems(Type,TopParentId,Guid)",
+
+ // used by movie suggestions
+ "create index if not exists idx_TypeTopParentIdGroup on TypedBaseItems(Type,TopParentId,PresentationUniqueKey)",
+ "create index if not exists idx_TypeTopParentId5 on TypedBaseItems(TopParentId,IsVirtualItem)",
+
+ // latest items
+ "create index if not exists idx_TypeTopParentId9 on TypedBaseItems(TopParentId,Type,IsVirtualItem,PresentationUniqueKey,DateCreated)",
+ "create index if not exists idx_TypeTopParentId8 on TypedBaseItems(TopParentId,IsFolder,IsVirtualItem,PresentationUniqueKey,DateCreated)",
+
+ // resume
+ "create index if not exists idx_TypeTopParentId7 on TypedBaseItems(TopParentId,MediaType,IsVirtualItem,PresentationUniqueKey)",
+
+ // items by name
+ "create index if not exists idx_ItemValues6 on ItemValues(ItemId,Type,CleanValue)",
+ "create index if not exists idx_ItemValues7 on ItemValues(Type,CleanValue,ItemId)",
+
+ // Used to update inherited tags
+ "create index if not exists idx_ItemValues8 on ItemValues(Type, ItemId, Value)",
+ };
+
+ using (var connection = GetConnection())
+ {
connection.RunQueries(queries);
connection.RunInTransaction(db =>
@@ -235,83 +307,6 @@ namespace Emby.Server.Implementations.Data
}, TransactionMode);
- string[] postQueries =
- {
- // obsolete
- "drop index if exists idx_TypedBaseItems",
- "drop index if exists idx_mediastreams",
- "drop index if exists idx_mediastreams1",
- "drop index if exists idx_"+ChaptersTableName,
- "drop index if exists idx_UserDataKeys1",
- "drop index if exists idx_UserDataKeys2",
- "drop index if exists idx_TypeTopParentId3",
- "drop index if exists idx_TypeTopParentId2",
- "drop index if exists idx_TypeTopParentId4",
- "drop index if exists idx_Type",
- "drop index if exists idx_TypeTopParentId",
- "drop index if exists idx_GuidType",
- "drop index if exists idx_TopParentId",
- "drop index if exists idx_TypeTopParentId6",
- "drop index if exists idx_ItemValues2",
- "drop index if exists Idx_ProviderIds",
- "drop index if exists idx_ItemValues3",
- "drop index if exists idx_ItemValues4",
- "drop index if exists idx_ItemValues5",
- "drop index if exists idx_UserDataKeys3",
- "drop table if exists UserDataKeys",
- "drop table if exists ProviderIds",
- "drop index if exists Idx_ProviderIds1",
- "drop table if exists Images",
- "drop index if exists idx_Images",
- "drop index if exists idx_TypeSeriesPresentationUniqueKey",
- "drop index if exists idx_SeriesPresentationUniqueKey",
- "drop index if exists idx_TypeSeriesPresentationUniqueKey2",
- "drop index if exists idx_AncestorIds3",
- "drop index if exists idx_AncestorIds4",
- "drop index if exists idx_AncestorIds2",
-
- "create index if not exists idx_PathTypedBaseItems on TypedBaseItems(Path)",
- "create index if not exists idx_ParentIdTypedBaseItems on TypedBaseItems(ParentId)",
-
- "create index if not exists idx_PresentationUniqueKey on TypedBaseItems(PresentationUniqueKey)",
- "create index if not exists idx_GuidTypeIsFolderIsVirtualItem on TypedBaseItems(Guid,Type,IsFolder,IsVirtualItem)",
- "create index if not exists idx_CleanNameType on TypedBaseItems(CleanName,Type)",
-
- // covering index
- "create index if not exists idx_TopParentIdGuid on TypedBaseItems(TopParentId,Guid)",
-
- // series
- "create index if not exists idx_TypeSeriesPresentationUniqueKey1 on TypedBaseItems(Type,SeriesPresentationUniqueKey,PresentationUniqueKey,SortName)",
-
- // series counts
- // seriesdateplayed sort order
- "create index if not exists idx_TypeSeriesPresentationUniqueKey3 on TypedBaseItems(SeriesPresentationUniqueKey,Type,IsFolder,IsVirtualItem)",
-
- // live tv programs
- "create index if not exists idx_TypeTopParentIdStartDate on TypedBaseItems(Type,TopParentId,StartDate)",
-
- // covering index for getitemvalues
- "create index if not exists idx_TypeTopParentIdGuid on TypedBaseItems(Type,TopParentId,Guid)",
-
- // used by movie suggestions
- "create index if not exists idx_TypeTopParentIdGroup on TypedBaseItems(Type,TopParentId,PresentationUniqueKey)",
- "create index if not exists idx_TypeTopParentId5 on TypedBaseItems(TopParentId,IsVirtualItem)",
-
- // latest items
- "create index if not exists idx_TypeTopParentId9 on TypedBaseItems(TopParentId,Type,IsVirtualItem,PresentationUniqueKey,DateCreated)",
- "create index if not exists idx_TypeTopParentId8 on TypedBaseItems(TopParentId,IsFolder,IsVirtualItem,PresentationUniqueKey,DateCreated)",
-
- // resume
- "create index if not exists idx_TypeTopParentId7 on TypedBaseItems(TopParentId,MediaType,IsVirtualItem,PresentationUniqueKey)",
-
- // items by name
- "create index if not exists idx_ItemValues6 on ItemValues(ItemId,Type,CleanValue)",
- "create index if not exists idx_ItemValues7 on ItemValues(Type,CleanValue,ItemId)",
-
- // Used to update inherited tags
- "create index if not exists idx_ItemValues8 on ItemValues(Type, ItemId, Value)",
- };
-
connection.RunQueries(postQueries);
}
@@ -669,7 +664,7 @@ namespace Emby.Server.Implementations.Data
if (TypeRequiresDeserialization(item.GetType()))
{
- saveItemStatement.TryBind("@data", _jsonSerializer.SerializeToBytes(item));
+ saveItemStatement.TryBind("@data", JsonSerializer.SerializeToUtf8Bytes(item, _jsonOptions));
}
else
{
@@ -696,7 +691,7 @@ namespace Emby.Server.Implementations.Data
saveItemStatement.TryBindNull("@EndDate");
}
- saveItemStatement.TryBind("@ChannelId", item.ChannelId.Equals(Guid.Empty) ? null : item.ChannelId.ToString("N"));
+ saveItemStatement.TryBind("@ChannelId", item.ChannelId.Equals(Guid.Empty) ? null : item.ChannelId.ToString("N", CultureInfo.InvariantCulture));
if (item is IHasProgramAttributes hasProgramAttributes)
{
@@ -851,7 +846,7 @@ namespace Emby.Server.Implementations.Data
}
else
{
- saveItemStatement.TryBind("@TopParentId", topParent.Id.ToString("N"));
+ saveItemStatement.TryBind("@TopParentId", topParent.Id.ToString("N", CultureInfo.InvariantCulture));
}
if (item is Trailer trailer && trailer.TrailerTypes.Length > 0)
@@ -977,7 +972,7 @@ namespace Emby.Server.Implementations.Data
}
string artists = null;
- if (item is IHasArtist hasArtists && hasArtists.Artists.Length > 0)
+ if (item is IHasArtist hasArtists && hasArtists.Artists.Count > 0)
{
artists = string.Join("|", hasArtists.Artists);
}
@@ -985,7 +980,7 @@ namespace Emby.Server.Implementations.Data
string albumArtists = null;
if (item is IHasAlbumArtist hasAlbumArtists
- && hasAlbumArtists.AlbumArtists.Length > 0)
+ && hasAlbumArtists.AlbumArtists.Count > 0)
{
albumArtists = string.Join("|", hasAlbumArtists.AlbumArtists);
}
@@ -1298,18 +1293,13 @@ namespace Emby.Server.Implementations.Data
if (TypeRequiresDeserialization(type))
{
- using (var stream = new MemoryStream(reader[1].ToBlob()))
+ try
{
- stream.Position = 0;
-
- try
- {
- item = _jsonSerializer.DeserializeFromStream(stream, type) as BaseItem;
- }
- catch (SerializationException ex)
- {
- Logger.LogError(ex, "Error deserializing item");
- }
+ item = JsonSerializer.Deserialize(reader[1].ToBlob(), type, _jsonOptions) as BaseItem;
+ }
+ catch (JsonException ex)
+ {
+ Logger.LogError(ex, "Error deserializing item with JSON: {Data}", reader.GetString(1));
}
}
@@ -1999,14 +1989,14 @@ namespace Emby.Server.Implementations.Data
throw new ArgumentNullException(nameof(chapters));
}
+ var idBlob = id.ToGuidBlob();
+
using (var connection = GetConnection())
{
connection.RunInTransaction(db =>
{
- var idBlob = id.ToGuidBlob();
-
- // First delete chapters
- db.Execute("delete from " + ChaptersTableName + " where ItemId=@ItemId", idBlob);
+ // First delete chapters
+ db.Execute("delete from " + ChaptersTableName + " where ItemId=@ItemId", idBlob);
InsertChapters(idBlob, chapters, db);
@@ -2535,6 +2525,7 @@ namespace Emby.Server.Implementations.Data
commandText += " where " + string.Join(" AND ", whereClauses);
}
+ int count;
using (var connection = GetConnection(true))
{
using (var statement = PrepareStatement(connection, commandText))
@@ -2550,11 +2541,12 @@ namespace Emby.Server.Implementations.Data
// Running this again will bind the params
GetWhereClauses(query, statement);
- var count = statement.ExecuteQuery().SelectScalarInt().First();
- LogQueryTime("GetCount", commandText, now);
- return count;
+ count = statement.ExecuteQuery().SelectScalarInt().First();
}
}
+
+ LogQueryTime("GetCount", commandText, now);
+ return count;
}
public List GetItemList(InternalItemsQuery query)
@@ -2604,10 +2596,9 @@ namespace Emby.Server.Implementations.Data
}
}
+ var items = new List();
using (var connection = GetConnection(true))
{
- var items = new List();
-
using (var statement = PrepareStatement(connection, commandText))
{
if (EnableJoinUserData(query))
@@ -2658,11 +2649,11 @@ namespace Emby.Server.Implementations.Data
items = newList;
}
+ }
- LogQueryTime("GetItemList", commandText, now);
+ LogQueryTime("GetItemList", commandText, now);
- return items;
- }
+ return items;
}
private string FixUnicodeChars(string buffer)
@@ -2726,7 +2717,7 @@ namespace Emby.Server.Implementations.Data
if (elapsed >= SlowThreshold)
{
- Logger.LogWarning(
+ Logger.LogDebug(
"{Method} query time (slow): {ElapsedMs}ms. Query: {Query}",
methodName,
elapsed,
@@ -2748,15 +2739,13 @@ namespace Emby.Server.Implementations.Data
var returnList = GetItemList(query);
return new QueryResult
{
- Items = returnList.ToArray(),
+ Items = returnList,
TotalRecordCount = returnList.Count
};
}
var now = DateTime.UtcNow;
- var list = new List();
-
// Hack for right now since we currently don't support filtering out these duplicates within a query
if (query.Limit.HasValue && query.EnableGroupByMetadataKey)
{
@@ -2822,11 +2811,13 @@ namespace Emby.Server.Implementations.Data
statementTexts.Add(commandText);
}
+ var list = new List();
+ var result = new QueryResult();
using (var connection = GetConnection(true))
{
- return connection.RunInTransaction(db =>
+ connection.RunInTransaction(db =>
{
- var result = new QueryResult();
+
var statements = PrepareAll(db, statementTexts).ToList();
if (!isReturningZeroItems)
@@ -2881,14 +2872,12 @@ namespace Emby.Server.Implementations.Data
result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
}
}
-
- LogQueryTime("GetItems", commandText, now);
-
- result.Items = list.ToArray();
- return result;
-
}, ReadTransactionMode);
}
+
+ LogQueryTime("GetItems", commandText, now);
+ result.Items = list;
+ return result;
}
private string GetOrderByText(InternalItemsQuery query)
@@ -3054,10 +3043,9 @@ namespace Emby.Server.Implementations.Data
}
}
+ var list = new List();
using (var connection = GetConnection(true))
{
- var list = new List();
-
using (var statement = PrepareStatement(connection, commandText))
{
if (EnableJoinUserData(query))
@@ -3076,11 +3064,10 @@ namespace Emby.Server.Implementations.Data
list.Add(row[0].ReadGuidFromBlob());
}
}
-
- LogQueryTime("GetItemList", commandText, now);
-
- return list;
}
+
+ LogQueryTime("GetItemList", commandText, now);
+ return list;
}
public List> GetItemIdsWithPath(InternalItemsQuery query)
@@ -3142,6 +3129,7 @@ namespace Emby.Server.Implementations.Data
{
path = row.GetString(1);
}
+
list.Add(new Tuple(id, path));
}
}
@@ -3166,7 +3154,7 @@ namespace Emby.Server.Implementations.Data
var returnList = GetItemIdsList(query);
return new QueryResult
{
- Items = returnList.ToArray(),
+ Items = returnList,
TotalRecordCount = returnList.Count
};
}
@@ -3203,7 +3191,7 @@ namespace Emby.Server.Implementations.Data
}
}
- var list = new List();
+
var isReturningZeroItems = query.Limit.HasValue && query.Limit <= 0;
var statementTexts = new List();
@@ -3233,12 +3221,12 @@ namespace Emby.Server.Implementations.Data
statementTexts.Add(commandText);
}
+ var list = new List();
+ var result = new QueryResult();
using (var connection = GetConnection(true))
{
- return connection.RunInTransaction(db =>
+ connection.RunInTransaction(db =>
{
- var result = new QueryResult();
-
var statements = PrepareAll(db, statementTexts).ToList();
if (!isReturningZeroItems)
@@ -3281,14 +3269,13 @@ namespace Emby.Server.Implementations.Data
result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
}
}
-
- LogQueryTime("GetItemIds", commandText, now);
-
- result.Items = list.ToArray();
- return result;
-
}, ReadTransactionMode);
}
+
+ LogQueryTime("GetItemIds", commandText, now);
+
+ result.Items = list;
+ return result;
}
private bool IsAlphaNumeric(string str)
@@ -3548,12 +3535,12 @@ namespace Emby.Server.Implementations.Data
whereClauses.Add("ChannelId=@ChannelId");
if (statement != null)
{
- statement.TryBind("@ChannelId", query.ChannelIds[0].ToString("N"));
+ statement.TryBind("@ChannelId", query.ChannelIds[0].ToString("N", CultureInfo.InvariantCulture));
}
}
else if (query.ChannelIds.Length > 1)
{
- var inClause = string.Join(",", query.ChannelIds.Select(i => "'" + i.ToString("N") + "'"));
+ var inClause = string.Join(",", query.ChannelIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'"));
whereClauses.Add($"ChannelId in ({inClause})");
}
@@ -4537,12 +4524,12 @@ namespace Emby.Server.Implementations.Data
}
if (statement != null)
{
- statement.TryBind("@TopParentId", queryTopParentIds[0].ToString("N"));
+ statement.TryBind("@TopParentId", queryTopParentIds[0].ToString("N", CultureInfo.InvariantCulture));
}
}
else if (queryTopParentIds.Length > 1)
{
- var val = string.Join(",", queryTopParentIds.Select(i => "'" + i.ToString("N") + "'"));
+ var val = string.Join(",", queryTopParentIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'"));
if (enableItemsByName && includedItemByNameTypes.Count == 1)
{
@@ -4574,7 +4561,7 @@ namespace Emby.Server.Implementations.Data
}
if (query.AncestorIds.Length > 1)
{
- var inClause = string.Join(",", query.AncestorIds.Select(i => "'" + i.ToString("N") + "'"));
+ var inClause = string.Join(",", query.AncestorIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'"));
whereClauses.Add(string.Format("Guid in (select itemId from AncestorIds where AncestorIdText in ({0}))", inClause));
}
if (!string.IsNullOrWhiteSpace(query.AncestorWithPresentationUniqueKey))
@@ -4637,7 +4624,7 @@ namespace Emby.Server.Implementations.Data
foreach (var folderId in query.BoxSetLibraryFolders)
{
- folderIdQueries.Add("data like '%" + folderId.ToString("N") + "%'");
+ folderIdQueries.Add("data like '%" + folderId.ToString("N", CultureInfo.InvariantCulture) + "%'");
}
whereClauses.Add("(" + string.Join(" OR ", folderIdQueries) + ")");
@@ -4864,22 +4851,25 @@ namespace Emby.Server.Implementations.Data
private void UpdateInheritedTags(CancellationToken cancellationToken)
{
- using (var connection = GetConnection())
- {
- connection.RunInTransaction(db =>
+ string sql = string.Join(
+ ";",
+ new string[]
{
- connection.ExecuteAll(string.Join(";", new string[]
- {
- "delete from itemvalues where type = 6",
+ "delete from itemvalues where type = 6",
- "insert into itemvalues (ItemId, Type, Value, CleanValue) select ItemId, 6, Value, CleanValue from ItemValues where Type=4",
+ "insert into itemvalues (ItemId, Type, Value, CleanValue) select ItemId, 6, Value, CleanValue from ItemValues where Type=4",
- @"insert into itemvalues (ItemId, Type, Value, CleanValue) select AncestorIds.itemid, 6, ItemValues.Value, ItemValues.CleanValue
+ @"insert into itemvalues (ItemId, Type, Value, CleanValue) select AncestorIds.itemid, 6, ItemValues.Value, ItemValues.CleanValue
FROM AncestorIds
LEFT JOIN ItemValues ON (AncestorIds.AncestorId = ItemValues.ItemId)
where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type = 4 "
+ });
- }));
+ using (var connection = GetConnection())
+ {
+ connection.RunInTransaction(db =>
+ {
+ connection.ExecuteAll(sql);
}, TransactionMode);
}
@@ -4933,23 +4923,23 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
{
var idBlob = id.ToGuidBlob();
- // Delete people
- ExecuteWithSingleParam(db, "delete from People where ItemId=@Id", idBlob);
+ // Delete people
+ ExecuteWithSingleParam(db, "delete from People where ItemId=@Id", idBlob);
- // Delete chapters
- ExecuteWithSingleParam(db, "delete from " + ChaptersTableName + " where ItemId=@Id", idBlob);
+ // Delete chapters
+ ExecuteWithSingleParam(db, "delete from " + ChaptersTableName + " where ItemId=@Id", idBlob);
- // Delete media streams
- ExecuteWithSingleParam(db, "delete from mediastreams where ItemId=@Id", idBlob);
+ // Delete media streams
+ ExecuteWithSingleParam(db, "delete from mediastreams where ItemId=@Id", idBlob);
- // Delete ancestors
- ExecuteWithSingleParam(db, "delete from AncestorIds where ItemId=@Id", idBlob);
+ // Delete ancestors
+ ExecuteWithSingleParam(db, "delete from AncestorIds where ItemId=@Id", idBlob);
- // Delete item values
- ExecuteWithSingleParam(db, "delete from ItemValues where ItemId=@Id", idBlob);
+ // Delete item values
+ ExecuteWithSingleParam(db, "delete from ItemValues where ItemId=@Id", idBlob);
- // Delete the item
- ExecuteWithSingleParam(db, "delete from TypedBaseItems where guid=@Id", idBlob);
+ // Delete the item
+ ExecuteWithSingleParam(db, "delete from TypedBaseItems where guid=@Id", idBlob);
}, TransactionMode);
}
}
@@ -4997,6 +4987,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
list.Add(row.GetString(0));
}
}
+
return list;
}
}
@@ -5161,7 +5152,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
var ancestorId = ancestorIds[i];
statement.TryBind("@AncestorId" + index, ancestorId.ToGuidBlob());
- statement.TryBind("@AncestorIdText" + index, ancestorId.ToString("N"));
+ statement.TryBind("@AncestorIdText" + index, ancestorId.ToString("N", CultureInfo.InvariantCulture));
}
statement.Reset();
@@ -5247,10 +5238,9 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
commandText += " Group By CleanValue";
+ var list = new List();
using (var connection = GetConnection(true))
{
- var list = new List();
-
using (var statement = PrepareStatement(connection, commandText))
{
foreach (var row in statement.ExecuteQuery())
@@ -5262,10 +5252,10 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
}
}
- LogQueryTime("GetItemValueNames", commandText, now);
-
- return list;
}
+
+ LogQueryTime("GetItemValueNames", commandText, now);
+ return list;
}
private QueryResult<(BaseItem, ItemCounts)> GetItemValues(InternalItemsQuery query, int[] itemValueTypes, string returnType)
@@ -5422,6 +5412,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
{
statementTexts.Add(commandText);
}
+
if (query.EnableTotalRecordCount)
{
var countText = "select "
@@ -5433,98 +5424,98 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
statementTexts.Add(countText);
}
+ var list = new List<(BaseItem, ItemCounts)>();
+ var result = new QueryResult<(BaseItem, ItemCounts)>();
using (var connection = GetConnection(true))
{
- return connection.RunInTransaction(db =>
- {
- var list = new List<(BaseItem, ItemCounts)>();
- var result = new QueryResult<(BaseItem, ItemCounts)>();
-
- var statements = PrepareAll(db, statementTexts).ToList();
-
- if (!isReturningZeroItems)
+ connection.RunInTransaction(
+ db =>
{
- using (var statement = statements[0])
+ var statements = PrepareAll(db, statementTexts).ToList();
+
+ if (!isReturningZeroItems)
{
- statement.TryBind("@SelectType", returnType);
- if (EnableJoinUserData(query))
+ using (var statement = statements[0])
{
- statement.TryBind("@UserId", query.User.InternalId);
- }
+ statement.TryBind("@SelectType", returnType);
+ if (EnableJoinUserData(query))
+ {
+ statement.TryBind("@UserId", query.User.InternalId);
+ }
- if (typeSubQuery != null)
- {
- GetWhereClauses(typeSubQuery, null);
- }
- BindSimilarParams(query, statement);
- BindSearchParams(query, statement);
- GetWhereClauses(innerQuery, statement);
- GetWhereClauses(outerQuery, statement);
+ if (typeSubQuery != null)
+ {
+ GetWhereClauses(typeSubQuery, null);
+ }
- var hasEpisodeAttributes = HasEpisodeAttributes(query);
- var hasProgramAttributes = HasProgramAttributes(query);
- var hasServiceName = HasServiceName(query);
- var hasStartDate = HasStartDate(query);
- var hasTrailerTypes = HasTrailerTypes(query);
- var hasArtistFields = HasArtistFields(query);
- var hasSeriesFields = HasSeriesFields(query);
+ BindSimilarParams(query, statement);
+ BindSearchParams(query, statement);
+ GetWhereClauses(innerQuery, statement);
+ GetWhereClauses(outerQuery, statement);
- foreach (var row in statement.ExecuteQuery())
- {
- var item = GetItem(row, query, hasProgramAttributes, hasEpisodeAttributes, hasServiceName, hasStartDate, hasTrailerTypes, hasArtistFields, hasSeriesFields);
- if (item != null)
+ var hasEpisodeAttributes = HasEpisodeAttributes(query);
+ var hasProgramAttributes = HasProgramAttributes(query);
+ var hasServiceName = HasServiceName(query);
+ var hasStartDate = HasStartDate(query);
+ var hasTrailerTypes = HasTrailerTypes(query);
+ var hasArtistFields = HasArtistFields(query);
+ var hasSeriesFields = HasSeriesFields(query);
+
+ foreach (var row in statement.ExecuteQuery())
{
- var countStartColumn = columns.Count - 1;
+ var item = GetItem(row, query, hasProgramAttributes, hasEpisodeAttributes, hasServiceName, hasStartDate, hasTrailerTypes, hasArtistFields, hasSeriesFields);
+ if (item != null)
+ {
+ var countStartColumn = columns.Count - 1;
- list.Add((item, GetItemCounts(row, countStartColumn, typesToCount)));
+ list.Add((item, GetItemCounts(row, countStartColumn, typesToCount)));
+ }
}
}
-
- LogQueryTime("GetItemValues", commandText, now);
}
- }
- if (query.EnableTotalRecordCount)
- {
- commandText = "select "
- + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count (distinct PresentationUniqueKey)" }))
- + GetFromText()
- + GetJoinUserDataText(query)
- + whereText;
-
- using (var statement = statements[statements.Count - 1])
+ if (query.EnableTotalRecordCount)
{
- statement.TryBind("@SelectType", returnType);
- if (EnableJoinUserData(query))
- {
- statement.TryBind("@UserId", query.User.InternalId);
- }
+ commandText = "select "
+ + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count (distinct PresentationUniqueKey)" }))
+ + GetFromText()
+ + GetJoinUserDataText(query)
+ + whereText;
- if (typeSubQuery != null)
+ using (var statement = statements[statements.Count - 1])
{
- GetWhereClauses(typeSubQuery, null);
- }
- BindSimilarParams(query, statement);
- BindSearchParams(query, statement);
- GetWhereClauses(innerQuery, statement);
- GetWhereClauses(outerQuery, statement);
+ statement.TryBind("@SelectType", returnType);
+ if (EnableJoinUserData(query))
+ {
+ statement.TryBind("@UserId", query.User.InternalId);
+ }
- result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
+ if (typeSubQuery != null)
+ {
+ GetWhereClauses(typeSubQuery, null);
+ }
+ BindSimilarParams(query, statement);
+ BindSearchParams(query, statement);
+ GetWhereClauses(innerQuery, statement);
+ GetWhereClauses(outerQuery, statement);
- LogQueryTime("GetItemValues", commandText, now);
+ result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
+ }
}
- }
-
- if (result.TotalRecordCount == 0)
- {
- result.TotalRecordCount = list.Count;
- }
- result.Items = list.ToArray();
+ },
+ ReadTransactionMode);
+ }
- return result;
+ LogQueryTime("GetItemValues", commandText, now);
- }, ReadTransactionMode);
+ if (result.TotalRecordCount == 0)
+ {
+ result.TotalRecordCount = list.Count;
}
+
+ result.Items = list;
+
+ return result;
}
private ItemCounts GetItemCounts(IReadOnlyList reader, int countStartColumn, string[] typesToCount)
@@ -5579,6 +5570,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
{
counts.TrailerCount = value;
}
+
counts.ItemCount += value;
}
@@ -5706,8 +5698,8 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
{
var itemIdBlob = itemId.ToGuidBlob();
- // First delete chapters
- db.Execute("delete from People where ItemId=@ItemId", itemIdBlob);
+ // First delete chapters
+ db.Execute("delete from People where ItemId=@ItemId", itemIdBlob);
InsertPeople(itemIdBlob, people, db);
@@ -5732,7 +5724,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
{
if (isSubsequentRow)
{
- insertText.Append(",");
+ insertText.Append(',');
}
insertText.AppendFormat("(@ItemId, @Name{0}, @Role{0}, @PersonType{0}, @SortOrder{0}, @ListOrder{0})", i.ToString(CultureInfo.InvariantCulture));
@@ -5867,8 +5859,8 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
{
var itemIdBlob = id.ToGuidBlob();
- // First delete chapters
- db.Execute("delete from mediastreams where ItemId=@ItemId", itemIdBlob);
+ // First delete chapters
+ db.Execute("delete from mediastreams where ItemId=@ItemId", itemIdBlob);
InsertMediaStreams(itemIdBlob, streams, db);
diff --git a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs
index 4035bb99d1..9d4855bcf3 100644
--- a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs
+++ b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs
@@ -44,7 +44,7 @@ namespace Emby.Server.Implementations.Data
var userDatasTableExists = TableExists(connection, "UserDatas");
var userDataTableExists = TableExists(connection, "userdata");
- var users = userDatasTableExists ? null : userManager.Users.ToArray();
+ var users = userDatasTableExists ? null : userManager.Users;
connection.RunInTransaction(db =>
{
@@ -84,7 +84,7 @@ namespace Emby.Server.Implementations.Data
}
}
- private void ImportUserIds(IDatabaseConnection db, User[] users)
+ private void ImportUserIds(IDatabaseConnection db, IEnumerable users)
{
var userIdsWithUserData = GetAllUserIdsWithUserData(db);
diff --git a/Emby.Server.Implementations/Data/SqliteUserRepository.cs b/Emby.Server.Implementations/Data/SqliteUserRepository.cs
index de2354eefc..80fe278f82 100644
--- a/Emby.Server.Implementations/Data/SqliteUserRepository.cs
+++ b/Emby.Server.Implementations/Data/SqliteUserRepository.cs
@@ -1,10 +1,11 @@
using System;
using System.Collections.Generic;
using System.IO;
+using System.Text.Json;
+using MediaBrowser.Common.Json;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Persistence;
-using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
using SQLitePCL.pretty;
@@ -15,15 +16,14 @@ namespace Emby.Server.Implementations.Data
///
public class SqliteUserRepository : BaseSqliteRepository, IUserRepository
{
- private readonly IJsonSerializer _jsonSerializer;
+ private readonly JsonSerializerOptions _jsonOptions;
public SqliteUserRepository(
- ILoggerFactory loggerFactory,
- IServerApplicationPaths appPaths,
- IJsonSerializer jsonSerializer)
- : base(loggerFactory.CreateLogger(nameof(SqliteUserRepository)))
+ ILogger logger,
+ IServerApplicationPaths appPaths)
+ : base(logger)
{
- _jsonSerializer = jsonSerializer;
+ _jsonOptions = JsonDefaults.GetOptions();;
DbFilePath = Path.Combine(appPaths.DataPath, "users.db");
}
@@ -35,9 +35,8 @@ namespace Emby.Server.Implementations.Data
public string Name => "SQLite";
///
- /// Opens the connection to the database
+ /// Opens the connection to the database.
///
- /// Task.
public void Initialize()
{
using (var connection = GetConnection())
@@ -85,7 +84,7 @@ namespace Emby.Server.Implementations.Data
}
user.Password = null;
- var serialized = _jsonSerializer.SerializeToBytes(user);
+ var serialized = JsonSerializer.SerializeToUtf8Bytes(user, _jsonOptions);
connection.RunInTransaction(db =>
{
@@ -109,7 +108,7 @@ namespace Emby.Server.Implementations.Data
throw new ArgumentNullException(nameof(user));
}
- var serialized = _jsonSerializer.SerializeToBytes(user);
+ var serialized = JsonSerializer.SerializeToUtf8Bytes(user, _jsonOptions);
using (var connection = GetConnection())
{
@@ -143,7 +142,7 @@ namespace Emby.Server.Implementations.Data
throw new ArgumentNullException(nameof(user));
}
- var serialized = _jsonSerializer.SerializeToBytes(user);
+ var serialized = JsonSerializer.SerializeToUtf8Bytes(user, _jsonOptions);
using (var connection = GetConnection())
{
@@ -180,14 +179,10 @@ namespace Emby.Server.Implementations.Data
var id = row[0].ToInt64();
var guid = row[1].ReadGuidFromBlob();
- using (var stream = new MemoryStream(row[2].ToBlob()))
- {
- stream.Position = 0;
- var user = _jsonSerializer.DeserializeFromStream(stream);
- user.InternalId = id;
- user.Id = guid;
- return user;
- }
+ var user = JsonSerializer.Deserialize(row[2].ToBlob(), _jsonOptions);
+ user.InternalId = id;
+ user.Id = guid;
+ return user;
}
///
diff --git a/Emby.Server.Implementations/Devices/DeviceId.cs b/Emby.Server.Implementations/Devices/DeviceId.cs
index 495c3436ab..7344dc72f3 100644
--- a/Emby.Server.Implementations/Devices/DeviceId.cs
+++ b/Emby.Server.Implementations/Devices/DeviceId.cs
@@ -1,8 +1,8 @@
using System;
+using System.Globalization;
using System.IO;
using System.Text;
using MediaBrowser.Common.Configuration;
-using MediaBrowser.Model.IO;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Devices
@@ -67,7 +67,7 @@ namespace Emby.Server.Implementations.Devices
private static string GetNewId()
{
- return Guid.NewGuid().ToString("N");
+ return Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
}
private string GetDeviceId()
diff --git a/Emby.Server.Implementations/Devices/DeviceManager.cs b/Emby.Server.Implementations/Devices/DeviceManager.cs
index 7d6529a675..d1704b3736 100644
--- a/Emby.Server.Implementations/Devices/DeviceManager.cs
+++ b/Emby.Server.Implementations/Devices/DeviceManager.cs
@@ -1,11 +1,11 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
-using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Devices;
using MediaBrowser.Controller.Entities;
@@ -195,7 +195,7 @@ namespace Emby.Server.Implementations.Devices
private string GetDevicePath(string id)
{
- return Path.Combine(GetDevicesPath(), id.GetMD5().ToString("N"));
+ return Path.Combine(GetDevicesPath(), id.GetMD5().ToString("N", CultureInfo.InvariantCulture));
}
public ContentUploadHistory GetCameraUploadHistory(string deviceId)
diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs
index 2f1b60be9c..6c0e32e05b 100644
--- a/Emby.Server.Implementations/Dto/DtoService.cs
+++ b/Emby.Server.Implementations/Dto/DtoService.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
@@ -79,27 +80,25 @@ namespace Emby.Server.Implementations.Dto
return GetBaseItemDto(item, options, user, owner);
}
- public BaseItemDto[] GetBaseItemDtos(IReadOnlyList items, DtoOptions options, User user = null, BaseItem owner = null)
- => GetBaseItemDtos(items, items.Count, options, user, owner);
-
- public BaseItemDto[] GetBaseItemDtos(IEnumerable items, int itemCount, DtoOptions options, User user = null, BaseItem owner = null)
+ ///
+ public IReadOnlyList GetBaseItemDtos(IReadOnlyList items, DtoOptions options, User user = null, BaseItem owner = null)
{
- var returnItems = new BaseItemDto[itemCount];
- var programTuples = new List>();
- var channelTuples = new List>();
+ var returnItems = new BaseItemDto[items.Count];
+ var programTuples = new List<(BaseItem, BaseItemDto)>();
+ var channelTuples = new List<(BaseItemDto, LiveTvChannel)>();
- var index = 0;
- foreach (var item in items)
+ for (int index = 0; index < items.Count; index++)
{
+ var item = items[index];
var dto = GetBaseItemDtoInternal(item, options, user, owner);
if (item is LiveTvChannel tvChannel)
{
- channelTuples.Add(new Tuple(dto, tvChannel));
+ channelTuples.Add((dto, tvChannel));
}
else if (item is LiveTvProgram)
{
- programTuples.Add(new Tuple(item, dto));
+ programTuples.Add((item, dto));
}
if (item is IItemByName byName)
@@ -120,7 +119,6 @@ namespace Emby.Server.Implementations.Dto
}
returnItems[index] = dto;
- index++;
}
if (programTuples.Count > 0)
@@ -139,33 +137,32 @@ namespace Emby.Server.Implementations.Dto
public BaseItemDto GetBaseItemDto(BaseItem item, DtoOptions options, User user = null, BaseItem owner = null)
{
var dto = GetBaseItemDtoInternal(item, options, user, owner);
- var tvChannel = item as LiveTvChannel;
- if (tvChannel != null)
+ if (item is LiveTvChannel tvChannel)
{
- var list = new List> { new Tuple(dto, tvChannel) };
+ var list = new List<(BaseItemDto, LiveTvChannel)>(1) { (dto, tvChannel) };
_livetvManager().AddChannelInfo(list, options, user);
}
else if (item is LiveTvProgram)
{
- var list = new List> { new Tuple(item, dto) };
+ var list = new List<(BaseItem, BaseItemDto)>(1) { (item, dto) };
var task = _livetvManager().AddInfoToProgramDto(list, options.Fields, user);
Task.WaitAll(task);
}
- var byName = item as IItemByName;
-
- if (byName != null)
+ if (item is IItemByName itemByName
+ && options.ContainsField(ItemFields.ItemCounts))
{
- if (options.ContainsField(ItemFields.ItemCounts))
- {
- SetItemByNameInfo(item, dto, GetTaggedItems(byName, user, new DtoOptions(false)
- {
- EnableImages = false
-
- }), user);
- }
-
- return dto;
+ SetItemByNameInfo(
+ item,
+ dto,
+ GetTaggedItems(
+ itemByName,
+ user,
+ new DtoOptions(false)
+ {
+ EnableImages = false
+ }),
+ user);
}
return dto;
@@ -173,12 +170,12 @@ namespace Emby.Server.Implementations.Dto
private static IList GetTaggedItems(IItemByName byName, User user, DtoOptions options)
{
- return byName.GetTaggedItems(new InternalItemsQuery(user)
- {
- Recursive = true,
- DtoOptions = options
-
- });
+ return byName.GetTaggedItems(
+ new InternalItemsQuery(user)
+ {
+ Recursive = true,
+ DtoOptions = options
+ });
}
private BaseItemDto GetBaseItemDtoInternal(BaseItem item, DtoOptions options, User user = null, BaseItem owner = null)
@@ -213,7 +210,7 @@ namespace Emby.Server.Implementations.Dto
if (options.ContainsField(ItemFields.DisplayPreferencesId))
{
- dto.DisplayPreferencesId = item.DisplayPreferencesId.ToString("N");
+ dto.DisplayPreferencesId = item.DisplayPreferencesId.ToString("N", CultureInfo.InvariantCulture);
}
if (user != null)
@@ -221,15 +218,12 @@ namespace Emby.Server.Implementations.Dto
AttachUserSpecificInfo(dto, item, user, options);
}
- var hasMediaSources = item as IHasMediaSources;
- if (hasMediaSources != null)
+ if (item is IHasMediaSources
+ && options.ContainsField(ItemFields.MediaSources))
{
- if (options.ContainsField(ItemFields.MediaSources))
- {
- dto.MediaSources = _mediaSourceManager().GetStaticMediaSources(item, true, user).ToArray();
+ dto.MediaSources = _mediaSourceManager().GetStaticMediaSources(item, true, user).ToArray();
- NormalizeMediaSourceContainers(dto);
- }
+ NormalizeMediaSourceContainers(dto);
}
if (options.ContainsField(ItemFields.Studios))
@@ -444,7 +438,7 @@ namespace Emby.Server.Implementations.Dto
/// item
public string GetDtoId(BaseItem item)
{
- return item.Id.ToString("N");
+ return item.Id.ToString("N", CultureInfo.InvariantCulture);
}
private static void SetBookProperties(BaseItemDto dto, Book item)
@@ -608,7 +602,7 @@ namespace Emby.Server.Implementations.Dto
if (dictionary.TryGetValue(person.Name, out Person entity))
{
baseItemPerson.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
- baseItemPerson.Id = entity.Id.ToString("N");
+ baseItemPerson.Id = entity.Id.ToString("N", CultureInfo.InvariantCulture);
list.Add(baseItemPerson);
}
}
@@ -768,14 +762,12 @@ namespace Emby.Server.Implementations.Dto
dto.CriticRating = item.CriticRating;
- var hasDisplayOrder = item as IHasDisplayOrder;
- if (hasDisplayOrder != null)
+ if (item is IHasDisplayOrder hasDisplayOrder)
{
dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
}
- var hasCollectionType = item as IHasCollectionType;
- if (hasCollectionType != null)
+ if (item is IHasCollectionType hasCollectionType)
{
dto.CollectionType = hasCollectionType.CollectionType;
}
@@ -885,15 +877,14 @@ namespace Emby.Server.Implementations.Dto
//}
}
- var hasArtist = item as IHasArtist;
- if (hasArtist != null)
+ if (item is IHasArtist hasArtist)
{
dto.Artists = hasArtist.Artists;
//var artistItems = _libraryManager.GetArtists(new InternalItemsQuery
//{
// EnableTotalRecordCount = false,
- // ItemIds = new[] { item.Id.ToString("N") }
+ // ItemIds = new[] { item.Id.ToString("N", CultureInfo.InvariantCulture) }
//});
//dto.ArtistItems = artistItems.Items
@@ -903,7 +894,7 @@ namespace Emby.Server.Implementations.Dto
// return new NameIdPair
// {
// Name = artist.Name,
- // Id = artist.Id.ToString("N")
+ // Id = artist.Id.ToString("N", CultureInfo.InvariantCulture)
// };
// })
// .ToList();
@@ -946,7 +937,7 @@ namespace Emby.Server.Implementations.Dto
//var artistItems = _libraryManager.GetAlbumArtists(new InternalItemsQuery
//{
// EnableTotalRecordCount = false,
- // ItemIds = new[] { item.Id.ToString("N") }
+ // ItemIds = new[] { item.Id.ToString("N", CultureInfo.InvariantCulture) }
//});
//dto.AlbumArtists = artistItems.Items
@@ -956,7 +947,7 @@ namespace Emby.Server.Implementations.Dto
// return new NameIdPair
// {
// Name = artist.Name,
- // Id = artist.Id.ToString("N")
+ // Id = artist.Id.ToString("N", CultureInfo.InvariantCulture)
// };
// })
// .ToList();
@@ -1044,7 +1035,7 @@ namespace Emby.Server.Implementations.Dto
}
else
{
- string id = item.Id.ToString("N");
+ string id = item.Id.ToString("N", CultureInfo.InvariantCulture);
mediaStreams = dto.MediaSources.Where(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase))
.SelectMany(i => i.MediaStreams)
.ToArray();
@@ -1073,17 +1064,24 @@ namespace Emby.Server.Implementations.Dto
if (options.ContainsField(ItemFields.LocalTrailerCount))
{
+ int trailerCount = 0;
if (allExtras == null)
{
allExtras = item.GetExtras().ToArray();
}
- dto.LocalTrailerCount = allExtras.Count(i => i.ExtraType.HasValue && i.ExtraType.Value == ExtraType.Trailer);
+ trailerCount += allExtras.Count(i => i.ExtraType.HasValue && i.ExtraType.Value == ExtraType.Trailer);
+
+ if (item is IHasTrailers hasTrailers)
+ {
+ trailerCount += hasTrailers.GetTrailerCount();
+ }
+
+ dto.LocalTrailerCount = trailerCount;
}
// Add EpisodeInfo
- var episode = item as Episode;
- if (episode != null)
+ if (item is Episode episode)
{
dto.IndexNumberEnd = episode.IndexNumberEnd;
dto.SeriesName = episode.SeriesName;
@@ -1101,6 +1099,8 @@ namespace Emby.Server.Implementations.Dto
Series episodeSeries = null;
+ // this block will add the series poster for episodes without a poster
+ // TODO maybe remove the if statement entirely
//if (options.ContainsField(ItemFields.SeriesPrimaryImage))
{
episodeSeries = episodeSeries ?? episode.Series;
@@ -1121,8 +1121,7 @@ namespace Emby.Server.Implementations.Dto
}
// Add SeriesInfo
- var series = item as Series;
- if (series != null)
+ if (item is Series series)
{
dto.AirDays = series.AirDays;
dto.AirTime = series.AirTime;
@@ -1130,8 +1129,7 @@ namespace Emby.Server.Implementations.Dto
}
// Add SeasonInfo
- var season = item as Season;
- if (season != null)
+ if (item is Season season)
{
dto.SeriesName = season.SeriesName;
dto.SeriesId = season.SeriesId;
@@ -1147,6 +1145,8 @@ namespace Emby.Server.Implementations.Dto
}
}
+ // this block will add the series poster for seasons without a poster
+ // TODO maybe remove the if statement entirely
//if (options.ContainsField(ItemFields.SeriesPrimaryImage))
{
series = series ?? season.Series;
@@ -1157,14 +1157,12 @@ namespace Emby.Server.Implementations.Dto
}
}
- var musicVideo = item as MusicVideo;
- if (musicVideo != null)
+ if (item is MusicVideo musicVideo)
{
SetMusicVideoProperties(dto, musicVideo);
}
- var book = item as Book;
- if (book != null)
+ if (item is Book book)
{
SetBookProperties(dto, book);
}
@@ -1204,8 +1202,7 @@ namespace Emby.Server.Implementations.Dto
}
}
- var photo = item as Photo;
- if (photo != null)
+ if (item is Photo photo)
{
SetPhotoProperties(dto, photo);
}
@@ -1224,8 +1221,7 @@ namespace Emby.Server.Implementations.Dto
private BaseItem GetImageDisplayParent(BaseItem currentItem, BaseItem originalItem)
{
- var musicAlbum = currentItem as MusicAlbum;
- if (musicAlbum != null)
+ if (currentItem is MusicAlbum musicAlbum)
{
var artist = musicAlbum.GetMusicArtist(new DtoOptions(false));
if (artist != null)
@@ -1363,7 +1359,7 @@ namespace Emby.Server.Implementations.Dto
return null;
}
- var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary);
+ var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToArray();
ImageDimensions size;
diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj
index abbaef26b8..ea44442687 100644
--- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj
+++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj
@@ -21,7 +21,7 @@
-
+
@@ -32,9 +32,9 @@
-
-
-
+
+
+
@@ -42,17 +42,19 @@
- netstandard2.0
+ netstandard2.1
false
+ true
-
- true
+
+
+ latest
-
+
diff --git a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs
index 8369f4f593..9c0db2cf5e 100644
--- a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs
+++ b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs
@@ -100,7 +100,7 @@ namespace Emby.Server.Implementations.EntryPoints
_lastProgressMessageTimes[item.Id] = DateTime.UtcNow;
var dict = new Dictionary();
- dict["ItemId"] = item.Id.ToString("N");
+ dict["ItemId"] = item.Id.ToString("N", CultureInfo.InvariantCulture);
dict["Progress"] = progress.ToString(CultureInfo.InvariantCulture);
try
@@ -116,7 +116,7 @@ namespace Emby.Server.Implementations.EntryPoints
foreach (var collectionFolder in collectionFolders)
{
var collectionFolderDict = new Dictionary();
- collectionFolderDict["ItemId"] = collectionFolder.Id.ToString("N");
+ collectionFolderDict["ItemId"] = collectionFolder.Id.ToString("N", CultureInfo.InvariantCulture);
collectionFolderDict["Progress"] = (collectionFolder.GetRefreshProgress() ?? 0).ToString(CultureInfo.InvariantCulture);
try
@@ -378,15 +378,15 @@ namespace Emby.Server.Implementations.EntryPoints
return new LibraryUpdateInfo
{
- ItemsAdded = itemsAdded.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N")).Distinct().ToArray(),
+ ItemsAdded = itemsAdded.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)).Distinct().ToArray(),
- ItemsUpdated = itemsUpdated.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N")).Distinct().ToArray(),
+ ItemsUpdated = itemsUpdated.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)).Distinct().ToArray(),
- ItemsRemoved = itemsRemoved.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user, true)).Select(i => i.Id.ToString("N")).Distinct().ToArray(),
+ ItemsRemoved = itemsRemoved.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user, true)).Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)).Distinct().ToArray(),
- FoldersAddedTo = foldersAddedTo.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N")).Distinct().ToArray(),
+ FoldersAddedTo = foldersAddedTo.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)).Distinct().ToArray(),
- FoldersRemovedFrom = foldersRemovedFrom.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N")).Distinct().ToArray(),
+ FoldersRemovedFrom = foldersRemovedFrom.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)).Distinct().ToArray(),
CollectionFolders = GetTopParentIds(newAndRemoved, allUserRootChildren).ToArray()
};
@@ -422,7 +422,7 @@ namespace Emby.Server.Implementations.EntryPoints
var collectionFolders = _libraryManager.GetCollectionFolders(item, allUserRootChildren);
foreach (var folder in allUserRootChildren)
{
- list.Add(folder.Id.ToString("N"));
+ list.Add(folder.Id.ToString("N", CultureInfo.InvariantCulture));
}
}
diff --git a/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs b/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs
index b7565adec4..b2328121e3 100644
--- a/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs
+++ b/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs
@@ -50,9 +50,7 @@ namespace Emby.Server.Implementations.EntryPoints
public async Task Execute(CancellationToken cancellationToken, IProgress progress)
{
- var users = _userManager.Users.ToList();
-
- foreach (var user in users)
+ foreach (var user in _userManager.Users)
{
cancellationToken.ThrowIfCancellationRequested();
diff --git a/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs b/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs
index 091dd6a45b..141e729584 100644
--- a/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs
+++ b/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Plugins;
@@ -134,7 +135,7 @@ namespace Emby.Server.Implementations.EntryPoints
/// The e.
void userManager_UserDeleted(object sender, GenericEventArgs e)
{
- SendMessageToUserSession(e.Argument, "UserDeleted", e.Argument.Id.ToString("N"));
+ SendMessageToUserSession(e.Argument, "UserDeleted", e.Argument.Id.ToString("N", CultureInfo.InvariantCulture));
}
void _userManager_UserPolicyUpdated(object sender, GenericEventArgs e)
diff --git a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs
index a5badaceec..bae3422ff6 100644
--- a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs
+++ b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -8,7 +9,6 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Entities;
-using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Session;
using Microsoft.Extensions.Logging;
@@ -125,12 +125,12 @@ namespace Emby.Server.Implementations.EntryPoints
.Select(i =>
{
var dto = _userDataManager.GetUserDataDto(i, user);
- dto.ItemId = i.Id.ToString("N");
+ dto.ItemId = i.Id.ToString("N", CultureInfo.InvariantCulture);
return dto;
})
.ToArray();
- var userIdString = userId.ToString("N");
+ var userIdString = userId.ToString("N", CultureInfo.InvariantCulture);
return new UserDataChangeInfo
{
diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs
index 331b5e29d7..0e6083773d 100644
--- a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs
+++ b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs
@@ -1,12 +1,10 @@
using System;
using System.Collections.Concurrent;
+using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
-using System.Net.Http.Headers;
-using System.Text;
-using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
@@ -19,7 +17,7 @@ using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.HttpClientManager
{
///
- /// Class HttpClientManager
+ /// Class HttpClientManager.
///
public class HttpClientManager : IHttpClient
{
@@ -44,19 +42,9 @@ namespace Emby.Server.Implementations.HttpClientManager
IFileSystem fileSystem,
Func defaultUserAgentFn)
{
- if (appPaths == null)
- {
- throw new ArgumentNullException(nameof(appPaths));
- }
-
- if (logger == null)
- {
- throw new ArgumentNullException(nameof(logger));
- }
-
- _logger = logger;
+ _logger = logger ?? throw new ArgumentNullException(nameof(logger));
_fileSystem = fileSystem;
- _appPaths = appPaths;
+ _appPaths = appPaths ?? throw new ArgumentNullException(nameof(appPaths));
_defaultUserAgentFn = defaultUserAgentFn;
}
@@ -95,7 +83,16 @@ namespace Emby.Server.Implementations.HttpClientManager
var request = new HttpRequestMessage(method, url);
- AddRequestHeaders(request, options);
+ foreach (var header in options.RequestHeaders)
+ {
+ request.Headers.TryAddWithoutValidation(header.Key, header.Value);
+ }
+
+ if (options.EnableDefaultUserAgent
+ && !request.Headers.TryGetValues(HeaderNames.UserAgent, out _))
+ {
+ request.Headers.Add(HeaderNames.UserAgent, _defaultUserAgentFn());
+ }
switch (options.DecompressionMethod)
{
@@ -117,7 +114,7 @@ namespace Emby.Server.Implementations.HttpClientManager
request.Headers.Add(HeaderNames.Connection, "Keep-Alive");
}
- //request.Headers.Add(HeaderNames.CacheControl, "no-cache");
+ // request.Headers.Add(HeaderNames.CacheControl, "no-cache");
/*
if (!string.IsNullOrWhiteSpace(userInfo))
@@ -133,26 +130,6 @@ namespace Emby.Server.Implementations.HttpClientManager
return request;
}
- private void AddRequestHeaders(HttpRequestMessage request, HttpRequestOptions options)
- {
- var hasUserAgent = false;
-
- foreach (var header in options.RequestHeaders)
- {
- if (string.Equals(header.Key, HeaderNames.UserAgent, StringComparison.OrdinalIgnoreCase))
- {
- hasUserAgent = true;
- }
-
- request.Headers.Add(header.Key, header.Value);
- }
-
- if (!hasUserAgent && options.EnableDefaultUserAgent)
- {
- request.Headers.Add(HeaderNames.UserAgent, _defaultUserAgentFn());
- }
- }
-
///
/// Gets the response internal.
///
@@ -195,7 +172,7 @@ namespace Emby.Server.Implementations.HttpClientManager
}
var url = options.Url;
- var urlHash = url.ToLowerInvariant().GetMD5().ToString("N");
+ var urlHash = url.ToUpperInvariant().GetMD5().ToString("N", CultureInfo.InvariantCulture);
var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
@@ -238,7 +215,13 @@ namespace Emby.Server.Implementations.HttpClientManager
{
Directory.CreateDirectory(Path.GetDirectoryName(responseCachePath));
- using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None, true))
+ using (var fileStream = new FileStream(
+ responseCachePath,
+ FileMode.Create,
+ FileAccess.Write,
+ FileShare.None,
+ StreamDefaults.DefaultFileStreamBufferSize,
+ true))
{
await response.Content.CopyToAsync(fileStream).ConfigureAwait(false);
@@ -277,16 +260,11 @@ namespace Emby.Server.Implementations.HttpClientManager
}
}
- if (options.LogRequest)
- {
- _logger.LogDebug("HttpClientManager {0}: {1}", httpMethod.ToString(), options.Url);
- }
-
options.CancellationToken.ThrowIfCancellationRequested();
var response = await client.SendAsync(
httpWebRequest,
- options.BufferContent ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead,
+ options.BufferContent || options.CacheMode == CacheMode.Unconditional ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead,
options.CancellationToken).ConfigureAwait(false);
await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
@@ -307,138 +285,6 @@ namespace Emby.Server.Implementations.HttpClientManager
public Task Post(HttpRequestOptions options)
=> SendAsync(options, HttpMethod.Post);
- ///
- /// Downloads the contents of a given url into a temporary location
- ///
- /// The options.
- /// Task{System.String}.
- public async Task GetTempFile(HttpRequestOptions options)
- {
- var response = await GetTempFileResponse(options).ConfigureAwait(false);
- return response.TempFilePath;
- }
-
- public async Task GetTempFileResponse(HttpRequestOptions options)
- {
- ValidateParams(options);
-
- Directory.CreateDirectory(_appPaths.TempDirectory);
-
- var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
-
- if (options.Progress == null)
- {
- throw new ArgumentException("Options did not have a Progress value.", nameof(options));
- }
-
- options.CancellationToken.ThrowIfCancellationRequested();
-
- var httpWebRequest = GetRequestMessage(options, HttpMethod.Get);
-
- options.Progress.Report(0);
-
- if (options.LogRequest)
- {
- _logger.LogDebug("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
- }
-
- var client = GetHttpClient(options.Url);
-
- try
- {
- options.CancellationToken.ThrowIfCancellationRequested();
-
- using (var response = (await client.SendAsync(httpWebRequest, options.CancellationToken).ConfigureAwait(false)))
- {
- await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
-
- options.CancellationToken.ThrowIfCancellationRequested();
-
- using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
- using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
- {
- await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
- }
-
- options.Progress.Report(100);
-
- var responseInfo = new HttpResponseInfo(response.Headers, response.Content.Headers)
- {
- TempFilePath = tempFile,
- StatusCode = response.StatusCode,
- ContentType = response.Content.Headers.ContentType?.MediaType,
- ContentLength = response.Content.Headers.ContentLength
- };
-
- return responseInfo;
- }
- }
- catch (Exception ex)
- {
- if (File.Exists(tempFile))
- {
- File.Delete(tempFile);
- }
-
- throw GetException(ex, options);
- }
- }
-
- private Exception GetException(Exception ex, HttpRequestOptions options)
- {
- if (ex is HttpException)
- {
- return ex;
- }
-
- var webException = ex as WebException
- ?? ex.InnerException as WebException;
-
- if (webException != null)
- {
- if (options.LogErrors)
- {
- _logger.LogError(webException, "Error {Status} getting response from {Url}", webException.Status, options.Url);
- }
-
- var exception = new HttpException(webException.Message, webException);
-
- using (var response = webException.Response as HttpWebResponse)
- {
- if (response != null)
- {
- exception.StatusCode = response.StatusCode;
- }
- }
-
- if (!exception.StatusCode.HasValue)
- {
- if (webException.Status == WebExceptionStatus.NameResolutionFailure ||
- webException.Status == WebExceptionStatus.ConnectFailure)
- {
- exception.IsTimedOut = true;
- }
- }
-
- return exception;
- }
-
- var operationCanceledException = ex as OperationCanceledException
- ?? ex.InnerException as OperationCanceledException;
-
- if (operationCanceledException != null)
- {
- return GetCancellationException(options, options.CancellationToken, operationCanceledException);
- }
-
- if (options.LogErrors)
- {
- _logger.LogError(ex, "Error getting response from {Url}", options.Url);
- }
-
- return ex;
- }
-
private void ValidateParams(HttpRequestOptions options)
{
if (string.IsNullOrEmpty(options.Url))
@@ -470,35 +316,6 @@ namespace Emby.Server.Implementations.HttpClientManager
return url;
}
- ///
- /// Throws the cancellation exception.
- ///
- /// The options.
- /// The cancellation token.
- /// The exception.
- /// Exception.
- private Exception GetCancellationException(HttpRequestOptions options, CancellationToken cancellationToken, OperationCanceledException exception)
- {
- // If the HttpClient's timeout is reached, it will cancel the Task internally
- if (!cancellationToken.IsCancellationRequested)
- {
- var msg = string.Format("Connection to {0} timed out", options.Url);
-
- if (options.LogErrors)
- {
- _logger.LogError(msg);
- }
-
- // Throw an HttpException so that the caller doesn't think it was cancelled by user code
- return new HttpException(msg, exception)
- {
- IsTimedOut = true
- };
- }
-
- return exception;
- }
-
private async Task EnsureSuccessStatusCode(HttpResponseMessage response, HttpRequestOptions options)
{
if (response.IsSuccessStatusCode)
@@ -506,8 +323,11 @@ namespace Emby.Server.Implementations.HttpClientManager
return;
}
- var msg = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
- _logger.LogError("HTTP request failed with message: {Message}", msg);
+ if (options.LogErrorResponseBody)
+ {
+ var msg = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
+ _logger.LogError("HTTP request failed with message: {Message}", msg);
+ }
throw new HttpException(response.ReasonPhrase)
{
diff --git a/Emby.Server.Implementations/HttpServer/FileWriter.cs b/Emby.Server.Implementations/HttpServer/FileWriter.cs
index ec41cc0a91..2c7e81361d 100644
--- a/Emby.Server.Implementations/HttpServer/FileWriter.cs
+++ b/Emby.Server.Implementations/HttpServer/FileWriter.cs
@@ -1,50 +1,43 @@
using System;
using System.Collections.Generic;
using System.Globalization;
+using System.IO;
using System.Linq;
using System.Net;
+using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
-using Emby.Server.Implementations.IO;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Services;
using Microsoft.Extensions.Logging;
+using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.HttpServer
{
public class FileWriter : IHttpResult
{
- private readonly IStreamHelper _streamHelper;
- private ILogger Logger { get; set; }
- private readonly IFileSystem _fileSystem;
-
- private string RangeHeader { get; set; }
- private bool IsHeadRequest { get; set; }
-
- private long RangeStart { get; set; }
- private long RangeEnd { get; set; }
- private long RangeLength { get; set; }
- public long TotalContentLength { get; set; }
+ private static readonly CultureInfo UsCulture = CultureInfo.ReadOnly(new CultureInfo("en-US"));
- public Action OnComplete { get; set; }
- public Action OnError { get; set; }
- private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
- public List Cookies { get; private set; }
+ private static readonly string[] _skipLogExtensions = {
+ ".js",
+ ".html",
+ ".css"
+ };
- public FileShareMode FileShare { get; set; }
+ private readonly IStreamHelper _streamHelper;
+ private readonly ILogger _logger;
+ private readonly IFileSystem _fileSystem;
///
/// The _options
///
private readonly IDictionary _options = new Dictionary();
+
///
- /// Gets the options.
+ /// The _requested ranges
///
- /// The options.
- public IDictionary Headers => _options;
-
- public string Path { get; set; }
+ private List> _requestedRanges;
public FileWriter(string path, string contentType, string rangeHeader, ILogger logger, IFileSystem fileSystem, IStreamHelper streamHelper)
{
@@ -57,7 +50,7 @@ namespace Emby.Server.Implementations.HttpServer
_fileSystem = fileSystem;
Path = path;
- Logger = logger;
+ _logger = logger;
RangeHeader = rangeHeader;
Headers[HeaderNames.ContentType] = contentType;
@@ -80,39 +73,34 @@ namespace Emby.Server.Implementations.HttpServer
Cookies = new List();
}
- ///
- /// Sets the range values.
- ///
- private void SetRangeValues()
- {
- var requestedRange = RequestedRanges[0];
+ private string RangeHeader { get; set; }
- // If the requested range is "0-", we can optimize by just doing a stream copy
- if (!requestedRange.Value.HasValue)
- {
- RangeEnd = TotalContentLength - 1;
- }
- else
- {
- RangeEnd = requestedRange.Value.Value;
- }
+ private bool IsHeadRequest { get; set; }
- RangeStart = requestedRange.Key;
- RangeLength = 1 + RangeEnd - RangeStart;
+ private long RangeStart { get; set; }
- // Content-Length is the length of what we're serving, not the original content
- var lengthString = RangeLength.ToString(CultureInfo.InvariantCulture);
- Headers[HeaderNames.ContentLength] = lengthString;
- var rangeString = $"bytes {RangeStart}-{RangeEnd}/{TotalContentLength}";
- Headers[HeaderNames.ContentRange] = rangeString;
+ private long RangeEnd { get; set; }
- Logger.LogDebug("Setting range response values for {0}. RangeRequest: {1} Content-Length: {2}, Content-Range: {3}", Path, RangeHeader, lengthString, rangeString);
- }
+ private long RangeLength { get; set; }
+
+ public long TotalContentLength { get; set; }
+
+ public Action OnComplete { get; set; }
+
+ public Action OnError { get; set; }
+
+ public List Cookies { get; private set; }
+
+ public FileShareMode FileShare { get; set; }
///
- /// The _requested ranges
+ /// Gets the options.
///
- private List> _requestedRanges;
+ /// The options.
+ public IDictionary Headers => _options;
+
+ public string Path { get; set; }
+
///
/// Gets the requested ranges.
///
@@ -139,6 +127,7 @@ namespace Emby.Server.Implementations.HttpServer
{
start = long.Parse(vals[0], UsCulture);
}
+
if (!string.IsNullOrEmpty(vals[1]))
{
end = long.Parse(vals[1], UsCulture);
@@ -152,13 +141,50 @@ namespace Emby.Server.Implementations.HttpServer
}
}
- private static readonly string[] SkipLogExtensions = {
- ".js",
- ".html",
- ".css"
- };
+ public string ContentType { get; set; }
+
+ public IRequest RequestContext { get; set; }
+
+ public object Response { get; set; }
+
+ public int Status { get; set; }
+
+ public HttpStatusCode StatusCode
+ {
+ get => (HttpStatusCode)Status;
+ set => Status = (int)value;
+ }
+
+ ///
+ /// Sets the range values.
+ ///
+ private void SetRangeValues()
+ {
+ var requestedRange = RequestedRanges[0];
+
+ // If the requested range is "0-", we can optimize by just doing a stream copy
+ if (!requestedRange.Value.HasValue)
+ {
+ RangeEnd = TotalContentLength - 1;
+ }
+ else
+ {
+ RangeEnd = requestedRange.Value.Value;
+ }
+
+ RangeStart = requestedRange.Key;
+ RangeLength = 1 + RangeEnd - RangeStart;
+
+ // Content-Length is the length of what we're serving, not the original content
+ var lengthString = RangeLength.ToString(CultureInfo.InvariantCulture);
+ Headers[HeaderNames.ContentLength] = lengthString;
+ var rangeString = $"bytes {RangeStart}-{RangeEnd}/{TotalContentLength}";
+ Headers[HeaderNames.ContentRange] = rangeString;
- public async Task WriteToAsync(IResponse response, CancellationToken cancellationToken)
+ _logger.LogDebug("Setting range response values for {0}. RangeRequest: {1} Content-Length: {2}, Content-Range: {3}", Path, RangeHeader, lengthString, rangeString);
+ }
+
+ public async Task WriteToAsync(HttpResponse response, CancellationToken cancellationToken)
{
try
{
@@ -176,16 +202,16 @@ namespace Emby.Server.Implementations.HttpServer
{
var extension = System.IO.Path.GetExtension(path);
- if (extension == null || !SkipLogExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
+ if (extension == null || !_skipLogExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
{
- Logger.LogDebug("Transmit file {0}", path);
+ _logger.LogDebug("Transmit file {0}", path);
}
offset = 0;
count = 0;
}
- await response.TransmitFile(path, offset, count, FileShare, _fileSystem, _streamHelper, cancellationToken).ConfigureAwait(false);
+ await TransmitFile(response.Body, path, offset, count, FileShare, cancellationToken).ConfigureAwait(false);
}
finally
{
@@ -193,18 +219,32 @@ namespace Emby.Server.Implementations.HttpServer
}
}
- public string ContentType { get; set; }
-
- public IRequest RequestContext { get; set; }
+ public async Task TransmitFile(Stream stream, string path, long offset, long count, FileShareMode fileShareMode, CancellationToken cancellationToken)
+ {
+ var fileOpenOptions = FileOpenOptions.SequentialScan;
- public object Response { get; set; }
+ // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
+ if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
+ {
+ fileOpenOptions |= FileOpenOptions.Asynchronous;
+ }
- public int Status { get; set; }
+ using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShareMode, fileOpenOptions))
+ {
+ if (offset > 0)
+ {
+ fs.Position = offset;
+ }
- public HttpStatusCode StatusCode
- {
- get => (HttpStatusCode)Status;
- set => Status = (int)value;
+ if (count > 0)
+ {
+ await _streamHelper.CopyToAsync(fs, stream, count, cancellationToken).ConfigureAwait(false);
+ }
+ else
+ {
+ await fs.CopyToAsync(stream, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false);
+ }
+ }
}
}
}
diff --git a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs
index d8938964fa..e4f98acb9b 100644
--- a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs
+++ b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs
@@ -5,9 +5,9 @@ using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
-using System.Text;
using System.Threading;
using System.Threading.Tasks;
+using Emby.Server.Implementations.Configuration;
using Emby.Server.Implementations.Net;
using Emby.Server.Implementations.Services;
using MediaBrowser.Common.Extensions;
@@ -30,11 +30,7 @@ namespace Emby.Server.Implementations.HttpServer
{
public class HttpListenerHost : IHttpServer, IDisposable
{
- private string DefaultRedirectPath { get; set; }
- public string[] UrlPrefixes { get; private set; }
-
- public event EventHandler> WebSocketConnected;
-
+ private readonly ILogger _logger;
private readonly IServerConfigurationManager _config;
private readonly INetworkManager _networkManager;
private readonly IServerApplicationHost _appHost;
@@ -42,18 +38,16 @@ namespace Emby.Server.Implementations.HttpServer
private readonly IXmlSerializer _xmlSerializer;
private readonly IHttpListener _socketListener;
private readonly Func> _funcParseFn;
-
- public Action[] ResponseFilters { get; set; }
-
+ private readonly string _defaultRedirectPath;
+ private readonly string _baseUrlPrefix;
private readonly Dictionary ServiceOperationsMap = new Dictionary();
- public static HttpListenerHost Instance { get; protected set; }
-
private IWebSocketListener[] _webSocketListeners = Array.Empty();
private readonly List _webSocketConnections = new List();
+ private bool _disposed = false;
public HttpListenerHost(
IServerApplicationHost applicationHost,
- ILoggerFactory loggerFactory,
+ ILogger logger,
IServerConfigurationManager config,
IConfiguration configuration,
INetworkManager networkManager,
@@ -62,9 +56,10 @@ namespace Emby.Server.Implementations.HttpServer
IHttpListener socketListener)
{
_appHost = applicationHost;
- Logger = loggerFactory.CreateLogger("HttpServer");
+ _logger = logger;
_config = config;
- DefaultRedirectPath = configuration["HttpListenerHost:DefaultRedirectPath"];
+ _defaultRedirectPath = configuration["HttpListenerHost:DefaultRedirectPath"];
+ _baseUrlPrefix = _config.Configuration.BaseUrl;
_networkManager = networkManager;
_jsonSerializer = jsonSerializer;
_xmlSerializer = xmlSerializer;
@@ -74,26 +69,48 @@ namespace Emby.Server.Implementations.HttpServer
_funcParseFn = t => s => JsvReader.GetParseFn(t)(s);
Instance = this;
- ResponseFilters = Array.Empty>();
+ ResponseFilters = Array.Empty>();
}
+ public Action[] ResponseFilters { get; set; }
+
+ public static HttpListenerHost Instance { get; protected set; }
+
+ public string[] UrlPrefixes { get; private set; }
+
public string GlobalResponse { get; set; }
- protected ILogger Logger { get; }
+ public ServiceController ServiceController { get; private set; }
+
+ public event EventHandler> WebSocketConnected;
public object CreateInstance(Type type)
{
return _appHost.CreateInstance(type);
}
+ private static string NormalizeUrlPath(string path)
+ {
+ if (path.StartsWith("/"))
+ {
+ // If the path begins with a leading slash, just return it as-is
+ return path;
+ }
+ else
+ {
+ // If the path does not begin with a leading slash, append one for consistency
+ return "/" + path;
+ }
+ }
+
///
/// Applies the request filters. Returns whether or not the request has been handled
/// and no more processing should be done.
///
///
- public void ApplyRequestFilters(IRequest req, IResponse res, object requestDto)
+ public void ApplyRequestFilters(IRequest req, HttpResponse res, object requestDto)
{
- //Exec all RequestFilter attributes with Priority < 0
+ // Exec all RequestFilter attributes with Priority < 0
var attributes = GetRequestFilterAttributes(requestDto.GetType());
int count = attributes.Count;
@@ -104,7 +121,7 @@ namespace Emby.Server.Implementations.HttpServer
attribute.RequestFilter(req, res, requestDto);
}
- //Exec remaining RequestFilter attributes with Priority >= 0
+ // Exec remaining RequestFilter attributes with Priority >= 0
for (; i < count && attributes[i].Priority >= 0; i++)
{
var attribute = attributes[i];
@@ -145,7 +162,7 @@ namespace Emby.Server.Implementations.HttpServer
return;
}
- var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, Logger)
+ var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger)
{
OnReceive = ProcessWebSocketMessageReceived,
Url = e.Url,
@@ -207,7 +224,7 @@ namespace Emby.Server.Implementations.HttpServer
}
}
- private async Task ErrorHandler(Exception ex, IRequest httpReq, bool logExceptionStackTrace, bool logExceptionMessage)
+ private async Task ErrorHandler(Exception ex, IRequest httpReq, bool logExceptionStackTrace)
{
try
{
@@ -215,16 +232,16 @@ namespace Emby.Server.Implementations.HttpServer
if (logExceptionStackTrace)
{
- Logger.LogError(ex, "Error processing request");
+ _logger.LogError(ex, "Error processing request");
}
- else if (logExceptionMessage)
+ else
{
- Logger.LogError(ex.Message);
+ _logger.LogError("Error processing request: {Message}", ex.Message);
}
var httpRes = httpReq.Response;
- if (httpRes.OriginalResponse.HasStarted)
+ if (httpRes.HasStarted)
{
return;
}
@@ -232,12 +249,14 @@ namespace Emby.Server.Implementations.HttpServer
var statusCode = GetStatusCode(ex);
httpRes.StatusCode = statusCode;
- httpRes.ContentType = "text/html";
- await Write(httpRes, NormalizeExceptionMessage(ex.Message)).ConfigureAwait(false);
+ var errContent = NormalizeExceptionMessage(ex.Message);
+ httpRes.ContentType = "text/plain";
+ httpRes.ContentLength = errContent.Length;
+ await httpRes.WriteAsync(errContent).ConfigureAwait(false);
}
catch (Exception errorEx)
{
- Logger.LogError(errorEx, "Error this.ProcessRequest(context)(Exception while writing error to the response)");
+ _logger.LogError(errorEx, "Error this.ProcessRequest(context)(Exception while writing error to the response)");
}
}
@@ -275,9 +294,9 @@ namespace Emby.Server.Implementations.HttpServer
{
connection.Dispose();
}
- catch
+ catch (Exception ex)
{
-
+ _logger.LogError(ex, "Error disposing connection");
}
}
}
@@ -431,7 +450,7 @@ namespace Emby.Server.Implementations.HttpServer
{
httpRes.StatusCode = 503;
httpRes.ContentType = "text/plain";
- await Write(httpRes, "Server shutting down").ConfigureAwait(false);
+ await httpRes.WriteAsync("Server shutting down", cancellationToken).ConfigureAwait(false);
return;
}
@@ -439,7 +458,7 @@ namespace Emby.Server.Implementations.HttpServer
{
httpRes.StatusCode = 400;
httpRes.ContentType = "text/plain";
- await Write(httpRes, "Invalid host").ConfigureAwait(false);
+ await httpRes.WriteAsync("Invalid host", cancellationToken).ConfigureAwait(false);
return;
}
@@ -447,7 +466,7 @@ namespace Emby.Server.Implementations.HttpServer
{
httpRes.StatusCode = 403;
httpRes.ContentType = "text/plain";
- await Write(httpRes, "Forbidden").ConfigureAwait(false);
+ await httpRes.WriteAsync("Forbidden", cancellationToken).ConfigureAwait(false);
return;
}
@@ -460,101 +479,28 @@ namespace Emby.Server.Implementations.HttpServer
if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
{
httpRes.StatusCode = 200;
- httpRes.AddHeader("Access-Control-Allow-Origin", "*");
- httpRes.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
- httpRes.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization");
+ httpRes.Headers.Add("Access-Control-Allow-Origin", "*");
+ httpRes.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
+ httpRes.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization");
httpRes.ContentType = "text/plain";
- await Write(httpRes, string.Empty).ConfigureAwait(false);
+ await httpRes.WriteAsync(string.Empty, cancellationToken).ConfigureAwait(false);
return;
}
urlToLog = GetUrlToLog(urlString);
- Logger.LogDebug("HTTP {HttpMethod} {Url} UserAgent: {UserAgent} \nHeaders: {@Headers}", urlToLog, httpReq.UserAgent ?? string.Empty, httpReq.HttpMethod, httpReq.Headers);
-
- if (string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase))
- {
- RedirectToUrl(httpRes, DefaultRedirectPath);
- return;
- }
-
- if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase) ||
- string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase))
- {
- RedirectToUrl(httpRes, "emby/" + DefaultRedirectPath);
- return;
- }
-
- if (localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1)
- {
- httpRes.StatusCode = 200;
- httpRes.ContentType = "text/html";
- var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
- .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);
-
- if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
- {
- await Write(httpRes,
- "Emby Please update your Emby bookmark to " + newUrl + " ").ConfigureAwait(false);
- return;
- }
- }
-
- if (localPath.IndexOf("dashboard/", StringComparison.OrdinalIgnoreCase) != -1 &&
- localPath.IndexOf("web/dashboard", StringComparison.OrdinalIgnoreCase) == -1)
- {
- httpRes.StatusCode = 200;
- httpRes.ContentType = "text/html";
- var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase)
- .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase);
-
- if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase))
- {
- await Write(httpRes,
- "Emby Please update your Emby bookmark to " + newUrl + " ").ConfigureAwait(false);
- return;
- }
- }
-
- if (string.Equals(localPath, "/web", StringComparison.OrdinalIgnoreCase))
- {
- RedirectToUrl(httpRes, DefaultRedirectPath);
- return;
- }
-
- if (string.Equals(localPath, "/web/", StringComparison.OrdinalIgnoreCase))
- {
- RedirectToUrl(httpRes, "../" + DefaultRedirectPath);
- return;
- }
- if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(localPath, _baseUrlPrefix + "/", StringComparison.OrdinalIgnoreCase)
+ || string.Equals(localPath, _baseUrlPrefix, StringComparison.OrdinalIgnoreCase)
+ || string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase)
+ || string.IsNullOrEmpty(localPath)
+ || !localPath.StartsWith(_baseUrlPrefix))
{
- RedirectToUrl(httpRes, DefaultRedirectPath);
+ // Always redirect back to the default path if the base prefix is invalid or missing
+ _logger.LogDebug("Normalizing a URL at {0}", localPath);
+ httpRes.Redirect(_baseUrlPrefix + "/" + _defaultRedirectPath);
return;
}
- if (string.IsNullOrEmpty(localPath))
- {
- RedirectToUrl(httpRes, "/" + DefaultRedirectPath);
- return;
- }
-
- if (!string.Equals(httpReq.QueryString["r"], "0", StringComparison.OrdinalIgnoreCase))
- {
- if (localPath.EndsWith("web/dashboard.html", StringComparison.OrdinalIgnoreCase))
- {
- RedirectToUrl(httpRes, "index.html#!/dashboard.html");
- }
-
- if (localPath.EndsWith("web/home.html", StringComparison.OrdinalIgnoreCase))
- {
- RedirectToUrl(httpRes, "index.html");
- }
- }
-
if (!string.IsNullOrEmpty(GlobalResponse))
{
// We don't want the address pings in ApplicationHost to fail
@@ -562,35 +508,34 @@ namespace Emby.Server.Implementations.HttpServer
{
httpRes.StatusCode = 503;
httpRes.ContentType = "text/html";
- await Write(httpRes, GlobalResponse).ConfigureAwait(false);
+ await httpRes.WriteAsync(GlobalResponse, cancellationToken).ConfigureAwait(false);
return;
}
}
var handler = GetServiceHandler(httpReq);
-
if (handler != null)
{
- await handler.ProcessRequestAsync(this, httpReq, httpRes, Logger, cancellationToken).ConfigureAwait(false);
+ await handler.ProcessRequestAsync(this, httpReq, httpRes, _logger, cancellationToken).ConfigureAwait(false);
}
else
{
- await ErrorHandler(new FileNotFoundException(), httpReq, false, false).ConfigureAwait(false);
+ await ErrorHandler(new FileNotFoundException(), httpReq, false).ConfigureAwait(false);
}
}
catch (Exception ex) when (ex is SocketException || ex is IOException || ex is OperationCanceledException)
{
- await ErrorHandler(ex, httpReq, false, false).ConfigureAwait(false);
+ await ErrorHandler(ex, httpReq, false).ConfigureAwait(false);
}
catch (SecurityException ex)
{
- await ErrorHandler(ex, httpReq, false, true).ConfigureAwait(false);
+ await ErrorHandler(ex, httpReq, false).ConfigureAwait(false);
}
catch (Exception ex)
{
var logException = !string.Equals(ex.GetType().Name, "SocketException", StringComparison.OrdinalIgnoreCase);
- await ErrorHandler(ex, httpReq, logException, false).ConfigureAwait(false);
+ await ErrorHandler(ex, httpReq, logException).ConfigureAwait(false);
}
finally
{
@@ -598,11 +543,7 @@ namespace Emby.Server.Implementations.HttpServer
var elapsed = stopWatch.Elapsed;
if (elapsed.TotalMilliseconds > 500)
{
- Logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
- }
- else
- {
- Logger.LogDebug("HTTP Response {StatusCode} to {RemoteIp}. Time: {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
+ _logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
}
}
}
@@ -619,18 +560,11 @@ namespace Emby.Server.Implementations.HttpServer
return new ServiceHandler(restPath, contentType);
}
- Logger.LogError("Could not find handler for {PathInfo}", pathInfo);
+ _logger.LogError("Could not find handler for {PathInfo}", pathInfo);
return null;
}
- private static Task Write(IResponse response, string text)
- {
- var bOutput = Encoding.UTF8.GetBytes(text);
- response.OriginalResponse.ContentLength = bOutput.Length;
- return response.OutputStream.WriteAsync(bOutput, 0, bOutput.Length);
- }
-
- private void RedirectToSecureUrl(IHttpRequest httpReq, IResponse httpRes, string url)
+ private void RedirectToSecureUrl(IHttpRequest httpReq, HttpResponse httpRes, string url)
{
if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
{
@@ -640,23 +574,11 @@ namespace Emby.Server.Implementations.HttpServer
Scheme = "https"
};
url = builder.Uri.ToString();
-
- RedirectToUrl(httpRes, url);
- }
- else
- {
- RedirectToUrl(httpRes, url);
}
- }
- public static void RedirectToUrl(IResponse httpRes, string url)
- {
- httpRes.StatusCode = 302;
- httpRes.AddHeader("Location", url);
+ httpRes.Redirect(url);
}
- public ServiceController ServiceController { get; private set; }
-
///
/// Adds the rest handlers.
///
@@ -672,9 +594,9 @@ namespace Emby.Server.Implementations.HttpServer
var types = services.Select(r => r.GetType());
ServiceController.Init(this, types);
- ResponseFilters = new Action[]
+ ResponseFilters = new Action[]
{
- new ResponseFilter(Logger).FilterResponse
+ new ResponseFilter(_logger).FilterResponse
};
}
@@ -685,22 +607,21 @@ namespace Emby.Server.Implementations.HttpServer
foreach (var route in clone)
{
- routes.Add(new RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
+ routes.Add(new RouteAttribute(NormalizeCustomRoutePath(route.Path), route.Verbs)
{
Notes = route.Notes,
Priority = route.Priority,
Summary = route.Summary
});
- routes.Add(new RouteAttribute(NormalizeMediaBrowserRoutePath(route.Path), route.Verbs)
+ routes.Add(new RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
{
Notes = route.Notes,
Priority = route.Priority,
Summary = route.Summary
});
- // needed because apps add /emby, and some users also add /emby, thereby double prefixing
- routes.Add(new RouteAttribute(DoubleNormalizeEmbyRoutePath(route.Path), route.Verbs)
+ routes.Add(new RouteAttribute(NormalizeMediaBrowserRoutePath(route.Path), route.Verbs)
{
Notes = route.Notes,
Priority = route.Priority,
@@ -741,55 +662,41 @@ namespace Emby.Server.Implementations.HttpServer
return _socketListener.ProcessWebSocketRequest(context);
}
- //TODO Add Jellyfin Route Path Normalizer
- private static string NormalizeEmbyRoutePath(string path)
+ private string NormalizeEmbyRoutePath(string path)
{
- if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
- {
- return "/emby" + path;
- }
-
- return "emby/" + path;
+ _logger.LogDebug("Normalizing /emby route");
+ return _baseUrlPrefix + "/emby" + NormalizeUrlPath(path);
}
- private static string NormalizeMediaBrowserRoutePath(string path)
+ private string NormalizeMediaBrowserRoutePath(string path)
{
- if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
- {
- return "/mediabrowser" + path;
- }
-
- return "mediabrowser/" + path;
+ _logger.LogDebug("Normalizing /mediabrowser route");
+ return _baseUrlPrefix + "/mediabrowser" + NormalizeUrlPath(path);
}
- private static string DoubleNormalizeEmbyRoutePath(string path)
+ private string NormalizeCustomRoutePath(string path)
{
- if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
- {
- return "/emby/emby" + path;
- }
-
- return "emby/emby/" + path;
+ _logger.LogDebug("Normalizing custom route {0}", path);
+ return _baseUrlPrefix + NormalizeUrlPath(path);
}
- private bool _disposed;
- private readonly object _disposeLock = new object();
+ ///
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
- lock (_disposeLock)
+ if (disposing)
{
- if (_disposed) return;
-
- _disposed = true;
-
- if (disposing)
- {
- Stop();
- }
+ Stop();
}
+
+ _disposed = true;
}
///
@@ -803,7 +710,7 @@ namespace Emby.Server.Implementations.HttpServer
return Task.CompletedTask;
}
- Logger.LogDebug("Websocket message received: {0}", result.MessageType);
+ _logger.LogDebug("Websocket message received: {0}", result.MessageType);
IEnumerable GetTasks()
{
@@ -815,10 +722,5 @@ namespace Emby.Server.Implementations.HttpServer
return Task.WhenAll(GetTasks());
}
-
- public void Dispose()
- {
- Dispose(true);
- }
}
}
diff --git a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs
index 08f4247577..3e731366e2 100644
--- a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs
+++ b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs
@@ -2,6 +2,7 @@ using System;
using System.Globalization;
using System.Text;
using MediaBrowser.Model.Services;
+using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
@@ -9,7 +10,7 @@ namespace Emby.Server.Implementations.HttpServer
{
public class ResponseFilter
{
- private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
+ private static readonly CultureInfo _usCulture = CultureInfo.ReadOnly(new CultureInfo("en-US"));
private readonly ILogger _logger;
public ResponseFilter(ILogger logger)
@@ -23,12 +24,12 @@ namespace Emby.Server.Implementations.HttpServer
/// The req.
/// The res.
/// The dto.
- public void FilterResponse(IRequest req, IResponse res, object dto)
+ public void FilterResponse(IRequest req, HttpResponse res, object dto)
{
// Try to prevent compatibility view
- res.AddHeader("Access-Control-Allow-Headers", "Accept, Accept-Language, Authorization, Cache-Control, Content-Disposition, Content-Encoding, Content-Language, Content-Length, Content-MD5, Content-Range, Content-Type, Date, Host, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, Origin, OriginToken, Pragma, Range, Slug, Transfer-Encoding, Want-Digest, X-MediaBrowser-Token, X-Emby-Authorization");
- res.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
- res.AddHeader("Access-Control-Allow-Origin", "*");
+ res.Headers.Add("Access-Control-Allow-Headers", "Accept, Accept-Language, Authorization, Cache-Control, Content-Disposition, Content-Encoding, Content-Language, Content-Length, Content-MD5, Content-Range, Content-Type, Date, Host, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, Origin, OriginToken, Pragma, Range, Slug, Transfer-Encoding, Want-Digest, X-MediaBrowser-Token, X-Emby-Authorization");
+ res.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
+ res.Headers.Add("Access-Control-Allow-Origin", "*");
if (dto is Exception exception)
{
@@ -39,7 +40,7 @@ namespace Emby.Server.Implementations.HttpServer
var error = exception.Message.Replace(Environment.NewLine, " ");
error = RemoveControlCharacters(error);
- res.AddHeader("X-Application-Error-Code", error);
+ res.Headers.Add("X-Application-Error-Code", error);
}
}
@@ -54,12 +55,11 @@ namespace Emby.Server.Implementations.HttpServer
if (hasHeaders.Headers.TryGetValue(HeaderNames.ContentLength, out string contentLength)
&& !string.IsNullOrEmpty(contentLength))
{
- var length = long.Parse(contentLength, UsCulture);
+ var length = long.Parse(contentLength, _usCulture);
if (length > 0)
{
- res.OriginalResponse.ContentLength = length;
- res.SendChunked = false;
+ res.ContentLength = length;
}
}
}
@@ -72,9 +72,12 @@ namespace Emby.Server.Implementations.HttpServer
/// System.String.
public static string RemoveControlCharacters(string inString)
{
- if (inString == null) return null;
+ if (inString == null)
+ {
+ return null;
+ }
- var newString = new StringBuilder();
+ var newString = new StringBuilder(inString.Length);
foreach (var ch in inString)
{
@@ -83,6 +86,7 @@ namespace Emby.Server.Implementations.HttpServer
newString.Append(ch);
}
}
+
return newString.ToString();
}
}
diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs
index 1027883ed9..93a61fe67a 100644
--- a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs
+++ b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs
@@ -3,7 +3,6 @@ using System.Linq;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
-using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Security;
using MediaBrowser.Controller.Session;
@@ -13,28 +12,23 @@ namespace Emby.Server.Implementations.HttpServer.Security
{
public class AuthService : IAuthService
{
+ private readonly IAuthorizationContext _authorizationContext;
+ private readonly ISessionManager _sessionManager;
private readonly IServerConfigurationManager _config;
+ private readonly INetworkManager _networkManager;
- public AuthService(IUserManager userManager, IAuthorizationContext authorizationContext, IServerConfigurationManager config, ISessionManager sessionManager, INetworkManager networkManager)
+ public AuthService(
+ IAuthorizationContext authorizationContext,
+ IServerConfigurationManager config,
+ ISessionManager sessionManager,
+ INetworkManager networkManager)
{
- AuthorizationContext = authorizationContext;
+ _authorizationContext = authorizationContext;
_config = config;
- SessionManager = sessionManager;
- UserManager = userManager;
- NetworkManager = networkManager;
+ _sessionManager = sessionManager;
+ _networkManager = networkManager;
}
- public IUserManager UserManager { get; private set; }
- public IAuthorizationContext AuthorizationContext { get; private set; }
- public ISessionManager SessionManager { get; private set; }
- public INetworkManager NetworkManager { get; private set; }
-
- ///
- /// Redirect the client to a specific URL if authentication failed.
- /// If this property is null, simply `401 Unauthorized` is returned.
- ///
- public string HtmlRedirect { get; set; }
-
public void Authenticate(IRequest request, IAuthenticationAttributes authAttribtues)
{
ValidateUser(request, authAttribtues);
@@ -43,7 +37,7 @@ namespace Emby.Server.Implementations.HttpServer.Security
private void ValidateUser(IRequest request, IAuthenticationAttributes authAttribtues)
{
// This code is executed before the service
- var auth = AuthorizationContext.GetAuthorizationInfo(request);
+ var auth = _authorizationContext.GetAuthorizationInfo(request);
if (!IsExemptFromAuthenticationToken(authAttribtues, request))
{
@@ -57,7 +51,7 @@ namespace Emby.Server.Implementations.HttpServer.Security
var user = auth.User;
- if (user == null & !auth.UserId.Equals(Guid.Empty))
+ if (user == null && auth.UserId != Guid.Empty)
{
throw new SecurityException("User with Id " + auth.UserId + " not found");
}
@@ -80,7 +74,7 @@ namespace Emby.Server.Implementations.HttpServer.Security
!string.IsNullOrEmpty(auth.Client) &&
!string.IsNullOrEmpty(auth.Device))
{
- SessionManager.LogSessionActivity(auth.Client,
+ _sessionManager.LogSessionActivity(auth.Client,
auth.Version,
auth.DeviceId,
auth.Device,
@@ -89,7 +83,9 @@ namespace Emby.Server.Implementations.HttpServer.Security
}
}
- private void ValidateUserAccess(User user, IRequest request,
+ private void ValidateUserAccess(
+ User user,
+ IRequest request,
IAuthenticationAttributes authAttribtues,
AuthorizationInfo auth)
{
@@ -101,7 +97,7 @@ namespace Emby.Server.Implementations.HttpServer.Security
};
}
- if (!user.Policy.EnableRemoteAccess && !NetworkManager.IsInLocalNetwork(request.RemoteIp))
+ if (!user.Policy.EnableRemoteAccess && !_networkManager.IsInLocalNetwork(request.RemoteIp))
{
throw new SecurityException("User account has been disabled.")
{
@@ -109,11 +105,11 @@ namespace Emby.Server.Implementations.HttpServer.Security
};
}
- if (!user.Policy.IsAdministrator &&
- !authAttribtues.EscapeParentalControl &&
- !user.IsParentalScheduleAllowed())
+ if (!user.Policy.IsAdministrator
+ && !authAttribtues.EscapeParentalControl
+ && !user.IsParentalScheduleAllowed())
{
- request.Response.AddHeader("X-Application-Error-Code", "ParentalControl");
+ request.Response.Headers.Add("X-Application-Error-Code", "ParentalControl");
throw new SecurityException("This user account is not allowed access at this time.")
{
@@ -183,6 +179,7 @@ namespace Emby.Server.Implementations.HttpServer.Security
};
}
}
+
if (roles.Contains("delete", StringComparer.OrdinalIgnoreCase))
{
if (user == null || !user.Policy.EnableContentDeletion)
@@ -193,6 +190,7 @@ namespace Emby.Server.Implementations.HttpServer.Security
};
}
}
+
if (roles.Contains("download", StringComparer.OrdinalIgnoreCase))
{
if (user == null || !user.Policy.EnableContentDownloading)
diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs
index 276312a300..4574486049 100644
--- a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs
+++ b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using System.Net;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Security;
@@ -89,7 +90,7 @@ namespace Emby.Server.Implementations.HttpServer.Security
AccessToken = token
});
- var tokenInfo = result.Items.Length > 0 ? result.Items[0] : null;
+ var tokenInfo = result.Items.Count > 0 ? result.Items[0] : null;
if (tokenInfo != null)
{
@@ -190,17 +191,23 @@ namespace Emby.Server.Implementations.HttpServer.Security
/// Dictionary{System.StringSystem.String}.
private Dictionary GetAuthorization(string authorizationHeader)
{
- if (authorizationHeader == null) return null;
+ if (authorizationHeader == null)
+ {
+ return null;
+ }
var parts = authorizationHeader.Split(new[] { ' ' }, 2);
// There should be at least to parts
- if (parts.Length != 2) return null;
+ if (parts.Length != 2)
+ {
+ return null;
+ }
var acceptedNames = new[] { "MediaBrowser", "Emby" };
// It has to be a digest request
- if (!acceptedNames.Contains(parts[0] ?? string.Empty, StringComparer.OrdinalIgnoreCase))
+ if (!acceptedNames.Contains(parts[0], StringComparer.OrdinalIgnoreCase))
{
return null;
}
@@ -232,7 +239,7 @@ namespace Emby.Server.Implementations.HttpServer.Security
return value;
}
- return System.Net.WebUtility.HtmlEncode(value);
+ return WebUtility.HtmlEncode(value);
}
}
}
diff --git a/Emby.Server.Implementations/IO/IsoManager.cs b/Emby.Server.Implementations/IO/IsoManager.cs
index f0a15097c9..94e92c2a6a 100644
--- a/Emby.Server.Implementations/IO/IsoManager.cs
+++ b/Emby.Server.Implementations/IO/IsoManager.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -8,12 +9,12 @@ using MediaBrowser.Model.IO;
namespace Emby.Server.Implementations.IO
{
///
- /// Class IsoManager
+ /// Class IsoManager.
///
public class IsoManager : IIsoManager
{
///
- /// The _mounters
+ /// The _mounters.
///
private readonly List _mounters = new List();
@@ -22,9 +23,7 @@ namespace Emby.Server.Implementations.IO
///
/// The iso path.
/// The cancellation token.
- /// IsoMount.
- /// isoPath
- ///
+ /// .
public Task Mount(string isoPath, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(isoPath))
@@ -36,7 +35,11 @@ namespace Emby.Server.Implementations.IO
if (mounter == null)
{
- throw new ArgumentException(string.Format("No mounters are able to mount {0}", isoPath));
+ throw new ArgumentException(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "No mounters are able to mount {0}",
+ isoPath));
}
return mounter.Mount(isoPath, cancellationToken);
@@ -60,16 +63,5 @@ namespace Emby.Server.Implementations.IO
{
_mounters.AddRange(mounters);
}
-
- ///
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- ///
- public void Dispose()
- {
- foreach (var mounter in _mounters)
- {
- mounter.Dispose();
- }
- }
}
}
diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs
index 8517abed6c..ae8371a32f 100644
--- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs
+++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Diagnostics;
using System.IO;
using System.Linq;
@@ -555,7 +556,7 @@ namespace Emby.Server.Implementations.IO
throw new ArgumentNullException(nameof(file2));
}
- var temp1 = Path.Combine(_tempPath, Guid.NewGuid().ToString("N"));
+ var temp1 = Path.Combine(_tempPath, Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture));
// Copying over will fail against hidden files
SetHidden(file1, false);
diff --git a/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs b/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs
index 46f209b4b4..6afcf567a8 100644
--- a/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs
+++ b/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
@@ -20,14 +21,6 @@ namespace Emby.Server.Implementations.Images
public abstract class BaseDynamicImageProvider : IHasItemChangeMonitor, IForcedProvider, ICustomMetadataProvider, IHasOrder
where T : BaseItem
{
- protected virtual IReadOnlyCollection SupportedImages { get; }
- = new ImageType[] { ImageType.Primary };
-
- protected IFileSystem FileSystem { get; private set; }
- protected IProviderManager ProviderManager { get; private set; }
- protected IApplicationPaths ApplicationPaths { get; private set; }
- protected IImageProcessor ImageProcessor { get; set; }
-
protected BaseDynamicImageProvider(IFileSystem fileSystem, IProviderManager providerManager, IApplicationPaths applicationPaths, IImageProcessor imageProcessor)
{
ApplicationPaths = applicationPaths;
@@ -36,6 +29,24 @@ namespace Emby.Server.Implementations.Images
ImageProcessor = imageProcessor;
}
+ protected IFileSystem FileSystem { get; }
+
+ protected IProviderManager ProviderManager { get; }
+
+ protected IApplicationPaths ApplicationPaths { get; }
+
+ protected IImageProcessor ImageProcessor { get; set; }
+
+ protected virtual IReadOnlyCollection SupportedImages { get; }
+ = new ImageType[] { ImageType.Primary };
+
+ ///
+ public string Name => "Dynamic Image Provider";
+
+ protected virtual int MaxImageAgeDays => 7;
+
+ public int Order => 0;
+
protected virtual bool Supports(BaseItem _) => true;
public async Task FetchAsync(T item, MetadataRefreshOptions options, CancellationToken cancellationToken)
@@ -84,12 +95,13 @@ namespace Emby.Server.Implementations.Images
return FetchToFileInternal(item, items, imageType, cancellationToken);
}
- protected async Task FetchToFileInternal(BaseItem item,
+ protected async Task FetchToFileInternal(
+ BaseItem item,
IReadOnlyList itemsWithImages,
ImageType imageType,
CancellationToken cancellationToken)
{
- var outputPathWithoutExtension = Path.Combine(ApplicationPaths.TempDirectory, Guid.NewGuid().ToString("N"));
+ var outputPathWithoutExtension = Path.Combine(ApplicationPaths.TempDirectory, Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture));
Directory.CreateDirectory(Path.GetDirectoryName(outputPathWithoutExtension));
string outputPath = CreateImage(item, itemsWithImages, outputPathWithoutExtension, imageType, 0);
@@ -180,8 +192,6 @@ namespace Emby.Server.Implementations.Images
return outputPath;
}
- public string Name => "Dynamic Image Provider";
-
protected virtual string CreateImage(BaseItem item,
IReadOnlyCollection itemsWithImages,
string outputPathWithoutExtension,
@@ -213,8 +223,6 @@ namespace Emby.Server.Implementations.Images
throw new ArgumentException("Unexpected image type", nameof(imageType));
}
- protected virtual int MaxImageAgeDays => 7;
-
public bool HasChanged(BaseItem item, IDirectoryService directoryServicee)
{
if (!Supports(item))
@@ -262,15 +270,9 @@ namespace Emby.Server.Implementations.Images
protected virtual bool HasChangedByDate(BaseItem item, ItemImageInfo image)
{
var age = DateTime.UtcNow - image.DateModified;
- if (age.TotalDays <= MaxImageAgeDays)
- {
- return false;
- }
- return true;
+ return age.TotalDays > MaxImageAgeDays;
}
- public int Order => 0;
-
protected string CreateSingleImage(IEnumerable itemsWithImages, string outputPathWithoutExtension, ImageType imageType)
{
var image = itemsWithImages
diff --git a/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs b/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs
index f1ae2fc9c0..8bdb387843 100644
--- a/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs
+++ b/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs
@@ -57,7 +57,6 @@ namespace Emby.Server.Implementations.Library
}
var filename = fileInfo.Name;
- var path = fileInfo.FullName;
// Ignore hidden files on UNIX
if (Environment.OSVersion.Platform != PlatformID.Win32NT
diff --git a/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs b/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs
index fe09b07ff6..c95b00ede2 100644
--- a/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs
+++ b/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs
@@ -2,24 +2,30 @@ using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
+using MediaBrowser.Common.Cryptography;
using MediaBrowser.Controller.Authentication;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Cryptography;
+using static MediaBrowser.Common.HexHelper;
namespace Emby.Server.Implementations.Library
{
public class DefaultAuthenticationProvider : IAuthenticationProvider, IRequiresResolvedUser
{
private readonly ICryptoProvider _cryptographyProvider;
- public DefaultAuthenticationProvider(ICryptoProvider crypto)
+
+ public DefaultAuthenticationProvider(ICryptoProvider cryptographyProvider)
{
- _cryptographyProvider = crypto;
+ _cryptographyProvider = cryptographyProvider;
}
+ ///
public string Name => "Default";
+ ///
public bool IsEnabled => true;
+ ///
// This is dumb and an artifact of the backwards way auth providers were designed.
// This version of authenticate was never meant to be called, but needs to be here for interface compat
// Only the providers that don't provide local user support use this
@@ -28,17 +34,18 @@ namespace Emby.Server.Implementations.Library
throw new NotImplementedException();
}
- // This is the verson that we need to use for local users. Because reasons.
+ ///
+ // This is the version that we need to use for local users. Because reasons.
public Task Authenticate(string username, string password, User resolvedUser)
{
bool success = false;
if (resolvedUser == null)
{
- throw new Exception("Invalid username or password");
+ throw new ArgumentNullException(nameof(resolvedUser));
}
- // As long as jellyfin supports passwordless users, we need this little block here to accomodate
- if (IsPasswordEmpty(resolvedUser, password))
+ // As long as jellyfin supports passwordless users, we need this little block here to accommodate
+ if (!HasPassword(resolvedUser) && string.IsNullOrEmpty(password))
{
return Task.FromResult(new ProviderAuthenticationResult
{
@@ -46,41 +53,27 @@ namespace Emby.Server.Implementations.Library
});
}
- ConvertPasswordFormat(resolvedUser);
byte[] passwordbytes = Encoding.UTF8.GetBytes(password);
- PasswordHash readyHash = new PasswordHash(resolvedUser.Password);
- byte[] calculatedHash;
- string calculatedHashString;
- if (_cryptographyProvider.GetSupportedHashMethods().Contains(readyHash.Id) || _cryptographyProvider.DefaultHashMethod == readyHash.Id)
+ PasswordHash readyHash = PasswordHash.Parse(resolvedUser.Password);
+ if (_cryptographyProvider.GetSupportedHashMethods().Contains(readyHash.Id)
+ || _cryptographyProvider.DefaultHashMethod == readyHash.Id)
{
- if (string.IsNullOrEmpty(readyHash.Salt))
- {
- calculatedHash = _cryptographyProvider.ComputeHash(readyHash.Id, passwordbytes);
- calculatedHashString = BitConverter.ToString(calculatedHash).Replace("-", string.Empty);
- }
- else
- {
- calculatedHash = _cryptographyProvider.ComputeHash(readyHash.Id, passwordbytes, readyHash.SaltBytes);
- calculatedHashString = BitConverter.ToString(calculatedHash).Replace("-", string.Empty);
- }
+ byte[] calculatedHash = _cryptographyProvider.ComputeHash(readyHash.Id, passwordbytes, readyHash.Salt);
- if (calculatedHashString == readyHash.Hash)
+ if (calculatedHash.SequenceEqual(readyHash.Hash))
{
success = true;
- // throw new Exception("Invalid username or password");
}
}
else
{
- throw new Exception(string.Format($"Requested crypto method not available in provider: {readyHash.Id}"));
+ throw new AuthenticationException($"Requested crypto method not available in provider: {readyHash.Id}");
}
- // var success = string.Equals(GetPasswordHash(resolvedUser), GetHashedString(resolvedUser, password), StringComparison.OrdinalIgnoreCase);
-
if (!success)
{
- throw new Exception("Invalid username or password");
+ throw new AuthenticationException("Invalid username or password");
}
return Task.FromResult(new ProviderAuthenticationResult
@@ -89,89 +82,31 @@ namespace Emby.Server.Implementations.Library
});
}
- // This allows us to move passwords forward to the newformat without breaking. They are still insecure, unsalted, and dumb before a password change
- // but at least they are in the new format.
- private void ConvertPasswordFormat(User user)
- {
- if (string.IsNullOrEmpty(user.Password))
- {
- return;
- }
-
- if (!user.Password.Contains("$"))
- {
- string hash = user.Password;
- user.Password = string.Format("$SHA1${0}", hash);
- }
-
- if (user.EasyPassword != null && !user.EasyPassword.Contains("$"))
- {
- string hash = user.EasyPassword;
- user.EasyPassword = string.Format("$SHA1${0}", hash);
- }
- }
-
- public Task HasPassword(User user)
- {
- var hasConfiguredPassword = !IsPasswordEmpty(user, GetPasswordHash(user));
- return Task.FromResult(hasConfiguredPassword);
- }
-
- private bool IsPasswordEmpty(User user, string password)
- {
- return (string.IsNullOrEmpty(user.Password) && string.IsNullOrEmpty(password));
- }
+ ///
+ public bool HasPassword(User user)
+ => !string.IsNullOrEmpty(user.Password);
+ ///
public Task ChangePassword(User user, string newPassword)
{
- ConvertPasswordFormat(user);
- // This is needed to support changing a no password user to a password user
- if (string.IsNullOrEmpty(user.Password))
+ if (string.IsNullOrEmpty(newPassword))
{
- PasswordHash newPasswordHash = new PasswordHash(_cryptographyProvider);
- newPasswordHash.SaltBytes = _cryptographyProvider.GenerateSalt();
- newPasswordHash.Salt = PasswordHash.ConvertToByteString(newPasswordHash.SaltBytes);
- newPasswordHash.Id = _cryptographyProvider.DefaultHashMethod;
- newPasswordHash.Hash = GetHashedStringChangeAuth(newPassword, newPasswordHash);
- user.Password = newPasswordHash.ToString();
+ user.Password = null;
return Task.CompletedTask;
}
- PasswordHash passwordHash = new PasswordHash(user.Password);
- if (passwordHash.Id == "SHA1" && string.IsNullOrEmpty(passwordHash.Salt))
- {
- passwordHash.SaltBytes = _cryptographyProvider.GenerateSalt();
- passwordHash.Salt = PasswordHash.ConvertToByteString(passwordHash.SaltBytes);
- passwordHash.Id = _cryptographyProvider.DefaultHashMethod;
- passwordHash.Hash = GetHashedStringChangeAuth(newPassword, passwordHash);
- }
- else if (newPassword != null)
- {
- passwordHash.Hash = GetHashedString(user, newPassword);
- }
-
- if (string.IsNullOrWhiteSpace(passwordHash.Hash))
- {
- throw new ArgumentNullException(nameof(passwordHash.Hash));
- }
-
- user.Password = passwordHash.ToString();
+ PasswordHash newPasswordHash = _cryptographyProvider.CreatePasswordHash(newPassword);
+ user.Password = newPasswordHash.ToString();
return Task.CompletedTask;
}
- public string GetPasswordHash(User user)
- {
- return user.Password;
- }
-
+ ///
public void ChangeEasyPassword(User user, string newPassword, string newPasswordHash)
{
- ConvertPasswordFormat(user);
-
if (newPassword != null)
{
- newPasswordHash = string.Format("$SHA1${0}", GetHashedString(user, newPassword));
+ newPasswordHash = _cryptographyProvider.CreatePasswordHash(newPassword).ToString();
}
if (string.IsNullOrWhiteSpace(newPasswordHash))
@@ -182,21 +117,12 @@ namespace Emby.Server.Implementations.Library
user.EasyPassword = newPasswordHash;
}
+ ///
public string GetEasyPasswordHash(User user)
{
- // This should be removed in the future. This was added to let user login after
- // Jellyfin 10.3.3 failed to save a well formatted PIN.
- ConvertPasswordFormat(user);
-
return string.IsNullOrEmpty(user.EasyPassword)
? null
- : (new PasswordHash(user.EasyPassword)).Hash;
- }
-
- public string GetHashedStringChangeAuth(string newPassword, PasswordHash passwordHash)
- {
- passwordHash.HashBytes = Encoding.UTF8.GetBytes(newPassword);
- return PasswordHash.ConvertToByteString(_cryptographyProvider.ComputeHash(passwordHash));
+ : ToHexString(PasswordHash.Parse(user.EasyPassword).Hash);
}
///
@@ -204,28 +130,36 @@ namespace Emby.Server.Implementations.Library
///
public string GetHashedString(User user, string str)
{
- PasswordHash passwordHash;
if (string.IsNullOrEmpty(user.Password))
{
- passwordHash = new PasswordHash(_cryptographyProvider);
- }
- else
- {
- ConvertPasswordFormat(user);
- passwordHash = new PasswordHash(user.Password);
+ return _cryptographyProvider.CreatePasswordHash(str).ToString();
}
- if (passwordHash.SaltBytes != null)
- {
- // the password is modern format with PBKDF and we should take advantage of that
- passwordHash.HashBytes = Encoding.UTF8.GetBytes(str);
- return PasswordHash.ConvertToByteString(_cryptographyProvider.ComputeHash(passwordHash));
- }
- else
+ // TODO: make use of iterations parameter?
+ PasswordHash passwordHash = PasswordHash.Parse(user.Password);
+ return new PasswordHash(
+ passwordHash.Id,
+ _cryptographyProvider.ComputeHash(
+ passwordHash.Id,
+ Encoding.UTF8.GetBytes(str),
+ passwordHash.Salt),
+ passwordHash.Salt,
+ passwordHash.Parameters.ToDictionary(x => x.Key, y => y.Value)).ToString();
+ }
+
+ public byte[] GetHashed(User user, string str)
+ {
+ if (string.IsNullOrEmpty(user.Password))
{
- // the password has no salt and should be called with the older method for safety
- return PasswordHash.ConvertToByteString(_cryptographyProvider.ComputeHash(passwordHash.Id, Encoding.UTF8.GetBytes(str)));
+ return _cryptographyProvider.CreatePasswordHash(str).Hash;
}
+
+ // TODO: make use of iterations parameter?
+ PasswordHash passwordHash = PasswordHash.Parse(user.Password);
+ return _cryptographyProvider.ComputeHash(
+ passwordHash.Id,
+ Encoding.UTF8.GetBytes(str),
+ passwordHash.Salt);
}
}
}
diff --git a/Emby.Server.Implementations/Library/DefaultPasswordResetProvider.cs b/Emby.Server.Implementations/Library/DefaultPasswordResetProvider.cs
index e218749d90..fa6bbcf91c 100644
--- a/Emby.Server.Implementations/Library/DefaultPasswordResetProvider.cs
+++ b/Emby.Server.Implementations/Library/DefaultPasswordResetProvider.cs
@@ -1,132 +1,131 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using MediaBrowser.Common.Extensions;
-using MediaBrowser.Controller.Authentication;
-using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Model.Cryptography;
-using MediaBrowser.Model.Serialization;
-using MediaBrowser.Model.Users;
-
-namespace Emby.Server.Implementations.Library
-{
- public class DefaultPasswordResetProvider : IPasswordResetProvider
- {
- public string Name => "Default Password Reset Provider";
-
- public bool IsEnabled => true;
-
- private readonly string _passwordResetFileBase;
- private readonly string _passwordResetFileBaseDir;
- private readonly string _passwordResetFileBaseName = "passwordreset";
-
- private readonly IJsonSerializer _jsonSerializer;
- private readonly IUserManager _userManager;
- private readonly ICryptoProvider _crypto;
-
- public DefaultPasswordResetProvider(IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IUserManager userManager, ICryptoProvider cryptoProvider)
- {
- _passwordResetFileBaseDir = configurationManager.ApplicationPaths.ProgramDataPath;
- _passwordResetFileBase = Path.Combine(_passwordResetFileBaseDir, _passwordResetFileBaseName);
- _jsonSerializer = jsonSerializer;
- _userManager = userManager;
- _crypto = cryptoProvider;
- }
-
- public async Task RedeemPasswordResetPin(string pin)
- {
- SerializablePasswordReset spr;
- HashSet usersreset = new HashSet();
- foreach (var resetfile in Directory.EnumerateFiles(_passwordResetFileBaseDir, $"{_passwordResetFileBaseName}*"))
- {
- using (var str = File.OpenRead(resetfile))
- {
- spr = await _jsonSerializer.DeserializeFromStreamAsync(str).ConfigureAwait(false);
- }
-
- if (spr.ExpirationDate < DateTime.Now)
- {
- File.Delete(resetfile);
- }
- else if (spr.Pin.Replace("-", "").Equals(pin.Replace("-", ""), StringComparison.InvariantCultureIgnoreCase))
- {
- var resetUser = _userManager.GetUserByName(spr.UserName);
- if (resetUser == null)
- {
- throw new Exception($"User with a username of {spr.UserName} not found");
- }
-
- await _userManager.ChangePassword(resetUser, pin).ConfigureAwait(false);
- usersreset.Add(resetUser.Name);
- File.Delete(resetfile);
- }
- }
-
- if (usersreset.Count < 1)
- {
- throw new ResourceNotFoundException($"No Users found with a password reset request matching pin {pin}");
- }
- else
- {
- return new PinRedeemResult
- {
- Success = true,
- UsersReset = usersreset.ToArray()
- };
- }
- }
-
- public async Task StartForgotPasswordProcess(MediaBrowser.Controller.Entities.User user, bool isInNetwork)
- {
- string pin = string.Empty;
- using (var cryptoRandom = System.Security.Cryptography.RandomNumberGenerator.Create())
- {
- byte[] bytes = new byte[4];
- cryptoRandom.GetBytes(bytes);
- pin = BitConverter.ToString(bytes);
- }
-
- DateTime expireTime = DateTime.Now.AddMinutes(30);
- string filePath = _passwordResetFileBase + user.InternalId + ".json";
- SerializablePasswordReset spr = new SerializablePasswordReset
- {
- ExpirationDate = expireTime,
- Pin = pin,
- PinFile = filePath,
- UserName = user.Name
- };
-
- try
- {
- using (FileStream fileStream = File.OpenWrite(filePath))
- {
- _jsonSerializer.SerializeToStream(spr, fileStream);
- await fileStream.FlushAsync().ConfigureAwait(false);
- }
- }
- catch (Exception e)
- {
- throw new Exception($"Error serializing or writing password reset for {user.Name} to location: {filePath}", e);
- }
-
- return new ForgotPasswordResult
- {
- Action = ForgotPasswordAction.PinCode,
- PinExpirationDate = expireTime,
- PinFile = filePath
- };
- }
-
- private class SerializablePasswordReset : PasswordPinCreationResult
- {
- public string Pin { get; set; }
-
- public string UserName { get; set; }
- }
- }
-}
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Security.Cryptography;
+using System.Threading.Tasks;
+using MediaBrowser.Common.Extensions;
+using MediaBrowser.Controller.Authentication;
+using MediaBrowser.Controller.Configuration;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Model.Serialization;
+using MediaBrowser.Model.Users;
+
+namespace Emby.Server.Implementations.Library
+{
+ public class DefaultPasswordResetProvider : IPasswordResetProvider
+ {
+ private const string BaseResetFileName = "passwordreset";
+
+ private readonly IJsonSerializer _jsonSerializer;
+ private readonly IUserManager _userManager;
+
+ private readonly string _passwordResetFileBase;
+ private readonly string _passwordResetFileBaseDir;
+
+ public DefaultPasswordResetProvider(
+ IServerConfigurationManager configurationManager,
+ IJsonSerializer jsonSerializer,
+ IUserManager userManager)
+ {
+ _passwordResetFileBaseDir = configurationManager.ApplicationPaths.ProgramDataPath;
+ _passwordResetFileBase = Path.Combine(_passwordResetFileBaseDir, BaseResetFileName);
+ _jsonSerializer = jsonSerializer;
+ _userManager = userManager;
+ }
+
+ ///
+ public string Name => "Default Password Reset Provider";
+
+ ///
+ public bool IsEnabled => true;
+
+ ///
+ public async Task RedeemPasswordResetPin(string pin)
+ {
+ SerializablePasswordReset spr;
+ List usersreset = new List();
+ foreach (var resetfile in Directory.EnumerateFiles(_passwordResetFileBaseDir, $"{BaseResetFileName}*"))
+ {
+ using (var str = File.OpenRead(resetfile))
+ {
+ spr = await _jsonSerializer.DeserializeFromStreamAsync(str).ConfigureAwait(false);
+ }
+
+ if (spr.ExpirationDate < DateTime.Now)
+ {
+ File.Delete(resetfile);
+ }
+ else if (string.Equals(
+ spr.Pin.Replace("-", string.Empty),
+ pin.Replace("-", string.Empty),
+ StringComparison.InvariantCultureIgnoreCase))
+ {
+ var resetUser = _userManager.GetUserByName(spr.UserName);
+ if (resetUser == null)
+ {
+ throw new ResourceNotFoundException($"User with a username of {spr.UserName} not found");
+ }
+
+ await _userManager.ChangePassword(resetUser, pin).ConfigureAwait(false);
+ usersreset.Add(resetUser.Name);
+ File.Delete(resetfile);
+ }
+ }
+
+ if (usersreset.Count < 1)
+ {
+ throw new ResourceNotFoundException($"No Users found with a password reset request matching pin {pin}");
+ }
+ else
+ {
+ return new PinRedeemResult
+ {
+ Success = true,
+ UsersReset = usersreset.ToArray()
+ };
+ }
+ }
+
+ ///
+ public async Task StartForgotPasswordProcess(MediaBrowser.Controller.Entities.User user, bool isInNetwork)
+ {
+ string pin = string.Empty;
+ using (var cryptoRandom = RandomNumberGenerator.Create())
+ {
+ byte[] bytes = new byte[4];
+ cryptoRandom.GetBytes(bytes);
+ pin = BitConverter.ToString(bytes);
+ }
+
+ DateTime expireTime = DateTime.Now.AddMinutes(30);
+ string filePath = _passwordResetFileBase + user.InternalId + ".json";
+ SerializablePasswordReset spr = new SerializablePasswordReset
+ {
+ ExpirationDate = expireTime,
+ Pin = pin,
+ PinFile = filePath,
+ UserName = user.Name
+ };
+
+ using (FileStream fileStream = File.OpenWrite(filePath))
+ {
+ _jsonSerializer.SerializeToStream(spr, fileStream);
+ await fileStream.FlushAsync().ConfigureAwait(false);
+ }
+
+ return new ForgotPasswordResult
+ {
+ Action = ForgotPasswordAction.PinCode,
+ PinExpirationDate = expireTime,
+ PinFile = filePath
+ };
+ }
+
+ private class SerializablePasswordReset : PasswordPinCreationResult
+ {
+ public string Pin { get; set; }
+
+ public string UserName { get; set; }
+ }
+ }
+}
diff --git a/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs b/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs
index 45a33a2969..a3c879f121 100644
--- a/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs
+++ b/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs
@@ -1,4 +1,5 @@
using System;
+using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Library;
@@ -26,7 +27,7 @@ namespace Emby.Server.Implementations.Library
EnableStreamSharing = false;
_closeFn = closeFn;
ConsumerCount = 1;
- UniqueId = Guid.NewGuid().ToString("N");
+ UniqueId = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
}
public Task Close()
diff --git a/Emby.Server.Implementations/Library/InvalidAuthProvider.cs b/Emby.Server.Implementations/Library/InvalidAuthProvider.cs
index 25d2331373..6956369dc1 100644
--- a/Emby.Server.Implementations/Library/InvalidAuthProvider.cs
+++ b/Emby.Server.Implementations/Library/InvalidAuthProvider.cs
@@ -1,6 +1,3 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
using System.Threading.Tasks;
using MediaBrowser.Controller.Authentication;
using MediaBrowser.Controller.Entities;
@@ -16,12 +13,12 @@ namespace Emby.Server.Implementations.Library
public Task Authenticate(string username, string password)
{
- throw new SecurityException("User Account cannot login with this provider. The Normal provider for this user cannot be found");
+ throw new AuthenticationException("User Account cannot login with this provider. The Normal provider for this user cannot be found");
}
- public Task HasPassword(User user)
+ public bool HasPassword(User user)
{
- return Task.FromResult(true);
+ return true;
}
public Task ChangePassword(User user, string newPassword)
@@ -31,7 +28,7 @@ namespace Emby.Server.Implementations.Library
public void ChangeEasyPassword(User user, string newPassword, string newPasswordHash)
{
- // Nothing here
+ // Nothing here
}
public string GetPasswordHash(User user)
diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs
index 4b5063ada6..87e951f25d 100644
--- a/Emby.Server.Implementations/Library/LibraryManager.cs
+++ b/Emby.Server.Implementations/Library/LibraryManager.cs
@@ -779,12 +779,23 @@ namespace Emby.Server.Implementations.Library
{
var userRootPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
+ _logger.LogDebug("Creating userRootPath at {path}", userRootPath);
Directory.CreateDirectory(userRootPath);
- var tmpItem = GetItemById(GetNewItemId(userRootPath, typeof(UserRootFolder))) as UserRootFolder;
+ var newItemId = GetNewItemId(userRootPath, typeof(UserRootFolder));
+ UserRootFolder tmpItem = null;
+ try
+ {
+ tmpItem = GetItemById(newItemId) as UserRootFolder;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error creating UserRootFolder {path}", newItemId);
+ }
if (tmpItem == null)
{
+ _logger.LogDebug("Creating new userRootFolder with DeepCopy");
tmpItem = ((Folder)ResolvePath(_fileSystem.GetDirectoryInfo(userRootPath))).DeepCopy();
}
@@ -796,6 +807,7 @@ namespace Emby.Server.Implementations.Library
}
_userRootFolder = tmpItem;
+ _logger.LogDebug("Setting userRootFolder: {folder}", _userRootFolder);
}
}
}
@@ -1146,8 +1158,10 @@ namespace Emby.Server.Implementations.Library
public List GetVirtualFolders(bool includeRefreshState)
{
+ _logger.LogDebug("Getting topLibraryFolders");
var topLibraryFolders = GetUserRootFolder().Children.ToList();
+ _logger.LogDebug("Getting refreshQueue");
var refreshQueue = includeRefreshState ? _providerManagerFactory().GetRefreshQueue() : null;
return _fileSystem.GetDirectoryPaths(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath)
@@ -1187,12 +1201,12 @@ namespace Emby.Server.Implementations.Library
if (libraryFolder != null && libraryFolder.HasImage(ImageType.Primary))
{
- info.PrimaryImageItemId = libraryFolder.Id.ToString("N");
+ info.PrimaryImageItemId = libraryFolder.Id.ToString("N", CultureInfo.InvariantCulture);
}
if (libraryFolder != null)
{
- info.ItemId = libraryFolder.Id.ToString("N");
+ info.ItemId = libraryFolder.Id.ToString("N", CultureInfo.InvariantCulture);
info.LibraryOptions = GetLibraryOptions(libraryFolder);
if (refreshQueue != null)
@@ -1441,7 +1455,7 @@ namespace Emby.Server.Implementations.Library
return new QueryResult
{
- Items = list.ToArray()
+ Items = list
};
}
@@ -1977,8 +1991,7 @@ namespace Emby.Server.Implementations.Library
public LibraryOptions GetLibraryOptions(BaseItem item)
{
- var collectionFolder = item as CollectionFolder;
- if (collectionFolder == null)
+ if (!(item is CollectionFolder collectionFolder))
{
collectionFolder = GetCollectionFolders(item)
.OfType()
@@ -2135,12 +2148,12 @@ namespace Emby.Server.Implementations.Library
string viewType,
string sortName)
{
- var parentIdString = parentId.Equals(Guid.Empty) ? null : parentId.ToString("N");
- var idValues = "38_namedview_" + name + user.Id.ToString("N") + (parentIdString ?? string.Empty) + (viewType ?? string.Empty);
+ var parentIdString = parentId.Equals(Guid.Empty) ? null : parentId.ToString("N", CultureInfo.InvariantCulture);
+ var idValues = "38_namedview_" + name + user.Id.ToString("N", CultureInfo.InvariantCulture) + (parentIdString ?? string.Empty) + (viewType ?? string.Empty);
var id = GetNewItemId(idValues, typeof(UserView));
- var path = Path.Combine(ConfigurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N"));
+ var path = Path.Combine(ConfigurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N", CultureInfo.InvariantCulture));
var item = GetItemById(id) as UserView;
@@ -2271,7 +2284,7 @@ namespace Emby.Server.Implementations.Library
throw new ArgumentNullException(nameof(name));
}
- var parentIdString = parentId.Equals(Guid.Empty) ? null : parentId.ToString("N");
+ var parentIdString = parentId.Equals(Guid.Empty) ? null : parentId.ToString("N", CultureInfo.InvariantCulture);
var idValues = "37_namedview_" + name + (parentIdString ?? string.Empty) + (viewType ?? string.Empty);
if (!string.IsNullOrEmpty(uniqueId))
{
@@ -2280,7 +2293,7 @@ namespace Emby.Server.Implementations.Library
var id = GetNewItemId(idValues, typeof(UserView));
- var path = Path.Combine(ConfigurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N"));
+ var path = Path.Combine(ConfigurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N", CultureInfo.InvariantCulture));
var item = GetItemById(id) as UserView;
diff --git a/Emby.Server.Implementations/Library/LiveStreamHelper.cs b/Emby.Server.Implementations/Library/LiveStreamHelper.cs
index c3082a78a7..33e6f24341 100644
--- a/Emby.Server.Implementations/Library/LiveStreamHelper.cs
+++ b/Emby.Server.Implementations/Library/LiveStreamHelper.cs
@@ -40,7 +40,7 @@ namespace Emby.Server.Implementations.Library
var now = DateTime.UtcNow;
MediaInfo mediaInfo = null;
- var cacheFilePath = string.IsNullOrEmpty(cacheKey) ? null : Path.Combine(_appPaths.CachePath, "mediainfo", cacheKey.GetMD5().ToString("N") + ".json");
+ var cacheFilePath = string.IsNullOrEmpty(cacheKey) ? null : Path.Combine(_appPaths.CachePath, "mediainfo", cacheKey.GetMD5().ToString("N", CultureInfo.InvariantCulture) + ".json");
if (!string.IsNullOrEmpty(cacheKey))
{
diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs
index 24ab8e7619..d83e1fc021 100644
--- a/Emby.Server.Implementations/Library/MediaSourceManager.cs
+++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs
@@ -269,7 +269,7 @@ namespace Emby.Server.Implementations.Library
private static void SetKeyProperties(IMediaSourceProvider provider, MediaSourceInfo mediaSource)
{
- var prefix = provider.GetType().FullName.GetMD5().ToString("N") + LiveStreamIdDelimeter;
+ var prefix = provider.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture) + LiveStreamIdDelimeter;
if (!string.IsNullOrEmpty(mediaSource.OpenToken) && !mediaSource.OpenToken.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
@@ -626,7 +626,7 @@ namespace Emby.Server.Implementations.Library
var now = DateTime.UtcNow;
MediaInfo mediaInfo = null;
- var cacheFilePath = string.IsNullOrEmpty(cacheKey) ? null : Path.Combine(_appPaths.CachePath, "mediainfo", cacheKey.GetMD5().ToString("N") + ".json");
+ var cacheFilePath = string.IsNullOrEmpty(cacheKey) ? null : Path.Combine(_appPaths.CachePath, "mediainfo", cacheKey.GetMD5().ToString("N", CultureInfo.InvariantCulture) + ".json");
if (!string.IsNullOrEmpty(cacheKey))
{
@@ -854,7 +854,7 @@ namespace Emby.Server.Implementations.Library
var keys = key.Split(new[] { LiveStreamIdDelimeter }, 2);
- var provider = _providers.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), keys[0], StringComparison.OrdinalIgnoreCase));
+ var provider = _providers.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture), keys[0], StringComparison.OrdinalIgnoreCase));
var splitIndex = key.IndexOf(LiveStreamIdDelimeter);
var keyId = key.Substring(splitIndex + 1);
diff --git a/Emby.Server.Implementations/Library/UserDataManager.cs b/Emby.Server.Implementations/Library/UserDataManager.cs
index dfa1edaffd..36adc0b9c4 100644
--- a/Emby.Server.Implementations/Library/UserDataManager.cs
+++ b/Emby.Server.Implementations/Library/UserDataManager.cs
@@ -152,7 +152,7 @@ namespace Emby.Server.Implementations.Library
/// System.String.
private static string GetCacheKey(long internalUserId, Guid itemId)
{
- return internalUserId.ToString(CultureInfo.InvariantCulture) + "-" + itemId.ToString("N");
+ return internalUserId.ToString(CultureInfo.InvariantCulture) + "-" + itemId.ToString("N", CultureInfo.InvariantCulture);
}
public UserItemData GetUserData(User user, BaseItem item)
diff --git a/Emby.Server.Implementations/Library/UserManager.cs b/Emby.Server.Implementations/Library/UserManager.cs
index 1701ced426..52b2f56ffc 100644
--- a/Emby.Server.Implementations/Library/UserManager.cs
+++ b/Emby.Server.Implementations/Library/UserManager.cs
@@ -1,4 +1,5 @@
using System;
+using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
@@ -7,24 +8,22 @@ using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
+using MediaBrowser.Common.Cryptography;
using MediaBrowser.Common.Events;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Authentication;
-using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Devices;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Security;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Configuration;
-using MediaBrowser.Model.Cryptography;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Events;
@@ -32,6 +31,7 @@ using MediaBrowser.Model.IO;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Users;
using Microsoft.Extensions.Logging;
+using static MediaBrowser.Common.HexHelper;
namespace Emby.Server.Implementations.Library
{
@@ -40,35 +40,20 @@ namespace Emby.Server.Implementations.Library
///
public class UserManager : IUserManager
{
- ///
- /// Gets the users.
- ///
- /// The users.
- public IEnumerable Users => _users;
-
- private User[] _users;
-
///
/// The _logger
///
private readonly ILogger _logger;
- ///
- /// Gets or sets the configuration manager.
- ///
- /// The configuration manager.
- private IServerConfigurationManager ConfigurationManager { get; set; }
+ private readonly object _policySyncLock = new object();
///
/// Gets the active user repository
///
/// The user repository.
- private IUserRepository UserRepository { get; set; }
- public event EventHandler> UserPasswordChanged;
-
+ private readonly IUserRepository _userRepository;
private readonly IXmlSerializer _xmlSerializer;
private readonly IJsonSerializer _jsonSerializer;
-
private readonly INetworkManager _networkManager;
private readonly Func _imageProcessorFactory;
@@ -76,6 +61,8 @@ namespace Emby.Server.Implementations.Library
private readonly IServerApplicationHost _appHost;
private readonly IFileSystem _fileSystem;
+ private ConcurrentDictionary _users;
+
private IAuthenticationProvider[] _authenticationProviders;
private DefaultAuthenticationProvider _defaultAuthenticationProvider;
@@ -85,8 +72,7 @@ namespace Emby.Server.Implementations.Library
private DefaultPasswordResetProvider _defaultPasswordResetProvider;
public UserManager(
- ILoggerFactory loggerFactory,
- IServerConfigurationManager configurationManager,
+ ILogger logger,
IUserRepository userRepository,
IXmlSerializer xmlSerializer,
INetworkManager networkManager,
@@ -96,8 +82,8 @@ namespace Emby.Server.Implementations.Library
IJsonSerializer jsonSerializer,
IFileSystem fileSystem)
{
- _logger = loggerFactory.CreateLogger(nameof(UserManager));
- UserRepository = userRepository;
+ _logger = logger;
+ _userRepository = userRepository;
_xmlSerializer = xmlSerializer;
_networkManager = networkManager;
_imageProcessorFactory = imageProcessorFactory;
@@ -105,8 +91,51 @@ namespace Emby.Server.Implementations.Library
_appHost = appHost;
_jsonSerializer = jsonSerializer;
_fileSystem = fileSystem;
- ConfigurationManager = configurationManager;
- _users = Array.Empty();
+ _users = null;
+ }
+
+ public event EventHandler> UserPasswordChanged;
+
+ ///
+ /// Occurs when [user updated].
+ ///
+ public event EventHandler> UserUpdated;
+
+ public event EventHandler> UserPolicyUpdated;
+
+ public event EventHandler> UserConfigurationUpdated;
+
+ public event EventHandler> UserLockedOut;
+
+ public event EventHandler> UserCreated;
+
+ ///
+ /// Occurs when [user deleted].
+ ///
+ public event EventHandler> UserDeleted;
+
+ ///
+ public IEnumerable Users => _users.Values;
+
+ ///
+ public IEnumerable UsersIds => _users.Keys;
+
+ ///
+ /// Called when [user updated].
+ ///
+ /// The user.
+ private void OnUserUpdated(User user)
+ {
+ UserUpdated?.Invoke(this, new GenericEventArgs { Argument = user });
+ }
+
+ ///
+ /// Called when [user deleted].
+ ///
+ /// The user.
+ private void OnUserDeleted(User user)
+ {
+ UserDeleted?.Invoke(this, new GenericEventArgs { Argument = user });
}
public NameIdPair[] GetAuthenticationProviders()
@@ -137,7 +166,7 @@ namespace Emby.Server.Implementations.Library
.ToArray();
}
- public void AddParts(IEnumerable authenticationProviders,IEnumerable passwordResetProviders)
+ public void AddParts(IEnumerable authenticationProviders, IEnumerable passwordResetProviders)
{
_authenticationProviders = authenticationProviders.ToArray();
@@ -150,54 +179,21 @@ namespace Emby.Server.Implementations.Library
_defaultPasswordResetProvider = passwordResetProviders.OfType().First();
}
- #region UserUpdated Event
///
- /// Occurs when [user updated].
- ///
- public event EventHandler> UserUpdated;
- public event EventHandler> UserPolicyUpdated;
- public event EventHandler> UserConfigurationUpdated;
- public event EventHandler> UserLockedOut;
-
- ///
- /// Called when [user updated].
- ///
- /// The user.
- private void OnUserUpdated(User user)
- {
- UserUpdated?.Invoke(this, new GenericEventArgs { Argument = user });
- }
- #endregion
-
- #region UserDeleted Event
- ///
- /// Occurs when [user deleted].
- ///
- public event EventHandler> UserDeleted;
- ///
- /// Called when [user deleted].
- ///
- /// The user.
- private void OnUserDeleted(User user)
- {
- UserDeleted?.Invoke(this, new GenericEventArgs { Argument = user });
- }
- #endregion
-
- ///
- /// Gets a User by Id
+ /// Gets a User by Id.
///
/// The id.
/// User.
- ///
+ ///
public User GetUserById(Guid id)
{
if (id == Guid.Empty)
{
- throw new ArgumentException(nameof(id), "Guid can't be empty");
+ throw new ArgumentException("Guid can't be empty", nameof(id));
}
- return Users.FirstOrDefault(u => u.Id == id);
+ _users.TryGetValue(id, out User user);
+ return user;
}
///
@@ -206,15 +202,13 @@ namespace Emby.Server.Implementations.Library
/// The identifier.
/// User.
public User GetUserById(string id)
- {
- return GetUserById(new Guid(id));
- }
+ => GetUserById(new Guid(id));
public User GetUserByName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
- throw new ArgumentNullException(nameof(name));
+ throw new ArgumentException("Invalid username", nameof(name));
}
return Users.FirstOrDefault(u => string.Equals(u.Name, name, StringComparison.OrdinalIgnoreCase));
@@ -222,8 +216,9 @@ namespace Emby.Server.Implementations.Library
public void Initialize()
{
- var users = LoadUsers();
- _users = users.ToArray();
+ LoadUsers();
+
+ var users = Users;
// If there are no local users with admin rights, make them all admins
if (!users.Any(i => i.Policy.IsAdministrator))
@@ -240,14 +235,12 @@ namespace Emby.Server.Implementations.Library
{
// This is some regex that matches only on unicode "word" characters, as well as -, _ and @
// In theory this will cut out most if not all 'control' characters which should help minimize any weirdness
- // Usernames can contain letters (a-z + whatever else unicode is cool with), numbers (0-9), at-signs (@), dashes (-), underscores (_), apostrophes ('), and periods (.)
+ // Usernames can contain letters (a-z + whatever else unicode is cool with), numbers (0-9), at-signs (@), dashes (-), underscores (_), apostrophes ('), and periods (.)
return Regex.IsMatch(username, @"^[\w\-'._@]*$");
}
private static bool IsValidUsernameCharacter(char i)
- {
- return IsValidUsername(i.ToString());
- }
+ => IsValidUsername(i.ToString(CultureInfo.InvariantCulture));
public string MakeValidUsername(string username)
{
@@ -266,6 +259,7 @@ namespace Emby.Server.Implementations.Library
builder.Append(c);
}
}
+
return builder.ToString();
}
@@ -276,35 +270,31 @@ namespace Emby.Server.Implementations.Library
throw new ArgumentNullException(nameof(username));
}
- var user = Users
- .FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
+ var user = Users.FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase));
var success = false;
- string updatedUsername = null;
IAuthenticationProvider authenticationProvider = null;
if (user != null)
{
var authResult = await AuthenticateLocalUser(username, password, hashedPassword, user, remoteEndPoint).ConfigureAwait(false);
- authenticationProvider = authResult.Item1;
- updatedUsername = authResult.Item2;
- success = authResult.Item3;
+ authenticationProvider = authResult.authenticationProvider;
+ success = authResult.success;
}
else
{
// user is null
var authResult = await AuthenticateLocalUser(username, password, hashedPassword, null, remoteEndPoint).ConfigureAwait(false);
- authenticationProvider = authResult.Item1;
- updatedUsername = authResult.Item2;
- success = authResult.Item3;
+ authenticationProvider = authResult.authenticationProvider;
+ string updatedUsername = authResult.username;
+ success = authResult.success;
- if (success && authenticationProvider != null && !(authenticationProvider is DefaultAuthenticationProvider))
+ if (success
+ && authenticationProvider != null
+ && !(authenticationProvider is DefaultAuthenticationProvider))
{
// We should trust the user that the authprovider says, not what was typed
- if (updatedUsername != username)
- {
- username = updatedUsername;
- }
+ username = updatedUsername;
// Search the database for the user again; the authprovider might have created it
user = Users
@@ -331,22 +321,26 @@ namespace Emby.Server.Implementations.Library
if (user == null)
{
- throw new SecurityException("Invalid username or password entered.");
+ throw new AuthenticationException("Invalid username or password entered.");
}
if (user.Policy.IsDisabled)
{
- throw new SecurityException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name));
+ throw new AuthenticationException(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "The {0} account is currently disabled. Please consult with your administrator.",
+ user.Name));
}
if (!user.Policy.EnableRemoteAccess && !_networkManager.IsInLocalNetwork(remoteEndPoint))
{
- throw new SecurityException("Forbidden.");
+ throw new AuthenticationException("Forbidden.");
}
if (!user.IsParentalScheduleAllowed())
{
- throw new SecurityException("User is not allowed access at this time.");
+ throw new AuthenticationException("User is not allowed access at this time.");
}
// Update LastActivityDate and LastLoginDate, then save
@@ -357,11 +351,12 @@ namespace Emby.Server.Implementations.Library
user.LastActivityDate = user.LastLoginDate = DateTime.UtcNow;
UpdateUser(user);
}
- UpdateInvalidLoginAttemptCount(user, 0);
+
+ ResetInvalidLoginAttemptCount(user);
}
else
{
- UpdateInvalidLoginAttemptCount(user, user.Policy.InvalidLoginAttemptCount + 1);
+ IncrementInvalidLoginAttemptCount(user);
}
_logger.LogInformation("Authentication request for {0} {1}.", user.Name, success ? "has succeeded" : "has been denied");
@@ -381,7 +376,7 @@ namespace Emby.Server.Implementations.Library
private IAuthenticationProvider GetAuthenticationProvider(User user)
{
- return GetAuthenticationProviders(user).First();
+ return GetAuthenticationProviders(user)[0];
}
private IPasswordResetProvider GetPasswordResetProvider(User user)
@@ -391,7 +386,7 @@ namespace Emby.Server.Implementations.Library
private IAuthenticationProvider[] GetAuthenticationProviders(User user)
{
- var authenticationProviderId = user == null ? null : user.Policy.AuthenticationProviderId;
+ var authenticationProviderId = user?.Policy.AuthenticationProviderId;
var providers = _authenticationProviders.Where(i => i.IsEnabled).ToArray();
@@ -429,139 +424,112 @@ namespace Emby.Server.Implementations.Library
return providers;
}
- private async Task> AuthenticateWithProvider(IAuthenticationProvider provider, string username, string password, User resolvedUser)
+ private async Task<(string username, bool success)> AuthenticateWithProvider(IAuthenticationProvider provider, string username, string password, User resolvedUser)
{
try
{
- var requiresResolvedUser = provider as IRequiresResolvedUser;
- ProviderAuthenticationResult authenticationResult = null;
- if (requiresResolvedUser != null)
- {
- authenticationResult = await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false);
- }
- else
- {
- authenticationResult = await provider.Authenticate(username, password).ConfigureAwait(false);
- }
- if(authenticationResult.Username != username)
+ var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser
+ ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false)
+ : await provider.Authenticate(username, password).ConfigureAwait(false);
+
+ if (authenticationResult.Username != username)
{
_logger.LogDebug("Authentication provider provided updated username {1}", authenticationResult.Username);
username = authenticationResult.Username;
}
- return new Tuple(username, true);
+ return (username, true);
}
- catch (Exception ex)
+ catch (AuthenticationException ex)
{
- _logger.LogError(ex, "Error authenticating with provider {provider}", provider.Name);
+ _logger.LogError(ex, "Error authenticating with provider {Provider}", provider.Name);
- return new Tuple(username, false);
+ return (username, false);
}
}
- private async Task> AuthenticateLocalUser(string username, string password, string hashedPassword, User user, string remoteEndPoint)
+ private async Task<(IAuthenticationProvider authenticationProvider, string username, bool success)> AuthenticateLocalUser(
+ string username,
+ string password,
+ string hashedPassword,
+ User user,
+ string remoteEndPoint)
{
- string updatedUsername = null;
bool success = false;
IAuthenticationProvider authenticationProvider = null;
- if (password != null && user != null)
+ foreach (var provider in GetAuthenticationProviders(user))
{
- // Doesn't look like this is even possible to be used, because of password == null checks below
- hashedPassword = _defaultAuthenticationProvider.GetHashedString(user, password);
- }
+ var providerAuthResult = await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
+ var updatedUsername = providerAuthResult.username;
+ success = providerAuthResult.success;
- if (password == null)
- {
- // legacy
- success = string.Equals(GetAuthenticationProvider(user).GetPasswordHash(user), hashedPassword.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
- }
- else
- {
- foreach (var provider in GetAuthenticationProviders(user))
+ if (success)
{
- var providerAuthResult = await AuthenticateWithProvider(provider, username, password, user).ConfigureAwait(false);
- updatedUsername = providerAuthResult.Item1;
- success = providerAuthResult.Item2;
-
- if (success)
- {
- authenticationProvider = provider;
- username = updatedUsername;
- break;
- }
+ authenticationProvider = provider;
+ username = updatedUsername;
+ break;
}
}
- if (user != null)
+ if (!success
+ && _networkManager.IsInLocalNetwork(remoteEndPoint)
+ && user.Configuration.EnableLocalPassword)
{
- if (!success && _networkManager.IsInLocalNetwork(remoteEndPoint) && user.Configuration.EnableLocalPassword)
- {
- if (password == null)
- {
- // legacy
- success = string.Equals(GetAuthenticationProvider(user).GetEasyPasswordHash(user), hashedPassword.Replace("-", string.Empty), StringComparison.OrdinalIgnoreCase);
- }
- else
- {
- success = string.Equals(GetAuthenticationProvider(user).GetEasyPasswordHash(user), _defaultAuthenticationProvider.GetHashedString(user, password), StringComparison.OrdinalIgnoreCase);
- }
- }
+ success = string.Equals(
+ GetLocalPasswordHash(user),
+ _defaultAuthenticationProvider.GetHashedString(user, password),
+ StringComparison.OrdinalIgnoreCase);
}
- return new Tuple(authenticationProvider, username, success);
+ return (authenticationProvider, username, success);
}
- private void UpdateInvalidLoginAttemptCount(User user, int newValue)
+ private string GetLocalPasswordHash(User user)
{
- if (user.Policy.InvalidLoginAttemptCount == newValue || newValue <= 0)
- {
- return;
- }
-
- user.Policy.InvalidLoginAttemptCount = newValue;
-
- // Check for users without a value here and then fill in the default value
- // also protect from an always lockout if misconfigured
- if (user.Policy.LoginAttemptsBeforeLockout == null || user.Policy.LoginAttemptsBeforeLockout == 0)
- {
- user.Policy.LoginAttemptsBeforeLockout = user.Policy.IsAdministrator ? 5 : 3;
- }
-
- var maxCount = user.Policy.LoginAttemptsBeforeLockout;
+ return string.IsNullOrEmpty(user.EasyPassword)
+ ? null
+ : ToHexString(PasswordHash.Parse(user.EasyPassword).Hash);
+ }
- var fireLockout = false;
+ private void ResetInvalidLoginAttemptCount(User user)
+ {
+ user.Policy.InvalidLoginAttemptCount = 0;
+ UpdateUserPolicy(user, user.Policy, false);
+ }
- // -1 can be used to specify no lockout value
- if (maxCount != -1 && newValue >= maxCount)
+ private void IncrementInvalidLoginAttemptCount(User user)
+ {
+ int invalidLogins = ++user.Policy.InvalidLoginAttemptCount;
+ int maxInvalidLogins = user.Policy.LoginAttemptsBeforeLockout;
+ if (maxInvalidLogins > 0
+ && invalidLogins >= maxInvalidLogins)
{
- _logger.LogDebug("Disabling user {0} due to {1} unsuccessful login attempts.", user.Name, newValue);
user.Policy.IsDisabled = true;
-
- fireLockout = true;
+ UserLockedOut?.Invoke(this, new GenericEventArgs(user));
+ _logger.LogWarning(
+ "Disabling user {UserName} due to {Attempts} unsuccessful login attempts.",
+ user.Name,
+ invalidLogins);
}
UpdateUserPolicy(user, user.Policy, false);
-
- if (fireLockout)
- {
- UserLockedOut?.Invoke(this, new GenericEventArgs(user));
- }
}
///
- /// Loads the users from the repository
+ /// Loads the users from the repository.
///
- /// IEnumerable{User}.
- private List LoadUsers()
+ private void LoadUsers()
{
- var users = UserRepository.RetrieveAllUsers();
+ var users = _userRepository.RetrieveAllUsers();
// There always has to be at least one user.
if (users.Count != 0)
{
- return users;
+ _users = new ConcurrentDictionary(
+ users.Select(x => new KeyValuePair(x.Id, x)));
+ return;
}
var defaultName = Environment.UserName;
@@ -576,14 +544,15 @@ namespace Emby.Server.Implementations.Library
user.DateLastSaved = DateTime.UtcNow;
- UserRepository.CreateUser(user);
+ _userRepository.CreateUser(user);
user.Policy.IsAdministrator = true;
user.Policy.EnableContentDeletion = true;
user.Policy.EnableRemoteControlOfOtherUsers = true;
UpdateUserPolicy(user, user.Policy, false);
- return new List { user };
+ _users = new ConcurrentDictionary();
+ _users[user.Id] = user;
}
public UserDto GetUserDto(User user, string remoteEndPoint = null)
@@ -593,7 +562,7 @@ namespace Emby.Server.Implementations.Library
throw new ArgumentNullException(nameof(user));
}
- bool hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user).Result;
+ bool hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user);
bool hasConfiguredEasyPassword = !string.IsNullOrEmpty(GetAuthenticationProvider(user).GetEasyPasswordHash(user));
bool hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
@@ -614,7 +583,7 @@ namespace Emby.Server.Implementations.Library
Policy = user.Policy
};
- if (!hasPassword && Users.Count() == 1)
+ if (!hasPassword && _users.Count == 1)
{
dto.EnableAutoLogin = true;
}
@@ -689,22 +658,26 @@ namespace Emby.Server.Implementations.Library
throw new ArgumentNullException(nameof(user));
}
- if (string.IsNullOrEmpty(newName))
+ if (string.IsNullOrWhiteSpace(newName))
{
- throw new ArgumentNullException(nameof(newName));
+ throw new ArgumentException("Invalid username", nameof(newName));
}
- if (Users.Any(u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
+ if (user.Name.Equals(newName, StringComparison.OrdinalIgnoreCase))
{
- throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", newName));
+ throw new ArgumentException("The new and old names must be different.");
}
- if (user.Name.Equals(newName, StringComparison.Ordinal))
+ if (Users.Any(
+ u => u.Id != user.Id && u.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
{
- throw new ArgumentException("The new and old names must be different.");
+ throw new ArgumentException(string.Format(
+ CultureInfo.InvariantCulture,
+ "A user with the name '{0}' already exists.",
+ newName));
}
- await user.Rename(newName);
+ await user.Rename(newName).ConfigureAwait(false);
OnUserUpdated(user);
}
@@ -722,23 +695,30 @@ namespace Emby.Server.Implementations.Library
throw new ArgumentNullException(nameof(user));
}
- if (user.Id.Equals(Guid.Empty) || !Users.Any(u => u.Id.Equals(user.Id)))
+ if (user.Id == Guid.Empty)
{
- throw new ArgumentException(string.Format("User with name '{0}' and Id {1} does not exist.", user.Name, user.Id));
+ throw new ArgumentException("Id can't be empty.", nameof(user));
+ }
+
+ if (!_users.ContainsKey(user.Id))
+ {
+ throw new ArgumentException(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "A user '{0}' with Id {1} does not exist.",
+ user.Name,
+ user.Id),
+ nameof(user));
}
user.DateModified = DateTime.UtcNow;
user.DateLastSaved = DateTime.UtcNow;
- UserRepository.UpdateUser(user);
+ _userRepository.UpdateUser(user);
OnUserUpdated(user);
}
- public event EventHandler> UserCreated;
-
- private readonly SemaphoreSlim _userListLock = new SemaphoreSlim(1, 1);
-
///
/// Creates the user.
///
@@ -746,7 +726,7 @@ namespace Emby.Server.Implementations.Library
/// User.
/// name
///
- public async Task CreateUser(string name)
+ public User CreateUser(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
@@ -763,28 +743,17 @@ namespace Emby.Server.Implementations.Library
throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name));
}
- await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
-
- try
- {
- var user = InstantiateNewUser(name);
+ var user = InstantiateNewUser(name);
- var list = Users.ToList();
- list.Add(user);
- _users = list.ToArray();
+ _users[user.Id] = user;
- user.DateLastSaved = DateTime.UtcNow;
+ user.DateLastSaved = DateTime.UtcNow;
- UserRepository.CreateUser(user);
+ _userRepository.CreateUser(user);
- EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs { Argument = user }, _logger);
+ EventHelper.QueueEventIfNotNull(UserCreated, this, new GenericEventArgs { Argument = user }, _logger);
- return user;
- }
- finally
- {
- _userListLock.Release();
- }
+ return user;
}
///
@@ -794,57 +763,59 @@ namespace Emby.Server.Implementations.Library
/// Task.
/// user
///
- public async Task DeleteUser(User user)
+ public void DeleteUser(User user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
- var allUsers = Users.ToList();
-
- if (allUsers.FirstOrDefault(u => u.Id == user.Id) == null)
+ if (!_users.ContainsKey(user.Id))
{
- throw new ArgumentException(string.Format("The user cannot be deleted because there is no user with the Name {0} and Id {1}.", user.Name, user.Id));
+ 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.Name,
+ user.Id));
}
- if (allUsers.Count == 1)
+ if (_users.Count == 1)
{
- throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one user in the system.", user.Name));
+ throw new ArgumentException(string.Format(
+ CultureInfo.InvariantCulture,
+ "The user '{0}' cannot be deleted because there must be at least one user in the system.",
+ user.Name));
}
- if (user.Policy.IsAdministrator && allUsers.Count(i => i.Policy.IsAdministrator) == 1)
+ if (user.Policy.IsAdministrator
+ && Users.Count(i => i.Policy.IsAdministrator) == 1)
{
- throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one admin user in the system.", user.Name));
+ throw new ArgumentException(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "The user '{0}' cannot be deleted because there must be at least one admin user in the system.",
+ user.Name),
+ nameof(user));
}
- await _userListLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
+ var configPath = GetConfigurationFilePath(user);
+
+ _userRepository.DeleteUser(user);
try
{
- var configPath = GetConfigurationFilePath(user);
-
- UserRepository.DeleteUser(user);
-
- try
- {
- _fileSystem.DeleteFile(configPath);
- }
- catch (IOException ex)
- {
- _logger.LogError(ex, "Error deleting file {path}", configPath);
- }
-
- DeleteUserPolicy(user);
-
- _users = allUsers.Where(i => i.Id != user.Id).ToArray();
-
- OnUserDeleted(user);
+ _fileSystem.DeleteFile(configPath);
}
- finally
+ catch (IOException ex)
{
- _userListLock.Release();
+ _logger.LogError(ex, "Error deleting file {path}", configPath);
}
+
+ DeleteUserPolicy(user);
+
+ _users.TryRemove(user.Id, out _);
+
+ OnUserDeleted(user);
}
///
@@ -901,8 +872,7 @@ namespace Emby.Server.Implementations.Library
Name = name,
Id = Guid.NewGuid(),
DateCreated = DateTime.UtcNow,
- DateModified = DateTime.UtcNow,
- UsesIdForConfigurationPath = true
+ DateModified = DateTime.UtcNow
};
}
@@ -984,7 +954,6 @@ namespace Emby.Server.Implementations.Library
};
}
- private readonly object _policySyncLock = new object();
public void UpdateUserPolicy(Guid userId, UserPolicy userPolicy)
{
var user = GetUserById(userId);
diff --git a/Emby.Server.Implementations/Library/UserViewManager.cs b/Emby.Server.Implementations/Library/UserViewManager.cs
index e9ce682ee1..88e2a8fa69 100644
--- a/Emby.Server.Implementations/Library/UserViewManager.cs
+++ b/Emby.Server.Implementations/Library/UserViewManager.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Threading;
using MediaBrowser.Controller.Channels;
@@ -117,7 +118,7 @@ namespace Emby.Server.Implementations.Library
if (!query.IncludeHidden)
{
- list = list.Where(i => !user.Configuration.MyMediaExcludes.Contains(i.Id.ToString("N"))).ToList();
+ list = list.Where(i => !user.Configuration.MyMediaExcludes.Contains(i.Id.ToString("N", CultureInfo.InvariantCulture))).ToList();
}
var sorted = _libraryManager.Sort(list, user, new[] { ItemSortBy.SortName }, SortOrder.Ascending).ToList();
@@ -127,7 +128,7 @@ namespace Emby.Server.Implementations.Library
return list
.OrderBy(i =>
{
- var index = orders.IndexOf(i.Id.ToString("N"));
+ var index = orders.IndexOf(i.Id.ToString("N", CultureInfo.InvariantCulture));
if (index == -1)
{
@@ -136,7 +137,7 @@ namespace Emby.Server.Implementations.Library
{
if (!view.DisplayParentId.Equals(Guid.Empty))
{
- index = orders.IndexOf(view.DisplayParentId.ToString("N"));
+ index = orders.IndexOf(view.DisplayParentId.ToString("N", CultureInfo.InvariantCulture));
}
}
}
@@ -223,7 +224,7 @@ namespace Emby.Server.Implementations.Library
return list;
}
- private List GetItemsForLatestItems(User user, LatestItemsQuery request, DtoOptions options)
+ private IReadOnlyList GetItemsForLatestItems(User user, LatestItemsQuery request, DtoOptions options)
{
var parentId = request.ParentId;
@@ -235,24 +236,22 @@ namespace Emby.Server.Implementations.Library
if (!parentId.Equals(Guid.Empty))
{
var parentItem = _libraryManager.GetItemById(parentId);
- var parentItemChannel = parentItem as Channel;
- if (parentItemChannel != null)
+ if (parentItem is Channel)
{
- return _channelManager.GetLatestChannelItemsInternal(new InternalItemsQuery(user)
- {
- ChannelIds = new[] { parentId },
- IsPlayed = request.IsPlayed,
- StartIndex = request.StartIndex,
- Limit = request.Limit,
- IncludeItemTypes = request.IncludeItemTypes,
- EnableTotalRecordCount = false
-
-
- }, CancellationToken.None).Result.Items.ToList();
+ return _channelManager.GetLatestChannelItemsInternal(
+ new InternalItemsQuery(user)
+ {
+ ChannelIds = new[] { parentId },
+ IsPlayed = request.IsPlayed,
+ StartIndex = request.StartIndex,
+ Limit = request.Limit,
+ IncludeItemTypes = request.IncludeItemTypes,
+ EnableTotalRecordCount = false
+ },
+ CancellationToken.None).GetAwaiter().GetResult().Items;
}
- var parent = parentItem as Folder;
- if (parent != null)
+ if (parentItem is Folder parent)
{
parents.Add(parent);
}
@@ -269,7 +268,7 @@ namespace Emby.Server.Implementations.Library
{
parents = _libraryManager.GetUserRootFolder().GetChildren(user, true)
.Where(i => i is Folder)
- .Where(i => !user.Configuration.LatestItemsExcludes.Contains(i.Id.ToString("N")))
+ .Where(i => !user.Configuration.LatestItemsExcludes.Contains(i.Id.ToString("N", CultureInfo.InvariantCulture)))
.ToList();
}
diff --git a/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs b/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs
index 294348660f..b584cc649d 100644
--- a/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs
@@ -1,4 +1,5 @@
using System;
+using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -91,7 +92,7 @@ namespace Emby.Server.Implementations.Library.Validators
continue;
}
- _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name);
+ _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N", CultureInfo.InvariantCulture), item.Name, item.GetType().Name);
_libraryManager.DeleteItem(item, new DeleteOptions
{
diff --git a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs
index 7899cf01b3..d00c6cde11 100644
--- a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs
@@ -1,7 +1,7 @@
using System;
+using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
@@ -96,7 +96,7 @@ namespace Emby.Server.Implementations.Library.Validators
foreach (var item in deadEntities)
{
- _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name);
+ _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N", CultureInfo.InvariantCulture), item.Name, item.GetType().Name);
_libraryManager.DeleteItem(item, new DeleteOptions
{
diff --git a/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs b/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs
index da4645a11d..93ded9e7bd 100644
--- a/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs
+++ b/Emby.Server.Implementations/Library/Validators/StudiosValidator.cs
@@ -1,4 +1,5 @@
using System;
+using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Entities;
@@ -76,7 +77,7 @@ namespace Emby.Server.Implementations.Library.Validators
foreach (var item in deadEntities)
{
- _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N"), item.Name, item.GetType().Name);
+ _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N", CultureInfo.InvariantCulture), item.Name, item.GetType().Name);
_libraryManager.DeleteItem(item, new DeleteOptions
{
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs
index 7b210d2313..da0013f128 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs
@@ -102,7 +102,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
_streamHelper = streamHelper;
_seriesTimerProvider = new SeriesTimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers.json"));
- _timerProvider = new TimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "timers.json"), _logger);
+ _timerProvider = new TimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "timers.json"));
_timerProvider.TimerFired += _timerProvider_TimerFired;
_config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
@@ -681,7 +681,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
}
}
- timer.Id = Guid.NewGuid().ToString("N");
+ timer.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
LiveTvProgram programInfo = null;
@@ -713,7 +713,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
public async Task CreateSeriesTimer(SeriesTimerInfo info, CancellationToken cancellationToken)
{
- info.Id = Guid.NewGuid().ToString("N");
+ info.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
// populate info.seriesID
var program = GetProgramInfoFromCache(info.ProgramId);
@@ -1059,7 +1059,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
var json = _jsonSerializer.SerializeToString(mediaSource);
mediaSource = _jsonSerializer.DeserializeFromString(json);
- mediaSource.Id = Guid.NewGuid().ToString("N") + "_" + mediaSource.Id;
+ mediaSource.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture) + "_" + mediaSource.Id;
//if (mediaSource.DateLiveStreamOpened.HasValue && enableStreamSharing)
//{
@@ -2529,7 +2529,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
var timer = new TimerInfo
{
ChannelId = channelId,
- Id = (seriesTimer.Id + parent.ExternalId).GetMD5().ToString("N"),
+ Id = (seriesTimer.Id + parent.ExternalId).GetMD5().ToString("N", CultureInfo.InvariantCulture),
StartDate = parent.StartDate,
EndDate = parent.EndDate.Value,
ProgramId = parent.ExternalId,
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs
index 9a9bae2151..cc9c8e5d29 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs
@@ -87,8 +87,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
CreateNoWindow = true,
UseShellExecute = false,
- // Must consume both stdout and stderr or deadlocks may occur
- //RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
@@ -120,9 +118,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
cancellationToken.Register(Stop);
- // MUST read both stdout and stderr asynchronously or a deadlock may occurr
- //process.BeginOutputReadLine();
-
onStarted();
// Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
@@ -138,11 +133,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
string videoArgs;
if (EncodeVideo(mediaSource))
{
- var maxBitrate = 25000000;
+ const int MaxBitrate = 25000000;
videoArgs = string.Format(
- "-codec:v:0 libx264 -force_key_frames \"expr:gte(t,n_forced*5)\" {0} -pix_fmt yuv420p -preset superfast -crf 23 -b:v {1} -maxrate {1} -bufsize ({1}*2) -vsync -1 -profile:v high -level 41",
- GetOutputSizeParam(),
- maxBitrate.ToString(CultureInfo.InvariantCulture));
+ CultureInfo.InvariantCulture,
+ "-codec:v:0 libx264 -force_key_frames \"expr:gte(t,n_forced*5)\" {0} -pix_fmt yuv420p -preset superfast -crf 23 -b:v {1} -maxrate {1} -bufsize ({1}*2) -vsync -1 -profile:v high -level 41",
+ GetOutputSizeParam(),
+ MaxBitrate);
}
else
{
@@ -151,18 +147,17 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
videoArgs += " -fflags +genpts";
- var durationParam = " -t " + _mediaEncoder.GetTimeParameter(duration.Ticks);
- durationParam = string.Empty;
-
var flags = new List();
if (mediaSource.IgnoreDts)
{
flags.Add("+igndts");
}
+
if (mediaSource.IgnoreIndex)
{
flags.Add("+ignidx");
}
+
if (mediaSource.GenPtsInput)
{
flags.Add("+genpts");
@@ -172,11 +167,9 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (flags.Count > 0)
{
- inputModifier += " -fflags " + string.Join("", flags.ToArray());
+ inputModifier += " -fflags " + string.Join(string.Empty, flags);
}
- var videoStream = mediaSource.VideoStream;
-
if (mediaSource.ReadAtNativeFramerate)
{
inputModifier += " -re";
@@ -200,13 +193,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
var outputParam = string.Empty;
- var commandLineArgs = string.Format("-i \"{0}\"{5} {2} -map_metadata -1 -threads 0 {3}{4}{6} -y \"{1}\"",
+ var commandLineArgs = string.Format(
+ CultureInfo.InvariantCulture,
+ "-i \"{0}\" {2} -map_metadata -1 -threads 0 {3}{4}{5} -y \"{1}\"",
inputTempFile,
targetFile,
videoArgs,
GetAudioArgs(mediaSource),
subtitleArgs,
- durationParam,
outputParam);
return inputModifier + " " + commandLineArgs;
@@ -214,9 +208,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
private static string GetAudioArgs(MediaSourceInfo mediaSource)
{
- var mediaStreams = mediaSource.MediaStreams ?? new List();
- var inputAudioCodec = mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Select(i => i.Codec).FirstOrDefault() ?? string.Empty;
-
return "-codec:a:0 copy";
//var audioChannels = 2;
@@ -257,7 +248,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
_logger.LogInformation("Stopping ffmpeg recording process for {path}", _targetPath);
- //process.Kill();
_process.StandardInput.WriteLine("q");
}
catch (Exception ex)
@@ -309,44 +299,26 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
_hasExited = true;
- DisposeLogStream();
+ _logFileStream?.Dispose();
+ _logFileStream = null;
- try
- {
- var exitCode = process.ExitCode;
+ var exitCode = process.ExitCode;
- _logger.LogInformation("FFMpeg recording exited with code {ExitCode} for {path}", exitCode, _targetPath);
+ _logger.LogInformation("FFMpeg recording exited with code {ExitCode} for {Path}", exitCode, _targetPath);
- if (exitCode == 0)
- {
- _taskCompletionSource.TrySetResult(true);
- }
- else
- {
- _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {path} failed. Exit code {ExitCode}", _targetPath, exitCode)));
- }
- }
- catch
+ if (exitCode == 0)
{
- _logger.LogError("FFMpeg recording exited with an error for {path}.", _targetPath);
- _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {path} failed", _targetPath)));
+ _taskCompletionSource.TrySetResult(true);
}
- }
-
- private void DisposeLogStream()
- {
- if (_logFileStream != null)
+ else
{
- try
- {
- _logFileStream.Dispose();
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error disposing recording log stream");
- }
-
- _logFileStream = null;
+ _taskCompletionSource.TrySetException(
+ new Exception(
+ string.Format(
+ CultureInfo.InvariantCulture,
+ "Recording for {0} failed. Exit code {1}",
+ _targetPath,
+ exitCode)));
}
}
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs
index 9c45ee36a2..9055a70a67 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs
@@ -10,67 +10,64 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
public class ItemDataProvider
where T : class
{
- private readonly object _fileDataLock = new object();
- private List _items;
private readonly IJsonSerializer _jsonSerializer;
- protected readonly ILogger Logger;
private readonly string _dataPath;
- protected readonly Func EqualityComparer;
+ private readonly object _fileDataLock = new object();
+ private T[] _items;
- public ItemDataProvider(IJsonSerializer jsonSerializer, ILogger logger, string dataPath, Func equalityComparer)
+ public ItemDataProvider(
+ IJsonSerializer jsonSerializer,
+ ILogger logger,
+ string dataPath,
+ Func equalityComparer)
{
+ _jsonSerializer = jsonSerializer;
Logger = logger;
_dataPath = dataPath;
EqualityComparer = equalityComparer;
- _jsonSerializer = jsonSerializer;
}
- public IReadOnlyList GetAll()
- {
- lock (_fileDataLock)
- {
- if (_items == null)
- {
- if (!File.Exists(_dataPath))
- {
- return new List();
- }
-
- Logger.LogInformation("Loading live tv data from {0}", _dataPath);
- _items = GetItemsFromFile(_dataPath);
- }
+ protected ILogger Logger { get; }
- return _items.ToList();
- }
- }
+ protected Func EqualityComparer { get; }
- private List GetItemsFromFile(string path)
+ private void EnsureLoaded()
{
- try
+ if (_items != null)
{
- return _jsonSerializer.DeserializeFromFile>(path);
+ return;
}
- catch (Exception ex)
+
+ if (File.Exists(_dataPath))
{
- Logger.LogError(ex, "Error deserializing {Path}", path);
+ Logger.LogInformation("Loading live tv data from {Path}", _dataPath);
+
+ try
+ {
+ _items = _jsonSerializer.DeserializeFromFile(_dataPath);
+ return;
+ }
+ catch (Exception ex)
+ {
+ Logger.LogError(ex, "Error deserializing {Path}", _dataPath);
+ }
}
- return new List();
+ _items = Array.Empty();
}
- private void UpdateList(List newList)
+ private void SaveList()
{
- if (newList == null)
- {
- throw new ArgumentNullException(nameof(newList));
- }
-
Directory.CreateDirectory(Path.GetDirectoryName(_dataPath));
+ _jsonSerializer.SerializeToFile(_items, _dataPath);
+ }
+ public IReadOnlyList GetAll()
+ {
lock (_fileDataLock)
{
- _jsonSerializer.SerializeToFile(newList, _dataPath);
- _items = newList;
+ EnsureLoaded();
+ return (T[])_items.Clone();
}
}
@@ -81,18 +78,20 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
throw new ArgumentNullException(nameof(item));
}
- var list = GetAll().ToList();
-
- var index = list.FindIndex(i => EqualityComparer(i, item));
-
- if (index == -1)
+ lock (_fileDataLock)
{
- throw new ArgumentException("item not found");
- }
+ EnsureLoaded();
- list[index] = item;
+ var index = Array.FindIndex(_items, i => EqualityComparer(i, item));
+ if (index == -1)
+ {
+ throw new ArgumentException("item not found");
+ }
- UpdateList(list);
+ _items[index] = item;
+
+ SaveList();
+ }
}
public virtual void Add(T item)
@@ -102,37 +101,58 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
throw new ArgumentNullException(nameof(item));
}
- var list = GetAll().ToList();
-
- if (list.Any(i => EqualityComparer(i, item)))
+ lock (_fileDataLock)
{
- throw new ArgumentException("item already exists");
- }
+ EnsureLoaded();
- list.Add(item);
+ if (_items.Any(i => EqualityComparer(i, item)))
+ {
+ throw new ArgumentException("item already exists", nameof(item));
+ }
- UpdateList(list);
+ int oldLen = _items.Length;
+ var newList = new T[oldLen + 1];
+ _items.CopyTo(newList, 0);
+ newList[oldLen] = item;
+ _items = newList;
+
+ SaveList();
+ }
}
- public void AddOrUpdate(T item)
+ public virtual void AddOrUpdate(T item)
{
- var list = GetAll().ToList();
-
- if (!list.Any(i => EqualityComparer(i, item)))
- {
- Add(item);
- }
- else
+ lock (_fileDataLock)
{
- Update(item);
+ EnsureLoaded();
+
+ int index = Array.FindIndex(_items, i => EqualityComparer(i, item));
+ if (index == -1)
+ {
+ int oldLen = _items.Length;
+ var newList = new T[oldLen + 1];
+ _items.CopyTo(newList, 0);
+ newList[oldLen] = item;
+ _items = newList;
+ }
+ else
+ {
+ _items[index] = item;
+ }
+
+ SaveList();
}
}
public virtual void Delete(T item)
{
- var list = GetAll().Where(i => !EqualityComparer(i, item)).ToList();
+ lock (_fileDataLock)
+ {
+ EnsureLoaded();
+ _items = _items.Where(i => !EqualityComparer(i, item)).ToArray();
- UpdateList(list);
+ SaveList();
+ }
}
}
}
diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs
index 3c807a8ead..d09b281d4c 100644
--- a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs
+++ b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs
@@ -14,21 +14,19 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
public class TimerManager : ItemDataProvider
{
private readonly ConcurrentDictionary _timers = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase);
- private readonly ILogger _logger;
- public event EventHandler> TimerFired;
-
- public TimerManager(IJsonSerializer jsonSerializer, ILogger logger, string dataPath, ILogger logger1)
+ public TimerManager(IJsonSerializer jsonSerializer, ILogger logger, string dataPath)
: base(jsonSerializer, logger, dataPath, (r1, r2) => string.Equals(r1.Id, r2.Id, StringComparison.OrdinalIgnoreCase))
{
- _logger = logger1;
}
+ public event EventHandler> TimerFired;
+
public void RestartTimers()
{
StopTimers();
- foreach (var item in GetAll().ToList())
+ foreach (var item in GetAll())
{
AddOrUpdateSystemTimer(item);
}
@@ -64,16 +62,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
return;
}
- var list = GetAll().ToList();
+ base.AddOrUpdate(item);
+ }
- if (!list.Any(i => EqualityComparer(i, item)))
- {
- base.Add(item);
- }
- else
- {
- base.Update(item);
- }
+ public override void AddOrUpdate(TimerInfo item)
+ {
+ base.AddOrUpdate(item);
+ AddOrUpdateSystemTimer(item);
}
public override void Add(TimerInfo item)
@@ -89,8 +84,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
private static bool ShouldStartTimer(TimerInfo item)
{
- if (item.Status == RecordingStatus.Completed ||
- item.Status == RecordingStatus.Cancelled)
+ if (item.Status == RecordingStatus.Completed
+ || item.Status == RecordingStatus.Cancelled)
{
return false;
}
@@ -126,12 +121,16 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
if (_timers.TryAdd(item.Id, timer))
{
- _logger.LogInformation("Creating recording timer for {id}, {name}. Timer will fire in {minutes} minutes", item.Id, item.Name, dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture));
+ Logger.LogInformation(
+ "Creating recording timer for {Id}, {Name}. Timer will fire in {Minutes} minutes",
+ item.Id,
+ item.Name,
+ dueTime.TotalMinutes.ToString(CultureInfo.InvariantCulture));
}
else
{
timer.Dispose();
- _logger.LogWarning("Timer already exists for item {id}", item.Id);
+ Logger.LogWarning("Timer already exists for item {Id}", item.Id);
}
}
diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs
index f5dffc22af..9a4c91d0bd 100644
--- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs
+++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs
@@ -17,7 +17,6 @@ using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
-using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.LiveTv.Listings
{
@@ -41,6 +40,12 @@ namespace Emby.Server.Implementations.LiveTv.Listings
private string UserAgent => _appHost.ApplicationUserAgent;
+ ///
+ public string Name => "Schedules Direct";
+
+ ///
+ public string Type => nameof(SchedulesDirect);
+
private static List GetScheduleRequestDates(DateTime startDateUtc, DateTime endDateUtc)
{
var dates = new List();
@@ -103,7 +108,6 @@ namespace Emby.Server.Implementations.LiveTv.Listings
httpOptions.RequestHeaders["token"] = token;
using (var response = await Post(httpOptions, true, info).ConfigureAwait(false))
- using (var reader = new StreamReader(response.Content))
{
var dailySchedules = await _jsonSerializer.DeserializeFromStreamAsync>(response.Content).ConfigureAwait(false);
_logger.LogDebug("Found {ScheduleCount} programs on {ChannelID} ScheduleDirect", dailySchedules.Count, channelId);
@@ -122,7 +126,6 @@ namespace Emby.Server.Implementations.LiveTv.Listings
httpOptions.RequestContent = "[\"" + string.Join("\", \"", programsID) + "\"]";
using (var innerResponse = await Post(httpOptions, true, info).ConfigureAwait(false))
- using (var innerReader = new StreamReader(innerResponse.Content))
{
var programDetails = await _jsonSerializer.DeserializeFromStreamAsync>(innerResponse.Content).ConfigureAwait(false);
var programDict = programDetails.ToDictionary(p => p.programID, y => y);
@@ -152,14 +155,14 @@ namespace Emby.Server.Implementations.LiveTv.Listings
var imagesWithText = allImages.Where(i => string.Equals(i.text, "yes", StringComparison.OrdinalIgnoreCase));
var imagesWithoutText = allImages.Where(i => string.Equals(i.text, "no", StringComparison.OrdinalIgnoreCase));
- const double desiredAspect = 0.666666667;
+ const double DesiredAspect = 2.0 / 3;
- programEntry.primaryImage = GetProgramImage(ApiUrl, imagesWithText, true, desiredAspect) ??
- GetProgramImage(ApiUrl, allImages, true, desiredAspect);
+ programEntry.primaryImage = GetProgramImage(ApiUrl, imagesWithText, true, DesiredAspect) ??
+ GetProgramImage(ApiUrl, allImages, true, DesiredAspect);
- const double wideAspect = 1.77777778;
+ const double WideAspect = 16.0 / 9;
- programEntry.thumbImage = GetProgramImage(ApiUrl, imagesWithText, true, wideAspect);
+ programEntry.thumbImage = GetProgramImage(ApiUrl, imagesWithText, true, WideAspect);
// Don't supply the same image twice
if (string.Equals(programEntry.primaryImage, programEntry.thumbImage, StringComparison.Ordinal))
@@ -167,7 +170,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
programEntry.thumbImage = null;
}
- programEntry.backdropImage = GetProgramImage(ApiUrl, imagesWithoutText, true, wideAspect);
+ programEntry.backdropImage = GetProgramImage(ApiUrl, imagesWithoutText, true, WideAspect);
//programEntry.bannerImage = GetProgramImage(ApiUrl, data, "Banner", false) ??
// GetProgramImage(ApiUrl, data, "Banner-L1", false) ??
@@ -178,6 +181,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
programsInfo.Add(GetProgram(channelId, schedule, programDict[schedule.programID]));
}
+
return programsInfo;
}
}
@@ -185,12 +189,10 @@ namespace Emby.Server.Implementations.LiveTv.Listings
private static int GetSizeOrder(ScheduleDirect.ImageData image)
{
- if (!string.IsNullOrWhiteSpace(image.height))
+ if (!string.IsNullOrWhiteSpace(image.height)
+ && int.TryParse(image.height, out int value))
{
- if (int.TryParse(image.height, out int value))
- {
- return value;
- }
+ return value;
}
return 0;
@@ -736,16 +738,11 @@ namespace Emby.Server.Implementations.LiveTv.Listings
httpOptions.RequestHeaders["token"] = token;
- using (var response = await _httpClient.SendAsync(httpOptions, "PUT"))
+ using (await _httpClient.SendAsync(httpOptions, "PUT"))
{
}
}
- public string Name => "Schedules Direct";
-
- public static string TypeName = "SchedulesDirect";
- public string Type => TypeName;
-
private async Task HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(info.ListingsId))
diff --git a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs
index 94225a0aa9..88693f22a4 100644
--- a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs
+++ b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs
@@ -211,7 +211,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
HasImage = program.Icon != null && !string.IsNullOrEmpty(program.Icon.Source),
OfficialRating = program.Rating != null && !string.IsNullOrEmpty(program.Rating.Value) ? program.Rating.Value : null,
CommunityRating = program.StarRating,
- SeriesId = program.Episode == null ? null : program.Title.GetMD5().ToString("N")
+ SeriesId = program.Episode == null ? null : program.Title.GetMD5().ToString("N", CultureInfo.InvariantCulture)
};
if (string.IsNullOrWhiteSpace(program.ProgramId))
@@ -227,7 +227,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
uniqueString = "-" + programInfo.EpisodeNumber.Value.ToString(CultureInfo.InvariantCulture);
}
- programInfo.ShowId = uniqueString.GetMD5().ToString("N");
+ programInfo.ShowId = uniqueString.GetMD5().ToString("N", CultureInfo.InvariantCulture);
// If we don't have valid episode info, assume it's a unique program, otherwise recordings might be skipped
if (programInfo.IsSeries
diff --git a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs
index 1144c9ab17..e584664c94 100644
--- a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs
+++ b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs
@@ -1,4 +1,5 @@
using System;
+using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -52,7 +53,7 @@ namespace Emby.Server.Implementations.LiveTv
ExternalId = info.Id,
ChannelId = GetInternalChannelId(service.Name, info.ChannelId),
Status = info.Status,
- SeriesTimerId = string.IsNullOrEmpty(info.SeriesTimerId) ? null : GetInternalSeriesTimerId(info.SeriesTimerId).ToString("N"),
+ SeriesTimerId = string.IsNullOrEmpty(info.SeriesTimerId) ? null : GetInternalSeriesTimerId(info.SeriesTimerId).ToString("N", CultureInfo.InvariantCulture),
PrePaddingSeconds = info.PrePaddingSeconds,
PostPaddingSeconds = info.PostPaddingSeconds,
IsPostPaddingRequired = info.IsPostPaddingRequired,
@@ -69,7 +70,7 @@ namespace Emby.Server.Implementations.LiveTv
if (!string.IsNullOrEmpty(info.ProgramId))
{
- dto.ProgramId = GetInternalProgramId(info.ProgramId).ToString("N");
+ dto.ProgramId = GetInternalProgramId(info.ProgramId).ToString("N", CultureInfo.InvariantCulture);
}
if (program != null)
@@ -107,7 +108,7 @@ namespace Emby.Server.Implementations.LiveTv
{
var dto = new SeriesTimerInfoDto
{
- Id = GetInternalSeriesTimerId(info.Id).ToString("N"),
+ Id = GetInternalSeriesTimerId(info.Id).ToString("N", CultureInfo.InvariantCulture),
Overview = info.Overview,
EndDate = info.EndDate,
Name = info.Name,
@@ -139,7 +140,7 @@ namespace Emby.Server.Implementations.LiveTv
if (!string.IsNullOrEmpty(info.ProgramId))
{
- dto.ProgramId = GetInternalProgramId(info.ProgramId).ToString("N");
+ dto.ProgramId = GetInternalProgramId(info.ProgramId).ToString("N", CultureInfo.InvariantCulture);
}
dto.DayPattern = info.Days == null ? null : GetDayPattern(info.Days.ToArray());
@@ -169,7 +170,7 @@ namespace Emby.Server.Implementations.LiveTv
try
{
dto.ParentThumbImageTag = _imageProcessor.GetImageCacheTag(librarySeries, image);
- dto.ParentThumbItemId = librarySeries.Id.ToString("N");
+ dto.ParentThumbItemId = librarySeries.Id.ToString("N", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
@@ -185,7 +186,7 @@ namespace Emby.Server.Implementations.LiveTv
{
_imageProcessor.GetImageCacheTag(librarySeries, image)
};
- dto.ParentBackdropItemId = librarySeries.Id.ToString("N");
+ dto.ParentBackdropItemId = librarySeries.Id.ToString("N", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
@@ -213,7 +214,7 @@ namespace Emby.Server.Implementations.LiveTv
try
{
dto.ParentPrimaryImageTag = _imageProcessor.GetImageCacheTag(program, image);
- dto.ParentPrimaryImageItemId = program.Id.ToString("N");
+ dto.ParentPrimaryImageItemId = program.Id.ToString("N", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
@@ -232,7 +233,7 @@ namespace Emby.Server.Implementations.LiveTv
{
_imageProcessor.GetImageCacheTag(program, image)
};
- dto.ParentBackdropItemId = program.Id.ToString("N");
+ dto.ParentBackdropItemId = program.Id.ToString("N", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
@@ -263,7 +264,7 @@ namespace Emby.Server.Implementations.LiveTv
try
{
dto.ParentThumbImageTag = _imageProcessor.GetImageCacheTag(librarySeries, image);
- dto.ParentThumbItemId = librarySeries.Id.ToString("N");
+ dto.ParentThumbItemId = librarySeries.Id.ToString("N", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
@@ -279,7 +280,7 @@ namespace Emby.Server.Implementations.LiveTv
{
_imageProcessor.GetImageCacheTag(librarySeries, image)
};
- dto.ParentBackdropItemId = librarySeries.Id.ToString("N");
+ dto.ParentBackdropItemId = librarySeries.Id.ToString("N", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
@@ -320,7 +321,7 @@ namespace Emby.Server.Implementations.LiveTv
try
{
dto.ParentPrimaryImageTag = _imageProcessor.GetImageCacheTag(program, image);
- dto.ParentPrimaryImageItemId = program.Id.ToString("N");
+ dto.ParentPrimaryImageItemId = program.Id.ToString("N", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
@@ -339,7 +340,7 @@ namespace Emby.Server.Implementations.LiveTv
{
_imageProcessor.GetImageCacheTag(program, image)
};
- dto.ParentBackdropItemId = program.Id.ToString("N");
+ dto.ParentBackdropItemId = program.Id.ToString("N", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
@@ -407,7 +408,7 @@ namespace Emby.Server.Implementations.LiveTv
{
var name = ServiceName + externalId + InternalVersionNumber;
- return name.ToLowerInvariant().GetMD5().ToString("N");
+ return name.ToLowerInvariant().GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
public Guid GetInternalSeriesTimerId(string externalId)
diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs
index 9093d9740f..89b92c999e 100644
--- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs
+++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -59,16 +60,6 @@ namespace Emby.Server.Implementations.LiveTv
private IListingsProvider[] _listingProviders = Array.Empty();
private readonly IFileSystem _fileSystem;
- public event EventHandler> SeriesTimerCancelled;
- public event EventHandler> TimerCancelled;
- public event EventHandler> TimerCreated;
- public event EventHandler> SeriesTimerCreated;
-
- public string GetEmbyTvActiveRecordingPath(string id)
- {
- return EmbyTV.EmbyTV.Current.GetActiveRecordingPath(id);
- }
-
public LiveTvManager(
IServerApplicationHost appHost,
IServerConfigurationManager config,
@@ -101,17 +92,34 @@ namespace Emby.Server.Implementations.LiveTv
_tvDtoService = new LiveTvDtoService(dtoService, imageProcessor, loggerFactory, appHost, _libraryManager);
}
+ public event EventHandler> SeriesTimerCancelled;
+
+ public event EventHandler> TimerCancelled;
+
+ public event EventHandler> TimerCreated;
+
+ public event EventHandler> SeriesTimerCreated;
+
///
/// Gets the services.
///
/// The services.
public IReadOnlyList Services => _services;
+ public ITunerHost[] TunerHosts => _tunerHosts;
+
+ public IListingsProvider[] ListingProviders => _listingProviders;
+
private LiveTvOptions GetConfiguration()
{
return _config.GetConfiguration("livetv");
}
+ public string GetEmbyTvActiveRecordingPath(string id)
+ {
+ return EmbyTV.EmbyTV.Current.GetActiveRecordingPath(id);
+ }
+
///
/// Adds the parts.
///
@@ -129,13 +137,13 @@ namespace Emby.Server.Implementations.LiveTv
{
if (service is EmbyTV.EmbyTV embyTv)
{
- embyTv.TimerCreated += EmbyTv_TimerCreated;
- embyTv.TimerCancelled += EmbyTv_TimerCancelled;
+ embyTv.TimerCreated += OnEmbyTvTimerCreated;
+ embyTv.TimerCancelled += OnEmbyTvTimerCancelled;
}
}
}
- private void EmbyTv_TimerCancelled(object sender, GenericEventArgs e)
+ private void OnEmbyTvTimerCancelled(object sender, GenericEventArgs e)
{
var timerId = e.Argument;
@@ -148,10 +156,9 @@ namespace Emby.Server.Implementations.LiveTv
});
}
- private void EmbyTv_TimerCreated(object sender, GenericEventArgs e)
+ private void OnEmbyTvTimerCreated(object sender, GenericEventArgs e)
{
var timer = e.Argument;
- var service = sender as ILiveTvService;
TimerCreated?.Invoke(this, new GenericEventArgs
{
@@ -163,10 +170,6 @@ namespace Emby.Server.Implementations.LiveTv
});
}
- public ITunerHost[] TunerHosts => _tunerHosts;
-
- public IListingsProvider[] ListingProviders => _listingProviders;
-
public List GetTunerHostTypes()
{
return _tunerHosts.OrderBy(i => i.Name).Select(i => new NameIdPair
@@ -258,7 +261,7 @@ namespace Emby.Server.Implementations.LiveTv
}
info.RequiresClosing = true;
- var idPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
+ var idPrefix = service.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture) + "_";
info.LiveStreamId = idPrefix + info.Id;
@@ -820,7 +823,7 @@ namespace Emby.Server.Implementations.LiveTv
if (!string.IsNullOrWhiteSpace(query.SeriesTimerId))
{
var seriesTimers = await GetSeriesTimersInternal(new SeriesTimerQuery { }, cancellationToken).ConfigureAwait(false);
- var seriesTimer = seriesTimers.Items.FirstOrDefault(i => string.Equals(_tvDtoService.GetInternalSeriesTimerId(i.Id).ToString("N"), query.SeriesTimerId, StringComparison.OrdinalIgnoreCase));
+ var seriesTimer = seriesTimers.Items.FirstOrDefault(i => string.Equals(_tvDtoService.GetInternalSeriesTimerId(i.Id).ToString("N", CultureInfo.InvariantCulture), query.SeriesTimerId, StringComparison.OrdinalIgnoreCase));
if (seriesTimer != null)
{
internalQuery.ExternalSeriesId = seriesTimer.SeriesId;
@@ -880,7 +883,7 @@ namespace Emby.Server.Implementations.LiveTv
}
var programList = _libraryManager.QueryItems(internalQuery).Items;
- var totalCount = programList.Length;
+ var totalCount = programList.Count;
var orderedPrograms = programList.Cast().OrderBy(i => i.StartDate.Date);
@@ -965,11 +968,8 @@ namespace Emby.Server.Implementations.LiveTv
private async Task AddRecordingInfo(IEnumerable> programs, CancellationToken cancellationToken)
{
- var timers = new Dictionary>();
- var seriesTimers = new Dictionary>();
-
- TimerInfo[] timerList = null;
- SeriesTimerInfo[] seriesTimerList = null;
+ IReadOnlyList timerList = null;
+ IReadOnlyList seriesTimerList = null;
foreach (var programTuple in programs)
{
@@ -997,7 +997,7 @@ namespace Emby.Server.Implementations.LiveTv
if (!string.IsNullOrEmpty(timer.SeriesTimerId))
{
program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(timer.SeriesTimerId)
- .ToString("N");
+ .ToString("N", CultureInfo.InvariantCulture);
foundSeriesTimer = true;
}
@@ -1018,7 +1018,7 @@ namespace Emby.Server.Implementations.LiveTv
if (seriesTimer != null)
{
program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(seriesTimer.Id)
- .ToString("N");
+ .ToString("N", CultureInfo.InvariantCulture);
}
}
}
@@ -1295,6 +1295,7 @@ namespace Emby.Server.Implementations.LiveTv
}
private const int MaxGuideDays = 14;
+
private double GetGuideDays()
{
var config = GetConfiguration();
@@ -1339,6 +1340,7 @@ namespace Emby.Server.Implementations.LiveTv
excludeItemTypes.Add(typeof(Movie).Name);
}
}
+
if (query.IsSeries.HasValue)
{
if (query.IsSeries.Value)
@@ -1350,10 +1352,12 @@ namespace Emby.Server.Implementations.LiveTv
excludeItemTypes.Add(typeof(Episode).Name);
}
}
+
if (query.IsSports ?? false)
{
genres.Add("Sports");
}
+
if (query.IsKids ?? false)
{
genres.Add("Kids");
@@ -1399,20 +1403,20 @@ namespace Emby.Server.Implementations.LiveTv
if (query.IsInProgress ?? false)
{
- //TODO Fix The co-variant conversion between Video[] and BaseItem[], this can generate runtime issues.
+ // TODO: Fix The co-variant conversion between Video[] and BaseItem[], this can generate runtime issues.
result.Items = result
.Items
.OfType()
.Where(i => !i.IsCompleteMedia)
.ToArray();
- result.TotalRecordCount = result.Items.Length;
+ result.TotalRecordCount = result.Items.Count;
}
return result;
}
- public Task AddInfoToProgramDto(List> tuples, ItemFields[] fields, User user = null)
+ public Task AddInfoToProgramDto(IReadOnlyCollection<(BaseItem, BaseItemDto)> tuples, ItemFields[] fields, User user = null)
{
var programTuples = new List>();
var hasChannelImage = fields.Contains(ItemFields.ChannelImage);
@@ -1472,7 +1476,7 @@ namespace Emby.Server.Implementations.LiveTv
dto.SeriesTimerId = string.IsNullOrEmpty(info.SeriesTimerId)
? null
- : _tvDtoService.GetInternalSeriesTimerId(info.SeriesTimerId).ToString("N");
+ : _tvDtoService.GetInternalSeriesTimerId(info.SeriesTimerId).ToString("N", CultureInfo.InvariantCulture);
dto.TimerId = string.IsNullOrEmpty(info.Id)
? null
@@ -1596,8 +1600,6 @@ namespace Emby.Server.Implementations.LiveTv
if (!string.IsNullOrEmpty(query.Id))
{
- var guid = new Guid(query.Id);
-
timers = timers
.Where(i => string.Equals(_tvDtoService.GetInternalTimerId(i.Item1.Id), query.Id, StringComparison.OrdinalIgnoreCase));
}
@@ -1876,7 +1878,7 @@ namespace Emby.Server.Implementations.LiveTv
return _libraryManager.GetItemById(internalChannelId);
}
- public void AddChannelInfo(List> tuples, DtoOptions options, User user)
+ public void AddChannelInfo(IReadOnlyCollection<(BaseItemDto, LiveTvChannel)> tuples, DtoOptions options, User user)
{
var now = DateTime.UtcNow;
@@ -2027,7 +2029,7 @@ namespace Emby.Server.Implementations.LiveTv
info.StartDate = program.StartDate;
info.Name = program.Name;
info.Overview = program.Overview;
- info.ProgramId = programDto.Id.ToString("N");
+ info.ProgramId = programDto.Id.ToString("N", CultureInfo.InvariantCulture);
info.ExternalProgramId = program.ExternalId;
if (program.EndDate.HasValue)
@@ -2088,7 +2090,7 @@ namespace Emby.Server.Implementations.LiveTv
if (service is ISupportsNewTimerIds supportsNewTimerIds)
{
newTimerId = await supportsNewTimerIds.CreateSeriesTimer(info, cancellationToken).ConfigureAwait(false);
- newTimerId = _tvDtoService.GetInternalSeriesTimerId(newTimerId).ToString("N");
+ newTimerId = _tvDtoService.GetInternalSeriesTimerId(newTimerId).ToString("N", CultureInfo.InvariantCulture);
}
else
{
@@ -2192,7 +2194,7 @@ namespace Emby.Server.Implementations.LiveTv
info.EnabledUsers = _userManager.Users
.Where(IsLiveTvEnabled)
- .Select(i => i.Id.ToString("N"))
+ .Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture))
.ToArray();
return info;
@@ -2219,7 +2221,7 @@ namespace Emby.Server.Implementations.LiveTv
{
var parts = id.Split(new[] { '_' }, 2);
- var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
+ var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture), parts[0], StringComparison.OrdinalIgnoreCase));
if (service == null)
{
@@ -2269,7 +2271,7 @@ namespace Emby.Server.Implementations.LiveTv
if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
{
- info.Id = Guid.NewGuid().ToString("N");
+ info.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
list.Add(info);
config.TunerHosts = list.ToArray();
}
@@ -2312,7 +2314,7 @@ namespace Emby.Server.Implementations.LiveTv
if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
{
- info.Id = Guid.NewGuid().ToString("N");
+ info.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
list.Add(info);
config.ListingProviders = list.ToArray();
}
diff --git a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs
index cd1731de55..52d60c004a 100644
--- a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs
+++ b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -101,7 +102,7 @@ namespace Emby.Server.Implementations.LiveTv
{
var openKeys = new List