mirror of
https://github.com/jellyfin/jellyfin.git
synced 2024-11-15 18:08:53 -07:00
Merge branch 'master' into subtitle-display-title
This commit is contained in:
commit
480a6607e2
192
.ci/azure-pipelines.yml
Normal file
192
.ci/azure-pipelines.yml
Normal file
@ -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
|
||||
|
||||
|
81
.drone.yml
81
.drone.yml
@ -28,84 +28,3 @@ steps:
|
||||
commands:
|
||||
- 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
|
||||
|
@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[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: AssemblyCulture("")]
|
||||
[assembly: NeutralResourcesLanguage("en")]
|
||||
|
@ -23,6 +23,7 @@
|
||||
- [fruhnow](https://github.com/fruhnow)
|
||||
- [Lynxy](https://github.com/Lynxy)
|
||||
- [fasheng](https://github.com/fasheng)
|
||||
- [ploughpuff](https://github.com/ploughpuff)
|
||||
|
||||
# Emby Contributors
|
||||
|
||||
|
@ -15,7 +15,7 @@ RUN apt-get update \
|
||||
libfontconfig1 \
|
||||
&& apt-get clean autoclean \
|
||||
&& apt-get autoremove \
|
||||
&& rm -rf /var/lib/{apt,dpkg,cache,log} \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& mkdir -p /cache /config /media \
|
||||
&& chmod 777 /cache /config /media
|
||||
COPY --from=ffmpeg / /
|
||||
@ -31,5 +31,4 @@ VOLUME /cache /config /media
|
||||
ENTRYPOINT dotnet /jellyfin/jellyfin.dll \
|
||||
--datadir /config \
|
||||
--cachedir /cache \
|
||||
--ffmpeg /usr/local/bin/ffmpeg \
|
||||
--ffprobe /usr/local/bin/ffprobe
|
||||
--ffmpeg /usr/local/bin/ffmpeg
|
||||
|
@ -25,6 +25,7 @@ FROM microsoft/dotnet:${DOTNET_VERSION}-runtime-stretch-slim-arm32v7
|
||||
COPY --from=qemu_extract qemu-arm-static /usr/bin
|
||||
RUN apt-get update \
|
||||
&& apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& mkdir -p /cache /config /media \
|
||||
&& chmod 777 /cache /config /media
|
||||
COPY --from=builder /jellyfin /jellyfin
|
||||
@ -39,5 +40,4 @@ VOLUME /cache /config /media
|
||||
ENTRYPOINT dotnet /jellyfin/jellyfin.dll \
|
||||
--datadir /config \
|
||||
--cachedir /cache \
|
||||
--ffmpeg /usr/bin/ffmpeg \
|
||||
--ffprobe /usr/bin/ffprobe
|
||||
--ffmpeg /usr/bin/ffmpeg
|
||||
|
@ -26,6 +26,7 @@ FROM microsoft/dotnet:${DOTNET_VERSION}-runtime-stretch-slim-arm64v8
|
||||
COPY --from=qemu_extract qemu-aarch64-static /usr/bin
|
||||
RUN apt-get update \
|
||||
&& apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& mkdir -p /cache /config /media \
|
||||
&& chmod 777 /cache /config /media
|
||||
COPY --from=builder /jellyfin /jellyfin
|
||||
@ -40,5 +41,4 @@ VOLUME /cache /config /media
|
||||
ENTRYPOINT dotnet /jellyfin/jellyfin.dll \
|
||||
--datadir /config \
|
||||
--cachedir /cache \
|
||||
--ffmpeg /usr/bin/ffmpeg \
|
||||
--ffprobe /usr/bin/ffprobe
|
||||
--ffmpeg /usr/bin/ffmpeg
|
||||
|
@ -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
|
||||
{
|
||||
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -25,13 +25,10 @@ namespace DvdLib.Ifo
|
||||
public byte[] SubpictureStreamControl { get; private set; } // 32*4 entries
|
||||
|
||||
private ushort _nextProgramNumber;
|
||||
public readonly ProgramChain Next;
|
||||
|
||||
private ushort _prevProgramNumber;
|
||||
public readonly ProgramChain Previous;
|
||||
|
||||
private ushort _goupProgramNumber;
|
||||
public readonly ProgramChain Goup; // ?? maybe Group
|
||||
|
||||
public ProgramPlaybackMode PlaybackMode { 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
|
||||
|
||||
private ushort _commandTableOffset;
|
||||
public readonly ProgramChainCommandTable CommandTable;
|
||||
|
||||
private ushort _programMapOffset;
|
||||
private ushort _cellPlaybackOffset;
|
||||
|
@ -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()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[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: AssemblyCulture("")]
|
||||
[assembly: NeutralResourcesLanguage("en")]
|
||||
|
@ -136,7 +136,7 @@ namespace Emby.Dlna.Api
|
||||
{
|
||||
var url = Request.AbsoluteUri;
|
||||
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 cacheKey = Request.RawUrl.GetMD5();
|
||||
@ -147,21 +147,21 @@ namespace Emby.Dlna.Api
|
||||
|
||||
public object Get(GetContentDirectory request)
|
||||
{
|
||||
var xml = ContentDirectory.GetServiceXml(Request.Headers.ToDictionary());
|
||||
var xml = ContentDirectory.GetServiceXml();
|
||||
|
||||
return _resultFactory.GetResult(Request, xml, XMLContentType);
|
||||
}
|
||||
|
||||
public object Get(GetMediaReceiverRegistrar request)
|
||||
{
|
||||
var xml = MediaReceiverRegistrar.GetServiceXml(Request.Headers.ToDictionary());
|
||||
var xml = MediaReceiverRegistrar.GetServiceXml();
|
||||
|
||||
return _resultFactory.GetResult(Request, xml, XMLContentType);
|
||||
}
|
||||
|
||||
public object Get(GetConnnectionManager request)
|
||||
{
|
||||
var xml = ConnectionManager.GetServiceXml(Request.Headers.ToDictionary());
|
||||
var xml = ConnectionManager.GetServiceXml();
|
||||
|
||||
return _resultFactory.GetResult(Request, xml, XMLContentType);
|
||||
}
|
||||
@ -193,7 +193,7 @@ namespace Emby.Dlna.Api
|
||||
|
||||
return service.ProcessControlRequest(new ControlRequest
|
||||
{
|
||||
Headers = Request.Headers.ToDictionary(),
|
||||
Headers = Request.Headers,
|
||||
InputXml = requestStream,
|
||||
TargetServerUuId = id,
|
||||
RequestedUrl = Request.AbsoluteUri
|
||||
|
@ -1,9 +1,7 @@
|
||||
using System.Collections.Generic;
|
||||
using Emby.Dlna.Service;
|
||||
using MediaBrowser.Common.Net;
|
||||
using MediaBrowser.Controller.Configuration;
|
||||
using MediaBrowser.Controller.Dlna;
|
||||
using MediaBrowser.Model.Xml;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Emby.Dlna.ConnectionManager
|
||||
@ -13,18 +11,16 @@ namespace Emby.Dlna.ConnectionManager
|
||||
private readonly IDlnaManager _dlna;
|
||||
private readonly ILogger _logger;
|
||||
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)
|
||||
{
|
||||
_dlna = dlna;
|
||||
_config = config;
|
||||
_logger = logger;
|
||||
XmlReaderSettingsFactory = xmlReaderSettingsFactory;
|
||||
}
|
||||
|
||||
public string GetServiceXml(IDictionary<string, string> headers)
|
||||
public string GetServiceXml()
|
||||
{
|
||||
return new ConnectionManagerXmlBuilder().GetXml();
|
||||
}
|
||||
@ -34,7 +30,7 @@ namespace Emby.Dlna.ConnectionManager
|
||||
var profile = _dlna.GetProfile(request.Headers) ??
|
||||
_dlna.GetDefaultProfile();
|
||||
|
||||
return new ControlHandler(_config, _logger, XmlReaderSettingsFactory, profile).ProcessControlRequest(request);
|
||||
return new ControlHandler(_config, _logger, profile).ProcessControlRequest(request);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -4,7 +4,6 @@ using Emby.Dlna.Service;
|
||||
using MediaBrowser.Common.Extensions;
|
||||
using MediaBrowser.Controller.Configuration;
|
||||
using MediaBrowser.Model.Dlna;
|
||||
using MediaBrowser.Model.Xml;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
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;
|
||||
}
|
||||
|
@ -11,7 +11,6 @@ using MediaBrowser.Controller.MediaEncoding;
|
||||
using MediaBrowser.Controller.TV;
|
||||
using MediaBrowser.Model.Dlna;
|
||||
using MediaBrowser.Model.Globalization;
|
||||
using MediaBrowser.Model.Xml;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Emby.Dlna.ContentDirectory
|
||||
@ -28,7 +27,6 @@ namespace Emby.Dlna.ContentDirectory
|
||||
private readonly IMediaSourceManager _mediaSourceManager;
|
||||
private readonly IUserViewManager _userViewManager;
|
||||
private readonly IMediaEncoder _mediaEncoder;
|
||||
protected readonly IXmlReaderSettingsFactory XmlReaderSettingsFactory;
|
||||
private readonly ITVSeriesManager _tvSeriesManager;
|
||||
|
||||
public ContentDirectory(IDlnaManager dlna,
|
||||
@ -38,7 +36,12 @@ namespace Emby.Dlna.ContentDirectory
|
||||
IServerConfigurationManager config,
|
||||
IUserManager userManager,
|
||||
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)
|
||||
{
|
||||
_dlna = dlna;
|
||||
@ -51,7 +54,6 @@ namespace Emby.Dlna.ContentDirectory
|
||||
_mediaSourceManager = mediaSourceManager;
|
||||
_userViewManager = userViewManager;
|
||||
_mediaEncoder = mediaEncoder;
|
||||
XmlReaderSettingsFactory = xmlReaderSettingsFactory;
|
||||
_tvSeriesManager = tvSeriesManager;
|
||||
}
|
||||
|
||||
@ -65,7 +67,7 @@ namespace Emby.Dlna.ContentDirectory
|
||||
}
|
||||
}
|
||||
|
||||
public string GetServiceXml(IDictionary<string, string> headers)
|
||||
public string GetServiceXml()
|
||||
{
|
||||
return new ContentDirectoryXmlBuilder().GetXml();
|
||||
}
|
||||
@ -94,7 +96,6 @@ namespace Emby.Dlna.ContentDirectory
|
||||
_mediaSourceManager,
|
||||
_userViewManager,
|
||||
_mediaEncoder,
|
||||
XmlReaderSettingsFactory,
|
||||
_tvSeriesManager)
|
||||
.ProcessControlRequest(request);
|
||||
}
|
||||
|
@ -25,7 +25,6 @@ using MediaBrowser.Model.Dlna;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.Globalization;
|
||||
using MediaBrowser.Model.Querying;
|
||||
using MediaBrowser.Model.Xml;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Emby.Dlna.ContentDirectory
|
||||
@ -51,8 +50,22 @@ namespace Emby.Dlna.ContentDirectory
|
||||
|
||||
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;
|
||||
_userDataManager = userDataManager;
|
||||
|
@ -1,11 +1,11 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Emby.Dlna
|
||||
{
|
||||
public class ControlRequest
|
||||
{
|
||||
public IDictionary<string, string> Headers { get; set; }
|
||||
public IHeaderDictionary Headers { get; set; }
|
||||
|
||||
public Stream InputXml { get; set; }
|
||||
|
||||
@ -15,7 +15,7 @@ namespace Emby.Dlna
|
||||
|
||||
public ControlRequest()
|
||||
{
|
||||
Headers = new Dictionary<string, string>();
|
||||
Headers = new HeaderDictionary();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -17,7 +17,9 @@ using MediaBrowser.Model.Dlna;
|
||||
using MediaBrowser.Model.Drawing;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Primitives;
|
||||
|
||||
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)
|
||||
{
|
||||
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));
|
||||
|
||||
if (profile != null)
|
||||
@ -228,12 +227,12 @@ namespace Emby.Dlna
|
||||
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));
|
||||
}
|
||||
|
||||
private bool IsMatch(IDictionary<string, string> headers, HttpHeaderInfo header)
|
||||
private bool IsMatch(IHeaderDictionary headers, HttpHeaderInfo header)
|
||||
{
|
||||
// Handle invalid user setup
|
||||
if (string.IsNullOrEmpty(header.Name))
|
||||
@ -241,14 +240,14 @@ namespace Emby.Dlna
|
||||
return false;
|
||||
}
|
||||
|
||||
if (headers.TryGetValue(header.Name, out string value))
|
||||
if (headers.TryGetValue(header.Name, out StringValues value))
|
||||
{
|
||||
switch (header.Match)
|
||||
{
|
||||
case HeaderMatchType.Equals:
|
||||
return string.Equals(value, header.Value, StringComparison.OrdinalIgnoreCase);
|
||||
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);
|
||||
return isMatch;
|
||||
case HeaderMatchType.Regex:
|
||||
@ -494,7 +493,7 @@ namespace Emby.Dlna
|
||||
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) ??
|
||||
GetDefaultProfile();
|
||||
|
@ -58,4 +58,9 @@
|
||||
<EmbeddedResource Include="Profiles\Xml\Xbox One.xml" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.WebUtilities" Version="2.2.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
@ -1,5 +1,3 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Emby.Dlna
|
||||
{
|
||||
public interface IUpnpService
|
||||
@ -7,9 +5,8 @@ namespace Emby.Dlna
|
||||
/// <summary>
|
||||
/// Gets the content directory XML.
|
||||
/// </summary>
|
||||
/// <param name="headers">The headers.</param>
|
||||
/// <returns>System.String.</returns>
|
||||
string GetServiceXml(IDictionary<string, string> headers);
|
||||
string GetServiceXml();
|
||||
|
||||
/// <summary>
|
||||
/// Processes the control request.
|
||||
|
@ -1,5 +1,4 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Emby.Dlna.PlayTo;
|
||||
@ -20,10 +19,10 @@ using MediaBrowser.Model.Dlna;
|
||||
using MediaBrowser.Model.Globalization;
|
||||
using MediaBrowser.Model.Net;
|
||||
using MediaBrowser.Model.System;
|
||||
using MediaBrowser.Model.Xml;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Rssdp;
|
||||
using Rssdp.Infrastructure;
|
||||
using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
|
||||
|
||||
namespace Emby.Dlna.Main
|
||||
{
|
||||
@ -48,9 +47,8 @@ namespace Emby.Dlna.Main
|
||||
private readonly IDeviceDiscovery _deviceDiscovery;
|
||||
|
||||
private SsdpDevicePublisher _Publisher;
|
||||
|
||||
|
||||
private readonly ISocketFactory _socketFactory;
|
||||
private readonly IEnvironmentInfo _environmentInfo;
|
||||
private readonly INetworkManager _networkManager;
|
||||
|
||||
private ISsdpCommunicationsServer _communicationsServer;
|
||||
@ -76,10 +74,8 @@ namespace Emby.Dlna.Main
|
||||
IDeviceDiscovery deviceDiscovery,
|
||||
IMediaEncoder mediaEncoder,
|
||||
ISocketFactory socketFactory,
|
||||
IEnvironmentInfo environmentInfo,
|
||||
INetworkManager networkManager,
|
||||
IUserViewManager userViewManager,
|
||||
IXmlReaderSettingsFactory xmlReaderSettingsFactory,
|
||||
ITVSeriesManager tvSeriesManager)
|
||||
{
|
||||
_config = config;
|
||||
@ -96,11 +92,11 @@ namespace Emby.Dlna.Main
|
||||
_deviceDiscovery = deviceDiscovery;
|
||||
_mediaEncoder = mediaEncoder;
|
||||
_socketFactory = socketFactory;
|
||||
_environmentInfo = environmentInfo;
|
||||
_networkManager = networkManager;
|
||||
_logger = loggerFactory.CreateLogger("Dlna");
|
||||
|
||||
ContentDirectory = new ContentDirectory.ContentDirectory(dlnaManager,
|
||||
ContentDirectory = new ContentDirectory.ContentDirectory(
|
||||
dlnaManager,
|
||||
userDataManager,
|
||||
imageProcessor,
|
||||
libraryManager,
|
||||
@ -112,12 +108,11 @@ namespace Emby.Dlna.Main
|
||||
mediaSourceManager,
|
||||
userViewManager,
|
||||
mediaEncoder,
|
||||
xmlReaderSettingsFactory,
|
||||
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;
|
||||
}
|
||||
|
||||
@ -169,8 +164,8 @@ namespace Emby.Dlna.Main
|
||||
{
|
||||
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)
|
||||
{
|
||||
@ -230,7 +225,7 @@ namespace Emby.Dlna.Main
|
||||
|
||||
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.SupportPnpRootDevice = false;
|
||||
|
||||
|
@ -3,7 +3,6 @@ using System.Collections.Generic;
|
||||
using Emby.Dlna.Service;
|
||||
using MediaBrowser.Common.Extensions;
|
||||
using MediaBrowser.Controller.Configuration;
|
||||
using MediaBrowser.Model.Xml;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
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)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using Emby.Dlna.Service;
|
||||
using MediaBrowser.Common.Net;
|
||||
using MediaBrowser.Controller.Configuration;
|
||||
using MediaBrowser.Model.Xml;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Emby.Dlna.MediaReceiverRegistrar
|
||||
@ -10,16 +8,14 @@ namespace Emby.Dlna.MediaReceiverRegistrar
|
||||
public class MediaReceiverRegistrar : BaseService, IMediaReceiverRegistrar
|
||||
{
|
||||
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)
|
||||
{
|
||||
_config = config;
|
||||
XmlReaderSettingsFactory = xmlReaderSettingsFactory;
|
||||
}
|
||||
|
||||
public string GetServiceXml(IDictionary<string, string> headers)
|
||||
public string GetServiceXml()
|
||||
{
|
||||
return new MediaReceiverRegistrarXmlBuilder().GetXml();
|
||||
}
|
||||
@ -28,7 +24,7 @@ namespace Emby.Dlna.MediaReceiverRegistrar
|
||||
{
|
||||
return new ControlHandler(
|
||||
_config,
|
||||
Logger, XmlReaderSettingsFactory)
|
||||
Logger)
|
||||
.ProcessControlRequest(request);
|
||||
}
|
||||
}
|
||||
|
@ -1,9 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace Emby.Dlna.PlayTo
|
||||
{
|
||||
public class CurrentIdEventArgs : EventArgs
|
||||
{
|
||||
public string Id { get; set; }
|
||||
}
|
||||
}
|
@ -1126,6 +1126,11 @@ namespace Emby.Dlna.PlayTo
|
||||
|
||||
private void OnPlaybackStart(uBaseObject mediaInfo)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(mediaInfo.Url))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
PlaybackStart?.Invoke(this, new PlaybackStartEventArgs
|
||||
{
|
||||
MediaInfo = mediaInfo
|
||||
@ -1134,8 +1139,7 @@ namespace Emby.Dlna.PlayTo
|
||||
|
||||
private void OnPlaybackProgress(uBaseObject mediaInfo)
|
||||
{
|
||||
var mediaUrl = mediaInfo.Url;
|
||||
if (string.IsNullOrWhiteSpace(mediaUrl))
|
||||
if (string.IsNullOrWhiteSpace(mediaInfo.Url))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@ -1148,7 +1152,6 @@ namespace Emby.Dlna.PlayTo
|
||||
|
||||
private void OnPlaybackStop(uBaseObject mediaInfo)
|
||||
{
|
||||
|
||||
PlaybackStopped?.Invoke(this, new PlaybackStoppedEventArgs
|
||||
{
|
||||
MediaInfo = mediaInfo
|
||||
|
@ -6,6 +6,7 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Emby.Dlna.Didl;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Common.Extensions;
|
||||
using MediaBrowser.Controller.Dlna;
|
||||
using MediaBrowser.Controller.Drawing;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
@ -17,8 +18,8 @@ using MediaBrowser.Model.Dto;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.Events;
|
||||
using MediaBrowser.Model.Globalization;
|
||||
using MediaBrowser.Model.Services;
|
||||
using MediaBrowser.Model.Session;
|
||||
using Microsoft.AspNetCore.WebUtilities;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Emby.Dlna.PlayTo
|
||||
@ -847,13 +848,13 @@ namespace Emby.Dlna.PlayTo
|
||||
if (index == -1) return request;
|
||||
|
||||
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.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))
|
||||
{
|
||||
@ -879,9 +880,9 @@ namespace Emby.Dlna.PlayTo
|
||||
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))
|
||||
{
|
||||
|
@ -9,8 +9,6 @@ namespace Emby.Dlna.PlayTo
|
||||
{
|
||||
public class PlaylistItemFactory
|
||||
{
|
||||
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
|
||||
|
||||
public PlaylistItem Create(Photo item, DeviceProfile profile)
|
||||
{
|
||||
var playlistItem = new PlaylistItem
|
||||
|
@ -1,9 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace Emby.Dlna.PlayTo
|
||||
{
|
||||
public class TransportStateEventArgs : EventArgs
|
||||
{
|
||||
public TRANSPORTSTATE State { get; set; }
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,9 +0,0 @@
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace Emby.Dlna.PlayTo
|
||||
{
|
||||
public class uParserObject
|
||||
{
|
||||
public XElement Element { get; set; }
|
||||
}
|
||||
}
|
@ -8,8 +8,8 @@ using System.Resources;
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[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: AssemblyCulture("")]
|
||||
[assembly: NeutralResourcesLanguage("en")]
|
||||
|
@ -7,7 +7,6 @@ using System.Xml;
|
||||
using Emby.Dlna.Didl;
|
||||
using MediaBrowser.Controller.Configuration;
|
||||
using MediaBrowser.Controller.Extensions;
|
||||
using MediaBrowser.Model.Xml;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Emby.Dlna.Service
|
||||
@ -18,13 +17,11 @@ namespace Emby.Dlna.Service
|
||||
|
||||
protected readonly IServerConfigurationManager Config;
|
||||
protected readonly ILogger _logger;
|
||||
protected readonly IXmlReaderSettingsFactory XmlReaderSettingsFactory;
|
||||
|
||||
protected BaseControlHandler(IServerConfigurationManager config, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
|
||||
protected BaseControlHandler(IServerConfigurationManager config, ILogger logger)
|
||||
{
|
||||
Config = config;
|
||||
_logger = logger;
|
||||
XmlReaderSettingsFactory = xmlReaderSettingsFactory;
|
||||
}
|
||||
|
||||
public ControlResponse ProcessControlRequest(ControlRequest request)
|
||||
@ -61,11 +58,13 @@ namespace Emby.Dlna.Service
|
||||
|
||||
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))
|
||||
{
|
||||
|
@ -180,6 +180,12 @@ namespace Emby.Drawing
|
||||
|
||||
var supportedImageInfo = await GetSupportedImage(originalImagePath, dateModified).ConfigureAwait(false);
|
||||
originalImagePath = supportedImageInfo.path;
|
||||
|
||||
if (!File.Exists(originalImagePath))
|
||||
{
|
||||
return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
|
||||
}
|
||||
|
||||
dateModified = supportedImageInfo.dateModified;
|
||||
bool requiresTransparency = TransparentImageTypes.Contains(Path.GetExtension(originalImagePath));
|
||||
|
||||
@ -265,8 +271,6 @@ namespace Emby.Drawing
|
||||
{
|
||||
// If it fails for whatever reason, return the original 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);
|
||||
}
|
||||
finally
|
||||
|
@ -8,8 +8,8 @@ using System.Runtime.InteropServices;
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[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: AssemblyCulture("")]
|
||||
|
||||
|
@ -7,6 +7,7 @@ using MediaBrowser.Model.Diagnostics;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.System;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
|
||||
|
||||
namespace IsoMounter
|
||||
{
|
||||
@ -17,7 +18,6 @@ namespace IsoMounter
|
||||
|
||||
#region Private Fields
|
||||
|
||||
private readonly IEnvironmentInfo EnvironmentInfo;
|
||||
private readonly bool ExecutablesAvailable;
|
||||
private readonly ILogger _logger;
|
||||
private readonly string MountCommand;
|
||||
@ -30,10 +30,8 @@ namespace IsoMounter
|
||||
|
||||
#region Constructor(s)
|
||||
|
||||
public LinuxIsoManager(ILogger logger, IEnvironmentInfo environment, IProcessFactory processFactory)
|
||||
public LinuxIsoManager(ILogger logger, IProcessFactory processFactory)
|
||||
{
|
||||
|
||||
EnvironmentInfo = environment;
|
||||
_logger = logger;
|
||||
ProcessFactory = processFactory;
|
||||
|
||||
@ -109,7 +107,7 @@ namespace IsoMounter
|
||||
public bool CanMount(string path)
|
||||
{
|
||||
|
||||
if (EnvironmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Linux)
|
||||
if (OperatingSystem.Id != OperatingSystemId.Linux)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@ -118,7 +116,7 @@ namespace IsoMounter
|
||||
Name,
|
||||
path,
|
||||
Path.GetExtension(path),
|
||||
EnvironmentInfo.OperatingSystem,
|
||||
OperatingSystem.Name,
|
||||
ExecutablesAvailable
|
||||
);
|
||||
|
||||
|
@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[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: AssemblyCulture("")]
|
||||
[assembly: NeutralResourcesLanguage("en")]
|
||||
|
@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[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: AssemblyCulture("")]
|
||||
[assembly: NeutralResourcesLanguage("en")]
|
||||
|
@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[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: AssemblyCulture("")]
|
||||
[assembly: NeutralResourcesLanguage("en")]
|
||||
|
@ -9,8 +9,8 @@ using System.Runtime.InteropServices;
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[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: AssemblyCulture("")]
|
||||
[assembly: NeutralResourcesLanguage("en")]
|
||||
|
@ -30,13 +30,10 @@ namespace Emby.Server.Implementations.Activity
|
||||
public class ActivityLogEntryPoint : IServerEntryPoint
|
||||
{
|
||||
private readonly IInstallationManager _installationManager;
|
||||
|
||||
//private readonly ILogger _logger;
|
||||
private readonly ISessionManager _sessionManager;
|
||||
private readonly ITaskManager _taskManager;
|
||||
private readonly IActivityManager _activityManager;
|
||||
private readonly ILocalizationManager _localization;
|
||||
|
||||
private readonly ILibraryManager _libraryManager;
|
||||
private readonly ISubtitleManager _subManager;
|
||||
private readonly IUserManager _userManager;
|
||||
@ -61,41 +58,37 @@ namespace Emby.Server.Implementations.Activity
|
||||
|
||||
public Task RunAsync()
|
||||
{
|
||||
_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.SubtitlesDownloaded += _subManager_SubtitlesDownloaded;
|
||||
_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;
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
void _deviceManager_CameraImageUploaded(object sender, GenericEventArgs<CameraImageUploadInfo> e)
|
||||
private void OnCameraImageUploaded(object sender, GenericEventArgs<CameraImageUploadInfo> e)
|
||||
{
|
||||
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
|
||||
{
|
||||
@ -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
|
||||
{
|
||||
@ -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;
|
||||
|
||||
@ -146,7 +139,7 @@ namespace Emby.Server.Implementations.Activity
|
||||
return;
|
||||
}
|
||||
|
||||
var user = e.Users.First();
|
||||
var user = e.Users[0];
|
||||
|
||||
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;
|
||||
|
||||
@ -232,7 +225,7 @@ namespace Emby.Server.Implementations.Activity
|
||||
return null;
|
||||
}
|
||||
|
||||
void _sessionManager_SessionEnded(object sender, SessionEventArgs e)
|
||||
private void OnSessionEnded(object sender, SessionEventArgs e)
|
||||
{
|
||||
string name;
|
||||
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;
|
||||
|
||||
@ -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
|
||||
{
|
||||
@ -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
|
||||
{
|
||||
@ -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
|
||||
{
|
||||
@ -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
|
||||
{
|
||||
@ -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
|
||||
{
|
||||
@ -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
|
||||
{
|
||||
@ -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;
|
||||
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
|
||||
{
|
||||
@ -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
|
||||
{
|
||||
@ -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
|
||||
{
|
||||
@ -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;
|
||||
|
||||
@ -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 task = e.Task;
|
||||
@ -468,48 +432,36 @@ namespace Emby.Server.Implementations.Activity
|
||||
}
|
||||
|
||||
private void CreateLogEntry(ActivityLogEntry entry)
|
||||
{
|
||||
try
|
||||
{
|
||||
_activityManager.Create(entry);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Logged at lower levels
|
||||
}
|
||||
}
|
||||
=> _activityManager.Create(entry);
|
||||
|
||||
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>
|
||||
@ -531,6 +483,7 @@ namespace Emby.Server.Implementations.Activity
|
||||
values.Add(CreateValueString(years, "year"));
|
||||
days = days % DaysInYear;
|
||||
}
|
||||
|
||||
// Number of months
|
||||
if (days >= DaysInMonth)
|
||||
{
|
||||
@ -538,25 +491,39 @@ namespace Emby.Server.Implementations.Activity
|
||||
values.Add(CreateValueString(months, "month"));
|
||||
days = days % DaysInMonth;
|
||||
}
|
||||
|
||||
// Number of days
|
||||
if (days >= 1)
|
||||
{
|
||||
values.Add(CreateValueString(days, "day"));
|
||||
}
|
||||
|
||||
// Number of hours
|
||||
if (span.Hours >= 1)
|
||||
{
|
||||
values.Add(CreateValueString(span.Hours, "hour"));
|
||||
}
|
||||
// Number of minutes
|
||||
if (span.Minutes >= 1)
|
||||
{
|
||||
values.Add(CreateValueString(span.Minutes, "minute"));
|
||||
}
|
||||
|
||||
// Number of seconds (include when 0 if no other components included)
|
||||
if (span.Seconds >= 1 || values.Count == 0)
|
||||
{
|
||||
values.Add(CreateValueString(span.Seconds, "second"));
|
||||
}
|
||||
|
||||
// Combine values into string
|
||||
var builder = new StringBuilder();
|
||||
for (int i = 0; i < values.Count; i++)
|
||||
{
|
||||
if (builder.Length > 0)
|
||||
{
|
||||
builder.Append(i == values.Count - 1 ? " and " : ", ");
|
||||
}
|
||||
|
||||
builder.Append(values[i]);
|
||||
}
|
||||
// Return result
|
||||
|
@ -17,12 +17,14 @@ namespace Emby.Server.Implementations.AppBase
|
||||
string programDataPath,
|
||||
string logDirectoryPath,
|
||||
string configurationDirectoryPath,
|
||||
string cacheDirectoryPath)
|
||||
string cacheDirectoryPath,
|
||||
string webDirectoryPath)
|
||||
{
|
||||
ProgramDataPath = programDataPath;
|
||||
LogDirectoryPath = logDirectoryPath;
|
||||
ConfigurationDirectoryPath = configurationDirectoryPath;
|
||||
CachePath = cacheDirectoryPath;
|
||||
WebPath = webDirectoryPath;
|
||||
|
||||
DataPath = Path.Combine(ProgramDataPath, "data");
|
||||
}
|
||||
@ -33,6 +35,12 @@ namespace Emby.Server.Implementations.AppBase
|
||||
/// <value>The program data path.</value>
|
||||
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>
|
||||
/// Gets the path to the system folder
|
||||
/// </summary>
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -36,7 +36,7 @@ namespace Emby.Server.Implementations.Collections
|
||||
return base.Supports(item);
|
||||
}
|
||||
|
||||
protected override List<BaseItem> GetItemsWithImages(BaseItem item)
|
||||
protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
|
||||
{
|
||||
var playlist = (BoxSet)item;
|
||||
|
||||
@ -80,7 +80,7 @@ namespace Emby.Server.Implementations.Collections
|
||||
.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);
|
||||
}
|
||||
|
@ -6,7 +6,8 @@ namespace Emby.Server.Implementations
|
||||
{
|
||||
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"}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -1,13 +1,49 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Linq;
|
||||
using MediaBrowser.Model.Cryptography;
|
||||
|
||||
namespace Emby.Server.Implementations.Cryptography
|
||||
{
|
||||
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)
|
||||
{
|
||||
return new Guid(ComputeMD5(Encoding.Unicode.GetBytes(str)));
|
||||
@ -36,5 +72,98 @@ namespace Emby.Server.Implementations.Cryptography
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -25,7 +25,6 @@ using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.Globalization;
|
||||
using MediaBrowser.Model.LiveTv;
|
||||
using MediaBrowser.Model.Querying;
|
||||
using MediaBrowser.Model.Reflection;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SQLitePCL.pretty;
|
||||
@ -69,7 +68,6 @@ namespace Emby.Server.Implementations.Data
|
||||
IServerApplicationHost appHost,
|
||||
IJsonSerializer jsonSerializer,
|
||||
ILoggerFactory loggerFactory,
|
||||
IAssemblyInfo assemblyInfo,
|
||||
ILocalizationManager localization)
|
||||
: base(loggerFactory.CreateLogger(nameof(SqliteItemRepository)))
|
||||
{
|
||||
@ -86,7 +84,7 @@ namespace Emby.Server.Implementations.Data
|
||||
_appHost = appHost;
|
||||
_config = config;
|
||||
_jsonSerializer = jsonSerializer;
|
||||
_typeMapper = new TypeMapper(assemblyInfo);
|
||||
_typeMapper = new TypeMapper();
|
||||
_localization = localization;
|
||||
|
||||
DbFilePath = Path.Combine(_config.ApplicationPaths.DataPath, "library.db");
|
||||
|
@ -55,6 +55,8 @@ namespace Emby.Server.Implementations.Data
|
||||
{
|
||||
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>
|
||||
/// Save a user in the repo
|
||||
/// </summary>
|
||||
|
@ -1,7 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq;
|
||||
using MediaBrowser.Model.Reflection;
|
||||
|
||||
namespace Emby.Server.Implementations.Data
|
||||
{
|
||||
@ -10,16 +9,13 @@ namespace Emby.Server.Implementations.Data
|
||||
/// </summary>
|
||||
public class TypeMapper
|
||||
{
|
||||
private readonly IAssemblyInfo _assemblyInfo;
|
||||
|
||||
/// <summary>
|
||||
/// This holds all the types in the running assemblies so that we can de-serialize properly when we don't have strong types
|
||||
/// </summary>
|
||||
private readonly ConcurrentDictionary<string, Type> _typeMap = new ConcurrentDictionary<string, Type>();
|
||||
|
||||
public TypeMapper(IAssemblyInfo assemblyInfo)
|
||||
public TypeMapper()
|
||||
{
|
||||
_assemblyInfo = assemblyInfo;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -45,8 +41,7 @@ namespace Emby.Server.Implementations.Data
|
||||
/// <returns>Type.</returns>
|
||||
private Type LookupType(string typeName)
|
||||
{
|
||||
return _assemblyInfo
|
||||
.GetCurrentAssemblies()
|
||||
return AppDomain.CurrentDomain.GetAssemblies()
|
||||
.Select(a => a.GetType(typeName))
|
||||
.FirstOrDefault(t => t != null);
|
||||
}
|
||||
|
@ -9,14 +9,14 @@ namespace Emby.Server.Implementations.Diagnostics
|
||||
{
|
||||
public class CommonProcess : IProcess
|
||||
{
|
||||
public event EventHandler Exited;
|
||||
|
||||
private readonly ProcessOptions _options;
|
||||
private readonly Process _process;
|
||||
|
||||
private bool _disposed = false;
|
||||
private bool _hasExited;
|
||||
|
||||
public CommonProcess(ProcessOptions options)
|
||||
{
|
||||
_options = options;
|
||||
StartInfo = options;
|
||||
|
||||
var startInfo = new ProcessStartInfo
|
||||
{
|
||||
@ -27,10 +27,10 @@ namespace Emby.Server.Implementations.Diagnostics
|
||||
CreateNoWindow = options.CreateNoWindow,
|
||||
RedirectStandardError = options.RedirectStandardError,
|
||||
RedirectStandardInput = options.RedirectStandardInput,
|
||||
RedirectStandardOutput = options.RedirectStandardOutput
|
||||
RedirectStandardOutput = options.RedirectStandardOutput,
|
||||
ErrorDialog = options.ErrorDialog
|
||||
};
|
||||
|
||||
startInfo.ErrorDialog = options.ErrorDialog;
|
||||
|
||||
if (options.IsHidden)
|
||||
{
|
||||
@ -45,11 +45,22 @@ namespace Emby.Server.Implementations.Diagnostics
|
||||
if (options.EnableRaisingEvents)
|
||||
{
|
||||
_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
|
||||
{
|
||||
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()
|
||||
{
|
||||
_process.Start();
|
||||
@ -108,7 +100,7 @@ namespace Emby.Server.Implementations.Diagnostics
|
||||
|
||||
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)
|
||||
{
|
||||
@ -130,7 +122,29 @@ namespace Emby.Server.Implementations.Diagnostics
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -9,12 +9,10 @@
|
||||
<ProjectReference Include="..\MediaBrowser.Providers\MediaBrowser.Providers.csproj" />
|
||||
<ProjectReference Include="..\MediaBrowser.WebDashboard\MediaBrowser.WebDashboard.csproj" />
|
||||
<ProjectReference Include="..\MediaBrowser.XbmcMetadata\MediaBrowser.XbmcMetadata.csproj" />
|
||||
<ProjectReference Include="..\SocketHttpListener\SocketHttpListener.csproj" />
|
||||
<ProjectReference Include="..\Emby.Dlna\Emby.Dlna.csproj" />
|
||||
<ProjectReference Include="..\Mono.Nat\Mono.Nat.csproj" />
|
||||
<ProjectReference Include="..\MediaBrowser.Api\MediaBrowser.Api.csproj" />
|
||||
<ProjectReference Include="..\MediaBrowser.LocalMetadata\MediaBrowser.LocalMetadata.csproj" />
|
||||
<ProjectReference Include="..\OpenSubtitlesHandler\OpenSubtitlesHandler.csproj" />
|
||||
<ProjectReference Include="..\Emby.Photos\Emby.Photos.csproj" />
|
||||
<ProjectReference Include="..\Emby.Drawing\Emby.Drawing.csproj" />
|
||||
<ProjectReference Include="..\Emby.XmlTv\Emby.XmlTv\Emby.XmlTv.csproj" />
|
||||
@ -22,6 +20,14 @@
|
||||
</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.DependencyInjection" Version="2.2.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="2.2.0" />
|
||||
@ -40,6 +46,21 @@
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
</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>
|
||||
<EmbeddedResource Include="Localization\iso6392.txt" />
|
||||
<EmbeddedResource Include="Localization\countries.json" />
|
||||
|
@ -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;
|
||||
}
|
||||
}
|
@ -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; }
|
||||
}
|
||||
}
|
@ -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";
|
||||
}
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
@ -15,6 +15,7 @@ using MediaBrowser.Common.Net;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.Net;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
|
||||
namespace Emby.Server.Implementations.HttpClientManager
|
||||
{
|
||||
@ -179,11 +180,11 @@ namespace Emby.Server.Implementations.HttpClientManager
|
||||
|
||||
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;
|
||||
}
|
||||
else if (string.Equals(header.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
|
||||
else if (string.Equals(header.Key, HeaderNames.UserAgent, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
SetUserAgent(request, header.Value);
|
||||
hasUserAgent = true;
|
||||
@ -327,7 +328,6 @@ namespace Emby.Server.Implementations.HttpClientManager
|
||||
}
|
||||
|
||||
httpWebRequest.ContentType = contentType;
|
||||
httpWebRequest.ContentLength = bytes.Length;
|
||||
(await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false)).Write(bytes, 0, bytes.Length);
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
@ -5,15 +5,19 @@ using System.Linq;
|
||||
using System.Net;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Emby.Server.Implementations.IO;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.Services;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
|
||||
namespace Emby.Server.Implementations.HttpServer
|
||||
{
|
||||
public class FileWriter : IHttpResult
|
||||
{
|
||||
private readonly IStreamHelper _streamHelper;
|
||||
private ILogger Logger { get; set; }
|
||||
private readonly IFileSystem _fileSystem;
|
||||
|
||||
private string RangeHeader { get; set; }
|
||||
private bool IsHeadRequest { get; set; }
|
||||
@ -42,25 +46,27 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
|
||||
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))
|
||||
{
|
||||
throw new ArgumentNullException(nameof(contentType));
|
||||
}
|
||||
|
||||
_streamHelper = streamHelper;
|
||||
_fileSystem = fileSystem;
|
||||
|
||||
Path = path;
|
||||
Logger = logger;
|
||||
RangeHeader = rangeHeader;
|
||||
|
||||
Headers["Content-Type"] = contentType;
|
||||
Headers[HeaderNames.ContentType] = contentType;
|
||||
|
||||
TotalContentLength = fileSystem.GetFileInfo(path).Length;
|
||||
Headers["Accept-Ranges"] = "bytes";
|
||||
Headers[HeaderNames.AcceptRanges] = "bytes";
|
||||
|
||||
if (string.IsNullOrWhiteSpace(rangeHeader))
|
||||
{
|
||||
Headers["Content-Length"] = TotalContentLength.ToString(UsCulture);
|
||||
StatusCode = HttpStatusCode.OK;
|
||||
}
|
||||
else
|
||||
@ -93,13 +99,10 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
RangeStart = requestedRange.Key;
|
||||
RangeLength = 1 + RangeEnd - RangeStart;
|
||||
|
||||
// Content-Length is the length of what we're serving, not the original content
|
||||
var lengthString = RangeLength.ToString(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>
|
||||
@ -145,8 +148,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
}
|
||||
}
|
||||
|
||||
private string[] SkipLogExtensions = new string[]
|
||||
{
|
||||
private static readonly string[] SkipLogExtensions = {
|
||||
".js",
|
||||
".html",
|
||||
".css"
|
||||
@ -163,8 +165,10 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
@ -173,20 +177,15 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
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
|
||||
{
|
||||
if (OnComplete != null)
|
||||
{
|
||||
OnComplete();
|
||||
}
|
||||
OnComplete?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
@ -203,8 +202,5 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
get => (HttpStatusCode)Status;
|
||||
set => Status = (int)value;
|
||||
}
|
||||
|
||||
public string StatusDescription { get; set; }
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -11,6 +11,7 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Emby.Server.Implementations.Net;
|
||||
using Emby.Server.Implementations.Services;
|
||||
using Emby.Server.Implementations.SocketSharp;
|
||||
using MediaBrowser.Common.Extensions;
|
||||
using MediaBrowser.Common.Net;
|
||||
using MediaBrowser.Controller;
|
||||
@ -20,6 +21,9 @@ using MediaBrowser.Model.Events;
|
||||
using MediaBrowser.Model.Extensions;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using MediaBrowser.Model.Services;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Internal;
|
||||
using Microsoft.AspNetCore.WebUtilities;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ServiceStack.Text.Jsv;
|
||||
@ -29,12 +33,8 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
public class HttpListenerHost : IHttpServer, IDisposable
|
||||
{
|
||||
private string DefaultRedirectPath { get; set; }
|
||||
|
||||
private readonly ILogger _logger;
|
||||
public string[] UrlPrefixes { get; private set; }
|
||||
|
||||
private IHttpListener _listener;
|
||||
|
||||
public event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected;
|
||||
|
||||
private readonly IServerConfigurationManager _config;
|
||||
@ -42,6 +42,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
private readonly IServerApplicationHost _appHost;
|
||||
private readonly IJsonSerializer _jsonSerializer;
|
||||
private readonly IXmlSerializer _xmlSerializer;
|
||||
private readonly IHttpListener _socketListener;
|
||||
private readonly Func<Type, Func<string, object>> _funcParseFn;
|
||||
|
||||
public Action<IRequest, IResponse, object>[] ResponseFilters { get; set; }
|
||||
@ -59,15 +60,18 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
IConfiguration configuration,
|
||||
INetworkManager networkManager,
|
||||
IJsonSerializer jsonSerializer,
|
||||
IXmlSerializer xmlSerializer)
|
||||
IXmlSerializer xmlSerializer,
|
||||
IHttpListener socketListener)
|
||||
{
|
||||
_appHost = applicationHost;
|
||||
_logger = loggerFactory.CreateLogger("HttpServer");
|
||||
Logger = loggerFactory.CreateLogger("HttpServer");
|
||||
_config = config;
|
||||
DefaultRedirectPath = configuration["HttpListenerHost:DefaultRedirectPath"];
|
||||
_networkManager = networkManager;
|
||||
_jsonSerializer = jsonSerializer;
|
||||
_xmlSerializer = xmlSerializer;
|
||||
_socketListener = socketListener;
|
||||
_socketListener.WebSocketConnected = OnWebSocketConnected;
|
||||
|
||||
_funcParseFn = t => s => JsvReader.GetParseFn(t)(s);
|
||||
|
||||
@ -77,7 +81,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
|
||||
public string GlobalResponse { get; set; }
|
||||
|
||||
protected ILogger Logger => _logger;
|
||||
protected ILogger Logger { get; }
|
||||
|
||||
public object CreateInstance(Type type)
|
||||
{
|
||||
@ -143,11 +147,11 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
return;
|
||||
}
|
||||
|
||||
var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger)
|
||||
var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, Logger)
|
||||
{
|
||||
OnReceive = ProcessWebSocketMessageReceived,
|
||||
Url = e.Url,
|
||||
QueryString = e.QueryString ?? new QueryParamCollection()
|
||||
QueryString = e.QueryString ?? new QueryCollection()
|
||||
};
|
||||
|
||||
connection.Closed += Connection_Closed;
|
||||
@ -212,16 +216,16 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
|
||||
if (logExceptionStackTrace)
|
||||
{
|
||||
_logger.LogError(ex, "Error processing request");
|
||||
Logger.LogError(ex, "Error processing request");
|
||||
}
|
||||
else if (logExceptionMessage)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
Logger.LogError(ex.Message);
|
||||
}
|
||||
|
||||
var httpRes = httpReq.Response;
|
||||
|
||||
if (httpRes.IsClosed)
|
||||
if (httpRes.OriginalResponse.HasStarted)
|
||||
{
|
||||
return;
|
||||
}
|
||||
@ -234,7 +238,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
}
|
||||
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)
|
||||
@ -292,7 +288,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
var uri = new Uri(url);
|
||||
|
||||
// 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;
|
||||
|
||||
@ -313,7 +309,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
string pagePathWithoutQueryString = url.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0];
|
||||
|
||||
return newQueryString.Count > 0
|
||||
? string.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString)
|
||||
? QueryHelpers.AddQueryString(pagePathWithoutQueryString, newQueryString.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()))
|
||||
: pagePathWithoutQueryString;
|
||||
}
|
||||
|
||||
@ -422,7 +418,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
/// <summary>
|
||||
/// Overridable method that can be used to implement a custom hnandler
|
||||
/// </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();
|
||||
stopWatch.Start();
|
||||
@ -599,17 +595,15 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
}
|
||||
finally
|
||||
{
|
||||
httpRes.Close();
|
||||
|
||||
stopWatch.Stop();
|
||||
var elapsed = stopWatch.Elapsed;
|
||||
if (elapsed.TotalMilliseconds > 500)
|
||||
{
|
||||
_logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
|
||||
Logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogDebug("HTTP Response {StatusCode} to {RemoteIp}. Time: {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
|
||||
Logger.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('/');
|
||||
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;
|
||||
}
|
||||
|
||||
@ -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;
|
||||
}
|
||||
|
||||
private static Task Write(IResponse response, string text)
|
||||
{
|
||||
var bOutput = Encoding.UTF8.GetBytes(text);
|
||||
response.SetContentLength(bOutput.Length);
|
||||
|
||||
return response.OutputStream.WriteAsync(bOutput, 0, bOutput.Length);
|
||||
}
|
||||
|
||||
@ -663,6 +655,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
}
|
||||
else
|
||||
{
|
||||
// TODO what is this?
|
||||
var httpsUrl = url
|
||||
.Replace("http://", "https://", 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.
|
||||
/// </summary>
|
||||
/// <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();
|
||||
|
||||
UrlPrefixes = urlPrefixes.ToArray();
|
||||
ServiceController = new ServiceController();
|
||||
|
||||
_logger.LogInformation("Calling ServiceStack AppHost.Init");
|
||||
Logger.LogInformation("Calling ServiceStack AppHost.Init");
|
||||
|
||||
var types = services.Select(r => r.GetType()).ToArray();
|
||||
|
||||
@ -697,7 +692,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
//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)
|
||||
{
|
||||
if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
|
||||
@ -793,6 +792,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
|
||||
private bool _disposed;
|
||||
private readonly object _disposeLock = new object();
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (_disposed) return;
|
||||
@ -821,7 +821,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
_logger.LogDebug("Websocket message received: {0}", result.MessageType);
|
||||
Logger.LogDebug("Websocket message received: {0}", result.MessageType);
|
||||
|
||||
var tasks = _webSocketListeners.Select(i => Task.Run(async () =>
|
||||
{
|
||||
@ -831,7 +831,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
public void StartServer(string[] urlPrefixes, IHttpListener httpListener)
|
||||
{
|
||||
UrlPrefixes = urlPrefixes;
|
||||
|
||||
_listener = httpListener;
|
||||
|
||||
_listener.WebSocketConnected = OnWebSocketConnected;
|
||||
_listener.ErrorHandler = ErrorHandler;
|
||||
_listener.RequestHandler = RequestHandler;
|
||||
|
||||
_listener.Start(UrlPrefixes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -16,6 +16,8 @@ using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using MediaBrowser.Model.Services;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Primitives;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
using IRequest = MediaBrowser.Model.Services.IRequest;
|
||||
using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
|
||||
|
||||
@ -32,17 +34,16 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
private readonly ILogger _logger;
|
||||
private readonly IFileSystem _fileSystem;
|
||||
private readonly IJsonSerializer _jsonSerializer;
|
||||
|
||||
private IBrotliCompressor _brotliCompressor;
|
||||
private readonly IStreamHelper _streamHelper;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HttpResultFactory" /> class.
|
||||
/// </summary>
|
||||
public HttpResultFactory(ILoggerFactory loggerfactory, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IBrotliCompressor brotliCompressor)
|
||||
public HttpResultFactory(ILoggerFactory loggerfactory, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IStreamHelper streamHelper)
|
||||
{
|
||||
_fileSystem = fileSystem;
|
||||
_jsonSerializer = jsonSerializer;
|
||||
_brotliCompressor = brotliCompressor;
|
||||
_streamHelper = streamHelper;
|
||||
_logger = loggerfactory.CreateLogger("HttpResultFactory");
|
||||
}
|
||||
|
||||
@ -76,7 +77,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
public object GetRedirectResult(string url)
|
||||
{
|
||||
var responseHeaders = new Dictionary<string, string>();
|
||||
responseHeaders["Location"] = url;
|
||||
responseHeaders[HeaderNames.Location] = url;
|
||||
|
||||
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>();
|
||||
}
|
||||
|
||||
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);
|
||||
@ -131,7 +132,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
content = Array.Empty<byte>();
|
||||
}
|
||||
|
||||
result = new StreamWriter(content, contentType, contentLength);
|
||||
result = new StreamWriter(content, contentType);
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -143,9 +144,9 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
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);
|
||||
@ -175,7 +176,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
bytes = Array.Empty<byte>();
|
||||
}
|
||||
|
||||
result = new StreamWriter(bytes, contentType, contentLength);
|
||||
result = new StreamWriter(bytes, contentType);
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -187,9 +188,9 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
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);
|
||||
@ -214,7 +215,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
responseHeaders["Expires"] = "-1";
|
||||
responseHeaders[HeaderNames.Expires] = "-1";
|
||||
|
||||
return ToOptimizedResultInternal(requestContext, result, responseHeaders);
|
||||
}
|
||||
@ -246,9 +247,9 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
|
||||
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)
|
||||
// return "br";
|
||||
@ -326,21 +327,21 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
if (isHeadRequest)
|
||||
{
|
||||
var result = new StreamWriter(Array.Empty<byte>(), contentType, contentLength);
|
||||
var result = new StreamWriter(Array.Empty<byte>(), contentType);
|
||||
AddResponseHeaders(result, responseHeaders);
|
||||
return result;
|
||||
}
|
||||
else
|
||||
{
|
||||
var result = new StreamWriter(content, contentType, contentLength);
|
||||
var result = new StreamWriter(content, contentType);
|
||||
AddResponseHeaders(result, responseHeaders);
|
||||
return result;
|
||||
}
|
||||
@ -348,11 +349,6 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
|
||||
private byte[] Compress(byte[] bytes, string compressionType)
|
||||
{
|
||||
if (string.Equals(compressionType, "br", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return CompressBrotli(bytes);
|
||||
}
|
||||
|
||||
if (string.Equals(compressionType, "deflate", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return Deflate(bytes);
|
||||
@ -366,11 +362,6 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
throw new NotSupportedException(compressionType);
|
||||
}
|
||||
|
||||
private byte[] CompressBrotli(byte[] bytes)
|
||||
{
|
||||
return _brotliCompressor.Compress(bytes);
|
||||
}
|
||||
|
||||
private static byte[] Deflate(byte[] bytes)
|
||||
{
|
||||
// In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
|
||||
@ -424,12 +415,12 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
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))
|
||||
{
|
||||
@ -530,7 +521,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
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
|
||||
var result = GetCachedResult(requestContext, options.ResponseHeaders, options);
|
||||
@ -548,11 +539,11 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
AddCachingHeaders(responseHeaders, options.CacheDuration, false, options.DateLastModified);
|
||||
AddAgeHeader(responseHeaders, options.DateLastModified);
|
||||
|
||||
var rangeHeader = requestContext.Headers.Get("Range");
|
||||
var rangeHeader = requestContext.Headers[HeaderNames.Range];
|
||||
|
||||
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,
|
||||
OnError = options.OnError,
|
||||
@ -590,11 +581,6 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
}
|
||||
else
|
||||
{
|
||||
if (totalContentLength.HasValue)
|
||||
{
|
||||
responseHeaders["Content-Length"] = totalContentLength.Value.ToString(UsCulture);
|
||||
}
|
||||
|
||||
if (isHeadRequest)
|
||||
{
|
||||
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>
|
||||
/// Adds the caching responseHeaders.
|
||||
/// </summary>
|
||||
@ -627,23 +608,23 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
if (cacheDuration.HasValue)
|
||||
{
|
||||
responseHeaders["Cache-Control"] = "public, max-age=" + cacheDuration.Value.TotalSeconds;
|
||||
responseHeaders[HeaderNames.CacheControl] = "public, max-age=" + cacheDuration.Value.TotalSeconds;
|
||||
}
|
||||
else
|
||||
{
|
||||
responseHeaders["Cache-Control"] = "public";
|
||||
responseHeaders[HeaderNames.CacheControl] = "public";
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
@ -1,10 +1,9 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Emby.Server.Implementations.Net;
|
||||
using MediaBrowser.Controller.Net;
|
||||
using MediaBrowser.Model.Services;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Emby.Server.Implementations.HttpServer
|
||||
{
|
||||
@ -28,21 +27,11 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
/// <value>The web socket handler.</value>
|
||||
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>
|
||||
/// Stops this instance.
|
||||
/// </summary>
|
||||
Task Stop();
|
||||
|
||||
Task ProcessWebSocketRequest(HttpContext ctx);
|
||||
}
|
||||
}
|
||||
|
@ -7,6 +7,7 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MediaBrowser.Model.Services;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
|
||||
namespace Emby.Server.Implementations.HttpServer
|
||||
{
|
||||
@ -66,8 +67,8 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
this._logger = logger;
|
||||
|
||||
ContentType = contentType;
|
||||
Headers["Content-Type"] = contentType;
|
||||
Headers["Accept-Ranges"] = "bytes";
|
||||
Headers[HeaderNames.ContentType] = contentType;
|
||||
Headers[HeaderNames.AcceptRanges] = "bytes";
|
||||
StatusCode = HttpStatusCode.PartialContent;
|
||||
|
||||
SetRangeValues(contentLength);
|
||||
@ -95,9 +96,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
RangeStart = requestedRange.Key;
|
||||
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)
|
||||
{
|
||||
|
@ -3,6 +3,7 @@ using System.Globalization;
|
||||
using System.Text;
|
||||
using MediaBrowser.Model.Services;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
|
||||
namespace Emby.Server.Implementations.HttpServer
|
||||
{
|
||||
@ -25,7 +26,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
public void FilterResponse(IRequest req, IResponse res, object dto)
|
||||
{
|
||||
// Try to prevent compatibility view
|
||||
res.AddHeader("Access-Control-Allow-Headers", "Accept, Accept-Language, Authorization, Cache-Control, Content-Disposition, Content-Encoding, Content-Language, Content-Length, Content-MD5, Content-Range, Content-Type, Date, Host, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, Origin, OriginToken, Pragma, Range, Slug, Transfer-Encoding, Want-Digest, X-MediaBrowser-Token, X-Emby-Authorization");
|
||||
res.AddHeader("Access-Control-Allow-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-Origin", "*");
|
||||
|
||||
@ -44,20 +45,19 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
|
||||
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
|
||||
if (hasHeaders.Headers.TryGetValue("Content-Length", out string contentLength)
|
||||
if (hasHeaders.Headers.TryGetValue(HeaderNames.ContentLength, out string contentLength)
|
||||
&& !string.IsNullOrEmpty(contentLength))
|
||||
{
|
||||
var length = long.Parse(contentLength, UsCulture);
|
||||
|
||||
if (length > 0)
|
||||
{
|
||||
res.SetContentLength(length);
|
||||
res.SendChunked = false;
|
||||
}
|
||||
}
|
||||
|
@ -5,6 +5,7 @@ using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.Net;
|
||||
using MediaBrowser.Controller.Security;
|
||||
using MediaBrowser.Model.Services;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
|
||||
namespace Emby.Server.Implementations.HttpServer.Security
|
||||
{
|
||||
@ -176,7 +177,7 @@ namespace Emby.Server.Implementations.HttpServer.Security
|
||||
|
||||
if (string.IsNullOrEmpty(auth))
|
||||
{
|
||||
auth = httpReq.Headers["Authorization"];
|
||||
auth = httpReq.Headers[HeaderNames.Authorization];
|
||||
}
|
||||
|
||||
return GetAuthorization(auth);
|
||||
|
@ -5,7 +5,7 @@ using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MediaBrowser.Model.Services;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
|
||||
namespace Emby.Server.Implementations.HttpServer
|
||||
{
|
||||
@ -52,12 +52,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
|
||||
SourceStream = source;
|
||||
|
||||
Headers["Content-Type"] = contentType;
|
||||
|
||||
if (source.CanSeek)
|
||||
{
|
||||
Headers["Content-Length"] = source.Length.ToString(UsCulture);
|
||||
}
|
||||
Headers[HeaderNames.ContentType] = contentType;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -65,8 +60,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
/// </summary>
|
||||
/// <param name="source">The source.</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))
|
||||
{
|
||||
@ -75,9 +69,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
|
||||
SourceBytes = source;
|
||||
|
||||
Headers["Content-Type"] = contentType;
|
||||
|
||||
Headers["Content-Length"] = contentLength.ToString(UsCulture);
|
||||
Headers[HeaderNames.ContentType] = contentType;
|
||||
}
|
||||
|
||||
public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken)
|
||||
|
@ -8,6 +8,7 @@ using MediaBrowser.Controller.Net;
|
||||
using MediaBrowser.Model.Net;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using MediaBrowser.Model.Services;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using UtfUnknown;
|
||||
|
||||
@ -67,7 +68,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
/// Gets or sets the query string.
|
||||
/// </summary>
|
||||
/// <value>The query string.</value>
|
||||
public QueryParamCollection QueryString { get; set; }
|
||||
public IQueryCollection QueryString { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
|
||||
@ -101,12 +102,6 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
_socket = socket;
|
||||
_socket.OnReceiveBytes = OnReceiveInternal;
|
||||
|
||||
var memorySocket = socket as IMemoryWebSocket;
|
||||
if (memorySocket != null)
|
||||
{
|
||||
memorySocket.OnReceiveMemoryBytes = OnReceiveInternal;
|
||||
}
|
||||
|
||||
RemoteEndPoint = remoteEndPoint;
|
||||
_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)
|
||||
{
|
||||
LastActivityDate = DateTime.UtcNow;
|
||||
@ -193,7 +160,7 @@ namespace Emby.Server.Implementations.HttpServer
|
||||
var info = new WebSocketMessageInfo
|
||||
{
|
||||
MessageType = stub.MessageType,
|
||||
Data = stub.Data == null ? null : stub.Data.ToString(),
|
||||
Data = stub.Data?.ToString(),
|
||||
Connection = this
|
||||
};
|
||||
|
||||
|
@ -10,8 +10,8 @@ using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.Plugins;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.System;
|
||||
using MediaBrowser.Model.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
|
||||
|
||||
namespace Emby.Server.Implementations.IO
|
||||
{
|
||||
@ -127,7 +127,6 @@ namespace Emby.Server.Implementations.IO
|
||||
private IServerConfigurationManager ConfigurationManager { get; set; }
|
||||
|
||||
private readonly IFileSystem _fileSystem;
|
||||
private readonly IEnvironmentInfo _environmentInfo;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryMonitor" /> class.
|
||||
@ -136,14 +135,12 @@ namespace Emby.Server.Implementations.IO
|
||||
ILoggerFactory loggerFactory,
|
||||
ILibraryManager libraryManager,
|
||||
IServerConfigurationManager configurationManager,
|
||||
IFileSystem fileSystem,
|
||||
IEnvironmentInfo environmentInfo)
|
||||
IFileSystem fileSystem)
|
||||
{
|
||||
LibraryManager = libraryManager;
|
||||
Logger = loggerFactory.CreateLogger(GetType().Name);
|
||||
ConfigurationManager = configurationManager;
|
||||
_fileSystem = fileSystem;
|
||||
_environmentInfo = environmentInfo;
|
||||
}
|
||||
|
||||
private bool IsLibraryMonitorEnabled(BaseItem item)
|
||||
@ -267,7 +264,7 @@ namespace Emby.Server.Implementations.IO
|
||||
return;
|
||||
}
|
||||
|
||||
if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
|
||||
if (OperatingSystem.Id != OperatingSystemId.Windows)
|
||||
{
|
||||
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
|
||||
if (_fileSystemWatchers.ContainsKey(path))
|
||||
{
|
||||
|
@ -7,8 +7,8 @@ using System.Text;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.System;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
|
||||
|
||||
namespace Emby.Server.Implementations.IO
|
||||
{
|
||||
@ -25,22 +25,19 @@ namespace Emby.Server.Implementations.IO
|
||||
|
||||
private readonly string _tempPath;
|
||||
|
||||
private readonly IEnvironmentInfo _environmentInfo;
|
||||
private readonly bool _isEnvironmentCaseInsensitive;
|
||||
|
||||
public ManagedFileSystem(
|
||||
ILoggerFactory loggerFactory,
|
||||
IEnvironmentInfo environmentInfo,
|
||||
IApplicationPaths applicationPaths)
|
||||
{
|
||||
Logger = loggerFactory.CreateLogger("FileSystem");
|
||||
_supportsAsyncFileStreams = true;
|
||||
_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)
|
||||
@ -469,7 +466,7 @@ namespace Emby.Server.Implementations.IO
|
||||
|
||||
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;
|
||||
}
|
||||
@ -493,7 +490,7 @@ namespace Emby.Server.Implementations.IO
|
||||
|
||||
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;
|
||||
}
|
||||
@ -517,7 +514,7 @@ namespace Emby.Server.Implementations.IO
|
||||
|
||||
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;
|
||||
}
|
||||
@ -711,20 +708,20 @@ namespace Emby.Server.Implementations.IO
|
||||
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;
|
||||
|
||||
// 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 ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions != null && extensions.Length == 1)
|
||||
if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions != null && extensions.Count == 1)
|
||||
{
|
||||
return ToMetadata(new DirectoryInfo(path).EnumerateFiles("*" + extensions[0], searchOption));
|
||||
}
|
||||
|
||||
var files = new DirectoryInfo(path).EnumerateFiles("*", searchOption);
|
||||
|
||||
if (extensions != null && extensions.Length > 0)
|
||||
if (extensions != null && extensions.Count > 0)
|
||||
{
|
||||
files = files.Where(i =>
|
||||
{
|
||||
@ -802,7 +799,7 @@ namespace Emby.Server.Implementations.IO
|
||||
|
||||
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));
|
||||
}
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@ -8,168 +9,213 @@ namespace Emby.Server.Implementations.IO
|
||||
{
|
||||
public class StreamHelper : IStreamHelper
|
||||
{
|
||||
private const int StreamCopyToBufferSize = 81920;
|
||||
|
||||
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();
|
||||
|
||||
await destination.WriteAsync(buffer, 0, read).ConfigureAwait(false);
|
||||
|
||||
if (onStarted != null)
|
||||
int read;
|
||||
while ((read = await source.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) != 0)
|
||||
{
|
||||
onStarted();
|
||||
onStarted = null;
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
await destination.WriteAsync(buffer, 0, read).ConfigureAwait(false);
|
||||
|
||||
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)
|
||||
{
|
||||
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)
|
||||
{
|
||||
int read;
|
||||
while ((read = await source.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) != 0)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
await destination.WriteAsync(buffer, 0, read).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var eofCount = 0;
|
||||
|
||||
while (eofCount < emptyReadLimit)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
await destination.WriteAsync(buffer, 0, read).ConfigureAwait(false);
|
||||
}
|
||||
var bytesRead = await source.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
|
||||
|
||||
return;
|
||||
if (bytesRead == 0)
|
||||
{
|
||||
eofCount++;
|
||||
await Task.Delay(50, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
eofCount = 0;
|
||||
|
||||
await destination.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var eofCount = 0;
|
||||
|
||||
while (eofCount < emptyReadLimit)
|
||||
finally
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var bytesRead = source.Read(buffer, 0, buffer.Length);
|
||||
|
||||
if (bytesRead == 0)
|
||||
{
|
||||
eofCount++;
|
||||
await Task.Delay(50, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
eofCount = 0;
|
||||
|
||||
await destination.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
|
||||
}
|
||||
ArrayPool<byte>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
const int StreamCopyToBufferSize = 81920;
|
||||
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)
|
||||
{
|
||||
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)
|
||||
{
|
||||
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)
|
||||
{
|
||||
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)
|
||||
{
|
||||
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)
|
||||
|
@ -7,11 +7,6 @@ namespace Emby.Server.Implementations
|
||||
/// </summary>
|
||||
string FFmpegPath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// --ffprobe
|
||||
/// </summary>
|
||||
string FFprobePath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// --service
|
||||
/// </summary>
|
||||
|
@ -20,6 +20,9 @@ namespace Emby.Server.Implementations.Images
|
||||
public abstract class BaseDynamicImageProvider<T> : IHasItemChangeMonitor, IForcedProvider, ICustomMetadataProvider<T>, IHasOrder
|
||||
where T : BaseItem
|
||||
{
|
||||
protected virtual IReadOnlyCollection<ImageType> SupportedImages { get; }
|
||||
= new ImageType[] { ImageType.Primary };
|
||||
|
||||
protected IFileSystem FileSystem { get; private set; }
|
||||
protected IProviderManager ProviderManager { get; private set; }
|
||||
protected IApplicationPaths ApplicationPaths { get; private set; }
|
||||
@ -33,18 +36,7 @@ namespace Emby.Server.Implementations.Images
|
||||
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)
|
||||
{
|
||||
@ -54,15 +46,14 @@ namespace Emby.Server.Implementations.Images
|
||||
}
|
||||
|
||||
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);
|
||||
updateType = updateType | primaryResult;
|
||||
}
|
||||
|
||||
if (supportedImages.Contains(ImageType.Thumb))
|
||||
if (SupportedImages.Contains(ImageType.Thumb))
|
||||
{
|
||||
var thumbResult = await FetchAsync(item, ImageType.Thumb, options, cancellationToken).ConfigureAwait(false);
|
||||
updateType = updateType | thumbResult;
|
||||
@ -94,7 +85,7 @@ namespace Emby.Server.Implementations.Images
|
||||
}
|
||||
|
||||
protected async Task<ItemUpdateType> FetchToFileInternal(BaseItem item,
|
||||
List<BaseItem> itemsWithImages,
|
||||
IReadOnlyList<BaseItem> itemsWithImages,
|
||||
ImageType imageType,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
@ -119,9 +110,9 @@ namespace Emby.Server.Implementations.Images
|
||||
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);
|
||||
}
|
||||
@ -132,38 +123,38 @@ namespace Emby.Server.Implementations.Images
|
||||
.Select(i =>
|
||||
{
|
||||
var image = i.GetImageInfo(ImageType.Primary, 0);
|
||||
|
||||
if (image != null && image.IsLocalFile)
|
||||
{
|
||||
return image.Path;
|
||||
}
|
||||
|
||||
image = i.GetImageInfo(ImageType.Thumb, 0);
|
||||
|
||||
if (image != null && image.IsLocalFile)
|
||||
{
|
||||
return image.Path;
|
||||
}
|
||||
|
||||
return null;
|
||||
})
|
||||
.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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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));
|
||||
|
||||
@ -192,7 +183,7 @@ namespace Emby.Server.Implementations.Images
|
||||
public string Name => "Dynamic Image Provider";
|
||||
|
||||
protected virtual string CreateImage(BaseItem item,
|
||||
List<BaseItem> itemsWithImages,
|
||||
IReadOnlyCollection<BaseItem> itemsWithImages,
|
||||
string outputPathWithoutExtension,
|
||||
ImageType imageType,
|
||||
int imageIndex)
|
||||
@ -211,18 +202,15 @@ namespace Emby.Server.Implementations.Images
|
||||
|
||||
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 CreatePosterCollage(item, itemsWithImages, outputPath);
|
||||
}
|
||||
|
||||
throw new ArgumentException("Unexpected image type");
|
||||
throw new ArgumentException("Unexpected image type", nameof(imageType));
|
||||
}
|
||||
|
||||
protected virtual int MaxImageAgeDays => 7;
|
||||
@ -234,13 +222,11 @@ namespace Emby.Server.Implementations.Images
|
||||
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;
|
||||
}
|
||||
if (supportedImages.Contains(ImageType.Thumb) && HasChanged(item, ImageType.Thumb))
|
||||
if (SupportedImages.Contains(ImageType.Thumb) && HasChanged(item, ImageType.Thumb))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@ -285,7 +271,7 @@ namespace Emby.Server.Implementations.Images
|
||||
|
||||
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
|
||||
.Where(i => i.HasImage(imageType) && i.GetImageInfo(imageType, 0).IsLocalFile && Path.HasExtension(i.GetImagePath(imageType)))
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using MediaBrowser.Controller.Authentication;
|
||||
@ -18,20 +19,64 @@ namespace Emby.Server.Implementations.Library
|
||||
public string Name => "Default";
|
||||
|
||||
public bool IsEnabled => true;
|
||||
|
||||
|
||||
// This is dumb and an artifact of the backwards way auth providers were designed.
|
||||
// This version of authenticate was never meant to be called, but needs to be here for interface compat
|
||||
// Only the providers that don't provide local user support use this
|
||||
public Task<ProviderAuthenticationResult> Authenticate(string username, string password)
|
||||
{
|
||||
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)
|
||||
{
|
||||
bool success = false;
|
||||
if (resolvedUser == null)
|
||||
{
|
||||
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)
|
||||
{
|
||||
@ -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)
|
||||
{
|
||||
var hasConfiguredPassword = !IsPasswordEmpty(user, GetPasswordHash(user));
|
||||
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)
|
||||
{
|
||||
string newPasswordHash = null;
|
||||
|
||||
if (newPassword != null)
|
||||
ConvertPasswordFormat(user);
|
||||
// This is needed to support changing a no password user to a password user
|
||||
if (string.IsNullOrEmpty(user.Password))
|
||||
{
|
||||
newPasswordHash = GetHashedString(user, newPassword);
|
||||
PasswordHash newPasswordHash = new PasswordHash(_cryptographyProvider);
|
||||
newPasswordHash.SaltBytes = _cryptographyProvider.GenerateSalt();
|
||||
newPasswordHash.Salt = PasswordHash.ConvertToByteString(newPasswordHash.SaltBytes);
|
||||
newPasswordHash.Id = _cryptographyProvider.DefaultHashMethod;
|
||||
newPasswordHash.Hash = GetHashedStringChangeAuth(newPassword, newPasswordHash);
|
||||
user.Password = newPasswordHash.ToString();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(newPasswordHash))
|
||||
PasswordHash passwordHash = new PasswordHash(user.Password);
|
||||
if (passwordHash.Id == "SHA1" && string.IsNullOrEmpty(passwordHash.Salt))
|
||||
{
|
||||
throw new ArgumentNullException(nameof(newPasswordHash));
|
||||
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);
|
||||
}
|
||||
|
||||
user.Password = newPasswordHash;
|
||||
if (string.IsNullOrWhiteSpace(passwordHash.Hash))
|
||||
{
|
||||
throw new ArgumentNullException(nameof(passwordHash.Hash));
|
||||
}
|
||||
|
||||
user.Password = passwordHash.ToString();
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
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>
|
||||
@ -91,14 +176,28 @@ namespace Emby.Server.Implementations.Library
|
||||
/// </summary>
|
||||
public string GetHashedString(User user, string str)
|
||||
{
|
||||
var salt = user.Salt;
|
||||
if (salt != null)
|
||||
PasswordHash passwordHash;
|
||||
if (string.IsNullOrEmpty(user.Password))
|
||||
{
|
||||
// return BCrypt.HashPassword(str, salt);
|
||||
passwordHash = new PasswordHash(_cryptographyProvider);
|
||||
}
|
||||
else
|
||||
{
|
||||
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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -58,22 +58,23 @@ namespace Emby.Server.Implementations.Library
|
||||
private ILibraryPostScanTask[] PostscanTasks { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the intro providers.
|
||||
/// Gets or sets the intro providers.
|
||||
/// </summary>
|
||||
/// <value>The intro providers.</value>
|
||||
private IIntroProvider[] IntroProviders { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of entity resolution ignore rules
|
||||
/// Gets or sets the list of entity resolution ignore rules
|
||||
/// </summary>
|
||||
/// <value>The entity resolution ignore rules.</value>
|
||||
private IResolverIgnoreRule[] EntityResolutionIgnoreRules { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of currently registered entity resolvers
|
||||
/// Gets or sets the list of currently registered entity resolvers
|
||||
/// </summary>
|
||||
/// <value>The entity resolvers enumerable.</value>
|
||||
private IItemResolver[] EntityResolvers { get; set; }
|
||||
|
||||
private IMultiItemResolver[] MultiItemResolvers { get; set; }
|
||||
|
||||
/// <summary>
|
||||
@ -83,7 +84,7 @@ namespace Emby.Server.Implementations.Library
|
||||
private IBaseItemComparer[] Comparers { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the active item repository
|
||||
/// Gets or sets the active item repository
|
||||
/// </summary>
|
||||
/// <value>The item repository.</value>
|
||||
public IItemRepository ItemRepository { get; set; }
|
||||
@ -133,12 +134,14 @@ namespace Emby.Server.Implementations.Library
|
||||
private readonly Func<IProviderManager> _providerManagerFactory;
|
||||
private readonly Func<IUserViewManager> _userviewManager;
|
||||
public bool IsScanRunning { get; private set; }
|
||||
|
||||
private IServerApplicationHost _appHost;
|
||||
|
||||
/// <summary>
|
||||
/// The _library items cache
|
||||
/// </summary>
|
||||
private readonly ConcurrentDictionary<Guid, BaseItem> _libraryItemsCache;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the library items cache.
|
||||
/// </summary>
|
||||
@ -150,7 +153,8 @@ namespace Emby.Server.Implementations.Library
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryManager" /> class.
|
||||
/// </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="userManager">The user manager.</param>
|
||||
/// <param name="configurationManager">The configuration manager.</param>
|
||||
@ -167,6 +171,7 @@ namespace Emby.Server.Implementations.Library
|
||||
Func<IProviderManager> providerManagerFactory,
|
||||
Func<IUserViewManager> userviewManager)
|
||||
{
|
||||
_appHost = appHost;
|
||||
_logger = loggerFactory.CreateLogger(nameof(LibraryManager));
|
||||
_taskManager = taskManager;
|
||||
_userManager = userManager;
|
||||
@ -176,7 +181,7 @@ namespace Emby.Server.Implementations.Library
|
||||
_fileSystem = fileSystem;
|
||||
_providerManagerFactory = providerManagerFactory;
|
||||
_userviewManager = userviewManager;
|
||||
_appHost = appHost;
|
||||
|
||||
_libraryItemsCache = new ConcurrentDictionary<Guid, BaseItem>();
|
||||
|
||||
ConfigurationManager.ConfigurationUpdated += ConfigurationUpdated;
|
||||
@ -191,8 +196,9 @@ namespace Emby.Server.Implementations.Library
|
||||
/// <param name="resolvers">The resolvers.</param>
|
||||
/// <param name="introProviders">The intro providers.</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<IIntroProvider> introProviders,
|
||||
IEnumerable<IBaseItemComparer> itemComparers,
|
||||
@ -203,24 +209,19 @@ namespace Emby.Server.Implementations.Library
|
||||
MultiItemResolvers = EntityResolvers.OfType<IMultiItemResolver>().ToArray();
|
||||
IntroProviders = introProviders.ToArray();
|
||||
Comparers = itemComparers.ToArray();
|
||||
|
||||
PostscanTasks = postscanTasks.OrderBy(i =>
|
||||
{
|
||||
var hasOrder = i as IHasOrder;
|
||||
|
||||
return hasOrder == null ? 0 : hasOrder.Order;
|
||||
|
||||
}).ToArray();
|
||||
PostscanTasks = postscanTasks.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The _root folder
|
||||
/// </summary>
|
||||
private volatile AggregateFolder _rootFolder;
|
||||
|
||||
/// <summary>
|
||||
/// The _root folder sync lock
|
||||
/// </summary>
|
||||
private readonly object _rootFolderSyncLock = new object();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the root folder.
|
||||
/// </summary>
|
||||
@ -239,11 +240,13 @@ namespace Emby.Server.Implementations.Library
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return _rootFolder;
|
||||
}
|
||||
}
|
||||
|
||||
private bool _wizardCompleted;
|
||||
|
||||
/// <summary>
|
||||
/// Records the configuration values.
|
||||
/// </summary>
|
||||
@ -258,7 +261,7 @@ namespace Emby.Server.Implementations.Library
|
||||
/// </summary>
|
||||
/// <param name="sender">The sender.</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;
|
||||
|
||||
@ -278,6 +281,7 @@ namespace Emby.Server.Implementations.Library
|
||||
{
|
||||
throw new ArgumentNullException(nameof(item));
|
||||
}
|
||||
|
||||
if (item is IItemByName)
|
||||
{
|
||||
if (!(item is MusicArtist))
|
||||
@ -285,18 +289,7 @@ namespace Emby.Server.Implementations.Library
|
||||
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))
|
||||
{
|
||||
@ -345,12 +338,14 @@ namespace Emby.Server.Implementations.Library
|
||||
// channel no longer installed
|
||||
}
|
||||
}
|
||||
|
||||
options.DeleteFileLocation = false;
|
||||
}
|
||||
|
||||
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.Name ?? "Unknown name",
|
||||
item.Path ?? string.Empty,
|
||||
@ -358,7 +353,8 @@ namespace Emby.Server.Implementations.Library
|
||||
}
|
||||
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.Name ?? "Unknown name",
|
||||
item.Path ?? string.Empty,
|
||||
@ -371,19 +367,20 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
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
|
||||
{
|
||||
Directory.Delete(metadataPath, true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
|
||||
}
|
||||
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));
|
||||
}
|
||||
|
||||
if (type == null)
|
||||
{
|
||||
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
|
||||
key = key.Substring(ConfigurationManager.ApplicationPaths.ProgramDataPath.Length)
|
||||
@ -520,13 +518,11 @@ namespace Emby.Server.Implementations.Library
|
||||
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,
|
||||
IItemResolver[] resolvers,
|
||||
Folder parent = null,
|
||||
@ -581,7 +577,7 @@ namespace Emby.Server.Implementations.Library
|
||||
{
|
||||
_logger.LogError(ex, "Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", isPhysicalRoot, isVf);
|
||||
|
||||
files = new FileSystemMetadata[] { };
|
||||
files = Array.Empty<FileSystemMetadata>();
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -609,13 +605,7 @@ namespace Emby.Server.Implementations.Library
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
@ -655,7 +645,8 @@ namespace Emby.Server.Implementations.Library
|
||||
return ResolvePaths(files, directoryService, parent, libraryOptions, collectionType, EntityResolvers);
|
||||
}
|
||||
|
||||
public IEnumerable<BaseItem> ResolvePaths(IEnumerable<FileSystemMetadata> files,
|
||||
public IEnumerable<BaseItem> ResolvePaths(
|
||||
IEnumerable<FileSystemMetadata> files,
|
||||
IDirectoryService directoryService,
|
||||
Folder parent,
|
||||
LibraryOptions libraryOptions,
|
||||
@ -681,6 +672,7 @@ namespace Emby.Server.Implementations.Library
|
||||
{
|
||||
ResolverHelper.SetInitialItemValues(item, parent, _fileSystem, this, directoryService);
|
||||
}
|
||||
|
||||
items.AddRange(ResolveFileList(result.ExtraFiles, directoryService, parent, collectionType, resolvers, libraryOptions));
|
||||
return items;
|
||||
}
|
||||
@ -690,7 +682,8 @@ namespace Emby.Server.Implementations.Library
|
||||
return ResolveFileList(fileList, directoryService, parent, collectionType, resolvers, libraryOptions);
|
||||
}
|
||||
|
||||
private IEnumerable<BaseItem> ResolveFileList(IEnumerable<FileSystemMetadata> fileList,
|
||||
private IEnumerable<BaseItem> ResolveFileList(
|
||||
IEnumerable<FileSystemMetadata> fileList,
|
||||
IDirectoryService directoryService,
|
||||
Folder parent,
|
||||
string collectionType,
|
||||
@ -775,6 +768,7 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
private volatile UserRootFolder _userRootFolder;
|
||||
private readonly object _syncLock = new object();
|
||||
|
||||
public Folder GetUserRootFolder()
|
||||
{
|
||||
if (_userRootFolder == null)
|
||||
@ -819,8 +813,6 @@ namespace Emby.Server.Implementations.Library
|
||||
throw new ArgumentNullException(nameof(path));
|
||||
}
|
||||
|
||||
//_logger.LogInformation("FindByPath {0}", path);
|
||||
|
||||
var query = new InternalItemsQuery
|
||||
{
|
||||
Path = path,
|
||||
@ -894,7 +886,6 @@ namespace Emby.Server.Implementations.Library
|
||||
/// </summary>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <returns>Task{Year}.</returns>
|
||||
/// <exception cref="ArgumentOutOfRangeException"></exception>
|
||||
public Year GetYear(int value)
|
||||
{
|
||||
if (value <= 0)
|
||||
@ -1036,20 +1027,25 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
private async Task ValidateTopLibraryFolders(CancellationToken cancellationToken)
|
||||
{
|
||||
var rootChildren = RootFolder.Children.ToList();
|
||||
rootChildren = GetUserRootFolder().Children.ToList();
|
||||
|
||||
await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// 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().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
|
||||
foreach (var folder in GetUserRootFolder().Children.OfType<Folder>().ToList())
|
||||
foreach (var folder in GetUserRootFolder().Children.OfType<Folder>())
|
||||
{
|
||||
await folder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@ -1213,7 +1209,7 @@ namespace Emby.Server.Implementations.Library
|
||||
private string GetCollectionType(string path)
|
||||
{
|
||||
return _fileSystem.GetFilePaths(path, new[] { ".collection" }, true, false)
|
||||
.Select(i => Path.GetFileNameWithoutExtension(i))
|
||||
.Select(Path.GetFileNameWithoutExtension)
|
||||
.FirstOrDefault(i => !string.IsNullOrEmpty(i));
|
||||
}
|
||||
|
||||
@ -1227,7 +1223,7 @@ namespace Emby.Server.Implementations.Library
|
||||
{
|
||||
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))
|
||||
@ -1395,17 +1391,7 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
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
|
||||
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)
|
||||
{
|
||||
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
|
||||
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)
|
||||
{
|
||||
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 };
|
||||
}
|
||||
@ -1537,8 +1511,10 @@ namespace Emby.Server.Implementations.Library
|
||||
{
|
||||
return GetTopParentIdsForQuery(displayParent, user);
|
||||
}
|
||||
|
||||
return Array.Empty<Guid>();
|
||||
}
|
||||
|
||||
if (!view.ParentId.Equals(Guid.Empty))
|
||||
{
|
||||
var displayParent = GetItemById(view.ParentId);
|
||||
@ -1546,6 +1522,7 @@ namespace Emby.Server.Implementations.Library
|
||||
{
|
||||
return GetTopParentIdsForQuery(displayParent, user);
|
||||
}
|
||||
|
||||
return Array.Empty<Guid>();
|
||||
}
|
||||
|
||||
@ -1559,11 +1536,11 @@ namespace Emby.Server.Implementations.Library
|
||||
.Where(i => user.IsFolderGrouped(i.Id))
|
||||
.SelectMany(i => GetTopParentIdsForQuery(i, user));
|
||||
}
|
||||
|
||||
return Array.Empty<Guid>();
|
||||
}
|
||||
|
||||
var collectionFolder = item as CollectionFolder;
|
||||
if (collectionFolder != null)
|
||||
if (item is CollectionFolder collectionFolder)
|
||||
{
|
||||
return collectionFolder.PhysicalFolderIds;
|
||||
}
|
||||
@ -1573,6 +1550,7 @@ namespace Emby.Server.Implementations.Library
|
||||
{
|
||||
return new[] { topParent.Id };
|
||||
}
|
||||
|
||||
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));
|
||||
|
||||
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;
|
||||
@ -1792,7 +1767,6 @@ namespace Emby.Server.Implementations.Library
|
||||
/// </summary>
|
||||
/// <param name="item">The item.</param>
|
||||
/// <param name="parent">The parent item.</param>
|
||||
/// <returns>Task.</returns>
|
||||
public void CreateItem(BaseItem item, BaseItem parent)
|
||||
{
|
||||
CreateItems(new[] { item }, parent, CancellationToken.None);
|
||||
@ -1802,20 +1776,23 @@ namespace Emby.Server.Implementations.Library
|
||||
/// Creates the items.
|
||||
/// </summary>
|
||||
/// <param name="items">The items.</param>
|
||||
/// <param name="parent">The parent item</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>Task.</returns>
|
||||
public void CreateItems(IEnumerable<BaseItem> items, BaseItem parent, CancellationToken cancellationToken)
|
||||
{
|
||||
ItemRepository.SaveItems(items, cancellationToken);
|
||||
// Don't iterate multiple times
|
||||
var itemsList = items.ToList();
|
||||
|
||||
foreach (var item in items)
|
||||
ItemRepository.SaveItems(itemsList, cancellationToken);
|
||||
|
||||
foreach (var item in itemsList)
|
||||
{
|
||||
RegisterItem(item);
|
||||
}
|
||||
|
||||
if (ItemAdded != null)
|
||||
{
|
||||
foreach (var item in items)
|
||||
foreach (var item in itemsList)
|
||||
{
|
||||
// With the live tv guide this just creates too much noise
|
||||
if (item.SourceType != SourceType.Library)
|
||||
@ -1825,11 +1802,13 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
try
|
||||
{
|
||||
ItemAdded(this, new ItemChangeEventArgs
|
||||
{
|
||||
Item = item,
|
||||
Parent = parent ?? item.GetParent()
|
||||
});
|
||||
ItemAdded(
|
||||
this,
|
||||
new ItemChangeEventArgs
|
||||
{
|
||||
Item = item,
|
||||
Parent = parent ?? item.GetParent()
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@ -1851,7 +1830,10 @@ namespace Emby.Server.Implementations.Library
|
||||
/// </summary>
|
||||
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)
|
||||
{
|
||||
@ -1863,14 +1845,11 @@ namespace Emby.Server.Implementations.Library
|
||||
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)
|
||||
{
|
||||
foreach (var item in items)
|
||||
foreach (var item in itemsList)
|
||||
{
|
||||
// With the live tv guide this just creates too much noise
|
||||
if (item.SourceType != SourceType.Library)
|
||||
@ -1880,12 +1859,14 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
try
|
||||
{
|
||||
ItemUpdated(this, new ItemChangeEventArgs
|
||||
{
|
||||
Item = item,
|
||||
Parent = parent,
|
||||
UpdateReason = updateReason
|
||||
});
|
||||
ItemUpdated(
|
||||
this,
|
||||
new ItemChangeEventArgs
|
||||
{
|
||||
Item = item,
|
||||
Parent = parent,
|
||||
UpdateReason = updateReason
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@ -1899,9 +1880,9 @@ namespace Emby.Server.Implementations.Library
|
||||
/// Updates the item.
|
||||
/// </summary>
|
||||
/// <param name="item">The item.</param>
|
||||
/// <param name="parent">The parent item.</param>
|
||||
/// <param name="updateReason">The update reason.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>Task.</returns>
|
||||
public void UpdateItem(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
|
||||
{
|
||||
UpdateItems(new [] { item }, parent, updateReason, cancellationToken);
|
||||
@ -1911,17 +1892,20 @@ namespace Emby.Server.Implementations.Library
|
||||
/// Reports the item removed.
|
||||
/// </summary>
|
||||
/// <param name="item">The item.</param>
|
||||
/// <param name="parent">The parent item.</param>
|
||||
public void ReportItemRemoved(BaseItem item, BaseItem parent)
|
||||
{
|
||||
if (ItemRemoved != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
ItemRemoved(this, new ItemChangeEventArgs
|
||||
{
|
||||
Item = item,
|
||||
Parent = parent
|
||||
});
|
||||
ItemRemoved(
|
||||
this,
|
||||
new ItemChangeEventArgs
|
||||
{
|
||||
Item = item,
|
||||
Parent = parent
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@ -2047,8 +2031,7 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
public string GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath)
|
||||
{
|
||||
var collectionFolder = item as ICollectionFolder;
|
||||
if (collectionFolder != null)
|
||||
if (item is ICollectionFolder collectionFolder)
|
||||
{
|
||||
return collectionFolder.CollectionType;
|
||||
}
|
||||
@ -2058,13 +2041,11 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
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)
|
||||
@ -2081,6 +2062,7 @@ namespace Emby.Server.Implementations.Library
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
item = parent;
|
||||
}
|
||||
|
||||
@ -2092,9 +2074,9 @@ namespace Emby.Server.Implementations.Library
|
||||
}
|
||||
|
||||
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 viewType,
|
||||
string sortName)
|
||||
@ -2102,13 +2084,15 @@ namespace Emby.Server.Implementations.Library
|
||||
return GetNamedView(user, name, Guid.Empty, viewType, sortName);
|
||||
}
|
||||
|
||||
public UserView GetNamedView(string name,
|
||||
public UserView GetNamedView(
|
||||
string name,
|
||||
string viewType,
|
||||
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));
|
||||
|
||||
@ -2144,7 +2128,8 @@ namespace Emby.Server.Implementations.Library
|
||||
return item;
|
||||
}
|
||||
|
||||
public UserView GetNamedView(User user,
|
||||
public UserView GetNamedView(
|
||||
User user,
|
||||
string name,
|
||||
Guid parentId,
|
||||
string viewType,
|
||||
@ -2173,10 +2158,10 @@ namespace Emby.Server.Implementations.Library
|
||||
Name = name,
|
||||
ViewType = viewType,
|
||||
ForcedSortName = sortName,
|
||||
UserId = user.Id
|
||||
UserId = user.Id,
|
||||
DisplayParentId = parentId
|
||||
};
|
||||
|
||||
item.DisplayParentId = parentId;
|
||||
|
||||
CreateItem(item, null);
|
||||
|
||||
@ -2193,20 +2178,24 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public UserView GetShadowView(BaseItem parent,
|
||||
string viewType,
|
||||
string sortName)
|
||||
public UserView GetShadowView(
|
||||
BaseItem parent,
|
||||
string viewType,
|
||||
string sortName)
|
||||
{
|
||||
if (parent == null)
|
||||
{
|
||||
@ -2257,18 +2246,21 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public UserView GetNamedView(string name,
|
||||
public UserView GetNamedView(
|
||||
string name,
|
||||
Guid parentId,
|
||||
string viewType,
|
||||
string sortName,
|
||||
@ -2331,17 +2323,21 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public void AddExternalSubtitleStreams(List<MediaStream> streams,
|
||||
public void AddExternalSubtitleStreams(
|
||||
List<MediaStream> streams,
|
||||
string videoPath,
|
||||
string[] files)
|
||||
{
|
||||
@ -2445,6 +2441,7 @@ namespace Emby.Server.Implementations.Library
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
|
||||
episode.IndexNumber = episodeInfo.EpisodeNumber;
|
||||
}
|
||||
|
||||
@ -2454,6 +2451,7 @@ namespace Emby.Server.Implementations.Library
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
|
||||
episode.IndexNumberEnd = episodeInfo.EndingEpsiodeNumber;
|
||||
}
|
||||
|
||||
@ -2463,6 +2461,7 @@ namespace Emby.Server.Implementations.Library
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
|
||||
episode.ParentIndexNumber = episodeInfo.SeasonNumber;
|
||||
}
|
||||
}
|
||||
@ -2492,6 +2491,7 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
private NamingOptions _namingOptions;
|
||||
private string[] _videoFileExtensions;
|
||||
|
||||
private NamingOptions GetNamingOptionsInternal()
|
||||
{
|
||||
if (_namingOptions == null)
|
||||
@ -2688,7 +2688,7 @@ namespace Emby.Server.Implementations.Library
|
||||
var newPath = path.Replace(from, to, StringComparison.OrdinalIgnoreCase);
|
||||
var changed = false;
|
||||
|
||||
if (!string.Equals(newPath, path))
|
||||
if (!string.Equals(newPath, path, StringComparison.Ordinal))
|
||||
{
|
||||
if (to.IndexOf('/') != -1)
|
||||
{
|
||||
@ -2812,6 +2812,7 @@ namespace Emby.Server.Implementations.Library
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -2916,6 +2917,7 @@ namespace Emby.Server.Implementations.Library
|
||||
}
|
||||
|
||||
private const string ShortcutFileExtension = ".mblink";
|
||||
|
||||
public void AddMediaPath(string virtualFolderName, MediaPathInfo pathInfo)
|
||||
{
|
||||
AddMediaPathInternal(virtualFolderName, pathInfo, true);
|
||||
@ -2932,7 +2934,7 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
if (string.IsNullOrWhiteSpace(path))
|
||||
{
|
||||
throw new ArgumentNullException(nameof(path));
|
||||
throw new ArgumentException(nameof(path));
|
||||
}
|
||||
|
||||
if (!Directory.Exists(path))
|
||||
|
@ -4,6 +4,7 @@ using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
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)
|
||||
{
|
||||
return !char.Equals(i, '<') && !char.Equals(i, '>');
|
||||
return IsValidUsername(i.ToString());
|
||||
}
|
||||
|
||||
public string MakeValidUsername(string username)
|
||||
@ -475,15 +471,10 @@ namespace Emby.Server.Implementations.Library
|
||||
private string GetLocalPasswordHash(User user)
|
||||
{
|
||||
return string.IsNullOrEmpty(user.EasyPassword)
|
||||
? _defaultAuthenticationProvider.GetEmptyHashedString(user)
|
||||
? null
|
||||
: user.EasyPassword;
|
||||
}
|
||||
|
||||
private bool IsPasswordEmpty(User user, string passwordHash)
|
||||
{
|
||||
return string.Equals(passwordHash, _defaultAuthenticationProvider.GetEmptyHashedString(user), StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads the users from the repository
|
||||
/// </summary>
|
||||
@ -526,14 +517,14 @@ namespace Emby.Server.Implementations.Library
|
||||
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 :
|
||||
hasConfiguredPassword;
|
||||
|
||||
var dto = new UserDto
|
||||
UserDto dto = new UserDto
|
||||
{
|
||||
Id = user.Id,
|
||||
Name = user.Name,
|
||||
@ -552,7 +543,7 @@ namespace Emby.Server.Implementations.Library
|
||||
dto.EnableAutoLogin = true;
|
||||
}
|
||||
|
||||
var image = user.GetImageInfo(ImageType.Primary, 0);
|
||||
ItemImageInfo image = user.GetImageInfo(ImageType.Primary, 0);
|
||||
|
||||
if (image != null)
|
||||
{
|
||||
@ -688,7 +679,7 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
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)))
|
||||
|
@ -33,7 +33,6 @@ using MediaBrowser.Model.LiveTv;
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
using MediaBrowser.Model.Providers;
|
||||
using MediaBrowser.Model.Querying;
|
||||
using MediaBrowser.Model.Reflection;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
@ -58,7 +57,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
|
||||
private readonly IProviderManager _providerManager;
|
||||
private readonly IMediaEncoder _mediaEncoder;
|
||||
private readonly IProcessFactory _processFactory;
|
||||
private readonly IAssemblyInfo _assemblyInfo;
|
||||
private IMediaSourceManager _mediaSourceManager;
|
||||
|
||||
public static EmbyTV Current;
|
||||
@ -74,7 +72,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
|
||||
public EmbyTV(IServerApplicationHost appHost,
|
||||
IStreamHelper streamHelper,
|
||||
IMediaSourceManager mediaSourceManager,
|
||||
IAssemblyInfo assemblyInfo,
|
||||
ILogger logger,
|
||||
IJsonSerializer jsonSerializer,
|
||||
IHttpClient httpClient,
|
||||
@ -101,12 +98,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
|
||||
_processFactory = processFactory;
|
||||
_liveTvManager = (LiveTvManager)liveTvManager;
|
||||
_jsonSerializer = jsonSerializer;
|
||||
_assemblyInfo = assemblyInfo;
|
||||
_mediaSourceManager = mediaSourceManager;
|
||||
_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;
|
||||
|
||||
_config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
|
||||
|
@ -2,7 +2,6 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
@ -32,32 +31,28 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
|
||||
{
|
||||
if (_items == null)
|
||||
{
|
||||
if (!File.Exists(_dataPath))
|
||||
{
|
||||
return new List<T>();
|
||||
}
|
||||
|
||||
Logger.LogInformation("Loading live tv data from {0}", _dataPath);
|
||||
_items = GetItemsFromFile(_dataPath);
|
||||
}
|
||||
|
||||
return _items.ToList();
|
||||
}
|
||||
}
|
||||
|
||||
private List<T> GetItemsFromFile(string path)
|
||||
{
|
||||
var jsonFile = path + ".json";
|
||||
|
||||
if (!File.Exists(jsonFile))
|
||||
{
|
||||
return new List<T>();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return _jsonSerializer.DeserializeFromFile<List<T>>(jsonFile) ?? new List<T>();
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
return _jsonSerializer.DeserializeFromFile<List<T>>(path);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "Error deserializing {jsonFile}", jsonFile);
|
||||
Logger.LogError(ex, "Error deserializing {Path}", path);
|
||||
}
|
||||
|
||||
return new List<T>();
|
||||
@ -70,12 +65,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
|
||||
throw new ArgumentNullException(nameof(newList));
|
||||
}
|
||||
|
||||
var file = _dataPath + ".json";
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(file));
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(_dataPath));
|
||||
|
||||
lock (_fileDataLock)
|
||||
{
|
||||
_jsonSerializer.SerializeToFile(newList, file);
|
||||
_jsonSerializer.SerializeToFile(newList, _dataPath);
|
||||
_items = newList;
|
||||
}
|
||||
}
|
||||
|
@ -17,6 +17,7 @@ using MediaBrowser.Model.LiveTv;
|
||||
using MediaBrowser.Model.Net;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
|
||||
namespace Emby.Server.Implementations.LiveTv.Listings
|
||||
{
|
||||
@ -638,7 +639,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
|
||||
#if NETSTANDARD2_0
|
||||
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
|
||||
{
|
||||
options.RequestHeaders["Accept-Encoding"] = "deflate";
|
||||
options.RequestHeaders[HeaderNames.AcceptEncoding] = "deflate";
|
||||
}
|
||||
#endif
|
||||
|
||||
@ -676,7 +677,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
|
||||
#if NETSTANDARD2_0
|
||||
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
|
||||
{
|
||||
options.RequestHeaders["Accept-Encoding"] = "deflate";
|
||||
options.RequestHeaders[HeaderNames.AcceptEncoding] = "deflate";
|
||||
}
|
||||
#endif
|
||||
|
||||
|
@ -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)
|
||||
{
|
||||
var bufferSize = 81920;
|
||||
|
@ -22,7 +22,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
|
||||
|
||||
public string OriginalStreamId { get; set; }
|
||||
public bool EnableStreamSharing { get; set; }
|
||||
public string UniqueId { get; private set; }
|
||||
public string UniqueId { get; }
|
||||
|
||||
protected readonly IFileSystem FileSystem;
|
||||
protected readonly IServerApplicationPaths AppPaths;
|
||||
@ -31,12 +31,10 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
|
||||
protected readonly ILogger Logger;
|
||||
protected readonly CancellationTokenSource LiveStreamCancellationTokenSource = new CancellationTokenSource();
|
||||
|
||||
public string TunerHostId { get; private set; }
|
||||
public string TunerHostId { get; }
|
||||
|
||||
public DateTime DateOpened { get; protected set; }
|
||||
|
||||
public Func<Task> OnClose { get; set; }
|
||||
|
||||
public LiveStream(MediaSourceInfo mediaSource, TunerHostInfo tuner, IFileSystem fileSystem, ILogger logger, IServerApplicationPaths appPaths)
|
||||
{
|
||||
OriginalMediaSource = mediaSource;
|
||||
@ -76,26 +74,9 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
|
||||
|
||||
LiveStreamCancellationTokenSource.Cancel();
|
||||
|
||||
if (OnClose != null)
|
||||
{
|
||||
return CloseWithExternalFn();
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
var fileOpenOptions = FileOpenOptions.SequentialScan;
|
||||
@ -113,27 +94,26 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
|
||||
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)
|
||||
{
|
||||
Logger.LogInformation("Deleting temp files {0}", string.Join(", ", paths.ToArray()));
|
||||
Logger.LogInformation("Deleting temp files {0}", paths);
|
||||
}
|
||||
|
||||
var failedFiles = new List<string>();
|
||||
|
||||
foreach (var path in paths)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
FileSystem.DeleteFile(path);
|
||||
}
|
||||
catch (DirectoryNotFoundException)
|
||||
{
|
||||
}
|
||||
catch (FileNotFoundException)
|
||||
{
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "Error deleting file {path}", path);
|
||||
@ -157,8 +137,8 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
|
||||
{
|
||||
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;
|
||||
|
||||
@ -181,28 +161,24 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
|
||||
Logger.LogInformation("Live Stream ended.");
|
||||
}
|
||||
|
||||
private Tuple<string, bool> GetNextFile(string currentFile)
|
||||
private (string file, bool isLastFile) GetNextFile(string currentFile)
|
||||
{
|
||||
var files = GetStreamFilePaths();
|
||||
|
||||
//logger.LogInformation("Live stream files: {0}", string.Join(", ", files.ToArray()));
|
||||
|
||||
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 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)
|
||||
{
|
||||
//logger.LogInformation("Opening live stream file {0}. Empty read limit: {1}", path, emptyReadLimit);
|
||||
|
||||
using (var inputStream = (FileStream)GetInputStream(path, allowAsync))
|
||||
{
|
||||
if (seekFile)
|
||||
@ -218,7 +194,11 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
|
||||
|
||||
private void TrySeek(FileStream stream, long offset)
|
||||
{
|
||||
//logger.LogInformation("TrySeek live stream");
|
||||
if (!stream.CanSeek)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
stream.Seek(offset, SeekOrigin.End);
|
||||
|
@ -19,6 +19,7 @@ using MediaBrowser.Model.MediaInfo;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using MediaBrowser.Model.System;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
|
||||
namespace Emby.Server.Implementations.LiveTv.TunerHosts
|
||||
{
|
||||
@ -145,7 +146,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
|
||||
if (protocol == MediaProtocol.Http)
|
||||
{
|
||||
// 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" :
|
||||
info.UserAgent;
|
||||
}
|
||||
|
@ -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",
|
||||
"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",
|
||||
"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}",
|
||||
"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}"
|
||||
}
|
||||
|
@ -1,97 +1,97 @@
|
||||
{
|
||||
"Albums": "Albums",
|
||||
"AppDeviceValues": "App: {0}, Device: {1}",
|
||||
"AppDeviceValues": "Application : {0}, Appareil : {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}",
|
||||
"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",
|
||||
"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",
|
||||
"HeaderAlbumArtists": "Album Artists",
|
||||
"HeaderCameraUploads": "Camera Uploads",
|
||||
"HeaderAlbumArtists": "Artistes de l'album",
|
||||
"HeaderCameraUploads": "Photos transférées",
|
||||
"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",
|
||||
"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",
|
||||
"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}",
|
||||
"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}",
|
||||
"VersionNumber": "Version {0}"
|
||||
}
|
||||
|
@ -44,7 +44,7 @@
|
||||
"NameInstallFailed": "{0} échec d'installation",
|
||||
"NameSeasonNumber": "Saison {0}",
|
||||
"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",
|
||||
"NotificationOptionApplicationUpdateInstalled": "Mise à jour de l'application installée",
|
||||
"NotificationOptionAudioPlayback": "Lecture audio démarrée",
|
||||
@ -89,7 +89,7 @@
|
||||
"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 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}",
|
||||
"ValueHasBeenAddedToLibrary": "{0} a été ajouté à votre librairie",
|
||||
"ValueSpecialEpisodeName": "Spécial - {0}",
|
||||
|
@ -1,8 +1,8 @@
|
||||
{
|
||||
"Albums": "Albums",
|
||||
"Albums": "אלבומים",
|
||||
"AppDeviceValues": "App: {0}, Device: {1}",
|
||||
"Application": "Application",
|
||||
"Artists": "Artists",
|
||||
"Application": "אפליקציה",
|
||||
"Artists": "אמנים",
|
||||
"AuthenticationSucceededWithUserName": "{0} successfully authenticated",
|
||||
"Books": "ספרים",
|
||||
"CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
|
||||
|
@ -34,17 +34,17 @@
|
||||
"LabelRunningTimeValue": "Durata: {0}",
|
||||
"Latest": "Più recenti",
|
||||
"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",
|
||||
"MessageServerConfigurationUpdated": "La configurazione del server è stata aggiornata",
|
||||
"MixedContent": "Contenuto misto",
|
||||
"Movies": "Film",
|
||||
"Music": "Musica",
|
||||
"MusicVideos": "Video musicali",
|
||||
"NameInstallFailed": "{0} installation failed",
|
||||
"NameInstallFailed": "{0} installazione fallita",
|
||||
"NameSeasonNumber": "Stagione {0}",
|
||||
"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",
|
||||
"NotificationOptionApplicationUpdateInstalled": "Aggiornamento dell'applicazione installato",
|
||||
"NotificationOptionAudioPlayback": "La riproduzione audio è iniziata",
|
||||
@ -70,12 +70,12 @@
|
||||
"ProviderValue": "Provider: {0}",
|
||||
"ScheduledTaskFailedWithName": "{0} fallito",
|
||||
"ScheduledTaskStartedWithName": "{0} avviati",
|
||||
"ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
|
||||
"ServerNameNeedsToBeRestarted": "{0} deve essere riavviato",
|
||||
"Shows": "Programmi",
|
||||
"Songs": "Canzoni",
|
||||
"StartupEmbyServerIsLoading": "Jellyfin server si sta avviando. Per favore riprova più tardi.",
|
||||
"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}",
|
||||
"Sync": "Sincronizza",
|
||||
"System": "Sistema",
|
||||
@ -91,7 +91,7 @@
|
||||
"UserPolicyUpdatedWithName": "La politica dell'utente è stata aggiornata per {0}",
|
||||
"UserStartedPlayingItemWithValues": "{0} ha avviato 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}",
|
||||
"VersionNumber": "Versione {0}"
|
||||
}
|
||||
|
@ -3,15 +3,15 @@
|
||||
"AppDeviceValues": "Qoldanba: {0}, Qurylǵy: {1}",
|
||||
"Application": "Qoldanba",
|
||||
"Artists": "Oryndaýshylar",
|
||||
"AuthenticationSucceededWithUserName": "{0} túpnusqalyǵyn rastalýy sátti",
|
||||
"AuthenticationSucceededWithUserName": "{0} túpnusqalyq rastalýy sátti aıaqtaldy",
|
||||
"Books": "Kitaptar",
|
||||
"CameraImageUploadedFrom": "Jańa sýret {0} kamerasynan júktep alyndy",
|
||||
"CameraImageUploadedFrom": "{0} kamerasynan jańa sýret júktep alyndy",
|
||||
"Channels": "Arnalar",
|
||||
"ChapterNameValue": "{0}-sahna",
|
||||
"Collections": "Jıyntyqtar",
|
||||
"DeviceOfflineWithName": "{0} ajyratylǵ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",
|
||||
"Folders": "Qaltalar",
|
||||
"Genres": "Janrlar",
|
||||
@ -28,13 +28,13 @@
|
||||
"HeaderRecordingGroups": "Jazba toptary",
|
||||
"HomeVideos": "Úılik beıneler",
|
||||
"Inherit": "Muraǵa ıelený",
|
||||
"ItemAddedWithName": "{0} tasyǵyshhanaǵa ústelindi",
|
||||
"ItemAddedWithName": "{0} tasyǵyshhanaǵa ústeldi",
|
||||
"ItemRemovedWithName": "{0} tasyǵyshhanadan alastaldy",
|
||||
"LabelIpAddressValue": "IP-mekenjaıy: {0}",
|
||||
"LabelRunningTimeValue": "Oınatý ýaqyty: {0}",
|
||||
"Latest": "Eń keıingi",
|
||||
"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",
|
||||
"MessageServerConfigurationUpdated": "Server teńshelimi jańartyldy",
|
||||
"MixedContent": "Aralas mazmun",
|
||||
|
@ -5,7 +5,7 @@
|
||||
"Artists": "Artistas",
|
||||
"AuthenticationSucceededWithUserName": "{0} autenticado com sucesso",
|
||||
"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",
|
||||
"ChapterNameValue": "Capítulo {0}",
|
||||
"Collections": "Coletâneas",
|
||||
@ -30,21 +30,21 @@
|
||||
"Inherit": "Herdar",
|
||||
"ItemAddedWithName": "{0} foi adicionado à biblioteca",
|
||||
"ItemRemovedWithName": "{0} foi removido da biblioteca",
|
||||
"LabelIpAddressValue": "Endereço ip: {0}",
|
||||
"LabelIpAddressValue": "Endereço IP: {0}",
|
||||
"LabelRunningTimeValue": "Tempo de execução: {0}",
|
||||
"Latest": "Recente",
|
||||
"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",
|
||||
"MessageServerConfigurationUpdated": "A configuração do servidor foi atualizada",
|
||||
"MixedContent": "Conteúdo misto",
|
||||
"Movies": "Filmes",
|
||||
"Music": "Música",
|
||||
"MusicVideos": "Vídeos musicais",
|
||||
"NameInstallFailed": "{0} installation failed",
|
||||
"NameInstallFailed": "A instalação de {0} falhou",
|
||||
"NameSeasonNumber": "Temporada {0}",
|
||||
"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",
|
||||
"NotificationOptionApplicationUpdateInstalled": "Atualização de aplicativo instalada",
|
||||
"NotificationOptionAudioPlayback": "Reprodução de áudio iniciada",
|
||||
@ -70,12 +70,12 @@
|
||||
"ProviderValue": "Provedor: {0}",
|
||||
"ScheduledTaskFailedWithName": "{0} falhou",
|
||||
"ScheduledTaskStartedWithName": "{0} iniciada",
|
||||
"ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
|
||||
"ServerNameNeedsToBeRestarted": "O servidor {0} precisa ser reiniciado",
|
||||
"Shows": "Séries",
|
||||
"Songs": "Músicas",
|
||||
"StartupEmbyServerIsLoading": "O Servidor Jellyfin está carregando. Por favor tente novamente em breve.",
|
||||
"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}",
|
||||
"Sync": "Sincronizar",
|
||||
"System": "Sistema",
|
||||
@ -91,7 +91,7 @@
|
||||
"UserPolicyUpdatedWithName": "A política de usuário foi atualizada para {0}",
|
||||
"UserStartedPlayingItemWithValues": "{0} iniciou a reprodução de {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}",
|
||||
"VersionNumber": "Versão {0}"
|
||||
}
|
||||
|
@ -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",
|
||||
"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",
|
||||
"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",
|
||||
"NotificationOptionUserLockedOut": "User locked out",
|
||||
"NotificationOptionVideoPlayback": "Video playback started",
|
||||
|
@ -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}",
|
||||
"Channels": "Channels",
|
||||
"Channels": "Kanallar",
|
||||
"ChapterNameValue": "Chapter {0}",
|
||||
"Collections": "Collections",
|
||||
"DeviceOfflineWithName": "{0} has disconnected",
|
||||
@ -17,8 +17,8 @@
|
||||
"Genres": "Genres",
|
||||
"HeaderAlbumArtists": "Album Artists",
|
||||
"HeaderCameraUploads": "Camera Uploads",
|
||||
"HeaderContinueWatching": "Continue Watching",
|
||||
"HeaderFavoriteAlbums": "Favorite Albums",
|
||||
"HeaderContinueWatching": "İzlemeye Devam Et",
|
||||
"HeaderFavoriteAlbums": "Favori Albümler",
|
||||
"HeaderFavoriteArtists": "Favorite Artists",
|
||||
"HeaderFavoriteEpisodes": "Favorite Episodes",
|
||||
"HeaderFavoriteShows": "Favori Showlar",
|
||||
@ -30,21 +30,21 @@
|
||||
"Inherit": "Inherit",
|
||||
"ItemAddedWithName": "{0} was added to 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",
|
||||
"MessageApplicationUpdated": "Jellyfin Server has been updated",
|
||||
"MessageApplicationUpdated": "Jellyfin Sunucusu güncellendi",
|
||||
"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.",
|
||||
"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",
|
||||
"NotificationOptionApplicationUpdateInstalled": "Application update installed",
|
||||
"NotificationOptionAudioPlayback": "Audio playback started",
|
||||
|
@ -34,14 +34,14 @@
|
||||
"LabelRunningTimeValue": "运行时间:{0}",
|
||||
"Latest": "最新",
|
||||
"MessageApplicationUpdated": "Jellyfin 服务器已更新",
|
||||
"MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
|
||||
"MessageApplicationUpdatedTo": "Jellyfin Server 的版本已更新为 {0}",
|
||||
"MessageNamedServerConfigurationUpdatedWithValue": "服务器配置 {0} 部分已更新",
|
||||
"MessageServerConfigurationUpdated": "服务器配置已更新",
|
||||
"MixedContent": "混合内容",
|
||||
"Movies": "电影",
|
||||
"Music": "音乐",
|
||||
"MusicVideos": "音乐视频",
|
||||
"NameInstallFailed": "{0} installation failed",
|
||||
"NameInstallFailed": "{0} 安装失败",
|
||||
"NameSeasonNumber": "季 {0}",
|
||||
"NameSeasonUnknown": "未知季",
|
||||
"NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
|
||||
@ -70,7 +70,7 @@
|
||||
"ProviderValue": "提供商:{0}",
|
||||
"ScheduledTaskFailedWithName": "{0} 已失败",
|
||||
"ScheduledTaskStartedWithName": "{0} 已开始",
|
||||
"ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
|
||||
"ServerNameNeedsToBeRestarted": "{0} 需要重新启动",
|
||||
"Shows": "节目",
|
||||
"Songs": "歌曲",
|
||||
"StartupEmbyServerIsLoading": "Jellyfin 服务器加载中。请稍后再试。",
|
||||
|
@ -11,7 +11,6 @@ using MediaBrowser.Controller.Configuration;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.Extensions;
|
||||
using MediaBrowser.Model.Globalization;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
@ -35,7 +34,6 @@ namespace Emby.Server.Implementations.Localization
|
||||
private readonly Dictionary<string, Dictionary<string, ParentalRating>> _allParentalRatings =
|
||||
new Dictionary<string, Dictionary<string, ParentalRating>>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private readonly IFileSystem _fileSystem;
|
||||
private readonly IJsonSerializer _jsonSerializer;
|
||||
private readonly ILogger _logger;
|
||||
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.
|
||||
/// </summary>
|
||||
/// <param name="configurationManager">The configuration manager.</param>
|
||||
/// <param name="fileSystem">The file system.</param>
|
||||
/// <param name="jsonSerializer">The json serializer.</param>
|
||||
/// <param name="loggerFactory">The logger factory</param>
|
||||
public LocalizationManager(
|
||||
IServerConfigurationManager configurationManager,
|
||||
IFileSystem fileSystem,
|
||||
IJsonSerializer jsonSerializer,
|
||||
ILoggerFactory loggerFactory)
|
||||
{
|
||||
_configurationManager = configurationManager;
|
||||
_fileSystem = fileSystem;
|
||||
_jsonSerializer = jsonSerializer;
|
||||
_logger = loggerFactory.CreateLogger(nameof(LocalizationManager));
|
||||
}
|
||||
|
||||
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
|
||||
foreach (var resource in _assembly.GetManifestResourceNames())
|
||||
{
|
||||
if (!resource.StartsWith(ratingsResource))
|
||||
if (!resource.StartsWith(RatingsResource, StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
string filename = "ratings-" + resource.Substring(ratingsResource.Length);
|
||||
string countryCode = resource.Substring(RatingsResource.Length, 2);
|
||||
var dict = new Dictionary<string, ParentalRating>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
if (existingFiles.Contains(filename))
|
||||
using (var str = _assembly.GetManifestResourceStream(resource))
|
||||
using (var reader = new StreamReader(str))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
using (var stream = _assembly.GetManifestResourceStream(resource))
|
||||
{
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
_allParentalRatings[countryCode] = dict;
|
||||
}
|
||||
|
||||
foreach (var file in GetRatingsFiles(LocalizationPath))
|
||||
{
|
||||
await LoadRatings(file);
|
||||
}
|
||||
|
||||
LoadAdditionalRatings();
|
||||
|
||||
await LoadCultures();
|
||||
await LoadCultures().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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)
|
||||
=> text.Normalize(NormalizationForm.FormKD);
|
||||
|
||||
@ -184,14 +117,14 @@ namespace Emby.Server.Implementations.Localization
|
||||
{
|
||||
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))
|
||||
{
|
||||
while (!reader.EndOfStream)
|
||||
{
|
||||
var line = await reader.ReadLineAsync();
|
||||
var line = await reader.ReadLineAsync().ConfigureAwait(false);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(line))
|
||||
{
|
||||
@ -217,11 +150,11 @@ namespace Emby.Server.Implementations.Localization
|
||||
string[] threeletterNames;
|
||||
if (string.IsNullOrWhiteSpace(parts[1]))
|
||||
{
|
||||
threeletterNames = new [] { parts[0] };
|
||||
threeletterNames = new[] { parts[0] };
|
||||
}
|
||||
else
|
||||
{
|
||||
threeletterNames = new [] { parts[0], parts[1] };
|
||||
threeletterNames = new[] { parts[0], parts[1] };
|
||||
}
|
||||
|
||||
list.Add(new CultureDto
|
||||
@ -281,6 +214,7 @@ namespace Emby.Server.Implementations.Localization
|
||||
/// Gets the ratings.
|
||||
/// </summary>
|
||||
/// <param name="countryCode">The country code.</param>
|
||||
/// <returns>The ratings</returns>
|
||||
private Dictionary<string, ParentalRating> GetRatings(string countryCode)
|
||||
{
|
||||
_allParentalRatings.TryGetValue(countryCode, out var value);
|
||||
@ -288,52 +222,14 @@ namespace Emby.Server.Implementations.Localization
|
||||
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" };
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <summary>
|
||||
/// Gets the rating level.
|
||||
/// </summary>
|
||||
/// <param name="rating">Rating field</param>
|
||||
/// <returns>The rating level</returns>>
|
||||
public int? GetRatingLevel(string rating)
|
||||
{
|
||||
if (string.IsNullOrEmpty(rating))
|
||||
@ -405,6 +301,7 @@ namespace Emby.Server.Implementations.Localization
|
||||
{
|
||||
culture = _configurationManager.Configuration.UICulture;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(culture))
|
||||
{
|
||||
culture = DefaultCulture;
|
||||
@ -450,8 +347,8 @@ namespace Emby.Server.Implementations.Localization
|
||||
|
||||
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;
|
||||
}
|
||||
@ -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 (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)
|
||||
{
|
||||
|
8
Emby.Server.Implementations/Localization/Ratings/au.csv
Normal file
8
Emby.Server.Implementations/Localization/Ratings/au.csv
Normal file
@ -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
Emby.Server.Implementations/Localization/Ratings/be.csv
Normal file
6
Emby.Server.Implementations/Localization/Ratings/be.csv
Normal file
@ -0,0 +1,6 @@
|
||||
BE-AL,1
|
||||
BE-MG6,2
|
||||
BE-6,3
|
||||
BE-9,5
|
||||
BE-12,6
|
||||
BE-16,8
|
|
10
Emby.Server.Implementations/Localization/Ratings/de.csv
Normal file
10
Emby.Server.Implementations/Localization/Ratings/de.csv
Normal file
@ -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
Emby.Server.Implementations/Localization/Ratings/ru.csv
Normal file
5
Emby.Server.Implementations/Localization/Ratings/ru.csv
Normal file
@ -0,0 +1,5 @@
|
||||
RU-0+,1
|
||||
RU-6+,3
|
||||
RU-12+,7
|
||||
RU-16+,9
|
||||
RU-18+,10
|
|
@ -202,6 +202,10 @@ namespace Emby.Server.Implementations.MediaEncoder
|
||||
private static List<string> GetSavedChapterImages(Video video, IDirectoryService directoryService)
|
||||
{
|
||||
var path = GetChapterImagesPath(video);
|
||||
if (!Directory.Exists(path))
|
||||
{
|
||||
return new List<string>();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -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
|
||||
}
|
||||
}
|
@ -45,9 +45,4 @@ namespace Emby.Server.Implementations.Net
|
||||
/// <returns>Task.</returns>
|
||||
Task SendAsync(string text, bool endOfMessage, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public interface IMemoryWebSocket
|
||||
{
|
||||
Action<Memory<byte>, int> OnReceiveMemoryBytes { get; set; }
|
||||
}
|
||||
}
|
||||
|
@ -4,7 +4,6 @@ using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using Emby.Server.Implementations.Networking;
|
||||
using MediaBrowser.Model.Net;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Emby.Server.Implementations.Net
|
||||
{
|
||||
@ -19,7 +18,10 @@ namespace Emby.Server.Implementations.Net
|
||||
|
||||
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
|
||||
? AddressFamily.InterNetwork
|
||||
@ -42,8 +44,7 @@ namespace Emby.Server.Implementations.Net
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (retVal != null)
|
||||
retVal.Dispose();
|
||||
retVal?.Dispose();
|
||||
|
||||
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>
|
||||
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);
|
||||
try
|
||||
@ -65,8 +69,7 @@ namespace Emby.Server.Implementations.Net
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (retVal != null)
|
||||
retVal.Dispose();
|
||||
retVal?.Dispose();
|
||||
|
||||
throw;
|
||||
}
|
||||
@ -74,7 +77,10 @@ namespace Emby.Server.Implementations.Net
|
||||
|
||||
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);
|
||||
try
|
||||
@ -86,8 +92,7 @@ namespace Emby.Server.Implementations.Net
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (retVal != null)
|
||||
retVal.Dispose();
|
||||
retVal?.Dispose();
|
||||
|
||||
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>
|
||||
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);
|
||||
try
|
||||
@ -114,8 +122,7 @@ namespace Emby.Server.Implementations.Net
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (retVal != null)
|
||||
retVal.Dispose();
|
||||
retVal?.Dispose();
|
||||
|
||||
throw;
|
||||
}
|
||||
@ -130,10 +137,25 @@ namespace Emby.Server.Implementations.Net
|
||||
/// <returns></returns>
|
||||
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);
|
||||
|
||||
@ -172,87 +194,13 @@ namespace Emby.Server.Implementations.Net
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (retVal != null)
|
||||
retVal.Dispose();
|
||||
retVal?.Dispose();
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -11,12 +11,15 @@ namespace Emby.Server.Implementations.Net
|
||||
// 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.
|
||||
|
||||
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()
|
||||
{
|
||||
@ -35,11 +38,11 @@ namespace Emby.Server.Implementations.Net
|
||||
{
|
||||
if (socket == null) throw new ArgumentNullException(nameof(socket));
|
||||
|
||||
_Socket = socket;
|
||||
_LocalPort = localPort;
|
||||
_socket = socket;
|
||||
_localPort = localPort;
|
||||
LocalIPAddress = NetworkManager.ToIpAddressInfo(ip);
|
||||
|
||||
_Socket.Bind(new IPEndPoint(ip, _LocalPort));
|
||||
_socket.Bind(new IPEndPoint(ip, _localPort));
|
||||
|
||||
InitReceiveSocketAsyncEventArgs();
|
||||
}
|
||||
@ -101,32 +104,26 @@ namespace Emby.Server.Implementations.Net
|
||||
{
|
||||
if (socket == null) throw new ArgumentNullException(nameof(socket));
|
||||
|
||||
_Socket = socket;
|
||||
_Socket.Connect(NetworkManager.ToIPEndPoint(endPoint));
|
||||
_socket = socket;
|
||||
_socket.Connect(NetworkManager.ToIPEndPoint(endPoint));
|
||||
|
||||
InitReceiveSocketAsyncEventArgs();
|
||||
}
|
||||
|
||||
public IpAddressInfo LocalIPAddress
|
||||
{
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
|
||||
public IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
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)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
return _Socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
|
||||
return _socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
|
||||
}
|
||||
|
||||
public SocketReceiveResult EndReceive(IAsyncResult result)
|
||||
@ -136,7 +133,7 @@ namespace Emby.Server.Implementations.Net
|
||||
var sender = new IPEndPoint(IPAddress.Any, 0);
|
||||
var remoteEndPoint = (EndPoint)sender;
|
||||
|
||||
var receivedBytes = _Socket.EndReceiveFrom(result, ref remoteEndPoint);
|
||||
var receivedBytes = _socket.EndReceiveFrom(result, ref remoteEndPoint);
|
||||
|
||||
var buffer = (byte[])result.AsyncState;
|
||||
|
||||
@ -236,37 +233,42 @@ namespace Emby.Server.Implementations.Net
|
||||
|
||||
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)
|
||||
{
|
||||
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();
|
||||
|
||||
var tcs = _currentReceiveTaskCompletionSource;
|
||||
if (tcs != null)
|
||||
{
|
||||
tcs.TrySetCanceled();
|
||||
}
|
||||
var sendTcs = _currentSendTaskCompletionSource;
|
||||
if (sendTcs != null)
|
||||
{
|
||||
sendTcs.TrySetCanceled();
|
||||
}
|
||||
throw new ObjectDisposedException(nameof(UdpSocket));
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
if (endpoint == null)
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user