소스 검색

Merge branch 'master' into subtitle-display-title

redSpoutnik 6 년 전
부모
커밋
480a6607e2
100개의 변경된 파일1944개의 추가작업 그리고 2270개의 파일을 삭제
  1. 192 0
      .ci/azure-pipelines.yml
  2. 0 81
      .drone.yml
  3. 2 2
      BDInfo/Properties/AssemblyInfo.cs
  4. 1 0
      CONTRIBUTORS.md
  5. 2 3
      Dockerfile
  6. 2 2
      Dockerfile.arm
  7. 2 2
      Dockerfile.arm64
  8. 0 36
      DvdLib/Ifo/AudioAttributes.cs
  9. 0 17
      DvdLib/Ifo/PgcCommandTable.cs
  10. 0 4
      DvdLib/Ifo/ProgramChain.cs
  11. 0 46
      DvdLib/Ifo/VideoAttributes.cs
  12. 2 2
      DvdLib/Properties/AssemblyInfo.cs
  13. 5 5
      Emby.Dlna/Api/DlnaServerService.cs
  14. 3 7
      Emby.Dlna/ConnectionManager/ConnectionManager.cs
  15. 2 2
      Emby.Dlna/ConnectionManager/ControlHandler.cs
  16. 7 6
      Emby.Dlna/ContentDirectory/ContentDirectory.cs
  17. 16 3
      Emby.Dlna/ContentDirectory/ControlHandler.cs
  18. 3 3
      Emby.Dlna/ControlRequest.cs
  19. 8 9
      Emby.Dlna/DlnaManager.cs
  20. 5 0
      Emby.Dlna/Emby.Dlna.csproj
  21. 1 4
      Emby.Dlna/IUpnpService.cs
  22. 9 14
      Emby.Dlna/Main/DlnaEntryPoint.cs
  23. 2 3
      Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs
  24. 3 7
      Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs
  25. 0 9
      Emby.Dlna/PlayTo/CurrentIdEventArgs.cs
  26. 6 3
      Emby.Dlna/PlayTo/Device.cs
  27. 12 11
      Emby.Dlna/PlayTo/PlayToController.cs
  28. 0 2
      Emby.Dlna/PlayTo/PlaylistItemFactory.cs
  29. 0 9
      Emby.Dlna/PlayTo/TransportStateEventArgs.cs
  30. 0 47
      Emby.Dlna/PlayTo/uParser.cs
  31. 0 9
      Emby.Dlna/PlayTo/uParserObject.cs
  32. 2 2
      Emby.Dlna/Properties/AssemblyInfo.cs
  33. 8 9
      Emby.Dlna/Service/BaseControlHandler.cs
  34. 6 2
      Emby.Drawing/ImageProcessor.cs
  35. 2 2
      Emby.Drawing/Properties/AssemblyInfo.cs
  36. 4 6
      Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs
  37. 2 2
      Emby.IsoMounting/IsoMounter/Properties/AssemblyInfo.cs
  38. 2 2
      Emby.Naming/Properties/AssemblyInfo.cs
  39. 2 2
      Emby.Notifications/Properties/AssemblyInfo.cs
  40. 2 2
      Emby.Photos/Properties/AssemblyInfo.cs
  41. 74 107
      Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs
  42. 9 1
      Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs
  43. 208 265
      Emby.Server.Implementations/ApplicationHost.cs
  44. 2 2
      Emby.Server.Implementations/Collections/CollectionImageProvider.cs
  45. 2 1
      Emby.Server.Implementations/ConfigurationOptions.cs
  46. 129 0
      Emby.Server.Implementations/Cryptography/CryptographyProvider.cs
  47. 1 3
      Emby.Server.Implementations/Data/SqliteItemRepository.cs
  48. 34 0
      Emby.Server.Implementations/Data/SqliteUserRepository.cs
  49. 2 7
      Emby.Server.Implementations/Data/TypeMapper.cs
  50. 43 29
      Emby.Server.Implementations/Diagnostics/CommonProcess.cs
  51. 23 2
      Emby.Server.Implementations/Emby.Server.Implementations.csproj
  52. 0 36
      Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs
  53. 0 24
      Emby.Server.Implementations/FFMpeg/FFMpegInfo.cs
  54. 0 17
      Emby.Server.Implementations/FFMpeg/FFMpegInstallInfo.cs
  55. 0 132
      Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs
  56. 3 3
      Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs
  57. 21 25
      Emby.Server.Implementations/HttpServer/FileWriter.cs
  58. 39 52
      Emby.Server.Implementations/HttpServer/HttpListenerHost.cs
  59. 32 56
      Emby.Server.Implementations/HttpServer/HttpResultFactory.cs
  60. 3 14
      Emby.Server.Implementations/HttpServer/IHttpListener.cs
  61. 4 5
      Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs
  62. 5 5
      Emby.Server.Implementations/HttpServer/ResponseFilter.cs
  63. 2 1
      Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs
  64. 4 12
      Emby.Server.Implementations/HttpServer/StreamWriter.cs
  65. 3 36
      Emby.Server.Implementations/HttpServer/WebSocketConnection.cs
  66. 3 12
      Emby.Server.Implementations/IO/LibraryMonitor.cs
  67. 10 13
      Emby.Server.Implementations/IO/ManagedFileSystem.cs
  68. 136 90
      Emby.Server.Implementations/IO/StreamHelper.cs
  69. 0 5
      Emby.Server.Implementations/IStartupOptions.cs
  70. 22 36
      Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs
  71. 120 21
      Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs
  72. 174 172
      Emby.Server.Implementations/Library/LibraryManager.cs
  73. 14 23
      Emby.Server.Implementations/Library/UserManager.cs
  74. 2 6
      Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs
  75. 10 16
      Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs
  76. 3 2
      Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs
  77. 2 1
      Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs
  78. 19 39
      Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs
  79. 2 1
      Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs
  80. 92 92
      Emby.Server.Implementations/Localization/Core/es-AR.json
  81. 85 85
      Emby.Server.Implementations/Localization/Core/fr-CA.json
  82. 2 2
      Emby.Server.Implementations/Localization/Core/fr.json
  83. 3 3
      Emby.Server.Implementations/Localization/Core/he.json
  84. 6 6
      Emby.Server.Implementations/Localization/Core/it.json
  85. 5 5
      Emby.Server.Implementations/Localization/Core/kk.json
  86. 8 8
      Emby.Server.Implementations/Localization/Core/pt-BR.json
  87. 56 56
      Emby.Server.Implementations/Localization/Core/sl-SI.json
  88. 18 18
      Emby.Server.Implementations/Localization/Core/tr.json
  89. 3 3
      Emby.Server.Implementations/Localization/Core/zh-CN.json
  90. 41 144
      Emby.Server.Implementations/Localization/LocalizationManager.cs
  91. 8 0
      Emby.Server.Implementations/Localization/Ratings/au.csv
  92. 6 0
      Emby.Server.Implementations/Localization/Ratings/be.csv
  93. 10 0
      Emby.Server.Implementations/Localization/Ratings/de.csv
  94. 5 0
      Emby.Server.Implementations/Localization/Ratings/ru.csv
  95. 4 0
      Emby.Server.Implementations/MediaEncoder/EncodingManager.cs
  96. 39 0
      Emby.Server.Implementations/Middleware/WebSocketMiddleware.cs
  97. 0 66
      Emby.Server.Implementations/Net/DisposableManagedObjectBase.cs
  98. 0 5
      Emby.Server.Implementations/Net/IWebSocket.cs
  99. 41 93
      Emby.Server.Implementations/Net/SocketFactory.cs
  100. 37 35
      Emby.Server.Implementations/Net/UdpSocket.cs

+ 192 - 0
.ci/azure-pipelines.yml

@@ -0,0 +1,192 @@
+name: $(Date:yyyyMMdd)$(Rev:.r)
+
+variables:
+  - name: TestProjects
+    value: 'Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj'
+  - name: RestoreBuildProjects
+    value: 'Jellyfin.Server/Jellyfin.Server.csproj'
+
+pr:
+  autoCancel: true
+
+trigger:
+  batch: true
+
+jobs:
+  - job: main_build
+    displayName: Main Build
+    pool:
+      vmImage: ubuntu-16.04
+    strategy:
+      matrix:
+        release:
+          BuildConfiguration: Release
+        debug:
+          BuildConfiguration: Debug
+      maxParallel: 2
+    steps:
+    - checkout: self
+      clean: true
+      submodules: true
+      persistCredentials: false
+
+    - task: DotNetCoreCLI@2
+      displayName: Restore
+      inputs:
+        command: restore
+        projects: '$(RestoreBuildProjects)'
+
+    - task: DotNetCoreCLI@2
+      displayName: Build
+      inputs:
+        projects: '$(RestoreBuildProjects)'
+        arguments: '--configuration $(BuildConfiguration)'
+
+    - task: DotNetCoreCLI@2
+      displayName: Test
+      inputs:
+        command: test
+        projects: '$(RestoreBuildProjects)'
+        arguments: '--configuration $(BuildConfiguration)'
+      enabled: false
+
+    - task: DotNetCoreCLI@2
+      displayName: Publish
+      inputs:
+        command: publish
+        publishWebProjects: false
+        projects: '$(RestoreBuildProjects)'
+        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: PublishBuildArtifacts@1
+      displayName: 'Publish Artifact Naming'
+      condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded())
+      inputs:
+        PathtoPublish: '$(build.artifactstagingdirectory)/Jellyfin.Server/Emby.Naming.dll'
+        artifactName: 'Jellyfin.Naming'
+
+    - task: PublishBuildArtifacts@1
+      displayName: 'Publish Artifact Controller'
+      condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded())
+      inputs:
+        PathtoPublish: '$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Controller.dll'
+        artifactName: 'Jellyfin.Controller'
+
+    - task: PublishBuildArtifacts@1
+      displayName: 'Publish Artifact Model'
+      condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded())
+      inputs:
+        PathtoPublish: '$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Model.dll'
+        artifactName: 'Jellyfin.Model'
+
+    - task: PublishBuildArtifacts@1
+      displayName: 'Publish Artifact Common'
+      condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded())
+      inputs:
+        PathtoPublish: '$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Common.dll'
+        artifactName: 'Jellyfin.Common'
+
+  - job: dotnet_compat
+    displayName: Compatibility Check
+    pool:
+      vmImage: ubuntu-16.04
+    dependsOn: main_build
+    condition: and(succeeded(), variables['System.PullRequest.PullRequestNumber']) # Only execute if the pullrequest numer is defined. (So not for normal CI builds)
+    strategy:
+      matrix:
+        Naming:
+          NugetPackageName: Jellyfin.Naming
+          AssemblyFileName: Emby.Naming.dll
+        Controller:
+          NugetPackageName: Jellyfin.Controller
+          AssemblyFileName: MediaBrowser.Controller.dll
+        Model:
+          NugetPackageName: Jellyfin.Model
+          AssemblyFileName: MediaBrowser.Model.dll
+        Common:
+          NugetPackageName: Jellyfin.Common
+          AssemblyFileName: MediaBrowser.Common.dll
+      maxParallel: 2
+    steps:
+    - checkout: none
+
+    - task: DownloadBuildArtifacts@0
+      displayName: Download the Reference Assembly Build Artifact
+      inputs:
+        buildType: 'specific' # Options: current, specific
+        project: $(System.TeamProjectId) # Required when buildType == Specific
+        pipeline: $(System.DefinitionId) # Required when buildType == Specific, not sure if this will take a name too
+        #specificBuildWithTriggering: false # Optional
+        buildVersionToDownload: 'latestFromBranch' # Required when buildType == Specific# Options: latest, latestFromBranch, specific
+        allowPartiallySucceededBuilds: false # Optional
+        branchName: '$(System.PullRequest.TargetBranch)' # Required when buildType == Specific && BuildVersionToDownload == LatestFromBranch
+        #buildId: # Required when buildType == Specific && BuildVersionToDownload == Specific
+        #tags: # Optional
+        downloadType: 'single' # Options: single, specific
+        artifactName: '$(NugetPackageName)'# Required when downloadType == Single
+        #itemPattern: '**' # Optional
+        downloadPath: '$(System.ArtifactsDirectory)/current-artifacts'
+        #parallelizationLimit: '8' # Optional
+
+    - task: CopyFiles@2
+      displayName: Copy Nuget Assembly to current-release folder
+      inputs:
+        sourceFolder: $(System.ArtifactsDirectory)/current-artifacts # Optional
+        contents: '**/*.dll'
+        targetFolder: $(System.ArtifactsDirectory)/current-release
+        cleanTargetFolder: true # Optional
+        overWrite: true # Optional
+        flattenFolders: true # Optional
+
+    - task: DownloadBuildArtifacts@0
+      displayName: Download the New Assembly Build Artifact
+      inputs:
+        buildType: 'current' # Options: current, specific
+        allowPartiallySucceededBuilds: false # Optional
+        downloadType: 'single' # Options: single, specific
+        artifactName: '$(NugetPackageName)' # Required when downloadType == Single
+        downloadPath: '$(System.ArtifactsDirectory)/new-artifacts'
+
+    - task: CopyFiles@2
+      displayName: Copy Artifact Assembly to new-release folder
+      inputs:
+        sourceFolder: $(System.ArtifactsDirectory)/new-artifacts # Optional
+        contents: '**/*.dll'
+        targetFolder: $(System.ArtifactsDirectory)/new-release
+        cleanTargetFolder: true # Optional
+        overWrite: true # Optional
+        flattenFolders: true # Optional
+
+    - task: DownloadGitHubRelease@0
+      displayName: Download ABI compatibility check tool from GitHub
+      inputs:
+        connection: Jellyfin GitHub
+        userRepository: EraYaN/dotnet-compatibility
+        defaultVersionType: 'latest' # Options: latest, specificVersion, specificTag
+        #version: # Required when defaultVersionType != Latest
+        itemPattern: '**-ci.zip' # Optional
+        downloadPath: '$(System.ArtifactsDirectory)'
+
+    - task: ExtractFiles@1
+      displayName: Extract ABI compatibility check tool
+      inputs:
+        archiveFilePatterns: '$(System.ArtifactsDirectory)/*-ci.zip'
+        destinationFolder: $(System.ArtifactsDirectory)/tools
+        cleanDestinationFolder: true
+
+    - task: CmdLine@2
+      displayName: Execute ABI compatibility check tool
+      inputs:
+        script: 'dotnet tools/CompatibilityCheckerCoreCLI.dll current-release/$(AssemblyFileName) new-release/$(AssemblyFileName)'
+        workingDirectory: $(System.ArtifactsDirectory) # Optional
+        #failOnStderr: false # Optional
+
+

+ 0 - 81
.drone.yml

@@ -28,84 +28,3 @@ steps:
   commands:
   commands:
     - dotnet publish "Jellyfin.Server" --configuration Release --output "../ci/ci-release"
     - dotnet publish "Jellyfin.Server" --configuration Release --output "../ci/ci-release"
 
 
----
-
-kind: pipeline
-name: check-abi
-
-steps:
-- name: submodules
-  image: docker:git
-  commands:
-    - git submodule update --init --recursive
-
-- name: build
-  image: microsoft/dotnet:2-sdk
-  commands:
-    - dotnet publish "Jellyfin.Server" --configuration Release --output "../ci/ci-release"
-
-- name: clone-dotnet-compat
-  image: docker:git
-  commands:
-    - git clone --depth 1 https://github.com/EraYaN/dotnet-compatibility ci/dotnet-compatibility
-
-- name: build-dotnet-compat
-  image: microsoft/dotnet:2-sdk
-  commands:
-    - dotnet publish "ci/dotnet-compatibility/CompatibilityCheckerCoreCLI" --configuration Release --output "../../ci-tools"
-
-- name: download-last-nuget-release-common
-  image: plugins/download
-  settings:
-    source: https://www.nuget.org/api/v2/package/Jellyfin.Common
-    destination: ci/Jellyfin.Common.nupkg
-
-- name: download-last-nuget-release-model
-  image: plugins/download
-  settings:
-    source: https://www.nuget.org/api/v2/package/Jellyfin.Model
-    destination: ci/Jellyfin.Model.nupkg
-
-- name: download-last-nuget-release-controller
-  image: plugins/download
-  settings:
-    source: https://www.nuget.org/api/v2/package/Jellyfin.Controller
-    destination: ci/Jellyfin.Controller.nupkg
-
-- name: download-last-nuget-release-naming
-  image: plugins/download
-  settings:
-    source: https://www.nuget.org/api/v2/package/Jellyfin.Naming
-    destination: ci/Jellyfin.Naming.nupkg
-
-- name: extract-downloaded-nuget-packages
-  image: garthk/unzip
-  commands:
-  - unzip -j ci/Jellyfin.Common.nupkg  "*.dll" -d ci/nuget-packages
-  - unzip -j ci/Jellyfin.Model.nupkg  "*.dll" -d ci/nuget-packages
-  - unzip -j ci/Jellyfin.Controller.nupkg  "*.dll" -d ci/nuget-packages
-  - unzip -j ci/Jellyfin.Naming.nupkg  "*.dll" -d ci/nuget-packages
-
-- name: run-dotnet-compat-common
-  image: microsoft/dotnet:2-runtime
-  err_ignore: true
-  commands:
-  - dotnet ci/ci-tools/CompatibilityCheckerCoreCLI.dll ci/nuget-packages/MediaBrowser.Common.dll ci/ci-release/MediaBrowser.Common.dll
-
-- name: run-dotnet-compat-model
-  image: microsoft/dotnet:2-runtime
-  err_ignore: true
-  commands:
-  - dotnet ci/ci-tools/CompatibilityCheckerCoreCLI.dll ci/nuget-packages/MediaBrowser.Model.dll ci/ci-release/MediaBrowser.Model.dll
-
-- name: run-dotnet-compat-controller
-  image: microsoft/dotnet:2-runtime
-  err_ignore: true
-  commands:
-  - dotnet ci/ci-tools/CompatibilityCheckerCoreCLI.dll ci/nuget-packages/MediaBrowser.Controller.dll ci/ci-release/MediaBrowser.Controller.dll
-
-- name: run-dotnet-compat-naming
-  image: microsoft/dotnet:2-runtime
-  err_ignore: true
-  commands:
-  - dotnet ci/ci-tools/CompatibilityCheckerCoreCLI.dll ci/nuget-packages/Emby.Naming.dll ci/ci-release/Emby.Naming.dll

+ 2 - 2
BDInfo/Properties/AssemblyInfo.cs

@@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyDescription("")]
 [assembly: AssemblyDescription("")]
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyCompany("Jellyfin Project")]
 [assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright ©  2016 CinemaSquid. Copyright ©  2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright ©  2016 CinemaSquid. Copyright ©  2019 Jellyfin Contributors. Code released under the GNU General Public License")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyCulture("")]
 [assembly: AssemblyCulture("")]
 [assembly: NeutralResourcesLanguage("en")]
 [assembly: NeutralResourcesLanguage("en")]

+ 1 - 0
CONTRIBUTORS.md

@@ -23,6 +23,7 @@
  - [fruhnow](https://github.com/fruhnow)
  - [fruhnow](https://github.com/fruhnow)
  - [Lynxy](https://github.com/Lynxy)
  - [Lynxy](https://github.com/Lynxy)
  - [fasheng](https://github.com/fasheng)
  - [fasheng](https://github.com/fasheng)
+ - [ploughpuff](https://github.com/ploughpuff) 
 
 
 # Emby Contributors
 # Emby Contributors
 
 

+ 2 - 3
Dockerfile

@@ -15,7 +15,7 @@ RUN apt-get update \
    libfontconfig1 \
    libfontconfig1 \
  && apt-get clean autoclean \
  && apt-get clean autoclean \
  && apt-get autoremove \
  && apt-get autoremove \
- && rm -rf /var/lib/{apt,dpkg,cache,log} \
+ && rm -rf /var/lib/apt/lists/* \
  && mkdir -p /cache /config /media \
  && mkdir -p /cache /config /media \
  && chmod 777 /cache /config /media
  && chmod 777 /cache /config /media
 COPY --from=ffmpeg / /
 COPY --from=ffmpeg / /
@@ -31,5 +31,4 @@ VOLUME /cache /config /media
 ENTRYPOINT dotnet /jellyfin/jellyfin.dll \
 ENTRYPOINT dotnet /jellyfin/jellyfin.dll \
     --datadir /config \
     --datadir /config \
     --cachedir /cache \
     --cachedir /cache \
-    --ffmpeg /usr/local/bin/ffmpeg \
-    --ffprobe /usr/local/bin/ffprobe
+    --ffmpeg /usr/local/bin/ffmpeg

+ 2 - 2
Dockerfile.arm

@@ -25,6 +25,7 @@ FROM microsoft/dotnet:${DOTNET_VERSION}-runtime-stretch-slim-arm32v7
 COPY --from=qemu_extract qemu-arm-static /usr/bin
 COPY --from=qemu_extract qemu-arm-static /usr/bin
 RUN apt-get update \
 RUN apt-get update \
  && apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \
  && apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \
+ && rm -rf /var/lib/apt/lists/* \
  && mkdir -p /cache /config /media \
  && mkdir -p /cache /config /media \
  && chmod 777 /cache /config /media
  && chmod 777 /cache /config /media
 COPY --from=builder /jellyfin /jellyfin
 COPY --from=builder /jellyfin /jellyfin
@@ -39,5 +40,4 @@ VOLUME /cache /config /media
 ENTRYPOINT dotnet /jellyfin/jellyfin.dll \
 ENTRYPOINT dotnet /jellyfin/jellyfin.dll \
     --datadir /config \
     --datadir /config \
     --cachedir /cache \
     --cachedir /cache \
-    --ffmpeg /usr/bin/ffmpeg \
-    --ffprobe /usr/bin/ffprobe
+    --ffmpeg /usr/bin/ffmpeg

+ 2 - 2
Dockerfile.arm64

@@ -26,6 +26,7 @@ FROM microsoft/dotnet:${DOTNET_VERSION}-runtime-stretch-slim-arm64v8
 COPY --from=qemu_extract qemu-aarch64-static /usr/bin
 COPY --from=qemu_extract qemu-aarch64-static /usr/bin
 RUN apt-get update \
 RUN apt-get update \
  && apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \
  && apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \
+ && rm -rf /var/lib/apt/lists/* \
  && mkdir -p /cache /config /media \
  && mkdir -p /cache /config /media \
  && chmod 777 /cache /config /media
  && chmod 777 /cache /config /media
 COPY --from=builder /jellyfin /jellyfin
 COPY --from=builder /jellyfin /jellyfin
@@ -40,5 +41,4 @@ VOLUME /cache /config /media
 ENTRYPOINT dotnet /jellyfin/jellyfin.dll \
 ENTRYPOINT dotnet /jellyfin/jellyfin.dll \
     --datadir /config \
     --datadir /config \
     --cachedir /cache \
     --cachedir /cache \
-    --ffmpeg /usr/bin/ffmpeg \
-    --ffprobe /usr/bin/ffprobe
+    --ffmpeg /usr/bin/ffmpeg

+ 0 - 36
DvdLib/Ifo/AudioAttributes.cs

@@ -1,36 +0,0 @@
-namespace DvdLib.Ifo
-{
-    public enum AudioCodec
-    {
-        AC3 = 0,
-        MPEG1 = 2,
-        MPEG2ext = 3,
-        LPCM = 4,
-        DTS = 6,
-    }
-
-    public enum ApplicationMode
-    {
-        Unspecified = 0,
-        Karaoke = 1,
-        Surround = 2,
-    }
-
-    public class AudioAttributes
-    {
-        public readonly AudioCodec Codec;
-        public readonly bool MultichannelExtensionPresent;
-        public readonly ApplicationMode Mode;
-        public readonly byte QuantDRC;
-        public readonly byte SampleRate;
-        public readonly byte Channels;
-        public readonly ushort LanguageCode;
-        public readonly byte LanguageExtension;
-        public readonly byte CodeExtension;
-    }
-
-    public class MultiChannelExtension
-    {
-
-    }
-}

+ 0 - 17
DvdLib/Ifo/PgcCommandTable.cs

@@ -1,17 +0,0 @@
-using System.Collections.Generic;
-
-namespace DvdLib.Ifo
-{
-    public class ProgramChainCommandTable
-    {
-        public readonly ushort LastByteAddress;
-        public readonly List<VirtualMachineCommand> PreCommands;
-        public readonly List<VirtualMachineCommand> PostCommands;
-        public readonly List<VirtualMachineCommand> CellCommands;
-    }
-
-    public class VirtualMachineCommand
-    {
-        public readonly byte[] Command;
-    }
-}

+ 0 - 4
DvdLib/Ifo/ProgramChain.cs

@@ -25,13 +25,10 @@ namespace DvdLib.Ifo
         public byte[] SubpictureStreamControl { get; private set; } // 32*4 entries
         public byte[] SubpictureStreamControl { get; private set; } // 32*4 entries
 
 
         private ushort _nextProgramNumber;
         private ushort _nextProgramNumber;
-        public readonly ProgramChain Next;
 
 
         private ushort _prevProgramNumber;
         private ushort _prevProgramNumber;
-        public readonly ProgramChain Previous;
 
 
         private ushort _goupProgramNumber;
         private ushort _goupProgramNumber;
-        public readonly ProgramChain Goup; // ?? maybe Group
 
 
         public ProgramPlaybackMode PlaybackMode { get; private set; }
         public ProgramPlaybackMode PlaybackMode { get; private set; }
         public uint ProgramCount { get; private set; }
         public uint ProgramCount { get; private set; }
@@ -40,7 +37,6 @@ namespace DvdLib.Ifo
         public byte[] Palette { get; private set; } // 16*4 entries
         public byte[] Palette { get; private set; } // 16*4 entries
 
 
         private ushort _commandTableOffset;
         private ushort _commandTableOffset;
-        public readonly ProgramChainCommandTable CommandTable;
 
 
         private ushort _programMapOffset;
         private ushort _programMapOffset;
         private ushort _cellPlaybackOffset;
         private ushort _cellPlaybackOffset;

+ 0 - 46
DvdLib/Ifo/VideoAttributes.cs

@@ -1,46 +0,0 @@
-namespace DvdLib.Ifo
-{
-    public enum VideoCodec
-    {
-        MPEG1 = 0,
-        MPEG2 = 1,
-    }
-
-    public enum VideoFormat
-    {
-        NTSC = 0,
-        PAL = 1,
-    }
-
-    public enum AspectRatio
-    {
-        ar4to3 = 0,
-        ar16to9 = 3
-    }
-
-    public enum FilmMode
-    {
-        None = -1,
-        Camera = 0,
-        Film = 1,
-    }
-
-    public class VideoAttributes
-    {
-        public readonly VideoCodec Codec;
-        public readonly VideoFormat Format;
-        public readonly AspectRatio Aspect;
-        public readonly bool AutomaticPanScan;
-        public readonly bool AutomaticLetterBox;
-        public readonly bool Line21CCField1;
-        public readonly bool Line21CCField2;
-        public readonly int Width;
-        public readonly int Height;
-        public readonly bool Letterboxed;
-        public readonly FilmMode FilmMode;
-
-        public VideoAttributes()
-        {
-        }
-    }
-}

+ 2 - 2
DvdLib/Properties/AssemblyInfo.cs

@@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyDescription("")]
 [assembly: AssemblyDescription("")]
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyCompany("Jellyfin Project")]
 [assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright ©  2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright ©  2019 Jellyfin Contributors. Code released under the GNU General Public License")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyCulture("")]
 [assembly: AssemblyCulture("")]
 [assembly: NeutralResourcesLanguage("en")]
 [assembly: NeutralResourcesLanguage("en")]

+ 5 - 5
Emby.Dlna/Api/DlnaServerService.cs

@@ -136,7 +136,7 @@ namespace Emby.Dlna.Api
         {
         {
             var url = Request.AbsoluteUri;
             var url = Request.AbsoluteUri;
             var serverAddress = url.Substring(0, url.IndexOf("/dlna/", StringComparison.OrdinalIgnoreCase));
             var serverAddress = url.Substring(0, url.IndexOf("/dlna/", StringComparison.OrdinalIgnoreCase));
-            var xml = _dlnaManager.GetServerDescriptionXml(Request.Headers.ToDictionary(), request.UuId, serverAddress);
+            var xml = _dlnaManager.GetServerDescriptionXml(Request.Headers, request.UuId, serverAddress);
 
 
             var cacheLength = TimeSpan.FromDays(1);
             var cacheLength = TimeSpan.FromDays(1);
             var cacheKey = Request.RawUrl.GetMD5();
             var cacheKey = Request.RawUrl.GetMD5();
@@ -147,21 +147,21 @@ namespace Emby.Dlna.Api
 
 
         public object Get(GetContentDirectory request)
         public object Get(GetContentDirectory request)
         {
         {
-            var xml = ContentDirectory.GetServiceXml(Request.Headers.ToDictionary());
+            var xml = ContentDirectory.GetServiceXml();
 
 
             return _resultFactory.GetResult(Request, xml, XMLContentType);
             return _resultFactory.GetResult(Request, xml, XMLContentType);
         }
         }
 
 
         public object Get(GetMediaReceiverRegistrar request)
         public object Get(GetMediaReceiverRegistrar request)
         {
         {
-            var xml = MediaReceiverRegistrar.GetServiceXml(Request.Headers.ToDictionary());
+            var xml = MediaReceiverRegistrar.GetServiceXml();
 
 
             return _resultFactory.GetResult(Request, xml, XMLContentType);
             return _resultFactory.GetResult(Request, xml, XMLContentType);
         }
         }
 
 
         public object Get(GetConnnectionManager request)
         public object Get(GetConnnectionManager request)
         {
         {
-            var xml = ConnectionManager.GetServiceXml(Request.Headers.ToDictionary());
+            var xml = ConnectionManager.GetServiceXml();
 
 
             return _resultFactory.GetResult(Request, xml, XMLContentType);
             return _resultFactory.GetResult(Request, xml, XMLContentType);
         }
         }
@@ -193,7 +193,7 @@ namespace Emby.Dlna.Api
 
 
             return service.ProcessControlRequest(new ControlRequest
             return service.ProcessControlRequest(new ControlRequest
             {
             {
-                Headers = Request.Headers.ToDictionary(),
+                Headers = Request.Headers,
                 InputXml = requestStream,
                 InputXml = requestStream,
                 TargetServerUuId = id,
                 TargetServerUuId = id,
                 RequestedUrl = Request.AbsoluteUri
                 RequestedUrl = Request.AbsoluteUri

+ 3 - 7
Emby.Dlna/ConnectionManager/ConnectionManager.cs

@@ -1,9 +1,7 @@
-using System.Collections.Generic;
 using Emby.Dlna.Service;
 using Emby.Dlna.Service;
 using MediaBrowser.Common.Net;
 using MediaBrowser.Common.Net;
 using MediaBrowser.Controller.Configuration;
 using MediaBrowser.Controller.Configuration;
 using MediaBrowser.Controller.Dlna;
 using MediaBrowser.Controller.Dlna;
-using MediaBrowser.Model.Xml;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
 
 
 namespace Emby.Dlna.ConnectionManager
 namespace Emby.Dlna.ConnectionManager
@@ -13,18 +11,16 @@ namespace Emby.Dlna.ConnectionManager
         private readonly IDlnaManager _dlna;
         private readonly IDlnaManager _dlna;
         private readonly ILogger _logger;
         private readonly ILogger _logger;
         private readonly IServerConfigurationManager _config;
         private readonly IServerConfigurationManager _config;
-        protected readonly IXmlReaderSettingsFactory XmlReaderSettingsFactory;
 
 
-        public ConnectionManager(IDlnaManager dlna, IServerConfigurationManager config, ILogger logger, IHttpClient httpClient, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
+        public ConnectionManager(IDlnaManager dlna, IServerConfigurationManager config, ILogger logger, IHttpClient httpClient)
             : base(logger, httpClient)
             : base(logger, httpClient)
         {
         {
             _dlna = dlna;
             _dlna = dlna;
             _config = config;
             _config = config;
             _logger = logger;
             _logger = logger;
-            XmlReaderSettingsFactory = xmlReaderSettingsFactory;
         }
         }
 
 
-        public string GetServiceXml(IDictionary<string, string> headers)
+        public string GetServiceXml()
         {
         {
             return new ConnectionManagerXmlBuilder().GetXml();
             return new ConnectionManagerXmlBuilder().GetXml();
         }
         }
@@ -34,7 +30,7 @@ namespace Emby.Dlna.ConnectionManager
             var profile = _dlna.GetProfile(request.Headers) ??
             var profile = _dlna.GetProfile(request.Headers) ??
                          _dlna.GetDefaultProfile();
                          _dlna.GetDefaultProfile();
 
 
-            return new ControlHandler(_config, _logger, XmlReaderSettingsFactory, profile).ProcessControlRequest(request);
+            return new ControlHandler(_config, _logger, profile).ProcessControlRequest(request);
         }
         }
     }
     }
 }
 }

+ 2 - 2
Emby.Dlna/ConnectionManager/ControlHandler.cs

@@ -4,7 +4,6 @@ using Emby.Dlna.Service;
 using MediaBrowser.Common.Extensions;
 using MediaBrowser.Common.Extensions;
 using MediaBrowser.Controller.Configuration;
 using MediaBrowser.Controller.Configuration;
 using MediaBrowser.Model.Dlna;
 using MediaBrowser.Model.Dlna;
-using MediaBrowser.Model.Xml;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
 
 
 namespace Emby.Dlna.ConnectionManager
 namespace Emby.Dlna.ConnectionManager
@@ -32,7 +31,8 @@ namespace Emby.Dlna.ConnectionManager
             };
             };
         }
         }
 
 
-        public ControlHandler(IServerConfigurationManager config, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory, DeviceProfile profile) : base(config, logger, xmlReaderSettingsFactory)
+        public ControlHandler(IServerConfigurationManager config, ILogger logger, DeviceProfile profile)
+            : base(config, logger)
         {
         {
             _profile = profile;
             _profile = profile;
         }
         }

+ 7 - 6
Emby.Dlna/ContentDirectory/ContentDirectory.cs

@@ -11,7 +11,6 @@ using MediaBrowser.Controller.MediaEncoding;
 using MediaBrowser.Controller.TV;
 using MediaBrowser.Controller.TV;
 using MediaBrowser.Model.Dlna;
 using MediaBrowser.Model.Dlna;
 using MediaBrowser.Model.Globalization;
 using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.Xml;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
 
 
 namespace Emby.Dlna.ContentDirectory
 namespace Emby.Dlna.ContentDirectory
@@ -28,7 +27,6 @@ namespace Emby.Dlna.ContentDirectory
         private readonly IMediaSourceManager _mediaSourceManager;
         private readonly IMediaSourceManager _mediaSourceManager;
         private readonly IUserViewManager _userViewManager;
         private readonly IUserViewManager _userViewManager;
         private readonly IMediaEncoder _mediaEncoder;
         private readonly IMediaEncoder _mediaEncoder;
-        protected readonly IXmlReaderSettingsFactory XmlReaderSettingsFactory;
         private readonly ITVSeriesManager _tvSeriesManager;
         private readonly ITVSeriesManager _tvSeriesManager;
 
 
         public ContentDirectory(IDlnaManager dlna,
         public ContentDirectory(IDlnaManager dlna,
@@ -38,7 +36,12 @@ namespace Emby.Dlna.ContentDirectory
             IServerConfigurationManager config,
             IServerConfigurationManager config,
             IUserManager userManager,
             IUserManager userManager,
             ILogger logger,
             ILogger logger,
-            IHttpClient httpClient, ILocalizationManager localization, IMediaSourceManager mediaSourceManager, IUserViewManager userViewManager, IMediaEncoder mediaEncoder, IXmlReaderSettingsFactory xmlReaderSettingsFactory, ITVSeriesManager tvSeriesManager)
+            IHttpClient httpClient,
+            ILocalizationManager localization,
+            IMediaSourceManager mediaSourceManager,
+            IUserViewManager userViewManager,
+            IMediaEncoder mediaEncoder,
+            ITVSeriesManager tvSeriesManager)
             : base(logger, httpClient)
             : base(logger, httpClient)
         {
         {
             _dlna = dlna;
             _dlna = dlna;
@@ -51,7 +54,6 @@ namespace Emby.Dlna.ContentDirectory
             _mediaSourceManager = mediaSourceManager;
             _mediaSourceManager = mediaSourceManager;
             _userViewManager = userViewManager;
             _userViewManager = userViewManager;
             _mediaEncoder = mediaEncoder;
             _mediaEncoder = mediaEncoder;
-            XmlReaderSettingsFactory = xmlReaderSettingsFactory;
             _tvSeriesManager = tvSeriesManager;
             _tvSeriesManager = tvSeriesManager;
         }
         }
 
 
@@ -65,7 +67,7 @@ namespace Emby.Dlna.ContentDirectory
             }
             }
         }
         }
 
 
-        public string GetServiceXml(IDictionary<string, string> headers)
+        public string GetServiceXml()
         {
         {
             return new ContentDirectoryXmlBuilder().GetXml();
             return new ContentDirectoryXmlBuilder().GetXml();
         }
         }
@@ -94,7 +96,6 @@ namespace Emby.Dlna.ContentDirectory
                 _mediaSourceManager,
                 _mediaSourceManager,
                 _userViewManager,
                 _userViewManager,
                 _mediaEncoder,
                 _mediaEncoder,
-                XmlReaderSettingsFactory,
                 _tvSeriesManager)
                 _tvSeriesManager)
                 .ProcessControlRequest(request);
                 .ProcessControlRequest(request);
         }
         }

+ 16 - 3
Emby.Dlna/ContentDirectory/ControlHandler.cs

@@ -25,7 +25,6 @@ using MediaBrowser.Model.Dlna;
 using MediaBrowser.Model.Entities;
 using MediaBrowser.Model.Entities;
 using MediaBrowser.Model.Globalization;
 using MediaBrowser.Model.Globalization;
 using MediaBrowser.Model.Querying;
 using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Xml;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
 
 
 namespace Emby.Dlna.ContentDirectory
 namespace Emby.Dlna.ContentDirectory
@@ -51,8 +50,22 @@ namespace Emby.Dlna.ContentDirectory
 
 
         private readonly DeviceProfile _profile;
         private readonly DeviceProfile _profile;
 
 
-        public ControlHandler(ILogger logger, ILibraryManager libraryManager, DeviceProfile profile, string serverAddress, string accessToken, IImageProcessor imageProcessor, IUserDataManager userDataManager, User user, int systemUpdateId, IServerConfigurationManager config, ILocalizationManager localization, IMediaSourceManager mediaSourceManager, IUserViewManager userViewManager, IMediaEncoder mediaEncoder, IXmlReaderSettingsFactory xmlReaderSettingsFactory, ITVSeriesManager tvSeriesManager)
-            : base(config, logger, xmlReaderSettingsFactory)
+        public ControlHandler(
+            ILogger logger,
+            ILibraryManager libraryManager,
+            DeviceProfile profile,
+            string serverAddress,
+            string accessToken,
+            IImageProcessor imageProcessor,
+            IUserDataManager userDataManager,
+            User user, int systemUpdateId,
+            IServerConfigurationManager config,
+            ILocalizationManager localization,
+            IMediaSourceManager mediaSourceManager,
+            IUserViewManager userViewManager,
+            IMediaEncoder mediaEncoder,
+            ITVSeriesManager tvSeriesManager)
+            : base(config, logger)
         {
         {
             _libraryManager = libraryManager;
             _libraryManager = libraryManager;
             _userDataManager = userDataManager;
             _userDataManager = userDataManager;

+ 3 - 3
Emby.Dlna/ControlRequest.cs

@@ -1,11 +1,11 @@
-using System.Collections.Generic;
 using System.IO;
 using System.IO;
+using Microsoft.AspNetCore.Http;
 
 
 namespace Emby.Dlna
 namespace Emby.Dlna
 {
 {
     public class ControlRequest
     public class ControlRequest
     {
     {
-        public IDictionary<string, string> Headers { get; set; }
+        public IHeaderDictionary Headers { get; set; }
 
 
         public Stream InputXml { get; set; }
         public Stream InputXml { get; set; }
 
 
@@ -15,7 +15,7 @@ namespace Emby.Dlna
 
 
         public ControlRequest()
         public ControlRequest()
         {
         {
-            Headers = new Dictionary<string, string>();
+            Headers = new HeaderDictionary();
         }
         }
     }
     }
 }
 }

+ 8 - 9
Emby.Dlna/DlnaManager.cs

@@ -17,7 +17,9 @@ using MediaBrowser.Model.Dlna;
 using MediaBrowser.Model.Drawing;
 using MediaBrowser.Model.Drawing;
 using MediaBrowser.Model.IO;
 using MediaBrowser.Model.IO;
 using MediaBrowser.Model.Serialization;
 using MediaBrowser.Model.Serialization;
+using Microsoft.AspNetCore.Http;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Primitives;
 
 
 namespace Emby.Dlna
 namespace Emby.Dlna
 {
 {
@@ -203,16 +205,13 @@ namespace Emby.Dlna
             }
             }
         }
         }
 
 
-        public DeviceProfile GetProfile(IDictionary<string, string> headers)
+        public DeviceProfile GetProfile(IHeaderDictionary headers)
         {
         {
             if (headers == null)
             if (headers == null)
             {
             {
                 throw new ArgumentNullException(nameof(headers));
                 throw new ArgumentNullException(nameof(headers));
             }
             }
 
 
-            // Convert to case insensitive
-            headers = new Dictionary<string, string>(headers, StringComparer.OrdinalIgnoreCase);
-
             var profile = GetProfiles().FirstOrDefault(i => i.Identification != null && IsMatch(headers, i.Identification));
             var profile = GetProfiles().FirstOrDefault(i => i.Identification != null && IsMatch(headers, i.Identification));
 
 
             if (profile != null)
             if (profile != null)
@@ -228,12 +227,12 @@ namespace Emby.Dlna
             return profile;
             return profile;
         }
         }
 
 
-        private bool IsMatch(IDictionary<string, string> headers, DeviceIdentification profileInfo)
+        private bool IsMatch(IHeaderDictionary headers, DeviceIdentification profileInfo)
         {
         {
             return profileInfo.Headers.Any(i => IsMatch(headers, i));
             return profileInfo.Headers.Any(i => IsMatch(headers, i));
         }
         }
 
 
-        private bool IsMatch(IDictionary<string, string> headers, HttpHeaderInfo header)
+        private bool IsMatch(IHeaderDictionary headers, HttpHeaderInfo header)
         {
         {
             // Handle invalid user setup
             // Handle invalid user setup
             if (string.IsNullOrEmpty(header.Name))
             if (string.IsNullOrEmpty(header.Name))
@@ -241,14 +240,14 @@ namespace Emby.Dlna
                 return false;
                 return false;
             }
             }
 
 
-            if (headers.TryGetValue(header.Name, out string value))
+            if (headers.TryGetValue(header.Name, out StringValues value))
             {
             {
                 switch (header.Match)
                 switch (header.Match)
                 {
                 {
                     case HeaderMatchType.Equals:
                     case HeaderMatchType.Equals:
                         return string.Equals(value, header.Value, StringComparison.OrdinalIgnoreCase);
                         return string.Equals(value, header.Value, StringComparison.OrdinalIgnoreCase);
                     case HeaderMatchType.Substring:
                     case HeaderMatchType.Substring:
-                        var isMatch = value.IndexOf(header.Value, StringComparison.OrdinalIgnoreCase) != -1;
+                        var isMatch = value.ToString().IndexOf(header.Value, StringComparison.OrdinalIgnoreCase) != -1;
                         //_logger.LogDebug("IsMatch-Substring value: {0} testValue: {1} isMatch: {2}", value, header.Value, isMatch);
                         //_logger.LogDebug("IsMatch-Substring value: {0} testValue: {1} isMatch: {2}", value, header.Value, isMatch);
                         return isMatch;
                         return isMatch;
                     case HeaderMatchType.Regex:
                     case HeaderMatchType.Regex:
@@ -494,7 +493,7 @@ namespace Emby.Dlna
             internal string Path { get; set; }
             internal string Path { get; set; }
         }
         }
 
 
-        public string GetServerDescriptionXml(IDictionary<string, string> headers, string serverUuId, string serverAddress)
+        public string GetServerDescriptionXml(IHeaderDictionary headers, string serverUuId, string serverAddress)
         {
         {
             var profile = GetProfile(headers) ??
             var profile = GetProfile(headers) ??
                           GetDefaultProfile();
                           GetDefaultProfile();

+ 5 - 0
Emby.Dlna/Emby.Dlna.csproj

@@ -58,4 +58,9 @@
     <EmbeddedResource Include="Profiles\Xml\Xbox One.xml" />
     <EmbeddedResource Include="Profiles\Xml\Xbox One.xml" />
   </ItemGroup>
   </ItemGroup>
 
 
+  <ItemGroup>
+    <PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
+    <PackageReference Include="Microsoft.AspNetCore.WebUtilities" Version="2.2.0" />
+  </ItemGroup>
+
 </Project>
 </Project>

+ 1 - 4
Emby.Dlna/IUpnpService.cs

@@ -1,5 +1,3 @@
-using System.Collections.Generic;
-
 namespace Emby.Dlna
 namespace Emby.Dlna
 {
 {
     public interface IUpnpService
     public interface IUpnpService
@@ -7,9 +5,8 @@ namespace Emby.Dlna
         /// <summary>
         /// <summary>
         /// Gets the content directory XML.
         /// Gets the content directory XML.
         /// </summary>
         /// </summary>
-        /// <param name="headers">The headers.</param>
         /// <returns>System.String.</returns>
         /// <returns>System.String.</returns>
-        string GetServiceXml(IDictionary<string, string> headers);
+        string GetServiceXml();
 
 
         /// <summary>
         /// <summary>
         /// Processes the control request.
         /// Processes the control request.

+ 9 - 14
Emby.Dlna/Main/DlnaEntryPoint.cs

@@ -1,5 +1,4 @@
 using System;
 using System;
-using System.Linq;
 using System.Threading;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
 using Emby.Dlna.PlayTo;
 using Emby.Dlna.PlayTo;
@@ -20,10 +19,10 @@ using MediaBrowser.Model.Dlna;
 using MediaBrowser.Model.Globalization;
 using MediaBrowser.Model.Globalization;
 using MediaBrowser.Model.Net;
 using MediaBrowser.Model.Net;
 using MediaBrowser.Model.System;
 using MediaBrowser.Model.System;
-using MediaBrowser.Model.Xml;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
 using Rssdp;
 using Rssdp;
 using Rssdp.Infrastructure;
 using Rssdp.Infrastructure;
+using OperatingSystem =  MediaBrowser.Common.System.OperatingSystem;
 
 
 namespace Emby.Dlna.Main
 namespace Emby.Dlna.Main
 {
 {
@@ -48,9 +47,8 @@ namespace Emby.Dlna.Main
         private readonly IDeviceDiscovery _deviceDiscovery;
         private readonly IDeviceDiscovery _deviceDiscovery;
 
 
         private SsdpDevicePublisher _Publisher;
         private SsdpDevicePublisher _Publisher;
-        
+
         private readonly ISocketFactory _socketFactory;
         private readonly ISocketFactory _socketFactory;
-        private readonly IEnvironmentInfo _environmentInfo;
         private readonly INetworkManager _networkManager;
         private readonly INetworkManager _networkManager;
 
 
         private ISsdpCommunicationsServer _communicationsServer;
         private ISsdpCommunicationsServer _communicationsServer;
@@ -76,10 +74,8 @@ namespace Emby.Dlna.Main
             IDeviceDiscovery deviceDiscovery,
             IDeviceDiscovery deviceDiscovery,
             IMediaEncoder mediaEncoder,
             IMediaEncoder mediaEncoder,
             ISocketFactory socketFactory,
             ISocketFactory socketFactory,
-            IEnvironmentInfo environmentInfo,
             INetworkManager networkManager,
             INetworkManager networkManager,
             IUserViewManager userViewManager,
             IUserViewManager userViewManager,
-            IXmlReaderSettingsFactory xmlReaderSettingsFactory,
             ITVSeriesManager tvSeriesManager)
             ITVSeriesManager tvSeriesManager)
         {
         {
             _config = config;
             _config = config;
@@ -96,11 +92,11 @@ namespace Emby.Dlna.Main
             _deviceDiscovery = deviceDiscovery;
             _deviceDiscovery = deviceDiscovery;
             _mediaEncoder = mediaEncoder;
             _mediaEncoder = mediaEncoder;
             _socketFactory = socketFactory;
             _socketFactory = socketFactory;
-            _environmentInfo = environmentInfo;
             _networkManager = networkManager;
             _networkManager = networkManager;
             _logger = loggerFactory.CreateLogger("Dlna");
             _logger = loggerFactory.CreateLogger("Dlna");
 
 
-            ContentDirectory = new ContentDirectory.ContentDirectory(dlnaManager,
+            ContentDirectory = new ContentDirectory.ContentDirectory(
+                dlnaManager,
                 userDataManager,
                 userDataManager,
                 imageProcessor,
                 imageProcessor,
                 libraryManager,
                 libraryManager,
@@ -112,12 +108,11 @@ namespace Emby.Dlna.Main
                 mediaSourceManager,
                 mediaSourceManager,
                 userViewManager,
                 userViewManager,
                 mediaEncoder,
                 mediaEncoder,
-                xmlReaderSettingsFactory,
                 tvSeriesManager);
                 tvSeriesManager);
 
 
-            ConnectionManager = new ConnectionManager.ConnectionManager(dlnaManager, config, _logger, httpClient, xmlReaderSettingsFactory);
+            ConnectionManager = new ConnectionManager.ConnectionManager(dlnaManager, config, _logger, httpClient);
 
 
-            MediaReceiverRegistrar = new MediaReceiverRegistrar.MediaReceiverRegistrar(_logger, httpClient, config, xmlReaderSettingsFactory);
+            MediaReceiverRegistrar = new MediaReceiverRegistrar.MediaReceiverRegistrar(_logger, httpClient, config);
             Current = this;
             Current = this;
         }
         }
 
 
@@ -169,8 +164,8 @@ namespace Emby.Dlna.Main
             {
             {
                 if (_communicationsServer == null)
                 if (_communicationsServer == null)
                 {
                 {
-                    var enableMultiSocketBinding = _environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows ||
-                                                   _environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Linux;
+                    var enableMultiSocketBinding = OperatingSystem.Id == OperatingSystemId.Windows ||
+                                                   OperatingSystem.Id == OperatingSystemId.Linux;
 
 
                     _communicationsServer = new SsdpCommunicationsServer(_config, _socketFactory, _networkManager, _logger, enableMultiSocketBinding)
                     _communicationsServer = new SsdpCommunicationsServer(_config, _socketFactory, _networkManager, _logger, enableMultiSocketBinding)
                     {
                     {
@@ -230,7 +225,7 @@ namespace Emby.Dlna.Main
 
 
             try
             try
             {
             {
-                _Publisher = new SsdpDevicePublisher(_communicationsServer, _networkManager, _environmentInfo.OperatingSystemName, _environmentInfo.OperatingSystemVersion, _config.GetDlnaConfiguration().SendOnlyMatchedHost);
+                _Publisher = new SsdpDevicePublisher(_communicationsServer, _networkManager, OperatingSystem.Name, Environment.OSVersion.VersionString, _config.GetDlnaConfiguration().SendOnlyMatchedHost);
                 _Publisher.LogFunction = LogMessage;
                 _Publisher.LogFunction = LogMessage;
                 _Publisher.SupportPnpRootDevice = false;
                 _Publisher.SupportPnpRootDevice = false;
 
 

+ 2 - 3
Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs

@@ -3,7 +3,6 @@ using System.Collections.Generic;
 using Emby.Dlna.Service;
 using Emby.Dlna.Service;
 using MediaBrowser.Common.Extensions;
 using MediaBrowser.Common.Extensions;
 using MediaBrowser.Controller.Configuration;
 using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Model.Xml;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
 
 
 namespace Emby.Dlna.MediaReceiverRegistrar
 namespace Emby.Dlna.MediaReceiverRegistrar
@@ -36,8 +35,8 @@ namespace Emby.Dlna.MediaReceiverRegistrar
             };
             };
         }
         }
 
 
-        public ControlHandler(IServerConfigurationManager config, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
-            : base(config, logger, xmlReaderSettingsFactory)
+        public ControlHandler(IServerConfigurationManager config, ILogger logger)
+            : base(config, logger)
         {
         {
         }
         }
     }
     }

+ 3 - 7
Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs

@@ -1,8 +1,6 @@
-using System.Collections.Generic;
 using Emby.Dlna.Service;
 using Emby.Dlna.Service;
 using MediaBrowser.Common.Net;
 using MediaBrowser.Common.Net;
 using MediaBrowser.Controller.Configuration;
 using MediaBrowser.Controller.Configuration;
-using MediaBrowser.Model.Xml;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
 
 
 namespace Emby.Dlna.MediaReceiverRegistrar
 namespace Emby.Dlna.MediaReceiverRegistrar
@@ -10,16 +8,14 @@ namespace Emby.Dlna.MediaReceiverRegistrar
     public class MediaReceiverRegistrar : BaseService, IMediaReceiverRegistrar
     public class MediaReceiverRegistrar : BaseService, IMediaReceiverRegistrar
     {
     {
         private readonly IServerConfigurationManager _config;
         private readonly IServerConfigurationManager _config;
-        protected readonly IXmlReaderSettingsFactory XmlReaderSettingsFactory;
 
 
-        public MediaReceiverRegistrar(ILogger logger, IHttpClient httpClient, IServerConfigurationManager config, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
+        public MediaReceiverRegistrar(ILogger logger, IHttpClient httpClient, IServerConfigurationManager config)
             : base(logger, httpClient)
             : base(logger, httpClient)
         {
         {
             _config = config;
             _config = config;
-            XmlReaderSettingsFactory = xmlReaderSettingsFactory;
         }
         }
 
 
-        public string GetServiceXml(IDictionary<string, string> headers)
+        public string GetServiceXml()
         {
         {
             return new MediaReceiverRegistrarXmlBuilder().GetXml();
             return new MediaReceiverRegistrarXmlBuilder().GetXml();
         }
         }
@@ -28,7 +24,7 @@ namespace Emby.Dlna.MediaReceiverRegistrar
         {
         {
             return new ControlHandler(
             return new ControlHandler(
                 _config,
                 _config,
-                Logger, XmlReaderSettingsFactory)
+                Logger)
                 .ProcessControlRequest(request);
                 .ProcessControlRequest(request);
         }
         }
     }
     }

+ 0 - 9
Emby.Dlna/PlayTo/CurrentIdEventArgs.cs

@@ -1,9 +0,0 @@
-using System;
-
-namespace Emby.Dlna.PlayTo
-{
-    public class CurrentIdEventArgs : EventArgs
-    {
-        public string Id { get; set; }
-    }
-}

+ 6 - 3
Emby.Dlna/PlayTo/Device.cs

@@ -1126,6 +1126,11 @@ namespace Emby.Dlna.PlayTo
 
 
         private void OnPlaybackStart(uBaseObject mediaInfo)
         private void OnPlaybackStart(uBaseObject mediaInfo)
         {
         {
+            if (string.IsNullOrWhiteSpace(mediaInfo.Url))
+            {
+                return;
+            }
+
             PlaybackStart?.Invoke(this, new PlaybackStartEventArgs
             PlaybackStart?.Invoke(this, new PlaybackStartEventArgs
             {
             {
                 MediaInfo = mediaInfo
                 MediaInfo = mediaInfo
@@ -1134,8 +1139,7 @@ namespace Emby.Dlna.PlayTo
 
 
         private void OnPlaybackProgress(uBaseObject mediaInfo)
         private void OnPlaybackProgress(uBaseObject mediaInfo)
         {
         {
-            var mediaUrl = mediaInfo.Url;
-            if (string.IsNullOrWhiteSpace(mediaUrl))
+            if (string.IsNullOrWhiteSpace(mediaInfo.Url))
             {
             {
                 return;
                 return;
             }
             }
@@ -1148,7 +1152,6 @@ namespace Emby.Dlna.PlayTo
 
 
         private void OnPlaybackStop(uBaseObject mediaInfo)
         private void OnPlaybackStop(uBaseObject mediaInfo)
         {
         {
-
             PlaybackStopped?.Invoke(this, new PlaybackStoppedEventArgs
             PlaybackStopped?.Invoke(this, new PlaybackStoppedEventArgs
             {
             {
                 MediaInfo = mediaInfo
                 MediaInfo = mediaInfo

+ 12 - 11
Emby.Dlna/PlayTo/PlayToController.cs

@@ -6,6 +6,7 @@ using System.Threading;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
 using Emby.Dlna.Didl;
 using Emby.Dlna.Didl;
 using MediaBrowser.Common.Configuration;
 using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Extensions;
 using MediaBrowser.Controller.Dlna;
 using MediaBrowser.Controller.Dlna;
 using MediaBrowser.Controller.Drawing;
 using MediaBrowser.Controller.Drawing;
 using MediaBrowser.Controller.Entities;
 using MediaBrowser.Controller.Entities;
@@ -17,8 +18,8 @@ using MediaBrowser.Model.Dto;
 using MediaBrowser.Model.Entities;
 using MediaBrowser.Model.Entities;
 using MediaBrowser.Model.Events;
 using MediaBrowser.Model.Events;
 using MediaBrowser.Model.Globalization;
 using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.Services;
 using MediaBrowser.Model.Session;
 using MediaBrowser.Model.Session;
+using Microsoft.AspNetCore.WebUtilities;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
 
 
 namespace Emby.Dlna.PlayTo
 namespace Emby.Dlna.PlayTo
@@ -847,13 +848,13 @@ namespace Emby.Dlna.PlayTo
                 if (index == -1) return request;
                 if (index == -1) return request;
 
 
                 var query = url.Substring(index + 1);
                 var query = url.Substring(index + 1);
-                QueryParamCollection values = MyHttpUtility.ParseQueryString(query);
+                Dictionary<string, string> values = QueryHelpers.ParseQuery(query).ToDictionary(kv => kv.Key, kv => kv.Value.ToString());
 
 
-                request.DeviceProfileId = values.Get("DeviceProfileId");
-                request.DeviceId = values.Get("DeviceId");
-                request.MediaSourceId = values.Get("MediaSourceId");
-                request.LiveStreamId = values.Get("LiveStreamId");
-                request.IsDirectStream = string.Equals("true", values.Get("Static"), StringComparison.OrdinalIgnoreCase);
+                request.DeviceProfileId = values.GetValueOrDefault("DeviceProfileId");
+                request.DeviceId = values.GetValueOrDefault("DeviceId");
+                request.MediaSourceId = values.GetValueOrDefault("MediaSourceId");
+                request.LiveStreamId = values.GetValueOrDefault("LiveStreamId");
+                request.IsDirectStream = string.Equals("true", values.GetValueOrDefault("Static"), StringComparison.OrdinalIgnoreCase);
 
 
                 request.AudioStreamIndex = GetIntValue(values, "AudioStreamIndex");
                 request.AudioStreamIndex = GetIntValue(values, "AudioStreamIndex");
                 request.SubtitleStreamIndex = GetIntValue(values, "SubtitleStreamIndex");
                 request.SubtitleStreamIndex = GetIntValue(values, "SubtitleStreamIndex");
@@ -867,9 +868,9 @@ namespace Emby.Dlna.PlayTo
             }
             }
         }
         }
 
 
-        private static int? GetIntValue(QueryParamCollection values, string name)
+        private static int? GetIntValue(IReadOnlyDictionary<string, string> values, string name)
         {
         {
-            var value = values.Get(name);
+            var value = values.GetValueOrDefault(name);
 
 
             if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
             if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
             {
             {
@@ -879,9 +880,9 @@ namespace Emby.Dlna.PlayTo
             return null;
             return null;
         }
         }
 
 
-        private static long GetLongValue(QueryParamCollection values, string name)
+        private static long GetLongValue(IReadOnlyDictionary<string, string> values, string name)
         {
         {
-            var value = values.Get(name);
+            var value = values.GetValueOrDefault(name);
 
 
             if (long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
             if (long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
             {
             {

+ 0 - 2
Emby.Dlna/PlayTo/PlaylistItemFactory.cs

@@ -9,8 +9,6 @@ namespace Emby.Dlna.PlayTo
 {
 {
     public class PlaylistItemFactory
     public class PlaylistItemFactory
     {
     {
-        private readonly CultureInfo _usCulture = new CultureInfo("en-US");
-
         public PlaylistItem Create(Photo item, DeviceProfile profile)
         public PlaylistItem Create(Photo item, DeviceProfile profile)
         {
         {
             var playlistItem = new PlaylistItem
             var playlistItem = new PlaylistItem

+ 0 - 9
Emby.Dlna/PlayTo/TransportStateEventArgs.cs

@@ -1,9 +0,0 @@
-using System;
-
-namespace Emby.Dlna.PlayTo
-{
-    public class TransportStateEventArgs : EventArgs
-    {
-        public TRANSPORTSTATE State { get; set; }
-    }
-}

+ 0 - 47
Emby.Dlna/PlayTo/uParser.cs

@@ -1,47 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Xml.Linq;
-
-namespace Emby.Dlna.PlayTo
-{
-    public class uParser
-    {
-        public static IList<uBaseObject> ParseBrowseXml(XDocument doc)
-        {
-            if (doc == null)
-            {
-                throw new ArgumentException("doc");
-            }
-
-            var list = new List<uBaseObject>();
-
-            var document = doc.Document;
-
-            if (document == null)
-                return list;
-
-            var item = (from result in document.Descendants("Result") select result).FirstOrDefault();
-
-            if (item == null)
-                return list;
-
-            var uPnpResponse = XElement.Parse((string)item);
-
-            var uObjects = from container in uPnpResponse.Elements(uPnpNamespaces.containers)
-                           select new uParserObject { Element = container };
-
-            var uObjects2 = from container in uPnpResponse.Elements(uPnpNamespaces.items)
-                            select new uParserObject { Element = container };
-
-            list.AddRange(uObjects.Concat(uObjects2).Select(CreateObjectFromXML).Where(uObject => uObject != null));
-
-            return list;
-        }
-
-        public static uBaseObject CreateObjectFromXML(uParserObject uItem)
-        {
-            return UpnpContainer.Create(uItem.Element);
-        }
-    }
-}

+ 0 - 9
Emby.Dlna/PlayTo/uParserObject.cs

@@ -1,9 +0,0 @@
-using System.Xml.Linq;
-
-namespace Emby.Dlna.PlayTo
-{
-    public class uParserObject
-    {
-        public XElement Element { get; set; }
-    }
-}

+ 2 - 2
Emby.Dlna/Properties/AssemblyInfo.cs

@@ -8,8 +8,8 @@ using System.Resources;
 [assembly: AssemblyDescription("")]
 [assembly: AssemblyDescription("")]
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyCompany("Jellyfin Project")]
 [assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright ©  2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright ©  2019 Jellyfin Contributors. Code released under the GNU General Public License")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyCulture("")]
 [assembly: AssemblyCulture("")]
 [assembly: NeutralResourcesLanguage("en")]
 [assembly: NeutralResourcesLanguage("en")]

+ 8 - 9
Emby.Dlna/Service/BaseControlHandler.cs

@@ -7,7 +7,6 @@ using System.Xml;
 using Emby.Dlna.Didl;
 using Emby.Dlna.Didl;
 using MediaBrowser.Controller.Configuration;
 using MediaBrowser.Controller.Configuration;
 using MediaBrowser.Controller.Extensions;
 using MediaBrowser.Controller.Extensions;
-using MediaBrowser.Model.Xml;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
 
 
 namespace Emby.Dlna.Service
 namespace Emby.Dlna.Service
@@ -18,13 +17,11 @@ namespace Emby.Dlna.Service
 
 
         protected readonly IServerConfigurationManager Config;
         protected readonly IServerConfigurationManager Config;
         protected readonly ILogger _logger;
         protected readonly ILogger _logger;
-        protected readonly IXmlReaderSettingsFactory XmlReaderSettingsFactory;
 
 
-        protected BaseControlHandler(IServerConfigurationManager config, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
+        protected BaseControlHandler(IServerConfigurationManager config, ILogger logger)
         {
         {
             Config = config;
             Config = config;
             _logger = logger;
             _logger = logger;
-            XmlReaderSettingsFactory = xmlReaderSettingsFactory;
         }
         }
 
 
         public ControlResponse ProcessControlRequest(ControlRequest request)
         public ControlResponse ProcessControlRequest(ControlRequest request)
@@ -61,11 +58,13 @@ namespace Emby.Dlna.Service
 
 
             using (var streamReader = new StreamReader(request.InputXml))
             using (var streamReader = new StreamReader(request.InputXml))
             {
             {
-                var readerSettings = XmlReaderSettingsFactory.Create(false);
-
-                readerSettings.CheckCharacters = false;
-                readerSettings.IgnoreProcessingInstructions = true;
-                readerSettings.IgnoreComments = true;
+                var readerSettings = new XmlReaderSettings()
+                {
+                    ValidationType = ValidationType.None,
+                    CheckCharacters = false,
+                    IgnoreProcessingInstructions = true,
+                    IgnoreComments = true
+                };
 
 
                 using (var reader = XmlReader.Create(streamReader, readerSettings))
                 using (var reader = XmlReader.Create(streamReader, readerSettings))
                 {
                 {

+ 6 - 2
Emby.Drawing/ImageProcessor.cs

@@ -180,6 +180,12 @@ namespace Emby.Drawing
 
 
             var supportedImageInfo = await GetSupportedImage(originalImagePath, dateModified).ConfigureAwait(false);
             var supportedImageInfo = await GetSupportedImage(originalImagePath, dateModified).ConfigureAwait(false);
             originalImagePath = supportedImageInfo.path;
             originalImagePath = supportedImageInfo.path;
+
+            if (!File.Exists(originalImagePath))
+            {
+                return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
+            }
+
             dateModified = supportedImageInfo.dateModified;
             dateModified = supportedImageInfo.dateModified;
             bool requiresTransparency = TransparentImageTypes.Contains(Path.GetExtension(originalImagePath));
             bool requiresTransparency = TransparentImageTypes.Contains(Path.GetExtension(originalImagePath));
 
 
@@ -265,8 +271,6 @@ namespace Emby.Drawing
             {
             {
                 // If it fails for whatever reason, return the original image
                 // If it fails for whatever reason, return the original image
                 _logger.LogError(ex, "Error encoding image");
                 _logger.LogError(ex, "Error encoding image");
-
-                // Just spit out the original file if all the options are default
                 return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
                 return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
             }
             }
             finally
             finally

+ 2 - 2
Emby.Drawing/Properties/AssemblyInfo.cs

@@ -8,8 +8,8 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyDescription("")]
 [assembly: AssemblyDescription("")]
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyCompany("Jellyfin Project")]
 [assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright ©  2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright ©  2019 Jellyfin Contributors. Code released under the GNU General Public License")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyCulture("")]
 [assembly: AssemblyCulture("")]
 
 

+ 4 - 6
Emby.IsoMounting/IsoMounter/LinuxIsoManager.cs

@@ -7,6 +7,7 @@ using MediaBrowser.Model.Diagnostics;
 using MediaBrowser.Model.IO;
 using MediaBrowser.Model.IO;
 using MediaBrowser.Model.System;
 using MediaBrowser.Model.System;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
+using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
 
 
 namespace IsoMounter
 namespace IsoMounter
 {
 {
@@ -17,7 +18,6 @@ namespace IsoMounter
 
 
         #region Private Fields
         #region Private Fields
 
 
-        private readonly IEnvironmentInfo EnvironmentInfo;
         private readonly bool ExecutablesAvailable;
         private readonly bool ExecutablesAvailable;
         private readonly ILogger _logger;
         private readonly ILogger _logger;
         private readonly string MountCommand;
         private readonly string MountCommand;
@@ -30,10 +30,8 @@ namespace IsoMounter
 
 
         #region Constructor(s)
         #region Constructor(s)
 
 
-        public LinuxIsoManager(ILogger logger, IEnvironmentInfo environment, IProcessFactory processFactory)
+        public LinuxIsoManager(ILogger logger, IProcessFactory processFactory)
         {
         {
-
-            EnvironmentInfo = environment;
             _logger = logger;
             _logger = logger;
             ProcessFactory = processFactory;
             ProcessFactory = processFactory;
 
 
@@ -109,7 +107,7 @@ namespace IsoMounter
         public bool CanMount(string path)
         public bool CanMount(string path)
         {
         {
 
 
-            if (EnvironmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Linux)
+            if (OperatingSystem.Id != OperatingSystemId.Linux)
             {
             {
                 return false;
                 return false;
             }
             }
@@ -118,7 +116,7 @@ namespace IsoMounter
                 Name,
                 Name,
                 path,
                 path,
                 Path.GetExtension(path),
                 Path.GetExtension(path),
-                EnvironmentInfo.OperatingSystem,
+                OperatingSystem.Name,
                 ExecutablesAvailable
                 ExecutablesAvailable
             );
             );
 
 

+ 2 - 2
Emby.IsoMounting/IsoMounter/Properties/AssemblyInfo.cs

@@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyDescription("")]
 [assembly: AssemblyDescription("")]
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyCompany("Jellyfin Project")]
 [assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright ©  2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright ©  2019 Jellyfin Contributors. Code released under the GNU General Public License")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyCulture("")]
 [assembly: AssemblyCulture("")]
 [assembly: NeutralResourcesLanguage("en")]
 [assembly: NeutralResourcesLanguage("en")]

+ 2 - 2
Emby.Naming/Properties/AssemblyInfo.cs

@@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyDescription("")]
 [assembly: AssemblyDescription("")]
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyCompany("Jellyfin Project")]
 [assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright ©  2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright ©  2019 Jellyfin Contributors. Code released under the GNU General Public License")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyCulture("")]
 [assembly: AssemblyCulture("")]
 [assembly: NeutralResourcesLanguage("en")]
 [assembly: NeutralResourcesLanguage("en")]

+ 2 - 2
Emby.Notifications/Properties/AssemblyInfo.cs

@@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyDescription("")]
 [assembly: AssemblyDescription("")]
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyCompany("Jellyfin Project")]
 [assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright ©  2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright ©  2019 Jellyfin Contributors. Code released under the GNU General Public License")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyCulture("")]
 [assembly: AssemblyCulture("")]
 [assembly: NeutralResourcesLanguage("en")]
 [assembly: NeutralResourcesLanguage("en")]

+ 2 - 2
Emby.Photos/Properties/AssemblyInfo.cs

@@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyDescription("")]
 [assembly: AssemblyDescription("")]
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyConfiguration("")]
 [assembly: AssemblyCompany("Jellyfin Project")]
 [assembly: AssemblyCompany("Jellyfin Project")]
-[assembly: AssemblyProduct("Jellyfin: The Free Software Media System")]
-[assembly: AssemblyCopyright("Copyright ©  2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
+[assembly: AssemblyProduct("Jellyfin Server")]
+[assembly: AssemblyCopyright("Copyright ©  2019 Jellyfin Contributors. Code released under the GNU General Public License")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyCulture("")]
 [assembly: AssemblyCulture("")]
 [assembly: NeutralResourcesLanguage("en")]
 [assembly: NeutralResourcesLanguage("en")]

+ 74 - 107
Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs

@@ -30,13 +30,10 @@ namespace Emby.Server.Implementations.Activity
     public class ActivityLogEntryPoint : IServerEntryPoint
     public class ActivityLogEntryPoint : IServerEntryPoint
     {
     {
         private readonly IInstallationManager _installationManager;
         private readonly IInstallationManager _installationManager;
-
-        //private readonly ILogger _logger;
         private readonly ISessionManager _sessionManager;
         private readonly ISessionManager _sessionManager;
         private readonly ITaskManager _taskManager;
         private readonly ITaskManager _taskManager;
         private readonly IActivityManager _activityManager;
         private readonly IActivityManager _activityManager;
         private readonly ILocalizationManager _localization;
         private readonly ILocalizationManager _localization;
-
         private readonly ILibraryManager _libraryManager;
         private readonly ILibraryManager _libraryManager;
         private readonly ISubtitleManager _subManager;
         private readonly ISubtitleManager _subManager;
         private readonly IUserManager _userManager;
         private readonly IUserManager _userManager;
@@ -61,41 +58,37 @@ namespace Emby.Server.Implementations.Activity
 
 
         public Task RunAsync()
         public Task RunAsync()
         {
         {
-            _taskManager.TaskCompleted += _taskManager_TaskCompleted;
-
-            _installationManager.PluginInstalled += _installationManager_PluginInstalled;
-            _installationManager.PluginUninstalled += _installationManager_PluginUninstalled;
-            _installationManager.PluginUpdated += _installationManager_PluginUpdated;
-            _installationManager.PackageInstallationFailed += _installationManager_PackageInstallationFailed;
+            _taskManager.TaskCompleted += OnTaskCompleted;
 
 
-            _sessionManager.SessionStarted += _sessionManager_SessionStarted;
-            _sessionManager.AuthenticationFailed += _sessionManager_AuthenticationFailed;
-            _sessionManager.AuthenticationSucceeded += _sessionManager_AuthenticationSucceeded;
-            _sessionManager.SessionEnded += _sessionManager_SessionEnded;
+            _installationManager.PluginInstalled += OnPluginInstalled;
+            _installationManager.PluginUninstalled += OnPluginUninstalled;
+            _installationManager.PluginUpdated += OnPluginUpdated;
+            _installationManager.PackageInstallationFailed += OnPackageInstallationFailed;
 
 
-            _sessionManager.PlaybackStart += _sessionManager_PlaybackStart;
-            _sessionManager.PlaybackStopped += _sessionManager_PlaybackStopped;
+            _sessionManager.SessionStarted += OnSessionStarted;
+            _sessionManager.AuthenticationFailed += OnAuthenticationFailed;
+            _sessionManager.AuthenticationSucceeded += OnAuthenticationSucceeded;
+            _sessionManager.SessionEnded += OnSessionEnded;
 
 
-            //_subManager.SubtitlesDownloaded += _subManager_SubtitlesDownloaded;
-            _subManager.SubtitleDownloadFailure += _subManager_SubtitleDownloadFailure;
+            _sessionManager.PlaybackStart += OnPlaybackStart;
+            _sessionManager.PlaybackStopped += OnPlaybackStopped;
 
 
-            _userManager.UserCreated += _userManager_UserCreated;
-            _userManager.UserPasswordChanged += _userManager_UserPasswordChanged;
-            _userManager.UserDeleted += _userManager_UserDeleted;
-            _userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
-            _userManager.UserLockedOut += _userManager_UserLockedOut;
+            _subManager.SubtitleDownloadFailure += OnSubtitleDownloadFailure;
 
 
-            //_config.ConfigurationUpdated += _config_ConfigurationUpdated;
-            //_config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
+            _userManager.UserCreated += OnUserCreated;
+            _userManager.UserPasswordChanged += OnUserPasswordChanged;
+            _userManager.UserDeleted += OnUserDeleted;
+            _userManager.UserPolicyUpdated += OnUserPolicyUpdated;
+            _userManager.UserLockedOut += OnUserLockedOut;
 
 
-            _deviceManager.CameraImageUploaded += _deviceManager_CameraImageUploaded;
+            _deviceManager.CameraImageUploaded += OnCameraImageUploaded;
 
 
-            _appHost.ApplicationUpdated += _appHost_ApplicationUpdated;
+            _appHost.ApplicationUpdated += OnApplicationUpdated;
 
 
             return Task.CompletedTask;
             return Task.CompletedTask;
         }
         }
 
 
-        void _deviceManager_CameraImageUploaded(object sender, GenericEventArgs<CameraImageUploadInfo> e)
+        private void OnCameraImageUploaded(object sender, GenericEventArgs<CameraImageUploadInfo> e)
         {
         {
             CreateLogEntry(new ActivityLogEntry
             CreateLogEntry(new ActivityLogEntry
             {
             {
@@ -104,7 +97,7 @@ namespace Emby.Server.Implementations.Activity
             });
             });
         }
         }
 
 
-        void _userManager_UserLockedOut(object sender, GenericEventArgs<User> e)
+        private void OnUserLockedOut(object sender, GenericEventArgs<User> e)
         {
         {
             CreateLogEntry(new ActivityLogEntry
             CreateLogEntry(new ActivityLogEntry
             {
             {
@@ -114,7 +107,7 @@ namespace Emby.Server.Implementations.Activity
             });
             });
         }
         }
 
 
-        void _subManager_SubtitleDownloadFailure(object sender, SubtitleDownloadFailureEventArgs e)
+        private void OnSubtitleDownloadFailure(object sender, SubtitleDownloadFailureEventArgs e)
         {
         {
             CreateLogEntry(new ActivityLogEntry
             CreateLogEntry(new ActivityLogEntry
             {
             {
@@ -125,7 +118,7 @@ namespace Emby.Server.Implementations.Activity
             });
             });
         }
         }
 
 
-        void _sessionManager_PlaybackStopped(object sender, PlaybackStopEventArgs e)
+        private void OnPlaybackStopped(object sender, PlaybackStopEventArgs e)
         {
         {
             var item = e.MediaInfo;
             var item = e.MediaInfo;
 
 
@@ -146,7 +139,7 @@ namespace Emby.Server.Implementations.Activity
                 return;
                 return;
             }
             }
 
 
-            var user = e.Users.First();
+            var user = e.Users[0];
 
 
             CreateLogEntry(new ActivityLogEntry
             CreateLogEntry(new ActivityLogEntry
             {
             {
@@ -156,7 +149,7 @@ namespace Emby.Server.Implementations.Activity
             });
             });
         }
         }
 
 
-        void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
+        private void OnPlaybackStart(object sender, PlaybackProgressEventArgs e)
         {
         {
             var item = e.MediaInfo;
             var item = e.MediaInfo;
 
 
@@ -232,7 +225,7 @@ namespace Emby.Server.Implementations.Activity
             return null;
             return null;
         }
         }
 
 
-        void _sessionManager_SessionEnded(object sender, SessionEventArgs e)
+        private void OnSessionEnded(object sender, SessionEventArgs e)
         {
         {
             string name;
             string name;
             var session = e.SessionInfo;
             var session = e.SessionInfo;
@@ -258,7 +251,7 @@ namespace Emby.Server.Implementations.Activity
             });
             });
         }
         }
 
 
-        void _sessionManager_AuthenticationSucceeded(object sender, GenericEventArgs<AuthenticationResult> e)
+        private void OnAuthenticationSucceeded(object sender, GenericEventArgs<AuthenticationResult> e)
         {
         {
             var user = e.Argument.User;
             var user = e.Argument.User;
 
 
@@ -271,7 +264,7 @@ namespace Emby.Server.Implementations.Activity
             });
             });
         }
         }
 
 
-        void _sessionManager_AuthenticationFailed(object sender, GenericEventArgs<AuthenticationRequest> e)
+        private void OnAuthenticationFailed(object sender, GenericEventArgs<AuthenticationRequest> e)
         {
         {
             CreateLogEntry(new ActivityLogEntry
             CreateLogEntry(new ActivityLogEntry
             {
             {
@@ -282,7 +275,7 @@ namespace Emby.Server.Implementations.Activity
             });
             });
         }
         }
 
 
-        void _appHost_ApplicationUpdated(object sender, GenericEventArgs<PackageVersionInfo> e)
+        private void OnApplicationUpdated(object sender, GenericEventArgs<PackageVersionInfo> e)
         {
         {
             CreateLogEntry(new ActivityLogEntry
             CreateLogEntry(new ActivityLogEntry
             {
             {
@@ -292,25 +285,7 @@ namespace Emby.Server.Implementations.Activity
             });
             });
         }
         }
 
 
-        void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
-        {
-            CreateLogEntry(new ActivityLogEntry
-            {
-                Name = string.Format(_localization.GetLocalizedString("MessageNamedServerConfigurationUpdatedWithValue"), e.Key),
-                Type = "NamedConfigurationUpdated"
-            });
-        }
-
-        void _config_ConfigurationUpdated(object sender, EventArgs e)
-        {
-            CreateLogEntry(new ActivityLogEntry
-            {
-                Name = _localization.GetLocalizedString("MessageServerConfigurationUpdated"),
-                Type = "ServerConfigurationUpdated"
-            });
-        }
-
-        void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
+        private void OnUserPolicyUpdated(object sender, GenericEventArgs<User> e)
         {
         {
             CreateLogEntry(new ActivityLogEntry
             CreateLogEntry(new ActivityLogEntry
             {
             {
@@ -320,7 +295,7 @@ namespace Emby.Server.Implementations.Activity
             });
             });
         }
         }
 
 
-        void _userManager_UserDeleted(object sender, GenericEventArgs<User> e)
+        private void OnUserDeleted(object sender, GenericEventArgs<User> e)
         {
         {
             CreateLogEntry(new ActivityLogEntry
             CreateLogEntry(new ActivityLogEntry
             {
             {
@@ -329,7 +304,7 @@ namespace Emby.Server.Implementations.Activity
             });
             });
         }
         }
 
 
-        void _userManager_UserPasswordChanged(object sender, GenericEventArgs<User> e)
+        private void OnUserPasswordChanged(object sender, GenericEventArgs<User> e)
         {
         {
             CreateLogEntry(new ActivityLogEntry
             CreateLogEntry(new ActivityLogEntry
             {
             {
@@ -339,7 +314,7 @@ namespace Emby.Server.Implementations.Activity
             });
             });
         }
         }
 
 
-        void _userManager_UserCreated(object sender, GenericEventArgs<User> e)
+        private void OnUserCreated(object sender, GenericEventArgs<User> e)
         {
         {
             CreateLogEntry(new ActivityLogEntry
             CreateLogEntry(new ActivityLogEntry
             {
             {
@@ -349,18 +324,7 @@ namespace Emby.Server.Implementations.Activity
             });
             });
         }
         }
 
 
-        void _subManager_SubtitlesDownloaded(object sender, SubtitleDownloadEventArgs e)
-        {
-            CreateLogEntry(new ActivityLogEntry
-            {
-                Name = string.Format(_localization.GetLocalizedString("SubtitlesDownloadedForItem"), Notifications.Notifications.GetItemName(e.Item)),
-                Type = "SubtitlesDownloaded",
-                ItemId = e.Item.Id.ToString("N"),
-                ShortOverview = string.Format(_localization.GetLocalizedString("ProviderValue"), e.Provider)
-            });
-        }
-
-        void _sessionManager_SessionStarted(object sender, SessionEventArgs e)
+        private void OnSessionStarted(object sender, SessionEventArgs e)
         {
         {
             string name;
             string name;
             var session = e.SessionInfo;
             var session = e.SessionInfo;
@@ -386,7 +350,7 @@ namespace Emby.Server.Implementations.Activity
             });
             });
         }
         }
 
 
-        void _installationManager_PluginUpdated(object sender, GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> e)
+        private void OnPluginUpdated(object sender, GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> e)
         {
         {
             CreateLogEntry(new ActivityLogEntry
             CreateLogEntry(new ActivityLogEntry
             {
             {
@@ -397,7 +361,7 @@ namespace Emby.Server.Implementations.Activity
             });
             });
         }
         }
 
 
-        void _installationManager_PluginUninstalled(object sender, GenericEventArgs<IPlugin> e)
+        private void OnPluginUninstalled(object sender, GenericEventArgs<IPlugin> e)
         {
         {
             CreateLogEntry(new ActivityLogEntry
             CreateLogEntry(new ActivityLogEntry
             {
             {
@@ -406,7 +370,7 @@ namespace Emby.Server.Implementations.Activity
             });
             });
         }
         }
 
 
-        void _installationManager_PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> e)
+        private void OnPluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> e)
         {
         {
             CreateLogEntry(new ActivityLogEntry
             CreateLogEntry(new ActivityLogEntry
             {
             {
@@ -416,7 +380,7 @@ namespace Emby.Server.Implementations.Activity
             });
             });
         }
         }
 
 
-        void _installationManager_PackageInstallationFailed(object sender, InstallationFailedEventArgs e)
+        private void OnPackageInstallationFailed(object sender, InstallationFailedEventArgs e)
         {
         {
             var installationInfo = e.InstallationInfo;
             var installationInfo = e.InstallationInfo;
 
 
@@ -429,7 +393,7 @@ namespace Emby.Server.Implementations.Activity
             });
             });
         }
         }
 
 
-        void _taskManager_TaskCompleted(object sender, TaskCompletionEventArgs e)
+        private void OnTaskCompleted(object sender, TaskCompletionEventArgs e)
         {
         {
             var result = e.Result;
             var result = e.Result;
             var task = e.Task;
             var task = e.Task;
@@ -468,48 +432,36 @@ namespace Emby.Server.Implementations.Activity
         }
         }
 
 
         private void CreateLogEntry(ActivityLogEntry entry)
         private void CreateLogEntry(ActivityLogEntry entry)
-        {
-            try
-            {
-                _activityManager.Create(entry);
-            }
-            catch
-            {
-                // Logged at lower levels
-            }
-        }
+            => _activityManager.Create(entry);
 
 
         public void Dispose()
         public void Dispose()
         {
         {
-            _taskManager.TaskCompleted -= _taskManager_TaskCompleted;
+            _taskManager.TaskCompleted -= OnTaskCompleted;
 
 
-            _installationManager.PluginInstalled -= _installationManager_PluginInstalled;
-            _installationManager.PluginUninstalled -= _installationManager_PluginUninstalled;
-            _installationManager.PluginUpdated -= _installationManager_PluginUpdated;
-            _installationManager.PackageInstallationFailed -= _installationManager_PackageInstallationFailed;
+            _installationManager.PluginInstalled -= OnPluginInstalled;
+            _installationManager.PluginUninstalled -= OnPluginUninstalled;
+            _installationManager.PluginUpdated -= OnPluginUpdated;
+            _installationManager.PackageInstallationFailed -= OnPackageInstallationFailed;
 
 
-            _sessionManager.SessionStarted -= _sessionManager_SessionStarted;
-            _sessionManager.AuthenticationFailed -= _sessionManager_AuthenticationFailed;
-            _sessionManager.AuthenticationSucceeded -= _sessionManager_AuthenticationSucceeded;
-            _sessionManager.SessionEnded -= _sessionManager_SessionEnded;
+            _sessionManager.SessionStarted -= OnSessionStarted;
+            _sessionManager.AuthenticationFailed -= OnAuthenticationFailed;
+            _sessionManager.AuthenticationSucceeded -= OnAuthenticationSucceeded;
+            _sessionManager.SessionEnded -= OnSessionEnded;
 
 
-            _sessionManager.PlaybackStart -= _sessionManager_PlaybackStart;
-            _sessionManager.PlaybackStopped -= _sessionManager_PlaybackStopped;
+            _sessionManager.PlaybackStart -= OnPlaybackStart;
+            _sessionManager.PlaybackStopped -= OnPlaybackStopped;
 
 
-            _subManager.SubtitleDownloadFailure -= _subManager_SubtitleDownloadFailure;
+            _subManager.SubtitleDownloadFailure -= OnSubtitleDownloadFailure;
 
 
-            _userManager.UserCreated -= _userManager_UserCreated;
-            _userManager.UserPasswordChanged -= _userManager_UserPasswordChanged;
-            _userManager.UserDeleted -= _userManager_UserDeleted;
-            _userManager.UserPolicyUpdated -= _userManager_UserPolicyUpdated;
-            _userManager.UserLockedOut -= _userManager_UserLockedOut;
+            _userManager.UserCreated -= OnUserCreated;
+            _userManager.UserPasswordChanged -= OnUserPasswordChanged;
+            _userManager.UserDeleted -= OnUserDeleted;
+            _userManager.UserPolicyUpdated -= OnUserPolicyUpdated;
+            _userManager.UserLockedOut -= OnUserLockedOut;
 
 
-            _config.ConfigurationUpdated -= _config_ConfigurationUpdated;
-            _config.NamedConfigurationUpdated -= _config_NamedConfigurationUpdated;
+            _deviceManager.CameraImageUploaded -= OnCameraImageUploaded;
 
 
-            _deviceManager.CameraImageUploaded -= _deviceManager_CameraImageUploaded;
-
-            _appHost.ApplicationUpdated -= _appHost_ApplicationUpdated;
+            _appHost.ApplicationUpdated -= OnApplicationUpdated;
         }
         }
 
 
         /// <summary>
         /// <summary>
@@ -531,6 +483,7 @@ namespace Emby.Server.Implementations.Activity
                 values.Add(CreateValueString(years, "year"));
                 values.Add(CreateValueString(years, "year"));
                 days = days % DaysInYear;
                 days = days % DaysInYear;
             }
             }
+
             // Number of months
             // Number of months
             if (days >= DaysInMonth)
             if (days >= DaysInMonth)
             {
             {
@@ -538,25 +491,39 @@ namespace Emby.Server.Implementations.Activity
                 values.Add(CreateValueString(months, "month"));
                 values.Add(CreateValueString(months, "month"));
                 days = days % DaysInMonth;
                 days = days % DaysInMonth;
             }
             }
+
             // Number of days
             // Number of days
             if (days >= 1)
             if (days >= 1)
+            {
                 values.Add(CreateValueString(days, "day"));
                 values.Add(CreateValueString(days, "day"));
+            }
+
             // Number of hours
             // Number of hours
             if (span.Hours >= 1)
             if (span.Hours >= 1)
+            {
                 values.Add(CreateValueString(span.Hours, "hour"));
                 values.Add(CreateValueString(span.Hours, "hour"));
+            }
             // Number of minutes
             // Number of minutes
             if (span.Minutes >= 1)
             if (span.Minutes >= 1)
+            {
                 values.Add(CreateValueString(span.Minutes, "minute"));
                 values.Add(CreateValueString(span.Minutes, "minute"));
+            }
+
             // Number of seconds (include when 0 if no other components included)
             // Number of seconds (include when 0 if no other components included)
             if (span.Seconds >= 1 || values.Count == 0)
             if (span.Seconds >= 1 || values.Count == 0)
+            {
                 values.Add(CreateValueString(span.Seconds, "second"));
                 values.Add(CreateValueString(span.Seconds, "second"));
+            }
 
 
             // Combine values into string
             // Combine values into string
             var builder = new StringBuilder();
             var builder = new StringBuilder();
             for (int i = 0; i < values.Count; i++)
             for (int i = 0; i < values.Count; i++)
             {
             {
                 if (builder.Length > 0)
                 if (builder.Length > 0)
+                {
                     builder.Append(i == values.Count - 1 ? " and " : ", ");
                     builder.Append(i == values.Count - 1 ? " and " : ", ");
+                }
+
                 builder.Append(values[i]);
                 builder.Append(values[i]);
             }
             }
             // Return result
             // Return result

+ 9 - 1
Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs

@@ -17,12 +17,14 @@ namespace Emby.Server.Implementations.AppBase
             string programDataPath,
             string programDataPath,
             string logDirectoryPath,
             string logDirectoryPath,
             string configurationDirectoryPath,
             string configurationDirectoryPath,
-            string cacheDirectoryPath)
+            string cacheDirectoryPath,
+            string webDirectoryPath)
         {
         {
             ProgramDataPath = programDataPath;
             ProgramDataPath = programDataPath;
             LogDirectoryPath = logDirectoryPath;
             LogDirectoryPath = logDirectoryPath;
             ConfigurationDirectoryPath = configurationDirectoryPath;
             ConfigurationDirectoryPath = configurationDirectoryPath;
             CachePath = cacheDirectoryPath;
             CachePath = cacheDirectoryPath;
+            WebPath = webDirectoryPath;
 
 
             DataPath = Path.Combine(ProgramDataPath, "data");
             DataPath = Path.Combine(ProgramDataPath, "data");
         }
         }
@@ -33,6 +35,12 @@ namespace Emby.Server.Implementations.AppBase
         /// <value>The program data path.</value>
         /// <value>The program data path.</value>
         public string ProgramDataPath { get; private set; }
         public string ProgramDataPath { get; private set; }
 
 
+        /// <summary>
+        /// Gets the path to the web UI resources folder
+        /// </summary>
+        /// <value>The web UI resources path.</value>
+        public string WebPath { get; set; }
+
         /// <summary>
         /// <summary>
         /// Gets the path to the system folder
         /// Gets the path to the system folder
         /// </summary>
         /// </summary>

파일 크기가 너무 크기때문에 변경 상태를 표시하지 않습니다.
+ 208 - 265
Emby.Server.Implementations/ApplicationHost.cs


+ 2 - 2
Emby.Server.Implementations/Collections/CollectionImageProvider.cs

@@ -36,7 +36,7 @@ namespace Emby.Server.Implementations.Collections
             return base.Supports(item);
             return base.Supports(item);
         }
         }
 
 
-        protected override List<BaseItem> GetItemsWithImages(BaseItem item)
+        protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
         {
         {
             var playlist = (BoxSet)item;
             var playlist = (BoxSet)item;
 
 
@@ -80,7 +80,7 @@ namespace Emby.Server.Implementations.Collections
                 .ToList();
                 .ToList();
         }
         }
 
 
-        protected override string CreateImage(BaseItem item, List<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
+        protected override string CreateImage(BaseItem item, IReadOnlyCollection<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
         {
         {
             return CreateSingleImage(itemsWithImages, outputPathWithoutExtension, ImageType.Primary);
             return CreateSingleImage(itemsWithImages, outputPathWithoutExtension, ImageType.Primary);
         }
         }

+ 2 - 1
Emby.Server.Implementations/ConfigurationOptions.cs

@@ -6,7 +6,8 @@ namespace Emby.Server.Implementations
     {
     {
         public static readonly Dictionary<string, string> Configuration = new Dictionary<string, string>
         public static readonly Dictionary<string, string> Configuration = new Dictionary<string, string>
         {
         {
-            {"HttpListenerHost:DefaultRedirectPath", "web/index.html"}
+            {"HttpListenerHost:DefaultRedirectPath", "web/index.html"},
+            {"MusicBrainz:BaseUrl", "https://www.musicbrainz.org"}
         };
         };
     }
     }
 }
 }

+ 129 - 0
Emby.Server.Implementations/Cryptography/CryptographyProvider.cs

@@ -1,13 +1,49 @@
 using System;
 using System;
+using System.Collections.Generic;
+using System.Globalization;
 using System.IO;
 using System.IO;
 using System.Security.Cryptography;
 using System.Security.Cryptography;
 using System.Text;
 using System.Text;
+using System.Linq;
 using MediaBrowser.Model.Cryptography;
 using MediaBrowser.Model.Cryptography;
 
 
 namespace Emby.Server.Implementations.Cryptography
 namespace Emby.Server.Implementations.Cryptography
 {
 {
     public class CryptographyProvider : ICryptoProvider
     public class CryptographyProvider : ICryptoProvider
     {
     {
+        private static readonly HashSet<string> _supportedHashMethods = new HashSet<string>()
+            {
+                "MD5",
+                "System.Security.Cryptography.MD5",
+                "SHA",
+                "SHA1",
+                "System.Security.Cryptography.SHA1",
+                "SHA256",
+                "SHA-256",
+                "System.Security.Cryptography.SHA256",
+                "SHA384",
+                "SHA-384",
+                "System.Security.Cryptography.SHA384",
+                "SHA512",
+                "SHA-512",
+                "System.Security.Cryptography.SHA512"
+            };
+
+        public string DefaultHashMethod => "PBKDF2";
+
+        private RandomNumberGenerator _randomNumberGenerator;
+
+        private const int _defaultIterations = 1000;
+
+        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
+            _randomNumberGenerator = RandomNumberGenerator.Create();
+        }
+
         public Guid GetMD5(string str)
         public Guid GetMD5(string str)
         {
         {
             return new Guid(ComputeMD5(Encoding.Unicode.GetBytes(str)));
             return new Guid(ComputeMD5(Encoding.Unicode.GetBytes(str)));
@@ -36,5 +72,98 @@ namespace Emby.Server.Implementations.Cryptography
                 return provider.ComputeHash(bytes);
                 return provider.ComputeHash(bytes);
             }
             }
         }
         }
+
+        public IEnumerable<string> GetSupportedHashMethods()
+        {
+            return _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
+            if (method == DefaultHashMethod)
+            {
+                using (var r = new Rfc2898DeriveBytes(bytes, salt, iterations))
+                {
+                    return r.GetBytes(32);
+                }
+            }
+
+            throw new CryptographicException($"Cannot currently use PBKDF2 with requested hash method: {method}");
+        }
+
+        public byte[] ComputeHash(string hashMethod, byte[] bytes)
+        {
+            return ComputeHash(hashMethod, bytes, Array.Empty<byte>());
+        }
+
+        public byte[] ComputeHashWithDefaultMethod(byte[] bytes)
+        {
+            return ComputeHash(DefaultHashMethod, bytes);
+        }
+
+        public byte[] ComputeHash(string hashMethod, byte[] bytes, byte[] salt)
+        {
+            if (hashMethod == DefaultHashMethod)
+            {
+                return PBKDF2(hashMethod, bytes, salt, _defaultIterations);
+            }
+            else if (_supportedHashMethods.Contains(hashMethod))
+            {
+                using (var h = HashAlgorithm.Create(hashMethod))
+                {
+                    if (salt.Length == 0)
+                    {
+                        return h.ComputeHash(bytes);
+                    }
+                    else
+                    {
+                        byte[] salted = new byte[bytes.Length + salt.Length];
+                        Array.Copy(bytes, salted, bytes.Length);
+                        Array.Copy(salt, 0, salted, bytes.Length, salt.Length);
+                        return h.ComputeHash(salted);
+                    }
+                }
+            }
+            else
+            {
+                throw new CryptographicException($"Requested hash method is not supported: {hashMethod}");
+            }
+        }
+
+        public byte[] ComputeHashWithDefaultMethod(byte[] bytes, byte[] salt)
+        {
+            return PBKDF2(DefaultHashMethod, bytes, salt, _defaultIterations);
+        }
+        
+        public byte[] ComputeHash(PasswordHash hash)
+        {
+            int iterations = _defaultIterations;
+            if (!hash.Parameters.ContainsKey("iterations"))
+            {
+                hash.Parameters.Add("iterations", _defaultIterations.ToString(CultureInfo.InvariantCulture));
+            }
+            else
+            {
+                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);
+                }
+            }
+
+            return PBKDF2(hash.Id, hash.HashBytes, hash.SaltBytes, iterations);
+        }
+
+        public byte[] GenerateSalt()
+        {
+            byte[] salt = new byte[64];
+            _randomNumberGenerator.GetBytes(salt);
+            return salt;
+        }
     }
     }
 }
 }

+ 1 - 3
Emby.Server.Implementations/Data/SqliteItemRepository.cs

@@ -25,7 +25,6 @@ using MediaBrowser.Model.Entities;
 using MediaBrowser.Model.Globalization;
 using MediaBrowser.Model.Globalization;
 using MediaBrowser.Model.LiveTv;
 using MediaBrowser.Model.LiveTv;
 using MediaBrowser.Model.Querying;
 using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Reflection;
 using MediaBrowser.Model.Serialization;
 using MediaBrowser.Model.Serialization;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
 using SQLitePCL.pretty;
 using SQLitePCL.pretty;
@@ -69,7 +68,6 @@ namespace Emby.Server.Implementations.Data
             IServerApplicationHost appHost,
             IServerApplicationHost appHost,
             IJsonSerializer jsonSerializer,
             IJsonSerializer jsonSerializer,
             ILoggerFactory loggerFactory,
             ILoggerFactory loggerFactory,
-            IAssemblyInfo assemblyInfo,
             ILocalizationManager localization)
             ILocalizationManager localization)
             : base(loggerFactory.CreateLogger(nameof(SqliteItemRepository)))
             : base(loggerFactory.CreateLogger(nameof(SqliteItemRepository)))
         {
         {
@@ -86,7 +84,7 @@ namespace Emby.Server.Implementations.Data
             _appHost = appHost;
             _appHost = appHost;
             _config = config;
             _config = config;
             _jsonSerializer = jsonSerializer;
             _jsonSerializer = jsonSerializer;
-            _typeMapper = new TypeMapper(assemblyInfo);
+            _typeMapper = new TypeMapper();
             _localization = localization;
             _localization = localization;
 
 
             DbFilePath = Path.Combine(_config.ApplicationPaths.DataPath, "library.db");
             DbFilePath = Path.Combine(_config.ApplicationPaths.DataPath, "library.db");

+ 34 - 0
Emby.Server.Implementations/Data/SqliteUserRepository.cs

@@ -55,6 +55,8 @@ namespace Emby.Server.Implementations.Data
                 {
                 {
                     TryMigrateToLocalUsersTable(connection);
                     TryMigrateToLocalUsersTable(connection);
                 }
                 }
+
+                RemoveEmptyPasswordHashes();
             }
             }
         }
         }
 
 
@@ -73,6 +75,38 @@ namespace Emby.Server.Implementations.Data
             }
             }
         }
         }
 
 
+        private void RemoveEmptyPasswordHashes()
+        {
+            foreach (var user in RetrieveAllUsers())
+            {
+                // If the user password is the sha1 hash of the empty string, remove it
+                if (!string.Equals(user.Password, "DA39A3EE5E6B4B0D3255BFEF95601890AFD80709", StringComparison.Ordinal)
+                    || !string.Equals(user.Password, "$SHA1$DA39A3EE5E6B4B0D3255BFEF95601890AFD80709", StringComparison.Ordinal))
+                {
+                    continue;
+                }
+
+                user.Password = null;
+                var serialized = _jsonSerializer.SerializeToBytes(user);
+
+                using (WriteLock.Write())
+                using (var connection = CreateConnection())
+                {
+                    connection.RunInTransaction(db =>
+                    {
+                        using (var statement = db.PrepareStatement("update LocalUsersv2 set data=@data where Id=@InternalId"))
+                        {
+                            statement.TryBind("@InternalId", user.InternalId);
+                            statement.TryBind("@data", serialized);
+                            statement.MoveNext();
+                        }
+
+                    }, TransactionMode);
+                }
+            }
+
+        }
+
         /// <summary>
         /// <summary>
         /// Save a user in the repo
         /// Save a user in the repo
         /// </summary>
         /// </summary>

+ 2 - 7
Emby.Server.Implementations/Data/TypeMapper.cs

@@ -1,7 +1,6 @@
 using System;
 using System;
 using System.Collections.Concurrent;
 using System.Collections.Concurrent;
 using System.Linq;
 using System.Linq;
-using MediaBrowser.Model.Reflection;
 
 
 namespace Emby.Server.Implementations.Data
 namespace Emby.Server.Implementations.Data
 {
 {
@@ -10,16 +9,13 @@ namespace Emby.Server.Implementations.Data
     /// </summary>
     /// </summary>
     public class TypeMapper
     public class TypeMapper
     {
     {
-        private readonly IAssemblyInfo _assemblyInfo;
-
         /// <summary>
         /// <summary>
         /// This holds all the types in the running assemblies so that we can de-serialize properly when we don't have strong types
         /// This holds all the types in the running assemblies so that we can de-serialize properly when we don't have strong types
         /// </summary>
         /// </summary>
         private readonly ConcurrentDictionary<string, Type> _typeMap = new ConcurrentDictionary<string, Type>();
         private readonly ConcurrentDictionary<string, Type> _typeMap = new ConcurrentDictionary<string, Type>();
 
 
-        public TypeMapper(IAssemblyInfo assemblyInfo)
+        public TypeMapper()
         {
         {
-            _assemblyInfo = assemblyInfo;
         }
         }
 
 
         /// <summary>
         /// <summary>
@@ -45,8 +41,7 @@ namespace Emby.Server.Implementations.Data
         /// <returns>Type.</returns>
         /// <returns>Type.</returns>
         private Type LookupType(string typeName)
         private Type LookupType(string typeName)
         {
         {
-            return _assemblyInfo
-                .GetCurrentAssemblies()
+            return AppDomain.CurrentDomain.GetAssemblies()
                 .Select(a => a.GetType(typeName))
                 .Select(a => a.GetType(typeName))
                 .FirstOrDefault(t => t != null);
                 .FirstOrDefault(t => t != null);
         }
         }

+ 43 - 29
Emby.Server.Implementations/Diagnostics/CommonProcess.cs

@@ -9,14 +9,14 @@ namespace Emby.Server.Implementations.Diagnostics
 {
 {
     public class CommonProcess : IProcess
     public class CommonProcess : IProcess
     {
     {
-        public event EventHandler Exited;
-
-        private readonly ProcessOptions _options;
         private readonly Process _process;
         private readonly Process _process;
 
 
+        private bool _disposed = false;
+        private bool _hasExited;
+
         public CommonProcess(ProcessOptions options)
         public CommonProcess(ProcessOptions options)
         {
         {
-            _options = options;
+            StartInfo = options;
 
 
             var startInfo = new ProcessStartInfo
             var startInfo = new ProcessStartInfo
             {
             {
@@ -27,10 +27,10 @@ namespace Emby.Server.Implementations.Diagnostics
                 CreateNoWindow = options.CreateNoWindow,
                 CreateNoWindow = options.CreateNoWindow,
                 RedirectStandardError = options.RedirectStandardError,
                 RedirectStandardError = options.RedirectStandardError,
                 RedirectStandardInput = options.RedirectStandardInput,
                 RedirectStandardInput = options.RedirectStandardInput,
-                RedirectStandardOutput = options.RedirectStandardOutput
+                RedirectStandardOutput = options.RedirectStandardOutput,
+                ErrorDialog = options.ErrorDialog
             };
             };
 
 
-            startInfo.ErrorDialog = options.ErrorDialog;
 
 
             if (options.IsHidden)
             if (options.IsHidden)
             {
             {
@@ -45,11 +45,22 @@ namespace Emby.Server.Implementations.Diagnostics
             if (options.EnableRaisingEvents)
             if (options.EnableRaisingEvents)
             {
             {
                 _process.EnableRaisingEvents = true;
                 _process.EnableRaisingEvents = true;
-                _process.Exited += _process_Exited;
+                _process.Exited += OnProcessExited;
             }
             }
         }
         }
 
 
-        private bool _hasExited;
+        public event EventHandler Exited;
+
+        public ProcessOptions StartInfo { get; }
+
+        public StreamWriter StandardInput => _process.StandardInput;
+
+        public StreamReader StandardError => _process.StandardError;
+
+        public StreamReader StandardOutput => _process.StandardOutput;
+
+        public int ExitCode => _process.ExitCode;
+
         private bool HasExited
         private bool HasExited
         {
         {
             get
             get
@@ -72,25 +83,6 @@ namespace Emby.Server.Implementations.Diagnostics
             }
             }
         }
         }
 
 
-        private void _process_Exited(object sender, EventArgs e)
-        {
-            _hasExited = true;
-            if (Exited != null)
-            {
-                Exited(this, e);
-            }
-        }
-
-        public ProcessOptions StartInfo => _options;
-
-        public StreamWriter StandardInput => _process.StandardInput;
-
-        public StreamReader StandardError => _process.StandardError;
-
-        public StreamReader StandardOutput => _process.StandardOutput;
-
-        public int ExitCode => _process.ExitCode;
-
         public void Start()
         public void Start()
         {
         {
             _process.Start();
             _process.Start();
@@ -108,7 +100,7 @@ namespace Emby.Server.Implementations.Diagnostics
 
 
         public Task<bool> WaitForExitAsync(int timeMs)
         public Task<bool> WaitForExitAsync(int timeMs)
         {
         {
-            //Note: For this function to work correctly, the option EnableRisingEvents needs to be set to true.
+            // Note: For this function to work correctly, the option EnableRisingEvents needs to be set to true.
 
 
             if (HasExited)
             if (HasExited)
             {
             {
@@ -130,7 +122,29 @@ namespace Emby.Server.Implementations.Diagnostics
 
 
         public void Dispose()
         public void Dispose()
         {
         {
-            _process.Dispose();
+            Dispose(true);
+            GC.SuppressFinalize(this);
+        }
+
+        protected virtual void Dispose(bool disposing)
+        {
+            if (_disposed)
+            {
+                return;
+            }
+
+            if (disposing)
+            {
+                _process?.Dispose();
+            }
+
+            _disposed = true;
+        }
+
+        private void OnProcessExited(object sender, EventArgs e)
+        {
+            _hasExited = true;
+            Exited?.Invoke(this, e);
         }
         }
     }
     }
 }
 }

+ 23 - 2
Emby.Server.Implementations/Emby.Server.Implementations.csproj

@@ -9,12 +9,10 @@
     <ProjectReference Include="..\MediaBrowser.Providers\MediaBrowser.Providers.csproj" />
     <ProjectReference Include="..\MediaBrowser.Providers\MediaBrowser.Providers.csproj" />
     <ProjectReference Include="..\MediaBrowser.WebDashboard\MediaBrowser.WebDashboard.csproj" />
     <ProjectReference Include="..\MediaBrowser.WebDashboard\MediaBrowser.WebDashboard.csproj" />
     <ProjectReference Include="..\MediaBrowser.XbmcMetadata\MediaBrowser.XbmcMetadata.csproj" />
     <ProjectReference Include="..\MediaBrowser.XbmcMetadata\MediaBrowser.XbmcMetadata.csproj" />
-    <ProjectReference Include="..\SocketHttpListener\SocketHttpListener.csproj" />
     <ProjectReference Include="..\Emby.Dlna\Emby.Dlna.csproj" />
     <ProjectReference Include="..\Emby.Dlna\Emby.Dlna.csproj" />
     <ProjectReference Include="..\Mono.Nat\Mono.Nat.csproj" />
     <ProjectReference Include="..\Mono.Nat\Mono.Nat.csproj" />
     <ProjectReference Include="..\MediaBrowser.Api\MediaBrowser.Api.csproj" />
     <ProjectReference Include="..\MediaBrowser.Api\MediaBrowser.Api.csproj" />
     <ProjectReference Include="..\MediaBrowser.LocalMetadata\MediaBrowser.LocalMetadata.csproj" />
     <ProjectReference Include="..\MediaBrowser.LocalMetadata\MediaBrowser.LocalMetadata.csproj" />
-    <ProjectReference Include="..\OpenSubtitlesHandler\OpenSubtitlesHandler.csproj" />
     <ProjectReference Include="..\Emby.Photos\Emby.Photos.csproj" />
     <ProjectReference Include="..\Emby.Photos\Emby.Photos.csproj" />
     <ProjectReference Include="..\Emby.Drawing\Emby.Drawing.csproj" />
     <ProjectReference Include="..\Emby.Drawing\Emby.Drawing.csproj" />
     <ProjectReference Include="..\Emby.XmlTv\Emby.XmlTv\Emby.XmlTv.csproj" />
     <ProjectReference Include="..\Emby.XmlTv\Emby.XmlTv\Emby.XmlTv.csproj" />
@@ -22,6 +20,14 @@
   </ItemGroup>
   </ItemGroup>
 
 
   <ItemGroup>
   <ItemGroup>
+    <PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.0" />
+    <PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="2.2.0" />
+    <PackageReference Include="Microsoft.AspNetCore.Hosting.Server.Abstractions" Version="2.2.0" />
+    <PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
+    <PackageReference Include="Microsoft.AspNetCore.Http.Extensions" Version="2.2.0" />
+    <PackageReference Include="Microsoft.AspNetCore.ResponseCompression" Version="2.2.0" />
+    <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.2.0" />
+    <PackageReference Include="Microsoft.AspNetCore.WebSockets" Version="2.2.1" />
     <PackageReference Include="Microsoft.Extensions.Logging" Version="2.2.0" />
     <PackageReference Include="Microsoft.Extensions.Logging" Version="2.2.0" />
     <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.2.0" />
     <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.2.0" />
     <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="2.2.0" />
     <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="2.2.0" />
@@ -40,6 +46,21 @@
     <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
     <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
   </PropertyGroup>
   </PropertyGroup>
 
 
+  <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
+    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
+  </PropertyGroup>
+
+  <!-- Code analysers-->
+  <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
+    <PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.6.3" />
+    <PackageReference Include="StyleCop.Analyzers" Version="1.0.2" />
+    <PackageReference Include="SerilogAnalyzer" Version="0.15.0" />
+  </ItemGroup>
+
+  <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
+    <CodeAnalysisRuleSet>../jellyfin.ruleset</CodeAnalysisRuleSet>
+  </PropertyGroup>
+
   <ItemGroup>
   <ItemGroup>
     <EmbeddedResource Include="Localization\iso6392.txt" />
     <EmbeddedResource Include="Localization\iso6392.txt" />
     <EmbeddedResource Include="Localization\countries.json" />
     <EmbeddedResource Include="Localization\countries.json" />

+ 0 - 36
Emby.Server.Implementations/EnvironmentInfo/EnvironmentInfo.cs

@@ -1,36 +0,0 @@
-using System;
-using System.Runtime.InteropServices;
-using MediaBrowser.Model.System;
-
-namespace Emby.Server.Implementations.EnvironmentInfo
-{
-    public class EnvironmentInfo : IEnvironmentInfo
-    {
-        public EnvironmentInfo(MediaBrowser.Model.System.OperatingSystem operatingSystem)
-        {
-            OperatingSystem = operatingSystem;
-        }
-
-        public MediaBrowser.Model.System.OperatingSystem OperatingSystem { get; private set; }
-
-        public string OperatingSystemName
-        {
-            get
-            {
-                switch (OperatingSystem)
-                {
-                    case MediaBrowser.Model.System.OperatingSystem.Android: return "Android";
-                    case MediaBrowser.Model.System.OperatingSystem.BSD: return "BSD";
-                    case MediaBrowser.Model.System.OperatingSystem.Linux: return "Linux";
-                    case MediaBrowser.Model.System.OperatingSystem.OSX: return "macOS";
-                    case MediaBrowser.Model.System.OperatingSystem.Windows: return "Windows";
-                    default: throw new Exception($"Unknown OS {OperatingSystem}");
-                }
-            }
-        }
-
-        public string OperatingSystemVersion => Environment.OSVersion.Version.ToString() + " " + Environment.OSVersion.ServicePack.ToString();
-
-        public Architecture SystemArchitecture => RuntimeInformation.OSArchitecture;
-    }
-}

+ 0 - 24
Emby.Server.Implementations/FFMpeg/FFMpegInfo.cs

@@ -1,24 +0,0 @@
-namespace Emby.Server.Implementations.FFMpeg
-{
-    /// <summary>
-    /// Class FFMpegInfo
-    /// </summary>
-    public class FFMpegInfo
-    {
-        /// <summary>
-        /// Gets or sets the path.
-        /// </summary>
-        /// <value>The path.</value>
-        public string EncoderPath { get; set; }
-        /// <summary>
-        /// Gets or sets the probe path.
-        /// </summary>
-        /// <value>The probe path.</value>
-        public string ProbePath { get; set; }
-        /// <summary>
-        /// Gets or sets the version.
-        /// </summary>
-        /// <value>The version.</value>
-        public string Version { get; set; }
-    }
-}

+ 0 - 17
Emby.Server.Implementations/FFMpeg/FFMpegInstallInfo.cs

@@ -1,17 +0,0 @@
-namespace Emby.Server.Implementations.FFMpeg
-{
-    public class FFMpegInstallInfo
-    {
-        public string Version { get; set; }
-        public string FFMpegFilename { get; set; }
-        public string FFProbeFilename { get; set; }
-        public string ArchiveType { get; set; }
-
-        public FFMpegInstallInfo()
-        {
-            Version = "Path";
-            FFMpegFilename = "ffmpeg";
-            FFProbeFilename = "ffprobe";
-        }
-    }
-}

+ 0 - 132
Emby.Server.Implementations/FFMpeg/FFMpegLoader.cs

@@ -1,132 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Model.IO;
-
-namespace Emby.Server.Implementations.FFMpeg
-{
-    public class FFMpegLoader
-    {
-        private readonly IApplicationPaths _appPaths;
-        private readonly IFileSystem _fileSystem;
-        private readonly FFMpegInstallInfo _ffmpegInstallInfo;
-
-        public FFMpegLoader(IApplicationPaths appPaths, IFileSystem fileSystem, FFMpegInstallInfo ffmpegInstallInfo)
-        {
-            _appPaths = appPaths;
-            _fileSystem = fileSystem;
-            _ffmpegInstallInfo = ffmpegInstallInfo;
-        }
-
-        public FFMpegInfo GetFFMpegInfo(IStartupOptions options)
-        {
-            var customffMpegPath = options.FFmpegPath;
-            var customffProbePath = options.FFprobePath;
-
-            if (!string.IsNullOrWhiteSpace(customffMpegPath) && !string.IsNullOrWhiteSpace(customffProbePath))
-            {
-                return new FFMpegInfo
-                {
-                    ProbePath = customffProbePath,
-                    EncoderPath = customffMpegPath,
-                    Version = "external"
-                };
-            }
-
-            var downloadInfo = _ffmpegInstallInfo;
-
-            var prebuiltFolder = _appPaths.ProgramSystemPath;
-            var prebuiltffmpeg = Path.Combine(prebuiltFolder, downloadInfo.FFMpegFilename);
-            var prebuiltffprobe = Path.Combine(prebuiltFolder, downloadInfo.FFProbeFilename);
-            if (File.Exists(prebuiltffmpeg) && File.Exists(prebuiltffprobe))
-            {
-                return new FFMpegInfo
-                {
-                    ProbePath = prebuiltffprobe,
-                    EncoderPath = prebuiltffmpeg,
-                    Version = "external"
-                };
-            }
-
-            var version = downloadInfo.Version;
-
-            if (string.Equals(version, "0", StringComparison.OrdinalIgnoreCase))
-            {
-                return new FFMpegInfo();
-            }
-
-            var rootEncoderPath = Path.Combine(_appPaths.ProgramDataPath, "ffmpeg");
-            var versionedDirectoryPath = Path.Combine(rootEncoderPath, version);
-
-            var info = new FFMpegInfo
-            {
-                ProbePath = Path.Combine(versionedDirectoryPath, downloadInfo.FFProbeFilename),
-                EncoderPath = Path.Combine(versionedDirectoryPath, downloadInfo.FFMpegFilename),
-                Version = version
-            };
-
-            Directory.CreateDirectory(versionedDirectoryPath);
-
-            var excludeFromDeletions = new List<string> { versionedDirectoryPath };
-
-            if (!File.Exists(info.ProbePath) || !File.Exists(info.EncoderPath))
-            {
-                // ffmpeg not present. See if there's an older version we can start with
-                var existingVersion = GetExistingVersion(info, rootEncoderPath);
-
-                // No older version. Need to download and block until complete
-                if (existingVersion == null)
-                {
-                    return new FFMpegInfo();
-                }
-                else
-                {
-                    info = existingVersion;
-                    versionedDirectoryPath = Path.GetDirectoryName(info.EncoderPath);
-                    excludeFromDeletions.Add(versionedDirectoryPath);
-                }
-            }
-
-            // Allow just one of these to be overridden, if desired.
-            if (!string.IsNullOrWhiteSpace(customffMpegPath))
-            {
-                info.EncoderPath = customffMpegPath;
-            }
-            if (!string.IsNullOrWhiteSpace(customffProbePath))
-            {
-                info.ProbePath = customffProbePath;
-            }
-
-            return info;
-        }
-
-        private FFMpegInfo GetExistingVersion(FFMpegInfo info, string rootEncoderPath)
-        {
-            var encoderFilename = Path.GetFileName(info.EncoderPath);
-            var probeFilename = Path.GetFileName(info.ProbePath);
-
-            foreach (var directory in _fileSystem.GetDirectoryPaths(rootEncoderPath))
-            {
-                var allFiles = _fileSystem.GetFilePaths(directory, true).ToList();
-
-                var encoder = allFiles.FirstOrDefault(i => string.Equals(Path.GetFileName(i), encoderFilename, StringComparison.OrdinalIgnoreCase));
-                var probe = allFiles.FirstOrDefault(i => string.Equals(Path.GetFileName(i), probeFilename, StringComparison.OrdinalIgnoreCase));
-
-                if (!string.IsNullOrWhiteSpace(encoder) &&
-                    !string.IsNullOrWhiteSpace(probe))
-                {
-                    return new FFMpegInfo
-                    {
-                        EncoderPath = encoder,
-                        ProbePath = probe,
-                        Version = Path.GetFileName(Path.GetDirectoryName(probe))
-                    };
-                }
-            }
-
-            return null;
-        }
-    }
-}

+ 3 - 3
Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs

@@ -15,6 +15,7 @@ using MediaBrowser.Common.Net;
 using MediaBrowser.Model.IO;
 using MediaBrowser.Model.IO;
 using MediaBrowser.Model.Net;
 using MediaBrowser.Model.Net;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
+using Microsoft.Net.Http.Headers;
 
 
 namespace Emby.Server.Implementations.HttpClientManager
 namespace Emby.Server.Implementations.HttpClientManager
 {
 {
@@ -179,11 +180,11 @@ namespace Emby.Server.Implementations.HttpClientManager
 
 
             foreach (var header in options.RequestHeaders)
             foreach (var header in options.RequestHeaders)
             {
             {
-                if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase))
+                if (string.Equals(header.Key, HeaderNames.Accept, StringComparison.OrdinalIgnoreCase))
                 {
                 {
                     request.Accept = header.Value;
                     request.Accept = header.Value;
                 }
                 }
-                else if (string.Equals(header.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
+                else if (string.Equals(header.Key, HeaderNames.UserAgent, StringComparison.OrdinalIgnoreCase))
                 {
                 {
                     SetUserAgent(request, header.Value);
                     SetUserAgent(request, header.Value);
                     hasUserAgent = true;
                     hasUserAgent = true;
@@ -327,7 +328,6 @@ namespace Emby.Server.Implementations.HttpClientManager
                     }
                     }
 
 
                     httpWebRequest.ContentType = contentType;
                     httpWebRequest.ContentType = contentType;
-                    httpWebRequest.ContentLength = bytes.Length;
                     (await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false)).Write(bytes, 0, bytes.Length);
                     (await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false)).Write(bytes, 0, bytes.Length);
                 }
                 }
                 catch (Exception ex)
                 catch (Exception ex)

+ 21 - 25
Emby.Server.Implementations/HttpServer/FileWriter.cs

@@ -5,15 +5,19 @@ using System.Linq;
 using System.Net;
 using System.Net;
 using System.Threading;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
+using Emby.Server.Implementations.IO;
 using MediaBrowser.Model.IO;
 using MediaBrowser.Model.IO;
 using MediaBrowser.Model.Services;
 using MediaBrowser.Model.Services;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
+using Microsoft.Net.Http.Headers;
 
 
 namespace Emby.Server.Implementations.HttpServer
 namespace Emby.Server.Implementations.HttpServer
 {
 {
     public class FileWriter : IHttpResult
     public class FileWriter : IHttpResult
     {
     {
+        private readonly IStreamHelper _streamHelper;
         private ILogger Logger { get; set; }
         private ILogger Logger { get; set; }
+        private readonly IFileSystem _fileSystem;
 
 
         private string RangeHeader { get; set; }
         private string RangeHeader { get; set; }
         private bool IsHeadRequest { get; set; }
         private bool IsHeadRequest { get; set; }
@@ -42,25 +46,27 @@ namespace Emby.Server.Implementations.HttpServer
 
 
         public string Path { get; set; }
         public string Path { get; set; }
 
 
-        public FileWriter(string path, string contentType, string rangeHeader, ILogger logger, IFileSystem fileSystem)
+        public FileWriter(string path, string contentType, string rangeHeader, ILogger logger, IFileSystem fileSystem, IStreamHelper streamHelper)
         {
         {
             if (string.IsNullOrEmpty(contentType))
             if (string.IsNullOrEmpty(contentType))
             {
             {
                 throw new ArgumentNullException(nameof(contentType));
                 throw new ArgumentNullException(nameof(contentType));
             }
             }
 
 
+            _streamHelper = streamHelper;
+            _fileSystem = fileSystem;
+
             Path = path;
             Path = path;
             Logger = logger;
             Logger = logger;
             RangeHeader = rangeHeader;
             RangeHeader = rangeHeader;
 
 
-            Headers["Content-Type"] = contentType;
+            Headers[HeaderNames.ContentType] = contentType;
 
 
             TotalContentLength = fileSystem.GetFileInfo(path).Length;
             TotalContentLength = fileSystem.GetFileInfo(path).Length;
-            Headers["Accept-Ranges"] = "bytes";
+            Headers[HeaderNames.AcceptRanges] = "bytes";
 
 
             if (string.IsNullOrWhiteSpace(rangeHeader))
             if (string.IsNullOrWhiteSpace(rangeHeader))
             {
             {
-                Headers["Content-Length"] = TotalContentLength.ToString(UsCulture);
                 StatusCode = HttpStatusCode.OK;
                 StatusCode = HttpStatusCode.OK;
             }
             }
             else
             else
@@ -93,13 +99,10 @@ namespace Emby.Server.Implementations.HttpServer
             RangeStart = requestedRange.Key;
             RangeStart = requestedRange.Key;
             RangeLength = 1 + RangeEnd - RangeStart;
             RangeLength = 1 + RangeEnd - RangeStart;
 
 
-            // Content-Length is the length of what we're serving, not the original content
-            var lengthString = RangeLength.ToString(UsCulture);
-            Headers["Content-Length"] = lengthString;
-            var rangeString = string.Format("bytes {0}-{1}/{2}", RangeStart, RangeEnd, TotalContentLength);
-            Headers["Content-Range"] = rangeString;
+            var rangeString = $"bytes {RangeStart}-{RangeEnd}/{TotalContentLength}";
+            Headers[HeaderNames.ContentRange] = rangeString;
 
 
-            Logger.LogInformation("Setting range response values for {0}. RangeRequest: {1} Content-Length: {2}, Content-Range: {3}", Path, RangeHeader, lengthString, rangeString);
+            Logger.LogInformation("Setting range response values for {0}. RangeRequest: {1} Content-Range: {2}", Path, RangeHeader, rangeString);
         }
         }
 
 
         /// <summary>
         /// <summary>
@@ -145,8 +148,7 @@ namespace Emby.Server.Implementations.HttpServer
             }
             }
         }
         }
 
 
-        private string[] SkipLogExtensions = new string[]
-        {
+        private static readonly string[] SkipLogExtensions = {
             ".js",
             ".js",
             ".html",
             ".html",
             ".css"
             ".css"
@@ -163,8 +165,10 @@ namespace Emby.Server.Implementations.HttpServer
                 }
                 }
 
 
                 var path = Path;
                 var path = Path;
+                var offset = RangeStart;
+                var count = RangeLength;
 
 
-                if (string.IsNullOrWhiteSpace(RangeHeader) || (RangeStart <= 0 && RangeEnd >= TotalContentLength - 1))
+                if (string.IsNullOrWhiteSpace(RangeHeader) || RangeStart <= 0 && RangeEnd >= TotalContentLength - 1)
                 {
                 {
                     var extension = System.IO.Path.GetExtension(path);
                     var extension = System.IO.Path.GetExtension(path);
 
 
@@ -173,20 +177,15 @@ namespace Emby.Server.Implementations.HttpServer
                         Logger.LogDebug("Transmit file {0}", path);
                         Logger.LogDebug("Transmit file {0}", path);
                     }
                     }
 
 
-                    //var count = FileShare == FileShareMode.ReadWrite ? TotalContentLength : 0;
-
-                    await response.TransmitFile(path, 0, 0, FileShare, cancellationToken).ConfigureAwait(false);
-                    return;
+                    offset = 0;
+                    count = 0;
                 }
                 }
 
 
-                await response.TransmitFile(path, RangeStart, RangeLength, FileShare, cancellationToken).ConfigureAwait(false);
+                await response.TransmitFile(path, offset, count, FileShare, _fileSystem, _streamHelper, cancellationToken).ConfigureAwait(false);
             }
             }
             finally
             finally
             {
             {
-                if (OnComplete != null)
-                {
-                    OnComplete();
-                }
+                OnComplete?.Invoke();
             }
             }
         }
         }
 
 
@@ -203,8 +202,5 @@ namespace Emby.Server.Implementations.HttpServer
             get => (HttpStatusCode)Status;
             get => (HttpStatusCode)Status;
             set => Status = (int)value;
             set => Status = (int)value;
         }
         }
-
-        public string StatusDescription { get; set; }
-
     }
     }
 }
 }

+ 39 - 52
Emby.Server.Implementations/HttpServer/HttpListenerHost.cs

@@ -11,6 +11,7 @@ using System.Threading;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
 using Emby.Server.Implementations.Net;
 using Emby.Server.Implementations.Net;
 using Emby.Server.Implementations.Services;
 using Emby.Server.Implementations.Services;
+using Emby.Server.Implementations.SocketSharp;
 using MediaBrowser.Common.Extensions;
 using MediaBrowser.Common.Extensions;
 using MediaBrowser.Common.Net;
 using MediaBrowser.Common.Net;
 using MediaBrowser.Controller;
 using MediaBrowser.Controller;
@@ -20,6 +21,9 @@ using MediaBrowser.Model.Events;
 using MediaBrowser.Model.Extensions;
 using MediaBrowser.Model.Extensions;
 using MediaBrowser.Model.Serialization;
 using MediaBrowser.Model.Serialization;
 using MediaBrowser.Model.Services;
 using MediaBrowser.Model.Services;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Http.Internal;
+using Microsoft.AspNetCore.WebUtilities;
 using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
 using ServiceStack.Text.Jsv;
 using ServiceStack.Text.Jsv;
@@ -29,12 +33,8 @@ namespace Emby.Server.Implementations.HttpServer
     public class HttpListenerHost : IHttpServer, IDisposable
     public class HttpListenerHost : IHttpServer, IDisposable
     {
     {
         private string DefaultRedirectPath { get; set; }
         private string DefaultRedirectPath { get; set; }
-
-        private readonly ILogger _logger;
         public string[] UrlPrefixes { get; private set; }
         public string[] UrlPrefixes { get; private set; }
 
 
-        private IHttpListener _listener;
-
         public event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected;
         public event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected;
 
 
         private readonly IServerConfigurationManager _config;
         private readonly IServerConfigurationManager _config;
@@ -42,6 +42,7 @@ namespace Emby.Server.Implementations.HttpServer
         private readonly IServerApplicationHost _appHost;
         private readonly IServerApplicationHost _appHost;
         private readonly IJsonSerializer _jsonSerializer;
         private readonly IJsonSerializer _jsonSerializer;
         private readonly IXmlSerializer _xmlSerializer;
         private readonly IXmlSerializer _xmlSerializer;
+        private readonly IHttpListener _socketListener;
         private readonly Func<Type, Func<string, object>> _funcParseFn;
         private readonly Func<Type, Func<string, object>> _funcParseFn;
 
 
         public Action<IRequest, IResponse, object>[] ResponseFilters { get; set; }
         public Action<IRequest, IResponse, object>[] ResponseFilters { get; set; }
@@ -59,15 +60,18 @@ namespace Emby.Server.Implementations.HttpServer
             IConfiguration configuration,
             IConfiguration configuration,
             INetworkManager networkManager,
             INetworkManager networkManager,
             IJsonSerializer jsonSerializer,
             IJsonSerializer jsonSerializer,
-            IXmlSerializer xmlSerializer)
+            IXmlSerializer xmlSerializer,
+            IHttpListener socketListener)
         {
         {
             _appHost = applicationHost;
             _appHost = applicationHost;
-            _logger = loggerFactory.CreateLogger("HttpServer");
+            Logger = loggerFactory.CreateLogger("HttpServer");
             _config = config;
             _config = config;
             DefaultRedirectPath = configuration["HttpListenerHost:DefaultRedirectPath"];
             DefaultRedirectPath = configuration["HttpListenerHost:DefaultRedirectPath"];
             _networkManager = networkManager;
             _networkManager = networkManager;
             _jsonSerializer = jsonSerializer;
             _jsonSerializer = jsonSerializer;
             _xmlSerializer = xmlSerializer;
             _xmlSerializer = xmlSerializer;
+            _socketListener = socketListener;
+            _socketListener.WebSocketConnected = OnWebSocketConnected;
 
 
             _funcParseFn = t => s => JsvReader.GetParseFn(t)(s);
             _funcParseFn = t => s => JsvReader.GetParseFn(t)(s);
 
 
@@ -77,7 +81,7 @@ namespace Emby.Server.Implementations.HttpServer
 
 
         public string GlobalResponse { get; set; }
         public string GlobalResponse { get; set; }
 
 
-        protected ILogger Logger => _logger;
+        protected ILogger Logger { get; }
 
 
         public object CreateInstance(Type type)
         public object CreateInstance(Type type)
         {
         {
@@ -143,11 +147,11 @@ namespace Emby.Server.Implementations.HttpServer
                 return;
                 return;
             }
             }
 
 
-            var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger)
+            var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, Logger)
             {
             {
                 OnReceive = ProcessWebSocketMessageReceived,
                 OnReceive = ProcessWebSocketMessageReceived,
                 Url = e.Url,
                 Url = e.Url,
-                QueryString = e.QueryString ?? new QueryParamCollection()
+                QueryString = e.QueryString ?? new QueryCollection()
             };
             };
 
 
             connection.Closed += Connection_Closed;
             connection.Closed += Connection_Closed;
@@ -212,16 +216,16 @@ namespace Emby.Server.Implementations.HttpServer
 
 
                 if (logExceptionStackTrace)
                 if (logExceptionStackTrace)
                 {
                 {
-                    _logger.LogError(ex, "Error processing request");
+                    Logger.LogError(ex, "Error processing request");
                 }
                 }
                 else if (logExceptionMessage)
                 else if (logExceptionMessage)
                 {
                 {
-                    _logger.LogError(ex.Message);
+                    Logger.LogError(ex.Message);
                 }
                 }
 
 
                 var httpRes = httpReq.Response;
                 var httpRes = httpReq.Response;
 
 
-                if (httpRes.IsClosed)
+                if (httpRes.OriginalResponse.HasStarted)
                 {
                 {
                     return;
                     return;
                 }
                 }
@@ -234,7 +238,7 @@ namespace Emby.Server.Implementations.HttpServer
             }
             }
             catch (Exception errorEx)
             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)");
             }
             }
         }
         }
 
 
@@ -277,14 +281,6 @@ namespace Emby.Server.Implementations.HttpServer
 
 
                 }
                 }
             }
             }
-
-            if (_listener != null)
-            {
-                _logger.LogInformation("Stopping HttpListener...");
-                var task = _listener.Stop();
-                Task.WaitAll(task);
-                _logger.LogInformation("HttpListener stopped");
-            }
         }
         }
 
 
         public static string RemoveQueryStringByKey(string url, string key)
         public static string RemoveQueryStringByKey(string url, string key)
@@ -292,7 +288,7 @@ namespace Emby.Server.Implementations.HttpServer
             var uri = new Uri(url);
             var uri = new Uri(url);
 
 
             // this gets all the query string key value pairs as a collection
             // this gets all the query string key value pairs as a collection
-            var newQueryString = MyHttpUtility.ParseQueryString(uri.Query);
+            var newQueryString = QueryHelpers.ParseQuery(uri.Query);
 
 
             var originalCount = newQueryString.Count;
             var originalCount = newQueryString.Count;
 
 
@@ -313,7 +309,7 @@ namespace Emby.Server.Implementations.HttpServer
             string pagePathWithoutQueryString = url.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0];
             string pagePathWithoutQueryString = url.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0];
 
 
             return newQueryString.Count > 0
             return newQueryString.Count > 0
-                ? string.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString)
+                ? QueryHelpers.AddQueryString(pagePathWithoutQueryString, newQueryString.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()))
                 : pagePathWithoutQueryString;
                 : pagePathWithoutQueryString;
         }
         }
 
 
@@ -422,7 +418,7 @@ namespace Emby.Server.Implementations.HttpServer
         /// <summary>
         /// <summary>
         /// Overridable method that can be used to implement a custom hnandler
         /// Overridable method that can be used to implement a custom hnandler
         /// </summary>
         /// </summary>
-        protected async Task RequestHandler(IHttpRequest httpReq, string urlString, string host, string localPath, CancellationToken cancellationToken)
+        public async Task RequestHandler(IHttpRequest httpReq, string urlString, string host, string localPath, CancellationToken cancellationToken)
         {
         {
             var stopWatch = new Stopwatch();
             var stopWatch = new Stopwatch();
             stopWatch.Start();
             stopWatch.Start();
@@ -599,17 +595,15 @@ namespace Emby.Server.Implementations.HttpServer
             }
             }
             finally
             finally
             {
             {
-                httpRes.Close();
-
                 stopWatch.Stop();
                 stopWatch.Stop();
                 var elapsed = stopWatch.Elapsed;
                 var elapsed = stopWatch.Elapsed;
                 if (elapsed.TotalMilliseconds > 500)
                 if (elapsed.TotalMilliseconds > 500)
                 {
                 {
-                    _logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {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);
                 }
                 }
                 else
                 else
                 {
                 {
-                    _logger.LogDebug("HTTP Response {StatusCode} to {RemoteIp}. Time: {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
+                    Logger.LogDebug("HTTP Response {StatusCode} to {RemoteIp}. Time: {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
                 }
                 }
             }
             }
         }
         }
@@ -622,7 +616,7 @@ namespace Emby.Server.Implementations.HttpServer
             var pathParts = pathInfo.TrimStart('/').Split('/');
             var pathParts = pathInfo.TrimStart('/').Split('/');
             if (pathParts.Length == 0)
             if (pathParts.Length == 0)
             {
             {
-                _logger.LogError("Path parts empty for PathInfo: {PathInfo}, Url: {RawUrl}", pathInfo, httpReq.RawUrl);
+                Logger.LogError("Path parts empty for PathInfo: {PathInfo}, Url: {RawUrl}", pathInfo, httpReq.RawUrl);
                 return null;
                 return null;
             }
             }
 
 
@@ -636,15 +630,13 @@ namespace Emby.Server.Implementations.HttpServer
                 };
                 };
             }
             }
 
 
-            _logger.LogError("Could not find handler for {PathInfo}", pathInfo);
+            Logger.LogError("Could not find handler for {PathInfo}", pathInfo);
             return null;
             return null;
         }
         }
 
 
         private static Task Write(IResponse response, string text)
         private static Task Write(IResponse response, string text)
         {
         {
             var bOutput = Encoding.UTF8.GetBytes(text);
             var bOutput = Encoding.UTF8.GetBytes(text);
-            response.SetContentLength(bOutput.Length);
-
             return response.OutputStream.WriteAsync(bOutput, 0, bOutput.Length);
             return response.OutputStream.WriteAsync(bOutput, 0, bOutput.Length);
         }
         }
 
 
@@ -663,6 +655,7 @@ namespace Emby.Server.Implementations.HttpServer
             }
             }
             else
             else
             {
             {
+                // TODO what is this?
                 var httpsUrl = url
                 var httpsUrl = url
                     .Replace("http://", "https://", StringComparison.OrdinalIgnoreCase)
                     .Replace("http://", "https://", StringComparison.OrdinalIgnoreCase)
                     .Replace(":" + _config.Configuration.PublicPort.ToString(CultureInfo.InvariantCulture), ":" + _config.Configuration.PublicHttpsPort.ToString(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase);
                     .Replace(":" + _config.Configuration.PublicPort.ToString(CultureInfo.InvariantCulture), ":" + _config.Configuration.PublicHttpsPort.ToString(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase);
@@ -683,13 +676,15 @@ namespace Emby.Server.Implementations.HttpServer
         /// Adds the rest handlers.
         /// Adds the rest handlers.
         /// </summary>
         /// </summary>
         /// <param name="services">The services.</param>
         /// <param name="services">The services.</param>
-        public void Init(IEnumerable<IService> services, IEnumerable<IWebSocketListener> listeners)
+        /// <param name="listeners"></param>
+        /// <param name="urlPrefixes"></param>
+        public void Init(IEnumerable<IService> services, IEnumerable<IWebSocketListener> listeners, IEnumerable<string> urlPrefixes)
         {
         {
             _webSocketListeners = listeners.ToArray();
             _webSocketListeners = listeners.ToArray();
-
+            UrlPrefixes = urlPrefixes.ToArray();
             ServiceController = new ServiceController();
             ServiceController = new ServiceController();
 
 
-            _logger.LogInformation("Calling ServiceStack AppHost.Init");
+            Logger.LogInformation("Calling ServiceStack AppHost.Init");
 
 
             var types = services.Select(r => r.GetType()).ToArray();
             var types = services.Select(r => r.GetType()).ToArray();
 
 
@@ -697,7 +692,7 @@ namespace Emby.Server.Implementations.HttpServer
 
 
             ResponseFilters = new Action<IRequest, IResponse, object>[]
             ResponseFilters = new Action<IRequest, IResponse, object>[]
             {
             {
-                new ResponseFilter(_logger).FilterResponse
+                new ResponseFilter(Logger).FilterResponse
             };
             };
         }
         }
 
 
@@ -759,8 +754,12 @@ namespace Emby.Server.Implementations.HttpServer
             return _jsonSerializer.DeserializeFromStreamAsync(stream, type);
             return _jsonSerializer.DeserializeFromStreamAsync(stream, type);
         }
         }
 
 
-        //TODO Add Jellyfin Route Path Normalizer
+        public Task ProcessWebSocketRequest(HttpContext context)
+        {
+            return _socketListener.ProcessWebSocketRequest(context);
+        }
 
 
+        //TODO Add Jellyfin Route Path Normalizer
         private static string NormalizeEmbyRoutePath(string path)
         private static string NormalizeEmbyRoutePath(string path)
         {
         {
             if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
             if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
@@ -793,6 +792,7 @@ namespace Emby.Server.Implementations.HttpServer
 
 
         private bool _disposed;
         private bool _disposed;
         private readonly object _disposeLock = new object();
         private readonly object _disposeLock = new object();
+
         protected virtual void Dispose(bool disposing)
         protected virtual void Dispose(bool disposing)
         {
         {
             if (_disposed) return;
             if (_disposed) return;
@@ -821,7 +821,7 @@ namespace Emby.Server.Implementations.HttpServer
                 return Task.CompletedTask;
                 return Task.CompletedTask;
             }
             }
 
 
-            _logger.LogDebug("Websocket message received: {0}", result.MessageType);
+            Logger.LogDebug("Websocket message received: {0}", result.MessageType);
 
 
             var tasks = _webSocketListeners.Select(i => Task.Run(async () =>
             var tasks = _webSocketListeners.Select(i => Task.Run(async () =>
             {
             {
@@ -831,7 +831,7 @@ namespace Emby.Server.Implementations.HttpServer
                 }
                 }
                 catch (Exception ex)
                 catch (Exception ex)
                 {
                 {
-                    _logger.LogError(ex, "{0} failed processing WebSocket message {1}", i.GetType().Name, result.MessageType ?? string.Empty);
+                    Logger.LogError(ex, "{0} failed processing WebSocket message {1}", i.GetType().Name, result.MessageType ?? string.Empty);
                 }
                 }
             }));
             }));
 
 
@@ -842,18 +842,5 @@ namespace Emby.Server.Implementations.HttpServer
         {
         {
             Dispose(true);
             Dispose(true);
         }
         }
-
-        public void StartServer(string[] urlPrefixes, IHttpListener httpListener)
-        {
-            UrlPrefixes = urlPrefixes;
-
-            _listener = httpListener;
-
-            _listener.WebSocketConnected = OnWebSocketConnected;
-            _listener.ErrorHandler = ErrorHandler;
-            _listener.RequestHandler = RequestHandler;
-
-            _listener.Start(UrlPrefixes);
-        }
     }
     }
 }
 }

+ 32 - 56
Emby.Server.Implementations/HttpServer/HttpResultFactory.cs

@@ -16,6 +16,8 @@ using MediaBrowser.Model.IO;
 using MediaBrowser.Model.Serialization;
 using MediaBrowser.Model.Serialization;
 using MediaBrowser.Model.Services;
 using MediaBrowser.Model.Services;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Primitives;
+using Microsoft.Net.Http.Headers;
 using IRequest = MediaBrowser.Model.Services.IRequest;
 using IRequest = MediaBrowser.Model.Services.IRequest;
 using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
 using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
 
 
@@ -32,17 +34,16 @@ namespace Emby.Server.Implementations.HttpServer
         private readonly ILogger _logger;
         private readonly ILogger _logger;
         private readonly IFileSystem _fileSystem;
         private readonly IFileSystem _fileSystem;
         private readonly IJsonSerializer _jsonSerializer;
         private readonly IJsonSerializer _jsonSerializer;
-
-        private IBrotliCompressor _brotliCompressor;
+        private readonly IStreamHelper _streamHelper;
 
 
         /// <summary>
         /// <summary>
         /// Initializes a new instance of the <see cref="HttpResultFactory" /> class.
         /// Initializes a new instance of the <see cref="HttpResultFactory" /> class.
         /// </summary>
         /// </summary>
-        public HttpResultFactory(ILoggerFactory loggerfactory, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IBrotliCompressor brotliCompressor)
+        public HttpResultFactory(ILoggerFactory loggerfactory, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IStreamHelper streamHelper)
         {
         {
             _fileSystem = fileSystem;
             _fileSystem = fileSystem;
             _jsonSerializer = jsonSerializer;
             _jsonSerializer = jsonSerializer;
-            _brotliCompressor = brotliCompressor;
+            _streamHelper = streamHelper;
             _logger = loggerfactory.CreateLogger("HttpResultFactory");
             _logger = loggerfactory.CreateLogger("HttpResultFactory");
         }
         }
 
 
@@ -76,7 +77,7 @@ namespace Emby.Server.Implementations.HttpServer
         public object GetRedirectResult(string url)
         public object GetRedirectResult(string url)
         {
         {
             var responseHeaders = new Dictionary<string, string>();
             var responseHeaders = new Dictionary<string, string>();
-            responseHeaders["Location"] = url;
+            responseHeaders[HeaderNames.Location] = url;
 
 
             var result = new HttpResult(Array.Empty<byte>(), "text/plain", HttpStatusCode.Redirect);
             var result = new HttpResult(Array.Empty<byte>(), "text/plain", HttpStatusCode.Redirect);
 
 
@@ -97,9 +98,9 @@ namespace Emby.Server.Implementations.HttpServer
                 responseHeaders = new Dictionary<string, string>();
                 responseHeaders = new Dictionary<string, string>();
             }
             }
 
 
-            if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string expires))
+            if (addCachePrevention && !responseHeaders.TryGetValue(HeaderNames.Expires, out string expires))
             {
             {
-                responseHeaders["Expires"] = "-1";
+                responseHeaders[HeaderNames.Expires] = "-1";
             }
             }
 
 
             AddResponseHeaders(result, responseHeaders);
             AddResponseHeaders(result, responseHeaders);
@@ -131,7 +132,7 @@ namespace Emby.Server.Implementations.HttpServer
                     content = Array.Empty<byte>();
                     content = Array.Empty<byte>();
                 }
                 }
 
 
-                result = new StreamWriter(content, contentType, contentLength);
+                result = new StreamWriter(content, contentType);
             }
             }
             else
             else
             {
             {
@@ -143,9 +144,9 @@ namespace Emby.Server.Implementations.HttpServer
                 responseHeaders = new Dictionary<string, string>();
                 responseHeaders = new Dictionary<string, string>();
             }
             }
 
 
-            if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string _))
+            if (addCachePrevention && !responseHeaders.TryGetValue(HeaderNames.Expires, out string _))
             {
             {
-                responseHeaders["Expires"] = "-1";
+                responseHeaders[HeaderNames.Expires] = "-1";
             }
             }
 
 
             AddResponseHeaders(result, responseHeaders);
             AddResponseHeaders(result, responseHeaders);
@@ -175,7 +176,7 @@ namespace Emby.Server.Implementations.HttpServer
                     bytes = Array.Empty<byte>();
                     bytes = Array.Empty<byte>();
                 }
                 }
 
 
-                result = new StreamWriter(bytes, contentType, contentLength);
+                result = new StreamWriter(bytes, contentType);
             }
             }
             else
             else
             {
             {
@@ -187,9 +188,9 @@ namespace Emby.Server.Implementations.HttpServer
                 responseHeaders = new Dictionary<string, string>();
                 responseHeaders = new Dictionary<string, string>();
             }
             }
 
 
-            if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string _))
+            if (addCachePrevention && !responseHeaders.TryGetValue(HeaderNames.Expires, out string _))
             {
             {
-                responseHeaders["Expires"] = "-1";
+                responseHeaders[HeaderNames.Expires] = "-1";
             }
             }
 
 
             AddResponseHeaders(result, responseHeaders);
             AddResponseHeaders(result, responseHeaders);
@@ -214,7 +215,7 @@ namespace Emby.Server.Implementations.HttpServer
                 responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                 responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
             }
             }
 
 
-            responseHeaders["Expires"] = "-1";
+            responseHeaders[HeaderNames.Expires] = "-1";
 
 
             return ToOptimizedResultInternal(requestContext, result, responseHeaders);
             return ToOptimizedResultInternal(requestContext, result, responseHeaders);
         }
         }
@@ -246,9 +247,9 @@ namespace Emby.Server.Implementations.HttpServer
 
 
         private static string GetCompressionType(IRequest request)
         private static string GetCompressionType(IRequest request)
         {
         {
-            var acceptEncoding = request.Headers["Accept-Encoding"];
+            var acceptEncoding = request.Headers[HeaderNames.AcceptEncoding].ToString();
 
 
-            if (acceptEncoding != null)
+            if (string.IsNullOrEmpty(acceptEncoding))
             {
             {
                 //if (_brotliCompressor != null && acceptEncoding.IndexOf("br", StringComparison.OrdinalIgnoreCase) != -1)
                 //if (_brotliCompressor != null && acceptEncoding.IndexOf("br", StringComparison.OrdinalIgnoreCase) != -1)
                 //    return "br";
                 //    return "br";
@@ -326,21 +327,21 @@ namespace Emby.Server.Implementations.HttpServer
             }
             }
 
 
             content = Compress(content, requestedCompressionType);
             content = Compress(content, requestedCompressionType);
-            responseHeaders["Content-Encoding"] = requestedCompressionType;
+            responseHeaders[HeaderNames.ContentEncoding] = requestedCompressionType;
 
 
-            responseHeaders["Vary"] = "Accept-Encoding";
+            responseHeaders[HeaderNames.Vary] = HeaderNames.AcceptEncoding;
 
 
             var contentLength = content.Length;
             var contentLength = content.Length;
 
 
             if (isHeadRequest)
             if (isHeadRequest)
             {
             {
-                var result = new StreamWriter(Array.Empty<byte>(), contentType, contentLength);
+                var result = new StreamWriter(Array.Empty<byte>(), contentType);
                 AddResponseHeaders(result, responseHeaders);
                 AddResponseHeaders(result, responseHeaders);
                 return result;
                 return result;
             }
             }
             else
             else
             {
             {
-                var result = new StreamWriter(content, contentType, contentLength);
+                var result = new StreamWriter(content, contentType);
                 AddResponseHeaders(result, responseHeaders);
                 AddResponseHeaders(result, responseHeaders);
                 return result;
                 return result;
             }
             }
@@ -348,11 +349,6 @@ namespace Emby.Server.Implementations.HttpServer
 
 
         private byte[] Compress(byte[] bytes, string compressionType)
         private byte[] Compress(byte[] bytes, string compressionType)
         {
         {
-            if (string.Equals(compressionType, "br", StringComparison.OrdinalIgnoreCase))
-            {
-                return CompressBrotli(bytes);
-            }
-
             if (string.Equals(compressionType, "deflate", StringComparison.OrdinalIgnoreCase))
             if (string.Equals(compressionType, "deflate", StringComparison.OrdinalIgnoreCase))
             {
             {
                 return Deflate(bytes);
                 return Deflate(bytes);
@@ -366,11 +362,6 @@ namespace Emby.Server.Implementations.HttpServer
             throw new NotSupportedException(compressionType);
             throw new NotSupportedException(compressionType);
         }
         }
 
 
-        private byte[] CompressBrotli(byte[] bytes)
-        {
-            return _brotliCompressor.Compress(bytes);
-        }
-
         private static byte[] Deflate(byte[] bytes)
         private static byte[] Deflate(byte[] bytes)
         {
         {
             // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
             // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
@@ -424,12 +415,12 @@ namespace Emby.Server.Implementations.HttpServer
         /// </summary>
         /// </summary>
         private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, StaticResultOptions options)
         private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, StaticResultOptions options)
         {
         {
-            bool noCache = (requestContext.Headers.Get("Cache-Control") ?? string.Empty).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1;
+            bool noCache = (requestContext.Headers[HeaderNames.CacheControl].ToString()).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1;
             AddCachingHeaders(responseHeaders, options.CacheDuration, noCache, options.DateLastModified);
             AddCachingHeaders(responseHeaders, options.CacheDuration, noCache, options.DateLastModified);
 
 
             if (!noCache)
             if (!noCache)
             {
             {
-                DateTime.TryParse(requestContext.Headers.Get("If-Modified-Since"), out var ifModifiedSinceHeader);
+                DateTime.TryParse(requestContext.Headers[HeaderNames.IfModifiedSince], out var ifModifiedSinceHeader);
 
 
                 if (IsNotModified(ifModifiedSinceHeader, options.CacheDuration, options.DateLastModified))
                 if (IsNotModified(ifModifiedSinceHeader, options.CacheDuration, options.DateLastModified))
                 {
                 {
@@ -530,7 +521,7 @@ namespace Emby.Server.Implementations.HttpServer
             options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
             options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
 
 
             var contentType = options.ContentType;
             var contentType = options.ContentType;
-            if (!string.IsNullOrEmpty(requestContext.Headers.Get("If-Modified-Since")))
+            if (!StringValues.IsNullOrEmpty(requestContext.Headers[HeaderNames.IfModifiedSince]))
             {
             {
                 // See if the result is already cached in the browser
                 // See if the result is already cached in the browser
                 var result = GetCachedResult(requestContext, options.ResponseHeaders, options);
                 var result = GetCachedResult(requestContext, options.ResponseHeaders, options);
@@ -548,11 +539,11 @@ namespace Emby.Server.Implementations.HttpServer
             AddCachingHeaders(responseHeaders, options.CacheDuration, false, options.DateLastModified);
             AddCachingHeaders(responseHeaders, options.CacheDuration, false, options.DateLastModified);
             AddAgeHeader(responseHeaders, options.DateLastModified);
             AddAgeHeader(responseHeaders, options.DateLastModified);
 
 
-            var rangeHeader = requestContext.Headers.Get("Range");
+            var rangeHeader = requestContext.Headers[HeaderNames.Range];
 
 
             if (!isHeadRequest && !string.IsNullOrEmpty(options.Path))
             if (!isHeadRequest && !string.IsNullOrEmpty(options.Path))
             {
             {
-                var hasHeaders = new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem)
+                var hasHeaders = new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem, _streamHelper)
                 {
                 {
                     OnComplete = options.OnComplete,
                     OnComplete = options.OnComplete,
                     OnError = options.OnError,
                     OnError = options.OnError,
@@ -590,11 +581,6 @@ namespace Emby.Server.Implementations.HttpServer
             }
             }
             else
             else
             {
             {
-                if (totalContentLength.HasValue)
-                {
-                    responseHeaders["Content-Length"] = totalContentLength.Value.ToString(UsCulture);
-                }
-
                 if (isHeadRequest)
                 if (isHeadRequest)
                 {
                 {
                     using (stream)
                     using (stream)
@@ -614,11 +600,6 @@ namespace Emby.Server.Implementations.HttpServer
             }
             }
         }
         }
 
 
-        /// <summary>
-        /// The us culture
-        /// </summary>
-        private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
-
         /// <summary>
         /// <summary>
         /// Adds the caching responseHeaders.
         /// Adds the caching responseHeaders.
         /// </summary>
         /// </summary>
@@ -627,23 +608,23 @@ namespace Emby.Server.Implementations.HttpServer
         {
         {
             if (noCache)
             if (noCache)
             {
             {
-                responseHeaders["Cache-Control"] = "no-cache, no-store, must-revalidate";
-                responseHeaders["pragma"] = "no-cache, no-store, must-revalidate";
+                responseHeaders[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate";
+                responseHeaders[HeaderNames.Pragma] = "no-cache, no-store, must-revalidate";
                 return;
                 return;
             }
             }
 
 
             if (cacheDuration.HasValue)
             if (cacheDuration.HasValue)
             {
             {
-                responseHeaders["Cache-Control"] = "public, max-age=" + cacheDuration.Value.TotalSeconds;
+                responseHeaders[HeaderNames.CacheControl] = "public, max-age=" + cacheDuration.Value.TotalSeconds;
             }
             }
             else
             else
             {
             {
-                responseHeaders["Cache-Control"] = "public";
+                responseHeaders[HeaderNames.CacheControl] = "public";
             }
             }
 
 
             if (lastModifiedDate.HasValue)
             if (lastModifiedDate.HasValue)
             {
             {
-                responseHeaders["Last-Modified"] = lastModifiedDate.ToString();
+                responseHeaders[HeaderNames.LastModified] = lastModifiedDate.ToString();
             }
             }
         }
         }
 
 
@@ -656,7 +637,7 @@ namespace Emby.Server.Implementations.HttpServer
         {
         {
             if (lastDateModified.HasValue)
             if (lastDateModified.HasValue)
             {
             {
-                responseHeaders["Age"] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
+                responseHeaders[HeaderNames.Age] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
             }
             }
         }
         }
 
 
@@ -714,9 +695,4 @@ namespace Emby.Server.Implementations.HttpServer
             }
             }
         }
         }
     }
     }
-
-    public interface IBrotliCompressor
-    {
-        byte[] Compress(byte[] content);
-    }
 }
 }

+ 3 - 14
Emby.Server.Implementations/HttpServer/IHttpListener.cs

@@ -1,10 +1,9 @@
 using System;
 using System;
-using System.Collections.Generic;
 using System.Threading;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
 using Emby.Server.Implementations.Net;
 using Emby.Server.Implementations.Net;
-using MediaBrowser.Controller.Net;
 using MediaBrowser.Model.Services;
 using MediaBrowser.Model.Services;
+using Microsoft.AspNetCore.Http;
 
 
 namespace Emby.Server.Implementations.HttpServer
 namespace Emby.Server.Implementations.HttpServer
 {
 {
@@ -28,21 +27,11 @@ namespace Emby.Server.Implementations.HttpServer
         /// <value>The web socket handler.</value>
         /// <value>The web socket handler.</value>
         Action<WebSocketConnectEventArgs> WebSocketConnected { get; set; }
         Action<WebSocketConnectEventArgs> WebSocketConnected { get; set; }
 
 
-        /// <summary>
-        /// Gets or sets the web socket connecting.
-        /// </summary>
-        /// <value>The web socket connecting.</value>
-        Action<WebSocketConnectingEventArgs> WebSocketConnecting { get; set; }
-
-        /// <summary>
-        /// Starts this instance.
-        /// </summary>
-        /// <param name="urlPrefixes">The URL prefixes.</param>
-        void Start(IEnumerable<string> urlPrefixes);
-
         /// <summary>
         /// <summary>
         /// Stops this instance.
         /// Stops this instance.
         /// </summary>
         /// </summary>
         Task Stop();
         Task Stop();
+
+        Task ProcessWebSocketRequest(HttpContext ctx);
     }
     }
 }
 }

+ 4 - 5
Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs

@@ -7,6 +7,7 @@ using System.Threading;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
 using MediaBrowser.Model.Services;
 using MediaBrowser.Model.Services;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
+using Microsoft.Net.Http.Headers;
 
 
 namespace Emby.Server.Implementations.HttpServer
 namespace Emby.Server.Implementations.HttpServer
 {
 {
@@ -66,8 +67,8 @@ namespace Emby.Server.Implementations.HttpServer
             this._logger = logger;
             this._logger = logger;
 
 
             ContentType = contentType;
             ContentType = contentType;
-            Headers["Content-Type"] = contentType;
-            Headers["Accept-Ranges"] = "bytes";
+            Headers[HeaderNames.ContentType] = contentType;
+            Headers[HeaderNames.AcceptRanges] = "bytes";
             StatusCode = HttpStatusCode.PartialContent;
             StatusCode = HttpStatusCode.PartialContent;
 
 
             SetRangeValues(contentLength);
             SetRangeValues(contentLength);
@@ -95,9 +96,7 @@ namespace Emby.Server.Implementations.HttpServer
             RangeStart = requestedRange.Key;
             RangeStart = requestedRange.Key;
             RangeLength = 1 + RangeEnd - RangeStart;
             RangeLength = 1 + RangeEnd - RangeStart;
 
 
-            // Content-Length is the length of what we're serving, not the original content
-            Headers["Content-Length"] = RangeLength.ToString(UsCulture);
-            Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", RangeStart, RangeEnd, TotalContentLength);
+            Headers[HeaderNames.ContentRange] = $"bytes {RangeStart}-{RangeEnd}/{TotalContentLength}";
 
 
             if (RangeStart > 0 && SourceStream.CanSeek)
             if (RangeStart > 0 && SourceStream.CanSeek)
             {
             {

+ 5 - 5
Emby.Server.Implementations/HttpServer/ResponseFilter.cs

@@ -3,6 +3,7 @@ using System.Globalization;
 using System.Text;
 using System.Text;
 using MediaBrowser.Model.Services;
 using MediaBrowser.Model.Services;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
+using Microsoft.Net.Http.Headers;
 
 
 namespace Emby.Server.Implementations.HttpServer
 namespace Emby.Server.Implementations.HttpServer
 {
 {
@@ -25,7 +26,7 @@ namespace Emby.Server.Implementations.HttpServer
         public void FilterResponse(IRequest req, IResponse res, object dto)
         public void FilterResponse(IRequest req, IResponse res, object dto)
         {
         {
             // Try to prevent compatibility view
             // 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-Headers", "Accept, Accept-Language, Authorization, Cache-Control, Content-Disposition, Content-Encoding, Content-Language, 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-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
             res.AddHeader("Access-Control-Allow-Origin", "*");
             res.AddHeader("Access-Control-Allow-Origin", "*");
 
 
@@ -44,20 +45,19 @@ namespace Emby.Server.Implementations.HttpServer
 
 
             if (dto is IHasHeaders hasHeaders)
             if (dto is IHasHeaders hasHeaders)
             {
             {
-                if (!hasHeaders.Headers.ContainsKey("Server"))
+                if (!hasHeaders.Headers.ContainsKey(HeaderNames.Server))
                 {
                 {
-                    hasHeaders.Headers["Server"] = "Microsoft-NetCore/2.0, UPnP/1.0 DLNADOC/1.50";
+                    hasHeaders.Headers[HeaderNames.Server] = "Microsoft-NetCore/2.0, UPnP/1.0 DLNADOC/1.50";
                 }
                 }
 
 
                 // Content length has to be explicitly set on on HttpListenerResponse or it won't be happy
                 // Content length has to be explicitly set on on HttpListenerResponse or it won't be happy
-                if (hasHeaders.Headers.TryGetValue("Content-Length", out string contentLength)
+                if (hasHeaders.Headers.TryGetValue(HeaderNames.ContentLength, out string contentLength)
                     && !string.IsNullOrEmpty(contentLength))
                     && !string.IsNullOrEmpty(contentLength))
                 {
                 {
                     var length = long.Parse(contentLength, UsCulture);
                     var length = long.Parse(contentLength, UsCulture);
 
 
                     if (length > 0)
                     if (length > 0)
                     {
                     {
-                        res.SetContentLength(length);
                         res.SendChunked = false;
                         res.SendChunked = false;
                     }
                     }
                 }
                 }

+ 2 - 1
Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs

@@ -5,6 +5,7 @@ using MediaBrowser.Controller.Library;
 using MediaBrowser.Controller.Net;
 using MediaBrowser.Controller.Net;
 using MediaBrowser.Controller.Security;
 using MediaBrowser.Controller.Security;
 using MediaBrowser.Model.Services;
 using MediaBrowser.Model.Services;
+using Microsoft.Net.Http.Headers;
 
 
 namespace Emby.Server.Implementations.HttpServer.Security
 namespace Emby.Server.Implementations.HttpServer.Security
 {
 {
@@ -176,7 +177,7 @@ namespace Emby.Server.Implementations.HttpServer.Security
 
 
             if (string.IsNullOrEmpty(auth))
             if (string.IsNullOrEmpty(auth))
             {
             {
-                auth = httpReq.Headers["Authorization"];
+                auth = httpReq.Headers[HeaderNames.Authorization];
             }
             }
 
 
             return GetAuthorization(auth);
             return GetAuthorization(auth);

+ 4 - 12
Emby.Server.Implementations/HttpServer/StreamWriter.cs

@@ -5,7 +5,7 @@ using System.IO;
 using System.Threading;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
 using MediaBrowser.Model.Services;
 using MediaBrowser.Model.Services;
-using Microsoft.Extensions.Logging;
+using Microsoft.Net.Http.Headers;
 
 
 namespace Emby.Server.Implementations.HttpServer
 namespace Emby.Server.Implementations.HttpServer
 {
 {
@@ -52,12 +52,7 @@ namespace Emby.Server.Implementations.HttpServer
 
 
             SourceStream = source;
             SourceStream = source;
 
 
-            Headers["Content-Type"] = contentType;
-
-            if (source.CanSeek)
-            {
-                Headers["Content-Length"] = source.Length.ToString(UsCulture);
-            }
+            Headers[HeaderNames.ContentType] = contentType;
         }
         }
 
 
         /// <summary>
         /// <summary>
@@ -65,8 +60,7 @@ namespace Emby.Server.Implementations.HttpServer
         /// </summary>
         /// </summary>
         /// <param name="source">The source.</param>
         /// <param name="source">The source.</param>
         /// <param name="contentType">Type of the content.</param>
         /// <param name="contentType">Type of the content.</param>
-        /// <param name="logger">The logger.</param>
-        public StreamWriter(byte[] source, string contentType, int contentLength)
+        public StreamWriter(byte[] source, string contentType)
         {
         {
             if (string.IsNullOrEmpty(contentType))
             if (string.IsNullOrEmpty(contentType))
             {
             {
@@ -75,9 +69,7 @@ namespace Emby.Server.Implementations.HttpServer
 
 
             SourceBytes = source;
             SourceBytes = source;
 
 
-            Headers["Content-Type"] = contentType;
-
-            Headers["Content-Length"] = contentLength.ToString(UsCulture);
+            Headers[HeaderNames.ContentType] = contentType;
         }
         }
 
 
         public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken)
         public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken)

+ 3 - 36
Emby.Server.Implementations/HttpServer/WebSocketConnection.cs

@@ -8,6 +8,7 @@ using MediaBrowser.Controller.Net;
 using MediaBrowser.Model.Net;
 using MediaBrowser.Model.Net;
 using MediaBrowser.Model.Serialization;
 using MediaBrowser.Model.Serialization;
 using MediaBrowser.Model.Services;
 using MediaBrowser.Model.Services;
+using Microsoft.AspNetCore.Http;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
 using UtfUnknown;
 using UtfUnknown;
 
 
@@ -67,7 +68,7 @@ namespace Emby.Server.Implementations.HttpServer
         /// Gets or sets the query string.
         /// Gets or sets the query string.
         /// </summary>
         /// </summary>
         /// <value>The query string.</value>
         /// <value>The query string.</value>
-        public QueryParamCollection QueryString { get; set; }
+        public IQueryCollection QueryString { get; set; }
 
 
         /// <summary>
         /// <summary>
         /// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
         /// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
@@ -101,12 +102,6 @@ namespace Emby.Server.Implementations.HttpServer
             _socket = socket;
             _socket = socket;
             _socket.OnReceiveBytes = OnReceiveInternal;
             _socket.OnReceiveBytes = OnReceiveInternal;
 
 
-            var memorySocket = socket as IMemoryWebSocket;
-            if (memorySocket != null)
-            {
-                memorySocket.OnReceiveMemoryBytes = OnReceiveInternal;
-            }
-
             RemoteEndPoint = remoteEndPoint;
             RemoteEndPoint = remoteEndPoint;
             _logger = logger;
             _logger = logger;
 
 
@@ -142,34 +137,6 @@ namespace Emby.Server.Implementations.HttpServer
             }
             }
         }
         }
 
 
-        /// <summary>
-        /// Called when [receive].
-        /// </summary>
-        /// <param name="memory">The memory block.</param>
-        /// <param name="length">The length of the memory block.</param>
-        private void OnReceiveInternal(Memory<byte> memory, int length)
-        {
-            LastActivityDate = DateTime.UtcNow;
-
-            if (OnReceive == null)
-            {
-                return;
-            }
-
-            var bytes = memory.Slice(0, length).ToArray();
-
-            var charset = CharsetDetector.DetectFromBytes(bytes).Detected?.EncodingName;
-
-            if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
-            {
-                OnReceiveInternal(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
-            }
-            else
-            {
-                OnReceiveInternal(Encoding.ASCII.GetString(bytes, 0, bytes.Length));
-            }
-        }
-
         private void OnReceiveInternal(string message)
         private void OnReceiveInternal(string message)
         {
         {
             LastActivityDate = DateTime.UtcNow;
             LastActivityDate = DateTime.UtcNow;
@@ -193,7 +160,7 @@ namespace Emby.Server.Implementations.HttpServer
                 var info = new WebSocketMessageInfo
                 var info = new WebSocketMessageInfo
                 {
                 {
                     MessageType = stub.MessageType,
                     MessageType = stub.MessageType,
-                    Data = stub.Data == null ? null : stub.Data.ToString(),
+                    Data = stub.Data?.ToString(),
                     Connection = this
                     Connection = this
                 };
                 };
 
 

+ 3 - 12
Emby.Server.Implementations/IO/LibraryMonitor.cs

@@ -10,8 +10,8 @@ using MediaBrowser.Controller.Library;
 using MediaBrowser.Controller.Plugins;
 using MediaBrowser.Controller.Plugins;
 using MediaBrowser.Model.IO;
 using MediaBrowser.Model.IO;
 using MediaBrowser.Model.System;
 using MediaBrowser.Model.System;
-using MediaBrowser.Model.Tasks;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
+using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
 
 
 namespace Emby.Server.Implementations.IO
 namespace Emby.Server.Implementations.IO
 {
 {
@@ -127,7 +127,6 @@ namespace Emby.Server.Implementations.IO
         private IServerConfigurationManager ConfigurationManager { get; set; }
         private IServerConfigurationManager ConfigurationManager { get; set; }
 
 
         private readonly IFileSystem _fileSystem;
         private readonly IFileSystem _fileSystem;
-        private readonly IEnvironmentInfo _environmentInfo;
 
 
         /// <summary>
         /// <summary>
         /// Initializes a new instance of the <see cref="LibraryMonitor" /> class.
         /// Initializes a new instance of the <see cref="LibraryMonitor" /> class.
@@ -136,14 +135,12 @@ namespace Emby.Server.Implementations.IO
             ILoggerFactory loggerFactory,
             ILoggerFactory loggerFactory,
             ILibraryManager libraryManager,
             ILibraryManager libraryManager,
             IServerConfigurationManager configurationManager,
             IServerConfigurationManager configurationManager,
-            IFileSystem fileSystem,
-            IEnvironmentInfo environmentInfo)
+            IFileSystem fileSystem)
         {
         {
             LibraryManager = libraryManager;
             LibraryManager = libraryManager;
             Logger = loggerFactory.CreateLogger(GetType().Name);
             Logger = loggerFactory.CreateLogger(GetType().Name);
             ConfigurationManager = configurationManager;
             ConfigurationManager = configurationManager;
             _fileSystem = fileSystem;
             _fileSystem = fileSystem;
-            _environmentInfo = environmentInfo;
         }
         }
 
 
         private bool IsLibraryMonitorEnabled(BaseItem item)
         private bool IsLibraryMonitorEnabled(BaseItem item)
@@ -267,7 +264,7 @@ namespace Emby.Server.Implementations.IO
                 return;
                 return;
             }
             }
 
 
-            if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
+            if (OperatingSystem.Id != OperatingSystemId.Windows)
             {
             {
                 if (path.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase) || path.StartsWith("smb://", StringComparison.OrdinalIgnoreCase))
                 if (path.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase) || path.StartsWith("smb://", StringComparison.OrdinalIgnoreCase))
                 {
                 {
@@ -276,12 +273,6 @@ namespace Emby.Server.Implementations.IO
                 }
                 }
             }
             }
 
 
-            if (_environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Android)
-            {
-                // causing crashing
-                return;
-            }
-
             // Already being watched
             // Already being watched
             if (_fileSystemWatchers.ContainsKey(path))
             if (_fileSystemWatchers.ContainsKey(path))
             {
             {

+ 10 - 13
Emby.Server.Implementations/IO/ManagedFileSystem.cs

@@ -7,8 +7,8 @@ using System.Text;
 using MediaBrowser.Common.Configuration;
 using MediaBrowser.Common.Configuration;
 using MediaBrowser.Model.IO;
 using MediaBrowser.Model.IO;
 using MediaBrowser.Model.System;
 using MediaBrowser.Model.System;
-using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
+using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
 
 
 namespace Emby.Server.Implementations.IO
 namespace Emby.Server.Implementations.IO
 {
 {
@@ -25,22 +25,19 @@ namespace Emby.Server.Implementations.IO
 
 
         private readonly string _tempPath;
         private readonly string _tempPath;
 
 
-        private readonly IEnvironmentInfo _environmentInfo;
         private readonly bool _isEnvironmentCaseInsensitive;
         private readonly bool _isEnvironmentCaseInsensitive;
 
 
         public ManagedFileSystem(
         public ManagedFileSystem(
             ILoggerFactory loggerFactory,
             ILoggerFactory loggerFactory,
-            IEnvironmentInfo environmentInfo,
             IApplicationPaths applicationPaths)
             IApplicationPaths applicationPaths)
         {
         {
             Logger = loggerFactory.CreateLogger("FileSystem");
             Logger = loggerFactory.CreateLogger("FileSystem");
             _supportsAsyncFileStreams = true;
             _supportsAsyncFileStreams = true;
             _tempPath = applicationPaths.TempDirectory;
             _tempPath = applicationPaths.TempDirectory;
-            _environmentInfo = environmentInfo;
 
 
-            SetInvalidFileNameChars(environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows);
+            SetInvalidFileNameChars(OperatingSystem.Id == OperatingSystemId.Windows);
 
 
-            _isEnvironmentCaseInsensitive = environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows;
+            _isEnvironmentCaseInsensitive = OperatingSystem.Id == OperatingSystemId.Windows;
         }
         }
 
 
         public virtual void AddShortcutHandler(IShortcutHandler handler)
         public virtual void AddShortcutHandler(IShortcutHandler handler)
@@ -469,7 +466,7 @@ namespace Emby.Server.Implementations.IO
 
 
         public virtual void SetHidden(string path, bool isHidden)
         public virtual void SetHidden(string path, bool isHidden)
         {
         {
-            if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
+            if (OperatingSystem.Id != MediaBrowser.Model.System.OperatingSystemId.Windows)
             {
             {
                 return;
                 return;
             }
             }
@@ -493,7 +490,7 @@ namespace Emby.Server.Implementations.IO
 
 
         public virtual void SetReadOnly(string path, bool isReadOnly)
         public virtual void SetReadOnly(string path, bool isReadOnly)
         {
         {
-            if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
+            if (OperatingSystem.Id != MediaBrowser.Model.System.OperatingSystemId.Windows)
             {
             {
                 return;
                 return;
             }
             }
@@ -517,7 +514,7 @@ namespace Emby.Server.Implementations.IO
 
 
         public virtual void SetAttributes(string path, bool isHidden, bool isReadOnly)
         public virtual void SetAttributes(string path, bool isHidden, bool isReadOnly)
         {
         {
-            if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
+            if (OperatingSystem.Id != MediaBrowser.Model.System.OperatingSystemId.Windows)
             {
             {
                 return;
                 return;
             }
             }
@@ -711,20 +708,20 @@ namespace Emby.Server.Implementations.IO
             return GetFiles(path, null, false, recursive);
             return GetFiles(path, null, false, recursive);
         }
         }
 
 
-        public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
+        public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, IReadOnlyList<string> extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
         {
         {
             var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
             var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
 
 
             // On linux and osx the search pattern is case sensitive
             // On linux and osx the search pattern is case sensitive
             // If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
             // If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
-            if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions != null && extensions.Length == 1)
+            if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions != null && extensions.Count == 1)
             {
             {
                 return ToMetadata(new DirectoryInfo(path).EnumerateFiles("*" + extensions[0], searchOption));
                 return ToMetadata(new DirectoryInfo(path).EnumerateFiles("*" + extensions[0], searchOption));
             }
             }
 
 
             var files = new DirectoryInfo(path).EnumerateFiles("*", searchOption);
             var files = new DirectoryInfo(path).EnumerateFiles("*", searchOption);
 
 
-            if (extensions != null && extensions.Length > 0)
+            if (extensions != null && extensions.Count > 0)
             {
             {
                 files = files.Where(i =>
                 files = files.Where(i =>
                 {
                 {
@@ -802,7 +799,7 @@ namespace Emby.Server.Implementations.IO
 
 
         public virtual void SetExecutable(string path)
         public virtual void SetExecutable(string path)
         {
         {
-            if (_environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.OSX)
+            if (OperatingSystem.Id == MediaBrowser.Model.System.OperatingSystemId.Darwin)
             {
             {
                 RunProcess("chmod", "+x \"" + path + "\"", Path.GetDirectoryName(path));
                 RunProcess("chmod", "+x \"" + path + "\"", Path.GetDirectoryName(path));
             }
             }

+ 136 - 90
Emby.Server.Implementations/IO/StreamHelper.cs

@@ -1,4 +1,5 @@
 using System;
 using System;
+using System.Buffers;
 using System.IO;
 using System.IO;
 using System.Threading;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
@@ -8,168 +9,213 @@ namespace Emby.Server.Implementations.IO
 {
 {
     public class StreamHelper : IStreamHelper
     public class StreamHelper : IStreamHelper
     {
     {
+        private const int StreamCopyToBufferSize = 81920;
+
         public async Task CopyToAsync(Stream source, Stream destination, int bufferSize, Action onStarted, CancellationToken cancellationToken)
         public async Task CopyToAsync(Stream source, Stream destination, int bufferSize, Action onStarted, CancellationToken cancellationToken)
         {
         {
-            byte[] buffer = new byte[bufferSize];
-            int read;
-            while ((read = source.Read(buffer, 0, buffer.Length)) != 0)
+            byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
+            try
             {
             {
-                cancellationToken.ThrowIfCancellationRequested();
+                int read;
+                while ((read = await source.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) != 0)
+                {
+                    cancellationToken.ThrowIfCancellationRequested();
 
 
-                await destination.WriteAsync(buffer, 0, read).ConfigureAwait(false);
+                    await destination.WriteAsync(buffer, 0, read).ConfigureAwait(false);
 
 
-                if (onStarted != null)
-                {
-                    onStarted();
-                    onStarted = null;
+                    if (onStarted != null)
+                    {
+                        onStarted();
+                        onStarted = null;
+                    }
                 }
                 }
             }
             }
+            finally
+            {
+                ArrayPool<byte>.Shared.Return(buffer);
+            }
         }
         }
 
 
         public async Task CopyToAsync(Stream source, Stream destination, int bufferSize, int emptyReadLimit, CancellationToken cancellationToken)
         public async Task CopyToAsync(Stream source, Stream destination, int bufferSize, int emptyReadLimit, CancellationToken cancellationToken)
         {
         {
-            byte[] buffer = new byte[bufferSize];
-
-            if (emptyReadLimit <= 0)
+            byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
+            try
             {
             {
-                int read;
-                while ((read = source.Read(buffer, 0, buffer.Length)) != 0)
+                if (emptyReadLimit <= 0)
                 {
                 {
-                    cancellationToken.ThrowIfCancellationRequested();
+                    int read;
+                    while ((read = await source.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) != 0)
+                    {
+                        cancellationToken.ThrowIfCancellationRequested();
 
 
-                    await destination.WriteAsync(buffer, 0, read).ConfigureAwait(false);
-                }
+                        await destination.WriteAsync(buffer, 0, read).ConfigureAwait(false);
+                    }
 
 
-                return;
-            }
+                    return;
+                }
 
 
-            var eofCount = 0;
+                var eofCount = 0;
 
 
-            while (eofCount < emptyReadLimit)
-            {
-                cancellationToken.ThrowIfCancellationRequested();
+                while (eofCount < emptyReadLimit)
+                {
+                    cancellationToken.ThrowIfCancellationRequested();
 
 
-                var bytesRead = source.Read(buffer, 0, buffer.Length);
+                    var bytesRead = await source.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
 
 
-                if (bytesRead == 0)
-                {
-                    eofCount++;
-                    await Task.Delay(50, cancellationToken).ConfigureAwait(false);
-                }
-                else
-                {
-                    eofCount = 0;
+                    if (bytesRead == 0)
+                    {
+                        eofCount++;
+                        await Task.Delay(50, cancellationToken).ConfigureAwait(false);
+                    }
+                    else
+                    {
+                        eofCount = 0;
 
 
-                    await destination.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
+                        await destination.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
+                    }
                 }
                 }
             }
             }
+            finally
+            {
+                ArrayPool<byte>.Shared.Return(buffer);
+            }
         }
         }
 
 
-        const int StreamCopyToBufferSize = 81920;
         public async Task<int> CopyToAsync(Stream source, Stream destination, CancellationToken cancellationToken)
         public async Task<int> CopyToAsync(Stream source, Stream destination, CancellationToken cancellationToken)
         {
         {
-            var array = new byte[StreamCopyToBufferSize];
-            int bytesRead;
-            int totalBytesRead = 0;
-
-            while ((bytesRead = await source.ReadAsync(array, 0, array.Length, cancellationToken).ConfigureAwait(false)) != 0)
+            byte[] buffer = ArrayPool<byte>.Shared.Rent(StreamCopyToBufferSize);
+            try
             {
             {
-                var bytesToWrite = bytesRead;
+                int totalBytesRead = 0;
 
 
-                if (bytesToWrite > 0)
+                int bytesRead;
+                while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
                 {
                 {
-                    await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
+                    var bytesToWrite = bytesRead;
 
 
-                    totalBytesRead += bytesRead;
+                    if (bytesToWrite > 0)
+                    {
+                        await destination.WriteAsync(buffer, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
+
+                        totalBytesRead += bytesRead;
+                    }
                 }
                 }
-            }
 
 
-            return totalBytesRead;
+                return totalBytesRead;
+            }
+            finally
+            {
+                ArrayPool<byte>.Shared.Return(buffer);
+            }
         }
         }
 
 
         public async Task<int> CopyToAsyncWithSyncRead(Stream source, Stream destination, CancellationToken cancellationToken)
         public async Task<int> CopyToAsyncWithSyncRead(Stream source, Stream destination, CancellationToken cancellationToken)
         {
         {
-            var array = new byte[StreamCopyToBufferSize];
-            int bytesRead;
-            int totalBytesRead = 0;
-
-            while ((bytesRead = source.Read(array, 0, array.Length)) != 0)
+            byte[] buffer = ArrayPool<byte>.Shared.Rent(StreamCopyToBufferSize);
+            try
             {
             {
-                var bytesToWrite = bytesRead;
+                int bytesRead;
+                int totalBytesRead = 0;
 
 
-                if (bytesToWrite > 0)
+                while ((bytesRead = source.Read(buffer, 0, buffer.Length)) != 0)
                 {
                 {
-                    await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
+                    var bytesToWrite = bytesRead;
 
 
-                    totalBytesRead += bytesRead;
+                    if (bytesToWrite > 0)
+                    {
+                        await destination.WriteAsync(buffer, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
+
+                        totalBytesRead += bytesRead;
+                    }
                 }
                 }
-            }
 
 
-            return totalBytesRead;
+                return totalBytesRead;
+            }
+            finally
+            {
+                ArrayPool<byte>.Shared.Return(buffer);
+            }
         }
         }
 
 
         public async Task CopyToAsyncWithSyncRead(Stream source, Stream destination, long copyLength, CancellationToken cancellationToken)
         public async Task CopyToAsyncWithSyncRead(Stream source, Stream destination, long copyLength, CancellationToken cancellationToken)
         {
         {
-            var array = new byte[StreamCopyToBufferSize];
-            int bytesRead;
-
-            while ((bytesRead = source.Read(array, 0, array.Length)) != 0)
+            byte[] buffer = ArrayPool<byte>.Shared.Rent(StreamCopyToBufferSize);
+            try
             {
             {
-                var bytesToWrite = Math.Min(bytesRead, copyLength);
+                int bytesRead;
 
 
-                if (bytesToWrite > 0)
+                while ((bytesRead = source.Read(buffer, 0, buffer.Length)) != 0)
                 {
                 {
-                    await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
-                }
+                    var bytesToWrite = Math.Min(bytesRead, copyLength);
 
 
-                copyLength -= bytesToWrite;
+                    if (bytesToWrite > 0)
+                    {
+                        await destination.WriteAsync(buffer, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
+                    }
 
 
-                if (copyLength <= 0)
-                {
-                    break;
+                    copyLength -= bytesToWrite;
+
+                    if (copyLength <= 0)
+                    {
+                        break;
+                    }
                 }
                 }
             }
             }
+            finally
+            {
+                ArrayPool<byte>.Shared.Return(buffer);
+            }
         }
         }
 
 
         public async Task CopyToAsync(Stream source, Stream destination, long copyLength, CancellationToken cancellationToken)
         public async Task CopyToAsync(Stream source, Stream destination, long copyLength, CancellationToken cancellationToken)
         {
         {
-            var array = new byte[StreamCopyToBufferSize];
-            int bytesRead;
-
-            while ((bytesRead = await source.ReadAsync(array, 0, array.Length, cancellationToken).ConfigureAwait(false)) != 0)
+            byte[] buffer = ArrayPool<byte>.Shared.Rent(StreamCopyToBufferSize);
+            try
             {
             {
-                var bytesToWrite = Math.Min(bytesRead, copyLength);
+                int bytesRead;
 
 
-                if (bytesToWrite > 0)
+                while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
                 {
                 {
-                    await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
-                }
+                    var bytesToWrite = Math.Min(bytesRead, copyLength);
 
 
-                copyLength -= bytesToWrite;
+                    if (bytesToWrite > 0)
+                    {
+                        await destination.WriteAsync(buffer, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
+                    }
 
 
-                if (copyLength <= 0)
-                {
-                    break;
+                    copyLength -= bytesToWrite;
+
+                    if (copyLength <= 0)
+                    {
+                        break;
+                    }
                 }
                 }
             }
             }
+            finally
+            {
+                ArrayPool<byte>.Shared.Return(buffer);
+            }
         }
         }
 
 
         public async Task CopyUntilCancelled(Stream source, Stream target, int bufferSize, CancellationToken cancellationToken)
         public async Task CopyUntilCancelled(Stream source, Stream target, int bufferSize, CancellationToken cancellationToken)
         {
         {
-            byte[] buffer = new byte[bufferSize];
-
-            while (!cancellationToken.IsCancellationRequested)
+            byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
+            try
             {
             {
-                var bytesRead = await CopyToAsyncInternal(source, target, buffer, cancellationToken).ConfigureAwait(false);
-
-                //var position = fs.Position;
-                //_logger.LogDebug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path);
-
-                if (bytesRead == 0)
+                while (!cancellationToken.IsCancellationRequested)
                 {
                 {
-                    await Task.Delay(100).ConfigureAwait(false);
+                    var bytesRead = await CopyToAsyncInternal(source, target, buffer, cancellationToken).ConfigureAwait(false);
+
+                    if (bytesRead == 0)
+                    {
+                        await Task.Delay(100).ConfigureAwait(false);
+                    }
                 }
                 }
             }
             }
+            finally
+            {
+                ArrayPool<byte>.Shared.Return(buffer);
+            }
         }
         }
 
 
         private static async Task<int> CopyToAsyncInternal(Stream source, Stream destination, byte[] buffer, CancellationToken cancellationToken)
         private static async Task<int> CopyToAsyncInternal(Stream source, Stream destination, byte[] buffer, CancellationToken cancellationToken)

+ 0 - 5
Emby.Server.Implementations/IStartupOptions.cs

@@ -7,11 +7,6 @@ namespace Emby.Server.Implementations
         /// </summary>
         /// </summary>
         string FFmpegPath { get; }
         string FFmpegPath { get; }
 
 
-        /// <summary>
-        /// --ffprobe
-        /// </summary>
-        string FFprobePath { get; }
-
         /// <summary>
         /// <summary>
         /// --service
         /// --service
         /// </summary>
         /// </summary>

+ 22 - 36
Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs

@@ -20,6 +20,9 @@ namespace Emby.Server.Implementations.Images
     public abstract class BaseDynamicImageProvider<T> : IHasItemChangeMonitor, IForcedProvider, ICustomMetadataProvider<T>, IHasOrder
     public abstract class BaseDynamicImageProvider<T> : IHasItemChangeMonitor, IForcedProvider, ICustomMetadataProvider<T>, IHasOrder
         where T : BaseItem
         where T : BaseItem
     {
     {
+        protected virtual IReadOnlyCollection<ImageType> SupportedImages { get; }
+            = new ImageType[] { ImageType.Primary };
+
         protected IFileSystem FileSystem { get; private set; }
         protected IFileSystem FileSystem { get; private set; }
         protected IProviderManager ProviderManager { get; private set; }
         protected IProviderManager ProviderManager { get; private set; }
         protected IApplicationPaths ApplicationPaths { get; private set; }
         protected IApplicationPaths ApplicationPaths { get; private set; }
@@ -33,18 +36,7 @@ namespace Emby.Server.Implementations.Images
             ImageProcessor = imageProcessor;
             ImageProcessor = imageProcessor;
         }
         }
 
 
-        protected virtual bool Supports(BaseItem item)
-        {
-            return true;
-        }
-
-        public virtual ImageType[] GetSupportedImages(BaseItem item)
-        {
-            return new ImageType[]
-            {
-                ImageType.Primary
-            };
-        }
+        protected virtual bool Supports(BaseItem _) => true;
 
 
         public async Task<ItemUpdateType> FetchAsync(T item, MetadataRefreshOptions options, CancellationToken cancellationToken)
         public async Task<ItemUpdateType> FetchAsync(T item, MetadataRefreshOptions options, CancellationToken cancellationToken)
         {
         {
@@ -54,15 +46,14 @@ namespace Emby.Server.Implementations.Images
             }
             }
 
 
             var updateType = ItemUpdateType.None;
             var updateType = ItemUpdateType.None;
-            var supportedImages = GetSupportedImages(item);
 
 
-            if (supportedImages.Contains(ImageType.Primary))
+            if (SupportedImages.Contains(ImageType.Primary))
             {
             {
                 var primaryResult = await FetchAsync(item, ImageType.Primary, options, cancellationToken).ConfigureAwait(false);
                 var primaryResult = await FetchAsync(item, ImageType.Primary, options, cancellationToken).ConfigureAwait(false);
                 updateType = updateType | primaryResult;
                 updateType = updateType | primaryResult;
             }
             }
 
 
-            if (supportedImages.Contains(ImageType.Thumb))
+            if (SupportedImages.Contains(ImageType.Thumb))
             {
             {
                 var thumbResult = await FetchAsync(item, ImageType.Thumb, options, cancellationToken).ConfigureAwait(false);
                 var thumbResult = await FetchAsync(item, ImageType.Thumb, options, cancellationToken).ConfigureAwait(false);
                 updateType = updateType | thumbResult;
                 updateType = updateType | thumbResult;
@@ -94,7 +85,7 @@ namespace Emby.Server.Implementations.Images
         }
         }
 
 
         protected async Task<ItemUpdateType> FetchToFileInternal(BaseItem item,
         protected async Task<ItemUpdateType> FetchToFileInternal(BaseItem item,
-            List<BaseItem> itemsWithImages,
+            IReadOnlyList<BaseItem> itemsWithImages,
             ImageType imageType,
             ImageType imageType,
             CancellationToken cancellationToken)
             CancellationToken cancellationToken)
         {
         {
@@ -119,9 +110,9 @@ namespace Emby.Server.Implementations.Images
             return ItemUpdateType.ImageUpdate;
             return ItemUpdateType.ImageUpdate;
         }
         }
 
 
-        protected abstract List<BaseItem> GetItemsWithImages(BaseItem item);
+        protected abstract IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item);
 
 
-        protected string CreateThumbCollage(BaseItem primaryItem, List<BaseItem> items, string outputPath)
+        protected string CreateThumbCollage(BaseItem primaryItem, IEnumerable<BaseItem> items, string outputPath)
         {
         {
             return CreateCollage(primaryItem, items, outputPath, 640, 360);
             return CreateCollage(primaryItem, items, outputPath, 640, 360);
         }
         }
@@ -132,38 +123,38 @@ namespace Emby.Server.Implementations.Images
                 .Select(i =>
                 .Select(i =>
                 {
                 {
                     var image = i.GetImageInfo(ImageType.Primary, 0);
                     var image = i.GetImageInfo(ImageType.Primary, 0);
-
                     if (image != null && image.IsLocalFile)
                     if (image != null && image.IsLocalFile)
                     {
                     {
                         return image.Path;
                         return image.Path;
                     }
                     }
-                    image = i.GetImageInfo(ImageType.Thumb, 0);
 
 
+                    image = i.GetImageInfo(ImageType.Thumb, 0);
                     if (image != null && image.IsLocalFile)
                     if (image != null && image.IsLocalFile)
                     {
                     {
                         return image.Path;
                         return image.Path;
                     }
                     }
+
                     return null;
                     return null;
                 })
                 })
                 .Where(i => !string.IsNullOrEmpty(i));
                 .Where(i => !string.IsNullOrEmpty(i));
         }
         }
 
 
-        protected string CreatePosterCollage(BaseItem primaryItem, List<BaseItem> items, string outputPath)
+        protected string CreatePosterCollage(BaseItem primaryItem, IEnumerable<BaseItem> items, string outputPath)
         {
         {
             return CreateCollage(primaryItem, items, outputPath, 400, 600);
             return CreateCollage(primaryItem, items, outputPath, 400, 600);
         }
         }
 
 
-        protected string CreateSquareCollage(BaseItem primaryItem, List<BaseItem> items, string outputPath)
+        protected string CreateSquareCollage(BaseItem primaryItem, IEnumerable<BaseItem> items, string outputPath)
         {
         {
             return CreateCollage(primaryItem, items, outputPath, 600, 600);
             return CreateCollage(primaryItem, items, outputPath, 600, 600);
         }
         }
 
 
-        protected string CreateThumbCollage(BaseItem primaryItem, List<BaseItem> items, string outputPath, int width, int height)
+        protected string CreateThumbCollage(BaseItem primaryItem, IEnumerable<BaseItem> items, string outputPath, int width, int height)
         {
         {
             return CreateCollage(primaryItem, items, outputPath, width, height);
             return CreateCollage(primaryItem, items, outputPath, width, height);
         }
         }
 
 
-        private string CreateCollage(BaseItem primaryItem, List<BaseItem> items, string outputPath, int width, int height)
+        private string CreateCollage(BaseItem primaryItem, IEnumerable<BaseItem> items, string outputPath, int width, int height)
         {
         {
             Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
             Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
 
 
@@ -192,7 +183,7 @@ namespace Emby.Server.Implementations.Images
         public string Name => "Dynamic Image Provider";
         public string Name => "Dynamic Image Provider";
 
 
         protected virtual string CreateImage(BaseItem item,
         protected virtual string CreateImage(BaseItem item,
-            List<BaseItem> itemsWithImages,
+            IReadOnlyCollection<BaseItem> itemsWithImages,
             string outputPathWithoutExtension,
             string outputPathWithoutExtension,
             ImageType imageType,
             ImageType imageType,
             int imageIndex)
             int imageIndex)
@@ -211,18 +202,15 @@ namespace Emby.Server.Implementations.Images
 
 
             if (imageType == ImageType.Primary)
             if (imageType == ImageType.Primary)
             {
             {
-                if (item is UserView)
-                {
-                    return CreateSquareCollage(item, itemsWithImages, outputPath);
-                }
-                if (item is Playlist || item is MusicGenre || item is Genre || item is PhotoAlbum)
+                if (item is UserView || item is Playlist || item is MusicGenre || item is Genre || item is PhotoAlbum)
                 {
                 {
                     return CreateSquareCollage(item, itemsWithImages, outputPath);
                     return CreateSquareCollage(item, itemsWithImages, outputPath);
                 }
                 }
+
                 return CreatePosterCollage(item, itemsWithImages, outputPath);
                 return CreatePosterCollage(item, itemsWithImages, outputPath);
             }
             }
 
 
-            throw new ArgumentException("Unexpected image type");
+            throw new ArgumentException("Unexpected image type", nameof(imageType));
         }
         }
 
 
         protected virtual int MaxImageAgeDays => 7;
         protected virtual int MaxImageAgeDays => 7;
@@ -234,13 +222,11 @@ namespace Emby.Server.Implementations.Images
                 return false;
                 return false;
             }
             }
 
 
-            var supportedImages = GetSupportedImages(item);
-
-            if (supportedImages.Contains(ImageType.Primary) && HasChanged(item, ImageType.Primary))
+            if (SupportedImages.Contains(ImageType.Primary) && HasChanged(item, ImageType.Primary))
             {
             {
                 return true;
                 return true;
             }
             }
-            if (supportedImages.Contains(ImageType.Thumb) && HasChanged(item, ImageType.Thumb))
+            if (SupportedImages.Contains(ImageType.Thumb) && HasChanged(item, ImageType.Thumb))
             {
             {
                 return true;
                 return true;
             }
             }
@@ -285,7 +271,7 @@ namespace Emby.Server.Implementations.Images
 
 
         public int Order => 0;
         public int Order => 0;
 
 
-        protected string CreateSingleImage(List<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType)
+        protected string CreateSingleImage(IEnumerable<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType)
         {
         {
             var image = itemsWithImages
             var image = itemsWithImages
                 .Where(i => i.HasImage(imageType) && i.GetImageInfo(imageType, 0).IsLocalFile && Path.HasExtension(i.GetImagePath(imageType)))
                 .Where(i => i.HasImage(imageType) && i.GetImageInfo(imageType, 0).IsLocalFile && Path.HasExtension(i.GetImagePath(imageType)))

+ 120 - 21
Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs

@@ -1,4 +1,5 @@
 using System;
 using System;
+using System.Linq;
 using System.Text;
 using System.Text;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
 using MediaBrowser.Controller.Authentication;
 using MediaBrowser.Controller.Authentication;
@@ -18,20 +19,64 @@ namespace Emby.Server.Implementations.Library
         public string Name => "Default";
         public string Name => "Default";
 
 
         public bool IsEnabled => true;
         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
         public Task<ProviderAuthenticationResult> Authenticate(string username, string password)
         public Task<ProviderAuthenticationResult> Authenticate(string username, string password)
         {
         {
             throw new NotImplementedException();
             throw new NotImplementedException();
         }
         }
-
+        
+        // This is the verson that we need to use for local users. Because reasons.
         public Task<ProviderAuthenticationResult> Authenticate(string username, string password, User resolvedUser)
         public Task<ProviderAuthenticationResult> Authenticate(string username, string password, User resolvedUser)
         {
         {
+            bool success = false;
             if (resolvedUser == null)
             if (resolvedUser == null)
             {
             {
                 throw new Exception("Invalid username or password");
                 throw new Exception("Invalid username or password");
             }
             }
 
 
-            var success = string.Equals(GetPasswordHash(resolvedUser), GetHashedString(resolvedUser, password), StringComparison.OrdinalIgnoreCase);
+            // As long as jellyfin supports passwordless users, we need this little block here to accomodate
+            if (IsPasswordEmpty(resolvedUser, password))
+            {
+                return Task.FromResult(new ProviderAuthenticationResult
+                {
+                    Username = username
+                });
+            }
+
+            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)
+            {
+                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);
+                }
+
+                if (calculatedHashString == 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}"));
+            }
+
+            // var success = string.Equals(GetPasswordHash(resolvedUser), GetHashedString(resolvedUser, password), StringComparison.OrdinalIgnoreCase);
 
 
             if (!success)
             if (!success)
             {
             {
@@ -44,46 +89,86 @@ 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<bool> HasPassword(User user)
         public Task<bool> HasPassword(User user)
         {
         {
             var hasConfiguredPassword = !IsPasswordEmpty(user, GetPasswordHash(user));
             var hasConfiguredPassword = !IsPasswordEmpty(user, GetPasswordHash(user));
             return Task.FromResult(hasConfiguredPassword);
             return Task.FromResult(hasConfiguredPassword);
         }
         }
 
 
-        private bool IsPasswordEmpty(User user, string passwordHash)
+        private bool IsPasswordEmpty(User user, string password)
         {
         {
-            return string.Equals(passwordHash, GetEmptyHashedString(user), StringComparison.OrdinalIgnoreCase);
+            return (string.IsNullOrEmpty(user.Password) && string.IsNullOrEmpty(password));
         }
         }
 
 
         public Task ChangePassword(User user, string newPassword)
         public Task ChangePassword(User user, string newPassword)
         {
         {
-            string newPasswordHash = null;
+            ConvertPasswordFormat(user);
+            // This is needed to support changing a no password user to a password user
+            if (string.IsNullOrEmpty(user.Password))
+            {
+                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();
+                return Task.CompletedTask;
+            }
 
 
-            if (newPassword != null)
+            PasswordHash passwordHash = new PasswordHash(user.Password);
+            if (passwordHash.Id == "SHA1" && string.IsNullOrEmpty(passwordHash.Salt))
             {
             {
-                newPasswordHash = GetHashedString(user, newPassword);
+                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(newPasswordHash))
+            if (string.IsNullOrWhiteSpace(passwordHash.Hash))
             {
             {
-                throw new ArgumentNullException(nameof(newPasswordHash));
+                throw new ArgumentNullException(nameof(passwordHash.Hash));
             }
             }
 
 
-            user.Password = newPasswordHash;
+            user.Password = passwordHash.ToString();
 
 
             return Task.CompletedTask;
             return Task.CompletedTask;
         }
         }
 
 
         public string GetPasswordHash(User user)
         public string GetPasswordHash(User user)
         {
         {
-            return string.IsNullOrEmpty(user.Password)
-                ? GetEmptyHashedString(user)
-                : user.Password;
+            return user.Password;
         }
         }
 
 
-        public string GetEmptyHashedString(User user)
+        public string GetHashedStringChangeAuth(string newPassword, PasswordHash passwordHash)
         {
         {
-            return GetHashedString(user, string.Empty);
+            passwordHash.HashBytes = Encoding.UTF8.GetBytes(newPassword);
+            return PasswordHash.ConvertToByteString(_cryptographyProvider.ComputeHash(passwordHash));
         }
         }
 
 
         /// <summary>
         /// <summary>
@@ -91,14 +176,28 @@ namespace Emby.Server.Implementations.Library
         /// </summary>
         /// </summary>
         public string GetHashedString(User user, string str)
         public string GetHashedString(User user, string str)
         {
         {
-            var salt = user.Salt;
-            if (salt != null)
+            PasswordHash passwordHash;
+            if (string.IsNullOrEmpty(user.Password))
+            {
+                passwordHash = new PasswordHash(_cryptographyProvider);
+            }
+            else
             {
             {
-                // return BCrypt.HashPassword(str, salt);
+                ConvertPasswordFormat(user);
+                passwordHash = new PasswordHash(user.Password);
             }
             }
 
 
-            // legacy
-            return BitConverter.ToString(_cryptographyProvider.ComputeSHA1(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty);
+            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
+            {
+                // 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)));
+            }
         }
         }
     }
     }
 }
 }

+ 174 - 172
Emby.Server.Implementations/Library/LibraryManager.cs

@@ -58,22 +58,23 @@ namespace Emby.Server.Implementations.Library
         private ILibraryPostScanTask[] PostscanTasks { get; set; }
         private ILibraryPostScanTask[] PostscanTasks { get; set; }
 
 
         /// <summary>
         /// <summary>
-        /// Gets the intro providers.
+        /// Gets or sets the intro providers.
         /// </summary>
         /// </summary>
         /// <value>The intro providers.</value>
         /// <value>The intro providers.</value>
         private IIntroProvider[] IntroProviders { get; set; }
         private IIntroProvider[] IntroProviders { get; set; }
 
 
         /// <summary>
         /// <summary>
-        /// Gets the list of entity resolution ignore rules
+        /// Gets or sets the list of entity resolution ignore rules
         /// </summary>
         /// </summary>
         /// <value>The entity resolution ignore rules.</value>
         /// <value>The entity resolution ignore rules.</value>
         private IResolverIgnoreRule[] EntityResolutionIgnoreRules { get; set; }
         private IResolverIgnoreRule[] EntityResolutionIgnoreRules { get; set; }
 
 
         /// <summary>
         /// <summary>
-        /// Gets the list of currently registered entity resolvers
+        /// Gets or sets the list of currently registered entity resolvers
         /// </summary>
         /// </summary>
         /// <value>The entity resolvers enumerable.</value>
         /// <value>The entity resolvers enumerable.</value>
         private IItemResolver[] EntityResolvers { get; set; }
         private IItemResolver[] EntityResolvers { get; set; }
+
         private IMultiItemResolver[] MultiItemResolvers { get; set; }
         private IMultiItemResolver[] MultiItemResolvers { get; set; }
 
 
         /// <summary>
         /// <summary>
@@ -83,7 +84,7 @@ namespace Emby.Server.Implementations.Library
         private IBaseItemComparer[] Comparers { get; set; }
         private IBaseItemComparer[] Comparers { get; set; }
 
 
         /// <summary>
         /// <summary>
-        /// Gets the active item repository
+        /// Gets or sets the active item repository
         /// </summary>
         /// </summary>
         /// <value>The item repository.</value>
         /// <value>The item repository.</value>
         public IItemRepository ItemRepository { get; set; }
         public IItemRepository ItemRepository { get; set; }
@@ -133,12 +134,14 @@ namespace Emby.Server.Implementations.Library
         private readonly Func<IProviderManager> _providerManagerFactory;
         private readonly Func<IProviderManager> _providerManagerFactory;
         private readonly Func<IUserViewManager> _userviewManager;
         private readonly Func<IUserViewManager> _userviewManager;
         public bool IsScanRunning { get; private set; }
         public bool IsScanRunning { get; private set; }
+
         private IServerApplicationHost _appHost;
         private IServerApplicationHost _appHost;
 
 
         /// <summary>
         /// <summary>
         /// The _library items cache
         /// The _library items cache
         /// </summary>
         /// </summary>
         private readonly ConcurrentDictionary<Guid, BaseItem> _libraryItemsCache;
         private readonly ConcurrentDictionary<Guid, BaseItem> _libraryItemsCache;
+
         /// <summary>
         /// <summary>
         /// Gets the library items cache.
         /// Gets the library items cache.
         /// </summary>
         /// </summary>
@@ -150,7 +153,8 @@ namespace Emby.Server.Implementations.Library
         /// <summary>
         /// <summary>
         /// Initializes a new instance of the <see cref="LibraryManager" /> class.
         /// Initializes a new instance of the <see cref="LibraryManager" /> class.
         /// </summary>
         /// </summary>
-        /// <param name="logger">The logger.</param>
+        /// <param name="appHost">The application host</param>
+        /// <param name="loggerFactory">The logger factory.</param>
         /// <param name="taskManager">The task manager.</param>
         /// <param name="taskManager">The task manager.</param>
         /// <param name="userManager">The user manager.</param>
         /// <param name="userManager">The user manager.</param>
         /// <param name="configurationManager">The configuration manager.</param>
         /// <param name="configurationManager">The configuration manager.</param>
@@ -167,6 +171,7 @@ namespace Emby.Server.Implementations.Library
             Func<IProviderManager> providerManagerFactory,
             Func<IProviderManager> providerManagerFactory,
             Func<IUserViewManager> userviewManager)
             Func<IUserViewManager> userviewManager)
         {
         {
+            _appHost = appHost;
             _logger = loggerFactory.CreateLogger(nameof(LibraryManager));
             _logger = loggerFactory.CreateLogger(nameof(LibraryManager));
             _taskManager = taskManager;
             _taskManager = taskManager;
             _userManager = userManager;
             _userManager = userManager;
@@ -176,7 +181,7 @@ namespace Emby.Server.Implementations.Library
             _fileSystem = fileSystem;
             _fileSystem = fileSystem;
             _providerManagerFactory = providerManagerFactory;
             _providerManagerFactory = providerManagerFactory;
             _userviewManager = userviewManager;
             _userviewManager = userviewManager;
-            _appHost = appHost;
+
             _libraryItemsCache = new ConcurrentDictionary<Guid, BaseItem>();
             _libraryItemsCache = new ConcurrentDictionary<Guid, BaseItem>();
 
 
             ConfigurationManager.ConfigurationUpdated += ConfigurationUpdated;
             ConfigurationManager.ConfigurationUpdated += ConfigurationUpdated;
@@ -191,8 +196,9 @@ namespace Emby.Server.Implementations.Library
         /// <param name="resolvers">The resolvers.</param>
         /// <param name="resolvers">The resolvers.</param>
         /// <param name="introProviders">The intro providers.</param>
         /// <param name="introProviders">The intro providers.</param>
         /// <param name="itemComparers">The item comparers.</param>
         /// <param name="itemComparers">The item comparers.</param>
-        /// <param name="postscanTasks">The postscan tasks.</param>
-        public void AddParts(IEnumerable<IResolverIgnoreRule> rules,
+        /// <param name="postscanTasks">The post scan tasks.</param>
+        public void AddParts(
+            IEnumerable<IResolverIgnoreRule> rules,
             IEnumerable<IItemResolver> resolvers,
             IEnumerable<IItemResolver> resolvers,
             IEnumerable<IIntroProvider> introProviders,
             IEnumerable<IIntroProvider> introProviders,
             IEnumerable<IBaseItemComparer> itemComparers,
             IEnumerable<IBaseItemComparer> itemComparers,
@@ -203,24 +209,19 @@ namespace Emby.Server.Implementations.Library
             MultiItemResolvers = EntityResolvers.OfType<IMultiItemResolver>().ToArray();
             MultiItemResolvers = EntityResolvers.OfType<IMultiItemResolver>().ToArray();
             IntroProviders = introProviders.ToArray();
             IntroProviders = introProviders.ToArray();
             Comparers = itemComparers.ToArray();
             Comparers = itemComparers.ToArray();
-
-            PostscanTasks = postscanTasks.OrderBy(i =>
-            {
-                var hasOrder = i as IHasOrder;
-
-                return hasOrder == null ? 0 : hasOrder.Order;
-
-            }).ToArray();
+            PostscanTasks = postscanTasks.ToArray();
         }
         }
 
 
         /// <summary>
         /// <summary>
         /// The _root folder
         /// The _root folder
         /// </summary>
         /// </summary>
         private volatile AggregateFolder _rootFolder;
         private volatile AggregateFolder _rootFolder;
+
         /// <summary>
         /// <summary>
         /// The _root folder sync lock
         /// The _root folder sync lock
         /// </summary>
         /// </summary>
         private readonly object _rootFolderSyncLock = new object();
         private readonly object _rootFolderSyncLock = new object();
+
         /// <summary>
         /// <summary>
         /// Gets the root folder.
         /// Gets the root folder.
         /// </summary>
         /// </summary>
@@ -239,11 +240,13 @@ namespace Emby.Server.Implementations.Library
                         }
                         }
                     }
                     }
                 }
                 }
+
                 return _rootFolder;
                 return _rootFolder;
             }
             }
         }
         }
 
 
         private bool _wizardCompleted;
         private bool _wizardCompleted;
+
         /// <summary>
         /// <summary>
         /// Records the configuration values.
         /// Records the configuration values.
         /// </summary>
         /// </summary>
@@ -258,7 +261,7 @@ namespace Emby.Server.Implementations.Library
         /// </summary>
         /// </summary>
         /// <param name="sender">The sender.</param>
         /// <param name="sender">The sender.</param>
         /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
         /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
-        void ConfigurationUpdated(object sender, EventArgs e)
+        private void ConfigurationUpdated(object sender, EventArgs e)
         {
         {
             var config = ConfigurationManager.Configuration;
             var config = ConfigurationManager.Configuration;
 
 
@@ -278,6 +281,7 @@ namespace Emby.Server.Implementations.Library
             {
             {
                 throw new ArgumentNullException(nameof(item));
                 throw new ArgumentNullException(nameof(item));
             }
             }
+
             if (item is IItemByName)
             if (item is IItemByName)
             {
             {
                 if (!(item is MusicArtist))
                 if (!(item is MusicArtist))
@@ -285,18 +289,7 @@ namespace Emby.Server.Implementations.Library
                     return;
                     return;
                 }
                 }
             }
             }
-
-            else if (item.IsFolder)
-            {
-                //if (!(item is ICollectionFolder) && !(item is UserView) && !(item is Channel) && !(item is AggregateFolder))
-                //{
-                //    if (item.SourceType != SourceType.Library)
-                //    {
-                //        return;
-                //    }
-                //}
-            }
-            else
+            else if (!item.IsFolder)
             {
             {
                 if (!(item is Video) && !(item is LiveTvChannel))
                 if (!(item is Video) && !(item is LiveTvChannel))
                 {
                 {
@@ -345,12 +338,14 @@ namespace Emby.Server.Implementations.Library
                         // channel no longer installed
                         // channel no longer installed
                     }
                     }
                 }
                 }
+
                 options.DeleteFileLocation = false;
                 options.DeleteFileLocation = false;
             }
             }
 
 
             if (item is LiveTvProgram)
             if (item is LiveTvProgram)
             {
             {
-                _logger.LogDebug("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
+                _logger.LogDebug(
+                    "Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
                     item.GetType().Name,
                     item.GetType().Name,
                     item.Name ?? "Unknown name",
                     item.Name ?? "Unknown name",
                     item.Path ?? string.Empty,
                     item.Path ?? string.Empty,
@@ -358,7 +353,8 @@ namespace Emby.Server.Implementations.Library
             }
             }
             else
             else
             {
             {
-                _logger.LogInformation("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
+                _logger.LogInformation(
+                    "Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
                     item.GetType().Name,
                     item.GetType().Name,
                     item.Name ?? "Unknown name",
                     item.Name ?? "Unknown name",
                     item.Path ?? string.Empty,
                     item.Path ?? string.Empty,
@@ -371,19 +367,20 @@ namespace Emby.Server.Implementations.Library
 
 
             foreach (var metadataPath in GetMetadataPaths(item, children))
             foreach (var metadataPath in GetMetadataPaths(item, children))
             {
             {
-                _logger.LogDebug("Deleting path {0}", metadataPath);
+                if (!Directory.Exists(metadataPath))
+                {
+                    continue;
+                }
+
+                _logger.LogDebug("Deleting path {MetadataPath}", metadataPath);
 
 
                 try
                 try
                 {
                 {
                     Directory.Delete(metadataPath, true);
                     Directory.Delete(metadataPath, true);
-                }
-                catch (IOException)
-                {
-
                 }
                 }
                 catch (Exception ex)
                 catch (Exception ex)
                 {
                 {
-                    _logger.LogError(ex, "Error deleting {metadataPath}", metadataPath);
+                    _logger.LogError(ex, "Error deleting {MetadataPath}", metadataPath);
                 }
                 }
             }
             }
 
 
@@ -497,12 +494,13 @@ namespace Emby.Server.Implementations.Library
             {
             {
                 throw new ArgumentNullException(nameof(key));
                 throw new ArgumentNullException(nameof(key));
             }
             }
+
             if (type == null)
             if (type == null)
             {
             {
                 throw new ArgumentNullException(nameof(type));
                 throw new ArgumentNullException(nameof(type));
             }
             }
 
 
-            if (key.StartsWith(ConfigurationManager.ApplicationPaths.ProgramDataPath))
+            if (key.StartsWith(ConfigurationManager.ApplicationPaths.ProgramDataPath, StringComparison.Ordinal))
             {
             {
                 // Try to normalize paths located underneath program-data in an attempt to make them more portable
                 // Try to normalize paths located underneath program-data in an attempt to make them more portable
                 key = key.Substring(ConfigurationManager.ApplicationPaths.ProgramDataPath.Length)
                 key = key.Substring(ConfigurationManager.ApplicationPaths.ProgramDataPath.Length)
@@ -520,13 +518,11 @@ namespace Emby.Server.Implementations.Library
             return key.GetMD5();
             return key.GetMD5();
         }
         }
 
 
-        public BaseItem ResolvePath(FileSystemMetadata fileInfo,
-            Folder parent = null)
-        {
-            return ResolvePath(fileInfo, new DirectoryService(_logger, _fileSystem), null, parent);
-        }
+        public BaseItem ResolvePath(FileSystemMetadata fileInfo, Folder parent = null)
+            => ResolvePath(fileInfo, new DirectoryService(_logger, _fileSystem), null, parent);
 
 
-        private BaseItem ResolvePath(FileSystemMetadata fileInfo,
+        private BaseItem ResolvePath(
+            FileSystemMetadata fileInfo,
             IDirectoryService directoryService,
             IDirectoryService directoryService,
             IItemResolver[] resolvers,
             IItemResolver[] resolvers,
             Folder parent = null,
             Folder parent = null,
@@ -581,7 +577,7 @@ namespace Emby.Server.Implementations.Library
                     {
                     {
                         _logger.LogError(ex, "Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", isPhysicalRoot, isVf);
                         _logger.LogError(ex, "Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", isPhysicalRoot, isVf);
 
 
-                        files = new FileSystemMetadata[] { };
+                        files = Array.Empty<FileSystemMetadata>();
                     }
                     }
                     else
                     else
                     {
                     {
@@ -609,13 +605,7 @@ namespace Emby.Server.Implementations.Library
         }
         }
 
 
         public bool IgnoreFile(FileSystemMetadata file, BaseItem parent)
         public bool IgnoreFile(FileSystemMetadata file, BaseItem parent)
-        {
-            if (EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(file, parent)))
-            {
-                return true;
-            }
-            return false;
-        }
+            => EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(file, parent));
 
 
         public List<FileSystemMetadata> NormalizeRootPathList(IEnumerable<FileSystemMetadata> paths)
         public List<FileSystemMetadata> NormalizeRootPathList(IEnumerable<FileSystemMetadata> paths)
         {
         {
@@ -655,7 +645,8 @@ namespace Emby.Server.Implementations.Library
             return ResolvePaths(files, directoryService, parent, libraryOptions, collectionType, EntityResolvers);
             return ResolvePaths(files, directoryService, parent, libraryOptions, collectionType, EntityResolvers);
         }
         }
 
 
-        public IEnumerable<BaseItem> ResolvePaths(IEnumerable<FileSystemMetadata> files,
+        public IEnumerable<BaseItem> ResolvePaths(
+            IEnumerable<FileSystemMetadata> files,
             IDirectoryService directoryService,
             IDirectoryService directoryService,
             Folder parent,
             Folder parent,
             LibraryOptions libraryOptions,
             LibraryOptions libraryOptions,
@@ -681,6 +672,7 @@ namespace Emby.Server.Implementations.Library
                         {
                         {
                             ResolverHelper.SetInitialItemValues(item, parent, _fileSystem, this, directoryService);
                             ResolverHelper.SetInitialItemValues(item, parent, _fileSystem, this, directoryService);
                         }
                         }
+
                         items.AddRange(ResolveFileList(result.ExtraFiles, directoryService, parent, collectionType, resolvers, libraryOptions));
                         items.AddRange(ResolveFileList(result.ExtraFiles, directoryService, parent, collectionType, resolvers, libraryOptions));
                         return items;
                         return items;
                     }
                     }
@@ -690,7 +682,8 @@ namespace Emby.Server.Implementations.Library
             return ResolveFileList(fileList, directoryService, parent, collectionType, resolvers, libraryOptions);
             return ResolveFileList(fileList, directoryService, parent, collectionType, resolvers, libraryOptions);
         }
         }
 
 
-        private IEnumerable<BaseItem> ResolveFileList(IEnumerable<FileSystemMetadata> fileList,
+        private IEnumerable<BaseItem> ResolveFileList(
+            IEnumerable<FileSystemMetadata> fileList,
             IDirectoryService directoryService,
             IDirectoryService directoryService,
             Folder parent,
             Folder parent,
             string collectionType,
             string collectionType,
@@ -775,6 +768,7 @@ namespace Emby.Server.Implementations.Library
 
 
         private volatile UserRootFolder _userRootFolder;
         private volatile UserRootFolder _userRootFolder;
         private readonly object _syncLock = new object();
         private readonly object _syncLock = new object();
+
         public Folder GetUserRootFolder()
         public Folder GetUserRootFolder()
         {
         {
             if (_userRootFolder == null)
             if (_userRootFolder == null)
@@ -819,8 +813,6 @@ namespace Emby.Server.Implementations.Library
                 throw new ArgumentNullException(nameof(path));
                 throw new ArgumentNullException(nameof(path));
             }
             }
 
 
-            //_logger.LogInformation("FindByPath {0}", path);
-
             var query = new InternalItemsQuery
             var query = new InternalItemsQuery
             {
             {
                 Path = path,
                 Path = path,
@@ -894,7 +886,6 @@ namespace Emby.Server.Implementations.Library
         /// </summary>
         /// </summary>
         /// <param name="value">The value.</param>
         /// <param name="value">The value.</param>
         /// <returns>Task{Year}.</returns>
         /// <returns>Task{Year}.</returns>
-        /// <exception cref="ArgumentOutOfRangeException"></exception>
         public Year GetYear(int value)
         public Year GetYear(int value)
         {
         {
             if (value <= 0)
             if (value <= 0)
@@ -1036,20 +1027,25 @@ namespace Emby.Server.Implementations.Library
 
 
         private async Task ValidateTopLibraryFolders(CancellationToken cancellationToken)
         private async Task ValidateTopLibraryFolders(CancellationToken cancellationToken)
         {
         {
-            var rootChildren = RootFolder.Children.ToList();
-            rootChildren = GetUserRootFolder().Children.ToList();
-
             await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
             await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
 
 
             // Start by just validating the children of the root, but go no further
             // Start by just validating the children of the root, but go no further
-            await RootFolder.ValidateChildren(new SimpleProgress<double>(), cancellationToken, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), recursive: false);
+            await RootFolder.ValidateChildren(
+                new SimpleProgress<double>(),
+                cancellationToken,
+                new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)),
+                recursive: false).ConfigureAwait(false);
 
 
             await GetUserRootFolder().RefreshMetadata(cancellationToken).ConfigureAwait(false);
             await GetUserRootFolder().RefreshMetadata(cancellationToken).ConfigureAwait(false);
 
 
-            await GetUserRootFolder().ValidateChildren(new SimpleProgress<double>(), cancellationToken, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), recursive: false).ConfigureAwait(false);
+            await GetUserRootFolder().ValidateChildren(
+                new SimpleProgress<double>(),
+                cancellationToken,
+                new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)),
+                recursive: false).ConfigureAwait(false);
 
 
             // Quickly scan CollectionFolders for changes
             // Quickly scan CollectionFolders for changes
-            foreach (var folder in GetUserRootFolder().Children.OfType<Folder>().ToList())
+            foreach (var folder in GetUserRootFolder().Children.OfType<Folder>())
             {
             {
                 await folder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
                 await folder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
             }
             }
@@ -1213,7 +1209,7 @@ namespace Emby.Server.Implementations.Library
         private string GetCollectionType(string path)
         private string GetCollectionType(string path)
         {
         {
             return _fileSystem.GetFilePaths(path, new[] { ".collection" }, true, false)
             return _fileSystem.GetFilePaths(path, new[] { ".collection" }, true, false)
-                .Select(i => Path.GetFileNameWithoutExtension(i))
+                .Select(Path.GetFileNameWithoutExtension)
                 .FirstOrDefault(i => !string.IsNullOrEmpty(i));
                 .FirstOrDefault(i => !string.IsNullOrEmpty(i));
         }
         }
 
 
@@ -1227,7 +1223,7 @@ namespace Emby.Server.Implementations.Library
         {
         {
             if (id == Guid.Empty)
             if (id == Guid.Empty)
             {
             {
-                throw new ArgumentException(nameof(id), "Guid can't be empty");
+                throw new ArgumentException("Guid can't be empty", nameof(id));
             }
             }
 
 
             if (LibraryItemsCache.TryGetValue(id, out BaseItem item))
             if (LibraryItemsCache.TryGetValue(id, out BaseItem item))
@@ -1395,17 +1391,7 @@ namespace Emby.Server.Implementations.Library
 
 
             var parents = query.AncestorIds.Select(i => GetItemById(i)).ToList();
             var parents = query.AncestorIds.Select(i => GetItemById(i)).ToList();
 
 
-            if (parents.All(i =>
-            {
-                if (i is ICollectionFolder || i is UserView)
-                {
-                    return true;
-                }
-
-                //_logger.LogDebug("Query requires ancestor query due to type: " + i.GetType().Name);
-                return false;
-
-            }))
+            if (parents.All(i => i is ICollectionFolder || i is UserView))
             {
             {
                 // Optimize by querying against top level views
                 // Optimize by querying against top level views
                 query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
                 query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
@@ -1461,17 +1447,7 @@ namespace Emby.Server.Implementations.Library
 
 
         private void SetTopParentIdsOrAncestors(InternalItemsQuery query, List<BaseItem> parents)
         private void SetTopParentIdsOrAncestors(InternalItemsQuery query, List<BaseItem> parents)
         {
         {
-            if (parents.All(i =>
-            {
-                if (i is ICollectionFolder || i is UserView)
-                {
-                    return true;
-                }
-
-                //_logger.LogDebug("Query requires ancestor query due to type: " + i.GetType().Name);
-                return false;
-
-            }))
+            if (parents.All(i => i is ICollectionFolder || i is UserView))
             {
             {
                 // Optimize by querying against top level views
                 // Optimize by querying against top level views
                 query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
                 query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
@@ -1520,11 +1496,9 @@ namespace Emby.Server.Implementations.Library
 
 
         private IEnumerable<Guid> GetTopParentIdsForQuery(BaseItem item, User user)
         private IEnumerable<Guid> GetTopParentIdsForQuery(BaseItem item, User user)
         {
         {
-            var view = item as UserView;
-
-            if (view != null)
+            if (item is UserView view)
             {
             {
-                if (string.Equals(view.ViewType, CollectionType.LiveTv))
+                if (string.Equals(view.ViewType, CollectionType.LiveTv, StringComparison.Ordinal))
                 {
                 {
                     return new[] { view.Id };
                     return new[] { view.Id };
                 }
                 }
@@ -1537,8 +1511,10 @@ namespace Emby.Server.Implementations.Library
                     {
                     {
                         return GetTopParentIdsForQuery(displayParent, user);
                         return GetTopParentIdsForQuery(displayParent, user);
                     }
                     }
+
                     return Array.Empty<Guid>();
                     return Array.Empty<Guid>();
                 }
                 }
+
                 if (!view.ParentId.Equals(Guid.Empty))
                 if (!view.ParentId.Equals(Guid.Empty))
                 {
                 {
                     var displayParent = GetItemById(view.ParentId);
                     var displayParent = GetItemById(view.ParentId);
@@ -1546,6 +1522,7 @@ namespace Emby.Server.Implementations.Library
                     {
                     {
                         return GetTopParentIdsForQuery(displayParent, user);
                         return GetTopParentIdsForQuery(displayParent, user);
                     }
                     }
+
                     return Array.Empty<Guid>();
                     return Array.Empty<Guid>();
                 }
                 }
 
 
@@ -1559,11 +1536,11 @@ namespace Emby.Server.Implementations.Library
                         .Where(i => user.IsFolderGrouped(i.Id))
                         .Where(i => user.IsFolderGrouped(i.Id))
                         .SelectMany(i => GetTopParentIdsForQuery(i, user));
                         .SelectMany(i => GetTopParentIdsForQuery(i, user));
                 }
                 }
+
                 return Array.Empty<Guid>();
                 return Array.Empty<Guid>();
             }
             }
 
 
-            var collectionFolder = item as CollectionFolder;
-            if (collectionFolder != null)
+            if (item is CollectionFolder collectionFolder)
             {
             {
                 return collectionFolder.PhysicalFolderIds;
                 return collectionFolder.PhysicalFolderIds;
             }
             }
@@ -1573,6 +1550,7 @@ namespace Emby.Server.Implementations.Library
             {
             {
                 return new[] { topParent.Id };
                 return new[] { topParent.Id };
             }
             }
+
             return Array.Empty<Guid>();
             return Array.Empty<Guid>();
         }
         }
 
 
@@ -1769,19 +1747,16 @@ namespace Emby.Server.Implementations.Library
         {
         {
             var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
             var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
 
 
-            if (comparer != null)
+            // If it requires a user, create a new one, and assign the user
+            if (comparer is IUserBaseItemComparer)
             {
             {
-                // If it requires a user, create a new one, and assign the user
-                if (comparer is IUserBaseItemComparer)
-                {
-                    var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
+                var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
 
 
-                    userComparer.User = user;
-                    userComparer.UserManager = _userManager;
-                    userComparer.UserDataRepository = _userDataRepository;
+                userComparer.User = user;
+                userComparer.UserManager = _userManager;
+                userComparer.UserDataRepository = _userDataRepository;
 
 
-                    return userComparer;
-                }
+                return userComparer;
             }
             }
 
 
             return comparer;
             return comparer;
@@ -1792,7 +1767,6 @@ namespace Emby.Server.Implementations.Library
         /// </summary>
         /// </summary>
         /// <param name="item">The item.</param>
         /// <param name="item">The item.</param>
         /// <param name="parent">The parent item.</param>
         /// <param name="parent">The parent item.</param>
-        /// <returns>Task.</returns>
         public void CreateItem(BaseItem item, BaseItem parent)
         public void CreateItem(BaseItem item, BaseItem parent)
         {
         {
             CreateItems(new[] { item }, parent, CancellationToken.None);
             CreateItems(new[] { item }, parent, CancellationToken.None);
@@ -1802,20 +1776,23 @@ namespace Emby.Server.Implementations.Library
         /// Creates the items.
         /// Creates the items.
         /// </summary>
         /// </summary>
         /// <param name="items">The items.</param>
         /// <param name="items">The items.</param>
+        /// <param name="parent">The parent item</param>
         /// <param name="cancellationToken">The cancellation token.</param>
         /// <param name="cancellationToken">The cancellation token.</param>
-        /// <returns>Task.</returns>
         public void CreateItems(IEnumerable<BaseItem> items, BaseItem parent, CancellationToken cancellationToken)
         public void CreateItems(IEnumerable<BaseItem> items, BaseItem parent, CancellationToken cancellationToken)
         {
         {
-            ItemRepository.SaveItems(items, cancellationToken);
+            // Don't iterate multiple times
+            var itemsList = items.ToList();
+
+            ItemRepository.SaveItems(itemsList, cancellationToken);
 
 
-            foreach (var item in items)
+            foreach (var item in itemsList)
             {
             {
                 RegisterItem(item);
                 RegisterItem(item);
             }
             }
 
 
             if (ItemAdded != null)
             if (ItemAdded != null)
             {
             {
-                foreach (var item in items)
+                foreach (var item in itemsList)
                 {
                 {
                     // With the live tv guide this just creates too much noise
                     // With the live tv guide this just creates too much noise
                     if (item.SourceType != SourceType.Library)
                     if (item.SourceType != SourceType.Library)
@@ -1825,11 +1802,13 @@ namespace Emby.Server.Implementations.Library
 
 
                     try
                     try
                     {
                     {
-                        ItemAdded(this, new ItemChangeEventArgs
-                        {
-                            Item = item,
-                            Parent = parent ?? item.GetParent()
-                        });
+                        ItemAdded(
+                            this,
+                            new ItemChangeEventArgs
+                            {
+                                Item = item,
+                                Parent = parent ?? item.GetParent()
+                            });
                     }
                     }
                     catch (Exception ex)
                     catch (Exception ex)
                     {
                     {
@@ -1851,7 +1830,10 @@ namespace Emby.Server.Implementations.Library
         /// </summary>
         /// </summary>
         public void UpdateItems(IEnumerable<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
         public void UpdateItems(IEnumerable<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
         {
         {
-            foreach (var item in items)
+            // Don't iterate multiple times
+            var itemsList = items.ToList();
+
+            foreach (var item in itemsList)
             {
             {
                 if (item.IsFileProtocol)
                 if (item.IsFileProtocol)
                 {
                 {
@@ -1863,14 +1845,11 @@ namespace Emby.Server.Implementations.Library
                 RegisterItem(item);
                 RegisterItem(item);
             }
             }
 
 
-            //var logName = item.LocationType == LocationType.Remote ? item.Name ?? item.Path : item.Path ?? item.Name;
-            //_logger.LogDebug("Saving {0} to database.", logName);
-
-            ItemRepository.SaveItems(items, cancellationToken);
+            ItemRepository.SaveItems(itemsList, cancellationToken);
 
 
             if (ItemUpdated != null)
             if (ItemUpdated != null)
             {
             {
-                foreach (var item in items)
+                foreach (var item in itemsList)
                 {
                 {
                     // With the live tv guide this just creates too much noise
                     // With the live tv guide this just creates too much noise
                     if (item.SourceType != SourceType.Library)
                     if (item.SourceType != SourceType.Library)
@@ -1880,12 +1859,14 @@ namespace Emby.Server.Implementations.Library
 
 
                     try
                     try
                     {
                     {
-                        ItemUpdated(this, new ItemChangeEventArgs
-                        {
-                            Item = item,
-                            Parent = parent,
-                            UpdateReason = updateReason
-                        });
+                        ItemUpdated(
+                            this,
+                            new ItemChangeEventArgs
+                            {
+                                Item = item,
+                                Parent = parent,
+                                UpdateReason = updateReason
+                            });
                     }
                     }
                     catch (Exception ex)
                     catch (Exception ex)
                     {
                     {
@@ -1899,9 +1880,9 @@ namespace Emby.Server.Implementations.Library
         /// Updates the item.
         /// Updates the item.
         /// </summary>
         /// </summary>
         /// <param name="item">The item.</param>
         /// <param name="item">The item.</param>
+        /// <param name="parent">The parent item.</param>
         /// <param name="updateReason">The update reason.</param>
         /// <param name="updateReason">The update reason.</param>
         /// <param name="cancellationToken">The cancellation token.</param>
         /// <param name="cancellationToken">The cancellation token.</param>
-        /// <returns>Task.</returns>
         public void UpdateItem(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
         public void UpdateItem(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
         {
         {
             UpdateItems(new [] { item }, parent, updateReason, cancellationToken);
             UpdateItems(new [] { item }, parent, updateReason, cancellationToken);
@@ -1911,17 +1892,20 @@ namespace Emby.Server.Implementations.Library
         /// Reports the item removed.
         /// Reports the item removed.
         /// </summary>
         /// </summary>
         /// <param name="item">The item.</param>
         /// <param name="item">The item.</param>
+        /// <param name="parent">The parent item.</param>
         public void ReportItemRemoved(BaseItem item, BaseItem parent)
         public void ReportItemRemoved(BaseItem item, BaseItem parent)
         {
         {
             if (ItemRemoved != null)
             if (ItemRemoved != null)
             {
             {
                 try
                 try
                 {
                 {
-                    ItemRemoved(this, new ItemChangeEventArgs
-                    {
-                        Item = item,
-                        Parent = parent
-                    });
+                    ItemRemoved(
+                        this,
+                        new ItemChangeEventArgs
+                        {
+                            Item = item,
+                            Parent = parent
+                        });
                 }
                 }
                 catch (Exception ex)
                 catch (Exception ex)
                 {
                 {
@@ -2047,8 +2031,7 @@ namespace Emby.Server.Implementations.Library
 
 
         public string GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath)
         public string GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath)
         {
         {
-            var collectionFolder = item as ICollectionFolder;
-            if (collectionFolder != null)
+            if (item is ICollectionFolder collectionFolder)
             {
             {
                 return collectionFolder.CollectionType;
                 return collectionFolder.CollectionType;
             }
             }
@@ -2058,13 +2041,11 @@ namespace Emby.Server.Implementations.Library
 
 
         private string GetContentTypeOverride(string path, bool inherit)
         private string GetContentTypeOverride(string path, bool inherit)
         {
         {
-            var nameValuePair = ConfigurationManager.Configuration.ContentTypes.FirstOrDefault(i => _fileSystem.AreEqual(i.Name, path) || (inherit && !string.IsNullOrEmpty(i.Name) && _fileSystem.ContainsSubPath(i.Name, path)));
-            if (nameValuePair != null)
-            {
-                return nameValuePair.Value;
-            }
-
-            return null;
+            var nameValuePair = ConfigurationManager.Configuration.ContentTypes
+                                    .FirstOrDefault(i => _fileSystem.AreEqual(i.Name, path)
+                                                         || (inherit && !string.IsNullOrEmpty(i.Name)
+                                                                     && _fileSystem.ContainsSubPath(i.Name, path)));
+            return nameValuePair?.Value;
         }
         }
 
 
         private string GetTopFolderContentType(BaseItem item)
         private string GetTopFolderContentType(BaseItem item)
@@ -2081,6 +2062,7 @@ namespace Emby.Server.Implementations.Library
                 {
                 {
                     break;
                     break;
                 }
                 }
+
                 item = parent;
                 item = parent;
             }
             }
 
 
@@ -2092,9 +2074,9 @@ namespace Emby.Server.Implementations.Library
         }
         }
 
 
         private readonly TimeSpan _viewRefreshInterval = TimeSpan.FromHours(24);
         private readonly TimeSpan _viewRefreshInterval = TimeSpan.FromHours(24);
-        //private readonly TimeSpan _viewRefreshInterval = TimeSpan.FromMinutes(1);
 
 
-        public UserView GetNamedView(User user,
+        public UserView GetNamedView(
+            User user,
             string name,
             string name,
             string viewType,
             string viewType,
             string sortName)
             string sortName)
@@ -2102,13 +2084,15 @@ namespace Emby.Server.Implementations.Library
             return GetNamedView(user, name, Guid.Empty, viewType, sortName);
             return GetNamedView(user, name, Guid.Empty, viewType, sortName);
         }
         }
 
 
-        public UserView GetNamedView(string name,
+        public UserView GetNamedView(
+            string name,
             string viewType,
             string viewType,
             string sortName)
             string sortName)
         {
         {
-            var path = Path.Combine(ConfigurationManager.ApplicationPaths.InternalMetadataPath,
-                                    "views",
-                                    _fileSystem.GetValidFilename(viewType));
+            var path = Path.Combine(
+                ConfigurationManager.ApplicationPaths.InternalMetadataPath,
+                "views",
+                _fileSystem.GetValidFilename(viewType));
 
 
             var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView));
             var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView));
 
 
@@ -2144,7 +2128,8 @@ namespace Emby.Server.Implementations.Library
             return item;
             return item;
         }
         }
 
 
-        public UserView GetNamedView(User user,
+        public UserView GetNamedView(
+            User user,
             string name,
             string name,
             Guid parentId,
             Guid parentId,
             string viewType,
             string viewType,
@@ -2173,10 +2158,10 @@ namespace Emby.Server.Implementations.Library
                     Name = name,
                     Name = name,
                     ViewType = viewType,
                     ViewType = viewType,
                     ForcedSortName = sortName,
                     ForcedSortName = sortName,
-                    UserId = user.Id
+                    UserId = user.Id,
+                    DisplayParentId = parentId
                 };
                 };
 
 
-                item.DisplayParentId = parentId;
 
 
                 CreateItem(item, null);
                 CreateItem(item, null);
 
 
@@ -2193,20 +2178,24 @@ namespace Emby.Server.Implementations.Library
 
 
             if (refresh)
             if (refresh)
             {
             {
-                _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
-                {
-                    // Need to force save to increment DateLastSaved
-                    ForceSave = true
+                _providerManagerFactory().QueueRefresh(
+                    item.Id,
+                    new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
+                    {
+                        // Need to force save to increment DateLastSaved
+                        ForceSave = true
 
 
-                }, RefreshPriority.Normal);
+                    },
+                    RefreshPriority.Normal);
             }
             }
 
 
             return item;
             return item;
         }
         }
 
 
-        public UserView GetShadowView(BaseItem parent,
-        string viewType,
-        string sortName)
+        public UserView GetShadowView(
+            BaseItem parent,
+            string viewType,
+            string sortName)
         {
         {
             if (parent == null)
             if (parent == null)
             {
             {
@@ -2257,18 +2246,21 @@ namespace Emby.Server.Implementations.Library
 
 
             if (refresh)
             if (refresh)
             {
             {
-                _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
-                {
-                    // Need to force save to increment DateLastSaved
-                    ForceSave = true
-
-                }, RefreshPriority.Normal);
+                _providerManagerFactory().QueueRefresh(
+                    item.Id,
+                    new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
+                    {
+                        // Need to force save to increment DateLastSaved
+                        ForceSave = true
+                    },
+                    RefreshPriority.Normal);
             }
             }
 
 
             return item;
             return item;
         }
         }
 
 
-        public UserView GetNamedView(string name,
+        public UserView GetNamedView(
+            string name,
             Guid parentId,
             Guid parentId,
             string viewType,
             string viewType,
             string sortName,
             string sortName,
@@ -2331,17 +2323,21 @@ namespace Emby.Server.Implementations.Library
 
 
             if (refresh)
             if (refresh)
             {
             {
-                _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
-                {
-                    // Need to force save to increment DateLastSaved
-                    ForceSave = true
-                }, RefreshPriority.Normal);
+                _providerManagerFactory().QueueRefresh(
+                    item.Id,
+                    new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
+                    {
+                        // Need to force save to increment DateLastSaved
+                        ForceSave = true
+                    },
+                    RefreshPriority.Normal);
             }
             }
 
 
             return item;
             return item;
         }
         }
 
 
-        public void AddExternalSubtitleStreams(List<MediaStream> streams,
+        public void AddExternalSubtitleStreams(
+            List<MediaStream> streams,
             string videoPath,
             string videoPath,
             string[] files)
             string[] files)
         {
         {
@@ -2445,6 +2441,7 @@ namespace Emby.Server.Implementations.Library
                     {
                     {
                         changed = true;
                         changed = true;
                     }
                     }
+
                     episode.IndexNumber = episodeInfo.EpisodeNumber;
                     episode.IndexNumber = episodeInfo.EpisodeNumber;
                 }
                 }
 
 
@@ -2454,6 +2451,7 @@ namespace Emby.Server.Implementations.Library
                     {
                     {
                         changed = true;
                         changed = true;
                     }
                     }
+
                     episode.IndexNumberEnd = episodeInfo.EndingEpsiodeNumber;
                     episode.IndexNumberEnd = episodeInfo.EndingEpsiodeNumber;
                 }
                 }
 
 
@@ -2463,6 +2461,7 @@ namespace Emby.Server.Implementations.Library
                     {
                     {
                         changed = true;
                         changed = true;
                     }
                     }
+
                     episode.ParentIndexNumber = episodeInfo.SeasonNumber;
                     episode.ParentIndexNumber = episodeInfo.SeasonNumber;
                 }
                 }
             }
             }
@@ -2492,6 +2491,7 @@ namespace Emby.Server.Implementations.Library
 
 
         private NamingOptions _namingOptions;
         private NamingOptions _namingOptions;
         private string[] _videoFileExtensions;
         private string[] _videoFileExtensions;
+
         private NamingOptions GetNamingOptionsInternal()
         private NamingOptions GetNamingOptionsInternal()
         {
         {
             if (_namingOptions == null)
             if (_namingOptions == null)
@@ -2688,7 +2688,7 @@ namespace Emby.Server.Implementations.Library
             var newPath = path.Replace(from, to, StringComparison.OrdinalIgnoreCase);
             var newPath = path.Replace(from, to, StringComparison.OrdinalIgnoreCase);
             var changed = false;
             var changed = false;
 
 
-            if (!string.Equals(newPath, path))
+            if (!string.Equals(newPath, path, StringComparison.Ordinal))
             {
             {
                 if (to.IndexOf('/') != -1)
                 if (to.IndexOf('/') != -1)
                 {
                 {
@@ -2812,6 +2812,7 @@ namespace Emby.Server.Implementations.Library
                     {
                     {
                         continue;
                         continue;
                     }
                     }
+
                     throw;
                     throw;
                 }
                 }
             }
             }
@@ -2916,6 +2917,7 @@ namespace Emby.Server.Implementations.Library
         }
         }
 
 
         private const string ShortcutFileExtension = ".mblink";
         private const string ShortcutFileExtension = ".mblink";
+
         public void AddMediaPath(string virtualFolderName, MediaPathInfo pathInfo)
         public void AddMediaPath(string virtualFolderName, MediaPathInfo pathInfo)
         {
         {
             AddMediaPathInternal(virtualFolderName, pathInfo, true);
             AddMediaPathInternal(virtualFolderName, pathInfo, true);
@@ -2932,7 +2934,7 @@ namespace Emby.Server.Implementations.Library
 
 
             if (string.IsNullOrWhiteSpace(path))
             if (string.IsNullOrWhiteSpace(path))
             {
             {
-                throw new ArgumentNullException(nameof(path));
+                throw new ArgumentException(nameof(path));
             }
             }
 
 
             if (!Directory.Exists(path))
             if (!Directory.Exists(path))

+ 14 - 23
Emby.Server.Implementations/Library/UserManager.cs

@@ -4,6 +4,7 @@ using System.Globalization;
 using System.IO;
 using System.IO;
 using System.Linq;
 using System.Linq;
 using System.Text;
 using System.Text;
+using System.Text.RegularExpressions;
 using System.Threading;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Threading.Tasks;
 using MediaBrowser.Common.Events;
 using MediaBrowser.Common.Events;
@@ -213,22 +214,17 @@ namespace Emby.Server.Implementations.Library
             }
             }
         }
         }
 
 
-        public bool IsValidUsername(string username)
+        public static bool IsValidUsername(string username)
         {
         {
-            // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
-            foreach (var currentChar in username)
-            {
-                if (!IsValidUsernameCharacter(currentChar))
-                {
-                    return false;
-                }
-            }
-            return true;
+            //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), dashes (-), underscores (_), apostrophes ('), and periods (.)
+            return Regex.IsMatch(username, "^[\\w-'._@]*$");
         }
         }
 
 
         private static bool IsValidUsernameCharacter(char i)
         private static bool IsValidUsernameCharacter(char i)
         {
         {
-            return !char.Equals(i, '<') && !char.Equals(i, '>');
+            return IsValidUsername(i.ToString());
         }
         }
 
 
         public string MakeValidUsername(string username)
         public string MakeValidUsername(string username)
@@ -475,15 +471,10 @@ namespace Emby.Server.Implementations.Library
         private string GetLocalPasswordHash(User user)
         private string GetLocalPasswordHash(User user)
         {
         {
             return string.IsNullOrEmpty(user.EasyPassword)
             return string.IsNullOrEmpty(user.EasyPassword)
-                ? _defaultAuthenticationProvider.GetEmptyHashedString(user)
+                ? null
                 : user.EasyPassword;
                 : user.EasyPassword;
         }
         }
 
 
-        private bool IsPasswordEmpty(User user, string passwordHash)
-        {
-            return string.Equals(passwordHash, _defaultAuthenticationProvider.GetEmptyHashedString(user), StringComparison.OrdinalIgnoreCase);
-        }
-
         /// <summary>
         /// <summary>
         /// Loads the users from the repository
         /// Loads the users from the repository
         /// </summary>
         /// </summary>
@@ -526,14 +517,14 @@ namespace Emby.Server.Implementations.Library
                 throw new ArgumentNullException(nameof(user));
                 throw new ArgumentNullException(nameof(user));
             }
             }
 
 
-            var hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user).Result;
-            var hasConfiguredEasyPassword = !IsPasswordEmpty(user, GetLocalPasswordHash(user));
+            bool hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user).Result;
+            bool hasConfiguredEasyPassword = string.IsNullOrEmpty(GetLocalPasswordHash(user));
 
 
-            var hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
+            bool hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
                 hasConfiguredEasyPassword :
                 hasConfiguredEasyPassword :
                 hasConfiguredPassword;
                 hasConfiguredPassword;
 
 
-            var dto = new UserDto
+            UserDto dto = new UserDto
             {
             {
                 Id = user.Id,
                 Id = user.Id,
                 Name = user.Name,
                 Name = user.Name,
@@ -552,7 +543,7 @@ namespace Emby.Server.Implementations.Library
                 dto.EnableAutoLogin = true;
                 dto.EnableAutoLogin = true;
             }
             }
 
 
-            var image = user.GetImageInfo(ImageType.Primary, 0);
+            ItemImageInfo image = user.GetImageInfo(ImageType.Primary, 0);
 
 
             if (image != null)
             if (image != null)
             {
             {
@@ -688,7 +679,7 @@ namespace Emby.Server.Implementations.Library
 
 
             if (!IsValidUsername(name))
             if (!IsValidUsername(name))
             {
             {
-                throw new ArgumentException("Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
+                throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
             }
             }
 
 
             if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
             if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))

+ 2 - 6
Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs

@@ -33,7 +33,6 @@ using MediaBrowser.Model.LiveTv;
 using MediaBrowser.Model.MediaInfo;
 using MediaBrowser.Model.MediaInfo;
 using MediaBrowser.Model.Providers;
 using MediaBrowser.Model.Providers;
 using MediaBrowser.Model.Querying;
 using MediaBrowser.Model.Querying;
-using MediaBrowser.Model.Reflection;
 using MediaBrowser.Model.Serialization;
 using MediaBrowser.Model.Serialization;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
 
 
@@ -58,7 +57,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
         private readonly IProviderManager _providerManager;
         private readonly IProviderManager _providerManager;
         private readonly IMediaEncoder _mediaEncoder;
         private readonly IMediaEncoder _mediaEncoder;
         private readonly IProcessFactory _processFactory;
         private readonly IProcessFactory _processFactory;
-        private readonly IAssemblyInfo _assemblyInfo;
         private IMediaSourceManager _mediaSourceManager;
         private IMediaSourceManager _mediaSourceManager;
 
 
         public static EmbyTV Current;
         public static EmbyTV Current;
@@ -74,7 +72,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
         public EmbyTV(IServerApplicationHost appHost,
         public EmbyTV(IServerApplicationHost appHost,
             IStreamHelper streamHelper,
             IStreamHelper streamHelper,
             IMediaSourceManager mediaSourceManager,
             IMediaSourceManager mediaSourceManager,
-            IAssemblyInfo assemblyInfo,
             ILogger logger,
             ILogger logger,
             IJsonSerializer jsonSerializer,
             IJsonSerializer jsonSerializer,
             IHttpClient httpClient,
             IHttpClient httpClient,
@@ -101,12 +98,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
             _processFactory = processFactory;
             _processFactory = processFactory;
             _liveTvManager = (LiveTvManager)liveTvManager;
             _liveTvManager = (LiveTvManager)liveTvManager;
             _jsonSerializer = jsonSerializer;
             _jsonSerializer = jsonSerializer;
-            _assemblyInfo = assemblyInfo;
             _mediaSourceManager = mediaSourceManager;
             _mediaSourceManager = mediaSourceManager;
             _streamHelper = streamHelper;
             _streamHelper = streamHelper;
 
 
-            _seriesTimerProvider = new SeriesTimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers"));
-            _timerProvider = new TimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "timers"), _logger);
+            _seriesTimerProvider = new SeriesTimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers.json"));
+            _timerProvider = new TimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "timers.json"), _logger);
             _timerProvider.TimerFired += _timerProvider_TimerFired;
             _timerProvider.TimerFired += _timerProvider_TimerFired;
 
 
             _config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
             _config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;

+ 10 - 16
Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs

@@ -2,7 +2,6 @@ using System;
 using System.Collections.Generic;
 using System.Collections.Generic;
 using System.IO;
 using System.IO;
 using System.Linq;
 using System.Linq;
-using MediaBrowser.Model.IO;
 using MediaBrowser.Model.Serialization;
 using MediaBrowser.Model.Serialization;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
 
 
@@ -32,32 +31,28 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
             {
             {
                 if (_items == null)
                 if (_items == null)
                 {
                 {
+                    if (!File.Exists(_dataPath))
+                    {
+                        return new List<T>();
+                    }
+
                     Logger.LogInformation("Loading live tv data from {0}", _dataPath);
                     Logger.LogInformation("Loading live tv data from {0}", _dataPath);
                     _items = GetItemsFromFile(_dataPath);
                     _items = GetItemsFromFile(_dataPath);
                 }
                 }
+
                 return _items.ToList();
                 return _items.ToList();
             }
             }
         }
         }
 
 
         private List<T> GetItemsFromFile(string path)
         private List<T> GetItemsFromFile(string path)
         {
         {
-            var jsonFile = path + ".json";
-
-            if (!File.Exists(jsonFile))
-            {
-                return new List<T>();
-            }
-
             try
             try
             {
             {
-                return _jsonSerializer.DeserializeFromFile<List<T>>(jsonFile) ?? new List<T>();
-            }
-            catch (IOException)
-            {
+                return _jsonSerializer.DeserializeFromFile<List<T>>(path);
             }
             }
             catch (Exception ex)
             catch (Exception ex)
             {
             {
-                Logger.LogError(ex, "Error deserializing {jsonFile}", jsonFile);
+                Logger.LogError(ex, "Error deserializing {Path}", path);
             }
             }
 
 
             return new List<T>();
             return new List<T>();
@@ -70,12 +65,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
                 throw new ArgumentNullException(nameof(newList));
                 throw new ArgumentNullException(nameof(newList));
             }
             }
 
 
-            var file = _dataPath + ".json";
-            Directory.CreateDirectory(Path.GetDirectoryName(file));
+            Directory.CreateDirectory(Path.GetDirectoryName(_dataPath));
 
 
             lock (_fileDataLock)
             lock (_fileDataLock)
             {
             {
-                _jsonSerializer.SerializeToFile(newList, file);
+                _jsonSerializer.SerializeToFile(newList, _dataPath);
                 _items = newList;
                 _items = newList;
             }
             }
         }
         }

+ 3 - 2
Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs

@@ -17,6 +17,7 @@ using MediaBrowser.Model.LiveTv;
 using MediaBrowser.Model.Net;
 using MediaBrowser.Model.Net;
 using MediaBrowser.Model.Serialization;
 using MediaBrowser.Model.Serialization;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
+using Microsoft.Net.Http.Headers;
 
 
 namespace Emby.Server.Implementations.LiveTv.Listings
 namespace Emby.Server.Implementations.LiveTv.Listings
 {
 {
@@ -638,7 +639,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
 #if NETSTANDARD2_0
 #if NETSTANDARD2_0
             if (Environment.OSVersion.Platform == PlatformID.Win32NT)
             if (Environment.OSVersion.Platform == PlatformID.Win32NT)
             {
             {
-                options.RequestHeaders["Accept-Encoding"] = "deflate";
+                options.RequestHeaders[HeaderNames.AcceptEncoding] = "deflate";
             }
             }
 #endif
 #endif
 
 
@@ -676,7 +677,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
 #if NETSTANDARD2_0
 #if NETSTANDARD2_0
             if (Environment.OSVersion.Platform == PlatformID.Win32NT)
             if (Environment.OSVersion.Platform == PlatformID.Win32NT)
             {
             {
-                options.RequestHeaders["Accept-Encoding"] = "deflate";
+                options.RequestHeaders[HeaderNames.AcceptEncoding] = "deflate";
             }
             }
 #endif
 #endif
 
 

+ 2 - 1
Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs

@@ -151,7 +151,8 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
             });
             });
         }
         }
 
 
-        private static int RtpHeaderBytes = 12;
+        private const int RtpHeaderBytes = 12;
+
         private async Task CopyTo(MediaBrowser.Model.Net.ISocket udpClient, string file, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
         private async Task CopyTo(MediaBrowser.Model.Net.ISocket udpClient, string file, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
         {
         {
             var bufferSize = 81920;
             var bufferSize = 81920;

+ 19 - 39
Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs

@@ -22,7 +22,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
 
 
         public string OriginalStreamId { get; set; }
         public string OriginalStreamId { get; set; }
         public bool EnableStreamSharing { get; set; }
         public bool EnableStreamSharing { get; set; }
-        public string UniqueId { get; private set; }
+        public string UniqueId { get; }
 
 
         protected readonly IFileSystem FileSystem;
         protected readonly IFileSystem FileSystem;
         protected readonly IServerApplicationPaths AppPaths;
         protected readonly IServerApplicationPaths AppPaths;
@@ -31,12 +31,10 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
         protected readonly ILogger Logger;
         protected readonly ILogger Logger;
         protected readonly CancellationTokenSource LiveStreamCancellationTokenSource = new CancellationTokenSource();
         protected readonly CancellationTokenSource LiveStreamCancellationTokenSource = new CancellationTokenSource();
 
 
-        public string TunerHostId { get; private set; }
+        public string TunerHostId { get; }
 
 
         public DateTime DateOpened { get; protected set; }
         public DateTime DateOpened { get; protected set; }
 
 
-        public Func<Task> OnClose { get; set; }
-
         public LiveStream(MediaSourceInfo mediaSource, TunerHostInfo tuner, IFileSystem fileSystem, ILogger logger, IServerApplicationPaths appPaths)
         public LiveStream(MediaSourceInfo mediaSource, TunerHostInfo tuner, IFileSystem fileSystem, ILogger logger, IServerApplicationPaths appPaths)
         {
         {
             OriginalMediaSource = mediaSource;
             OriginalMediaSource = mediaSource;
@@ -76,26 +74,9 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
 
 
             LiveStreamCancellationTokenSource.Cancel();
             LiveStreamCancellationTokenSource.Cancel();
 
 
-            if (OnClose != null)
-            {
-                return CloseWithExternalFn();
-            }
-
             return Task.CompletedTask;
             return Task.CompletedTask;
         }
         }
 
 
-        private async Task CloseWithExternalFn()
-        {
-            try
-            {
-                await OnClose().ConfigureAwait(false);
-            }
-            catch (Exception ex)
-            {
-                Logger.LogError(ex, "Error closing live stream");
-            }
-        }
-
         protected Stream GetInputStream(string path, bool allowAsyncFileRead)
         protected Stream GetInputStream(string path, bool allowAsyncFileRead)
         {
         {
             var fileOpenOptions = FileOpenOptions.SequentialScan;
             var fileOpenOptions = FileOpenOptions.SequentialScan;
@@ -113,26 +94,25 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
             return DeleteTempFiles(GetStreamFilePaths());
             return DeleteTempFiles(GetStreamFilePaths());
         }
         }
 
 
-        protected async Task DeleteTempFiles(List<string> paths, int retryCount = 0)
+        protected async Task DeleteTempFiles(IEnumerable<string> paths, int retryCount = 0)
         {
         {
             if (retryCount == 0)
             if (retryCount == 0)
             {
             {
-                Logger.LogInformation("Deleting temp files {0}", string.Join(", ", paths.ToArray()));
+                Logger.LogInformation("Deleting temp files {0}", paths);
             }
             }
 
 
             var failedFiles = new List<string>();
             var failedFiles = new List<string>();
 
 
             foreach (var path in paths)
             foreach (var path in paths)
             {
             {
-                try
-                {
-                    FileSystem.DeleteFile(path);
-                }
-                catch (DirectoryNotFoundException)
+                if (!File.Exists(path))
                 {
                 {
+                    continue;
                 }
                 }
-                catch (FileNotFoundException)
+
+                try
                 {
                 {
+                    FileSystem.DeleteFile(path);
                 }
                 }
                 catch (Exception ex)
                 catch (Exception ex)
                 {
                 {
@@ -157,8 +137,8 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
         {
         {
             cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, LiveStreamCancellationTokenSource.Token).Token;
             cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, LiveStreamCancellationTokenSource.Token).Token;
 
 
-            var allowAsync = false;
-            // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
+            // use non-async filestream on windows along with read due to https://github.com/dotnet/corefx/issues/6039
+            var allowAsync = Environment.OSVersion.Platform != PlatformID.Win32NT;
 
 
             bool seekFile = (DateTime.UtcNow - DateOpened).TotalSeconds > 10;
             bool seekFile = (DateTime.UtcNow - DateOpened).TotalSeconds > 10;
 
 
@@ -181,28 +161,24 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
             Logger.LogInformation("Live Stream ended.");
             Logger.LogInformation("Live Stream ended.");
         }
         }
 
 
-        private Tuple<string, bool> GetNextFile(string currentFile)
+        private (string file, bool isLastFile) GetNextFile(string currentFile)
         {
         {
             var files = GetStreamFilePaths();
             var files = GetStreamFilePaths();
 
 
-            //logger.LogInformation("Live stream files: {0}", string.Join(", ", files.ToArray()));
-
             if (string.IsNullOrEmpty(currentFile))
             if (string.IsNullOrEmpty(currentFile))
             {
             {
-                return new Tuple<string, bool>(files.Last(), true);
+                return (files.Last(), true);
             }
             }
 
 
             var nextIndex = files.FindIndex(i => string.Equals(i, currentFile, StringComparison.OrdinalIgnoreCase)) + 1;
             var nextIndex = files.FindIndex(i => string.Equals(i, currentFile, StringComparison.OrdinalIgnoreCase)) + 1;
 
 
             var isLastFile = nextIndex == files.Count - 1;
             var isLastFile = nextIndex == files.Count - 1;
 
 
-            return new Tuple<string, bool>(files.ElementAtOrDefault(nextIndex), isLastFile);
+            return (files.ElementAtOrDefault(nextIndex), isLastFile);
         }
         }
 
 
         private async Task CopyFile(string path, bool seekFile, int emptyReadLimit, bool allowAsync, Stream stream, CancellationToken cancellationToken)
         private async Task CopyFile(string path, bool seekFile, int emptyReadLimit, bool allowAsync, Stream stream, CancellationToken cancellationToken)
         {
         {
-            //logger.LogInformation("Opening live stream file {0}. Empty read limit: {1}", path, emptyReadLimit);
-
             using (var inputStream = (FileStream)GetInputStream(path, allowAsync))
             using (var inputStream = (FileStream)GetInputStream(path, allowAsync))
             {
             {
                 if (seekFile)
                 if (seekFile)
@@ -218,7 +194,11 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
 
 
         private void TrySeek(FileStream stream, long offset)
         private void TrySeek(FileStream stream, long offset)
         {
         {
-            //logger.LogInformation("TrySeek live stream");
+            if (!stream.CanSeek)
+            {
+                return;
+            }
+
             try
             try
             {
             {
                 stream.Seek(offset, SeekOrigin.End);
                 stream.Seek(offset, SeekOrigin.End);

+ 2 - 1
Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs

@@ -19,6 +19,7 @@ using MediaBrowser.Model.MediaInfo;
 using MediaBrowser.Model.Serialization;
 using MediaBrowser.Model.Serialization;
 using MediaBrowser.Model.System;
 using MediaBrowser.Model.System;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
+using Microsoft.Net.Http.Headers;
 
 
 namespace Emby.Server.Implementations.LiveTv.TunerHosts
 namespace Emby.Server.Implementations.LiveTv.TunerHosts
 {
 {
@@ -145,7 +146,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
             if (protocol == MediaProtocol.Http)
             if (protocol == MediaProtocol.Http)
             {
             {
                 // Use user-defined user-agent. If there isn't one, make it look like a browser.
                 // Use user-defined user-agent. If there isn't one, make it look like a browser.
-                httpHeaders["User-Agent"] = string.IsNullOrWhiteSpace(info.UserAgent) ?
+                httpHeaders[HeaderNames.UserAgent] = string.IsNullOrWhiteSpace(info.UserAgent) ?
                     "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.85 Safari/537.36" :
                     "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.85 Safari/537.36" :
                     info.UserAgent;
                     info.UserAgent;
             }
             }

+ 92 - 92
Emby.Server.Implementations/Localization/Core/es-AR.json

@@ -1,97 +1,97 @@
 {
 {
-    "Albums": "Albums",
-    "AppDeviceValues": "App: {0}, Device: {1}",
-    "Application": "Application",
-    "Artists": "Artists",
-    "AuthenticationSucceededWithUserName": "{0} successfully authenticated",
-    "Books": "Books",
-    "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
-    "Channels": "Channels",
-    "ChapterNameValue": "Chapter {0}",
-    "Collections": "Collections",
-    "DeviceOfflineWithName": "{0} has disconnected",
-    "DeviceOnlineWithName": "{0} is connected",
-    "FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
-    "Favorites": "Favorites",
-    "Folders": "Folders",
-    "Genres": "Genres",
-    "HeaderAlbumArtists": "Album Artists",
-    "HeaderCameraUploads": "Camera Uploads",
-    "HeaderContinueWatching": "Continue Watching",
-    "HeaderFavoriteAlbums": "Favorite Albums",
-    "HeaderFavoriteArtists": "Favorite Artists",
-    "HeaderFavoriteEpisodes": "Favorite Episodes",
-    "HeaderFavoriteShows": "Favorite Shows",
-    "HeaderFavoriteSongs": "Favorite Songs",
-    "HeaderLiveTV": "Live TV",
-    "HeaderNextUp": "Next Up",
-    "HeaderRecordingGroups": "Recording Groups",
-    "HomeVideos": "Home videos",
-    "Inherit": "Inherit",
-    "ItemAddedWithName": "{0} was added to the library",
-    "ItemRemovedWithName": "{0} was removed from the library",
-    "LabelIpAddressValue": "Ip address: {0}",
-    "LabelRunningTimeValue": "Running time: {0}",
-    "Latest": "Latest",
-    "MessageApplicationUpdated": "Jellyfin Server has been updated",
-    "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
-    "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
-    "MessageServerConfigurationUpdated": "Server configuration has been updated",
-    "MixedContent": "Mixed content",
-    "Movies": "Movies",
-    "Music": "Music",
-    "MusicVideos": "Music videos",
-    "NameInstallFailed": "{0} installation failed",
-    "NameSeasonNumber": "Season {0}",
-    "NameSeasonUnknown": "Season Unknown",
-    "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
-    "NotificationOptionApplicationUpdateAvailable": "Application update available",
-    "NotificationOptionApplicationUpdateInstalled": "Application update installed",
-    "NotificationOptionAudioPlayback": "Audio playback started",
-    "NotificationOptionAudioPlaybackStopped": "Audio playback stopped",
-    "NotificationOptionCameraImageUploaded": "Camera image uploaded",
-    "NotificationOptionInstallationFailed": "Installation failure",
-    "NotificationOptionNewLibraryContent": "New content added",
-    "NotificationOptionPluginError": "Plugin failure",
-    "NotificationOptionPluginInstalled": "Plugin installed",
-    "NotificationOptionPluginUninstalled": "Plugin uninstalled",
-    "NotificationOptionPluginUpdateInstalled": "Plugin update installed",
-    "NotificationOptionServerRestartRequired": "Server restart required",
-    "NotificationOptionTaskFailed": "Scheduled task failure",
-    "NotificationOptionUserLockedOut": "User locked out",
-    "NotificationOptionVideoPlayback": "Video playback started",
-    "NotificationOptionVideoPlaybackStopped": "Video playback stopped",
-    "Photos": "Photos",
-    "Playlists": "Playlists",
+    "Albums": "Álbumes",
+    "AppDeviceValues": "Aplicación: {0}, Dispositivo: {1}",
+    "Application": "Aplicación",
+    "Artists": "Artistas",
+    "AuthenticationSucceededWithUserName": "{0} autenticado correctamente",
+    "Books": "Libros",
+    "CameraImageUploadedFrom": "Se ha subido una nueva imagen de cámara desde {0}",
+    "Channels": "Canales",
+    "ChapterNameValue": "Capítulo {0}",
+    "Collections": "Colecciones",
+    "DeviceOfflineWithName": "{0} se ha desconectado",
+    "DeviceOnlineWithName": "{0} está conectado",
+    "FailedLoginAttemptWithUserName": "Error al intentar iniciar sesión desde {0}",
+    "Favorites": "Favoritos",
+    "Folders": "Carpetas",
+    "Genres": "Géneros",
+    "HeaderAlbumArtists": "Artistas de álbumes",
+    "HeaderCameraUploads": "Subidas de cámara",
+    "HeaderContinueWatching": "Continuar viendo",
+    "HeaderFavoriteAlbums": "Álbumes favoritos",
+    "HeaderFavoriteArtists": "Artistas favoritos",
+    "HeaderFavoriteEpisodes": "Episodios favoritos",
+    "HeaderFavoriteShows": "Programas favoritos",
+    "HeaderFavoriteSongs": "Canciones favoritas",
+    "HeaderLiveTV": "TV en vivo",
+    "HeaderNextUp": "Continuar Viendo",
+    "HeaderRecordingGroups": "Grupos de grabación",
+    "HomeVideos": "Videos caseros",
+    "Inherit": "Heredar",
+    "ItemAddedWithName": "{0} se ha añadido a la biblioteca",
+    "ItemRemovedWithName": "{0} ha sido eliminado de la biblioteca",
+    "LabelIpAddressValue": "Dirección IP: {0}",
+    "LabelRunningTimeValue": "Tiempo de funcionamiento: {0}",
+    "Latest": "Últimos",
+    "MessageApplicationUpdated": "El servidor Jellyfin fue actualizado",
+    "MessageApplicationUpdatedTo": "Se ha actualizado el servidor Jellyfin a la versión {0}",
+    "MessageNamedServerConfigurationUpdatedWithValue": "Fue actualizada la sección {0} de la configuración del servidor",
+    "MessageServerConfigurationUpdated": "Fue actualizada la configuración del servidor",
+    "MixedContent": "Contenido mixto",
+    "Movies": "Películas",
+    "Music": "Música",
+    "MusicVideos": "Videos musicales",
+    "NameInstallFailed": "{0} error de instalación",
+    "NameSeasonNumber": "Temporada {0}",
+    "NameSeasonUnknown": "Temporada desconocida",
+    "NewVersionIsAvailable": "Disponible una nueva versión de Jellyfin para descargar.",
+    "NotificationOptionApplicationUpdateAvailable": "Actualización de la aplicación disponible",
+    "NotificationOptionApplicationUpdateInstalled": "Actualización de la aplicación instalada",
+    "NotificationOptionAudioPlayback": "Se inició la reproducción de audio",
+    "NotificationOptionAudioPlaybackStopped": "Se detuvo la reproducción de audio",
+    "NotificationOptionCameraImageUploaded": "Imagen de la cámara cargada",
+    "NotificationOptionInstallationFailed": "Error de instalación",
+    "NotificationOptionNewLibraryContent": "Nuevo contenido añadido",
+    "NotificationOptionPluginError": "Error en plugin",
+    "NotificationOptionPluginInstalled": "Plugin instalado",
+    "NotificationOptionPluginUninstalled": "Plugin desinstalado",
+    "NotificationOptionPluginUpdateInstalled": "Actualización del complemento instalada",
+    "NotificationOptionServerRestartRequired": "Se requiere reinicio del servidor",
+    "NotificationOptionTaskFailed": "Error de tarea programada",
+    "NotificationOptionUserLockedOut": "Usuario bloqueado",
+    "NotificationOptionVideoPlayback": "Se inició la reproducción de video",
+    "NotificationOptionVideoPlaybackStopped": "Reproducción de video detenida",
+    "Photos": "Fotos",
+    "Playlists": "Listas de reproducción",
     "Plugin": "Plugin",
     "Plugin": "Plugin",
-    "PluginInstalledWithName": "{0} was installed",
-    "PluginUninstalledWithName": "{0} was uninstalled",
-    "PluginUpdatedWithName": "{0} was updated",
-    "ProviderValue": "Provider: {0}",
-    "ScheduledTaskFailedWithName": "{0} failed",
-    "ScheduledTaskStartedWithName": "{0} started",
-    "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
+    "PluginInstalledWithName": "{0} fue instalado",
+    "PluginUninstalledWithName": "{0} fue desinstalado",
+    "PluginUpdatedWithName": "{0} fue actualizado",
+    "ProviderValue": "Proveedor: {0}",
+    "ScheduledTaskFailedWithName": "{0} falló",
+    "ScheduledTaskStartedWithName": "{0} iniciada",
+    "ServerNameNeedsToBeRestarted": "{0} necesita ser reiniciado",
     "Shows": "Series",
     "Shows": "Series",
-    "Songs": "Songs",
-    "StartupEmbyServerIsLoading": "Jellyfin Server is loading. Please try again shortly.",
+    "Songs": "Canciones",
+    "StartupEmbyServerIsLoading": "Jellyfin Server se está cargando. Vuelve a intentarlo en breve.",
     "SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
     "SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
-    "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
-    "SubtitlesDownloadedForItem": "Subtitles downloaded for {0}",
-    "Sync": "Sync",
-    "System": "System",
-    "TvShows": "TV Shows",
-    "User": "User",
-    "UserCreatedWithName": "User {0} has been created",
-    "UserDeletedWithName": "User {0} has been deleted",
-    "UserDownloadingItemWithValues": "{0} is downloading {1}",
-    "UserLockedOutWithName": "User {0} has been locked out",
-    "UserOfflineFromDevice": "{0} has disconnected from {1}",
-    "UserOnlineFromDevice": "{0} is online from {1}",
-    "UserPasswordChangedWithName": "Password has been changed for user {0}",
-    "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
-    "UserStartedPlayingItemWithValues": "{0} is playing {1} on {2}",
-    "UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}",
-    "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
-    "ValueSpecialEpisodeName": "Special - {0}",
-    "VersionNumber": "Version {0}"
+    "SubtitleDownloadFailureFromForItem": "Fallo de descarga de subtítulos desde {0} para {1}",
+    "SubtitlesDownloadedForItem": "Descargar subtítulos para {0}",
+    "Sync": "Sincronizar",
+    "System": "Sistema",
+    "TvShows": "Series de TV",
+    "User": "Usuario",
+    "UserCreatedWithName": "El usuario {0} ha sido creado",
+    "UserDeletedWithName": "El usuario {0} ha sido borrado",
+    "UserDownloadingItemWithValues": "{0} está descargando {1}",
+    "UserLockedOutWithName": "El usuario {0} ha sido bloqueado",
+    "UserOfflineFromDevice": "{0} se ha desconectado de {1}",
+    "UserOnlineFromDevice": "{0} está en línea desde {1}",
+    "UserPasswordChangedWithName": "Se ha cambiado la contraseña para el usuario {0}",
+    "UserPolicyUpdatedWithName": "Actualizada política de usuario para {0}",
+    "UserStartedPlayingItemWithValues": "{0} está reproduciendo {1} en {2}",
+    "UserStoppedPlayingItemWithValues": "{0} ha terminado de reproducir {1} en {2}",
+    "ValueHasBeenAddedToLibrary": "{0} ha sido añadido a tu biblioteca multimedia",
+    "ValueSpecialEpisodeName": "Especial - {0}",
+    "VersionNumber": "Versión {0}"
 }
 }

+ 85 - 85
Emby.Server.Implementations/Localization/Core/fr-CA.json

@@ -1,97 +1,97 @@
 {
 {
     "Albums": "Albums",
     "Albums": "Albums",
-    "AppDeviceValues": "App: {0}, Device: {1}",
+    "AppDeviceValues": "Application : {0}, Appareil : {1}",
     "Application": "Application",
     "Application": "Application",
-    "Artists": "Artists",
-    "AuthenticationSucceededWithUserName": "{0} successfully authenticated",
-    "Books": "Books",
-    "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
-    "Channels": "Channels",
-    "ChapterNameValue": "Chapter {0}",
+    "Artists": "Artistes",
+    "AuthenticationSucceededWithUserName": "{0} s'est authentifié avec succès",
+    "Books": "Livres",
+    "CameraImageUploadedFrom": "Une nouvelle image de caméra a été téléchargée depuis {0}",
+    "Channels": "Chaînes",
+    "ChapterNameValue": "Chapitre {0}",
     "Collections": "Collections",
     "Collections": "Collections",
-    "DeviceOfflineWithName": "{0} has disconnected",
-    "DeviceOnlineWithName": "{0} is connected",
-    "FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
-    "Favorites": "Favorites",
-    "Folders": "Folders",
+    "DeviceOfflineWithName": "{0} s'est déconnecté",
+    "DeviceOnlineWithName": "{0} est connecté",
+    "FailedLoginAttemptWithUserName": "Échec d'une tentative de connexion de {0}",
+    "Favorites": "Favoris",
+    "Folders": "Dossiers",
     "Genres": "Genres",
     "Genres": "Genres",
-    "HeaderAlbumArtists": "Album Artists",
-    "HeaderCameraUploads": "Camera Uploads",
+    "HeaderAlbumArtists": "Artistes de l'album",
+    "HeaderCameraUploads": "Photos transférées",
     "HeaderContinueWatching": "Continuer à regarder",
     "HeaderContinueWatching": "Continuer à regarder",
-    "HeaderFavoriteAlbums": "Favorite Albums",
-    "HeaderFavoriteArtists": "Favorite Artists",
-    "HeaderFavoriteEpisodes": "Favorite Episodes",
-    "HeaderFavoriteShows": "Favorite Shows",
-    "HeaderFavoriteSongs": "Favorite Songs",
-    "HeaderLiveTV": "Live TV",
+    "HeaderFavoriteAlbums": "Albums favoris",
+    "HeaderFavoriteArtists": "Artistes favoris",
+    "HeaderFavoriteEpisodes": "Épisodes favoris",
+    "HeaderFavoriteShows": "Séries favorites",
+    "HeaderFavoriteSongs": "Chansons favorites",
+    "HeaderLiveTV": "TV en direct",
     "HeaderNextUp": "À Suivre",
     "HeaderNextUp": "À Suivre",
-    "HeaderRecordingGroups": "Recording Groups",
-    "HomeVideos": "Home videos",
-    "Inherit": "Inherit",
-    "ItemAddedWithName": "{0} was added to the library",
-    "ItemRemovedWithName": "{0} was removed from the library",
-    "LabelIpAddressValue": "Ip address: {0}",
-    "LabelRunningTimeValue": "Running time: {0}",
-    "Latest": "Latest",
-    "MessageApplicationUpdated": "Jellyfin Server has been updated",
-    "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
-    "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
-    "MessageServerConfigurationUpdated": "Server configuration has been updated",
-    "MixedContent": "Mixed content",
-    "Movies": "Movies",
-    "Music": "Music",
-    "MusicVideos": "Music videos",
-    "NameInstallFailed": "{0} installation failed",
-    "NameSeasonNumber": "Season {0}",
-    "NameSeasonUnknown": "Season Unknown",
-    "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
-    "NotificationOptionApplicationUpdateAvailable": "Application update available",
-    "NotificationOptionApplicationUpdateInstalled": "Application update installed",
-    "NotificationOptionAudioPlayback": "Audio playback started",
-    "NotificationOptionAudioPlaybackStopped": "Audio playback stopped",
-    "NotificationOptionCameraImageUploaded": "Camera image uploaded",
-    "NotificationOptionInstallationFailed": "Installation failure",
-    "NotificationOptionNewLibraryContent": "New content added",
-    "NotificationOptionPluginError": "Plugin failure",
-    "NotificationOptionPluginInstalled": "Plugin installed",
-    "NotificationOptionPluginUninstalled": "Plugin uninstalled",
-    "NotificationOptionPluginUpdateInstalled": "Plugin update installed",
-    "NotificationOptionServerRestartRequired": "Server restart required",
-    "NotificationOptionTaskFailed": "Scheduled task failure",
-    "NotificationOptionUserLockedOut": "User locked out",
-    "NotificationOptionVideoPlayback": "Video playback started",
-    "NotificationOptionVideoPlaybackStopped": "Video playback stopped",
+    "HeaderRecordingGroups": "Groupes d'enregistrements",
+    "HomeVideos": "Vidéos personnelles",
+    "Inherit": "Hériter",
+    "ItemAddedWithName": "{0} a été ajouté à la médiathèque",
+    "ItemRemovedWithName": "{0} a été supprimé de la médiathèque",
+    "LabelIpAddressValue": "Adresse IP : {0}",
+    "LabelRunningTimeValue": "Durée : {0}",
+    "Latest": "Derniers",
+    "MessageApplicationUpdated": "Le serveur Jellyfin a été mis à jour",
+    "MessageApplicationUpdatedTo": "Le serveur Jellyfin a été mis à jour vers la version {0}",
+    "MessageNamedServerConfigurationUpdatedWithValue": "La configuration de la section {0} du serveur a été mise à jour",
+    "MessageServerConfigurationUpdated": "La configuration du serveur a été mise à jour",
+    "MixedContent": "Contenu mixte",
+    "Movies": "Films",
+    "Music": "Musique",
+    "MusicVideos": "Vidéos musicales",
+    "NameInstallFailed": "{0} échec d'installation",
+    "NameSeasonNumber": "Saison {0}",
+    "NameSeasonUnknown": "Saison Inconnue",
+    "NewVersionIsAvailable": "Une nouvelle version du serveur Jellyfin est disponible au téléchargement.",
+    "NotificationOptionApplicationUpdateAvailable": "Mise à jour de l'application disponible",
+    "NotificationOptionApplicationUpdateInstalled": "Mise à jour de l'application installée",
+    "NotificationOptionAudioPlayback": "Lecture audio démarrée",
+    "NotificationOptionAudioPlaybackStopped": "Lecture audio arrêtée",
+    "NotificationOptionCameraImageUploaded": "L'image de l'appareil photo a été transférée",
+    "NotificationOptionInstallationFailed": "Échec d'installation",
+    "NotificationOptionNewLibraryContent": "Nouveau contenu ajouté",
+    "NotificationOptionPluginError": "Erreur d'extension",
+    "NotificationOptionPluginInstalled": "Extension installée",
+    "NotificationOptionPluginUninstalled": "Extension désinstallée",
+    "NotificationOptionPluginUpdateInstalled": "Mise à jour d'extension installée",
+    "NotificationOptionServerRestartRequired": "Un redémarrage du serveur est requis",
+    "NotificationOptionTaskFailed": "Échec de tâche planifiée",
+    "NotificationOptionUserLockedOut": "Utilisateur verrouillé",
+    "NotificationOptionVideoPlayback": "Lecture vidéo démarrée",
+    "NotificationOptionVideoPlaybackStopped": "Lecture vidéo arrêtée",
     "Photos": "Photos",
     "Photos": "Photos",
-    "Playlists": "Playlists",
-    "Plugin": "Plugin",
-    "PluginInstalledWithName": "{0} was installed",
-    "PluginUninstalledWithName": "{0} was uninstalled",
-    "PluginUpdatedWithName": "{0} was updated",
-    "ProviderValue": "Provider: {0}",
-    "ScheduledTaskFailedWithName": "{0} failed",
-    "ScheduledTaskStartedWithName": "{0} started",
-    "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
-    "Shows": "Series",
-    "Songs": "Songs",
-    "StartupEmbyServerIsLoading": "Jellyfin Server is loading. Please try again shortly.",
+    "Playlists": "Listes de lecture",
+    "Plugin": "Extension",
+    "PluginInstalledWithName": "{0} a été installé",
+    "PluginUninstalledWithName": "{0} a été désinstallé",
+    "PluginUpdatedWithName": "{0} a été mis à jour",
+    "ProviderValue": "Fournisseur : {0}",
+    "ScheduledTaskFailedWithName": "{0} a échoué",
+    "ScheduledTaskStartedWithName": "{0} a commencé",
+    "ServerNameNeedsToBeRestarted": "{0} doit être redémarré",
+    "Shows": "Émissions",
+    "Songs": "Chansons",
+    "StartupEmbyServerIsLoading": "Le serveur Jellyfin est en cours de chargement. Veuillez réessayer dans quelques instants.",
     "SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
     "SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
-    "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
-    "SubtitlesDownloadedForItem": "Subtitles downloaded for {0}",
-    "Sync": "Sync",
-    "System": "System",
-    "TvShows": "TV Shows",
-    "User": "User",
-    "UserCreatedWithName": "User {0} has been created",
-    "UserDeletedWithName": "User {0} has been deleted",
-    "UserDownloadingItemWithValues": "{0} is downloading {1}",
-    "UserLockedOutWithName": "User {0} has been locked out",
-    "UserOfflineFromDevice": "{0} has disconnected from {1}",
-    "UserOnlineFromDevice": "{0} is online from {1}",
-    "UserPasswordChangedWithName": "Password has been changed for user {0}",
-    "UserPolicyUpdatedWithName": "User policy has been updated for {0}",
-    "UserStartedPlayingItemWithValues": "{0} is playing {1} on {2}",
-    "UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}",
-    "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
+    "SubtitleDownloadFailureFromForItem": "Échec du téléchargement des sous-titres depuis {0} pour {1}",
+    "SubtitlesDownloadedForItem": "Les sous-titres de {0} ont été téléchargés",
+    "Sync": "Synchroniser",
+    "System": "Système",
+    "TvShows": "Séries Télé",
+    "User": "Utilisateur",
+    "UserCreatedWithName": "L'utilisateur {0} a été créé",
+    "UserDeletedWithName": "L'utilisateur {0} a été supprimé",
+    "UserDownloadingItemWithValues": "{0} est en train de télécharger {1}",
+    "UserLockedOutWithName": "L'utilisateur {0} a été verrouillé",
+    "UserOfflineFromDevice": "{0} s'est déconnecté depuis {1}",
+    "UserOnlineFromDevice": "{0} s'est connecté depuis {1}",
+    "UserPasswordChangedWithName": "Le mot de passe pour l'utilisateur {0} a été modifié",
+    "UserPolicyUpdatedWithName": "La politique de l'utilisateur a été mise à jour pour {0}",
+    "UserStartedPlayingItemWithValues": "{0} est en train de lire {1} sur {2}",
+    "UserStoppedPlayingItemWithValues": "{0} vient d'arrêter la lecture de {1} sur {2}",
+    "ValueHasBeenAddedToLibrary": "{0} a été ajouté à votre médiathèque",
     "ValueSpecialEpisodeName": "Spécial - {0}",
     "ValueSpecialEpisodeName": "Spécial - {0}",
     "VersionNumber": "Version {0}"
     "VersionNumber": "Version {0}"
 }
 }

+ 2 - 2
Emby.Server.Implementations/Localization/Core/fr.json

@@ -44,7 +44,7 @@
     "NameInstallFailed": "{0} échec d'installation",
     "NameInstallFailed": "{0} échec d'installation",
     "NameSeasonNumber": "Saison {0}",
     "NameSeasonNumber": "Saison {0}",
     "NameSeasonUnknown": "Saison Inconnue",
     "NameSeasonUnknown": "Saison Inconnue",
-    "NewVersionIsAvailable": "Une nouvelle version d'Jellyfin Serveur est disponible au téléchargement.",
+    "NewVersionIsAvailable": "Une nouvelle version de Jellyfin Serveur est disponible au téléchargement.",
     "NotificationOptionApplicationUpdateAvailable": "Mise à jour de l'application disponible",
     "NotificationOptionApplicationUpdateAvailable": "Mise à jour de l'application disponible",
     "NotificationOptionApplicationUpdateInstalled": "Mise à jour de l'application installée",
     "NotificationOptionApplicationUpdateInstalled": "Mise à jour de l'application installée",
     "NotificationOptionAudioPlayback": "Lecture audio démarrée",
     "NotificationOptionAudioPlayback": "Lecture audio démarrée",
@@ -89,7 +89,7 @@
     "UserOnlineFromDevice": "{0} s'est connecté depuis {1}",
     "UserOnlineFromDevice": "{0} s'est connecté depuis {1}",
     "UserPasswordChangedWithName": "Le mot de passe pour l'utilisateur {0} a été modifié",
     "UserPasswordChangedWithName": "Le mot de passe pour l'utilisateur {0} a été modifié",
     "UserPolicyUpdatedWithName": "La politique de l'utilisateur a été mise à jour pour {0}",
     "UserPolicyUpdatedWithName": "La politique de l'utilisateur a été mise à jour pour {0}",
-    "UserStartedPlayingItemWithValues": "{0} est entrain de lire {1} sur {2}",
+    "UserStartedPlayingItemWithValues": "{0} est en train de lire {1} sur {2}",
     "UserStoppedPlayingItemWithValues": "{0} vient d'arrêter la lecture de {1} sur {2}",
     "UserStoppedPlayingItemWithValues": "{0} vient d'arrêter la lecture de {1} sur {2}",
     "ValueHasBeenAddedToLibrary": "{0} a été ajouté à votre librairie",
     "ValueHasBeenAddedToLibrary": "{0} a été ajouté à votre librairie",
     "ValueSpecialEpisodeName": "Spécial - {0}",
     "ValueSpecialEpisodeName": "Spécial - {0}",

+ 3 - 3
Emby.Server.Implementations/Localization/Core/he.json

@@ -1,8 +1,8 @@
 {
 {
-    "Albums": "Albums",
+    "Albums": "אלבומים",
     "AppDeviceValues": "App: {0}, Device: {1}",
     "AppDeviceValues": "App: {0}, Device: {1}",
-    "Application": "Application",
-    "Artists": "Artists",
+    "Application": "אפליקציה",
+    "Artists": "אמנים",
     "AuthenticationSucceededWithUserName": "{0} successfully authenticated",
     "AuthenticationSucceededWithUserName": "{0} successfully authenticated",
     "Books": "ספרים",
     "Books": "ספרים",
     "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
     "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",

+ 6 - 6
Emby.Server.Implementations/Localization/Core/it.json

@@ -34,17 +34,17 @@
     "LabelRunningTimeValue": "Durata: {0}",
     "LabelRunningTimeValue": "Durata: {0}",
     "Latest": "Più recenti",
     "Latest": "Più recenti",
     "MessageApplicationUpdated": "Il Server Jellyfin è stato aggiornato",
     "MessageApplicationUpdated": "Il Server Jellyfin è stato aggiornato",
-    "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
+    "MessageApplicationUpdatedTo": "Jellyfin Server è stato aggiornato a {0}",
     "MessageNamedServerConfigurationUpdatedWithValue": "La sezione {0} della configurazione server è stata aggiornata",
     "MessageNamedServerConfigurationUpdatedWithValue": "La sezione {0} della configurazione server è stata aggiornata",
     "MessageServerConfigurationUpdated": "La configurazione del server è stata aggiornata",
     "MessageServerConfigurationUpdated": "La configurazione del server è stata aggiornata",
     "MixedContent": "Contenuto misto",
     "MixedContent": "Contenuto misto",
     "Movies": "Film",
     "Movies": "Film",
     "Music": "Musica",
     "Music": "Musica",
     "MusicVideos": "Video musicali",
     "MusicVideos": "Video musicali",
-    "NameInstallFailed": "{0} installation failed",
+    "NameInstallFailed": "{0} installazione fallita",
     "NameSeasonNumber": "Stagione {0}",
     "NameSeasonNumber": "Stagione {0}",
     "NameSeasonUnknown": "Stagione sconosciuto",
     "NameSeasonUnknown": "Stagione sconosciuto",
-    "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
+    "NewVersionIsAvailable": "Una nuova versione di Jellyfin Server è disponibile per il download.",
     "NotificationOptionApplicationUpdateAvailable": "Aggiornamento dell'applicazione disponibile",
     "NotificationOptionApplicationUpdateAvailable": "Aggiornamento dell'applicazione disponibile",
     "NotificationOptionApplicationUpdateInstalled": "Aggiornamento dell'applicazione installato",
     "NotificationOptionApplicationUpdateInstalled": "Aggiornamento dell'applicazione installato",
     "NotificationOptionAudioPlayback": "La riproduzione audio è iniziata",
     "NotificationOptionAudioPlayback": "La riproduzione audio è iniziata",
@@ -70,12 +70,12 @@
     "ProviderValue": "Provider: {0}",
     "ProviderValue": "Provider: {0}",
     "ScheduledTaskFailedWithName": "{0} fallito",
     "ScheduledTaskFailedWithName": "{0} fallito",
     "ScheduledTaskStartedWithName": "{0} avviati",
     "ScheduledTaskStartedWithName": "{0} avviati",
-    "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
+    "ServerNameNeedsToBeRestarted": "{0} deve essere riavviato",
     "Shows": "Programmi",
     "Shows": "Programmi",
     "Songs": "Canzoni",
     "Songs": "Canzoni",
     "StartupEmbyServerIsLoading": "Jellyfin server si sta avviando. Per favore riprova più tardi.",
     "StartupEmbyServerIsLoading": "Jellyfin server si sta avviando. Per favore riprova più tardi.",
     "SubtitleDownloadFailureForItem": "Impossibile scaricare i sottotitoli per {0}",
     "SubtitleDownloadFailureForItem": "Impossibile scaricare i sottotitoli per {0}",
-    "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
+    "SubtitleDownloadFailureFromForItem": "Impossibile scaricare i sottotitoli da {0} per {1}",
     "SubtitlesDownloadedForItem": "Sottotitoli scaricati per {0}",
     "SubtitlesDownloadedForItem": "Sottotitoli scaricati per {0}",
     "Sync": "Sincronizza",
     "Sync": "Sincronizza",
     "System": "Sistema",
     "System": "Sistema",
@@ -91,7 +91,7 @@
     "UserPolicyUpdatedWithName": "La politica dell'utente è stata aggiornata per {0}",
     "UserPolicyUpdatedWithName": "La politica dell'utente è stata aggiornata per {0}",
     "UserStartedPlayingItemWithValues": "{0} ha avviato la riproduzione di {1}",
     "UserStartedPlayingItemWithValues": "{0} ha avviato la riproduzione di {1}",
     "UserStoppedPlayingItemWithValues": "{0} ha interrotto la riproduzione di {1}",
     "UserStoppedPlayingItemWithValues": "{0} ha interrotto la riproduzione di {1}",
-    "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
+    "ValueHasBeenAddedToLibrary": "{0} è stato aggiunto alla tua libreria multimediale",
     "ValueSpecialEpisodeName": "Speciale - {0}",
     "ValueSpecialEpisodeName": "Speciale - {0}",
     "VersionNumber": "Versione {0}"
     "VersionNumber": "Versione {0}"
 }
 }

+ 5 - 5
Emby.Server.Implementations/Localization/Core/kk.json

@@ -3,15 +3,15 @@
     "AppDeviceValues": "Qoldanba: {0}, Qurylǵy: {1}",
     "AppDeviceValues": "Qoldanba: {0}, Qurylǵy: {1}",
     "Application": "Qoldanba",
     "Application": "Qoldanba",
     "Artists": "Oryndaýshylar",
     "Artists": "Oryndaýshylar",
-    "AuthenticationSucceededWithUserName": "{0} túpnusqalyǵyn rastalýy sátti",
+    "AuthenticationSucceededWithUserName": "{0} túpnusqalyq rastalýy sátti aıaqtaldy",
     "Books": "Kitaptar",
     "Books": "Kitaptar",
-    "CameraImageUploadedFrom": "Jańa sýret {0} kamerasynan júktep alyndy",
+    "CameraImageUploadedFrom": "{0} kamerasynan jańa sýret júktep alyndy",
     "Channels": "Arnalar",
     "Channels": "Arnalar",
     "ChapterNameValue": "{0}-sahna",
     "ChapterNameValue": "{0}-sahna",
     "Collections": "Jıyntyqtar",
     "Collections": "Jıyntyqtar",
     "DeviceOfflineWithName": "{0} ajyratylǵan",
     "DeviceOfflineWithName": "{0} ajyratylǵan",
     "DeviceOnlineWithName": "{0} qosylǵan",
     "DeviceOnlineWithName": "{0} qosylǵan",
-    "FailedLoginAttemptWithUserName": "{0} tarapynan kirý áreketi sátsiz",
+    "FailedLoginAttemptWithUserName": "{0} tarapynan kirý áreketi sátsiz aıaqtaldy",
     "Favorites": "Tańdaýlylar",
     "Favorites": "Tańdaýlylar",
     "Folders": "Qaltalar",
     "Folders": "Qaltalar",
     "Genres": "Janrlar",
     "Genres": "Janrlar",
@@ -28,13 +28,13 @@
     "HeaderRecordingGroups": "Jazba toptary",
     "HeaderRecordingGroups": "Jazba toptary",
     "HomeVideos": "Úılik beıneler",
     "HomeVideos": "Úılik beıneler",
     "Inherit": "Muraǵa ıelený",
     "Inherit": "Muraǵa ıelený",
-    "ItemAddedWithName": "{0} tasyǵyshhanaǵa ústelindi",
+    "ItemAddedWithName": "{0} tasyǵyshhanaǵa ústeldi",
     "ItemRemovedWithName": "{0} tasyǵyshhanadan alastaldy",
     "ItemRemovedWithName": "{0} tasyǵyshhanadan alastaldy",
     "LabelIpAddressValue": "IP-mekenjaıy: {0}",
     "LabelIpAddressValue": "IP-mekenjaıy: {0}",
     "LabelRunningTimeValue": "Oınatý ýaqyty: {0}",
     "LabelRunningTimeValue": "Oınatý ýaqyty: {0}",
     "Latest": "Eń keıingi",
     "Latest": "Eń keıingi",
     "MessageApplicationUpdated": "Jellyfin Serveri jańartyldy",
     "MessageApplicationUpdated": "Jellyfin Serveri jańartyldy",
-    "MessageApplicationUpdatedTo": "Jellyfin Serveri {0} deńgeıge jańartyldy",
+    "MessageApplicationUpdatedTo": "Jellyfin Serveri {0} nusqasyna jańartyldy",
     "MessageNamedServerConfigurationUpdatedWithValue": "Server teńsheliminiń {0} bólimi jańartyldy",
     "MessageNamedServerConfigurationUpdatedWithValue": "Server teńsheliminiń {0} bólimi jańartyldy",
     "MessageServerConfigurationUpdated": "Server teńshelimi jańartyldy",
     "MessageServerConfigurationUpdated": "Server teńshelimi jańartyldy",
     "MixedContent": "Aralas mazmun",
     "MixedContent": "Aralas mazmun",

+ 8 - 8
Emby.Server.Implementations/Localization/Core/pt-BR.json

@@ -5,7 +5,7 @@
     "Artists": "Artistas",
     "Artists": "Artistas",
     "AuthenticationSucceededWithUserName": "{0} autenticado com sucesso",
     "AuthenticationSucceededWithUserName": "{0} autenticado com sucesso",
     "Books": "Livros",
     "Books": "Livros",
-    "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
+    "CameraImageUploadedFrom": "Uma nova imagem da câmera foi submetida de {0}",
     "Channels": "Canais",
     "Channels": "Canais",
     "ChapterNameValue": "Capítulo {0}",
     "ChapterNameValue": "Capítulo {0}",
     "Collections": "Coletâneas",
     "Collections": "Coletâneas",
@@ -30,21 +30,21 @@
     "Inherit": "Herdar",
     "Inherit": "Herdar",
     "ItemAddedWithName": "{0} foi adicionado à biblioteca",
     "ItemAddedWithName": "{0} foi adicionado à biblioteca",
     "ItemRemovedWithName": "{0} foi removido da biblioteca",
     "ItemRemovedWithName": "{0} foi removido da biblioteca",
-    "LabelIpAddressValue": "Endereço ip: {0}",
+    "LabelIpAddressValue": "Endereço IP: {0}",
     "LabelRunningTimeValue": "Tempo de execução: {0}",
     "LabelRunningTimeValue": "Tempo de execução: {0}",
     "Latest": "Recente",
     "Latest": "Recente",
     "MessageApplicationUpdated": "O servidor Jellyfin foi atualizado",
     "MessageApplicationUpdated": "O servidor Jellyfin foi atualizado",
-    "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
+    "MessageApplicationUpdatedTo": "O Servidor Jellyfin foi atualizado para {0}",
     "MessageNamedServerConfigurationUpdatedWithValue": "A seção {0} da configuração do servidor foi atualizada",
     "MessageNamedServerConfigurationUpdatedWithValue": "A seção {0} da configuração do servidor foi atualizada",
     "MessageServerConfigurationUpdated": "A configuração do servidor foi atualizada",
     "MessageServerConfigurationUpdated": "A configuração do servidor foi atualizada",
     "MixedContent": "Conteúdo misto",
     "MixedContent": "Conteúdo misto",
     "Movies": "Filmes",
     "Movies": "Filmes",
     "Music": "Música",
     "Music": "Música",
     "MusicVideos": "Vídeos musicais",
     "MusicVideos": "Vídeos musicais",
-    "NameInstallFailed": "{0} installation failed",
+    "NameInstallFailed": "A instalação de {0} falhou",
     "NameSeasonNumber": "Temporada {0}",
     "NameSeasonNumber": "Temporada {0}",
     "NameSeasonUnknown": "Temporada Desconhecida",
     "NameSeasonUnknown": "Temporada Desconhecida",
-    "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
+    "NewVersionIsAvailable": "Uma nova versão do servidor Jellyfin está disponível para download.",
     "NotificationOptionApplicationUpdateAvailable": "Atualização de aplicativo disponível",
     "NotificationOptionApplicationUpdateAvailable": "Atualização de aplicativo disponível",
     "NotificationOptionApplicationUpdateInstalled": "Atualização de aplicativo instalada",
     "NotificationOptionApplicationUpdateInstalled": "Atualização de aplicativo instalada",
     "NotificationOptionAudioPlayback": "Reprodução de áudio iniciada",
     "NotificationOptionAudioPlayback": "Reprodução de áudio iniciada",
@@ -70,12 +70,12 @@
     "ProviderValue": "Provedor: {0}",
     "ProviderValue": "Provedor: {0}",
     "ScheduledTaskFailedWithName": "{0} falhou",
     "ScheduledTaskFailedWithName": "{0} falhou",
     "ScheduledTaskStartedWithName": "{0} iniciada",
     "ScheduledTaskStartedWithName": "{0} iniciada",
-    "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
+    "ServerNameNeedsToBeRestarted": "O servidor {0} precisa ser reiniciado",
     "Shows": "Séries",
     "Shows": "Séries",
     "Songs": "Músicas",
     "Songs": "Músicas",
     "StartupEmbyServerIsLoading": "O Servidor Jellyfin está carregando. Por favor tente novamente em breve.",
     "StartupEmbyServerIsLoading": "O Servidor Jellyfin está carregando. Por favor tente novamente em breve.",
     "SubtitleDownloadFailureForItem": "Download de legendas falhou para {0}",
     "SubtitleDownloadFailureForItem": "Download de legendas falhou para {0}",
-    "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
+    "SubtitleDownloadFailureFromForItem": "Houve um problema ao baixar as legendas de {0} para {1}",
     "SubtitlesDownloadedForItem": "Legendas baixadas para {0}",
     "SubtitlesDownloadedForItem": "Legendas baixadas para {0}",
     "Sync": "Sincronizar",
     "Sync": "Sincronizar",
     "System": "Sistema",
     "System": "Sistema",
@@ -91,7 +91,7 @@
     "UserPolicyUpdatedWithName": "A política de usuário foi atualizada para {0}",
     "UserPolicyUpdatedWithName": "A política de usuário foi atualizada para {0}",
     "UserStartedPlayingItemWithValues": "{0} iniciou a reprodução de {1}",
     "UserStartedPlayingItemWithValues": "{0} iniciou a reprodução de {1}",
     "UserStoppedPlayingItemWithValues": "{0} parou de reproduzir {1}",
     "UserStoppedPlayingItemWithValues": "{0} parou de reproduzir {1}",
-    "ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
+    "ValueHasBeenAddedToLibrary": "{0} foi adicionado a sua biblioteca",
     "ValueSpecialEpisodeName": "Especial - {0}",
     "ValueSpecialEpisodeName": "Especial - {0}",
     "VersionNumber": "Versão {0}"
     "VersionNumber": "Versão {0}"
 }
 }

+ 56 - 56
Emby.Server.Implementations/Localization/Core/sl-SI.json

@@ -1,62 +1,62 @@
 {
 {
-    "Albums": "Albums",
-    "AppDeviceValues": "App: {0}, Device: {1}",
-    "Application": "Application",
-    "Artists": "Artists",
-    "AuthenticationSucceededWithUserName": "{0} successfully authenticated",
-    "Books": "Books",
-    "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
-    "Channels": "Channels",
-    "ChapterNameValue": "Chapter {0}",
-    "Collections": "Collections",
+    "Albums": "Albumi",
+    "AppDeviceValues": "Aplikacija: {0}, Naprava: {1}",
+    "Application": "Aplikacija",
+    "Artists": "Izvajalci",
+    "AuthenticationSucceededWithUserName": "{0} preverjanje uspešno",
+    "Books": "Knjige",
+    "CameraImageUploadedFrom": "Nova fotografija je bila naložena z {0}",
+    "Channels": "Kanali",
+    "ChapterNameValue": "Poglavje {0}",
+    "Collections": "Zbirke",
     "DeviceOfflineWithName": "{0} has disconnected",
     "DeviceOfflineWithName": "{0} has disconnected",
-    "DeviceOnlineWithName": "{0} is connected",
-    "FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
-    "Favorites": "Favorites",
-    "Folders": "Folders",
-    "Genres": "Genres",
-    "HeaderAlbumArtists": "Album Artists",
-    "HeaderCameraUploads": "Camera Uploads",
-    "HeaderContinueWatching": "Continue Watching",
-    "HeaderFavoriteAlbums": "Favorite Albums",
-    "HeaderFavoriteArtists": "Favorite Artists",
-    "HeaderFavoriteEpisodes": "Favorite Episodes",
-    "HeaderFavoriteShows": "Favorite Shows",
-    "HeaderFavoriteSongs": "Favorite Songs",
-    "HeaderLiveTV": "Live TV",
-    "HeaderNextUp": "Next Up",
-    "HeaderRecordingGroups": "Recording Groups",
-    "HomeVideos": "Home videos",
-    "Inherit": "Inherit",
-    "ItemAddedWithName": "{0} was added to the library",
-    "ItemRemovedWithName": "{0} was removed from the library",
-    "LabelIpAddressValue": "Ip address: {0}",
-    "LabelRunningTimeValue": "Running time: {0}",
-    "Latest": "Latest",
-    "MessageApplicationUpdated": "Jellyfin Server has been updated",
-    "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
+    "DeviceOnlineWithName": "{0} je povezan",
+    "FailedLoginAttemptWithUserName": "Neuspešen poskus prijave z {0}",
+    "Favorites": "Priljubljeni",
+    "Folders": "Mape",
+    "Genres": "Zvrsti",
+    "HeaderAlbumArtists": "Izvajalci albuma",
+    "HeaderCameraUploads": "Posnetki kamere",
+    "HeaderContinueWatching": "Nadaljuj gledanje",
+    "HeaderFavoriteAlbums": "Priljubljeni albumi",
+    "HeaderFavoriteArtists": "Priljubljeni izvajalci",
+    "HeaderFavoriteEpisodes": "Priljubljene epizode",
+    "HeaderFavoriteShows": "Priljubljene serije",
+    "HeaderFavoriteSongs": "Priljubljene pesmi",
+    "HeaderLiveTV": "TV v živo",
+    "HeaderNextUp": "Sledi",
+    "HeaderRecordingGroups": "Zbirke posnetkov",
+    "HomeVideos": "Domači posnetki",
+    "Inherit": "Podeduj",
+    "ItemAddedWithName": "{0} je dodan v knjižnico",
+    "ItemRemovedWithName": "{0} je bil odstranjen iz knjižnice",
+    "LabelIpAddressValue": "IP naslov: {0}",
+    "LabelRunningTimeValue": "Čas trajanja: {0}",
+    "Latest": "Najnovejše",
+    "MessageApplicationUpdated": "Jellyfin strežnik je bil posodobljen",
+    "MessageApplicationUpdatedTo": "Jellyfin strežnik je bil posodobljen na {0}",
     "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
     "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
-    "MessageServerConfigurationUpdated": "Server configuration has been updated",
-    "MixedContent": "Mixed content",
-    "Movies": "Movies",
-    "Music": "Music",
-    "MusicVideos": "Music videos",
-    "NameInstallFailed": "{0} installation failed",
-    "NameSeasonNumber": "Season {0}",
-    "NameSeasonUnknown": "Season Unknown",
-    "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
-    "NotificationOptionApplicationUpdateAvailable": "Application update available",
-    "NotificationOptionApplicationUpdateInstalled": "Application update installed",
-    "NotificationOptionAudioPlayback": "Audio playback started",
-    "NotificationOptionAudioPlaybackStopped": "Audio playback stopped",
-    "NotificationOptionCameraImageUploaded": "Camera image uploaded",
-    "NotificationOptionInstallationFailed": "Installation failure",
-    "NotificationOptionNewLibraryContent": "New content added",
-    "NotificationOptionPluginError": "Plugin failure",
-    "NotificationOptionPluginInstalled": "Plugin installed",
-    "NotificationOptionPluginUninstalled": "Plugin uninstalled",
-    "NotificationOptionPluginUpdateInstalled": "Plugin update installed",
-    "NotificationOptionServerRestartRequired": "Server restart required",
+    "MessageServerConfigurationUpdated": "Nastavitve strežnika so bile posodobljene",
+    "MixedContent": "Razne vsebine",
+    "Movies": "Filmi",
+    "Music": "Glasba",
+    "MusicVideos": "Glasbeni posnetki",
+    "NameInstallFailed": "{0} namestitev neuspešna",
+    "NameSeasonNumber": "Sezona {0}",
+    "NameSeasonUnknown": "Season neznana",
+    "NewVersionIsAvailable": "Nova razničica Jellyfin strežnika je na voljo za prenos.",
+    "NotificationOptionApplicationUpdateAvailable": "Posodobitev aplikacije je na voljo",
+    "NotificationOptionApplicationUpdateInstalled": "Posodobitev aplikacije je bila nameščena",
+    "NotificationOptionAudioPlayback": "Predvajanje zvoka začeto",
+    "NotificationOptionAudioPlaybackStopped": "Predvajanje zvoka zaustavljeno",
+    "NotificationOptionCameraImageUploaded": "Posnetek kamere naložen",
+    "NotificationOptionInstallationFailed": "Napaka pri nameščanju",
+    "NotificationOptionNewLibraryContent": "Nove vsebine dodane",
+    "NotificationOptionPluginError": "Napaka dodatka",
+    "NotificationOptionPluginInstalled": "Dodatek nameščen",
+    "NotificationOptionPluginUninstalled": "Dodatek odstranjen",
+    "NotificationOptionPluginUpdateInstalled": "Posodobitev dodatka nameščena",
+    "NotificationOptionServerRestartRequired": "Potreben je ponovni zagon strežnika",
     "NotificationOptionTaskFailed": "Scheduled task failure",
     "NotificationOptionTaskFailed": "Scheduled task failure",
     "NotificationOptionUserLockedOut": "User locked out",
     "NotificationOptionUserLockedOut": "User locked out",
     "NotificationOptionVideoPlayback": "Video playback started",
     "NotificationOptionVideoPlayback": "Video playback started",

+ 18 - 18
Emby.Server.Implementations/Localization/Core/tr.json

@@ -1,12 +1,12 @@
 {
 {
-    "Albums": "Albums",
-    "AppDeviceValues": "App: {0}, Device: {1}",
-    "Application": "Application",
-    "Artists": "Artists",
-    "AuthenticationSucceededWithUserName": "{0} successfully authenticated",
-    "Books": "Books",
+    "Albums": "Albümler",
+    "AppDeviceValues": "Uygulama: {0}, Aygıt: {1}",
+    "Application": "Uygulama",
+    "Artists": "Sanatçılar",
+    "AuthenticationSucceededWithUserName": "{0} başarı ile giriş yaptı",
+    "Books": "Kitaplar",
     "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
     "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
-    "Channels": "Channels",
+    "Channels": "Kanallar",
     "ChapterNameValue": "Chapter {0}",
     "ChapterNameValue": "Chapter {0}",
     "Collections": "Collections",
     "Collections": "Collections",
     "DeviceOfflineWithName": "{0} has disconnected",
     "DeviceOfflineWithName": "{0} has disconnected",
@@ -17,8 +17,8 @@
     "Genres": "Genres",
     "Genres": "Genres",
     "HeaderAlbumArtists": "Album Artists",
     "HeaderAlbumArtists": "Album Artists",
     "HeaderCameraUploads": "Camera Uploads",
     "HeaderCameraUploads": "Camera Uploads",
-    "HeaderContinueWatching": "Continue Watching",
-    "HeaderFavoriteAlbums": "Favorite Albums",
+    "HeaderContinueWatching": "İzlemeye Devam Et",
+    "HeaderFavoriteAlbums": "Favori Albümler",
     "HeaderFavoriteArtists": "Favorite Artists",
     "HeaderFavoriteArtists": "Favorite Artists",
     "HeaderFavoriteEpisodes": "Favorite Episodes",
     "HeaderFavoriteEpisodes": "Favorite Episodes",
     "HeaderFavoriteShows": "Favori Showlar",
     "HeaderFavoriteShows": "Favori Showlar",
@@ -30,21 +30,21 @@
     "Inherit": "Inherit",
     "Inherit": "Inherit",
     "ItemAddedWithName": "{0} was added to the library",
     "ItemAddedWithName": "{0} was added to the library",
     "ItemRemovedWithName": "{0} was removed from the library",
     "ItemRemovedWithName": "{0} was removed from the library",
-    "LabelIpAddressValue": "Ip address: {0}",
-    "LabelRunningTimeValue": "Running time: {0}",
+    "LabelIpAddressValue": "Ip adresi: {0}",
+    "LabelRunningTimeValue": "Çalışma süresi: {0}",
     "Latest": "Latest",
     "Latest": "Latest",
-    "MessageApplicationUpdated": "Jellyfin Server has been updated",
+    "MessageApplicationUpdated": "Jellyfin Sunucusu güncellendi",
     "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
     "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
     "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
     "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
     "MessageServerConfigurationUpdated": "Server configuration has been updated",
     "MessageServerConfigurationUpdated": "Server configuration has been updated",
     "MixedContent": "Mixed content",
     "MixedContent": "Mixed content",
     "Movies": "Movies",
     "Movies": "Movies",
-    "Music": "Music",
-    "MusicVideos": "Music videos",
-    "NameInstallFailed": "{0} installation failed",
-    "NameSeasonNumber": "Season {0}",
-    "NameSeasonUnknown": "Season Unknown",
-    "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
+    "Music": "Müzik",
+    "MusicVideos": "Müzik videoları",
+    "NameInstallFailed": "{0} kurulum başarısız",
+    "NameSeasonNumber": "Sezon {0}",
+    "NameSeasonUnknown": "Bilinmeyen Sezon",
+    "NewVersionIsAvailable": "Jellyfin Sunucusunun yeni bir versiyonu indirmek için hazır.",
     "NotificationOptionApplicationUpdateAvailable": "Application update available",
     "NotificationOptionApplicationUpdateAvailable": "Application update available",
     "NotificationOptionApplicationUpdateInstalled": "Application update installed",
     "NotificationOptionApplicationUpdateInstalled": "Application update installed",
     "NotificationOptionAudioPlayback": "Audio playback started",
     "NotificationOptionAudioPlayback": "Audio playback started",

+ 3 - 3
Emby.Server.Implementations/Localization/Core/zh-CN.json

@@ -34,14 +34,14 @@
     "LabelRunningTimeValue": "运行时间:{0}",
     "LabelRunningTimeValue": "运行时间:{0}",
     "Latest": "最新",
     "Latest": "最新",
     "MessageApplicationUpdated": "Jellyfin 服务器已更新",
     "MessageApplicationUpdated": "Jellyfin 服务器已更新",
-    "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
+    "MessageApplicationUpdatedTo": "Jellyfin Server 的版本已更新为 {0}",
     "MessageNamedServerConfigurationUpdatedWithValue": "服务器配置 {0} 部分已更新",
     "MessageNamedServerConfigurationUpdatedWithValue": "服务器配置 {0} 部分已更新",
     "MessageServerConfigurationUpdated": "服务器配置已更新",
     "MessageServerConfigurationUpdated": "服务器配置已更新",
     "MixedContent": "混合内容",
     "MixedContent": "混合内容",
     "Movies": "电影",
     "Movies": "电影",
     "Music": "音乐",
     "Music": "音乐",
     "MusicVideos": "音乐视频",
     "MusicVideos": "音乐视频",
-    "NameInstallFailed": "{0} installation failed",
+    "NameInstallFailed": "{0} 安装失败",
     "NameSeasonNumber": "季 {0}",
     "NameSeasonNumber": "季 {0}",
     "NameSeasonUnknown": "未知季",
     "NameSeasonUnknown": "未知季",
     "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
     "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
@@ -70,7 +70,7 @@
     "ProviderValue": "提供商:{0}",
     "ProviderValue": "提供商:{0}",
     "ScheduledTaskFailedWithName": "{0} 已失败",
     "ScheduledTaskFailedWithName": "{0} 已失败",
     "ScheduledTaskStartedWithName": "{0} 已开始",
     "ScheduledTaskStartedWithName": "{0} 已开始",
-    "ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
+    "ServerNameNeedsToBeRestarted": "{0} 需要重新启动",
     "Shows": "节目",
     "Shows": "节目",
     "Songs": "歌曲",
     "Songs": "歌曲",
     "StartupEmbyServerIsLoading": "Jellyfin 服务器加载中。请稍后再试。",
     "StartupEmbyServerIsLoading": "Jellyfin 服务器加载中。请稍后再试。",

+ 41 - 144
Emby.Server.Implementations/Localization/LocalizationManager.cs

@@ -11,7 +11,6 @@ using MediaBrowser.Controller.Configuration;
 using MediaBrowser.Model.Entities;
 using MediaBrowser.Model.Entities;
 using MediaBrowser.Model.Extensions;
 using MediaBrowser.Model.Extensions;
 using MediaBrowser.Model.Globalization;
 using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.IO;
 using MediaBrowser.Model.Serialization;
 using MediaBrowser.Model.Serialization;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Logging;
 
 
@@ -35,7 +34,6 @@ namespace Emby.Server.Implementations.Localization
         private readonly Dictionary<string, Dictionary<string, ParentalRating>> _allParentalRatings =
         private readonly Dictionary<string, Dictionary<string, ParentalRating>> _allParentalRatings =
             new Dictionary<string, Dictionary<string, ParentalRating>>(StringComparer.OrdinalIgnoreCase);
             new Dictionary<string, Dictionary<string, ParentalRating>>(StringComparer.OrdinalIgnoreCase);
 
 
-        private readonly IFileSystem _fileSystem;
         private readonly IJsonSerializer _jsonSerializer;
         private readonly IJsonSerializer _jsonSerializer;
         private readonly ILogger _logger;
         private readonly ILogger _logger;
         private static readonly Assembly _assembly = typeof(LocalizationManager).Assembly;
         private static readonly Assembly _assembly = typeof(LocalizationManager).Assembly;
@@ -44,130 +42,65 @@ namespace Emby.Server.Implementations.Localization
         /// Initializes a new instance of the <see cref="LocalizationManager" /> class.
         /// Initializes a new instance of the <see cref="LocalizationManager" /> class.
         /// </summary>
         /// </summary>
         /// <param name="configurationManager">The configuration manager.</param>
         /// <param name="configurationManager">The configuration manager.</param>
-        /// <param name="fileSystem">The file system.</param>
         /// <param name="jsonSerializer">The json serializer.</param>
         /// <param name="jsonSerializer">The json serializer.</param>
+        /// <param name="loggerFactory">The logger factory</param>
         public LocalizationManager(
         public LocalizationManager(
             IServerConfigurationManager configurationManager,
             IServerConfigurationManager configurationManager,
-            IFileSystem fileSystem,
             IJsonSerializer jsonSerializer,
             IJsonSerializer jsonSerializer,
             ILoggerFactory loggerFactory)
             ILoggerFactory loggerFactory)
         {
         {
             _configurationManager = configurationManager;
             _configurationManager = configurationManager;
-            _fileSystem = fileSystem;
             _jsonSerializer = jsonSerializer;
             _jsonSerializer = jsonSerializer;
             _logger = loggerFactory.CreateLogger(nameof(LocalizationManager));
             _logger = loggerFactory.CreateLogger(nameof(LocalizationManager));
         }
         }
 
 
         public async Task LoadAll()
         public async Task LoadAll()
         {
         {
-            const string ratingsResource = "Emby.Server.Implementations.Localization.Ratings.";
-
-            Directory.CreateDirectory(LocalizationPath);
-
-            var existingFiles = GetRatingsFiles(LocalizationPath).Select(Path.GetFileName);
+            const string RatingsResource = "Emby.Server.Implementations.Localization.Ratings.";
 
 
             // Extract from the assembly
             // Extract from the assembly
             foreach (var resource in _assembly.GetManifestResourceNames())
             foreach (var resource in _assembly.GetManifestResourceNames())
             {
             {
-                if (!resource.StartsWith(ratingsResource))
+                if (!resource.StartsWith(RatingsResource, StringComparison.Ordinal))
                 {
                 {
                     continue;
                     continue;
                 }
                 }
 
 
-                string filename = "ratings-" + resource.Substring(ratingsResource.Length);
-
-                if (existingFiles.Contains(filename))
-                {
-                    continue;
-                }
+                string countryCode = resource.Substring(RatingsResource.Length, 2);
+                var dict = new Dictionary<string, ParentalRating>(StringComparer.OrdinalIgnoreCase);
 
 
-                using (var stream = _assembly.GetManifestResourceStream(resource))
+                using (var str = _assembly.GetManifestResourceStream(resource))
+                using (var reader = new StreamReader(str))
                 {
                 {
-                    string target = Path.Combine(LocalizationPath, filename);
-                    _logger.LogInformation("Extracting ratings to {0}", target);
-
-                    using (var fs = _fileSystem.GetFileStream(target, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
+                    string line;
+                    while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null)
                     {
                     {
-                        await stream.CopyToAsync(fs);
+                        if (string.IsNullOrWhiteSpace(line))
+                        {
+                            continue;
+                        }
+
+                        string[] parts = line.Split(',');
+                        if (parts.Length == 2
+                            && int.TryParse(parts[1], NumberStyles.Integer, UsCulture, out var value))
+                        {
+                            dict.Add(parts[0], new ParentalRating { Name = parts[0], Value = value });
+                        }
+#if DEBUG
+                        else
+                        {
+                            _logger.LogWarning("Malformed line in ratings file for country {CountryCode}", countryCode);
+                        }
+#endif
                     }
                     }
                 }
                 }
-            }
 
 
-            foreach (var file in GetRatingsFiles(LocalizationPath))
-            {
-                await LoadRatings(file);
+                _allParentalRatings[countryCode] = dict;
             }
             }
 
 
-            LoadAdditionalRatings();
-
-            await LoadCultures();
-        }
-
-        private void LoadAdditionalRatings()
-        {
-            LoadRatings("au", new[]
-            {
-                new ParentalRating("AU-G", 1),
-                new ParentalRating("AU-PG", 5),
-                new ParentalRating("AU-M", 6),
-                new ParentalRating("AU-MA15+", 7),
-                new ParentalRating("AU-M15+", 8),
-                new ParentalRating("AU-R18+", 9),
-                new ParentalRating("AU-X18+", 10),
-                new ParentalRating("AU-RC", 11)
-            });
-
-            LoadRatings("be", new[]
-            {
-                new ParentalRating("BE-AL", 1),
-                new ParentalRating("BE-MG6", 2),
-                new ParentalRating("BE-6", 3),
-                new ParentalRating("BE-9", 5),
-                new ParentalRating("BE-12", 6),
-                new ParentalRating("BE-16", 8)
-            });
-
-            LoadRatings("de", new[]
-            {
-                new ParentalRating("DE-0", 1),
-                new ParentalRating("FSK-0", 1),
-                new ParentalRating("DE-6", 5),
-                new ParentalRating("FSK-6", 5),
-                new ParentalRating("DE-12", 7),
-                new ParentalRating("FSK-12", 7),
-                new ParentalRating("DE-16", 8),
-                new ParentalRating("FSK-16", 8),
-                new ParentalRating("DE-18", 9),
-                new ParentalRating("FSK-18", 9)
-            });
-
-            LoadRatings("ru", new[]
-            {
-                new ParentalRating("RU-0+", 1),
-                new ParentalRating("RU-6+", 3),
-                new ParentalRating("RU-12+", 7),
-                new ParentalRating("RU-16+", 9),
-                new ParentalRating("RU-18+", 10)
-            });
-        }
-
-        private void LoadRatings(string country, ParentalRating[] ratings)
-        {
-            _allParentalRatings[country] = ratings.ToDictionary(i => i.Name);
+            await LoadCultures().ConfigureAwait(false);
         }
         }
 
 
-        private IEnumerable<string> GetRatingsFiles(string directory)
-            => _fileSystem.GetFilePaths(directory, false)
-                .Where(i => string.Equals(Path.GetExtension(i), ".csv", StringComparison.OrdinalIgnoreCase))
-                .Where(i => Path.GetFileName(i).StartsWith("ratings-", StringComparison.OrdinalIgnoreCase));
-
-        /// <summary>
-        /// Gets the localization path.
-        /// </summary>
-        /// <value>The localization path.</value>
-        public string LocalizationPath
-            => Path.Combine(_configurationManager.ApplicationPaths.ProgramDataPath, "localization");
-
         public string NormalizeFormKD(string text)
         public string NormalizeFormKD(string text)
             => text.Normalize(NormalizationForm.FormKD);
             => text.Normalize(NormalizationForm.FormKD);
 
 
@@ -184,14 +117,14 @@ namespace Emby.Server.Implementations.Localization
         {
         {
             List<CultureDto> list = new List<CultureDto>();
             List<CultureDto> list = new List<CultureDto>();
 
 
-            const string path = "Emby.Server.Implementations.Localization.iso6392.txt";
+            const string ResourcePath = "Emby.Server.Implementations.Localization.iso6392.txt";
 
 
-            using (var stream = _assembly.GetManifestResourceStream(path))
+            using (var stream = _assembly.GetManifestResourceStream(ResourcePath))
             using (var reader = new StreamReader(stream))
             using (var reader = new StreamReader(stream))
             {
             {
                 while (!reader.EndOfStream)
                 while (!reader.EndOfStream)
                 {
                 {
-                    var line = await reader.ReadLineAsync();
+                    var line = await reader.ReadLineAsync().ConfigureAwait(false);
 
 
                     if (string.IsNullOrWhiteSpace(line))
                     if (string.IsNullOrWhiteSpace(line))
                     {
                     {
@@ -217,11 +150,11 @@ namespace Emby.Server.Implementations.Localization
                         string[] threeletterNames;
                         string[] threeletterNames;
                         if (string.IsNullOrWhiteSpace(parts[1]))
                         if (string.IsNullOrWhiteSpace(parts[1]))
                         {
                         {
-                            threeletterNames = new [] { parts[0] };
+                            threeletterNames = new[] { parts[0] };
                         }
                         }
                         else
                         else
                         {
                         {
-                            threeletterNames = new [] { parts[0], parts[1] };
+                            threeletterNames = new[] { parts[0], parts[1] };
                         }
                         }
 
 
                         list.Add(new CultureDto
                         list.Add(new CultureDto
@@ -281,6 +214,7 @@ namespace Emby.Server.Implementations.Localization
         /// Gets the ratings.
         /// Gets the ratings.
         /// </summary>
         /// </summary>
         /// <param name="countryCode">The country code.</param>
         /// <param name="countryCode">The country code.</param>
+        /// <returns>The ratings</returns>
         private Dictionary<string, ParentalRating> GetRatings(string countryCode)
         private Dictionary<string, ParentalRating> GetRatings(string countryCode)
         {
         {
             _allParentalRatings.TryGetValue(countryCode, out var value);
             _allParentalRatings.TryGetValue(countryCode, out var value);
@@ -288,52 +222,14 @@ namespace Emby.Server.Implementations.Localization
             return value;
             return value;
         }
         }
 
 
-        /// <summary>
-        /// Loads the ratings.
-        /// </summary>
-        /// <param name="file">The file.</param>
-        /// <returns>Dictionary{System.StringParentalRating}.</returns>
-        private async Task LoadRatings(string file)
-        {
-            Dictionary<string, ParentalRating> dict
-                = new Dictionary<string, ParentalRating>(StringComparer.OrdinalIgnoreCase);
-
-            using (var str = File.OpenRead(file))
-            using (var reader = new StreamReader(str))
-            {
-                string line;
-                while ((line = await reader.ReadLineAsync()) != null)
-                {
-                    if (string.IsNullOrWhiteSpace(line))
-                    {
-                        continue;
-                    }
-
-                    string[] parts = line.Split(',');
-                    if (parts.Length == 2
-                        && int.TryParse(parts[1], NumberStyles.Integer, UsCulture, out var value))
-                    {
-                        dict.Add(parts[0], (new ParentalRating { Name = parts[0], Value = value }));
-                    }
-#if DEBUG
-                    else
-                    {
-                        _logger.LogWarning("Misformed line in {Path}", file);
-                    }
-#endif
-                }
-            }
-
-            var countryCode = Path.GetFileNameWithoutExtension(file).Split('-')[1];
-
-            _allParentalRatings[countryCode] = dict;
-        }
-
         private static readonly string[] _unratedValues = { "n/a", "unrated", "not rated" };
         private static readonly string[] _unratedValues = { "n/a", "unrated", "not rated" };
 
 
+        /// <inheritdoc />
         /// <summary>
         /// <summary>
         /// Gets the rating level.
         /// Gets the rating level.
         /// </summary>
         /// </summary>
+        /// <param name="rating">Rating field</param>
+        /// <returns>The rating level</returns>&gt;
         public int? GetRatingLevel(string rating)
         public int? GetRatingLevel(string rating)
         {
         {
             if (string.IsNullOrEmpty(rating))
             if (string.IsNullOrEmpty(rating))
@@ -405,6 +301,7 @@ namespace Emby.Server.Implementations.Localization
             {
             {
                 culture = _configurationManager.Configuration.UICulture;
                 culture = _configurationManager.Configuration.UICulture;
             }
             }
+
             if (string.IsNullOrEmpty(culture))
             if (string.IsNullOrEmpty(culture))
             {
             {
                 culture = DefaultCulture;
                 culture = DefaultCulture;
@@ -450,8 +347,8 @@ namespace Emby.Server.Implementations.Localization
 
 
             var namespaceName = GetType().Namespace + "." + prefix;
             var namespaceName = GetType().Namespace + "." + prefix;
 
 
-            await CopyInto(dictionary, namespaceName + "." + baseFilename);
-            await CopyInto(dictionary, namespaceName + "." + GetResourceFilename(culture));
+            await CopyInto(dictionary, namespaceName + "." + baseFilename).ConfigureAwait(false);
+            await CopyInto(dictionary, namespaceName + "." + GetResourceFilename(culture)).ConfigureAwait(false);
 
 
             return dictionary;
             return dictionary;
         }
         }
@@ -463,7 +360,7 @@ namespace Emby.Server.Implementations.Localization
                 // If a Culture doesn't have a translation the stream will be null and it defaults to en-us further up the chain
                 // If a Culture doesn't have a translation the stream will be null and it defaults to en-us further up the chain
                 if (stream != null)
                 if (stream != null)
                 {
                 {
-                    var dict = await _jsonSerializer.DeserializeFromStreamAsync<Dictionary<string, string>>(stream);
+                    var dict = await _jsonSerializer.DeserializeFromStreamAsync<Dictionary<string, string>>(stream).ConfigureAwait(false);
 
 
                     foreach (var key in dict.Keys)
                     foreach (var key in dict.Keys)
                     {
                     {

+ 8 - 0
Emby.Server.Implementations/Localization/Ratings/au.csv

@@ -0,0 +1,8 @@
+AU-G,1
+AU-PG,5
+AU-M,6
+AU-MA15+,7
+AU-M15+,8
+AU-R18+,9
+AU-X18+,10
+AU-RC,11

+ 6 - 0
Emby.Server.Implementations/Localization/Ratings/be.csv

@@ -0,0 +1,6 @@
+BE-AL,1
+BE-MG6,2
+BE-6,3
+BE-9,5
+BE-12,6
+BE-16,8

+ 10 - 0
Emby.Server.Implementations/Localization/Ratings/de.csv

@@ -0,0 +1,10 @@
+DE-0,1
+FSK-0,1
+DE-6,5
+FSK-6,5
+DE-12,7
+FSK-12,7
+DE-16,8
+FSK-16,8
+DE-18,9
+FSK-18,9

+ 5 - 0
Emby.Server.Implementations/Localization/Ratings/ru.csv

@@ -0,0 +1,5 @@
+RU-0+,1
+RU-6+,3
+RU-12+,7
+RU-16+,9
+RU-18+,10

+ 4 - 0
Emby.Server.Implementations/MediaEncoder/EncodingManager.cs

@@ -202,6 +202,10 @@ namespace Emby.Server.Implementations.MediaEncoder
         private static List<string> GetSavedChapterImages(Video video, IDirectoryService directoryService)
         private static List<string> GetSavedChapterImages(Video video, IDirectoryService directoryService)
         {
         {
             var path = GetChapterImagesPath(video);
             var path = GetChapterImagesPath(video);
+            if (!Directory.Exists(path))
+            {
+                return new List<string>();
+            }
 
 
             try
             try
             {
             {

+ 39 - 0
Emby.Server.Implementations/Middleware/WebSocketMiddleware.cs

@@ -0,0 +1,39 @@
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Logging;
+using WebSocketManager = Emby.Server.Implementations.WebSockets.WebSocketManager;
+
+namespace Emby.Server.Implementations.Middleware
+{
+    public class WebSocketMiddleware
+    {
+        private readonly RequestDelegate _next;
+        private readonly ILogger<WebSocketMiddleware> _logger;
+        private readonly WebSocketManager _webSocketManager;
+
+        public WebSocketMiddleware(RequestDelegate next, ILogger<WebSocketMiddleware> logger, WebSocketManager webSocketManager)
+        {
+            _next = next;
+            _logger = logger;
+            _webSocketManager = webSocketManager;
+        }
+
+        public async Task Invoke(HttpContext httpContext)
+        {
+            _logger.LogInformation("Handling request: " + httpContext.Request.Path);
+
+            if (httpContext.WebSockets.IsWebSocketRequest)
+            {
+                var webSocketContext = await httpContext.WebSockets.AcceptWebSocketAsync(null).ConfigureAwait(false);
+                if (webSocketContext != null)
+                {
+                    await _webSocketManager.OnWebSocketConnected(webSocketContext);
+                }
+            }
+            else
+            {
+                await _next.Invoke(httpContext);
+            }
+        }
+    }
+}

+ 0 - 66
Emby.Server.Implementations/Net/DisposableManagedObjectBase.cs

@@ -1,66 +0,0 @@
-using System;
-
-namespace Emby.Server.Implementations.Net
-{
-    /// <summary>
-    /// Correclty implements the <see cref="IDisposable"/> interface and pattern for an object containing only managed resources, and adds a few common niceities not on the interface such as an <see cref="IsDisposed"/> property.
-    /// </summary>
-    public abstract class DisposableManagedObjectBase : IDisposable
-    {
-
-        #region Public Methods
-
-        /// <summary>
-        /// Override this method and dispose any objects you own the lifetime of if disposing is true;
-        /// </summary>
-        /// <param name="disposing">True if managed objects should be disposed, if false, only unmanaged resources should be released.</param>
-        protected abstract void Dispose(bool disposing);
-
-
-        //TODO Remove and reimplement using the IsDisposed property directly.
-        /// <summary>
-        /// Throws an <see cref="ObjectDisposedException"/> if the <see cref="IsDisposed"/> property is true.
-        /// </summary>
-        /// <seealso cref="IsDisposed"/>
-        /// <exception cref="ObjectDisposedException">Thrown if the <see cref="IsDisposed"/> property is true.</exception>
-        /// <seealso cref="Dispose()"/>
-        protected virtual void ThrowIfDisposed()
-        {
-            if (IsDisposed) throw new ObjectDisposedException(GetType().Name);
-        }
-
-        #endregion
-
-        #region Public Properties
-
-        /// <summary>
-        /// Sets or returns a boolean indicating whether or not this instance has been disposed.
-        /// </summary>
-        /// <seealso cref="Dispose()"/>
-        public bool IsDisposed
-        {
-            get;
-            private set;
-        }
-
-        #endregion
-
-        #region IDisposable Members
-
-        /// <summary>
-        /// Disposes this object instance and all internally managed resources.
-        /// </summary>
-        /// <remarks>
-        /// <para>Sets the <see cref="IsDisposed"/> property to true. Does not explicitly throw an exception if called multiple times, but makes no promises about behaviour of derived classes.</para>
-        /// </remarks>
-        /// <seealso cref="IsDisposed"/>
-        public void Dispose()
-        {
-            IsDisposed = true;
-
-            Dispose(true);
-        }
-
-        #endregion
-    }
-}

+ 0 - 5
Emby.Server.Implementations/Net/IWebSocket.cs

@@ -45,9 +45,4 @@ namespace Emby.Server.Implementations.Net
         /// <returns>Task.</returns>
         /// <returns>Task.</returns>
         Task SendAsync(string text, bool endOfMessage, CancellationToken cancellationToken);
         Task SendAsync(string text, bool endOfMessage, CancellationToken cancellationToken);
     }
     }
-
-    public interface IMemoryWebSocket
-    {
-        Action<Memory<byte>, int> OnReceiveMemoryBytes { get; set; }
-    }
 }
 }

+ 41 - 93
Emby.Server.Implementations/Net/SocketFactory.cs

@@ -4,7 +4,6 @@ using System.Net;
 using System.Net.Sockets;
 using System.Net.Sockets;
 using Emby.Server.Implementations.Networking;
 using Emby.Server.Implementations.Networking;
 using MediaBrowser.Model.Net;
 using MediaBrowser.Model.Net;
-using Microsoft.Extensions.Logging;
 
 
 namespace Emby.Server.Implementations.Net
 namespace Emby.Server.Implementations.Net
 {
 {
@@ -19,7 +18,10 @@ namespace Emby.Server.Implementations.Net
 
 
         public ISocket CreateTcpSocket(IpAddressInfo remoteAddress, int remotePort)
         public ISocket CreateTcpSocket(IpAddressInfo remoteAddress, int remotePort)
         {
         {
-            if (remotePort < 0) throw new ArgumentException("remotePort cannot be less than zero.", nameof(remotePort));
+            if (remotePort < 0)
+            {
+                throw new ArgumentException("remotePort cannot be less than zero.", nameof(remotePort));
+            }
 
 
             var addressFamily = remoteAddress.AddressFamily == IpAddressFamily.InterNetwork
             var addressFamily = remoteAddress.AddressFamily == IpAddressFamily.InterNetwork
                 ? AddressFamily.InterNetwork
                 ? AddressFamily.InterNetwork
@@ -42,8 +44,7 @@ namespace Emby.Server.Implementations.Net
             }
             }
             catch
             catch
             {
             {
-                if (retVal != null)
-                    retVal.Dispose();
+                retVal?.Dispose();
 
 
                 throw;
                 throw;
             }
             }
@@ -55,7 +56,10 @@ namespace Emby.Server.Implementations.Net
         /// <param name="localPort">An integer specifying the local port to bind the acceptSocket to.</param>
         /// <param name="localPort">An integer specifying the local port to bind the acceptSocket to.</param>
         public ISocket CreateUdpSocket(int localPort)
         public ISocket CreateUdpSocket(int localPort)
         {
         {
-            if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
+            if (localPort < 0)
+            {
+                throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
+            }
 
 
             var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
             var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
             try
             try
@@ -65,8 +69,7 @@ namespace Emby.Server.Implementations.Net
             }
             }
             catch
             catch
             {
             {
-                if (retVal != null)
-                    retVal.Dispose();
+                retVal?.Dispose();
 
 
                 throw;
                 throw;
             }
             }
@@ -74,7 +77,10 @@ namespace Emby.Server.Implementations.Net
 
 
         public ISocket CreateUdpBroadcastSocket(int localPort)
         public ISocket CreateUdpBroadcastSocket(int localPort)
         {
         {
-            if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
+            if (localPort < 0)
+            {
+                throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
+            }
 
 
             var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
             var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
             try
             try
@@ -86,8 +92,7 @@ namespace Emby.Server.Implementations.Net
             }
             }
             catch
             catch
             {
             {
-                if (retVal != null)
-                    retVal.Dispose();
+                retVal?.Dispose();
 
 
                 throw;
                 throw;
             }
             }
@@ -99,7 +104,10 @@ namespace Emby.Server.Implementations.Net
         /// <returns>An implementation of the <see cref="ISocket"/> interface used by RSSDP components to perform acceptSocket operations.</returns>
         /// <returns>An implementation of the <see cref="ISocket"/> interface used by RSSDP components to perform acceptSocket operations.</returns>
         public ISocket CreateSsdpUdpSocket(IpAddressInfo localIpAddress, int localPort)
         public ISocket CreateSsdpUdpSocket(IpAddressInfo localIpAddress, int localPort)
         {
         {
-            if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
+            if (localPort < 0)
+            {
+                throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
+            }
 
 
             var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
             var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
             try
             try
@@ -114,8 +122,7 @@ namespace Emby.Server.Implementations.Net
             }
             }
             catch
             catch
             {
             {
-                if (retVal != null)
-                    retVal.Dispose();
+                retVal?.Dispose();
 
 
                 throw;
                 throw;
             }
             }
@@ -130,10 +137,25 @@ namespace Emby.Server.Implementations.Net
         /// <returns></returns>
         /// <returns></returns>
         public ISocket CreateUdpMulticastSocket(string ipAddress, int multicastTimeToLive, int localPort)
         public ISocket CreateUdpMulticastSocket(string ipAddress, int multicastTimeToLive, int localPort)
         {
         {
-            if (ipAddress == null) throw new ArgumentNullException(nameof(ipAddress));
-            if (ipAddress.Length == 0) throw new ArgumentException("ipAddress cannot be an empty string.", nameof(ipAddress));
-            if (multicastTimeToLive <= 0) throw new ArgumentException("multicastTimeToLive cannot be zero or less.", nameof(multicastTimeToLive));
-            if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
+            if (ipAddress == null)
+            {
+                throw new ArgumentNullException(nameof(ipAddress));
+            }
+
+            if (ipAddress.Length == 0)
+            {
+                throw new ArgumentException("ipAddress cannot be an empty string.", nameof(ipAddress));
+            }
+
+            if (multicastTimeToLive <= 0)
+            {
+                throw new ArgumentException("multicastTimeToLive cannot be zero or less.", nameof(multicastTimeToLive));
+            }
+
+            if (localPort < 0)
+            {
+                throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
+            }
 
 
             var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
             var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
 
 
@@ -172,87 +194,13 @@ namespace Emby.Server.Implementations.Net
             }
             }
             catch
             catch
             {
             {
-                if (retVal != null)
-                    retVal.Dispose();
+                retVal?.Dispose();
 
 
                 throw;
                 throw;
             }
             }
         }
         }
 
 
         public Stream CreateNetworkStream(ISocket socket, bool ownsSocket)
         public Stream CreateNetworkStream(ISocket socket, bool ownsSocket)
-        {
-            var netSocket = (UdpSocket)socket;
-
-            return new SocketStream(netSocket.Socket, ownsSocket);
-        }
+            => new NetworkStream(((UdpSocket)socket).Socket, ownsSocket);
     }
     }
-
-    public class SocketStream : Stream
-    {
-        private readonly Socket _socket;
-
-        public SocketStream(Socket socket, bool ownsSocket)
-        {
-            _socket = socket;
-        }
-
-        public override void Flush()
-        {
-        }
-
-        public override bool CanRead => true;
-
-        public override bool CanSeek => false;
-
-        public override bool CanWrite => true;
-
-        public override long Length => throw new NotImplementedException();
-
-        public override long Position
-        {
-            get => throw new NotImplementedException();
-            set => throw new NotImplementedException();
-        }
-
-        public override void Write(byte[] buffer, int offset, int count)
-        {
-            _socket.Send(buffer, offset, count, SocketFlags.None);
-        }
-
-        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
-        {
-            return _socket.BeginSend(buffer, offset, count, SocketFlags.None, callback, state);
-        }
-
-        public override void EndWrite(IAsyncResult asyncResult)
-        {
-            _socket.EndSend(asyncResult);
-        }
-
-        public override void SetLength(long value)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override long Seek(long offset, SeekOrigin origin)
-        {
-            throw new NotImplementedException();
-        }
-
-        public override int Read(byte[] buffer, int offset, int count)
-        {
-            return _socket.Receive(buffer, offset, count, SocketFlags.None);
-        }
-
-        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
-        {
-            return _socket.BeginReceive(buffer, offset, count, SocketFlags.None, callback, state);
-        }
-
-        public override int EndRead(IAsyncResult asyncResult)
-        {
-            return _socket.EndReceive(asyncResult);
-        }
-    }
-
 }
 }

+ 37 - 35
Emby.Server.Implementations/Net/UdpSocket.cs

@@ -11,12 +11,15 @@ namespace Emby.Server.Implementations.Net
     // THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
     // THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
     // Be careful to check any changes compile and work for all platform projects it is shared in.
     // Be careful to check any changes compile and work for all platform projects it is shared in.
 
 
-    public sealed class UdpSocket : DisposableManagedObjectBase, ISocket
+    public sealed class UdpSocket : ISocket, IDisposable
     {
     {
-        private Socket _Socket;
-        private int _LocalPort;
+        private Socket _socket;
+        private int _localPort;
+        private bool _disposed = false;
 
 
-        public Socket Socket => _Socket;
+        public Socket Socket => _socket;
+
+        public IpAddressInfo LocalIPAddress { get; }
 
 
         private readonly SocketAsyncEventArgs _receiveSocketAsyncEventArgs = new SocketAsyncEventArgs()
         private readonly SocketAsyncEventArgs _receiveSocketAsyncEventArgs = new SocketAsyncEventArgs()
         {
         {
@@ -35,11 +38,11 @@ namespace Emby.Server.Implementations.Net
         {
         {
             if (socket == null) throw new ArgumentNullException(nameof(socket));
             if (socket == null) throw new ArgumentNullException(nameof(socket));
 
 
-            _Socket = socket;
-            _LocalPort = localPort;
+            _socket = socket;
+            _localPort = localPort;
             LocalIPAddress = NetworkManager.ToIpAddressInfo(ip);
             LocalIPAddress = NetworkManager.ToIpAddressInfo(ip);
 
 
-            _Socket.Bind(new IPEndPoint(ip, _LocalPort));
+            _socket.Bind(new IPEndPoint(ip, _localPort));
 
 
             InitReceiveSocketAsyncEventArgs();
             InitReceiveSocketAsyncEventArgs();
         }
         }
@@ -101,32 +104,26 @@ namespace Emby.Server.Implementations.Net
         {
         {
             if (socket == null) throw new ArgumentNullException(nameof(socket));
             if (socket == null) throw new ArgumentNullException(nameof(socket));
 
 
-            _Socket = socket;
-            _Socket.Connect(NetworkManager.ToIPEndPoint(endPoint));
+            _socket = socket;
+            _socket.Connect(NetworkManager.ToIPEndPoint(endPoint));
 
 
             InitReceiveSocketAsyncEventArgs();
             InitReceiveSocketAsyncEventArgs();
         }
         }
 
 
-        public IpAddressInfo LocalIPAddress
-        {
-            get;
-            private set;
-        }
-
         public IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback)
         public IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback)
         {
         {
             ThrowIfDisposed();
             ThrowIfDisposed();
 
 
             EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0);
             EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0);
 
 
-            return _Socket.BeginReceiveFrom(buffer, offset, count, SocketFlags.None, ref receivedFromEndPoint, callback, buffer);
+            return _socket.BeginReceiveFrom(buffer, offset, count, SocketFlags.None, ref receivedFromEndPoint, callback, buffer);
         }
         }
 
 
         public int Receive(byte[] buffer, int offset, int count)
         public int Receive(byte[] buffer, int offset, int count)
         {
         {
             ThrowIfDisposed();
             ThrowIfDisposed();
 
 
-            return _Socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
+            return _socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
         }
         }
 
 
         public SocketReceiveResult EndReceive(IAsyncResult result)
         public SocketReceiveResult EndReceive(IAsyncResult result)
@@ -136,7 +133,7 @@ namespace Emby.Server.Implementations.Net
             var sender = new IPEndPoint(IPAddress.Any, 0);
             var sender = new IPEndPoint(IPAddress.Any, 0);
             var remoteEndPoint = (EndPoint)sender;
             var remoteEndPoint = (EndPoint)sender;
 
 
-            var receivedBytes = _Socket.EndReceiveFrom(result, ref remoteEndPoint);
+            var receivedBytes = _socket.EndReceiveFrom(result, ref remoteEndPoint);
 
 
             var buffer = (byte[])result.AsyncState;
             var buffer = (byte[])result.AsyncState;
 
 
@@ -236,35 +233,40 @@ namespace Emby.Server.Implementations.Net
 
 
             var ipEndPoint = NetworkManager.ToIPEndPoint(endPoint);
             var ipEndPoint = NetworkManager.ToIPEndPoint(endPoint);
 
 
-            return _Socket.BeginSendTo(buffer, offset, size, SocketFlags.None, ipEndPoint, callback, state);
+            return _socket.BeginSendTo(buffer, offset, size, SocketFlags.None, ipEndPoint, callback, state);
         }
         }
 
 
         public int EndSendTo(IAsyncResult result)
         public int EndSendTo(IAsyncResult result)
         {
         {
             ThrowIfDisposed();
             ThrowIfDisposed();
 
 
-            return _Socket.EndSendTo(result);
+            return _socket.EndSendTo(result);
         }
         }
 
 
-        protected override void Dispose(bool disposing)
+        private void ThrowIfDisposed()
         {
         {
-            if (disposing)
+            if (_disposed)
             {
             {
-                var socket = _Socket;
-                if (socket != null)
-                    socket.Dispose();
+                throw new ObjectDisposedException(nameof(UdpSocket));
+            }
+        }
 
 
-                var tcs = _currentReceiveTaskCompletionSource;
-                if (tcs != null)
-                {
-                    tcs.TrySetCanceled();
-                }
-                var sendTcs = _currentSendTaskCompletionSource;
-                if (sendTcs != null)
-                {
-                    sendTcs.TrySetCanceled();
-                }
+        public void Dispose()
+        {
+            if (_disposed)
+            {
+                return;
             }
             }
+
+            _socket?.Dispose();
+            _currentReceiveTaskCompletionSource?.TrySetCanceled();
+            _currentSendTaskCompletionSource?.TrySetCanceled();
+
+            _socket = null;
+            _currentReceiveTaskCompletionSource = null;
+            _currentSendTaskCompletionSource = null;
+
+            _disposed = true;
         }
         }
 
 
         private static IpEndPointInfo ToIpEndPointInfo(IPEndPoint endpoint)
         private static IpEndPointInfo ToIpEndPointInfo(IPEndPoint endpoint)

이 변경점에서 너무 많은 파일들이 변경되어 몇몇 파일들은 표시되지 않았습니다.