diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml index 46c478b08d..13cc67528f 100644 --- a/.ci/azure-pipelines.yml +++ b/.ci/azure-pipelines.yml @@ -200,8 +200,8 @@ jobs: persistCredentials: true - task: CmdLine@2 - displayName: "Check out web" - condition: and(succeeded(), or(contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + displayName: "Check out web (master, release or tag)" + condition: and(succeeded(), or(contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master'), contains(variables['Build.SourceBranch'], 'tag')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI', 'BuildCompletion')) inputs: script: 'git clone --single-branch --branch $(Build.SourceBranchName) --depth=1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web' @@ -245,7 +245,7 @@ jobs: inputs: targetType: 'filePath' # Optional. Options: filePath, inline filePath: ./deployment/windows/build-jellyfin.ps1 # Required when targetType == FilePath - arguments: -InstallFFMPEG -InstallNSSM -MakeNSIS -UXLocation $(Agent.TempDirectory)\jellyfin-ux -InstallLocation $(build.artifactstagingdirectory) + arguments: -InstallFFMPEG -InstallNSSM -MakeNSIS -InstallTrayApp -UXLocation $(Agent.TempDirectory)\jellyfin-ux -InstallLocation $(build.artifactstagingdirectory) #script: '# Write your PowerShell commands here.Write-Host Hello World' # Required when targetType == Inline errorActionPreference: 'stop' # Optional. Options: stop, continue, silentlyContinue #failOnStderr: false # Optional diff --git a/.copr/Makefile b/.copr/Makefile index 84b98a0116..ba330ada95 100644 --- a/.copr/Makefile +++ b/.copr/Makefile @@ -1,8 +1,59 @@ -srpm: - dnf -y install git - git submodule update --init --recursive - cd deployment/fedora-package-x64; \ - ./create_tarball.sh; \ - rpmbuild -bs pkg-src/jellyfin.spec \ - --define "_sourcedir $$PWD/pkg-src/" \ - --define "_srcrpmdir $(outdir)" +VERSION := $(shell sed -ne '/^Version:/s/.* *//p' \ + deployment/fedora-package-x64/pkg-src/jellyfin.spec) + +deployment/fedora-package-x64/pkg-src/jellyfin-web-$(VERSION).tar.gz: + curl -f -L -o deployment/fedora-package-x64/pkg-src/jellyfin-web-$(VERSION).tar.gz \ + https://github.com/jellyfin/jellyfin-web/archive/v$(VERSION).tar.gz \ + || curl -f -L -o deployment/fedora-package-x64/pkg-src/jellyfin-web-$(VERSION).tar.gz \ + https://github.com/jellyfin/jellyfin-web/archive/master.tar.gz \ + +srpm: deployment/fedora-package-x64/pkg-src/jellyfin-web-$(VERSION).tar.gz + cd deployment/fedora-package-x64; \ + SOURCE_DIR=../.. \ + WORKDIR="$${PWD}"; \ + package_temporary_dir="$${WORKDIR}/pkg-dist-tmp"; \ + pkg_src_dir="$${WORKDIR}/pkg-src"; \ + GNU_TAR=1; \ + tar \ + --transform "s,^\.,jellyfin-$(VERSION)," \ + --exclude='.git*' \ + --exclude='**/.git' \ + --exclude='**/.hg' \ + --exclude='**/.vs' \ + --exclude='**/.vscode' \ + --exclude='deployment' \ + --exclude='**/bin' \ + --exclude='**/obj' \ + --exclude='**/.nuget' \ + --exclude='*.deb' \ + --exclude='*.rpm' \ + -czf "pkg-src/jellyfin-$(VERSION).tar.gz" \ + -C $${SOURCE_DIR} ./ || GNU_TAR=0; \ + if [ $${GNU_TAR} -eq 0 ]; then \ + package_temporary_dir="$$(mktemp -d)"; \ + mkdir -p "$${package_temporary_dir}/jellyfin"; \ + tar \ + --exclude='.git*' \ + --exclude='**/.git' \ + --exclude='**/.hg' \ + --exclude='**/.vs' \ + --exclude='**/.vscode' \ + --exclude='deployment' \ + --exclude='**/bin' \ + --exclude='**/obj' \ + --exclude='**/.nuget' \ + --exclude='*.deb' \ + --exclude='*.rpm' \ + -czf "$${package_temporary_dir}/jellyfin/jellyfin-$(VERSION).tar.gz" \ + -C $${SOURCE_DIR} ./; \ + mkdir -p "$${package_temporary_dir}/jellyfin-$(VERSION)"; \ + tar -xzf "$${package_temporary_dir}/jellyfin/jellyfin-$(VERSION).tar.gz" \ + -C "$${package_temporary_dir}/jellyfin-$(VERSION); \ + rm -f "$${package_temporary_dir}/jellyfin/jellyfin-$(VERSION).tar.gz"; \ + tar -czf "$${SOURCE_DIR}/SOURCES/pkg-src/jellyfin-$(VERSION).tar.gz" \ + -C "$${package_temporary_dir}" "jellyfin-$(VERSION); \ + rm -rf $${package_temporary_dir}; \ + fi; \ + rpmbuild -bs pkg-src/jellyfin.spec \ + --define "_sourcedir $$PWD/pkg-src/" \ + --define "_srcrpmdir $(outdir)" diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index ca89c1cb91..bd13d4b00e 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -30,6 +30,7 @@ assignees: '' - OS: [e.g. Docker, Debian, Windows] - Browser: [e.g. Firefox, Chrome, Safari] - Jellyfin Version: [e.g. 10.0.1] + - Installed Plugins: [e.g. none, Fanart, Anime, etc.] - Reverse proxy: [e.g. no, nginx, apache, etc.] **Additional context** diff --git a/.github/stale.yml b/.github/stale.yml index 9ea0e3796a..05892c44dc 100644 --- a/.github/stale.yml +++ b/.github/stale.yml @@ -1,7 +1,7 @@ # Number of days of inactivity before an issue becomes stale -daysUntilStale: 90 +daysUntilStale: 120 # Number of days of inactivity before a stale issue is closed -daysUntilClose: 14 +daysUntilClose: 21 # Issues with these labels will never be considered stale exemptLabels: - regression @@ -11,12 +11,15 @@ exemptLabels: - future - feature - enhancement + - confirmed # Label to use when marking an issue as stale staleLabel: stale # Comment to post when marking an issue as stale. Set to `false` to disable markComment: > - Issues go stale after 90d of inactivity. Mark the issue as fresh by adding a comment or commit. Stale issues close after an additional 14d of inactivity. - If this issue is safe to close now please do so. - If you have any questions you can reach us on [Matrix or Social Media](https://docs.jellyfin.org/general/getting-help.html). + This issue has gone 120 days without comment. To avoid abandoned issues, it will be closed in 21 days if there are no new comments. + + If you're the original submitter of this issue, please comment confirming if this issue still affects you in the latest release or nightlies, or close the issue if it has been fixed. If you're another user also affected by this bug, please comment confirming so. Either action will remove the stale label. + + This bot exists to prevent issues from becoming stale and forgotten. Jellyfin is always moving forward, and bugs are often fixed as side effects of other changes. We therefore ask that bug report authors remain vigilant about their issues to ensure they are closed if fixed, or re-confirmed - perhaps with fresh logs or reproduction examples - regularly. If you have any questions you can reach us on [Matrix or Social Media](https://docs.jellyfin.org/general/getting-help.html). # Comment to post when closing a stale issue. Set to `false` to disable closeComment: false diff --git a/.gitignore b/.gitignore index 34cf1a84c2..42243f01a8 100644 --- a/.gitignore +++ b/.gitignore @@ -268,3 +268,6 @@ doc/ # Deployment artifacts dist *.exe + +# BenchmarkDotNet artifacts +BenchmarkDotNet.Artifacts diff --git a/.vscode/launch.json b/.vscode/launch.json index 21b8323ea0..e2a09c0f15 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -10,7 +10,7 @@ "request": "launch", "preLaunchTask": "build", // If you have changed target frameworks, make sure to update the program path. - "program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/netcoreapp2.1/jellyfin.dll", + "program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/netcoreapp3.0/jellyfin.dll", "args": [], "cwd": "${workspaceFolder}/Jellyfin.Server", // For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window @@ -25,4 +25,4 @@ "processId": "${command:pickProcess}" } ,] -} \ No newline at end of file +} diff --git a/Dockerfile b/Dockerfile index 118acfc0f4..2a60bf1845 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,8 +1,8 @@ -ARG DOTNET_VERSION=2.2 +ARG DOTNET_VERSION=3.0 ARG FFMPEG_VERSION=latest FROM node:alpine as web-builder -ARG JELLYFIN_WEB_VERSION=v10.5.0 +ARG JELLYFIN_WEB_VERSION=master RUN apk add curl \ && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \ && cd jellyfin-web-* \ @@ -10,33 +10,39 @@ RUN apk add curl \ && yarn build \ && mv dist /dist -FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION} as builder +FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster as builder WORKDIR /repo COPY . . ENV DOTNET_CLI_TELEMETRY_OPTOUT=1 RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" --self-contained --runtime linux-x64 "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none" FROM jellyfin/ffmpeg:${FFMPEG_VERSION} as ffmpeg +FROM debian:buster-slim -FROM mcr.microsoft.com/dotnet/core/runtime:${DOTNET_VERSION} -COPY --from=ffmpeg / / +COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg COPY --from=builder /jellyfin /jellyfin COPY --from=web-builder /dist /jellyfin/jellyfin-web # Install dependencies: # libfontconfig1: needed for Skia +# libgomp1: needed for ffmpeg +# libva-drm2: needed for ffmpeg # mesa-va-drivers: needed for VAAPI RUN apt-get update \ && apt-get install --no-install-recommends --no-install-suggests -y \ - libfontconfig1 mesa-va-drivers \ + libfontconfig1 libgomp1 libva-drm2 mesa-va-drivers openssl \ && apt-get clean autoclean \ && apt-get autoremove \ && rm -rf /var/lib/apt/lists/* \ && mkdir -p /cache /config /media \ - && chmod 777 /cache /config /media + && chmod 777 /cache /config /media \ + && ln -s /opt/ffmpeg/bin/ffmpeg /usr/local/bin \ + && ln -s /opt/ffmpeg/bin/ffprobe /usr/local/bin + +ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 EXPOSE 8096 VOLUME /cache /config /media -ENTRYPOINT dotnet /jellyfin/jellyfin.dll \ - --datadir /config \ - --cachedir /cache \ - --ffmpeg /usr/local/bin/ffmpeg +ENTRYPOINT ["./jellyfin/jellyfin", \ + "--datadir", "/config", \ + "--cachedir", "/cache", \ + "--ffmpeg", "/usr/local/bin/ffmpeg"] diff --git a/Dockerfile.arm b/Dockerfile.arm index ec710620a7..fd3d1e0704 100644 --- a/Dockerfile.arm +++ b/Dockerfile.arm @@ -4,7 +4,7 @@ ARG DOTNET_VERSION=3.0 FROM node:alpine as web-builder -ARG JELLYFIN_WEB_VERSION=v10.5.0 +ARG JELLYFIN_WEB_VERSION=master RUN apk add curl \ && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \ && cd jellyfin-web-* \ @@ -17,8 +17,6 @@ FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION} as builder WORKDIR /repo COPY . . ENV DOTNET_CLI_TELEMETRY_OPTOUT=1 -# TODO Remove or update the sed line when we update dotnet version. -RUN find . -type f -exec sed -i 's/netcoreapp2.1/netcoreapp3.0/g' {} \; # Discard objs - may cause failures if exists RUN find . -type d -name obj | xargs -r rm -r # Build @@ -26,7 +24,7 @@ RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" FROM multiarch/qemu-user-static:x86_64-arm as qemu -FROM mcr.microsoft.com/dotnet/core/runtime:${DOTNET_VERSION}-stretch-slim-arm32v7 +FROM debian:stretch-slim-arm32v7 COPY --from=qemu /usr/bin/qemu-arm-static /usr/bin RUN apt-get update \ && apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \ @@ -36,9 +34,11 @@ RUN apt-get update \ COPY --from=builder /jellyfin /jellyfin COPY --from=web-builder /dist /jellyfin/jellyfin-web +ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 + EXPOSE 8096 VOLUME /cache /config /media -ENTRYPOINT dotnet /jellyfin/jellyfin.dll \ - --datadir /config \ - --cachedir /cache \ - --ffmpeg /usr/bin/ffmpeg +ENTRYPOINT ["./jellyfin/jellyfin", \ + "--datadir", "/config", \ + "--cachedir", "/cache", \ + "--ffmpeg", "/usr/bin/ffmpeg"] diff --git a/Dockerfile.arm64 b/Dockerfile.arm64 index 30de0bab49..3c1b2e3eab 100644 --- a/Dockerfile.arm64 +++ b/Dockerfile.arm64 @@ -4,7 +4,7 @@ ARG DOTNET_VERSION=3.0 FROM node:alpine as web-builder -ARG JELLYFIN_WEB_VERSION=v10.5.0 +ARG JELLYFIN_WEB_VERSION=master RUN apk add curl \ && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \ && cd jellyfin-web-* \ @@ -17,8 +17,6 @@ FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION} as builder WORKDIR /repo COPY . . ENV DOTNET_CLI_TELEMETRY_OPTOUT=1 -# TODO Remove or update the sed line when we update dotnet version. -RUN find . -type f -exec sed -i 's/netcoreapp2.1/netcoreapp3.0/g' {} \; # Discard objs - may cause failures if exists RUN find . -type d -name obj | xargs -r rm -r # Build @@ -26,7 +24,7 @@ RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" FROM multiarch/qemu-user-static:x86_64-aarch64 as qemu -FROM mcr.microsoft.com/dotnet/core/runtime:${DOTNET_VERSION}-stretch-slim-arm64v8 +FROM debian:stretch-slim-arm64v8 COPY --from=qemu /usr/bin/qemu-aarch64-static /usr/bin RUN apt-get update \ && apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \ @@ -36,9 +34,11 @@ RUN apt-get update \ COPY --from=builder /jellyfin /jellyfin COPY --from=web-builder /dist /jellyfin/jellyfin-web +ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 + EXPOSE 8096 VOLUME /cache /config /media -ENTRYPOINT dotnet /jellyfin/jellyfin.dll \ - --datadir /config \ - --cachedir /cache \ - --ffmpeg /usr/bin/ffmpeg +ENTRYPOINT ["./jellyfin/jellyfin", \ + "--datadir", "/config", \ + "--cachedir", "/cache", \ + "--ffmpeg", "/usr/bin/ffmpeg"] diff --git a/Emby.Dlna/Api/DlnaServerService.cs b/Emby.Dlna/Api/DlnaServerService.cs index 8bf3797f85..7ddcaf7e6e 100644 --- a/Emby.Dlna/Api/DlnaServerService.cs +++ b/Emby.Dlna/Api/DlnaServerService.cs @@ -6,6 +6,7 @@ using System.Text; using System.Threading.Tasks; using Emby.Dlna.Main; using MediaBrowser.Common.Extensions; +using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dlna; using MediaBrowser.Controller.Net; using MediaBrowser.Model.Services; @@ -108,12 +109,13 @@ namespace Emby.Dlna.Api public class DlnaServerService : IService, IRequiresRequest { - private readonly IDlnaManager _dlnaManager; - private const string XMLContentType = "text/xml; charset=UTF-8"; + private readonly IDlnaManager _dlnaManager; + private readonly IHttpResultFactory _resultFactory; + private readonly IServerConfigurationManager _configurationManager; + public IRequest Request { get; set; } - private IHttpResultFactory _resultFactory; private IContentDirectory ContentDirectory => DlnaEntryPoint.Current.ContentDirectory; @@ -121,10 +123,14 @@ namespace Emby.Dlna.Api private IMediaReceiverRegistrar MediaReceiverRegistrar => DlnaEntryPoint.Current.MediaReceiverRegistrar; - public DlnaServerService(IDlnaManager dlnaManager, IHttpResultFactory httpResultFactory) + public DlnaServerService( + IDlnaManager dlnaManager, + IHttpResultFactory httpResultFactory, + IServerConfigurationManager configurationManager) { _dlnaManager = dlnaManager; _resultFactory = httpResultFactory; + _configurationManager = configurationManager; } private string GetHeader(string name) @@ -205,19 +211,32 @@ namespace Emby.Dlna.Api var pathInfo = Parse(Request.PathInfo); var first = pathInfo[0]; + string baseUrl = _configurationManager.Configuration.BaseUrl; + // backwards compatibility - // TODO: Work out what this is doing. - if (string.Equals(first, "mediabrowser", StringComparison.OrdinalIgnoreCase) || - string.Equals(first, "emby", StringComparison.OrdinalIgnoreCase) || - string.Equals(first, "jellyfin", StringComparison.OrdinalIgnoreCase)) + if (baseUrl.Length == 0) + { + if (string.Equals(first, "mediabrowser", StringComparison.OrdinalIgnoreCase) + || string.Equals(first, "emby", StringComparison.OrdinalIgnoreCase)) + { + index++; + } + } + else if (string.Equals(first, baseUrl.Remove(0, 1))) { index++; + var second = pathInfo[1]; + if (string.Equals(second, "mediabrowser", StringComparison.OrdinalIgnoreCase) + || string.Equals(second, "emby", StringComparison.OrdinalIgnoreCase)) + { + index++; + } } return pathInfo[index]; } - private List Parse(string pathUri) + private static string[] Parse(string pathUri) { var actionParts = pathUri.Split(new[] { "://" }, StringSplitOptions.None); @@ -231,7 +250,7 @@ namespace Emby.Dlna.Api var args = pathInfo.Split('/'); - return args.Skip(1).ToList(); + return args.Skip(1).ToArray(); } public object Get(GetIcon request) diff --git a/Emby.Dlna/Emby.Dlna.csproj b/Emby.Dlna/Emby.Dlna.csproj index 34b49120bb..8d6fabdb44 100644 --- a/Emby.Dlna/Emby.Dlna.csproj +++ b/Emby.Dlna/Emby.Dlna.csproj @@ -12,7 +12,7 @@ - netstandard2.0 + netstandard2.1 false true diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs index a3a013096c..2ca44b7ea2 100644 --- a/Emby.Dlna/PlayTo/PlayToManager.cs +++ b/Emby.Dlna/PlayTo/PlayToManager.cs @@ -160,7 +160,7 @@ namespace Emby.Dlna.PlayTo uuid = location.GetMD5().ToString("N", CultureInfo.InvariantCulture); } - var sessionInfo = _sessionManager.LogSessionActivity("DLNA", _appHost.ApplicationVersion, uuid, null, uri.OriginalString, null); + var sessionInfo = _sessionManager.LogSessionActivity("DLNA", _appHost.ApplicationVersionString, uuid, null, uri.OriginalString, null); var controller = sessionInfo.SessionControllers.OfType().FirstOrDefault(); diff --git a/Emby.Dlna/Ssdp/DeviceDiscovery.cs b/Emby.Dlna/Ssdp/DeviceDiscovery.cs index 298f68a28e..c5f3593da8 100644 --- a/Emby.Dlna/Ssdp/DeviceDiscovery.cs +++ b/Emby.Dlna/Ssdp/DeviceDiscovery.cs @@ -4,8 +4,6 @@ using System.Linq; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Net; -using Microsoft.Extensions.Logging; using Rssdp; using Rssdp.Infrastructure; @@ -15,13 +13,14 @@ namespace Emby.Dlna.Ssdp { private bool _disposed; - private readonly ILogger _logger; private readonly IServerConfigurationManager _config; private event EventHandler> DeviceDiscoveredInternal; private int _listenerCount; private object _syncLock = new object(); + + /// public event EventHandler> DeviceDiscovered { add @@ -31,6 +30,7 @@ namespace Emby.Dlna.Ssdp _listenerCount++; DeviceDiscoveredInternal += value; } + StartInternal(); } remove @@ -43,21 +43,16 @@ namespace Emby.Dlna.Ssdp } } + /// public event EventHandler> DeviceLeft; private SsdpDeviceLocator _deviceLocator; - private readonly ISocketFactory _socketFactory; private ISsdpCommunicationsServer _commsServer; - public DeviceDiscovery( - ILoggerFactory loggerFactory, - IServerConfigurationManager config, - ISocketFactory socketFactory) + public DeviceDiscovery(IServerConfigurationManager config) { - _logger = loggerFactory.CreateLogger(nameof(DeviceDiscovery)); _config = config; - _socketFactory = socketFactory; } // Call this method from somewhere in your code to start the search. @@ -82,8 +77,8 @@ namespace Emby.Dlna.Ssdp //_DeviceLocator.NotificationFilter = "upnp:rootdevice"; // Connect our event handler so we process devices as they are found - _deviceLocator.DeviceAvailable += deviceLocator_DeviceAvailable; - _deviceLocator.DeviceUnavailable += _DeviceLocator_DeviceUnavailable; + _deviceLocator.DeviceAvailable += OnDeviceLocatorDeviceAvailable; + _deviceLocator.DeviceUnavailable += OnDeviceLocatorDeviceUnavailable; var dueTime = TimeSpan.FromSeconds(5); var interval = TimeSpan.FromSeconds(_config.GetDlnaConfiguration().ClientDiscoveryIntervalSeconds); @@ -94,7 +89,7 @@ namespace Emby.Dlna.Ssdp } // Process each found device in the event handler - void deviceLocator_DeviceAvailable(object sender, DeviceAvailableEventArgs e) + private void OnDeviceLocatorDeviceAvailable(object sender, DeviceAvailableEventArgs e) { var originalHeaders = e.DiscoveredDevice.ResponseHeaders; @@ -115,7 +110,7 @@ namespace Emby.Dlna.Ssdp DeviceDiscoveredInternal?.Invoke(this, args); } - private void _DeviceLocator_DeviceUnavailable(object sender, DeviceUnavailableEventArgs e) + private void OnDeviceLocatorDeviceUnavailable(object sender, DeviceUnavailableEventArgs e) { var originalHeaders = e.DiscoveredDevice.ResponseHeaders; diff --git a/Emby.Drawing/Emby.Drawing.csproj b/Emby.Drawing/Emby.Drawing.csproj index 2e539f2c7f..85cecdc44e 100644 --- a/Emby.Drawing/Emby.Drawing.csproj +++ b/Emby.Drawing/Emby.Drawing.csproj @@ -1,7 +1,7 @@ - netstandard2.0 + netstandard2.1 false true true @@ -17,9 +17,4 @@ - - - latest - - diff --git a/Emby.Naming/AudioBook/AudioBookFileInfo.cs b/Emby.Naming/AudioBook/AudioBookFileInfo.cs index 326ea05ef3..769e3d7fac 100644 --- a/Emby.Naming/AudioBook/AudioBookFileInfo.cs +++ b/Emby.Naming/AudioBook/AudioBookFileInfo.cs @@ -3,7 +3,7 @@ using System; namespace Emby.Naming.AudioBook { /// - /// Represents a single video file + /// Represents a single video file. /// public class AudioBookFileInfo : IComparable { diff --git a/Emby.Naming/AudioBook/AudioBookInfo.cs b/Emby.Naming/AudioBook/AudioBookInfo.cs index 600d3f05da..d53f53c528 100644 --- a/Emby.Naming/AudioBook/AudioBookInfo.cs +++ b/Emby.Naming/AudioBook/AudioBookInfo.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; namespace Emby.Naming.AudioBook { /// - /// Represents a complete video, including all parts and subtitles + /// Represents a complete video, including all parts and subtitles. /// public class AudioBookInfo { diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 88a9b46e63..d37be0e639 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -311,6 +311,14 @@ namespace Emby.Naming.Common } }, + // This isn't a Kodi naming rule, but the expression below causes false positives, + // so we make sure this one gets tested first. + // "Foo Bar 889" + new EpisodeExpression(@".*[\\\/](?![Ee]pisode)(?(\w+\s*?)*)\s(?\d{1,3})(-(?\d{2,3}))*[^\\\/]*$") + { + IsNamed = true + }, + new EpisodeExpression("[\\\\/\\._ \\[\\(-]([0-9]+)x([0-9]+(?:(?:[a-i]|\\.[1-9])(?![0-9]))?)([^\\\\/]*)$") { SupportsAbsoluteEpisodeNumbers = true @@ -328,28 +336,33 @@ namespace Emby.Naming.Common // *** End Kodi Standard Naming - new EpisodeExpression(@".*(\\|\/)[sS]?(?\d{1,4})[xX](?\d{1,3})[^\\\/]*$") +                // [bar] Foo - 1 [baz] + new EpisodeExpression(@".*?(\[.*?\])+.*?(?(\w+\s*?)+?)[-\s_]+(?\d+).*$") + { + IsNamed = true + }, + new EpisodeExpression(@".*(\\|\/)[sS]?(?\d+)[xX](?\d+)[^\\\/]*$") { IsNamed = true }, - new EpisodeExpression(@".*(\\|\/)[sS](?\d{1,4})[x,X]?[eE](?\d{1,3})[^\\\/]*$") + new EpisodeExpression(@".*(\\|\/)[sS](?\d+)[x,X]?[eE](?\d+)[^\\\/]*$") { IsNamed = true }, - new EpisodeExpression(@".*(\\|\/)(?((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?\d{1,4})[xX](?\d{1,3}))[^\\\/]*$") + new EpisodeExpression(@".*(\\|\/)(?((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?\d{1,4})[xX](?\d+))[^\\\/]*$") { IsNamed = true }, - new EpisodeExpression(@".*(\\|\/)(?[^\\\/]*)[sS](?\d{1,4})[xX\.]?[eE](?\d{1,3})[^\\\/]*$") + new EpisodeExpression(@".*(\\|\/)(?[^\\\/]*)[sS](?\d{1,4})[xX\.]?[eE](?\d+)[^\\\/]*$") { IsNamed = true }, // "01.avi" - new EpisodeExpression(@".*[\\\/](?\d{1,3})(-(?\d{2,3}))*\.\w+$") + new EpisodeExpression(@".*[\\\/](?\d+)(-(?\d+))*\.\w+$") { IsOptimistic = true, IsNamed = true @@ -654,9 +667,9 @@ namespace Emby.Naming.Common @".*(\\|\/)(?[^\\\/]*)[sS](?\d{1,4})[xX\.]?[eE](?\d{1,3})((-| - )?[xXeE](?\d{1,3}))+[^\\\/]*$", @".*(\\|\/)(?[^\\\/]*)[sS](?\d{1,4})[xX\.]?[eE](?\d{1,3})(-[xX]?[eE]?(?\d{1,3}))+[^\\\/]*$" }.Select(i => new EpisodeExpression(i) - { - IsNamed = true - }).ToArray(); + { + IsNamed = true + }).ToArray(); VideoFileExtensions = extensions .Distinct(StringComparer.OrdinalIgnoreCase) diff --git a/Emby.Naming/Emby.Naming.csproj b/Emby.Naming/Emby.Naming.csproj index fca0aa1b38..7258beaf49 100644 --- a/Emby.Naming/Emby.Naming.csproj +++ b/Emby.Naming/Emby.Naming.csproj @@ -3,6 +3,7 @@ netstandard2.1 false + true @@ -18,14 +19,14 @@ Jellyfin.Naming https://www.gnu.org/licenses/old-licenses/gpl-2.0.txt https://github.com/jellyfin/jellyfin - true - - - + + + + diff --git a/Emby.Naming/TV/SeasonPathParser.cs b/Emby.Naming/TV/SeasonPathParser.cs index 9096ccaf5d..f34faf8e83 100644 --- a/Emby.Naming/TV/SeasonPathParser.cs +++ b/Emby.Naming/TV/SeasonPathParser.cs @@ -25,7 +25,7 @@ namespace Emby.Naming.TV } /// - /// A season folder must contain one of these somewhere in the name + /// A season folder must contain one of these somewhere in the name. /// private static readonly string[] _seasonFolderNames = { @@ -124,7 +124,7 @@ namespace Emby.Naming.TV } /// - /// Extracts the season number from the second half of the Season folder name (everything after "Season", or "Staffel") + /// Extracts the season number from the second half of the Season folder name (everything after "Season", or "Staffel"). /// /// The path. /// System.Nullable{System.Int32}. diff --git a/Emby.Naming/Video/CleanDateTimeParser.cs b/Emby.Naming/Video/CleanDateTimeParser.cs index 25fa09c488..c6b6039d4d 100644 --- a/Emby.Naming/Video/CleanDateTimeParser.cs +++ b/Emby.Naming/Video/CleanDateTimeParser.cs @@ -8,7 +8,7 @@ using Emby.Naming.Common; namespace Emby.Naming.Video { /// - /// http://kodi.wiki/view/Advancedsettings.xml#video + /// . /// public class CleanDateTimeParser { diff --git a/Emby.Naming/Video/VideoFileInfo.cs b/Emby.Naming/Video/VideoFileInfo.cs index 78f688ca8a..2f42f77845 100644 --- a/Emby.Naming/Video/VideoFileInfo.cs +++ b/Emby.Naming/Video/VideoFileInfo.cs @@ -1,7 +1,7 @@ namespace Emby.Naming.Video { /// - /// Represents a single video file + /// Represents a single video file. /// public class VideoFileInfo { diff --git a/Emby.Naming/Video/VideoInfo.cs b/Emby.Naming/Video/VideoInfo.cs index 2e456bda2b..f576b6ca28 100644 --- a/Emby.Naming/Video/VideoInfo.cs +++ b/Emby.Naming/Video/VideoInfo.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; namespace Emby.Naming.Video { /// - /// Represents a complete video, including all parts and subtitles + /// Represents a complete video, including all parts and subtitles. /// public class VideoInfo { diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index 02a25c4b5b..91f443500f 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -41,7 +41,7 @@ namespace Emby.Naming.Video /// if set to true [is folder]. /// Whether or not the name should be parsed for info /// VideoFileInfo. - /// path + /// path is null. public VideoFileInfo Resolve(string path, bool isDirectory, bool parseName = true) { if (string.IsNullOrEmpty(path)) diff --git a/Emby.Notifications/Emby.Notifications.csproj b/Emby.Notifications/Emby.Notifications.csproj index cbd3bde4f9..004ded77b1 100644 --- a/Emby.Notifications/Emby.Notifications.csproj +++ b/Emby.Notifications/Emby.Notifications.csproj @@ -1,7 +1,7 @@ - netstandard2.0 + netstandard2.1 false true diff --git a/Emby.Photos/Emby.Photos.csproj b/Emby.Photos/Emby.Photos.csproj index b57b93a8c5..64692c3703 100644 --- a/Emby.Photos/Emby.Photos.csproj +++ b/Emby.Photos/Emby.Photos.csproj @@ -14,7 +14,7 @@ - netstandard2.0 + netstandard2.1 false true true @@ -22,7 +22,7 @@ - + diff --git a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs index 1514402d68..efaaa116c6 100644 --- a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs +++ b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs @@ -616,8 +616,8 @@ namespace Emby.Server.Implementations.Activity /// /// Constructs a string description of a time-span value. /// - /// The value of this item - /// The name of this item (singular form) + /// The value of this item. + /// The name of this item (singular form). private static string CreateValueString(int value, string description) { return string.Format( diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index 4832c19c4e..2a5d56c603 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; -using System.Threading; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Events; using MediaBrowser.Common.Extensions; @@ -16,7 +15,7 @@ using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.AppBase { /// - /// Class BaseConfigurationManager + /// Class BaseConfigurationManager. /// public abstract class BaseConfigurationManager : IConfigurationManager { @@ -35,7 +34,7 @@ namespace Emby.Server.Implementations.AppBase /// /// The _configuration sync lock. /// - private object _configurationSyncLock = new object(); + private readonly object _configurationSyncLock = new object(); /// /// The _configuration. @@ -48,7 +47,7 @@ namespace Emby.Server.Implementations.AppBase /// The application paths. /// The logger factory. /// The XML serializer. - /// The file system + /// The file system. protected BaseConfigurationManager(IApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IXmlSerializer xmlSerializer, IFileSystem fileSystem) { CommonApplicationPaths = applicationPaths; @@ -85,6 +84,7 @@ namespace Emby.Server.Implementations.AppBase /// /// The logger. protected ILogger Logger { get; private set; } + /// /// Gets the XML serializer. /// @@ -92,23 +92,39 @@ namespace Emby.Server.Implementations.AppBase protected IXmlSerializer XmlSerializer { get; private set; } /// - /// Gets or sets the application paths. + /// Gets the application paths. /// /// The application paths. public IApplicationPaths CommonApplicationPaths { get; private set; } /// - /// Gets the system configuration + /// Gets or sets the system configuration. /// /// The configuration. public BaseApplicationConfiguration CommonConfiguration { get { - // Lazy load - LazyInitializer.EnsureInitialized(ref _configuration, ref _configurationLoaded, ref _configurationSyncLock, () => (BaseApplicationConfiguration)ConfigurationHelper.GetXmlConfiguration(ConfigurationType, CommonApplicationPaths.SystemConfigurationFilePath, XmlSerializer)); - return _configuration; + if (_configurationLoaded) + { + return _configuration; + } + + lock (_configurationSyncLock) + { + if (_configurationLoaded) + { + return _configuration; + } + + _configuration = (BaseApplicationConfiguration)ConfigurationHelper.GetXmlConfiguration(ConfigurationType, CommonApplicationPaths.SystemConfigurationFilePath, XmlSerializer); + + _configurationLoaded = true; + + return _configuration; + } } + protected set { _configuration = value; @@ -158,7 +174,7 @@ namespace Emby.Server.Implementations.AppBase /// Replaces the configuration. /// /// The new configuration. - /// newConfiguration + /// newConfiguration is null. public virtual void ReplaceConfiguration(BaseApplicationConfiguration newConfiguration) { if (newConfiguration == null) @@ -201,7 +217,7 @@ namespace Emby.Server.Implementations.AppBase cachePath = CommonConfiguration.CachePath; } - Logger.LogInformation("Setting cache path to " + cachePath); + Logger.LogInformation("Setting cache path: {Path}", cachePath); ((BaseApplicationPaths)CommonApplicationPaths).CachePath = cachePath; } @@ -209,7 +225,7 @@ namespace Emby.Server.Implementations.AppBase /// Replaces the cache path. /// /// The new configuration. - /// + /// The new cache path doesn't exist. private void ValidateCachePath(BaseApplicationConfiguration newConfig) { var newPath = newConfig.CachePath; @@ -220,7 +236,7 @@ namespace Emby.Server.Implementations.AppBase // Validate if (!Directory.Exists(newPath)) { - throw new FileNotFoundException( + throw new DirectoryNotFoundException( string.Format( CultureInfo.InvariantCulture, "{0} does not exist.", @@ -299,8 +315,7 @@ namespace Emby.Server.Implementations.AppBase throw new ArgumentException("Expected configuration type is " + configurationType.Name); } - var validatingStore = configurationStore as IValidatingConfiguration; - if (validatingStore != null) + if (configurationStore is IValidatingConfiguration validatingStore) { var currentConfiguration = GetConfiguration(key); diff --git a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs index 90b97061f3..854d7b4cbf 100644 --- a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs +++ b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs @@ -6,13 +6,13 @@ using MediaBrowser.Model.Serialization; namespace Emby.Server.Implementations.AppBase { /// - /// Class ConfigurationHelper + /// Class ConfigurationHelper. /// public static class ConfigurationHelper { /// /// Reads an xml configuration file from the file system - /// It will immediately re-serialize and save if new serialization data is available due to property changes + /// It will immediately re-serialize and save if new serialization data is available due to property changes. /// /// The type. /// The path. diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 04904fc4a5..8c625539ab 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -88,7 +88,6 @@ using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; @@ -110,9 +109,8 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; -using ServiceStack; +using Microsoft.OpenApi.Models; using OperatingSystem = MediaBrowser.Common.System.OperatingSystem; namespace Emby.Server.Implementations @@ -232,7 +230,25 @@ namespace Emby.Server.Implementations } } - protected IServiceProvider _serviceProvider; + /// + /// Gets or sets the service provider. + /// + public IServiceProvider ServiceProvider { get; set; } + + /// + /// Gets the http port for the webhost. + /// + public int HttpPort { get; private set; } + + /// + /// Gets the https port for the webhost. + /// + public int HttpsPort { get; private set; } + + /// + /// Gets the content root for the webhost. + /// + public string ContentRoot { get; private set; } /// /// Gets the server configuration manager. @@ -321,7 +337,7 @@ namespace Emby.Server.Implementations private readonly IConfiguration _configuration; /// - /// Gets or sets the installation manager. + /// Gets the installation manager. /// /// The installation manager. protected IInstallationManager InstallationManager { get; private set; } @@ -362,7 +378,7 @@ namespace Emby.Server.Implementations { _configuration = configuration; - XmlSerializer = new MyXmlSerializer(fileSystem, loggerFactory); + XmlSerializer = new MyXmlSerializer(); NetworkManager = networkManager; networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets; @@ -410,13 +426,17 @@ namespace Emby.Server.Implementations _validAddressResults.Clear(); } - public string ApplicationVersion { get; } = typeof(ApplicationHost).Assembly.GetName().Version.ToString(3); + /// + public Version ApplicationVersion { get; } = typeof(ApplicationHost).Assembly.GetName().Version; + + /// + public string ApplicationVersionString { get; } = typeof(ApplicationHost).Assembly.GetName().Version.ToString(3); /// /// Gets the current application user agent. /// /// The application user agent. - public string ApplicationUserAgent => Name.Replace(' ', '-') + "/" + ApplicationVersion; + public string ApplicationUserAgent => Name.Replace(' ', '-') + "/" + ApplicationVersionString; /// /// Gets the email address for use within a comment section of a user agent field. @@ -452,20 +472,20 @@ namespace Emby.Server.Implementations public string Name => ApplicationProductName; /// - /// Creates an instance of type and resolves all constructor dependencies + /// Creates an instance of type and resolves all constructor dependencies. /// /// The type. /// System.Object. public object CreateInstance(Type type) - => ActivatorUtilities.CreateInstance(_serviceProvider, type); + => ActivatorUtilities.CreateInstance(ServiceProvider, type); /// - /// Creates an instance of type and resolves all constructor dependencies + /// Creates an instance of type and resolves all constructor dependencies. /// /// /// The type. /// T. public T CreateInstance() - => ActivatorUtilities.CreateInstance(_serviceProvider); + => ActivatorUtilities.CreateInstance(ServiceProvider); /// /// Creates the instance safe. @@ -477,7 +497,7 @@ namespace Emby.Server.Implementations try { Logger.LogDebug("Creating instance of {Type}", type); - return ActivatorUtilities.CreateInstance(_serviceProvider, type); + return ActivatorUtilities.CreateInstance(ServiceProvider, type); } catch (Exception ex) { @@ -491,12 +511,12 @@ namespace Emby.Server.Implementations /// /// The type /// ``0. - public T Resolve() => _serviceProvider.GetService(); + public T Resolve() => ServiceProvider.GetService(); /// /// Gets the export types. /// - /// The type + /// The type. /// IEnumerable{Type}. public IEnumerable GetExportTypes() { @@ -508,11 +528,12 @@ namespace Emby.Server.Implementations /// public IReadOnlyCollection GetExports(bool manageLifetime = true) { + // Convert to list so this isn't executed for each iteration var parts = GetExportTypes() .Select(CreateInstanceSafe) .Where(i => i != null) .Cast() - .ToList(); // Convert to list so this isn't executed for each iteration + .ToList(); if (manageLifetime) { @@ -607,77 +628,14 @@ namespace Emby.Server.Implementations await RegisterResources(serviceCollection).ConfigureAwait(false); - FindParts(); - - string contentRoot = ServerConfigurationManager.Configuration.DashboardSourcePath; - if (string.IsNullOrEmpty(contentRoot)) + ContentRoot = ServerConfigurationManager.Configuration.DashboardSourcePath; + if (string.IsNullOrEmpty(ContentRoot)) { - contentRoot = ServerConfigurationManager.ApplicationPaths.WebPath; - } - - var host = new WebHostBuilder() - .UseKestrel(options => - { - var addresses = ServerConfigurationManager - .Configuration - .LocalNetworkAddresses - .Select(NormalizeConfiguredLocalAddress) - .Where(i => i != null) - .ToList(); - if (addresses.Any()) - { - foreach (var address in addresses) - { - Logger.LogInformation("Kestrel listening on {ipaddr}", address); - options.Listen(address, HttpPort); - - if (EnableHttps && Certificate != null) - { - options.Listen(address, HttpsPort, listenOptions => listenOptions.UseHttps(Certificate)); - } - } - } - else - { - Logger.LogInformation("Kestrel listening on all interfaces"); - options.ListenAnyIP(HttpPort); - - if (EnableHttps && Certificate != null) - { - options.ListenAnyIP(HttpsPort, listenOptions => listenOptions.UseHttps(Certificate)); - } - } - }) - .UseContentRoot(contentRoot) - .ConfigureServices(services => - { - services.AddResponseCompression(); - services.AddHttpContextAccessor(); - }) - .Configure(app => - { - app.UseWebSockets(); - - app.UseResponseCompression(); - - // TODO app.UseMiddleware(); - app.Use(ExecuteWebsocketHandlerAsync); - app.Use(ExecuteHttpHandlerAsync); - }) - .Build(); - - try - { - await host.StartAsync().ConfigureAwait(false); - } - catch - { - Logger.LogError("Kestrel failed to start! This is most likely due to an invalid address or port bind - correct your bind configuration in system.xml and try again."); - throw; + ContentRoot = ServerConfigurationManager.ApplicationPaths.WebPath; } } - private async Task ExecuteWebsocketHandlerAsync(HttpContext context, Func next) + public async Task ExecuteWebsocketHandlerAsync(HttpContext context, Func next) { if (!context.WebSockets.IsWebSocketRequest) { @@ -688,7 +646,7 @@ namespace Emby.Server.Implementations await HttpServer.ProcessWebSocketRequest(context).ConfigureAwait(false); } - private async Task ExecuteHttpHandlerAsync(HttpContext context, Func next) + public async Task ExecuteHttpHandlerAsync(HttpContext context, Func next) { if (context.WebSockets.IsWebSocketRequest) { @@ -749,7 +707,8 @@ namespace Emby.Server.Implementations serviceCollection.AddSingleton(typeof(IStreamHelper), typeof(StreamHelper)); - serviceCollection.AddSingleton(typeof(ICryptoProvider), typeof(CryptographyProvider)); + var cryptoProvider = new CryptographyProvider(); + serviceCollection.AddSingleton(cryptoProvider); SocketFactory = new SocketFactory(); serviceCollection.AddSingleton(SocketFactory); @@ -788,7 +747,17 @@ namespace Emby.Server.Implementations _userRepository = GetUserRepository(); - UserManager = new UserManager(LoggerFactory.CreateLogger(), _userRepository, XmlSerializer, NetworkManager, () => ImageProcessor, () => DtoService, this, JsonSerializer, FileSystemManager); + UserManager = new UserManager( + LoggerFactory.CreateLogger(), + _userRepository, + XmlSerializer, + NetworkManager, + () => ImageProcessor, + () => DtoService, + this, + JsonSerializer, + FileSystemManager, + cryptoProvider); serviceCollection.AddSingleton(UserManager); @@ -866,8 +835,7 @@ namespace Emby.Server.Implementations NotificationManager = new NotificationManager(LoggerFactory, UserManager, ServerConfigurationManager); serviceCollection.AddSingleton(NotificationManager); - serviceCollection.AddSingleton( - new DeviceDiscovery(LoggerFactory, ServerConfigurationManager, SocketFactory)); + serviceCollection.AddSingleton(new DeviceDiscovery(ServerConfigurationManager)); ChapterManager = new ChapterManager(LibraryManager, LoggerFactory, ServerConfigurationManager, ItemRepository); serviceCollection.AddSingleton(ChapterManager); @@ -896,7 +864,7 @@ namespace Emby.Server.Implementations serviceCollection.AddSingleton(authContext); serviceCollection.AddSingleton(new SessionContext(UserManager, authContext, SessionManager)); - AuthService = new AuthService(authContext, ServerConfigurationManager, SessionManager, NetworkManager); + AuthService = new AuthService(LoggerFactory.CreateLogger(), authContext, ServerConfigurationManager, SessionManager, NetworkManager); serviceCollection.AddSingleton(AuthService); SubtitleEncoder = new MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder(LibraryManager, LoggerFactory, ApplicationPaths, FileSystemManager, MediaEncoder, JsonSerializer, HttpClient, MediaSourceManager, ProcessFactory); @@ -906,7 +874,7 @@ namespace Emby.Server.Implementations _displayPreferencesRepository.Initialize(); - var userDataRepo = new SqliteUserDataRepository(LoggerFactory, ApplicationPaths); + var userDataRepo = new SqliteUserDataRepository(LoggerFactory.CreateLogger(), ApplicationPaths); SetStaticProperties(); @@ -915,8 +883,6 @@ namespace Emby.Server.Implementations ((UserDataManager)UserDataManager).Repository = userDataRepo; ItemRepository.Initialize(userDataRepo, UserManager); ((LibraryManager)LibraryManager).ItemRepository = ItemRepository; - - _serviceProvider = serviceCollection.BuildServiceProvider(); } public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths) @@ -1007,7 +973,7 @@ namespace Emby.Server.Implementations } /// - /// Dirty hacks + /// Dirty hacks. /// private void SetStaticProperties() { @@ -1073,9 +1039,9 @@ namespace Emby.Server.Implementations /// /// Finds the parts. /// - protected void FindParts() + public void FindParts() { - InstallationManager = _serviceProvider.GetService(); + InstallationManager = ServiceProvider.GetService(); InstallationManager.PluginInstalled += PluginInstalled; if (!ServerConfigurationManager.Configuration.IsPortAuthorized) @@ -1204,7 +1170,7 @@ namespace Emby.Server.Implementations private CertificateInfo CertificateInfo { get; set; } - protected X509Certificate2 Certificate { get; private set; } + public X509Certificate2 Certificate { get; private set; } private IEnumerable GetUrlPrefixes() { @@ -1415,17 +1381,18 @@ namespace Emby.Server.Implementations /// /// Gets the system status. /// - /// The cancellation token + /// The cancellation token. /// SystemInfo. public async Task GetSystemInfo(CancellationToken cancellationToken) { var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false); + var transcodingTempPath = ConfigurationManager.GetTranscodePath(); return new SystemInfo { HasPendingRestart = HasPendingRestart, IsShuttingDown = IsShuttingDown, - Version = ApplicationVersion, + Version = ApplicationVersionString, WebSocketPortNumber = HttpPort, CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(), Id = SystemId, @@ -1443,7 +1410,7 @@ namespace Emby.Server.Implementations CanSelfRestart = CanSelfRestart, CanLaunchWebBrowser = CanLaunchWebBrowser, HasUpdateAvailable = HasUpdateAvailable, - TranscodingTempPath = ApplicationPaths.TranscodingTempPath, + TranscodingTempPath = transcodingTempPath, ServerName = FriendlyName, LocalAddress = localAddress, SupportsLibraryMonitor = true, @@ -1465,7 +1432,7 @@ namespace Emby.Server.Implementations return new PublicSystemInfo { - Version = ApplicationVersion, + Version = ApplicationVersionString, ProductName = ApplicationProductName, Id = SystemId, OperatingSystem = OperatingSystem.Id.ToString(), @@ -1588,7 +1555,7 @@ namespace Emby.Server.Implementations return resultList; } - private IPAddress NormalizeConfiguredLocalAddress(string address) + public IPAddress NormalizeConfiguredLocalAddress(string address) { var index = address.Trim('/').IndexOf('/'); @@ -1664,10 +1631,6 @@ namespace Emby.Server.Implementations ? Environment.MachineName : ServerConfigurationManager.Configuration.ServerName; - public int HttpPort { get; private set; } - - public int HttpsPort { get; private set; } - /// /// Shuts down. /// @@ -1730,7 +1693,7 @@ namespace Emby.Server.Implementations /// dns is prefixed with a valid Uri prefix. /// /// The external dns prefix to get the hostname of. - /// The hostname in + /// The hostname in . private static string GetHostnameFromExternalDns(string externalDns) { if (string.IsNullOrEmpty(externalDns)) @@ -1844,6 +1807,7 @@ namespace Emby.Server.Implementations internal class CertificateInfo { public string Path { get; set; } + public string Password { get; set; } } } diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index 54a027dac6..8e955f1b0e 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -470,10 +470,10 @@ namespace Emby.Server.Implementations.Channels _libraryManager.CreateItem(item, null); } - await item.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) + await item.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_fileSystem)) { ForceSave = !isNew && forceUpdate - }, cancellationToken); + }, cancellationToken).ConfigureAwait(false); return item; } @@ -636,7 +636,7 @@ namespace Emby.Server.Implementations.Channels private async Task RefreshLatestChannelItems(IChannel channel, CancellationToken cancellationToken) { - var internalChannel = await GetChannel(channel, cancellationToken); + var internalChannel = await GetChannel(channel, cancellationToken).ConfigureAwait(false); var query = new InternalItemsQuery(); query.Parent = internalChannel; @@ -1156,7 +1156,7 @@ namespace Emby.Server.Implementations.Channels if (isNew || forceUpdate || item.DateLastRefreshed == default(DateTime)) { - _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), RefreshPriority.Normal); + _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.Normal); } return item; diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs index bb5057b1c2..c5a77ce5b5 100644 --- a/Emby.Server.Implementations/Collections/CollectionManager.cs +++ b/Emby.Server.Implementations/Collections/CollectionManager.cs @@ -121,7 +121,7 @@ namespace Emby.Server.Implementations.Collections // This could cause it to get re-resolved as a plain folder var folderName = _fileSystem.GetValidFilename(name) + " [boxset]"; - var parentFolder = GetCollectionsFolder(true).Result; + var parentFolder = GetCollectionsFolder(true).GetAwaiter().GetResult(); if (parentFolder == null) { @@ -149,7 +149,7 @@ namespace Emby.Server.Implementations.Collections if (options.ItemIdList.Length > 0) { - AddToCollection(collection.Id, options.ItemIdList, false, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) + AddToCollection(collection.Id, options.ItemIdList, false, new MetadataRefreshOptions(new DirectoryService(_fileSystem)) { // The initial adding of items is going to create a local metadata file // This will cause internet metadata to be skipped as a result @@ -158,7 +158,7 @@ namespace Emby.Server.Implementations.Collections } else { - _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), RefreshPriority.High); + _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.High); } CollectionCreated?.Invoke(this, new CollectionCreatedEventArgs @@ -178,12 +178,12 @@ namespace Emby.Server.Implementations.Collections public void AddToCollection(Guid collectionId, IEnumerable ids) { - AddToCollection(collectionId, ids, true, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))); + AddToCollection(collectionId, ids, true, new MetadataRefreshOptions(new DirectoryService(_fileSystem))); } public void AddToCollection(Guid collectionId, IEnumerable ids) { - AddToCollection(collectionId, ids.Select(i => i.ToString("N", CultureInfo.InvariantCulture)), true, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))); + AddToCollection(collectionId, ids.Select(i => i.ToString("N", CultureInfo.InvariantCulture)), true, new MetadataRefreshOptions(new DirectoryService(_fileSystem))); } private void AddToCollection(Guid collectionId, IEnumerable ids, bool fireEvent, MetadataRefreshOptions refreshOptions) @@ -287,7 +287,7 @@ namespace Emby.Server.Implementations.Collections } collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None); - _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) + _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)) { ForceSave = true }, RefreshPriority.High); diff --git a/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs b/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs index c7f92b80b6..2291345bee 100644 --- a/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs +++ b/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.IO; using Emby.Server.Implementations.AppBase; using MediaBrowser.Common.Configuration; @@ -14,7 +13,7 @@ using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Configuration { /// - /// Class ServerConfigurationManager + /// Class ServerConfigurationManager. /// public class ServerConfigurationManager : BaseConfigurationManager, IServerConfigurationManager { @@ -62,13 +61,6 @@ namespace Emby.Server.Implementations.Configuration base.OnConfigurationUpdated(); } - public override void AddParts(IEnumerable factories) - { - base.AddParts(factories); - - UpdateTranscodePath(); - } - /// /// Updates the metadata path. /// @@ -84,28 +76,6 @@ namespace Emby.Server.Implementations.Configuration } } - /// - /// Updates the transcoding temporary path. - /// - private void UpdateTranscodePath() - { - var encodingConfig = this.GetConfiguration("encoding"); - - ((ServerApplicationPaths)ApplicationPaths).TranscodingTempPath = string.IsNullOrEmpty(encodingConfig.TranscodingTempPath) ? - null : - Path.Combine(encodingConfig.TranscodingTempPath, "transcodes"); - } - - protected override void OnNamedConfigurationUpdated(string key, object configuration) - { - base.OnNamedConfigurationUpdated(key, configuration); - - if (string.Equals(key, "encoding", StringComparison.OrdinalIgnoreCase)) - { - UpdateTranscodePath(); - } - } - /// /// Replaces the configuration. /// @@ -123,7 +93,6 @@ namespace Emby.Server.Implementations.Configuration base.ReplaceConfiguration(newConfiguration); } - /// /// Validates the SSL certificate. /// diff --git a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs index 23b77e2687..fec7d161e5 100644 --- a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs +++ b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs @@ -30,6 +30,9 @@ namespace Emby.Server.Implementations.Cryptography private bool _disposed = false; + /// + /// Initializes a new instance of the class. + /// public CryptographyProvider() { // FIXME: When we get DotNet Standard 2.1 we need to revisit how we do the crypto @@ -59,12 +62,6 @@ namespace Emby.Server.Implementations.Cryptography throw new CryptographicException($"Cannot currently use PBKDF2 with requested hash method: {method}"); } - public byte[] ComputeHash(string hashMethod, byte[] bytes) - => ComputeHash(hashMethod, bytes, Array.Empty()); - - public byte[] ComputeHashWithDefaultMethod(byte[] bytes) - => ComputeHash(DefaultHashMethod, bytes); - public byte[] ComputeHash(string hashMethod, byte[] bytes, byte[] salt) { if (hashMethod == DefaultHashMethod) @@ -90,7 +87,6 @@ namespace Emby.Server.Implementations.Cryptography } throw new CryptographicException($"Requested hash method is not supported: {hashMethod}"); - } public byte[] ComputeHashWithDefaultMethod(byte[] bytes, byte[] salt) diff --git a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs index 2cd4d65b3a..2f6c1288da 100644 --- a/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteDisplayPreferencesRepository.cs @@ -110,8 +110,8 @@ namespace Emby.Server.Implementations.Data using (var statement = connection.PrepareStatement("replace into userdisplaypreferences (id, userid, client, data) values (@id, @userId, @client, @data)")) { - statement.TryBind("@id", displayPreferences.Id.ToGuidBlob()); - statement.TryBind("@userId", userId.ToGuidBlob()); + statement.TryBind("@id", new Guid(displayPreferences.Id).ToByteArray()); + statement.TryBind("@userId", userId.ToByteArray()); statement.TryBind("@client", client); statement.TryBind("@data", serialized); @@ -170,8 +170,8 @@ namespace Emby.Server.Implementations.Data { using (var statement = connection.PrepareStatement("select data from userdisplaypreferences where id = @id and userId=@userId and client=@client")) { - statement.TryBind("@id", guidId.ToGuidBlob()); - statement.TryBind("@userId", userId.ToGuidBlob()); + statement.TryBind("@id", guidId.ToByteArray()); + statement.TryBind("@userId", userId.ToByteArray()); statement.TryBind("@client", client); foreach (var row in statement.ExecuteQuery()) @@ -200,7 +200,7 @@ namespace Emby.Server.Implementations.Data using (var connection = GetConnection(true)) using (var statement = connection.PrepareStatement("select data from userdisplaypreferences where userId=@userId")) { - statement.TryBind("@userId", userId.ToGuidBlob()); + statement.TryBind("@userId", userId.ToByteArray()); foreach (var row in statement.ExecuteQuery()) { diff --git a/Emby.Server.Implementations/Data/SqliteExtensions.cs b/Emby.Server.Implementations/Data/SqliteExtensions.cs index e7c394b548..c76ae0cac0 100644 --- a/Emby.Server.Implementations/Data/SqliteExtensions.cs +++ b/Emby.Server.Implementations/Data/SqliteExtensions.cs @@ -9,6 +9,47 @@ namespace Emby.Server.Implementations.Data { public static class SqliteExtensions { + private const string DatetimeFormatUtc = "yyyy-MM-dd HH:mm:ss.FFFFFFFK"; + private const string DatetimeFormatLocal = "yyyy-MM-dd HH:mm:ss.FFFFFFF"; + + /// + /// An array of ISO-8601 DateTime formats that we support parsing. + /// + private static readonly string[] _datetimeFormats = new string[] + { + "THHmmssK", + "THHmmK", + "HH:mm:ss.FFFFFFFK", + "HH:mm:ssK", + "HH:mmK", + DatetimeFormatUtc, + "yyyy-MM-dd HH:mm:ssK", + "yyyy-MM-dd HH:mmK", + "yyyy-MM-ddTHH:mm:ss.FFFFFFFK", + "yyyy-MM-ddTHH:mmK", + "yyyy-MM-ddTHH:mm:ssK", + "yyyyMMddHHmmssK", + "yyyyMMddHHmmK", + "yyyyMMddTHHmmssFFFFFFFK", + "THHmmss", + "THHmm", + "HH:mm:ss.FFFFFFF", + "HH:mm:ss", + "HH:mm", + DatetimeFormatLocal, + "yyyy-MM-dd HH:mm:ss", + "yyyy-MM-dd HH:mm", + "yyyy-MM-ddTHH:mm:ss.FFFFFFF", + "yyyy-MM-ddTHH:mm", + "yyyy-MM-ddTHH:mm:ss", + "yyyyMMddHHmmss", + "yyyyMMddHHmm", + "yyyyMMddTHHmmssFFFFFFF", + "yyyy-MM-dd", + "yyyyMMdd", + "yy-MM-dd" + }; + public static void RunQueries(this SQLiteDatabaseConnection connection, string[] queries) { if (queries == null) @@ -22,16 +63,6 @@ namespace Emby.Server.Implementations.Data }); } - public static byte[] ToGuidBlob(this string str) - { - return ToGuidBlob(new Guid(str)); - } - - public static byte[] ToGuidBlob(this Guid guid) - { - return guid.ToByteArray(); - } - public static Guid ReadGuidFromBlob(this IResultSetValue result) { return new Guid(result.ToBlob()); @@ -50,58 +81,16 @@ namespace Emby.Server.Implementations.Data CultureInfo.InvariantCulture); } - private static string GetDateTimeKindFormat( - DateTimeKind kind) - { - return (kind == DateTimeKind.Utc) ? _datetimeFormatUtc : _datetimeFormatLocal; - } - - /// - /// An array of ISO-8601 DateTime formats that we support parsing. - /// - private static string[] _datetimeFormats = new string[] { - "THHmmssK", - "THHmmK", - "HH:mm:ss.FFFFFFFK", - "HH:mm:ssK", - "HH:mmK", - "yyyy-MM-dd HH:mm:ss.FFFFFFFK", /* NOTE: UTC default (5). */ - "yyyy-MM-dd HH:mm:ssK", - "yyyy-MM-dd HH:mmK", - "yyyy-MM-ddTHH:mm:ss.FFFFFFFK", - "yyyy-MM-ddTHH:mmK", - "yyyy-MM-ddTHH:mm:ssK", - "yyyyMMddHHmmssK", - "yyyyMMddHHmmK", - "yyyyMMddTHHmmssFFFFFFFK", - "THHmmss", - "THHmm", - "HH:mm:ss.FFFFFFF", - "HH:mm:ss", - "HH:mm", - "yyyy-MM-dd HH:mm:ss.FFFFFFF", /* NOTE: Non-UTC default (19). */ - "yyyy-MM-dd HH:mm:ss", - "yyyy-MM-dd HH:mm", - "yyyy-MM-ddTHH:mm:ss.FFFFFFF", - "yyyy-MM-ddTHH:mm", - "yyyy-MM-ddTHH:mm:ss", - "yyyyMMddHHmmss", - "yyyyMMddHHmm", - "yyyyMMddTHHmmssFFFFFFF", - "yyyy-MM-dd", - "yyyyMMdd", - "yy-MM-dd" - }; - - private static string _datetimeFormatUtc = _datetimeFormats[5]; - private static string _datetimeFormatLocal = _datetimeFormats[19]; + private static string GetDateTimeKindFormat(DateTimeKind kind) + => (kind == DateTimeKind.Utc) ? DatetimeFormatUtc : DatetimeFormatLocal; public static DateTime ReadDateTime(this IResultSetValue result) { var dateText = result.ToString(); return DateTime.ParseExact( - dateText, _datetimeFormats, + dateText, + _datetimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime(); } @@ -139,7 +128,10 @@ namespace Emby.Server.Implementations.Data public static void Attach(SQLiteDatabaseConnection db, string path, string alias) { - var commandText = string.Format("attach @path as {0};", alias); + var commandText = string.Format( + CultureInfo.InvariantCulture, + "attach @path as {0};", + alias); using (var statement = db.PrepareStatement(commandText)) { @@ -186,10 +178,7 @@ namespace Emby.Server.Implementations.Data private static void CheckName(string name) { #if DEBUG - //if (!name.IndexOf("@", StringComparison.OrdinalIgnoreCase) != 0) - { - throw new Exception("Invalid param name: " + name); - } + throw new ArgumentException("Invalid param name: " + name, nameof(name)); #endif } @@ -264,7 +253,7 @@ namespace Emby.Server.Implementations.Data { if (statement.BindParameters.TryGetValue(name, out IBindParameter bindParam)) { - bindParam.Bind(value.ToGuidBlob()); + bindParam.Bind(value.ToByteArray()); } else { @@ -392,8 +381,7 @@ namespace Emby.Server.Implementations.Data } } - public static IEnumerable> ExecuteQuery( - this IStatement This) + public static IEnumerable> ExecuteQuery(this IStatement This) { while (This.MoveNext()) { diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index b372ab55c2..69cfcb67b5 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -27,7 +27,6 @@ using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.LiveTv; using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; using SQLitePCL.pretty; @@ -548,7 +547,7 @@ namespace Emby.Server.Implementations.Data { using (var saveImagesStatement = base.PrepareStatement(db, "Update TypedBaseItems set Images=@Images where guid=@Id")) { - saveImagesStatement.TryBind("@Id", item.Id.ToGuidBlob()); + saveImagesStatement.TryBind("@Id", item.Id.ToByteArray()); saveImagesStatement.TryBind("@Images", SerializeImages(item)); saveImagesStatement.MoveNext(); @@ -658,12 +657,14 @@ namespace Emby.Server.Implementations.Data private void SaveItem(BaseItem item, BaseItem topParent, string userDataKey, IStatement saveItemStatement) { - saveItemStatement.TryBind("@guid", item.Id); - saveItemStatement.TryBind("@type", item.GetType().FullName); + Type type = item.GetType(); - if (TypeRequiresDeserialization(item.GetType())) + saveItemStatement.TryBind("@guid", item.Id); + saveItemStatement.TryBind("@type", type.FullName); + + if (TypeRequiresDeserialization(type)) { - saveItemStatement.TryBind("@data", JsonSerializer.SerializeToUtf8Bytes(item, _jsonOptions)); + saveItemStatement.TryBind("@data", JsonSerializer.SerializeToUtf8Bytes(item, type, _jsonOptions)); } else { @@ -1177,7 +1178,7 @@ namespace Emby.Server.Implementations.Data { if (id == Guid.Empty) { - throw new ArgumentException(nameof(id), "Guid can't be empty"); + throw new ArgumentException("Guid can't be empty", nameof(id)); } CheckDisposed(); @@ -1988,7 +1989,7 @@ namespace Emby.Server.Implementations.Data throw new ArgumentNullException(nameof(chapters)); } - var idBlob = id.ToGuidBlob(); + var idBlob = id.ToByteArray(); using (var connection = GetConnection()) { @@ -3760,7 +3761,7 @@ namespace Emby.Server.Implementations.Data if (statement != null) { - statement.TryBind(paramName, personId.ToGuidBlob()); + statement.TryBind(paramName, personId.ToByteArray()); } index++; } @@ -3971,7 +3972,7 @@ namespace Emby.Server.Implementations.Data clauses.Add("(guid in (select itemid from itemvalues where CleanValue = (select CleanName from TypedBaseItems where guid=" + paramName + ") and Type<=1))"); if (statement != null) { - statement.TryBind(paramName, artistId.ToGuidBlob()); + statement.TryBind(paramName, artistId.ToByteArray()); } index++; } @@ -3990,7 +3991,7 @@ namespace Emby.Server.Implementations.Data clauses.Add("(guid in (select itemid from itemvalues where CleanValue = (select CleanName from TypedBaseItems where guid=" + paramName + ") and Type=1))"); if (statement != null) { - statement.TryBind(paramName, artistId.ToGuidBlob()); + statement.TryBind(paramName, artistId.ToByteArray()); } index++; } @@ -4009,7 +4010,7 @@ namespace Emby.Server.Implementations.Data clauses.Add("((select CleanName from TypedBaseItems where guid=" + paramName + ") in (select CleanValue from itemvalues where ItemId=Guid and Type=0) AND (select CleanName from TypedBaseItems where guid=" + paramName + ") not in (select CleanValue from itemvalues where ItemId=Guid and Type=1))"); if (statement != null) { - statement.TryBind(paramName, artistId.ToGuidBlob()); + statement.TryBind(paramName, artistId.ToByteArray()); } index++; } @@ -4028,7 +4029,7 @@ namespace Emby.Server.Implementations.Data clauses.Add("Album in (select Name from typedbaseitems where guid=" + paramName + ")"); if (statement != null) { - statement.TryBind(paramName, albumId.ToGuidBlob()); + statement.TryBind(paramName, albumId.ToByteArray()); } index++; } @@ -4047,7 +4048,7 @@ namespace Emby.Server.Implementations.Data clauses.Add("(guid not in (select itemid from itemvalues where CleanValue = (select CleanName from TypedBaseItems where guid=" + paramName + ") and Type<=1))"); if (statement != null) { - statement.TryBind(paramName, artistId.ToGuidBlob()); + statement.TryBind(paramName, artistId.ToByteArray()); } index++; } @@ -4066,7 +4067,7 @@ namespace Emby.Server.Implementations.Data clauses.Add("(guid in (select itemid from itemvalues where CleanValue = (select CleanName from TypedBaseItems where guid=" + paramName + ") and Type=2))"); if (statement != null) { - statement.TryBind(paramName, genreId.ToGuidBlob()); + statement.TryBind(paramName, genreId.ToByteArray()); } index++; } @@ -4137,7 +4138,7 @@ namespace Emby.Server.Implementations.Data if (statement != null) { - statement.TryBind(paramName, studioId.ToGuidBlob()); + statement.TryBind(paramName, studioId.ToByteArray()); } index++; } @@ -4913,7 +4914,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type { connection.RunInTransaction(db => { - var idBlob = id.ToGuidBlob(); + var idBlob = id.ToByteArray(); // Delete people ExecuteWithSingleParam(db, "delete from People where ItemId=@Id", idBlob); @@ -5032,7 +5033,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type whereClauses.Add("ItemId=@ItemId"); if (statement != null) { - statement.TryBind("@ItemId", query.ItemId.ToGuidBlob()); + statement.TryBind("@ItemId", query.ItemId.ToByteArray()); } } if (!query.AppearsInItemId.Equals(Guid.Empty)) @@ -5040,7 +5041,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type whereClauses.Add("Name in (Select Name from People where ItemId=@AppearsInItemId)"); if (statement != null) { - statement.TryBind("@AppearsInItemId", query.AppearsInItemId.ToGuidBlob()); + statement.TryBind("@AppearsInItemId", query.AppearsInItemId.ToByteArray()); } } var queryPersonTypes = query.PersonTypes.Where(IsValidPersonType).ToList(); @@ -5109,7 +5110,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type CheckDisposed(); - var itemIdBlob = itemId.ToGuidBlob(); + var itemIdBlob = itemId.ToByteArray(); // First delete deleteAncestorsStatement.Reset(); @@ -5143,7 +5144,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type var ancestorId = ancestorIds[i]; - statement.TryBind("@AncestorId" + index, ancestorId.ToGuidBlob()); + statement.TryBind("@AncestorId" + index, ancestorId.ToByteArray()); statement.TryBind("@AncestorIdText" + index, ancestorId.ToString("N", CultureInfo.InvariantCulture)); } @@ -5608,7 +5609,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type CheckDisposed(); - var guidBlob = itemId.ToGuidBlob(); + var guidBlob = itemId.ToByteArray(); // First delete db.Execute("delete from ItemValues where ItemId=@Id", guidBlob); @@ -5632,10 +5633,13 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type { if (isSubsequentRow) { - insertText.Append(","); + insertText.Append(','); } - insertText.AppendFormat("(@ItemId, @Type{0}, @Value{0}, @CleanValue{0})", i.ToString(CultureInfo.InvariantCulture)); + insertText.AppendFormat( + CultureInfo.InvariantCulture, + "(@ItemId, @Type{0}, @Value{0}, @CleanValue{0})", + i); isSubsequentRow = true; } @@ -5688,7 +5692,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type { connection.RunInTransaction(db => { - var itemIdBlob = itemId.ToGuidBlob(); + var itemIdBlob = itemId.ToByteArray(); // First delete chapters db.Execute("delete from People where ItemId=@ItemId", itemIdBlob); @@ -5807,7 +5811,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type using (var statement = PrepareStatement(connection, cmdText)) { - statement.TryBind("@ItemId", query.ItemId.ToGuidBlob()); + statement.TryBind("@ItemId", query.ItemId.ToByteArray()); if (query.Type.HasValue) { @@ -5849,7 +5853,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type { connection.RunInTransaction(db => { - var itemIdBlob = id.ToGuidBlob(); + var itemIdBlob = id.ToByteArray(); // First delete chapters db.Execute("delete from mediastreams where ItemId=@ItemId", itemIdBlob); diff --git a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs index 9d4855bcf3..26ac17bdc2 100644 --- a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Threading; using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities; @@ -15,23 +14,19 @@ namespace Emby.Server.Implementations.Data public class SqliteUserDataRepository : BaseSqliteRepository, IUserDataRepository { public SqliteUserDataRepository( - ILoggerFactory loggerFactory, + ILogger logger, IApplicationPaths appPaths) - : base(loggerFactory.CreateLogger(nameof(SqliteUserDataRepository))) + : base(logger) { DbFilePath = Path.Combine(appPaths.DataPath, "library.db"); } - /// - /// Gets the name of the repository - /// - /// The name. + /// public string Name => "SQLite"; /// - /// Opens the connection to the database + /// Opens the connection to the database. /// - /// Task. public void Initialize(IUserManager userManager, SemaphoreSlim dbLock, SQLiteDatabaseConnection dbConnection) { WriteLock.Dispose(); @@ -97,7 +92,7 @@ namespace Emby.Server.Implementations.Data continue; } - statement.TryBind("@UserId", user.Id.ToGuidBlob()); + statement.TryBind("@UserId", user.Id.ToByteArray()); statement.TryBind("@InternalUserId", user.InternalId); statement.MoveNext(); diff --git a/Emby.Server.Implementations/Data/SqliteUserRepository.cs b/Emby.Server.Implementations/Data/SqliteUserRepository.cs index 80fe278f82..26798993b4 100644 --- a/Emby.Server.Implementations/Data/SqliteUserRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserRepository.cs @@ -116,7 +116,7 @@ namespace Emby.Server.Implementations.Data { using (var statement = db.PrepareStatement("insert into LocalUsersv2 (guid, data) values (@guid, @data)")) { - statement.TryBind("@guid", user.Id.ToGuidBlob()); + statement.TryBind("@guid", user.Id.ToByteArray()); statement.TryBind("@data", serialized); statement.MoveNext(); diff --git a/Emby.Server.Implementations/Devices/DeviceManager.cs b/Emby.Server.Implementations/Devices/DeviceManager.cs index d1704b3736..36d4418512 100644 --- a/Emby.Server.Implementations/Devices/DeviceManager.cs +++ b/Emby.Server.Implementations/Devices/DeviceManager.cs @@ -130,7 +130,6 @@ namespace Emby.Server.Implementations.Devices var session = _authRepo.Get(new AuthenticationInfoQuery { DeviceId = id - }).Items.FirstOrDefault(); var device = session == null ? null : ToDeviceInfo(session); diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index ea44442687..fde4d70599 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -3,6 +3,7 @@ + @@ -10,7 +11,6 @@ - @@ -29,12 +29,15 @@ - - - - + + + + + + + @@ -47,16 +50,12 @@ true - - - latest - - - - + + + diff --git a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs index f26a705867..a2619367d5 100644 --- a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs +++ b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs @@ -1,10 +1,9 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Net; +using System.Text; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Plugins; @@ -15,209 +14,134 @@ using Mono.Nat; namespace Emby.Server.Implementations.EntryPoints { + /// + /// Server entrypoint handling external port forwarding. + /// public class ExternalPortForwarding : IServerEntryPoint { private readonly IServerApplicationHost _appHost; private readonly ILogger _logger; - private readonly IHttpClient _httpClient; private readonly IServerConfigurationManager _config; private readonly IDeviceDiscovery _deviceDiscovery; + private readonly object _createdRulesLock = new object(); + private List _createdRules = new List(); private Timer _timer; + private string _lastConfigIdentifier; - private NatManager _natManager; + private bool _disposed = false; - public ExternalPortForwarding(ILoggerFactory loggerFactory, IServerApplicationHost appHost, IServerConfigurationManager config, IDeviceDiscovery deviceDiscovery, IHttpClient httpClient) + /// + /// Initializes a new instance of the class. + /// + /// The logger. + /// The application host. + /// The configuration manager. + /// The device discovery. + public ExternalPortForwarding( + ILogger logger, + IServerApplicationHost appHost, + IServerConfigurationManager config, + IDeviceDiscovery deviceDiscovery) { - _logger = loggerFactory.CreateLogger("PortMapper"); + _logger = logger; _appHost = appHost; _config = config; _deviceDiscovery = deviceDiscovery; - _httpClient = httpClient; - _config.ConfigurationUpdated += _config_ConfigurationUpdated1; } - private void _config_ConfigurationUpdated1(object sender, EventArgs e) - { - _config_ConfigurationUpdated(sender, e); - } - - private string _lastConfigIdentifier; private string GetConfigIdentifier() { - var values = new List(); + const char Separator = '|'; var config = _config.Configuration; - values.Add(config.EnableUPnP.ToString()); - values.Add(config.PublicPort.ToString(CultureInfo.InvariantCulture)); - values.Add(_appHost.HttpPort.ToString(CultureInfo.InvariantCulture)); - values.Add(_appHost.HttpsPort.ToString(CultureInfo.InvariantCulture)); - values.Add(_appHost.EnableHttps.ToString()); - values.Add((config.EnableRemoteAccess).ToString()); - - return string.Join("|", values.ToArray()); + return new StringBuilder(32) + .Append(config.EnableUPnP).Append(Separator) + .Append(config.PublicPort).Append(Separator) + .Append(_appHost.HttpPort).Append(Separator) + .Append(_appHost.HttpsPort).Append(Separator) + .Append(_appHost.EnableHttps).Append(Separator) + .Append(config.EnableRemoteAccess).Append(Separator) + .ToString(); } - private async void _config_ConfigurationUpdated(object sender, EventArgs e) + private void OnConfigurationUpdated(object sender, EventArgs e) { if (!string.Equals(_lastConfigIdentifier, GetConfigIdentifier(), StringComparison.OrdinalIgnoreCase)) { - DisposeNat(); - - await RunAsync(); + Stop(); + Start(); } } + /// public Task RunAsync() { - if (_config.Configuration.EnableUPnP && _config.Configuration.EnableRemoteAccess) - { - Start(); - } + Start(); - _config.ConfigurationUpdated -= _config_ConfigurationUpdated; - _config.ConfigurationUpdated += _config_ConfigurationUpdated; + _config.ConfigurationUpdated += OnConfigurationUpdated; return Task.CompletedTask; } private void Start() { - _logger.LogDebug("Starting NAT discovery"); - if (_natManager == null) + if (!_config.Configuration.EnableUPnP || !_config.Configuration.EnableRemoteAccess) { - _natManager = new NatManager(_logger, _httpClient); - _natManager.DeviceFound += NatUtility_DeviceFound; - _natManager.StartDiscovery(); + return; } + _logger.LogDebug("Starting NAT discovery"); + + NatUtility.DeviceFound += OnNatUtilityDeviceFound; + NatUtility.StartDiscovery(); + _timer = new Timer(ClearCreatedRules, null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10)); - _deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered; + _deviceDiscovery.DeviceDiscovered += OnDeviceDiscoveryDeviceDiscovered; _lastConfigIdentifier = GetConfigIdentifier(); } - private async void _deviceDiscovery_DeviceDiscovered(object sender, GenericEventArgs e) + private void Stop() { - if (_disposed) - { - return; - } + _logger.LogDebug("Stopping NAT discovery"); - var info = e.Argument; + NatUtility.StopDiscovery(); + NatUtility.DeviceFound -= OnNatUtilityDeviceFound; - if (!info.Headers.TryGetValue("USN", out string usn)) usn = string.Empty; + _timer?.Dispose(); - if (!info.Headers.TryGetValue("NT", out string nt)) nt = string.Empty; - - // Filter device type - if (usn.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 && - nt.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 && - usn.IndexOf("WANPPPConnection:", StringComparison.OrdinalIgnoreCase) == -1 && - nt.IndexOf("WANPPPConnection:", StringComparison.OrdinalIgnoreCase) == -1) - { - return; - } - - var identifier = string.IsNullOrWhiteSpace(usn) ? nt : usn; - - if (info.Location == null) - { - return; - } - - lock (_usnsHandled) - { - if (_usnsHandled.Contains(identifier)) - { - return; - } - _usnsHandled.Add(identifier); - } - - _logger.LogDebug("Found NAT device: " + identifier); - - if (IPAddress.TryParse(info.Location.Host, out var address)) - { - // The Handle method doesn't need the port - var endpoint = new IPEndPoint(address, info.Location.Port); - - IPAddress localAddress = null; - - try - { - var localAddressString = await _appHost.GetLocalApiUrl(CancellationToken.None).ConfigureAwait(false); - - if (Uri.TryCreate(localAddressString, UriKind.Absolute, out var uri)) - { - localAddressString = uri.Host; - - if (!IPAddress.TryParse(localAddressString, out localAddress)) - { - return; - } - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Error"); - return; - } - - if (_disposed) - { - return; - } - - // This should never happen, but the Handle method will throw ArgumentNullException if it does - if (localAddress == null) - { - return; - } - - var natManager = _natManager; - if (natManager != null) - { - await natManager.Handle(localAddress, info, endpoint, NatProtocol.Upnp).ConfigureAwait(false); - } - } + _deviceDiscovery.DeviceDiscovered -= OnDeviceDiscoveryDeviceDiscovered; } private void ClearCreatedRules(object state) { - lock (_createdRules) + lock (_createdRulesLock) { _createdRules.Clear(); } - lock (_usnsHandled) - { - _usnsHandled.Clear(); - } } - void NatUtility_DeviceFound(object sender, DeviceEventArgs e) + private void OnDeviceDiscoveryDeviceDiscovered(object sender, GenericEventArgs e) { - if (_disposed) - { - return; - } + NatUtility.Search(e.Argument.LocalIpAddress, NatProtocol.Upnp); + } + private void OnNatUtilityDeviceFound(object sender, DeviceEventArgs e) + { try { var device = e.Device; CreateRules(device); } - catch + catch (Exception ex) { - // Commenting out because users are reporting problems out of our control - //_logger.LogError(ex, "Error creating port forwarding rules"); + _logger.LogError(ex, "Error creating port forwarding rules"); } } - private List _createdRules = new List(); - private List _usnsHandled = new List(); private async void CreateRules(INatDevice device) { if (_disposed) @@ -227,15 +151,13 @@ namespace Emby.Server.Implementations.EntryPoints // On some systems the device discovered event seems to fire repeatedly // This check will help ensure we're not trying to port map the same device over and over - var address = device.LocalAddress; + var address = device.DeviceEndpoint; - var addressString = address.ToString(); - - lock (_createdRules) + lock (_createdRulesLock) { - if (!_createdRules.Contains(addressString)) + if (!_createdRules.Contains(address)) { - _createdRules.Add(addressString); + _createdRules.Add(address); } else { @@ -263,54 +185,43 @@ namespace Emby.Server.Implementations.EntryPoints } } - private Task CreatePortMap(INatDevice device, int privatePort, int publicPort) + private Task CreatePortMap(INatDevice device, int privatePort, int publicPort) { - _logger.LogDebug("Creating port map on local port {0} to public port {1} with device {2}", privatePort, publicPort, device.LocalAddress.ToString()); + _logger.LogDebug( + "Creating port map on local port {0} to public port {1} with device {2}", + privatePort, + publicPort, + device.DeviceEndpoint); - return device.CreatePortMap(new Mapping(Protocol.Tcp, privatePort, publicPort) - { - Description = _appHost.Name - }); + return device.CreatePortMapAsync( + new Mapping(Protocol.Tcp, privatePort, publicPort, 0, _appHost.Name)); } - private bool _disposed = false; + /// public void Dispose() { - _disposed = true; - DisposeNat(); + Dispose(true); + GC.SuppressFinalize(this); } - private void DisposeNat() + /// + /// Releases unmanaged and - optionally - managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected virtual void Dispose(bool dispose) { - _logger.LogDebug("Stopping NAT discovery"); - - if (_timer != null) + if (_disposed) { - _timer.Dispose(); - _timer = null; + return; } - _deviceDiscovery.DeviceDiscovered -= _deviceDiscovery_DeviceDiscovered; + _config.ConfigurationUpdated -= OnConfigurationUpdated; - var natManager = _natManager; + Stop(); - if (natManager != null) - { - _natManager = null; + _timer = null; - using (natManager) - { - try - { - natManager.StopDiscovery(); - natManager.DeviceFound -= NatUtility_DeviceFound; - } - catch (Exception ex) - { - _logger.LogError(ex, "Error stopping NAT Discovery"); - } - } - } + _disposed = true; } } } diff --git a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs index 9c0db2cf5e..24906220d1 100644 --- a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs @@ -21,7 +21,7 @@ namespace Emby.Server.Implementations.EntryPoints public class LibraryChangedNotifier : IServerEntryPoint { /// - /// The _library manager + /// The library manager. /// private readonly ILibraryManager _libraryManager; @@ -30,7 +30,7 @@ namespace Emby.Server.Implementations.EntryPoints private readonly ILogger _logger; /// - /// The _library changed sync lock + /// The library changed sync lock. /// private readonly object _libraryChangedSyncLock = new object(); @@ -48,7 +48,7 @@ namespace Emby.Server.Implementations.EntryPoints private Timer LibraryUpdateTimer { get; set; } /// - /// The library update duration + /// The library update duration. /// private const int LibraryUpdateDuration = 30000; @@ -188,8 +188,11 @@ namespace Emby.Server.Implementations.EntryPoints { if (LibraryUpdateTimer == null) { - LibraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, LibraryUpdateDuration, - Timeout.Infinite); + LibraryUpdateTimer = new Timer( + LibraryUpdateTimerCallback, + null, + LibraryUpdateDuration, + Timeout.Infinite); } else { @@ -452,7 +455,7 @@ namespace Emby.Server.Implementations.EntryPoints return new[] { item }; } - return new T[] { }; + return Array.Empty(); } /// diff --git a/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs b/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs index b2328121e3..3a7516dca9 100644 --- a/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs +++ b/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs @@ -54,7 +54,7 @@ namespace Emby.Server.Implementations.EntryPoints { cancellationToken.ThrowIfCancellationRequested(); - await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false); + await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_fileSystem)), cancellationToken).ConfigureAwait(false); } } diff --git a/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs b/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs index 141e729584..3ff8d99685 100644 --- a/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/ServerEventNotifier.cs @@ -156,7 +156,7 @@ namespace Emby.Server.Implementations.EntryPoints { try { - await _sessionManager.SendMessageToAdminSessions(name, data, CancellationToken.None); + await _sessionManager.SendMessageToAdminSessions(name, data, CancellationToken.None).ConfigureAwait(false); } catch (Exception) { diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs index 0e6083773d..2da0191ddb 100644 --- a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs +++ b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs @@ -325,7 +325,7 @@ namespace Emby.Server.Implementations.HttpClientManager if (options.LogErrorResponseBody) { - var msg = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + string msg = await response.Content.ReadAsStringAsync().ConfigureAwait(false); _logger.LogError("HTTP request failed with message: {Message}", msg); } diff --git a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs index e4f98acb9b..6dd016f8a2 100644 --- a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -7,7 +7,6 @@ using System.Net.Sockets; using System.Reflection; using System.Threading; using System.Threading.Tasks; -using Emby.Server.Implementations.Configuration; using Emby.Server.Implementations.Net; using Emby.Server.Implementations.Services; using MediaBrowser.Common.Extensions; @@ -16,11 +15,9 @@ using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Net; 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; @@ -166,7 +163,7 @@ namespace Emby.Server.Implementations.HttpServer { OnReceive = ProcessWebSocketMessageReceived, Url = e.Url, - QueryString = e.QueryString ?? new QueryCollection() + QueryString = e.QueryString }; connection.Closed += OnConnectionClosed; @@ -539,6 +536,11 @@ namespace Emby.Server.Implementations.HttpServer } finally { + if (httpRes.StatusCode >= 500) + { + _logger.LogDebug("Sending HTTP Response 500 in response to {Url}", urlToLog); + } + stopWatch.Stop(); var elapsed = stopWatch.Elapsed; if (elapsed.TotalMilliseconds > 500) diff --git a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs index 0b2924a3ba..b5cfb6b09a 100644 --- a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs +++ b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs @@ -460,7 +460,7 @@ namespace Emby.Server.Implementations.HttpServer if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException(nameof(path)); + throw new ArgumentException("Path can't be empty.", nameof(options)); } if (fileShare != FileShareMode.Read && fileShare != FileShareMode.ReadWrite) diff --git a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs index e27f794ba6..320136d11a 100644 --- a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs +++ b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs @@ -48,12 +48,14 @@ namespace Emby.Server.Implementations.HttpServer public IDictionary Headers => _options; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The range header. + /// The content length. /// The source. /// Type of the content. /// if set to true [is head request]. + /// The logger instance. public RangeRequestWriter(string rangeHeader, long contentLength, Stream source, string contentType, bool isHeadRequest, ILogger logger) { if (string.IsNullOrEmpty(contentType)) diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs index 93a61fe67a..594f464989 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using Emby.Server.Implementations.SocketSharp; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; @@ -7,22 +8,27 @@ using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Security; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Services; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.HttpServer.Security { public class AuthService : IAuthService { + private readonly ILogger _logger; private readonly IAuthorizationContext _authorizationContext; private readonly ISessionManager _sessionManager; private readonly IServerConfigurationManager _config; private readonly INetworkManager _networkManager; public AuthService( + ILogger logger, IAuthorizationContext authorizationContext, IServerConfigurationManager config, ISessionManager sessionManager, INetworkManager networkManager) { + _logger = logger; _authorizationContext = authorizationContext; _config = config; _sessionManager = sessionManager; @@ -34,7 +40,14 @@ namespace Emby.Server.Implementations.HttpServer.Security ValidateUser(request, authAttribtues); } - private void ValidateUser(IRequest request, IAuthenticationAttributes authAttribtues) + public User Authenticate(HttpRequest request, IAuthenticationAttributes authAttributes) + { + var req = new WebSocketSharpRequest(request, null, request.Path, _logger); + var user = ValidateUser(req, authAttributes); + return user; + } + + private User ValidateUser(IRequest request, IAuthenticationAttributes authAttribtues) { // This code is executed before the service var auth = _authorizationContext.GetAuthorizationInfo(request); @@ -81,6 +94,8 @@ namespace Emby.Server.Implementations.HttpServer.Security request.RemoteIp, user); } + + return user; } private void ValidateUserAccess( diff --git a/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs b/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs index c95b00ede2..c043568d55 100644 --- a/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs +++ b/Emby.Server.Implementations/Library/DefaultAuthenticationProvider.cs @@ -2,11 +2,11 @@ using System; using System.Linq; using System.Text; using System.Threading.Tasks; +using MediaBrowser.Common; using MediaBrowser.Common.Cryptography; using MediaBrowser.Controller.Authentication; using MediaBrowser.Controller.Entities; using MediaBrowser.Model.Cryptography; -using static MediaBrowser.Common.HexHelper; namespace Emby.Server.Implementations.Library { @@ -59,7 +59,10 @@ namespace Emby.Server.Implementations.Library if (_cryptographyProvider.GetSupportedHashMethods().Contains(readyHash.Id) || _cryptographyProvider.DefaultHashMethod == readyHash.Id) { - byte[] calculatedHash = _cryptographyProvider.ComputeHash(readyHash.Id, passwordbytes, readyHash.Salt); + byte[] calculatedHash = _cryptographyProvider.ComputeHash( + readyHash.Id, + passwordbytes, + readyHash.Salt); if (calculatedHash.SequenceEqual(readyHash.Hash)) { @@ -122,7 +125,7 @@ namespace Emby.Server.Implementations.Library { return string.IsNullOrEmpty(user.EasyPassword) ? null - : ToHexString(PasswordHash.Parse(user.EasyPassword).Hash); + : Hex.Encode(PasswordHash.Parse(user.EasyPassword).Hash); } /// diff --git a/Emby.Server.Implementations/Library/InvalidAuthProvider.cs b/Emby.Server.Implementations/Library/InvalidAuthProvider.cs index 6956369dc1..7913df5e40 100644 --- a/Emby.Server.Implementations/Library/InvalidAuthProvider.cs +++ b/Emby.Server.Implementations/Library/InvalidAuthProvider.cs @@ -1,7 +1,6 @@ using System.Threading.Tasks; using MediaBrowser.Controller.Authentication; using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Net; namespace Emby.Server.Implementations.Library { diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 9a2a6dc5f5..826cdb9c6e 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -519,7 +519,7 @@ namespace Emby.Server.Implementations.Library } public BaseItem ResolvePath(FileSystemMetadata fileInfo, Folder parent = null) - => ResolvePath(fileInfo, new DirectoryService(_logger, _fileSystem), null, parent); + => ResolvePath(fileInfo, new DirectoryService(_fileSystem), null, parent); private BaseItem ResolvePath( FileSystemMetadata fileInfo, @@ -1045,7 +1045,7 @@ namespace Emby.Server.Implementations.Library await RootFolder.ValidateChildren( new SimpleProgress(), cancellationToken, - new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), + new MetadataRefreshOptions(new DirectoryService(_fileSystem)), recursive: false).ConfigureAwait(false); await GetUserRootFolder().RefreshMetadata(cancellationToken).ConfigureAwait(false); @@ -1053,7 +1053,7 @@ namespace Emby.Server.Implementations.Library await GetUserRootFolder().ValidateChildren( new SimpleProgress(), cancellationToken, - new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), + new MetadataRefreshOptions(new DirectoryService(_fileSystem)), recursive: false).ConfigureAwait(false); // Quickly scan CollectionFolders for changes @@ -1074,7 +1074,7 @@ namespace Emby.Server.Implementations.Library innerProgress.RegisterAction(pct => progress.Report(pct * .96)); // Now validate the entire media library - await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), recursive: true).ConfigureAwait(false); + await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), recursive: true).ConfigureAwait(false); progress.Report(96); @@ -1899,7 +1899,7 @@ namespace Emby.Server.Implementations.Library /// The cancellation token. public void UpdateItem(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken) { - UpdateItems(new [] { item }, parent, updateReason, cancellationToken); + UpdateItems(new[] { item }, parent, updateReason, cancellationToken); } /// @@ -2135,7 +2135,7 @@ namespace Emby.Server.Implementations.Library if (refresh) { item.UpdateToRepository(ItemUpdateType.MetadataImport, CancellationToken.None); - _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), RefreshPriority.Normal); + _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.Normal); } return item; @@ -2175,7 +2175,6 @@ namespace Emby.Server.Implementations.Library DisplayParentId = parentId }; - CreateItem(item, null); isNew = true; @@ -2193,11 +2192,10 @@ namespace Emby.Server.Implementations.Library { _providerManagerFactory().QueueRefresh( item.Id, - new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) + new MetadataRefreshOptions(new DirectoryService(_fileSystem)) { // Need to force save to increment DateLastSaved ForceSave = true - }, RefreshPriority.Normal); } @@ -2261,7 +2259,7 @@ namespace Emby.Server.Implementations.Library { _providerManagerFactory().QueueRefresh( item.Id, - new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) + new MetadataRefreshOptions(new DirectoryService(_fileSystem)) { // Need to force save to increment DateLastSaved ForceSave = true @@ -2338,7 +2336,7 @@ namespace Emby.Server.Implementations.Library { _providerManagerFactory().QueueRefresh( item.Id, - new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) + new MetadataRefreshOptions(new DirectoryService(_fileSystem)) { // Need to force save to increment DateLastSaved ForceSave = true @@ -2487,6 +2485,15 @@ namespace Emby.Server.Implementations.Library { episode.ParentIndexNumber = season.IndexNumber; } + else + { + /* + Anime series don't generally have a season in their file name, however, + tvdb needs a season to correctly get the metadata. + Hence, a null season needs to be filled with something. */ + //FIXME perhaps this would be better for tvdb parser to ask for season 1 if no season is specified + episode.ParentIndexNumber = 1; + } if (episode.ParentIndexNumber.HasValue) { diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index d83e1fc021..7a26e0c37d 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -134,12 +134,13 @@ namespace Emby.Server.Implementations.Library if (allowMediaProbe && mediaSources[0].Type != MediaSourceType.Placeholder && !mediaSources[0].MediaStreams.Any(i => i.Type == MediaStreamType.Audio || i.Type == MediaStreamType.Video)) { - await item.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) - { - EnableRemoteContentProbe = true, - MetadataRefreshMode = MediaBrowser.Controller.Providers.MetadataRefreshMode.FullRefresh - - }, cancellationToken).ConfigureAwait(false); + await item.RefreshMetadata( + new MetadataRefreshOptions(new DirectoryService(_fileSystem)) + { + EnableRemoteContentProbe = true, + MetadataRefreshMode = MetadataRefreshMode.FullRefresh + }, + cancellationToken).ConfigureAwait(false); mediaSources = GetStaticMediaSources(item, enablePathSubstitution, user); } diff --git a/Emby.Server.Implementations/Library/SearchEngine.cs b/Emby.Server.Implementations/Library/SearchEngine.cs index c10b77a246..c749aec424 100644 --- a/Emby.Server.Implementations/Library/SearchEngine.cs +++ b/Emby.Server.Implementations/Library/SearchEngine.cs @@ -83,7 +83,7 @@ namespace Emby.Server.Implementations.Library if (string.IsNullOrEmpty(searchTerm)) { - throw new ArgumentNullException(nameof(searchTerm)); + throw new ArgumentNullException("SearchTerm can't be empty.", nameof(searchTerm)); } searchTerm = searchTerm.Trim().RemoveDiacritics(); diff --git a/Emby.Server.Implementations/Library/UserManager.cs b/Emby.Server.Implementations/Library/UserManager.cs index 52b2f56ffc..2b22129f33 100644 --- a/Emby.Server.Implementations/Library/UserManager.cs +++ b/Emby.Server.Implementations/Library/UserManager.cs @@ -24,6 +24,7 @@ using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Security; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Events; @@ -31,7 +32,6 @@ using MediaBrowser.Model.IO; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Users; using Microsoft.Extensions.Logging; -using static MediaBrowser.Common.HexHelper; namespace Emby.Server.Implementations.Library { @@ -60,6 +60,7 @@ namespace Emby.Server.Implementations.Library private readonly Func _dtoServiceFactory; private readonly IServerApplicationHost _appHost; private readonly IFileSystem _fileSystem; + private readonly ICryptoProvider _cryptoProvider; private ConcurrentDictionary _users; @@ -80,7 +81,8 @@ namespace Emby.Server.Implementations.Library Func dtoServiceFactory, IServerApplicationHost appHost, IJsonSerializer jsonSerializer, - IFileSystem fileSystem) + IFileSystem fileSystem, + ICryptoProvider cryptoProvider) { _logger = logger; _userRepository = userRepository; @@ -91,6 +93,7 @@ namespace Emby.Server.Implementations.Library _appHost = appHost; _jsonSerializer = jsonSerializer; _fileSystem = fileSystem; + _cryptoProvider = cryptoProvider; _users = null; } @@ -179,12 +182,7 @@ namespace Emby.Server.Implementations.Library _defaultPasswordResetProvider = passwordResetProviders.OfType().First(); } - /// - /// Gets a User by Id. - /// - /// The id. - /// User. - /// + /// public User GetUserById(Guid id) { if (id == Guid.Empty) @@ -196,11 +194,7 @@ namespace Emby.Server.Implementations.Library return user; } - /// - /// Gets the user by identifier. - /// - /// The identifier. - /// User. + /// public User GetUserById(string id) => GetUserById(new Guid(id)); @@ -428,7 +422,6 @@ namespace Emby.Server.Implementations.Library { try { - var authenticationResult = provider is IRequiresResolvedUser requiresResolvedUser ? await requiresResolvedUser.Authenticate(username, password, resolvedUser).ConfigureAwait(false) : await provider.Authenticate(username, password).ConfigureAwait(false); @@ -475,24 +468,21 @@ namespace Emby.Server.Implementations.Library if (!success && _networkManager.IsInLocalNetwork(remoteEndPoint) - && user.Configuration.EnableLocalPassword) + && user.Configuration.EnableLocalPassword + && !string.IsNullOrEmpty(user.EasyPassword)) { - success = string.Equals( - GetLocalPasswordHash(user), - _defaultAuthenticationProvider.GetHashedString(user, password), - StringComparison.OrdinalIgnoreCase); + // Check easy password + var passwordHash = PasswordHash.Parse(user.EasyPassword); + var hash = _cryptoProvider.ComputeHash( + passwordHash.Id, + Encoding.UTF8.GetBytes(password), + passwordHash.Salt); + success = passwordHash.Hash.SequenceEqual(hash); } return (authenticationProvider, username, success); } - private string GetLocalPasswordHash(User user) - { - return string.IsNullOrEmpty(user.EasyPassword) - ? null - : ToHexString(PasswordHash.Parse(user.EasyPassword).Hash); - } - private void ResetInvalidLoginAttemptCount(User user) { user.Policy.InvalidLoginAttemptCount = 0; @@ -538,6 +528,8 @@ namespace Emby.Server.Implementations.Library defaultName = "MyJellyfinUser"; } + _logger.LogWarning("No users, creating one with username {UserName}", defaultName); + var name = MakeValidUsername(defaultName); var user = InstantiateNewUser(name); @@ -601,7 +593,7 @@ namespace Emby.Server.Implementations.Library catch (Exception ex) { // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions - _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {user}", user.Name); + _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {User}", user.Name); } } @@ -625,7 +617,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError(ex, "Error getting {imageType} image info for {imagePath}", image.Type, image.Path); + _logger.LogError(ex, "Error getting {ImageType} image info for {ImagePath}", image.Type, image.Path); return null; } } @@ -639,7 +631,7 @@ namespace Emby.Server.Implementations.Library { foreach (var user in Users) { - await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), cancellationToken).ConfigureAwait(false); + await user.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_fileSystem)), cancellationToken).ConfigureAwait(false); } } diff --git a/Emby.Server.Implementations/Library/UserViewManager.cs b/Emby.Server.Implementations/Library/UserViewManager.cs index 1b0813280d..a9b39c064e 100644 --- a/Emby.Server.Implementations/Library/UserViewManager.cs +++ b/Emby.Server.Implementations/Library/UserViewManager.cs @@ -42,6 +42,11 @@ namespace Emby.Server.Implementations.Library { var user = _userManager.GetUserById(query.UserId); + if (user == null) + { + throw new ArgumentException("User Id specified in the query does not exist.", nameof(query)); + } + var folders = _libraryManager.GetUserRootFolder() .GetChildren(user, true) .OfType() @@ -54,7 +59,7 @@ namespace Emby.Server.Implementations.Library foreach (var folder in folders) { var collectionFolder = folder as ICollectionFolder; - var folderViewType = collectionFolder == null ? null : collectionFolder.CollectionType; + var folderViewType = collectionFolder?.CollectionType; if (UserView.IsUserSpecific(folder)) { @@ -130,16 +135,11 @@ namespace Emby.Server.Implementations.Library { var index = orders.IndexOf(i.Id.ToString("N", CultureInfo.InvariantCulture)); - if (index == -1) + if (index == -1 + && i is UserView view + && view.DisplayParentId != Guid.Empty) { - var view = i as UserView; - if (view != null) - { - if (!view.DisplayParentId.Equals(Guid.Empty)) - { - index = orders.IndexOf(view.DisplayParentId.ToString("N", CultureInfo.InvariantCulture)); - } - } + index = orders.IndexOf(view.DisplayParentId.ToString("N", CultureInfo.InvariantCulture)); } return index == -1 ? int.MaxValue : index; diff --git a/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs b/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs index b584cc649d..d06cda177f 100644 --- a/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/ArtistsValidator.cs @@ -28,10 +28,11 @@ namespace Emby.Server.Implementations.Library.Validators private readonly IItemRepository _itemRepo; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The library manager. /// The logger. + /// The item repository. public ArtistsValidator(ILibraryManager libraryManager, ILogger logger, IItemRepository itemRepo) { _libraryManager = libraryManager; diff --git a/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs index 0568073005..3bc5c2fb2a 100644 --- a/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs +++ b/Emby.Server.Implementations/Library/Validators/GenresPostScanTask.cs @@ -10,17 +10,18 @@ namespace Emby.Server.Implementations.Library.Validators public class GenresPostScanTask : ILibraryPostScanTask { /// - /// The _library manager + /// The _library manager. /// private readonly ILibraryManager _libraryManager; private readonly ILogger _logger; private readonly IItemRepository _itemRepo; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The library manager. /// The logger. + /// The item repository. public GenresPostScanTask(ILibraryManager libraryManager, ILogger logger, IItemRepository itemRepo) { _libraryManager = libraryManager; diff --git a/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs index d7ab92d306..9ac4bf7618 100644 --- a/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs +++ b/Emby.Server.Implementations/Library/Validators/MusicGenresPostScanTask.cs @@ -20,10 +20,11 @@ namespace Emby.Server.Implementations.Library.Validators private readonly IItemRepository _itemRepo; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The library manager. /// The logger. + /// The item repository. public MusicGenresPostScanTask(ILibraryManager libraryManager, ILogger logger, IItemRepository itemRepo) { _libraryManager = libraryManager; diff --git a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs index d00c6cde11..137a010ec3 100644 --- a/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs +++ b/Emby.Server.Implementations/Library/Validators/PeopleValidator.cs @@ -11,16 +11,17 @@ using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library.Validators { /// - /// Class PeopleValidator + /// Class PeopleValidator. /// public class PeopleValidator { /// - /// The _library manager + /// The _library manager. /// private readonly ILibraryManager _libraryManager; + /// - /// The _logger + /// The _logger. /// private readonly ILogger _logger; @@ -62,7 +63,7 @@ namespace Emby.Server.Implementations.Library.Validators { var item = _libraryManager.GetPerson(person); - var options = new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) + var options = new MetadataRefreshOptions(new DirectoryService(_fileSystem)) { ImageRefreshMode = MetadataRefreshMode.ValidationOnly, MetadataRefreshMode = MetadataRefreshMode.ValidationOnly @@ -96,12 +97,19 @@ namespace Emby.Server.Implementations.Library.Validators foreach (var item in deadEntities) { - _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N", CultureInfo.InvariantCulture), item.Name, item.GetType().Name); + _logger.LogInformation( + "Deleting dead {2} {0} {1}.", + item.Id.ToString("N", CultureInfo.InvariantCulture), + item.Name, + item.GetType().Name); - _libraryManager.DeleteItem(item, new DeleteOptions - { - DeleteFileLocation = false - }, false); + _libraryManager.DeleteItem( + item, + new DeleteOptions + { + DeleteFileLocation = false + }, + false); } progress.Report(100); diff --git a/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs b/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs index 4aa5c7e72a..2efae0fe44 100644 --- a/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs +++ b/Emby.Server.Implementations/Library/Validators/StudiosPostScanTask.cs @@ -21,9 +21,11 @@ namespace Emby.Server.Implementations.Library.Validators private readonly IItemRepository _itemRepo; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The library manager. + /// The logger. + /// Th item repository. public StudiosPostScanTask(ILibraryManager libraryManager, ILogger logger, IItemRepository itemRepo) { _libraryManager = libraryManager; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 7b0cd40229..3b6bfce6a7 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -237,7 +237,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (requiresRefresh) { - await _libraryManager.ValidateMediaLibrary(new SimpleProgress(), CancellationToken.None); + await _libraryManager.ValidateMediaLibrary(new SimpleProgress(), CancellationToken.None).ConfigureAwait(false); } } @@ -1489,16 +1489,18 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { _logger.LogInformation("Refreshing recording parent {path}", item.Path); - _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) - { - RefreshPaths = new string[] + _providerManager.QueueRefresh( + item.Id, + new MetadataRefreshOptions(new DirectoryService(_fileSystem)) { - path, - Path.GetDirectoryName(path), - Path.GetDirectoryName(Path.GetDirectoryName(path)) - } - - }, RefreshPriority.High); + RefreshPaths = new string[] + { + path, + Path.GetDirectoryName(path), + Path.GetDirectoryName(Path.GetDirectoryName(path)) + } + }, + RefreshPriority.High); } } diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 9a4c91d0bd..838ac97d77 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -501,7 +501,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings public async Task> GetHeadends(ListingsProviderInfo info, string country, string location, CancellationToken cancellationToken) { - var token = await GetToken(info, cancellationToken); + var token = await GetToken(info, cancellationToken).ConfigureAwait(false); var lineups = new List(); @@ -713,7 +713,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings private async Task AddLineupToAccount(ListingsProviderInfo info, CancellationToken cancellationToken) { - var token = await GetToken(info, cancellationToken); + var token = await GetToken(info, cancellationToken).ConfigureAwait(false); if (string.IsNullOrEmpty(token)) { @@ -738,7 +738,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings httpOptions.RequestHeaders["token"] = token; - using (await _httpClient.SendAsync(httpOptions, "PUT")) + using (await _httpClient.SendAsync(httpOptions, "PUT").ConfigureAwait(false)) { } } @@ -750,7 +750,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings throw new ArgumentException("Listings Id required"); } - var token = await GetToken(info, cancellationToken); + var token = await GetToken(info, cancellationToken).ConfigureAwait(false); if (string.IsNullOrEmpty(token)) { @@ -833,7 +833,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings throw new Exception("ListingsId required"); } - var token = await GetToken(info, cancellationToken); + var token = await GetToken(info, cancellationToken).ConfigureAwait(false); if (string.IsNullOrEmpty(token)) { diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index c2350684b9..2ecf4e1847 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -1226,12 +1226,13 @@ namespace Emby.Server.Implementations.LiveTv currentChannel.AddTag("Kids"); } - //currentChannel.UpdateToRepository(ItemUpdateType.MetadataImport, cancellationToken); - await currentChannel.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) - { - ForceSave = true - - }, cancellationToken).ConfigureAwait(false); + currentChannel.UpdateToRepository(ItemUpdateType.MetadataImport, cancellationToken); + await currentChannel.RefreshMetadata( + new MetadataRefreshOptions(new DirectoryService(_fileSystem)) + { + ForceSave = true + }, + cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -1245,7 +1246,7 @@ namespace Emby.Server.Implementations.LiveTv numComplete++; double percent = numComplete / (double)allChannelsList.Count; - progress.Report(85 * percent + 15); + progress.Report((85 * percent) + 15); } progress.Report(100); @@ -1278,12 +1279,14 @@ namespace Emby.Server.Implementations.LiveTv if (item != null) { - _libraryManager.DeleteItem(item, new DeleteOptions - { - DeleteFileLocation = false, - DeleteFromExternalProvider = false - - }, false); + _libraryManager.DeleteItem( + item, + new DeleteOptions + { + DeleteFileLocation = false, + DeleteFromExternalProvider = false + }, + false); } } @@ -2301,8 +2304,10 @@ namespace Emby.Server.Implementations.LiveTv if (provider == null) { throw new ResourceNotFoundException( - string.Format("Couldn't find provider of type: '{0}'", info.Type) - ); + string.Format( + CultureInfo.InvariantCulture, + "Couldn't find provider of type: '{0}'", + info.Type)); } await provider.Validate(info, validateLogin, validateListings).ConfigureAwait(false); diff --git a/Emby.Server.Implementations/LiveTv/RefreshChannelsScheduledTask.cs b/Emby.Server.Implementations/LiveTv/RefreshChannelsScheduledTask.cs index 542951de4a..1056a33b9a 100644 --- a/Emby.Server.Implementations/LiveTv/RefreshChannelsScheduledTask.cs +++ b/Emby.Server.Implementations/LiveTv/RefreshChannelsScheduledTask.cs @@ -38,8 +38,8 @@ namespace Emby.Server.Implementations.LiveTv /// IEnumerable{BaseTaskTrigger}. public IEnumerable GetDefaultTriggers() { - return new[] { - + return new[] + { // Every so often new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks} }; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index da98f3e58b..06f27fa3ea 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -185,7 +185,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun Url = string.Format("{0}/tuners.html", GetApiUrl(info)), CancellationToken = cancellationToken, BufferContent = false - }, HttpMethod.Get)) + }, HttpMethod.Get).ConfigureAwait(false)) using (var stream = response.Content) using (var sr = new StreamReader(stream, System.Text.Encoding.UTF8)) { @@ -259,7 +259,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun for (int i = 0; i < model.TunerCount; ++i) { var name = string.Format("Tuner {0}", i + 1); - var currentChannel = "none"; /// @todo Get current channel and map back to Station Id + var currentChannel = "none"; // @todo Get current channel and map back to Station Id var isAvailable = await manager.CheckTunerAvailability(ipInfo, i, cancellationToken).ConfigureAwait(false); var status = isAvailable ? LiveTvTunerStatus.Available : LiveTvTunerStatus.LiveTv; tuners.Add(new LiveTvTunerInfo @@ -298,7 +298,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun public async Task> GetTunerInfos(TunerHostInfo info, CancellationToken cancellationToken) { // TODO Need faster way to determine UDP vs HTTP - var channels = await GetChannels(info, true, cancellationToken); + var channels = await GetChannels(info, true, cancellationToken).ConfigureAwait(false); var hdHomerunChannelInfo = channels.FirstOrDefault() as HdHomerunChannelInfo; @@ -582,11 +582,10 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun modelInfo.TunerCount, FileSystem, Logger, - Config.ApplicationPaths, + Config, _appHost, _networkManager, _streamHelper); - } var enableHttpStream = true; @@ -611,7 +610,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun FileSystem, _httpClient, Logger, - Config.ApplicationPaths, + Config, _appHost, _streamHelper); } @@ -624,7 +623,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun modelInfo.TunerCount, FileSystem, Logger, - Config.ApplicationPaths, + Config, _appHost, _networkManager, _streamHelper); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index eafa86d54e..649becbd3c 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -6,6 +6,7 @@ using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Net; +using MediaBrowser.Common.Configuration; using MediaBrowser.Controller; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Dto; @@ -33,11 +34,11 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun int numTuners, IFileSystem fileSystem, ILogger logger, - IServerApplicationPaths appPaths, + IConfigurationManager configurationManager, IServerApplicationHost appHost, INetworkManager networkManager, IStreamHelper streamHelper) - : base(mediaSource, tunerHostInfo, fileSystem, logger, appPaths, streamHelper) + : base(mediaSource, tunerHostInfo, fileSystem, logger, configurationManager, streamHelper) { _appHost = appHost; _networkManager = networkManager; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs index d12c96392d..1d55e7992e 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs @@ -5,8 +5,8 @@ using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Controller; using MediaBrowser.Controller.Library; +using MediaBrowser.Common.Configuration; using MediaBrowser.Model.Dto; using MediaBrowser.Model.IO; using MediaBrowser.Model.LiveTv; @@ -16,8 +16,10 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts { public class LiveStream : ILiveStream { + private readonly IConfigurationManager _configurationManager; + protected readonly IFileSystem FileSystem; - protected readonly IServerApplicationPaths AppPaths; + protected readonly IStreamHelper StreamHelper; protected string TempFilePath; @@ -29,7 +31,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts TunerHostInfo tuner, IFileSystem fileSystem, ILogger logger, - IServerApplicationPaths appPaths, + IConfigurationManager configurationManager, IStreamHelper streamHelper) { OriginalMediaSource = mediaSource; @@ -44,7 +46,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts TunerHostId = tuner.Id; } - AppPaths = appPaths; + _configurationManager = configurationManager; StreamHelper = streamHelper; ConsumerCount = 1; @@ -68,7 +70,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts protected void SetTempFilePath(string extension) { - TempFilePath = Path.Combine(AppPaths.GetTranscodingTempPath(), UniqueId + "." + extension); + TempFilePath = Path.Combine(_configurationManager.GetTranscodePath(), UniqueId + "." + extension); } public virtual Task Open(CancellationToken openCancellationToken) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs index a02a9ade49..df054f1ebb 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs @@ -114,11 +114,11 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts if (!_disallowedSharedStreamExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)) { - return new SharedHttpStream(mediaSource, info, streamId, FileSystem, _httpClient, Logger, Config.ApplicationPaths, _appHost, _streamHelper); + return new SharedHttpStream(mediaSource, info, streamId, FileSystem, _httpClient, Logger, Config, _appHost, _streamHelper); } } - return new LiveStream(mediaSource, info, FileSystem, Logger, Config.ApplicationPaths, _streamHelper); + return new LiveStream(mediaSource, info, FileSystem, Logger, Config, _streamHelper); } public async Task Validate(TunerHostInfo info) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs index c6e894560d..7584953624 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.Library; @@ -26,10 +27,10 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts IFileSystem fileSystem, IHttpClient httpClient, ILogger logger, - IServerApplicationPaths appPaths, + IConfigurationManager configurationManager, IServerApplicationHost appHost, IStreamHelper streamHelper) - : base(mediaSource, tunerHostInfo, fileSystem, logger, appPaths, streamHelper) + : base(mediaSource, tunerHostInfo, fileSystem, logger, configurationManager, streamHelper) { _httpClient = httpClient; _appHost = appHost; diff --git a/Emby.Server.Implementations/Localization/Core/af.json b/Emby.Server.Implementations/Localization/Core/af.json new file mode 100644 index 0000000000..dcec268017 --- /dev/null +++ b/Emby.Server.Implementations/Localization/Core/af.json @@ -0,0 +1,96 @@ +{ + "Artists": "Kunstenare", + "Channels": "Kanale", + "Folders": "Fouers", + "Favorites": "Gunstelinge", + "HeaderFavoriteShows": "Gunsteling Vertonings", + "ValueSpecialEpisodeName": "Spesiaal - {0}", + "HeaderAlbumArtists": "Album Kunstenaars", + "Books": "Boeke", + "HeaderNextUp": "Volgende", + "Movies": "Rolprente", + "Shows": "Program", + "HeaderContinueWatching": "Hou Aan Kyk", + "HeaderFavoriteEpisodes": "Gunsteling Episodes", + "Photos": "Fotos", + "Playlists": "Speellysse", + "HeaderFavoriteArtists": "Gunsteling Kunstenaars", + "HeaderFavoriteAlbums": "Gunsteling Albums", + "Sync": "Sinkroniseer", + "HeaderFavoriteSongs": "Gunsteling Liedjies", + "Songs": "Liedjies", + "DeviceOnlineWithName": "{0} is verbind", + "DeviceOfflineWithName": "{0} het afgesluit", + "Collections": "Versamelings", + "Inherit": "Ontvang", + "HeaderLiveTV": "Live TV", + "Application": "Program", + "AppDeviceValues": "App: {0}, Toestel: {1}", + "VersionNumber": "Weergawe {0}", + "ValueHasBeenAddedToLibrary": "{0} is by jou media biblioteek bygevoeg", + "UserStoppedPlayingItemWithValues": "{0} het klaar {1} op {2} gespeel", + "UserStartedPlayingItemWithValues": "{0} is besig om {1} op {2} te speel", + "UserPolicyUpdatedWithName": "Gebruiker beleid is verander vir {0}", + "UserPasswordChangedWithName": "Gebruiker {0} se wagwoord is verander", + "UserOnlineFromDevice": "{0} is aanlyn van {1}", + "UserOfflineFromDevice": "{0} is ontkoppel van {1}", + "UserLockedOutWithName": "Gebruiker {0} is uitgesluit", + "UserDownloadingItemWithValues": "{0} is besig om {1} af te laai", + "UserDeletedWithName": "Gebruiker {0} is verwyder", + "UserCreatedWithName": "Gebruiker {0} is geskep", + "User": "Gebruiker", + "TvShows": "TV Programme", + "System": "Stelsel", + "SubtitlesDownloadedForItem": "Ondertitels afgelaai vir {0}", + "SubtitleDownloadFailureFromForItem": "Ondertitels het misluk om af te laai van {0} vir {1}", + "StartupEmbyServerIsLoading": "Jellyfin Bediener is besig om te laai. Probeer weer in 'n kort tyd.", + "ServerNameNeedsToBeRestarted": "{0} moet herbegin word", + "ScheduledTaskStartedWithName": "{0} het begin", + "ScheduledTaskFailedWithName": "{0} het misluk", + "ProviderValue": "Voorsiener: {0}", + "PluginUpdatedWithName": "{0} was opgedateer", + "PluginUninstalledWithName": "{0} was verwyder", + "PluginInstalledWithName": "{0} is geïnstalleer", + "Plugin": "Inprop module", + "NotificationOptionVideoPlaybackStopped": "Video terugspeel het gestop", + "NotificationOptionVideoPlayback": "Video terugspeel het begin", + "NotificationOptionUserLockedOut": "Gebruiker uitgeslyt", + "NotificationOptionTaskFailed": "Geskeduleerde taak het misluk", + "NotificationOptionServerRestartRequired": "Bediener herbegin nodig", + "NotificationOptionPluginUpdateInstalled": "Nuwe inprop module geïnstalleer", + "NotificationOptionPluginUninstalled": "Inprop module verwyder", + "NotificationOptionPluginInstalled": "Inprop module geïnstalleer", + "NotificationOptionPluginError": "Inprop module het misluk", + "NotificationOptionNewLibraryContent": "Nuwe inhoud bygevoeg", + "NotificationOptionInstallationFailed": "Installering het misluk", + "NotificationOptionCameraImageUploaded": "Kamera foto is opgelaai", + "NotificationOptionAudioPlaybackStopped": "Oudio terugspeel het gestop", + "NotificationOptionAudioPlayback": "Oudio terugspeel het begin", + "NotificationOptionApplicationUpdateInstalled": "Nuwe program weergawe geïnstalleer", + "NotificationOptionApplicationUpdateAvailable": "Nuwe program weergawe beskikbaar", + "NewVersionIsAvailable": "'n Nuwe Jellyfin Bedienaar weergawe kan afgelaai word.", + "NameSeasonUnknown": "Seisoen Onbekend", + "NameSeasonNumber": "Seisoen {0}", + "NameInstallFailed": "{0} installering het misluk", + "MusicVideos": "Musiek videos", + "Music": "Musiek", + "MixedContent": "Gemengde inhoud", + "MessageServerConfigurationUpdated": "Bediener konfigurasie is opgedateer", + "MessageNamedServerConfigurationUpdatedWithValue": "Bediener konfigurasie seksie {0} is opgedateer", + "MessageApplicationUpdatedTo": "Jellyfin Bediener is opgedateer na {0}", + "MessageApplicationUpdated": "Jellyfin Bediener is opgedateer", + "Latest": "Nuutste", + "LabelRunningTimeValue": "Lopende tyd: {0}", + "LabelIpAddressValue": "IP adres: {0}", + "ItemRemovedWithName": "{0} is uit versameling verwyder", + "ItemAddedWithName": "{0} is in die versameling", + "HomeVideos": "Tuis opnames", + "HeaderRecordingGroups": "Groep Opnames", + "HeaderCameraUploads": "Kamera Oplaai", + "Genres": "Genres", + "FailedLoginAttemptWithUserName": "Mislukte aansluiting van {0}", + "ChapterNameValue": "Hoofstuk", + "CameraImageUploadedFrom": "'n Nuwe kamera photo opgelaai van {0}", + "AuthenticationSucceededWithUserName": "{0} suksesvol geverifieer", + "Albums": "Albums" +} diff --git a/Emby.Server.Implementations/Localization/Core/bg-BG.json b/Emby.Server.Implementations/Localization/Core/bg-BG.json index a71dc93467..bfe32a6c2b 100644 --- a/Emby.Server.Implementations/Localization/Core/bg-BG.json +++ b/Emby.Server.Implementations/Localization/Core/bg-BG.json @@ -1,22 +1,22 @@ { "Albums": "Албуми", - "AppDeviceValues": "Програма: {0}, Устройство: {1}", + "AppDeviceValues": "Програма: {0}, устройство: {1}", "Application": "Програма", "Artists": "Изпълнители", "AuthenticationSucceededWithUserName": "{0} се удостовери успешно", "Books": "Книги", - "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}", + "CameraImageUploadedFrom": "", "Channels": "Канали", "ChapterNameValue": "Глава {0}", "Collections": "Колекции", "DeviceOfflineWithName": "{0} се разкачи", "DeviceOnlineWithName": "{0} е свързан", - "FailedLoginAttemptWithUserName": "Failed login attempt from {0}", + "FailedLoginAttemptWithUserName": "", "Favorites": "Любими", "Folders": "Папки", "Genres": "Жанрове", "HeaderAlbumArtists": "Изпълнители на албуми", - "HeaderCameraUploads": "Camera Uploads", + "HeaderCameraUploads": "", "HeaderContinueWatching": "Продължаване на гледането", "HeaderFavoriteAlbums": "Любими албуми", "HeaderFavoriteArtists": "Любими изпълнители", @@ -25,26 +25,26 @@ "HeaderFavoriteSongs": "Любими песни", "HeaderLiveTV": "Телевизия на живо", "HeaderNextUp": "Следва", - "HeaderRecordingGroups": "Recording Groups", + "HeaderRecordingGroups": "", "HomeVideos": "Домашни клипове", "Inherit": "Наследяване", "ItemAddedWithName": "{0} е добавено към библиотеката", "ItemRemovedWithName": "{0} е премахнато от библиотеката", "LabelIpAddressValue": "ИП адрес: {0}", - "LabelRunningTimeValue": "Running time: {0}", + "LabelRunningTimeValue": "", "Latest": "Последни", "MessageApplicationUpdated": "Сървърът е обновен", - "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}", - "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated", - "MessageServerConfigurationUpdated": "Server configuration has been updated", + "MessageApplicationUpdatedTo": "", + "MessageNamedServerConfigurationUpdatedWithValue": "", + "MessageServerConfigurationUpdated": "", "MixedContent": "Смесено съдържание", "Movies": "Филми", "Music": "Музика", "MusicVideos": "Музикални клипове", - "NameInstallFailed": "{0} installation failed", + "NameInstallFailed": "", "NameSeasonNumber": "Сезон {0}", - "NameSeasonUnknown": "Season Unknown", - "NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.", + "NameSeasonUnknown": "Неразпознат сезон", + "NewVersionIsAvailable": "", "NotificationOptionApplicationUpdateAvailable": "Налично е обновление на програмата", "NotificationOptionApplicationUpdateInstalled": "Обновлението на програмата е инсталирано", "NotificationOptionAudioPlayback": "Възпроизвеждането на звук започна", @@ -58,7 +58,7 @@ "NotificationOptionPluginUpdateInstalled": "Обновлението на приставката е инсталирано", "NotificationOptionServerRestartRequired": "Нужно е повторно пускане на сървъра", "NotificationOptionTaskFailed": "Грешка в планирана задача", - "NotificationOptionUserLockedOut": "User locked out", + "NotificationOptionUserLockedOut": "", "NotificationOptionVideoPlayback": "Възпроизвеждането на видео започна", "NotificationOptionVideoPlaybackStopped": "Възпроизвеждането на видео е спряно", "Photos": "Снимки", @@ -70,12 +70,12 @@ "ProviderValue": "Доставчик: {0}", "ScheduledTaskFailedWithName": "{0} се провали", "ScheduledTaskStartedWithName": "{0} започна", - "ServerNameNeedsToBeRestarted": "{0} needs to be restarted", + "ServerNameNeedsToBeRestarted": "", "Shows": "Сериали", "Songs": "Песни", "StartupEmbyServerIsLoading": "Сървърът зарежда. Моля, опитайте отново след малко.", "SubtitleDownloadFailureForItem": "Неуспешно изтегляне на субтитри за {0}", - "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}", + "SubtitleDownloadFailureFromForItem": "", "SubtitlesDownloadedForItem": "Изтеглени са субтитри за {0}", "Sync": "Синхронизиране", "System": "Система", @@ -83,15 +83,15 @@ "User": "Потребител", "UserCreatedWithName": "Потребителят {0} е създаден", "UserDeletedWithName": "Потребителят {0} е изтрит", - "UserDownloadingItemWithValues": "{0} is downloading {1}", - "UserLockedOutWithName": "User {0} has been locked out", + "UserDownloadingItemWithValues": "", + "UserLockedOutWithName": "", "UserOfflineFromDevice": "{0} се разкачи от {1}", "UserOnlineFromDevice": "{0} е на линия от {1}", "UserPasswordChangedWithName": "Паролата на потребителя {0} е променена", - "UserPolicyUpdatedWithName": "User policy has been updated for {0}", + "UserPolicyUpdatedWithName": "", "UserStartedPlayingItemWithValues": "{0} пусна {1}", "UserStoppedPlayingItemWithValues": "{0} спря {1}", - "ValueHasBeenAddedToLibrary": "{0} has been added to your media library", + "ValueHasBeenAddedToLibrary": "", "ValueSpecialEpisodeName": "Специални - {0}", "VersionNumber": "Версия {0}" } diff --git a/Emby.Server.Implementations/Localization/Core/cs.json b/Emby.Server.Implementations/Localization/Core/cs.json index c19148921b..86fbac3805 100644 --- a/Emby.Server.Implementations/Localization/Core/cs.json +++ b/Emby.Server.Implementations/Localization/Core/cs.json @@ -23,7 +23,7 @@ "HeaderFavoriteEpisodes": "Oblíbené epizody", "HeaderFavoriteShows": "Oblíbené seriály", "HeaderFavoriteSongs": "Oblíbená hudba", - "HeaderLiveTV": "Live TV", + "HeaderLiveTV": "Živá TV", "HeaderNextUp": "Nadcházející", "HeaderRecordingGroups": "Skupiny nahrávek", "HomeVideos": "Domáci videa", diff --git a/Emby.Server.Implementations/Localization/Core/de.json b/Emby.Server.Implementations/Localization/Core/de.json index 0db2017692..019736c471 100644 --- a/Emby.Server.Implementations/Localization/Core/de.json +++ b/Emby.Server.Implementations/Localization/Core/de.json @@ -3,14 +3,14 @@ "AppDeviceValues": "App: {0}, Gerät: {1}", "Application": "Anwendung", "Artists": "Interpreten", - "AuthenticationSucceededWithUserName": "{0} hat sich angemeldet", + "AuthenticationSucceededWithUserName": "{0} hat sich erfolgreich angemeldet", "Books": "Bücher", "CameraImageUploadedFrom": "Ein neues Foto wurde hochgeladen von {0}", "Channels": "Kanäle", "ChapterNameValue": "Kapitel {0}", "Collections": "Sammlungen", "DeviceOfflineWithName": "{0} wurde getrennt", - "DeviceOnlineWithName": "{0} hat sich verbunden", + "DeviceOnlineWithName": "{0} ist verbunden", "FailedLoginAttemptWithUserName": "Fehlgeschlagener Anmeldeversuch von {0}", "Favorites": "Favoriten", "Folders": "Verzeichnisse", @@ -23,7 +23,7 @@ "HeaderFavoriteEpisodes": "Lieblingsepisoden", "HeaderFavoriteShows": "Lieblingsserien", "HeaderFavoriteSongs": "Lieblingslieder", - "HeaderLiveTV": "Live-TV", + "HeaderLiveTV": "Live TV", "HeaderNextUp": "Als Nächstes", "HeaderRecordingGroups": "Aufnahme-Gruppen", "HomeVideos": "Heimvideos", @@ -35,7 +35,7 @@ "Latest": "Neueste", "MessageApplicationUpdated": "Jellyfin-Server wurde aktualisiert", "MessageApplicationUpdatedTo": "Jellyfin-Server wurde auf Version {0} aktualisiert", - "MessageNamedServerConfigurationUpdatedWithValue": "Der Server Einstellungsbereich {0} wurde aktualisiert", + "MessageNamedServerConfigurationUpdatedWithValue": "Der Server-Einstellungsbereich {0} wurde aktualisiert", "MessageServerConfigurationUpdated": "Servereinstellungen wurden aktualisiert", "MixedContent": "Gemischte Inhalte", "Movies": "Filme", diff --git a/Emby.Server.Implementations/Localization/Core/fr.json b/Emby.Server.Implementations/Localization/Core/fr.json index 6bfedb712c..9805992be9 100644 --- a/Emby.Server.Implementations/Localization/Core/fr.json +++ b/Emby.Server.Implementations/Localization/Core/fr.json @@ -5,7 +5,7 @@ "Artists": "Artistes", "AuthenticationSucceededWithUserName": "{0} s'est authentifié avec succès", "Books": "Livres", - "CameraImageUploadedFrom": "Une image de caméra a été chargée depuis {0}", + "CameraImageUploadedFrom": "Une nouvelle image de caméra a été chargée depuis {0}", "Channels": "Chaînes", "ChapterNameValue": "Chapitre {0}", "Collections": "Collections", @@ -17,7 +17,7 @@ "Genres": "Genres", "HeaderAlbumArtists": "Artistes de l'album", "HeaderCameraUploads": "Photos transférées", - "HeaderContinueWatching": "Reprendre", + "HeaderContinueWatching": "Continuer à regarder", "HeaderFavoriteAlbums": "Albums favoris", "HeaderFavoriteArtists": "Artistes favoris", "HeaderFavoriteEpisodes": "Épisodes favoris", @@ -34,14 +34,14 @@ "LabelRunningTimeValue": "Durée : {0}", "Latest": "Derniers", "MessageApplicationUpdated": "Le serveur Jellyfin a été mis à jour", - "MessageApplicationUpdatedTo": "Jellyfin Serveur a été mis à jour en version {0}", + "MessageApplicationUpdatedTo": "Le serveur Jellyfin a été mis à jour vers {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", + "NameInstallFailed": "{0} échec de l'installation", "NameSeasonNumber": "Saison {0}", "NameSeasonUnknown": "Saison Inconnue", "NewVersionIsAvailable": "Une nouvelle version de Jellyfin Serveur est disponible au téléchargement.", @@ -50,7 +50,7 @@ "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", + "NotificationOptionInstallationFailed": "Échec de l'installation", "NotificationOptionNewLibraryContent": "Nouveau contenu ajouté", "NotificationOptionPluginError": "Erreur d'extension", "NotificationOptionPluginInstalled": "Extension installée", @@ -91,7 +91,7 @@ "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 librairie", + "ValueHasBeenAddedToLibrary": "{0} a été ajouté à votre médiathèque", "ValueSpecialEpisodeName": "Spécial - {0}", "VersionNumber": "Version {0}" } diff --git a/Emby.Server.Implementations/Localization/Core/he.json b/Emby.Server.Implementations/Localization/Core/he.json index 0ed998c4bd..b08c8966e2 100644 --- a/Emby.Server.Implementations/Localization/Core/he.json +++ b/Emby.Server.Implementations/Localization/Core/he.json @@ -1,41 +1,41 @@ { "Albums": "אלבומים", - "AppDeviceValues": "App: {0}, Device: {1}", + "AppDeviceValues": "יישום: {0}, מכשיר: {1}", "Application": "אפליקציה", "Artists": "אמנים", - "AuthenticationSucceededWithUserName": "{0} successfully authenticated", + "AuthenticationSucceededWithUserName": "{0} זוהה בהצלחה", "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", + "CameraImageUploadedFrom": "תמונה חדשה הועלתה מ{0}", + "Channels": "ערוצים", + "ChapterNameValue": "פרק {0}", + "Collections": "קולקציות", + "DeviceOfflineWithName": "{0} התנתק", + "DeviceOnlineWithName": "{0} מחובר", + "FailedLoginAttemptWithUserName": "ניסיון כניסה שגוי מ{0}", + "Favorites": "אהובים", + "Folders": "תיקיות", "Genres": "ז'אנרים", - "HeaderAlbumArtists": "Album Artists", - "HeaderCameraUploads": "Camera Uploads", - "HeaderContinueWatching": "המשך בצפייה", - "HeaderFavoriteAlbums": "Favorite Albums", - "HeaderFavoriteArtists": "Favorite Artists", - "HeaderFavoriteEpisodes": "Favorite Episodes", - "HeaderFavoriteShows": "Favorite Shows", - "HeaderFavoriteSongs": "Favorite Songs", - "HeaderLiveTV": "Live TV", - "HeaderNextUp": "Next Up", + "HeaderAlbumArtists": "אמני האלבום", + "HeaderCameraUploads": "העלאות ממצלמה", + "HeaderContinueWatching": "המשך לצפות", + "HeaderFavoriteAlbums": "אלבומים שאהבתי", + "HeaderFavoriteArtists": "אמנים שאהבתי", + "HeaderFavoriteEpisodes": "פרקים אהובים", + "HeaderFavoriteShows": "תוכניות אהובות", + "HeaderFavoriteSongs": "שירים שאהבתי", + "HeaderLiveTV": "טלוויזיה בשידור חי", + "HeaderNextUp": "הבא", "HeaderRecordingGroups": "קבוצות הקלטה", - "HomeVideos": "Home videos", - "Inherit": "Inherit", + "HomeVideos": "סרטונים בייתים", + "Inherit": "הורש", "ItemAddedWithName": "{0} was added to the library", - "ItemRemovedWithName": "{0} was removed from the library", - "LabelIpAddressValue": "Ip address: {0}", - "LabelRunningTimeValue": "Running time: {0}", + "ItemRemovedWithName": "{0} נמחק מהספרייה", + "LabelIpAddressValue": "Ip כתובת: {0}", + "LabelRunningTimeValue": "משך צפייה: {0}", "Latest": "אחרון", - "MessageApplicationUpdated": "Jellyfin Server has been updated", - "MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}", - "MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated", + "MessageApplicationUpdated": "שרת הJellyfin עודכן", + "MessageApplicationUpdatedTo": "שרת הJellyfin עודכן לגרסא {0}", + "MessageNamedServerConfigurationUpdatedWithValue": "הגדרת השרת {0} שונתה", "MessageServerConfigurationUpdated": "Server configuration has been updated", "MixedContent": "תוכן מעורב", "Movies": "סרטים", @@ -50,7 +50,7 @@ "NotificationOptionAudioPlayback": "Audio playback started", "NotificationOptionAudioPlaybackStopped": "Audio playback stopped", "NotificationOptionCameraImageUploaded": "Camera image uploaded", - "NotificationOptionInstallationFailed": "Installation failure", + "NotificationOptionInstallationFailed": "התקנה נכשלה", "NotificationOptionNewLibraryContent": "New content added", "NotificationOptionPluginError": "Plugin failure", "NotificationOptionPluginInstalled": "Plugin installed", diff --git a/Emby.Server.Implementations/Localization/Core/hu.json b/Emby.Server.Implementations/Localization/Core/hu.json index a2fc126a25..3a6852321d 100644 --- a/Emby.Server.Implementations/Localization/Core/hu.json +++ b/Emby.Server.Implementations/Localization/Core/hu.json @@ -5,7 +5,7 @@ "Artists": "Előadók", "AuthenticationSucceededWithUserName": "{0} sikeresen azonosítva", "Books": "Könyvek", - "CameraImageUploadedFrom": "Új kamerakép került feltöltésre {0}", + "CameraImageUploadedFrom": "Új kamerakép került feltöltésre innen: {0}", "Channels": "Csatornák", "ChapterNameValue": "Jelenet {0}", "Collections": "Gyűjtemények", @@ -15,14 +15,14 @@ "Favorites": "Kedvencek", "Folders": "Könyvtárak", "Genres": "Műfajok", - "HeaderAlbumArtists": "Album Előadók", + "HeaderAlbumArtists": "Album előadók", "HeaderCameraUploads": "Kamera feltöltések", "HeaderContinueWatching": "Folyamatban lévő filmek", - "HeaderFavoriteAlbums": "Kedvenc Albumok", - "HeaderFavoriteArtists": "Kedvenc Előadók", - "HeaderFavoriteEpisodes": "Kedvenc Epizódok", - "HeaderFavoriteShows": "Kedvenc Sorozatok", - "HeaderFavoriteSongs": "Kedvenc Dalok", + "HeaderFavoriteAlbums": "Kedvenc albumok", + "HeaderFavoriteArtists": "Kedvenc előadók", + "HeaderFavoriteEpisodes": "Kedvenc epizódok", + "HeaderFavoriteShows": "Kedvenc sorozatok", + "HeaderFavoriteSongs": "Kedvenc dalok", "HeaderLiveTV": "Élő TV", "HeaderNextUp": "Következik", "HeaderRecordingGroups": "Felvételi csoportok", @@ -34,21 +34,21 @@ "LabelRunningTimeValue": "Futási idő: {0}", "Latest": "Legújabb", "MessageApplicationUpdated": "Jellyfin Szerver frissítve", - "MessageApplicationUpdatedTo": "Jellyfin Szerver frissítve lett a következőre {0}", - "MessageNamedServerConfigurationUpdatedWithValue": "Szerver konfigurációs rész {0} frissítve", + "MessageApplicationUpdatedTo": "Jellyfin Szerver frissítve lett a következőre: {0}", + "MessageNamedServerConfigurationUpdatedWithValue": "Szerver konfigurációs rész frissítve: {0}", "MessageServerConfigurationUpdated": "Szerver konfiguráció frissítve", "MixedContent": "Vegyes tartalom", "Movies": "Filmek", "Music": "Zene", - "MusicVideos": "Zenei Videók", + "MusicVideos": "Zenei videók", "NameInstallFailed": "{0} sikertelen telepítés", "NameSeasonNumber": "Évad {0}", "NameSeasonUnknown": "Ismeretlen évad", "NewVersionIsAvailable": "Letölthető a Jellyfin Szerver új verziója.", - "NotificationOptionApplicationUpdateAvailable": "Új programfrissítés érhető el", - "NotificationOptionApplicationUpdateInstalled": "Programfrissítés telepítve", + "NotificationOptionApplicationUpdateAvailable": "Frissítés érhető el az alkalmazáshoz", + "NotificationOptionApplicationUpdateInstalled": "Alkalmazásfrissítés telepítve", "NotificationOptionAudioPlayback": "Audió lejátszás elkezdve", - "NotificationOptionAudioPlaybackStopped": "Audió lejátszás befejezve", + "NotificationOptionAudioPlaybackStopped": "Audió lejátszás leállítva", "NotificationOptionCameraImageUploaded": "Kamera kép feltöltve", "NotificationOptionInstallationFailed": "Telepítési hiba", "NotificationOptionNewLibraryContent": "Új tartalom hozzáadva", @@ -60,15 +60,15 @@ "NotificationOptionTaskFailed": "Ütemezett feladat hiba", "NotificationOptionUserLockedOut": "Felhasználó tiltva", "NotificationOptionVideoPlayback": "Videó lejátszás elkezdve", - "NotificationOptionVideoPlaybackStopped": "Videó lejátszás befejezve", + "NotificationOptionVideoPlaybackStopped": "Videó lejátszás leállítva", "Photos": "Fényképek", "Playlists": "Lejátszási listák", "Plugin": "Bővítmény", "PluginInstalledWithName": "{0} telepítve", "PluginUninstalledWithName": "{0} eltávolítva", "PluginUpdatedWithName": "{0} frissítve", - "ProviderValue": "Provider: {0}", - "ScheduledTaskFailedWithName": "{0} hiba", + "ProviderValue": "Szolgáltató: {0}", + "ScheduledTaskFailedWithName": "{0} sikertelen", "ScheduledTaskStartedWithName": "{0} elkezdve", "ServerNameNeedsToBeRestarted": "{0}-t újra kell indítani", "Shows": "Műsorok", @@ -76,10 +76,10 @@ "StartupEmbyServerIsLoading": "A Jellyfin Szerver betöltődik. Kérlek próbáld újra később.", "SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}", "SubtitleDownloadFailureFromForItem": "Nem sikerült a felirat letöltése innen: {0} ehhez: {1}", - "SubtitlesDownloadedForItem": "Letöltött feliratok a következőhöz {0}", + "SubtitlesDownloadedForItem": "Letöltött feliratok a következőhöz: {0}", "Sync": "Szinkronizál", "System": "Rendszer", - "TvShows": "TV Műsorok", + "TvShows": "TV műsorok", "User": "Felhasználó", "UserCreatedWithName": "{0} felhasználó létrehozva", "UserDeletedWithName": "{0} felhasználó törölve", @@ -88,7 +88,7 @@ "UserOfflineFromDevice": "{0} kijelentkezett innen: {1}", "UserOnlineFromDevice": "{0} online itt: {1}", "UserPasswordChangedWithName": "Jelszó megváltozott a következő felhasználó számára: {0}", - "UserPolicyUpdatedWithName": "A felhasználói házirend frissítve lett {0}", + "UserPolicyUpdatedWithName": "A felhasználói házirend frissítve lett neki: {0}", "UserStartedPlayingItemWithValues": "{0} elkezdte játszani a következőt: {1} itt: {2}", "UserStoppedPlayingItemWithValues": "{0} befejezte a következőt: {1} itt: {2}", "ValueHasBeenAddedToLibrary": "{0} hozzáadva a médiatárhoz", diff --git a/Emby.Server.Implementations/Localization/Core/is.json b/Emby.Server.Implementations/Localization/Core/is.json new file mode 100644 index 0000000000..0967ef424b --- /dev/null +++ b/Emby.Server.Implementations/Localization/Core/is.json @@ -0,0 +1 @@ +{} diff --git a/Emby.Server.Implementations/Localization/Core/it.json b/Emby.Server.Implementations/Localization/Core/it.json index 357883cd37..8f91effb92 100644 --- a/Emby.Server.Implementations/Localization/Core/it.json +++ b/Emby.Server.Implementations/Localization/Core/it.json @@ -9,13 +9,13 @@ "Channels": "Canali", "ChapterNameValue": "Capitolo {0}", "Collections": "Collezioni", - "DeviceOfflineWithName": "{0} è stato disconnesso", + "DeviceOfflineWithName": "{0} ha disconnesso", "DeviceOnlineWithName": "{0} è connesso", "FailedLoginAttemptWithUserName": "Tentativo di accesso fallito da {0}", "Favorites": "Preferiti", "Folders": "Cartelle", "Genres": "Generi", - "HeaderAlbumArtists": "Artisti Album", + "HeaderAlbumArtists": "Artisti dell' Album", "HeaderCameraUploads": "Caricamenti Fotocamera", "HeaderContinueWatching": "Continua a guardare", "HeaderFavoriteAlbums": "Album preferiti", @@ -32,7 +32,7 @@ "ItemRemovedWithName": "{0} è stato rimosso dalla libreria", "LabelIpAddressValue": "Indirizzo IP: {0}", "LabelRunningTimeValue": "Durata: {0}", - "Latest": "Più recenti", + "Latest": "Novità", "MessageApplicationUpdated": "Il Server Jellyfin è stato aggiornato", "MessageApplicationUpdatedTo": "Jellyfin Server è stato aggiornato a {0}", "MessageNamedServerConfigurationUpdatedWithValue": "La sezione {0} della configurazione server è stata aggiornata", @@ -43,7 +43,7 @@ "MusicVideos": "Video musicali", "NameInstallFailed": "{0} installazione fallita", "NameSeasonNumber": "Stagione {0}", - "NameSeasonUnknown": "Stagione sconosciuto", + "NameSeasonUnknown": "Stagione sconosciuta", "NewVersionIsAvailable": "Una nuova versione di Jellyfin Server è disponibile per il download.", "NotificationOptionApplicationUpdateAvailable": "Aggiornamento dell'applicazione disponibile", "NotificationOptionApplicationUpdateInstalled": "Aggiornamento dell'applicazione installato", @@ -88,9 +88,9 @@ "UserOfflineFromDevice": "{0} è stato disconnesso da {1}", "UserOnlineFromDevice": "{0} è online da {1}", "UserPasswordChangedWithName": "La password è stata cambiata per l'utente {0}", - "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}", + "UserPolicyUpdatedWithName": "La policy dell'utente è stata aggiornata per {0}", + "UserStartedPlayingItemWithValues": "{0} ha avviato la riproduzione di {1} su {2}", + "UserStoppedPlayingItemWithValues": "{0} ha interrotto la riproduzione di {1} su {2}", "ValueHasBeenAddedToLibrary": "{0} è stato aggiunto alla tua libreria multimediale", "ValueSpecialEpisodeName": "Speciale - {0}", "VersionNumber": "Versione {0}" diff --git a/Emby.Server.Implementations/Localization/Core/nl.json b/Emby.Server.Implementations/Localization/Core/nl.json index 24af1839fc..637e514ed6 100644 --- a/Emby.Server.Implementations/Localization/Core/nl.json +++ b/Emby.Server.Implementations/Localization/Core/nl.json @@ -1,7 +1,7 @@ { "Albums": "Albums", "AppDeviceValues": "App: {0}, Apparaat: {1}", - "Application": "Toepassing", + "Application": "Applicatie", "Artists": "Artiesten", "AuthenticationSucceededWithUserName": "{0} is succesvol geverifieerd", "Books": "Boeken", @@ -30,7 +30,7 @@ "Inherit": "Overerven", "ItemAddedWithName": "{0} is toegevoegd aan de bibliotheek", "ItemRemovedWithName": "{0} is verwijderd uit de bibliotheek", - "LabelIpAddressValue": "IP adres: {0}", + "LabelIpAddressValue": "IP-adres: {0}", "LabelRunningTimeValue": "Looptijd: {0}", "Latest": "Nieuwste", "MessageApplicationUpdated": "Jellyfin Server is bijgewerkt", @@ -50,7 +50,7 @@ "NotificationOptionAudioPlayback": "Muziek gestart", "NotificationOptionAudioPlaybackStopped": "Muziek gestopt", "NotificationOptionCameraImageUploaded": "Camera-afbeelding geüpload", - "NotificationOptionInstallationFailed": "Installatie mislukt", + "NotificationOptionInstallationFailed": "Installatie mislukking", "NotificationOptionNewLibraryContent": "Nieuwe content toegevoegd", "NotificationOptionPluginError": "Plug-in fout", "NotificationOptionPluginInstalled": "Plug-in geïnstalleerd", diff --git a/Emby.Server.Implementations/Localization/Core/sk.json b/Emby.Server.Implementations/Localization/Core/sk.json index 6eade79429..75eecbe3e0 100644 --- a/Emby.Server.Implementations/Localization/Core/sk.json +++ b/Emby.Server.Implementations/Localization/Core/sk.json @@ -5,7 +5,7 @@ "Artists": "Umelci", "AuthenticationSucceededWithUserName": "{0} úspešne overený", "Books": "Knihy", - "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}", + "CameraImageUploadedFrom": "Z {0} bola nahraná nová fotografia", "Channels": "Kanály", "ChapterNameValue": "Kapitola {0}", "Collections": "Zbierky", @@ -15,9 +15,9 @@ "Favorites": "Obľúbené", "Folders": "Priečinky", "Genres": "Žánre", - "HeaderAlbumArtists": "Album Artists", + "HeaderAlbumArtists": "Albumy umelcov", "HeaderCameraUploads": "Nahrané fotografie", - "HeaderContinueWatching": "Pokračujte v pozeraní", + "HeaderContinueWatching": "Pokračovať v pozeraní", "HeaderFavoriteAlbums": "Obľúbené albumy", "HeaderFavoriteArtists": "Obľúbení umelci", "HeaderFavoriteEpisodes": "Obľúbené epizódy", diff --git a/Emby.Server.Implementations/Localization/Core/tr.json b/Emby.Server.Implementations/Localization/Core/tr.json index 3cc95e46ec..eb1c2623f7 100644 --- a/Emby.Server.Implementations/Localization/Core/tr.json +++ b/Emby.Server.Implementations/Localization/Core/tr.json @@ -5,93 +5,93 @@ "Artists": "Sanatçılar", "AuthenticationSucceededWithUserName": "{0} kimlik başarıyla doğrulandı", "Books": "Kitaplar", - "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}", + "CameraImageUploadedFrom": "{0} 'den yeni bir kamera resmi yüklendi", "Channels": "Kanallar", - "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", + "ChapterNameValue": "Bölüm {0}", + "Collections": "Koleksiyonlar", + "DeviceOfflineWithName": "{0} bağlantısı kesildi", + "DeviceOnlineWithName": "{0} bağlı", + "FailedLoginAttemptWithUserName": "{0} adresinden giriş başarısız oldu", + "Favorites": "Favoriler", + "Folders": "Klasörler", + "Genres": "Türler", + "HeaderAlbumArtists": "Albüm Sanatçıları", + "HeaderCameraUploads": "Kamera Yüklemeleri", "HeaderContinueWatching": "İzlemeye Devam Et", "HeaderFavoriteAlbums": "Favori Albümler", - "HeaderFavoriteArtists": "Favorite Artists", - "HeaderFavoriteEpisodes": "Favorite Episodes", - "HeaderFavoriteShows": "Favori Showlar", - "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 adresi: {0}", + "HeaderFavoriteArtists": "Favori Sanatçılar", + "HeaderFavoriteEpisodes": "Favori Bölümler", + "HeaderFavoriteShows": "Favori Diziler", + "HeaderFavoriteSongs": "Favori Şarkılar", + "HeaderLiveTV": "Canlı TV", + "HeaderNextUp": "Sonraki hafta", + "HeaderRecordingGroups": "Kayıt Grupları", + "HomeVideos": "Ev videoları", + "Inherit": "Devral", + "ItemAddedWithName": "{0} kütüphaneye eklendi", + "ItemRemovedWithName": "{0} kütüphaneden silindi", + "LabelIpAddressValue": "IP adresi: {0}", "LabelRunningTimeValue": "Çalışma süresi: {0}", - "Latest": "Latest", + "Latest": "En son", "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", + "MessageApplicationUpdatedTo": "Jellyfin Sunucusu {0} olarak güncellendi", + "MessageNamedServerConfigurationUpdatedWithValue": "Sunucu ayarları kısım {0} güncellendi", + "MessageServerConfigurationUpdated": "Sunucu ayarları güncellendi", + "MixedContent": "Karışık içerik", + "Movies": "Filmler", "Music": "Müzik", "MusicVideos": "Müzik videoları", - "NameInstallFailed": "{0} kurulum başarısız", + "NameInstallFailed": "{0} kurulumu 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", - "NotificationOptionAudioPlaybackStopped": "Audio playback stopped", - "NotificationOptionCameraImageUploaded": "Camera image uploaded", - "NotificationOptionInstallationFailed": "Yükleme hatası", - "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", - "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": "Shows", - "Songs": "Songs", - "StartupEmbyServerIsLoading": "Jellyfin Server is loading. Please try again shortly.", + "NotificationOptionApplicationUpdateAvailable": "Uygulama güncellemesi mevcut", + "NotificationOptionApplicationUpdateInstalled": "Uygulama güncellemesi yüklendi", + "NotificationOptionAudioPlayback": "Ses çalma başladı", + "NotificationOptionAudioPlaybackStopped": "Ses çalma durduruldu", + "NotificationOptionCameraImageUploaded": "Kamera fotoğrafı yüklendi", + "NotificationOptionInstallationFailed": "Yükleme başarısız oldu", + "NotificationOptionNewLibraryContent": "Yeni içerik eklendi", + "NotificationOptionPluginError": "Eklenti hatası", + "NotificationOptionPluginInstalled": "Eklenti yüklendi", + "NotificationOptionPluginUninstalled": "Eklenti kaldırıldı", + "NotificationOptionPluginUpdateInstalled": "Eklenti güncellemesi yüklendi", + "NotificationOptionServerRestartRequired": "Sunucu yeniden başlatma gerekli", + "NotificationOptionTaskFailed": "Zamanlanmış görev hatası", + "NotificationOptionUserLockedOut": "Kullanıcı kitlendi", + "NotificationOptionVideoPlayback": "Video oynatma başladı", + "NotificationOptionVideoPlaybackStopped": "Video oynatma durduruldu", + "Photos": "Fotoğraflar", + "Playlists": "Çalma listeleri", + "Plugin": "Eklenti", + "PluginInstalledWithName": "{0} yüklendi", + "PluginUninstalledWithName": "{0} kaldırıldı", + "PluginUpdatedWithName": "{0} güncellendi", + "ProviderValue": "Sağlayıcı: {0}", + "ScheduledTaskFailedWithName": "{0} başarısız oldu", + "ScheduledTaskStartedWithName": "{0} başladı", + "ServerNameNeedsToBeRestarted": "{0} yeniden başlatılması gerekiyor", + "Shows": "Diziler", + "Songs": "Şarkılar", + "StartupEmbyServerIsLoading": "Jellyfin Sunucusu yükleniyor. Lütfen kısa süre sonra tekrar deneyin.", "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": "{1} için alt yazılar {0} 'dan indirilemedi", + "SubtitlesDownloadedForItem": "{0} için altyazılar indirildi", + "Sync": "Eşitle", + "System": "Sistem", + "TvShows": "Diziler", + "User": "Kullanıcı", + "UserCreatedWithName": "{0} kullanıcısı oluşturuldu", + "UserDeletedWithName": "Kullanıcı {0} silindi", + "UserDownloadingItemWithValues": "{0} indiriliyor {1}", + "UserLockedOutWithName": "Kullanıcı {0} kitlendi", + "UserOfflineFromDevice": "{0}, {1} ile bağlantısı kesildi", + "UserOnlineFromDevice": "{0}, {1} çevrimiçi", + "UserPasswordChangedWithName": "{0} kullanıcısı için şifre değiştirildi", + "UserPolicyUpdatedWithName": "Kullanıcı politikası {0} için güncellendi", + "UserStartedPlayingItemWithValues": "{0}, {2} cihazında {1} izliyor", + "UserStoppedPlayingItemWithValues": "{0}, {2} cihazında {1} izlemeyi bitirdi", + "ValueHasBeenAddedToLibrary": "Medya kitaplığınıza {0} eklendi", + "ValueSpecialEpisodeName": "Özel - {0}", + "VersionNumber": "Versiyon {0}" } diff --git a/Emby.Server.Implementations/Localization/Core/zh-CN.json b/Emby.Server.Implementations/Localization/Core/zh-CN.json index ba5e939828..87f8553ae0 100644 --- a/Emby.Server.Implementations/Localization/Core/zh-CN.json +++ b/Emby.Server.Implementations/Localization/Core/zh-CN.json @@ -5,7 +5,7 @@ "Artists": "艺术家", "AuthenticationSucceededWithUserName": "{0} 认证成功", "Books": "书籍", - "CameraImageUploadedFrom": "已从 {0} 上传了一张新的相机图像", + "CameraImageUploadedFrom": "已从 {0} 上传了一张新的相片", "Channels": "频道", "ChapterNameValue": "章节 {0}", "Collections": "合集", diff --git a/Emby.Server.Implementations/Localization/Core/zh-HK.json b/Emby.Server.Implementations/Localization/Core/zh-HK.json index 387fc2b92b..33fcb2d37c 100644 --- a/Emby.Server.Implementations/Localization/Core/zh-HK.json +++ b/Emby.Server.Implementations/Localization/Core/zh-HK.json @@ -2,7 +2,7 @@ "Albums": "Albums", "AppDeviceValues": "App: {0}, Device: {1}", "Application": "Application", - "Artists": "Artists", + "Artists": "藝人", "AuthenticationSucceededWithUserName": "{0} successfully authenticated", "Books": "Books", "CameraImageUploadedFrom": "A new camera image has been uploaded from {0}", diff --git a/Emby.Server.Implementations/Localization/Core/zh-TW.json b/Emby.Server.Implementations/Localization/Core/zh-TW.json index 293fc28a86..33bdbfb989 100644 --- a/Emby.Server.Implementations/Localization/Core/zh-TW.json +++ b/Emby.Server.Implementations/Localization/Core/zh-TW.json @@ -1,6 +1,6 @@ { "Albums": "專輯", - "AppDeviceValues": "應用: {0}, 裝置: {1}", + "AppDeviceValues": "軟體: {0}, 裝置: {1}", "Application": "應用程式", "Artists": "演出者", "AuthenticationSucceededWithUserName": "{0} 成功授權", diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs index 13cdc50ca4..bda43e832a 100644 --- a/Emby.Server.Implementations/Localization/LocalizationManager.cs +++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs @@ -5,11 +5,9 @@ using System.Globalization; using System.IO; using System.Linq; using System.Reflection; -using System.Text; using System.Threading.Tasks; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; diff --git a/Emby.Server.Implementations/Middleware/WebSocketMiddleware.cs b/Emby.Server.Implementations/Middleware/WebSocketMiddleware.cs index 268bf4042d..fda32da5e8 100644 --- a/Emby.Server.Implementations/Middleware/WebSocketMiddleware.cs +++ b/Emby.Server.Implementations/Middleware/WebSocketMiddleware.cs @@ -27,12 +27,12 @@ namespace Emby.Server.Implementations.Middleware var webSocketContext = await httpContext.WebSockets.AcceptWebSocketAsync(null).ConfigureAwait(false); if (webSocketContext != null) { - await _webSocketManager.OnWebSocketConnected(webSocketContext); + await _webSocketManager.OnWebSocketConnected(webSocketContext).ConfigureAwait(false); } } else { - await _next.Invoke(httpContext); + await _next.Invoke(httpContext).ConfigureAwait(false); } } } diff --git a/Emby.Server.Implementations/Networking/NetworkManager.cs b/Emby.Server.Implementations/Networking/NetworkManager.cs index 7d85a0666a..1d8d3cf395 100644 --- a/Emby.Server.Implementations/Networking/NetworkManager.cs +++ b/Emby.Server.Implementations/Networking/NetworkManager.cs @@ -7,8 +7,6 @@ using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading.Tasks; using MediaBrowser.Common.Net; -using MediaBrowser.Model.IO; -using MediaBrowser.Model.Net; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Networking @@ -20,6 +18,9 @@ namespace Emby.Server.Implementations.Networking private IPAddress[] _localIpAddresses; private readonly object _localIpAddressSyncLock = new object(); + private readonly object _subnetLookupLock = new object(); + private Dictionary> _subnetLookup = new Dictionary>(StringComparer.Ordinal); + public NetworkManager(ILogger logger) { _logger = logger; @@ -28,10 +29,10 @@ namespace Emby.Server.Implementations.Networking NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged; } - public Func LocalSubnetsFn { get; set; } - public event EventHandler NetworkChanged; + public Func LocalSubnetsFn { get; set; } + private void OnNetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e) { _logger.LogDebug("NetworkAvailabilityChanged"); @@ -52,10 +53,7 @@ namespace Emby.Server.Implementations.Networking _macAddresses = null; } - if (NetworkChanged != null) - { - NetworkChanged(this, EventArgs.Empty); - } + NetworkChanged?.Invoke(this, EventArgs.Empty); } public IPAddress[] GetLocalIpAddresses(bool ignoreVirtualInterface = true) @@ -179,10 +177,9 @@ namespace Emby.Server.Implementations.Networking return false; } - private Dictionary> _subnetLookup = new Dictionary>(StringComparer.Ordinal); private List GetSubnets(string endpointFirstPart) { - lock (_subnetLookup) + lock (_subnetLookupLock) { if (_subnetLookup.TryGetValue(endpointFirstPart, out var subnets)) { @@ -200,7 +197,11 @@ namespace Emby.Server.Implementations.Networking int subnet_Test = 0; foreach (string part in unicastIPAddressInformation.IPv4Mask.ToString().Split('.')) { - if (part.Equals("0")) break; + if (part.Equals("0", StringComparison.Ordinal)) + { + break; + } + subnet_Test++; } @@ -255,10 +256,10 @@ namespace Emby.Server.Implementations.Networking return true; } - if (normalizedSubnet.IndexOf('/') != -1) + if (normalizedSubnet.Contains('/', StringComparison.Ordinal)) { - var ipnetwork = IPNetwork.Parse(normalizedSubnet); - if (ipnetwork.Contains(address)) + var ipNetwork = IPNetwork.Parse(normalizedSubnet); + if (ipNetwork.Contains(address)) { return true; } @@ -447,119 +448,11 @@ namespace Emby.Server.Implementations.Networking .Select(x => x.GetPhysicalAddress()) .Where(x => x != null && x != PhysicalAddress.None); - /// - /// Parses the specified endpointstring. - /// - /// The endpointstring. - /// IPEndPoint. - public IPEndPoint Parse(string endpointstring) - { - return Parse(endpointstring, -1).Result; - } - - /// - /// Parses the specified endpointstring. - /// - /// The endpointstring. - /// The defaultport. - /// IPEndPoint. - /// Endpoint descriptor may not be empty. - /// - private static async Task Parse(string endpointstring, int defaultport) - { - if (string.IsNullOrEmpty(endpointstring) - || endpointstring.Trim().Length == 0) - { - throw new ArgumentException("Endpoint descriptor may not be empty."); - } - - if (defaultport != -1 && - (defaultport < IPEndPoint.MinPort - || defaultport > IPEndPoint.MaxPort)) - { - throw new ArgumentException(string.Format("Invalid default port '{0}'", defaultport)); - } - - string[] values = endpointstring.Split(new char[] { ':' }); - IPAddress ipaddy; - int port = -1; - - //check if we have an IPv6 or ports - if (values.Length <= 2) // ipv4 or hostname - { - port = values.Length == 1 ? defaultport : GetPort(values[1]); - - //try to use the address as IPv4, otherwise get hostname - if (!IPAddress.TryParse(values[0], out ipaddy)) - ipaddy = await GetIPfromHost(values[0]).ConfigureAwait(false); - } - else if (values.Length > 2) //ipv6 - { - //could [a:b:c]:d - if (values[0].StartsWith("[") && values[values.Length - 2].EndsWith("]")) - { - string ipaddressstring = string.Join(":", values.Take(values.Length - 1).ToArray()); - ipaddy = IPAddress.Parse(ipaddressstring); - port = GetPort(values[values.Length - 1]); - } - else //[a:b:c] or a:b:c - { - ipaddy = IPAddress.Parse(endpointstring); - port = defaultport; - } - } - else - { - throw new FormatException(string.Format("Invalid endpoint ipaddress '{0}'", endpointstring)); - } - - if (port == -1) - throw new ArgumentException(string.Format("No port specified: '{0}'", endpointstring)); - - return new IPEndPoint(ipaddy, port); - } - - protected static readonly CultureInfo UsCulture = new CultureInfo("en-US"); - - /// - /// Gets the port. - /// - /// The p. - /// System.Int32. - /// - private static int GetPort(string p) - { - if (!int.TryParse(p, out var port) - || port < IPEndPoint.MinPort - || port > IPEndPoint.MaxPort) - { - throw new FormatException(string.Format("Invalid end point port '{0}'", p)); - } - - return port; - } - - /// - /// Gets the I pfrom host. - /// - /// The p. - /// IPAddress. - /// - private static async Task GetIPfromHost(string p) - { - var hosts = await Dns.GetHostAddressesAsync(p).ConfigureAwait(false); - - if (hosts == null || hosts.Length == 0) - throw new ArgumentException(string.Format("Host not found: {0}", p)); - - return hosts[0]; - } - public bool IsInSameSubnet(IPAddress address1, IPAddress address2, IPAddress subnetMask) { - IPAddress network1 = GetNetworkAddress(address1, subnetMask); - IPAddress network2 = GetNetworkAddress(address2, subnetMask); - return network1.Equals(network2); + IPAddress network1 = GetNetworkAddress(address1, subnetMask); + IPAddress network2 = GetNetworkAddress(address2, subnetMask); + return network1.Equals(network2); } private IPAddress GetNetworkAddress(IPAddress address, IPAddress subnetMask) @@ -575,7 +468,7 @@ namespace Emby.Server.Implementations.Networking byte[] broadcastAddress = new byte[ipAdressBytes.Length]; for (int i = 0; i < broadcastAddress.Length; i++) { - broadcastAddress[i] = (byte)(ipAdressBytes[i] & (subnetMaskBytes[i])); + broadcastAddress[i] = (byte)(ipAdressBytes[i] & subnetMaskBytes[i]); } return new IPAddress(broadcastAddress); @@ -615,24 +508,5 @@ namespace Emby.Server.Implementations.Networking return null; } - - /// - /// Gets the network shares. - /// - /// The path. - /// IEnumerable{NetworkShare}. - public virtual IEnumerable GetNetworkShares(string path) - { - return new List(); - } - - /// - /// Gets available devices within the domain - /// - /// PC's in the Domain - public virtual IEnumerable GetNetworkDevices() - { - return new List(); - } } } diff --git a/Emby.Server.Implementations/Playlists/ManualPlaylistsFolder.cs b/Emby.Server.Implementations/Playlists/ManualPlaylistsFolder.cs index f4decc856e..cd9f7946e9 100644 --- a/Emby.Server.Implementations/Playlists/ManualPlaylistsFolder.cs +++ b/Emby.Server.Implementations/Playlists/ManualPlaylistsFolder.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using System.Linq; +using System.Text.Json.Serialization; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Playlists; using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Serialization; namespace Emby.Server.Implementations.Playlists { @@ -24,13 +24,13 @@ namespace Emby.Server.Implementations.Playlists return base.GetEligibleChildrenForRecursiveChildren(user).OfType(); } - [IgnoreDataMember] + [JsonIgnore] public override bool IsHidden => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsInheritedParentImages => false; - [IgnoreDataMember] + [JsonIgnore] public override string CollectionType => MediaBrowser.Model.Entities.CollectionType.Playlists; protected override QueryResult GetItemsInternal(InternalItemsQuery query) @@ -48,4 +48,3 @@ namespace Emby.Server.Implementations.Playlists } } } - diff --git a/Emby.Server.Implementations/Playlists/PlaylistManager.cs b/Emby.Server.Implementations/Playlists/PlaylistManager.cs index 40b568b40a..0f58e43ed1 100644 --- a/Emby.Server.Implementations/Playlists/PlaylistManager.cs +++ b/Emby.Server.Implementations/Playlists/PlaylistManager.cs @@ -90,8 +90,7 @@ namespace Emby.Server.Implementations.Playlists } else { - var folder = item as Folder; - if (folder != null) + if (item is Folder folder) { options.MediaType = folder.GetRecursiveChildren(i => !i.IsFolder && i.SupportsAddingToPlaylist) .Select(i => i.MediaType) @@ -140,7 +139,7 @@ namespace Emby.Server.Implementations.Playlists parentFolder.AddChild(playlist, CancellationToken.None); - await playlist.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) { ForceSave = true }, CancellationToken.None) + await playlist.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_fileSystem)) { ForceSave = true }, CancellationToken.None) .ConfigureAwait(false); if (options.ItemIdList.Length > 0) @@ -201,7 +200,7 @@ namespace Emby.Server.Implementations.Playlists var list = new List(); - var items = (GetPlaylistItems(itemIds, playlist.MediaType, user, options)) + var items = GetPlaylistItems(itemIds, playlist.MediaType, user, options) .Where(i => i.SupportsAddingToPlaylist) .ToList(); @@ -221,18 +220,18 @@ namespace Emby.Server.Implementations.Playlists SavePlaylistFile(playlist); } - _providerManager.QueueRefresh(playlist.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) - { - ForceSave = true - - }, RefreshPriority.High); + _providerManager.QueueRefresh( + playlist.Id, + new MetadataRefreshOptions(new DirectoryService(_fileSystem)) + { + ForceSave = true + }, + RefreshPriority.High); } public void RemoveFromPlaylist(string playlistId, IEnumerable entryIds) { - var playlist = _libraryManager.GetItemById(playlistId) as Playlist; - - if (playlist == null) + if (!(_libraryManager.GetItemById(playlistId) is Playlist playlist)) { throw new ArgumentException("No Playlist exists with the supplied Id"); } @@ -254,7 +253,7 @@ namespace Emby.Server.Implementations.Playlists SavePlaylistFile(playlist); } - _providerManager.QueueRefresh(playlist.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) + _providerManager.QueueRefresh(playlist.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)) { ForceSave = true @@ -263,9 +262,7 @@ namespace Emby.Server.Implementations.Playlists public void MoveItem(string playlistId, string entryId, int newIndex) { - var playlist = _libraryManager.GetItemById(playlistId) as Playlist; - - if (playlist == null) + if (!(_libraryManager.GetItemById(playlistId) is Playlist playlist)) { throw new ArgumentException("No Playlist exists with the supplied Id"); } diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index 83226b07f1..5b188d9626 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -23,7 +23,7 @@ namespace Emby.Server.Implementations.ScheduledTasks public event EventHandler> TaskProgress; /// - /// Gets or sets the scheduled task. + /// Gets the scheduled task. /// /// The scheduled task. public IScheduledTask ScheduledTask { get; private set; } @@ -215,11 +215,12 @@ namespace Emby.Server.Implementations.ScheduledTasks public double? CurrentProgress { get; private set; } /// - /// The _triggers + /// The _triggers. /// private Tuple[] _triggers; + /// - /// Gets the triggers that define when the task will run + /// Gets the triggers that define when the task will run. /// /// The triggers. private Tuple[] InternalTriggers @@ -245,7 +246,7 @@ namespace Emby.Server.Implementations.ScheduledTasks } /// - /// Gets the triggers that define when the task will run + /// Gets the triggers that define when the task will run. /// /// The triggers. /// value diff --git a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs index 595c3037d7..ecf58dbc0e 100644 --- a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs +++ b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs @@ -36,19 +36,19 @@ namespace Emby.Server.Implementations.ScheduledTasks /// Gets or sets the json serializer. /// /// The json serializer. - private IJsonSerializer JsonSerializer { get; set; } + private readonly IJsonSerializer _jsonSerializer; /// /// Gets or sets the application paths. /// /// The application paths. - private IApplicationPaths ApplicationPaths { get; set; } + private readonly IApplicationPaths _applicationPaths; /// /// Gets the logger. /// /// The logger. - private ILogger Logger { get; set; } + private readonly ILogger _logger; private readonly IFileSystem _fileSystem; /// @@ -57,19 +57,19 @@ namespace Emby.Server.Implementations.ScheduledTasks /// The application paths. /// The json serializer. /// The logger factory. - /// kernel + /// The filesystem manager. public TaskManager( IApplicationPaths applicationPaths, IJsonSerializer jsonSerializer, ILoggerFactory loggerFactory, IFileSystem fileSystem) { - ApplicationPaths = applicationPaths; - JsonSerializer = jsonSerializer; - Logger = loggerFactory.CreateLogger(nameof(TaskManager)); + _applicationPaths = applicationPaths; + _jsonSerializer = jsonSerializer; + _logger = loggerFactory.CreateLogger(nameof(TaskManager)); _fileSystem = fileSystem; - ScheduledTasks = new IScheduledTaskWorker[] { }; + ScheduledTasks = Array.Empty(); } /// @@ -78,7 +78,7 @@ namespace Emby.Server.Implementations.ScheduledTasks /// /// Task options. public void CancelIfRunningAndQueue(TaskOptions options) - where T : IScheduledTask + where T : IScheduledTask { var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T)); ((ScheduledTaskWorker)task).CancelIfRunning(); @@ -115,7 +115,7 @@ namespace Emby.Server.Implementations.ScheduledTasks if (scheduledTask == null) { - Logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", typeof(T).Name); + _logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", typeof(T).Name); } else { @@ -147,13 +147,13 @@ namespace Emby.Server.Implementations.ScheduledTasks if (scheduledTask == null) { - Logger.LogError("Unable to find scheduled task of type {0} in Execute.", typeof(T).Name); + _logger.LogError("Unable to find scheduled task of type {0} in Execute.", typeof(T).Name); } else { var type = scheduledTask.ScheduledTask.GetType(); - Logger.LogInformation("Queueing task {0}", type.Name); + _logger.LogInformation("Queueing task {0}", type.Name); lock (_taskQueue) { @@ -176,7 +176,7 @@ namespace Emby.Server.Implementations.ScheduledTasks if (scheduledTask == null) { - Logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name); + _logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name); } else { @@ -193,7 +193,7 @@ namespace Emby.Server.Implementations.ScheduledTasks { var type = task.ScheduledTask.GetType(); - Logger.LogInformation("Queueing task {0}", type.Name); + _logger.LogInformation("Queueing task {0}", type.Name); lock (_taskQueue) { @@ -213,7 +213,7 @@ namespace Emby.Server.Implementations.ScheduledTasks /// The tasks. public void AddTasks(IEnumerable tasks) { - var list = tasks.Select(t => new ScheduledTaskWorker(t, ApplicationPaths, this, JsonSerializer, Logger, _fileSystem)); + var list = tasks.Select(t => new ScheduledTaskWorker(t, _applicationPaths, this, _jsonSerializer, _logger, _fileSystem)); ScheduledTasks = ScheduledTasks.Concat(list).ToArray(); } @@ -281,7 +281,7 @@ namespace Emby.Server.Implementations.ScheduledTasks /// private void ExecuteQueuedTasks() { - Logger.LogInformation("ExecuteQueuedTasks"); + _logger.LogInformation("ExecuteQueuedTasks"); // Execute queued tasks lock (_taskQueue) diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs index 2f07ff15a9..ecd5262510 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs @@ -19,16 +19,17 @@ using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.ScheduledTasks { /// - /// Class ChapterImagesTask + /// Class ChapterImagesTask. /// public class ChapterImagesTask : IScheduledTask { /// - /// The _logger + /// The _logger. /// private readonly ILogger _logger; + /// - /// The _library manager + /// The _library manager. /// private readonly ILibraryManager _libraryManager; @@ -53,12 +54,12 @@ namespace Emby.Server.Implementations.ScheduledTasks } /// - /// Creates the triggers that define when the task will run + /// Creates the triggers that define when the task will run. /// public IEnumerable GetDefaultTriggers() { - return new[] { - + return new[] + { new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerDaily, @@ -117,7 +118,7 @@ namespace Emby.Server.Implementations.ScheduledTasks previouslyFailedImages = new List(); } - var directoryService = new DirectoryService(_logger, _fileSystem); + var directoryService = new DirectoryService(_fileSystem); foreach (var video in videos) { diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs index c343a7d482..72b524df02 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Configuration; using MediaBrowser.Model.IO; using MediaBrowser.Model.Tasks; using Microsoft.Extensions.Logging; @@ -15,24 +16,18 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks /// public class DeleteTranscodeFileTask : IScheduledTask, IConfigurableScheduledTask { - /// - /// Gets or sets the application paths. - /// - /// The application paths. - private ServerApplicationPaths ApplicationPaths { get; set; } - private readonly ILogger _logger; - + private readonly IConfigurationManager _configurationManager; private readonly IFileSystem _fileSystem; /// /// Initializes a new instance of the class. /// - public DeleteTranscodeFileTask(ServerApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem) + public DeleteTranscodeFileTask(ILogger logger, IFileSystem fileSystem, IConfigurationManager configurationManager) { - ApplicationPaths = appPaths; _logger = logger; _fileSystem = fileSystem; + _configurationManager = configurationManager; } /// @@ -52,14 +47,7 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks var minDateModified = DateTime.UtcNow.AddDays(-1); progress.Report(50); - try - { - DeleteTempFilesFromDirectory(cancellationToken, ApplicationPaths.TranscodingTempPath, minDateModified, progress); - } - catch (DirectoryNotFoundException) - { - // No biggie here. Nothing to delete - } + DeleteTempFilesFromDirectory(cancellationToken, _configurationManager.GetTranscodePath(), minDateModified, progress); return Task.CompletedTask; } @@ -138,13 +126,13 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks } } - public string Name => "Transcoding temp cleanup"; + public string Name => "Transcode file cleanup"; - public string Description => "Deletes transcoding temp files older than 24 hours."; + public string Description => "Deletes transcode files more than 24 hours old."; public string Category => "Maintenance"; - public string Key => "DeleteTranscodingTempFiles"; + public string Key => "DeleteTranscodeFiles"; public bool IsHidden => false; diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs index 7afeba9dd7..909fffb1ff 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs @@ -1,24 +1,23 @@ -using MediaBrowser.Common.Updates; -using MediaBrowser.Model.Net; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Common.Progress; +using MediaBrowser.Common.Updates; +using MediaBrowser.Model.Net; using MediaBrowser.Model.Tasks; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.ScheduledTasks { /// - /// Plugin Update Task + /// Plugin Update Task. /// public class PluginUpdateTask : IScheduledTask, IConfigurableScheduledTask { /// - /// The _logger + /// The _logger. /// private readonly ILogger _logger; @@ -31,7 +30,7 @@ namespace Emby.Server.Implementations.ScheduledTasks } /// - /// Creates the triggers that define when the task will run + /// Creates the triggers that define when the task will run. /// /// IEnumerable{BaseTaskTrigger}. public IEnumerable GetDefaultTriggers() @@ -44,16 +43,18 @@ namespace Emby.Server.Implementations.ScheduledTasks } /// - /// Update installed plugins + /// Update installed plugins. /// /// The cancellation token. /// The progress. - /// Task. + /// . public async Task Execute(CancellationToken cancellationToken, IProgress progress) { progress.Report(0); - var packagesToInstall = (await _installationManager.GetAvailablePluginUpdates(typeof(PluginUpdateTask).Assembly.GetName().Version, true, cancellationToken).ConfigureAwait(false)).ToList(); + var packagesToInstall = await _installationManager.GetAvailablePluginUpdates(cancellationToken) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); progress.Report(10); @@ -94,18 +95,25 @@ namespace Emby.Server.Implementations.ScheduledTasks progress.Report(100); } + /// public string Name => "Check for plugin updates"; + /// public string Description => "Downloads and installs updates for plugins that are configured to update automatically."; + /// public string Category => "Application"; + /// public string Key => "PluginUpdates"; + /// public bool IsHidden => false; + /// public bool IsEnabled => true; + /// public bool IsLogged => true; } } diff --git a/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs index ec9466c4ab..ea278de0d9 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs @@ -1,5 +1,4 @@ using System; -using System.Globalization; using System.Threading; using MediaBrowser.Model.Tasks; using Microsoft.Extensions.Logging; @@ -7,12 +6,12 @@ using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.ScheduledTasks { /// - /// Represents a task trigger that fires everyday + /// Represents a task trigger that fires everyday. /// public class DailyTrigger : ITaskTrigger { /// - /// Get the time of day to trigger the task to run + /// Get the time of day to trigger the task to run. /// /// The time of day. public TimeSpan TimeOfDay { get; set; } diff --git a/Emby.Server.Implementations/Serialization/XmlSerializer.cs b/Emby.Server.Implementations/Serialization/MyXmlSerializer.cs similarity index 74% rename from Emby.Server.Implementations/Serialization/XmlSerializer.cs rename to Emby.Server.Implementations/Serialization/MyXmlSerializer.cs index 6400ec16ec..2968229810 100644 --- a/Emby.Server.Implementations/Serialization/XmlSerializer.cs +++ b/Emby.Server.Implementations/Serialization/MyXmlSerializer.cs @@ -1,11 +1,9 @@ using System; -using System.Collections.Generic; +using System.Collections.Concurrent; using System.IO; using System.Xml; using System.Xml.Serialization; -using MediaBrowser.Model.IO; using MediaBrowser.Model.Serialization; -using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Serialization { @@ -14,35 +12,13 @@ namespace Emby.Server.Implementations.Serialization /// public class MyXmlSerializer : IXmlSerializer { - private readonly IFileSystem _fileSystem; - private readonly ILogger _logger; - - public MyXmlSerializer( - IFileSystem fileSystem, - ILoggerFactory loggerFactory) - { - _fileSystem = fileSystem; - _logger = loggerFactory.CreateLogger("XmlSerializer"); - } - // Need to cache these // http://dotnetcodebox.blogspot.com/2013/01/xmlserializer-class-may-result-in.html - private readonly Dictionary _serializers = - new Dictionary(); + private static readonly ConcurrentDictionary _serializers = + new ConcurrentDictionary(); - private XmlSerializer GetSerializer(Type type) - { - var key = type.FullName; - lock (_serializers) - { - if (!_serializers.TryGetValue(key, out var serializer)) - { - serializer = new XmlSerializer(type); - _serializers[key] = serializer; - } - return serializer; - } - } + private static XmlSerializer GetSerializer(Type type) + => _serializers.GetOrAdd(type.FullName, _ => new XmlSerializer(type)); /// /// Serializes to writer. @@ -91,7 +67,6 @@ namespace Emby.Server.Implementations.Serialization /// The file. public void SerializeToFile(object obj, string file) { - _logger.LogDebug("Serializing to file {0}", file); using (var stream = new FileStream(file, FileMode.Create)) { SerializeToStream(obj, stream); @@ -106,7 +81,6 @@ namespace Emby.Server.Implementations.Serialization /// System.Object. public object DeserializeFromFile(Type type, string file) { - _logger.LogDebug("Deserializing file {0}", file); using (var stream = File.OpenRead(file)) { return DeserializeFromStream(type, stream); diff --git a/Emby.Server.Implementations/ServerApplicationPaths.cs b/Emby.Server.Implementations/ServerApplicationPaths.cs index 2f5a8af802..2f57c97a13 100644 --- a/Emby.Server.Implementations/ServerApplicationPaths.cs +++ b/Emby.Server.Implementations/ServerApplicationPaths.cs @@ -1,4 +1,3 @@ -using System; using System.IO; using Emby.Server.Implementations.AppBase; using MediaBrowser.Controller; @@ -6,12 +5,10 @@ using MediaBrowser.Controller; namespace Emby.Server.Implementations { /// - /// Extends BaseApplicationPaths to add paths that are only applicable on the server + /// Extends BaseApplicationPaths to add paths that are only applicable on the server. /// public class ServerApplicationPaths : BaseApplicationPaths, IServerApplicationPaths { - private string _defaultTranscodingTempPath; - private string _transcodingTempPath; private string _internalMetadataPath; /// @@ -23,7 +20,8 @@ namespace Emby.Server.Implementations string configurationDirectoryPath, string cacheDirectoryPath, string webDirectoryPath) - : base(programDataPath, + : base( + programDataPath, logDirectoryPath, configurationDirectoryPath, cacheDirectoryPath, @@ -31,8 +29,6 @@ namespace Emby.Server.Implementations { } - public string ApplicationResourcesPath { get; } = AppContext.BaseDirectory; - /// /// Gets the path to the base root media directory. /// @@ -45,18 +41,13 @@ namespace Emby.Server.Implementations /// The default user views path. public string DefaultUserViewsPath => Path.Combine(RootFolderPath, "default"); - /// - /// Gets the path to localization data. - /// - /// The localization path. - public string LocalizationPath => Path.Combine(ProgramDataPath, "localization"); - /// /// Gets the path to the People directory. /// /// The people path. public string PeoplePath => Path.Combine(InternalMetadataPath, "People"); + /// public string ArtistsPath => Path.Combine(InternalMetadataPath, "artists"); /// @@ -107,46 +98,14 @@ namespace Emby.Server.Implementations /// The user configuration directory path. public string UserConfigurationDirectoryPath => Path.Combine(ConfigurationDirectoryPath, "users"); - public string DefaultTranscodingTempPath => _defaultTranscodingTempPath ?? (_defaultTranscodingTempPath = Path.Combine(ProgramDataPath, "transcoding-temp")); - - public string TranscodingTempPath - { - get => _transcodingTempPath ?? (_transcodingTempPath = DefaultTranscodingTempPath); - set => _transcodingTempPath = value; - } - - public string GetTranscodingTempPath() - { - var path = TranscodingTempPath; - - if (!string.Equals(path, DefaultTranscodingTempPath, StringComparison.OrdinalIgnoreCase)) - { - try - { - Directory.CreateDirectory(path); - - var testPath = Path.Combine(path, Guid.NewGuid().ToString()); - Directory.CreateDirectory(testPath); - Directory.Delete(testPath); - - return path; - } - catch - { - } - } - - path = DefaultTranscodingTempPath; - Directory.CreateDirectory(path); - return path; - } - + /// public string InternalMetadataPath { get => _internalMetadataPath ?? (_internalMetadataPath = Path.Combine(DataPath, "metadata")); set => _internalMetadataPath = value; } + /// public string VirtualInternalMetadataPath { get; } = "%MetadataPath%"; } } diff --git a/Emby.Server.Implementations/Services/ServicePath.cs b/Emby.Server.Implementations/Services/ServicePath.cs index ccb28e8df0..27c4dcba07 100644 --- a/Emby.Server.Implementations/Services/ServicePath.cs +++ b/Emby.Server.Implementations/Services/ServicePath.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; +using System.Text.Json.Serialization; namespace Emby.Server.Implementations.Services { @@ -28,6 +30,13 @@ namespace Emby.Server.Implementations.Services private readonly bool[] isWildcard; private readonly int wildcardCount = 0; + internal static string[] IgnoreAttributesNamed = new[] + { + nameof(JsonIgnoreAttribute) + }; + + private static Type _excludeType = typeof(Stream); + public int VariableArgsCount { get; set; } /// @@ -37,8 +46,8 @@ namespace Emby.Server.Implementations.Services public int PathComponentsCount { get; set; } /// - /// The total number of segments after subparts have been exploded ('.') - /// e.g. /path/to/here.ext == 4 + /// Gets or sets the total number of segments after subparts have been exploded ('.') + /// e.g. /path/to/here.ext == 4. /// public int TotalComponentsCount { get; set; } @@ -190,21 +199,12 @@ namespace Emby.Server.Implementations.Services StringComparer.OrdinalIgnoreCase); } - internal static string[] IgnoreAttributesNamed = new[] - { - "IgnoreDataMemberAttribute", - "JsonIgnoreAttribute" - }; - - - private static Type excludeType = typeof(Stream); - internal static IEnumerable GetSerializableProperties(Type type) { foreach (var prop in GetPublicProperties(type)) { if (prop.GetMethod == null - || excludeType == prop.PropertyType) + || _excludeType == prop.PropertyType) { continue; } @@ -280,7 +280,7 @@ namespace Emby.Server.Implementations.Services } /// - /// Provide for quick lookups based on hashes that can be determined from a request url + /// Provide for quick lookups based on hashes that can be determined from a request url. /// public string FirstMatchHashKey { get; private set; } @@ -437,9 +437,12 @@ namespace Emby.Server.Implementations.Services && requestComponents.Length >= this.TotalComponentsCount - this.wildcardCount; if (!isValidWildCardPath) - throw new ArgumentException(string.Format( - "Path Mismatch: Request Path '{0}' has invalid number of components compared to: '{1}'", - pathInfo, this.restPath)); + throw new ArgumentException( + string.Format( + CultureInfo.InvariantCulture, + "Path Mismatch: Request Path '{0}' has invalid number of components compared to: '{1}'", + pathInfo, + this.restPath)); } var requestKeyValuesMap = new Dictionary(); diff --git a/Emby.Server.Implementations/Services/SwaggerService.cs b/Emby.Server.Implementations/Services/SwaggerService.cs index d223864364..c30f32af94 100644 --- a/Emby.Server.Implementations/Services/SwaggerService.cs +++ b/Emby.Server.Implementations/Services/SwaggerService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using MediaBrowser.Controller.Net; @@ -175,7 +175,7 @@ namespace Emby.Server.Implementations.Services private SwaggerTag[] GetTags() { - return new SwaggerTag[] { }; + return Array.Empty(); } private Dictionary GetDefinitions() diff --git a/Emby.Server.Implementations/Session/HttpSessionController.cs b/Emby.Server.Implementations/Session/HttpSessionController.cs index 1104a7a85b..dfb81816c7 100644 --- a/Emby.Server.Implementations/Session/HttpSessionController.cs +++ b/Emby.Server.Implementations/Session/HttpSessionController.cs @@ -105,7 +105,7 @@ namespace Emby.Server.Implementations.Session return SendMessage(command.Command.ToString(), messageId, args, cancellationToken); } - private string[] _supportedMessages = new string[] { }; + private string[] _supportedMessages = Array.Empty(); public Task SendMessage(string name, string messageId, T data, ISessionController[] allControllers, CancellationToken cancellationToken) { if (!IsSessionActive) diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index 68cd3c0bae..b87ca3a114 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -1386,27 +1386,28 @@ namespace Emby.Server.Implementations.Session if (user != null) { // TODO: Move this to userManager? - if (!string.IsNullOrEmpty(request.DeviceId)) + if (!string.IsNullOrEmpty(request.DeviceId) + && !_deviceManager.CanAccessDevice(user, request.DeviceId)) { - if (!_deviceManager.CanAccessDevice(user, request.DeviceId)) - { - throw new SecurityException("User is not allowed access from this device."); - } + throw new SecurityException("User is not allowed access from this device."); } } if (enforcePassword) { - var result = await _userManager.AuthenticateUser(request.Username, request.Password, request.PasswordSha1, request.RemoteEndPoint, true).ConfigureAwait(false); + user = await _userManager.AuthenticateUser( + request.Username, + request.Password, + request.PasswordSha1, + request.RemoteEndPoint, + true).ConfigureAwait(false); + } - if (result == null) - { - AuthenticationFailed?.Invoke(this, new GenericEventArgs(request)); + if (user == null) + { + AuthenticationFailed?.Invoke(this, new GenericEventArgs(request)); - throw new SecurityException("Invalid user or password entered."); - } - - user = result; + throw new SecurityException("Invalid user or password entered."); } var token = GetAuthorizationToken(user, request.DeviceId, request.App, request.AppVersion, request.DeviceName); diff --git a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs index 63ec757626..930f2d35d3 100644 --- a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs +++ b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs @@ -4,7 +4,6 @@ using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Events; using MediaBrowser.Model.Serialization; -using MediaBrowser.Model.Services; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; @@ -67,7 +66,7 @@ namespace Emby.Server.Implementations.Session { if (queryString == null) { - throw new ArgumentNullException(nameof(queryString)); + return null; } var token = queryString["api_key"]; @@ -75,6 +74,7 @@ namespace Emby.Server.Implementations.Session { return null; } + var deviceId = queryString["deviceId"]; return _sessionManager.GetSessionByAuthenticationToken(token, deviceId, remoteEndpoint); } diff --git a/Emby.Server.Implementations/SocketSharp/SharpWebSocket.cs b/Emby.Server.Implementations/SocketSharp/SharpWebSocket.cs index 62b16ed8c8..67521d6c63 100644 --- a/Emby.Server.Implementations/SocketSharp/SharpWebSocket.cs +++ b/Emby.Server.Implementations/SocketSharp/SharpWebSocket.cs @@ -33,7 +33,7 @@ namespace Emby.Server.Implementations.SocketSharp } /// - /// Gets or sets the state. + /// Gets the state. /// /// The state. public WebSocketState State => _webSocket.State; diff --git a/Emby.Server.Implementations/SocketSharp/WebSocketSharpListener.cs b/Emby.Server.Implementations/SocketSharp/WebSocketSharpListener.cs index e93bff1244..ba5ba1904c 100644 --- a/Emby.Server.Implementations/SocketSharp/WebSocketSharpListener.cs +++ b/Emby.Server.Implementations/SocketSharp/WebSocketSharpListener.cs @@ -81,8 +81,10 @@ namespace Emby.Server.Implementations.SocketSharp if (webSocketContext.State == WebSocketState.Open) { - await webSocketContext.CloseAsync(result.CloseStatus ?? WebSocketCloseStatus.NormalClosure, - result.CloseStatusDescription, _disposeCancellationToken); + await webSocketContext.CloseAsync( + result.CloseStatus ?? WebSocketCloseStatus.NormalClosure, + result.CloseStatusDescription, + _disposeCancellationToken).ConfigureAwait(false); } socket.Dispose(); diff --git a/Emby.Server.Implementations/SocketSharp/WebSocketSharpRequest.cs b/Emby.Server.Implementations/SocketSharp/WebSocketSharpRequest.cs index 332ce39034..1781df8b51 100644 --- a/Emby.Server.Implementations/SocketSharp/WebSocketSharpRequest.cs +++ b/Emby.Server.Implementations/SocketSharp/WebSocketSharpRequest.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Net; -using System.Linq; +using System.Net.Mime; using MediaBrowser.Common.Net; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; @@ -13,11 +13,11 @@ using IHttpRequest = MediaBrowser.Model.Services.IHttpRequest; namespace Emby.Server.Implementations.SocketSharp { - public partial class WebSocketSharpRequest : IHttpRequest + public class WebSocketSharpRequest : IHttpRequest { - public const string FormUrlEncoded = "application/x-www-form-urlencoded"; - public const string MultiPartFormData = "multipart/form-data"; - public const string Soap11 = "text/xml; charset=utf-8"; + private const string FormUrlEncoded = "application/x-www-form-urlencoded"; + private const string MultiPartFormData = "multipart/form-data"; + private const string Soap11 = "text/xml; charset=utf-8"; private string _remoteIp; private Dictionary _items; @@ -78,7 +78,7 @@ namespace Emby.Server.Implementations.SocketSharp get => _responseContentType ?? (_responseContentType = GetResponseContentType(Request)); - set => this._responseContentType = value; + set => _responseContentType = value; } public string PathInfo => Request.Path.Value; @@ -91,7 +91,6 @@ namespace Emby.Server.Implementations.SocketSharp public bool IsLocal => Request.HttpContext.Connection.LocalIpAddress.Equals(Request.HttpContext.Connection.RemoteIpAddress); - public string HttpMethod => Request.Method; public string Verb => HttpMethod; @@ -124,24 +123,29 @@ namespace Emby.Server.Implementations.SocketSharp return specifiedContentType; } - const string serverDefaultContentType = "application/json"; + const string ServerDefaultContentType = MediaTypeNames.Application.Json; var acceptContentTypes = httpReq.Headers.GetCommaSeparatedValues(HeaderNames.Accept); string defaultContentType = null; if (HasAnyOfContentTypes(httpReq, FormUrlEncoded, MultiPartFormData)) { - defaultContentType = serverDefaultContentType; + defaultContentType = ServerDefaultContentType; } var acceptsAnything = false; var hasDefaultContentType = defaultContentType != null; if (acceptContentTypes != null) { - foreach (var acceptsType in acceptContentTypes) + foreach (ReadOnlySpan acceptsType in acceptContentTypes) { - // TODO: @bond move to Span when Span.Split lands - // https://github.com/dotnet/corefx/issues/26528 - var contentType = acceptsType?.Split(';')[0].Trim(); + ReadOnlySpan contentType = acceptsType; + var index = contentType.IndexOf(';'); + if (index != -1) + { + contentType = contentType.Slice(0, index); + } + + contentType = contentType.Trim(); acceptsAnything = contentType.Equals("*/*", StringComparison.OrdinalIgnoreCase); if (acceptsAnything) @@ -158,7 +162,7 @@ namespace Emby.Server.Implementations.SocketSharp } else { - return serverDefaultContentType; + return ServerDefaultContentType; } } } @@ -169,7 +173,7 @@ namespace Emby.Server.Implementations.SocketSharp } // We could also send a '406 Not Acceptable', but this is allowed also - return serverDefaultContentType; + return ServerDefaultContentType; } public static bool HasAnyOfContentTypes(HttpRequest request, params string[] contentTypes) @@ -197,12 +201,12 @@ namespace Emby.Server.Implementations.SocketSharp private static string GetQueryStringContentType(HttpRequest httpReq) { - ReadOnlySpan format = httpReq.Query["format"].ToString().AsSpan(); + ReadOnlySpan format = httpReq.Query["format"].ToString(); if (format == null) { - const int formatMaxLength = 4; - ReadOnlySpan pi = httpReq.Path.ToString().AsSpan(); - if (pi == null || pi.Length <= formatMaxLength) + const int FormatMaxLength = 4; + ReadOnlySpan pi = httpReq.Path.ToString(); + if (pi == null || pi.Length <= FormatMaxLength) { return null; } @@ -213,18 +217,18 @@ namespace Emby.Server.Implementations.SocketSharp } format = LeftPart(pi, '/'); - if (format.Length > formatMaxLength) + if (format.Length > FormatMaxLength) { return null; } } format = LeftPart(format, '.'); - if (format.Contains("json".AsSpan(), StringComparison.OrdinalIgnoreCase)) + if (format.Contains("json", StringComparison.OrdinalIgnoreCase)) { return "application/json"; } - else if (format.Contains("xml".AsSpan(), StringComparison.OrdinalIgnoreCase)) + else if (format.Contains("xml", StringComparison.OrdinalIgnoreCase)) { return "application/xml"; } diff --git a/Emby.Server.Implementations/Sorting/NameComparer.cs b/Emby.Server.Implementations/Sorting/NameComparer.cs index 10fa4359aa..4eb1549f58 100644 --- a/Emby.Server.Implementations/Sorting/NameComparer.cs +++ b/Emby.Server.Implementations/Sorting/NameComparer.cs @@ -19,10 +19,14 @@ namespace Emby.Server.Implementations.Sorting public int Compare(BaseItem x, BaseItem y) { if (x == null) + { throw new ArgumentNullException(nameof(x)); + } if (y == null) + { throw new ArgumentNullException(nameof(y)); + } return string.Compare(x.Name, y.Name, StringComparison.CurrentCultureIgnoreCase); } diff --git a/Emby.Server.Implementations/Sorting/OfficialRatingComparer.cs b/Emby.Server.Implementations/Sorting/OfficialRatingComparer.cs index e8fa8edc8e..7afbd9ff7d 100644 --- a/Emby.Server.Implementations/Sorting/OfficialRatingComparer.cs +++ b/Emby.Server.Implementations/Sorting/OfficialRatingComparer.cs @@ -24,10 +24,14 @@ namespace Emby.Server.Implementations.Sorting public int Compare(BaseItem x, BaseItem y) { if (x == null) + { throw new ArgumentNullException(nameof(x)); + } if (y == null) + { throw new ArgumentNullException(nameof(y)); + } var levelX = string.IsNullOrEmpty(x.OfficialRating) ? 0 : _localization.GetRatingLevel(x.OfficialRating) ?? 0; var levelY = string.IsNullOrEmpty(y.OfficialRating) ? 0 : _localization.GetRatingLevel(y.OfficialRating) ?? 0; diff --git a/Emby.Server.Implementations/Sorting/StudioComparer.cs b/Emby.Server.Implementations/Sorting/StudioComparer.cs index 617ed55d52..c9ac765c10 100644 --- a/Emby.Server.Implementations/Sorting/StudioComparer.cs +++ b/Emby.Server.Implementations/Sorting/StudioComparer.cs @@ -17,10 +17,15 @@ namespace Emby.Server.Implementations.Sorting public int Compare(BaseItem x, BaseItem y) { if (x == null) + { throw new ArgumentNullException(nameof(x)); + } if (y == null) + { throw new ArgumentNullException(nameof(y)); + } + return AlphanumComparator.CompareValues(x.Studios.FirstOrDefault() ?? string.Empty, y.Studios.FirstOrDefault() ?? string.Empty); } diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index 0c0c77cda1..09a5a0dca8 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -19,52 +19,18 @@ using MediaBrowser.Model.IO; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Updates; using Microsoft.Extensions.Logging; -using static MediaBrowser.Common.HexHelper; namespace Emby.Server.Implementations.Updates { /// - /// Manages all install, uninstall and update operations (both plugins and system) + /// Manages all install, uninstall and update operations (both plugins and system). /// public class InstallationManager : IInstallationManager { - public event EventHandler PackageInstalling; - public event EventHandler PackageInstallationCompleted; - public event EventHandler PackageInstallationFailed; - public event EventHandler PackageInstallationCancelled; - /// - /// The current installations - /// - private List<(InstallationInfo info, CancellationTokenSource token)> _currentInstallations { get; set; } - - /// - /// The completed installations - /// - private ConcurrentBag _completedInstallationsInternal; - - public IEnumerable CompletedInstallations => _completedInstallationsInternal; - - /// - /// Occurs when [plugin uninstalled]. - /// - public event EventHandler> PluginUninstalled; - - /// - /// Occurs when [plugin updated]. - /// - public event EventHandler> PluginUpdated; - - /// - /// Occurs when [plugin updated]. - /// - public event EventHandler> PluginInstalled; - - /// - /// The _logger + /// The _logger. /// private readonly ILogger _logger; - private readonly IApplicationPaths _appPaths; private readonly IHttpClient _httpClient; private readonly IJsonSerializer _jsonSerializer; @@ -79,6 +45,18 @@ namespace Emby.Server.Implementations.Updates private readonly IZipClient _zipClient; + private readonly object _currentInstallationsLock = new object(); + + /// + /// The current installations. + /// + private readonly List<(InstallationInfo info, CancellationTokenSource token)> _currentInstallations; + + /// + /// The completed installations. + /// + private readonly ConcurrentBag _completedInstallationsInternal; + public InstallationManager( ILogger logger, IApplicationHost appHost, @@ -107,26 +85,32 @@ namespace Emby.Server.Implementations.Updates _zipClient = zipClient; } - /// - /// Gets all available packages. - /// - /// Task{List{PackageInfo}}. - public async Task> GetAvailablePackages( - CancellationToken cancellationToken, - bool withRegistration = true, - string packageType = null, - Version applicationVersion = null) - { - var packages = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false); - return FilterPackages(packages, packageType, applicationVersion); - } + /// + public event EventHandler PackageInstalling; - /// - /// Gets all available packages. - /// - /// The cancellation token. - /// Task{List{PackageInfo}}. - public async Task> GetAvailablePackagesWithoutRegistrationInfo(CancellationToken cancellationToken) + /// + public event EventHandler PackageInstallationCompleted; + + /// + public event EventHandler PackageInstallationFailed; + + /// + public event EventHandler PackageInstallationCancelled; + + /// + public event EventHandler> PluginUninstalled; + + /// + public event EventHandler> PluginUpdated; + + /// + public event EventHandler> PluginInstalled; + + /// + public IEnumerable CompletedInstallations => _completedInstallationsInternal; + + /// + public async Task> GetAvailablePackages(CancellationToken cancellationToken = default) { using (var response = await _httpClient.SendAsync( new HttpRequestOptions @@ -134,178 +118,95 @@ namespace Emby.Server.Implementations.Updates Url = "https://repo.jellyfin.org/releases/plugin/manifest.json", CancellationToken = cancellationToken, CacheMode = CacheMode.Unconditional, - CacheLength = GetCacheLength() + CacheLength = TimeSpan.FromMinutes(3) }, HttpMethod.Get).ConfigureAwait(false)) using (Stream stream = response.Content) { - return FilterPackages(await _jsonSerializer.DeserializeFromStreamAsync(stream).ConfigureAwait(false)); + return await _jsonSerializer.DeserializeFromStreamAsync>( + stream).ConfigureAwait(false); } } - private static TimeSpan GetCacheLength() + /// + public IEnumerable FilterPackages( + IEnumerable availablePackages, + string name = null, + Guid guid = default) { - return TimeSpan.FromMinutes(3); - } - - protected List FilterPackages(IEnumerable packages) - { - var list = new List(); - - foreach (var package in packages) + if (name != null) { - var versions = new List(); - foreach (var version in package.versions) - { - if (string.IsNullOrEmpty(version.sourceUrl)) - { - continue; - } - - versions.Add(version); - } - - package.versions = versions - .OrderByDescending(x => x.Version) - .ToArray(); - - if (package.versions.Length == 0) - { - continue; - } - - list.Add(package); + availablePackages = availablePackages.Where(x => x.name.Equals(name, StringComparison.OrdinalIgnoreCase)); } - // Remove packages with no versions - return list; - } - - protected List FilterPackages(IEnumerable packages, string packageType, Version applicationVersion) - { - var packagesList = FilterPackages(packages); - - var returnList = new List(); - - var filterOnPackageType = !string.IsNullOrEmpty(packageType); - - foreach (var p in packagesList) + if (guid != Guid.Empty) { - if (filterOnPackageType && !string.Equals(p.type, packageType, StringComparison.OrdinalIgnoreCase)) - { - continue; - } - - // If an app version was supplied, filter the versions for each package to only include supported versions - if (applicationVersion != null) - { - p.versions = p.versions.Where(v => IsPackageVersionUpToDate(v, applicationVersion)).ToArray(); - } - - if (p.versions.Length == 0) - { - continue; - } - - returnList.Add(p); + var strGuid = guid.ToString("N", CultureInfo.InvariantCulture); + availablePackages = availablePackages.Where(x => x.guid.Equals(strGuid, StringComparison.OrdinalIgnoreCase)); } - return returnList; + return availablePackages; } - /// - /// Determines whether [is package version up to date] [the specified package version info]. - /// - /// The package version info. - /// The current server version. - /// true if [is package version up to date] [the specified package version info]; otherwise, false. - private static bool IsPackageVersionUpToDate(PackageVersionInfo packageVersionInfo, Version currentServerVersion) + /// + public IEnumerable GetCompatibleVersions( + IEnumerable availableVersions, + Version minVersion = null, + PackageVersionClass classification = PackageVersionClass.Release) { - if (string.IsNullOrEmpty(packageVersionInfo.requiredVersionStr)) + var appVer = _applicationHost.ApplicationVersion; + availableVersions = availableVersions + .Where(x => x.classification == classification + && Version.Parse(x.requiredVersionStr) <= appVer); + + if (minVersion != null) { - return true; + availableVersions = availableVersions.Where(x => x.Version >= minVersion); } - return Version.TryParse(packageVersionInfo.requiredVersionStr, out var requiredVersion) && currentServerVersion >= requiredVersion; + return availableVersions.OrderByDescending(x => x.Version); } - /// - /// Gets the package. - /// - /// The name. - /// The assembly guid - /// The classification. - /// The version. - /// Task{PackageVersionInfo}. - public async Task GetPackage(string name, string guid, PackageVersionClass classification, Version version) + /// + public IEnumerable GetCompatibleVersions( + IEnumerable availablePackages, + string name = null, + Guid guid = default, + Version minVersion = null, + PackageVersionClass classification = PackageVersionClass.Release) { - var packages = await GetAvailablePackages(CancellationToken.None, false).ConfigureAwait(false); - - var package = packages.FirstOrDefault(p => string.Equals(p.guid, guid ?? "none", StringComparison.OrdinalIgnoreCase)) - ?? packages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase)); + var package = FilterPackages(availablePackages, name, guid).FirstOrDefault(); + // Package not found. if (package == null) { - return null; + return Enumerable.Empty(); } - return package.versions.FirstOrDefault(v => v.Version == version && v.classification == classification); + return GetCompatibleVersions( + package.versions, + minVersion, + classification); } - /// - /// Gets the latest compatible version. - /// - /// The name. - /// The assembly guid if this is a plug-in - /// The current server version. - /// The classification. - /// Task{PackageVersionInfo}. - public async Task GetLatestCompatibleVersion(string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release) + /// + public async IAsyncEnumerable GetAvailablePluginUpdates(CancellationToken cancellationToken = default) { - var packages = await GetAvailablePackages(CancellationToken.None, false).ConfigureAwait(false); - - return GetLatestCompatibleVersion(packages, name, guid, currentServerVersion, classification); - } - - /// - /// Gets the latest compatible version. - /// - /// The available packages. - /// The name. - /// The current server version. - /// The classification. - /// PackageVersionInfo. - public PackageVersionInfo GetLatestCompatibleVersion(IEnumerable availablePackages, string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release) - { - var package = availablePackages.FirstOrDefault(p => string.Equals(p.guid, guid ?? "none", StringComparison.OrdinalIgnoreCase)) - ?? availablePackages.FirstOrDefault(p => p.name.Equals(name, StringComparison.OrdinalIgnoreCase)); - - return package?.versions - .OrderByDescending(x => x.Version) - .FirstOrDefault(v => v.classification <= classification && IsPackageVersionUpToDate(v, currentServerVersion)); - } - - /// - /// Gets the available plugin updates. - /// - /// The current server version. - /// if set to true [with auto update enabled]. - /// The cancellation token. - /// Task{IEnumerable{PackageVersionInfo}}. - public async Task> GetAvailablePluginUpdates(Version applicationVersion, bool withAutoUpdateEnabled, CancellationToken cancellationToken) - { - var catalog = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false); + var catalog = await GetAvailablePackages(cancellationToken).ConfigureAwait(false); var systemUpdateLevel = _applicationHost.SystemUpdateLevel; // Figure out what needs to be installed - return _applicationHost.Plugins.Select(p => + foreach (var plugin in _applicationHost.Plugins) { - var latestPluginInfo = GetLatestCompatibleVersion(catalog, p.Name, p.Id.ToString(), applicationVersion, systemUpdateLevel); - - return latestPluginInfo != null && latestPluginInfo.Version > p.Version ? latestPluginInfo : null; - }).Where(i => i != null) - .Where(p => !string.IsNullOrEmpty(p.sourceUrl) && !CompletedInstallations.Any(i => string.Equals(i.AssemblyGuid, p.guid, StringComparison.OrdinalIgnoreCase))); + var compatibleversions = GetCompatibleVersions(catalog, plugin.Name, plugin.Id, plugin.Version, systemUpdateLevel); + var version = compatibleversions.FirstOrDefault(y => y.Version > plugin.Version); + if (version != null + && !CompletedInstallations.Any(x => string.Equals(x.AssemblyGuid, version.guid, StringComparison.OrdinalIgnoreCase))) + { + yield return version; + } + } } /// @@ -330,7 +231,7 @@ namespace Emby.Server.Implementations.Updates var tuple = (installationInfo, innerCancellationTokenSource); // Add it to the in-progress list - lock (_currentInstallations) + lock (_currentInstallationsLock) { _currentInstallations.Add(tuple); } @@ -349,7 +250,7 @@ namespace Emby.Server.Implementations.Updates { await InstallPackageInternal(package, linkedToken).ConfigureAwait(false); - lock (_currentInstallations) + lock (_currentInstallationsLock) { _currentInstallations.Remove(tuple); } @@ -360,7 +261,7 @@ namespace Emby.Server.Implementations.Updates } catch (OperationCanceledException) { - lock (_currentInstallations) + lock (_currentInstallationsLock) { _currentInstallations.Remove(tuple); } @@ -375,7 +276,7 @@ namespace Emby.Server.Implementations.Updates { _logger.LogError(ex, "Package installation failed"); - lock (_currentInstallations) + lock (_currentInstallationsLock) { _currentInstallations.Remove(tuple); } @@ -391,7 +292,7 @@ namespace Emby.Server.Implementations.Updates finally { // Dispose the progress object and remove the installation from the in-progress list - tuple.Item2.Dispose(); + tuple.innerCancellationTokenSource.Dispose(); } } @@ -439,7 +340,7 @@ namespace Emby.Server.Implementations.Updates // Always override the passed-in target (which is a file) and figure it out again string targetDir = Path.Combine(_appPaths.PluginsPath, package.name); -// CA5351: Do Not Use Broken Cryptographic Algorithms + // CA5351: Do Not Use Broken Cryptographic Algorithms #pragma warning disable CA5351 using (var res = await _httpClient.SendAsync( new HttpRequestOptions @@ -455,7 +356,7 @@ namespace Emby.Server.Implementations.Updates { cancellationToken.ThrowIfCancellationRequested(); - var hash = ToHexString(md5.ComputeHash(stream)); + var hash = Hex.Encode(md5.ComputeHash(stream)); if (!string.Equals(package.checksum, hash, StringComparison.OrdinalIgnoreCase)) { _logger.LogError( @@ -535,20 +436,21 @@ namespace Emby.Server.Implementations.Updates /// public bool CancelInstallation(Guid id) { - lock (_currentInstallations) + lock (_currentInstallationsLock) { - var install = _currentInstallations.Find(x => x.Item1.Id == id); + var install = _currentInstallations.Find(x => x.info.Id == id); if (install == default((InstallationInfo, CancellationTokenSource))) { return false; } - install.Item2.Cancel(); + install.token.Cancel(); _currentInstallations.Remove(install); return true; } } + /// public void Dispose() { Dispose(true); @@ -563,11 +465,11 @@ namespace Emby.Server.Implementations.Updates { if (dispose) { - lock (_currentInstallations) + lock (_currentInstallationsLock) { foreach (var tuple in _currentInstallations) { - tuple.Item2.Dispose(); + tuple.token.Dispose(); } _currentInstallations.Clear(); diff --git a/Emby.Server.Implementations/WebSockets/WebSocketManager.cs b/Emby.Server.Implementations/WebSockets/WebSocketManager.cs index 04c73ecea7..efd97e4ff1 100644 --- a/Emby.Server.Implementations/WebSockets/WebSocketManager.cs +++ b/Emby.Server.Implementations/WebSockets/WebSocketManager.cs @@ -39,12 +39,12 @@ namespace Emby.Server.Implementations.WebSockets do { var buffer = WebSocket.CreateServerBuffer(BufferSize); - result = await webSocket.ReceiveAsync(buffer, cancellationToken); + result = await webSocket.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false); message.AddRange(buffer.Array.Take(result.Count)); if (result.EndOfMessage) { - await ProcessMessage(message.ToArray(), taskCompletionSource); + await ProcessMessage(message.ToArray(), taskCompletionSource).ConfigureAwait(false); message.Clear(); } } while (!taskCompletionSource.Task.IsCompleted && @@ -53,8 +53,10 @@ namespace Emby.Server.Implementations.WebSockets if (webSocket.State == WebSocketState.Open) { - await webSocket.CloseAsync(result.CloseStatus ?? WebSocketCloseStatus.NormalClosure, - result.CloseStatusDescription, cancellationToken); + await webSocket.CloseAsync( + result.CloseStatus ?? WebSocketCloseStatus.NormalClosure, + result.CloseStatusDescription, + cancellationToken).ConfigureAwait(false); } } diff --git a/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs b/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs new file mode 100644 index 0000000000..26f7d9d2dd --- /dev/null +++ b/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs @@ -0,0 +1,68 @@ +using System.Security.Claims; +using System.Text.Encodings.Web; +using System.Threading.Tasks; +using Jellyfin.Api.Constants; +using MediaBrowser.Controller.Net; +using Microsoft.AspNetCore.Authentication; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace Jellyfin.Api.Auth +{ + /// + /// Custom authentication handler wrapping the legacy authentication. + /// + public class CustomAuthenticationHandler : AuthenticationHandler + { + private readonly IAuthService _authService; + + /// + /// Initializes a new instance of the class. + /// + /// The jellyfin authentication service. + /// Options monitor. + /// The logger. + /// The url encoder. + /// The system clock. + public CustomAuthenticationHandler( + IAuthService authService, + IOptionsMonitor options, + ILoggerFactory logger, + UrlEncoder encoder, + ISystemClock clock) : base(options, logger, encoder, clock) + { + _authService = authService; + } + + /// + protected override Task HandleAuthenticateAsync() + { + var authenticatedAttribute = new AuthenticatedAttribute(); + try + { + var user = _authService.Authenticate(Request, authenticatedAttribute); + if (user == null) + { + return Task.FromResult(AuthenticateResult.Fail("Invalid user")); + } + + var claims = new[] + { + new Claim(ClaimTypes.Name, user.Name), + new Claim( + ClaimTypes.Role, + value: user.Policy.IsAdministrator ? UserRoles.Administrator : UserRoles.User) + }; + var identity = new ClaimsIdentity(claims, Scheme.Name); + var principal = new ClaimsPrincipal(identity); + var ticket = new AuthenticationTicket(principal, Scheme.Name); + + return Task.FromResult(AuthenticateResult.Success(ticket)); + } + catch (SecurityException ex) + { + return Task.FromResult(AuthenticateResult.Fail(ex)); + } + } + } +} diff --git a/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs b/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs new file mode 100644 index 0000000000..34aa5d12c8 --- /dev/null +++ b/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs @@ -0,0 +1,43 @@ +using System.Threading.Tasks; +using Jellyfin.Api.Constants; +using MediaBrowser.Common.Configuration; +using Microsoft.AspNetCore.Authorization; + +namespace Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy +{ + /// + /// Authorization handler for requiring first time setup or elevated privileges. + /// + public class FirstTimeSetupOrElevatedHandler : AuthorizationHandler + { + private readonly IConfigurationManager _configurationManager; + + /// + /// Initializes a new instance of the class. + /// + /// The jellyfin configuration manager. + public FirstTimeSetupOrElevatedHandler(IConfigurationManager configurationManager) + { + _configurationManager = configurationManager; + } + + /// + protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, FirstTimeSetupOrElevatedRequirement firstTimeSetupOrElevatedRequirement) + { + if (!_configurationManager.CommonConfiguration.IsStartupWizardCompleted) + { + context.Succeed(firstTimeSetupOrElevatedRequirement); + } + else if (context.User.IsInRole(UserRoles.Administrator)) + { + context.Succeed(firstTimeSetupOrElevatedRequirement); + } + else + { + context.Fail(); + } + + return Task.CompletedTask; + } + } +} diff --git a/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedRequirement.cs b/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedRequirement.cs new file mode 100644 index 0000000000..51ba637b60 --- /dev/null +++ b/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedRequirement.cs @@ -0,0 +1,11 @@ +using Microsoft.AspNetCore.Authorization; + +namespace Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy +{ + /// + /// The authorization requirement, requiring incomplete first time setup or elevated privileges, for the authorization handler. + /// + public class FirstTimeSetupOrElevatedRequirement : IAuthorizationRequirement + { + } +} diff --git a/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs b/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs new file mode 100644 index 0000000000..2d3bb1aa48 --- /dev/null +++ b/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs @@ -0,0 +1,23 @@ +using System.Threading.Tasks; +using Jellyfin.Api.Constants; +using Microsoft.AspNetCore.Authorization; + +namespace Jellyfin.Api.Auth.RequiresElevationPolicy +{ + /// + /// Authorization handler for requiring elevated privileges. + /// + public class RequiresElevationHandler : AuthorizationHandler + { + /// + protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RequiresElevationRequirement requirement) + { + if (context.User.IsInRole(UserRoles.Administrator)) + { + context.Succeed(requirement); + } + + return Task.CompletedTask; + } + } +} diff --git a/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationRequirement.cs b/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationRequirement.cs new file mode 100644 index 0000000000..cfff1cc0c5 --- /dev/null +++ b/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationRequirement.cs @@ -0,0 +1,11 @@ +using Microsoft.AspNetCore.Authorization; + +namespace Jellyfin.Api.Auth.RequiresElevationPolicy +{ + /// + /// The authorization requirement for requiring elevated privileges in the authorization handler. + /// + public class RequiresElevationRequirement : IAuthorizationRequirement + { + } +} diff --git a/Jellyfin.Api/BaseJellyfinApiController.cs b/Jellyfin.Api/BaseJellyfinApiController.cs new file mode 100644 index 0000000000..1f4508e6cb --- /dev/null +++ b/Jellyfin.Api/BaseJellyfinApiController.cs @@ -0,0 +1,13 @@ +using Microsoft.AspNetCore.Mvc; + +namespace Jellyfin.Api +{ + /// + /// Base api controller for the API setting a default route. + /// + [ApiController] + [Route("[controller]")] + public class BaseJellyfinApiController : ControllerBase + { + } +} diff --git a/Jellyfin.Api/Constants/AuthenticationSchemes.cs b/Jellyfin.Api/Constants/AuthenticationSchemes.cs new file mode 100644 index 0000000000..bac3379e71 --- /dev/null +++ b/Jellyfin.Api/Constants/AuthenticationSchemes.cs @@ -0,0 +1,13 @@ +namespace Jellyfin.Api.Constants +{ + /// + /// Authentication schemes for user authentication in the API. + /// + public static class AuthenticationSchemes + { + /// + /// Scheme name for the custom legacy authentication. + /// + public const string CustomAuthentication = "CustomAuthentication"; + } +} diff --git a/Jellyfin.Api/Constants/Policies.cs b/Jellyfin.Api/Constants/Policies.cs new file mode 100644 index 0000000000..e2b383f75d --- /dev/null +++ b/Jellyfin.Api/Constants/Policies.cs @@ -0,0 +1,18 @@ +namespace Jellyfin.Api.Constants +{ + /// + /// Policies for the API authorization. + /// + public static class Policies + { + /// + /// Policy name for requiring first time setup or elevated privileges. + /// + public const string FirstTimeSetupOrElevated = "FirstTimeOrElevated"; + + /// + /// Policy name for requiring elevated privileges. + /// + public const string RequiresElevation = "RequiresElevation"; + } +} diff --git a/Jellyfin.Api/Constants/UserRoles.cs b/Jellyfin.Api/Constants/UserRoles.cs new file mode 100644 index 0000000000..d9a536e7d7 --- /dev/null +++ b/Jellyfin.Api/Constants/UserRoles.cs @@ -0,0 +1,23 @@ +namespace Jellyfin.Api.Constants +{ + /// + /// Constants for user roles used in the authentication and authorization for the API. + /// + public static class UserRoles + { + /// + /// Guest user. + /// + public const string Guest = "Guest"; + + /// + /// Regular user with no special privileges. + /// + public const string User = "User"; + + /// + /// Administrator user with elevated privileges. + /// + public const string Administrator = "Administrator"; + } +} diff --git a/Jellyfin.Api/Controllers/StartupController.cs b/Jellyfin.Api/Controllers/StartupController.cs new file mode 100644 index 0000000000..1014c8c56b --- /dev/null +++ b/Jellyfin.Api/Controllers/StartupController.cs @@ -0,0 +1,127 @@ +using System.Linq; +using System.Threading.Tasks; +using Jellyfin.Api.Constants; +using Jellyfin.Api.Models.StartupDtos; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Library; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Jellyfin.Api.Controllers +{ + /// + /// The startup wizard controller. + /// + [Authorize(Policy = Policies.FirstTimeSetupOrElevated)] + public class StartupController : BaseJellyfinApiController + { + private readonly IServerConfigurationManager _config; + private readonly IUserManager _userManager; + + /// + /// Initializes a new instance of the class. + /// + /// The server configuration manager. + /// The user manager. + public StartupController(IServerConfigurationManager config, IUserManager userManager) + { + _config = config; + _userManager = userManager; + } + + /// + /// Api endpoint for completing the startup wizard. + /// + [HttpPost("Complete")] + public void CompleteWizard() + { + _config.Configuration.IsStartupWizardCompleted = true; + _config.SetOptimalValues(); + _config.SaveConfiguration(); + } + + /// + /// Endpoint for getting the initial startup wizard configuration. + /// + /// The initial startup wizard configuration. + [HttpGet("Configuration")] + public StartupConfigurationDto GetStartupConfiguration() + { + var result = new StartupConfigurationDto + { + UICulture = _config.Configuration.UICulture, + MetadataCountryCode = _config.Configuration.MetadataCountryCode, + PreferredMetadataLanguage = _config.Configuration.PreferredMetadataLanguage + }; + + return result; + } + + /// + /// Endpoint for updating the initial startup wizard configuration. + /// + /// The UI language culture. + /// The metadata country code. + /// The preferred language for metadata. + [HttpPost("Configuration")] + public void UpdateInitialConfiguration( + [FromForm] string uiCulture, + [FromForm] string metadataCountryCode, + [FromForm] string preferredMetadataLanguage) + { + _config.Configuration.UICulture = uiCulture; + _config.Configuration.MetadataCountryCode = metadataCountryCode; + _config.Configuration.PreferredMetadataLanguage = preferredMetadataLanguage; + _config.SaveConfiguration(); + } + + /// + /// Endpoint for (dis)allowing remote access and UPnP. + /// + /// Enable remote access. + /// Enable UPnP. + [HttpPost("RemoteAccess")] + public void SetRemoteAccess([FromForm] bool enableRemoteAccess, [FromForm] bool enableAutomaticPortMapping) + { + _config.Configuration.EnableRemoteAccess = enableRemoteAccess; + _config.Configuration.EnableUPnP = enableAutomaticPortMapping; + _config.SaveConfiguration(); + } + + /// + /// Endpoint for returning the first user. + /// + /// The first user. + [HttpGet("User")] + public StartupUserDto GetFirstUser() + { + var user = _userManager.Users.First(); + + return new StartupUserDto + { + Name = user.Name, + Password = user.Password + }; + } + + /// + /// Endpoint for updating the user name and password. + /// + /// The DTO containing username and password. + /// The async task. + [HttpPost("User")] + public async Task UpdateUser([FromForm] StartupUserDto startupUserDto) + { + var user = _userManager.Users.First(); + + user.Name = startupUserDto.Name; + + _userManager.UpdateUser(user); + + if (!string.IsNullOrEmpty(startupUserDto.Password)) + { + await _userManager.ChangePassword(user, startupUserDto.Password).ConfigureAwait(false); + } + } + } +} diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj new file mode 100644 index 0000000000..a2818b45da --- /dev/null +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -0,0 +1,32 @@ + + + + netstandard2.1 + true + true + + + + + + + + + + + + + + + + + + + + + + + ../jellyfin.ruleset + + + diff --git a/Jellyfin.Api/Models/StartupDtos/StartupConfigurationDto.cs b/Jellyfin.Api/Models/StartupDtos/StartupConfigurationDto.cs new file mode 100644 index 0000000000..d048dad0a1 --- /dev/null +++ b/Jellyfin.Api/Models/StartupDtos/StartupConfigurationDto.cs @@ -0,0 +1,23 @@ +namespace Jellyfin.Api.Models.StartupDtos +{ + /// + /// The startup configuration DTO. + /// + public class StartupConfigurationDto + { + /// + /// Gets or sets UI language culture. + /// + public string UICulture { get; set; } + + /// + /// Gets or sets the metadata country code. + /// + public string MetadataCountryCode { get; set; } + + /// + /// Gets or sets the preferred language for the metadata. + /// + public string PreferredMetadataLanguage { get; set; } + } +} diff --git a/Jellyfin.Api/Models/StartupDtos/StartupUserDto.cs b/Jellyfin.Api/Models/StartupDtos/StartupUserDto.cs new file mode 100644 index 0000000000..3a9348037a --- /dev/null +++ b/Jellyfin.Api/Models/StartupDtos/StartupUserDto.cs @@ -0,0 +1,18 @@ +namespace Jellyfin.Api.Models.StartupDtos +{ + /// + /// The startup user DTO. + /// + public class StartupUserDto + { + /// + /// Gets or sets the username. + /// + public string Name { get; set; } + + /// + /// Gets or sets the user's password. + /// + public string Password { get; set; } + } +} diff --git a/Jellyfin.Api/MvcRoutePrefix.cs b/Jellyfin.Api/MvcRoutePrefix.cs new file mode 100644 index 0000000000..e009730947 --- /dev/null +++ b/Jellyfin.Api/MvcRoutePrefix.cs @@ -0,0 +1,56 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ApplicationModels; + +namespace Jellyfin.Api +{ + /// + /// Route prefixing for ASP.NET MVC. + /// + public static class MvcRoutePrefix + { + /// + /// Adds route prefixes to the MVC conventions. + /// + /// The MVC options. + /// The list of prefixes. + public static void UseGeneralRoutePrefix(this MvcOptions opts, params string[] prefixes) + { + opts.Conventions.Insert(0, new RoutePrefixConvention(prefixes)); + } + + private class RoutePrefixConvention : IApplicationModelConvention + { + private readonly AttributeRouteModel[] _routePrefixes; + + public RoutePrefixConvention(IEnumerable prefixes) + { + _routePrefixes = prefixes.Select(p => new AttributeRouteModel(new RouteAttribute(p))).ToArray(); + } + + public void Apply(ApplicationModel application) + { + foreach (var controller in application.Controllers) + { + if (controller.Selectors == null) + { + continue; + } + + var newSelectors = new List(); + foreach (var selector in controller.Selectors) + { + newSelectors.AddRange(_routePrefixes.Select(routePrefix => new SelectorModel(selector) + { + AttributeRouteModel = AttributeRouteModel.CombineAttributeRouteModel(routePrefix, selector.AttributeRouteModel) + })); + } + + controller.Selectors.Clear(); + newSelectors.ForEach(selector => controller.Selectors.Add(selector)); + } + } + } + } +} diff --git a/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj b/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj index 396bdd4b71..988ac364ae 100644 --- a/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj +++ b/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj @@ -1,7 +1,7 @@ - netstandard2.0 + netstandard2.1 false true diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs new file mode 100644 index 0000000000..db06eb4552 --- /dev/null +++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs @@ -0,0 +1,27 @@ +using Microsoft.AspNetCore.Builder; + +namespace Jellyfin.Server.Extensions +{ + /// + /// Extensions for adding API specific functionality to the application pipeline. + /// + public static class ApiApplicationBuilderExtensions + { + /// + /// Adds swagger and swagger UI to the application pipeline. + /// + /// The application builder. + /// The updated application builder. + public static IApplicationBuilder UseJellyfinApiSwagger(this IApplicationBuilder applicationBuilder) + { + applicationBuilder.UseSwagger(); + + // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), + // specifying the Swagger JSON endpoint. + return applicationBuilder.UseSwaggerUI(c => + { + c.SwaggerEndpoint("/swagger/v1/swagger.json", "Jellyfin API V1"); + }); + } + } +} diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs new file mode 100644 index 0000000000..dd4f9cd238 --- /dev/null +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -0,0 +1,90 @@ +using Jellyfin.Api; +using Jellyfin.Api.Auth; +using Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy; +using Jellyfin.Api.Auth.RequiresElevationPolicy; +using Jellyfin.Api.Constants; +using Jellyfin.Api.Controllers; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authorization; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.OpenApi.Models; + +namespace Jellyfin.Server.Extensions +{ + /// + /// API specific extensions for the service collection. + /// + public static class ApiServiceCollectionExtensions + { + /// + /// Adds jellyfin API authorization policies to the DI container. + /// + /// The service collection. + /// The updated service collection. + public static IServiceCollection AddJellyfinApiAuthorization(this IServiceCollection serviceCollection) + { + serviceCollection.AddSingleton(); + serviceCollection.AddSingleton(); + return serviceCollection.AddAuthorizationCore(options => + { + options.AddPolicy( + Policies.RequiresElevation, + policy => + { + policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication); + policy.AddRequirements(new RequiresElevationRequirement()); + }); + options.AddPolicy( + Policies.FirstTimeSetupOrElevated, + policy => + { + policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication); + policy.AddRequirements(new FirstTimeSetupOrElevatedRequirement()); + }); + }); + } + + /// + /// Adds custom legacy authentication to the service collection. + /// + /// The service collection. + /// The updated service collection. + public static AuthenticationBuilder AddCustomAuthentication(this IServiceCollection serviceCollection) + { + return serviceCollection.AddAuthentication(AuthenticationSchemes.CustomAuthentication) + .AddScheme(AuthenticationSchemes.CustomAuthentication, null); + } + + /// + /// Extension method for adding the jellyfin API to the service collection. + /// + /// The service collection. + /// The base url for the API. + /// The MVC builder. + public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, string baseUrl) + { + return serviceCollection.AddMvc(opts => + { + opts.UseGeneralRoutePrefix(baseUrl); + }) + + // Clear app parts to avoid other assemblies being picked up + .ConfigureApplicationPartManager(a => a.ApplicationParts.Clear()) + .AddApplicationPart(typeof(StartupController).Assembly) + .AddControllersAsServices(); + } + + /// + /// Adds Swagger to the service collection. + /// + /// The service collection. + /// The updated service collection. + public static IServiceCollection AddJellyfinApiSwagger(this IServiceCollection serviceCollection) + { + return serviceCollection.AddSwaggerGen(c => + { + c.SwaggerDoc("v1", new OpenApiInfo { Title = "Jellyfin API", Version = "v1" }); + }); + } + } +} diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index efdb75f980..110028176c 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -9,9 +9,8 @@ - - latest true + enable @@ -22,11 +21,16 @@ + + + + - - + + + @@ -35,15 +39,15 @@ - - - + + + - - - + + + diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 3ab19769a1..5ac005b40b 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -1,5 +1,6 @@ using System; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Net; @@ -18,9 +19,12 @@ using Jellyfin.Drawing.Skia; using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Drawing; using MediaBrowser.Model.Globalization; +using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using Serilog; using Serilog.Extensions.Logging; using SQLitePCL; @@ -35,7 +39,7 @@ namespace Jellyfin.Server { private static readonly CancellationTokenSource _tokenSource = new CancellationTokenSource(); private static readonly ILoggerFactory _loggerFactory = new SerilogLoggerFactory(); - private static ILogger _logger; + private static ILogger _logger = NullLogger.Instance; private static bool _restartOnShutdown; /// @@ -86,6 +90,12 @@ namespace Jellyfin.Server { var stopWatch = new Stopwatch(); stopWatch.Start(); + + // Log all uncaught exceptions to std error + static void UnhandledExceptionToConsole(object sender, UnhandledExceptionEventArgs e) => + Console.Error.WriteLine("Unhandled Exception\n" + e.ExceptionObject.ToString()); + AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionToConsole; + ServerApplicationPaths appPaths = CreateApplicationPaths(options); // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager @@ -97,6 +107,8 @@ namespace Jellyfin.Server _logger = _loggerFactory.CreateLogger("Main"); + // Log uncaught exceptions to the logging instead of std error + AppDomain.CurrentDomain.UnhandledException -= UnhandledExceptionToConsole; AppDomain.CurrentDomain.UnhandledException += (sender, e) => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception"); @@ -129,7 +141,7 @@ namespace Jellyfin.Server _logger.LogInformation( "Jellyfin version: {Version}", - Assembly.GetEntryAssembly().GetName().Version.ToString(3)); + Assembly.GetEntryAssembly()!.GetName().Version!.ToString(3)); ApplicationHost.LogEnvironmentInfo(_logger, appPaths); @@ -141,13 +153,6 @@ namespace Jellyfin.Server // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c ServicePointManager.Expect100Continue = false; -// CA5359: Do Not Disable Certificate Validation -#pragma warning disable CA5359 - - // Allow all https requests - ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; }); -#pragma warning restore CA5359 - Batteries_V2.Init(); if (raw.sqlite3_enable_shared_cache(1) != raw.SQLITE_OK) { @@ -164,7 +169,24 @@ namespace Jellyfin.Server appConfig); try { - await appHost.InitAsync(new ServiceCollection()).ConfigureAwait(false); + ServiceCollection serviceCollection = new ServiceCollection(); + await appHost.InitAsync(serviceCollection).ConfigureAwait(false); + + var host = CreateWebHostBuilder(appHost, serviceCollection).Build(); + + // A bit hacky to re-use service provider since ASP.NET doesn't allow a custom service collection. + appHost.ServiceProvider = host.Services; + appHost.FindParts(); + + try + { + await host.StartAsync().ConfigureAwait(false); + } + catch + { + _logger.LogError("Kestrel failed to start! This is most likely due to an invalid address or port bind - correct your bind configuration in system.xml and try again."); + throw; + } appHost.ImageProcessor.ImageEncoder = GetImageEncoder(appPaths, appHost.LocalizationManager); @@ -196,6 +218,55 @@ namespace Jellyfin.Server } } + private static IWebHostBuilder CreateWebHostBuilder(ApplicationHost appHost, IServiceCollection serviceCollection) + { + return new WebHostBuilder() + .UseKestrel(options => + { + var addresses = appHost.ServerConfigurationManager + .Configuration + .LocalNetworkAddresses + .Select(appHost.NormalizeConfiguredLocalAddress) + .Where(i => i != null) + .ToList(); + if (addresses.Any()) + { + foreach (var address in addresses) + { + _logger.LogInformation("Kestrel listening on {ipaddr}", address); + options.Listen(address, appHost.HttpPort); + + if (appHost.EnableHttps && appHost.Certificate != null) + { + options.Listen( + address, + appHost.HttpsPort, + listenOptions => listenOptions.UseHttps(appHost.Certificate)); + } + } + } + else + { + _logger.LogInformation("Kestrel listening on all interfaces"); + options.ListenAnyIP(appHost.HttpPort); + + if (appHost.EnableHttps && appHost.Certificate != null) + { + options.ListenAnyIP( + appHost.HttpsPort, + listenOptions => listenOptions.UseHttps(appHost.Certificate)); + } + } + }) + .UseContentRoot(appHost.ContentRoot) + .ConfigureServices(services => + { + // Merge the external ServiceCollection into ASP.NET DI + services.TryAdd(serviceCollection); + }) + .UseStartup(); + } + /// /// Create the data, config and log paths from the variety of inputs(command line args, /// environment variables) or decide on what default to use. For Windows it's %AppPath% @@ -361,22 +432,31 @@ namespace Jellyfin.Server private static async Task CreateConfiguration(IApplicationPaths appPaths) { + const string ResourcePath = "Jellyfin.Server.Resources.Configuration.logging.json"; string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, "logging.json"); if (!File.Exists(configPath)) { // For some reason the csproj name is used instead of the assembly name - using (Stream rscstr = typeof(Program).Assembly - .GetManifestResourceStream("Jellyfin.Server.Resources.Configuration.logging.json")) - using (Stream fstr = File.Open(configPath, FileMode.CreateNew)) + using (Stream? resource = typeof(Program).Assembly.GetManifestResourceStream(ResourcePath)) { - await rscstr.CopyToAsync(fstr).ConfigureAwait(false); + if (resource == null) + { + throw new InvalidOperationException( + string.Format( + CultureInfo.InvariantCulture, + "Invalid resource path: '{0}'", + ResourcePath)); + } + + using Stream dst = File.Open(configPath, FileMode.CreateNew); + await resource.CopyToAsync(dst).ConfigureAwait(false); } } return new ConfigurationBuilder() .SetBasePath(appPaths.ConfigurationDirectoryPath) - .AddJsonFile("logging.json") + .AddJsonFile("logging.json", false, true) .AddEnvironmentVariables("JELLYFIN_") .AddInMemoryCollection(ConfigurationOptions.Configuration) .Build(); @@ -433,7 +513,7 @@ namespace Jellyfin.Server { _logger.LogInformation("Starting new instance"); - string module = options.RestartPath; + var module = options.RestartPath; if (string.IsNullOrWhiteSpace(module)) { @@ -441,7 +521,6 @@ namespace Jellyfin.Server } string commandLineArgsString; - if (options.RestartArgs != null) { commandLineArgsString = options.RestartArgs ?? string.Empty; diff --git a/Jellyfin.Server/Resources/Configuration/logging.json b/Jellyfin.Server/Resources/Configuration/logging.json index d169912774..e85ef05afd 100644 --- a/Jellyfin.Server/Resources/Configuration/logging.json +++ b/Jellyfin.Server/Resources/Configuration/logging.json @@ -17,6 +17,9 @@ "Args": { "path": "%JELLYFIN_LOG_DIR%//log_.log", "rollingInterval": "Day", + "retainedFileCountLimit": 3, + "rollOnFileSizeLimit": true, + "fileSizeLimitBytes": 100000000, "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}" } } diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs new file mode 100644 index 0000000000..3ee5fb8b50 --- /dev/null +++ b/Jellyfin.Server/Startup.cs @@ -0,0 +1,81 @@ +using Jellyfin.Server.Extensions; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Configuration; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Jellyfin.Server +{ + /// + /// Startup configuration for the Kestrel webhost. + /// + public class Startup + { + private readonly IServerConfigurationManager _serverConfigurationManager; + + /// + /// Initializes a new instance of the class. + /// + /// The server configuration manager. + public Startup(IServerConfigurationManager serverConfigurationManager) + { + _serverConfigurationManager = serverConfigurationManager; + } + + /// + /// Configures the service collection for the webhost. + /// + /// The service collection. + public void ConfigureServices(IServiceCollection services) + { + services.AddResponseCompression(); + services.AddHttpContextAccessor(); + services.AddJellyfinApi(_serverConfigurationManager.Configuration.BaseUrl.TrimStart('/')); + + services.AddJellyfinApiSwagger(); + + // configure custom legacy authentication + services.AddCustomAuthentication(); + + services.AddJellyfinApiAuthorization(); + } + + /// + /// Configures the app builder for the webhost. + /// + /// The application builder. + /// The webhost environment. + /// The server application host. + public void Configure( + IApplicationBuilder app, + IWebHostEnvironment env, + IServerApplicationHost serverApplicationHost) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + app.UseWebSockets(); + + app.UseResponseCompression(); + + // TODO app.UseMiddleware(); + app.Use(serverApplicationHost.ExecuteWebsocketHandlerAsync); + + // TODO use when old API is removed: app.UseAuthentication(); + app.UseJellyfinApiSwagger(); + app.UseRouting(); + app.UseAuthorization(); + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + + app.Use(serverApplicationHost.ExecuteHttpHandlerAsync); + } + } +} diff --git a/Jellyfin.Server/StartupOptions.cs b/Jellyfin.Server/StartupOptions.cs index bb0adaf630..1fb1c5af8e 100644 --- a/Jellyfin.Server/StartupOptions.cs +++ b/Jellyfin.Server/StartupOptions.cs @@ -13,39 +13,39 @@ namespace Jellyfin.Server /// /// The path to the data directory. [Option('d', "datadir", Required = false, HelpText = "Path to use for the data folder (database files, etc.).")] - public string DataDir { get; set; } + public string? DataDir { get; set; } /// /// Gets or sets the path to the web directory. /// /// The path to the web directory. [Option('w', "webdir", Required = false, HelpText = "Path to the Jellyfin web UI resources.")] - public string WebDir { get; set; } + public string? WebDir { get; set; } /// /// Gets or sets the path to the cache directory. /// /// The path to the cache directory. [Option('C', "cachedir", Required = false, HelpText = "Path to use for caching.")] - public string CacheDir { get; set; } + public string? CacheDir { get; set; } /// /// Gets or sets the path to the config directory. /// /// The path to the config directory. [Option('c', "configdir", Required = false, HelpText = "Path to use for configuration data (user settings and pictures).")] - public string ConfigDir { get; set; } + public string? ConfigDir { get; set; } /// /// Gets or sets the path to the log directory. /// /// The path to the log directory. [Option('l', "logdir", Required = false, HelpText = "Path to use for writing log files.")] - public string LogDir { get; set; } + public string? LogDir { get; set; } /// [Option("ffmpeg", Required = false, HelpText = "Path to external FFmpeg executable to use in place of default found in PATH.")] - public string FFmpegPath { get; set; } + public string? FFmpegPath { get; set; } /// [Option("service", Required = false, HelpText = "Run as headless service.")] @@ -57,14 +57,14 @@ namespace Jellyfin.Server /// [Option("package-name", Required = false, HelpText = "Used when packaging Jellyfin (example, synology).")] - public string PackageName { get; set; } + public string? PackageName { get; set; } /// [Option("restartpath", Required = false, HelpText = "Path to restart script.")] - public string RestartPath { get; set; } + public string? RestartPath { get; set; } /// [Option("restartargs", Required = false, HelpText = "Arguments for restart script.")] - public string RestartArgs { get; set; } + public string? RestartArgs { get; set; } } } diff --git a/MediaBrowser.Api/ApiEntryPoint.cs b/MediaBrowser.Api/ApiEntryPoint.cs index 7dca7e8147..0542807af7 100644 --- a/MediaBrowser.Api/ApiEntryPoint.cs +++ b/MediaBrowser.Api/ApiEntryPoint.cs @@ -13,7 +13,6 @@ using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.Dto; using MediaBrowser.Model.IO; @@ -40,14 +39,13 @@ namespace MediaBrowser.Api internal IHttpResultFactory ResultFactory { get; private set; } /// - /// The application paths + /// Gets the configuration manager. /// - private readonly IServerConfigurationManager _config; + internal IServerConfigurationManager ConfigurationManager { get; } private readonly ISessionManager _sessionManager; private readonly IFileSystem _fileSystem; private readonly IMediaSourceManager _mediaSourceManager; - public readonly IProcessFactory ProcessFactory; /// /// The active transcoding jobs @@ -73,15 +71,13 @@ namespace MediaBrowser.Api IServerConfigurationManager config, IFileSystem fileSystem, IMediaSourceManager mediaSourceManager, - IProcessFactory processFactory, IHttpResultFactory resultFactory) { Logger = logger; _sessionManager = sessionManager; - _config = config; + ConfigurationManager = config; _fileSystem = fileSystem; _mediaSourceManager = mediaSourceManager; - ProcessFactory = processFactory; ResultFactory = resultFactory; _sessionManager.PlaybackProgress += _sessionManager_PlaybackProgress; @@ -160,17 +156,12 @@ namespace MediaBrowser.Api return Task.CompletedTask; } - public EncodingOptions GetEncodingOptions() - { - return ConfigurationManagerExtensions.GetConfiguration(_config, "encoding"); - } - /// /// Deletes the encoded media cache. /// private void DeleteEncodedMediaCache() { - var path = _config.ApplicationPaths.GetTranscodingTempPath(); + var path = ConfigurationManager.GetTranscodePath(); if (!Directory.Exists(path)) { diff --git a/MediaBrowser.Api/BaseApiService.cs b/MediaBrowser.Api/BaseApiService.cs index 49f8c6ace0..5f1f6c5b16 100644 --- a/MediaBrowser.Api/BaseApiService.cs +++ b/MediaBrowser.Api/BaseApiService.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Linq; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -298,11 +297,26 @@ namespace MediaBrowser.Api var pathInfo = Parse(Request.PathInfo); var first = pathInfo[0]; + string baseUrl = ApiEntryPoint.Instance.ConfigurationManager.Configuration.BaseUrl; + // backwards compatibility - if (string.Equals(first, "mediabrowser", StringComparison.OrdinalIgnoreCase) || - string.Equals(first, "emby", StringComparison.OrdinalIgnoreCase)) + if (baseUrl.Length == 0) + { + if (string.Equals(first, "mediabrowser", StringComparison.OrdinalIgnoreCase) + || string.Equals(first, "emby", StringComparison.OrdinalIgnoreCase)) + { + index++; + } + } + else if (string.Equals(first, baseUrl.Remove(0, 1))) { index++; + var second = pathInfo[1]; + if (string.Equals(second, "mediabrowser", StringComparison.OrdinalIgnoreCase) + || string.Equals(second, "emby", StringComparison.OrdinalIgnoreCase)) + { + index++; + } } return pathInfo[index]; diff --git a/MediaBrowser.Api/EnvironmentService.cs b/MediaBrowser.Api/EnvironmentService.cs index f4813e7132..a63ef9f053 100644 --- a/MediaBrowser.Api/EnvironmentService.cs +++ b/MediaBrowser.Api/EnvironmentService.cs @@ -52,6 +52,7 @@ namespace MediaBrowser.Api public bool? IsFile { get; set; } } + [Obsolete] [Route("/Environment/NetworkShares", "GET", Summary = "Gets shares from a network device")] public class GetNetworkShares : IReturn> { @@ -192,22 +193,18 @@ namespace MediaBrowser.Api var networkPrefix = UncSeparatorString + UncSeparatorString; - if (path.StartsWith(networkPrefix, StringComparison.OrdinalIgnoreCase) && path.LastIndexOf(UncSeparator) == 1) + if (path.StartsWith(networkPrefix, StringComparison.OrdinalIgnoreCase) + && path.LastIndexOf(UncSeparator) == 1) { - return ToOptimizedResult(GetNetworkShares(path).OrderBy(i => i.Path).ToList()); + return ToOptimizedResult(Array.Empty()); } return ToOptimizedResult(GetFileSystemEntries(request).ToList()); } + [Obsolete] public object Get(GetNetworkShares request) - { - var path = request.Path; - - var shares = GetNetworkShares(path).OrderBy(i => i.Path).ToList(); - - return ToOptimizedResult(shares); - } + => ToOptimizedResult(Array.Empty()); /// /// Gets the specified request. @@ -241,26 +238,7 @@ namespace MediaBrowser.Api /// The request. /// System.Object. public object Get(GetNetworkDevices request) - { - var result = _networkManager.GetNetworkDevices().ToList(); - - return ToOptimizedResult(result); - } - - /// - /// Gets the network shares. - /// - /// The path. - /// IEnumerable{FileSystemEntryInfo}. - private IEnumerable GetNetworkShares(string path) - { - return _networkManager.GetNetworkShares(path).Where(s => s.ShareType == NetworkShareType.Disk).Select(c => new FileSystemEntryInfo - { - Name = c.Name, - Path = Path.Combine(path, c.Name), - Type = FileSystemEntryType.NetworkShare - }); - } + => ToOptimizedResult(Array.Empty()); /// /// Gets the file system entries. diff --git a/MediaBrowser.Api/IHasItemFields.cs b/MediaBrowser.Api/IHasItemFields.cs index 8598ea262f..85b4a7e2d2 100644 --- a/MediaBrowser.Api/IHasItemFields.cs +++ b/MediaBrowser.Api/IHasItemFields.cs @@ -32,7 +32,7 @@ namespace MediaBrowser.Api if (string.IsNullOrEmpty(val)) { - return new ItemFields[] { }; + return Array.Empty(); } return val.Split(',').Select(v => @@ -41,6 +41,7 @@ namespace MediaBrowser.Api { return (ItemFields?)value; } + return null; }).Where(i => i.HasValue).Select(i => i.Value).ToArray(); diff --git a/MediaBrowser.Api/ItemLookupService.cs b/MediaBrowser.Api/ItemLookupService.cs index f3ea7907f6..084b20bc15 100644 --- a/MediaBrowser.Api/ItemLookupService.cs +++ b/MediaBrowser.Api/ItemLookupService.cs @@ -227,15 +227,17 @@ namespace MediaBrowser.Api //item.ProductionYear = request.ProductionYear; //item.Name = request.Name; - return _providerManager.RefreshFullItem(item, new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem)) - { - MetadataRefreshMode = MetadataRefreshMode.FullRefresh, - ImageRefreshMode = MetadataRefreshMode.FullRefresh, - ReplaceAllMetadata = true, - ReplaceAllImages = request.ReplaceAllImages, - SearchResult = request - - }, CancellationToken.None); + return _providerManager.RefreshFullItem( + item, + new MetadataRefreshOptions(new DirectoryService(_fileSystem)) + { + MetadataRefreshMode = MetadataRefreshMode.FullRefresh, + ImageRefreshMode = MetadataRefreshMode.FullRefresh, + ReplaceAllMetadata = true, + ReplaceAllImages = request.ReplaceAllImages, + SearchResult = request + }, + CancellationToken.None); } /// @@ -294,11 +296,9 @@ namespace MediaBrowser.Api Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath)); using (var stream = result.Content) + using (var filestream = _fileSystem.GetFileStream(fullCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) { - using (var filestream = _fileSystem.GetFileStream(fullCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true)) - { - await stream.CopyToAsync(filestream).ConfigureAwait(false); - } + await stream.CopyToAsync(filestream).ConfigureAwait(false); } Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath)); @@ -311,9 +311,6 @@ namespace MediaBrowser.Api /// The filename. /// System.String. private string GetFullCachePath(string filename) - { - return Path.Combine(_appPaths.CachePath, "remote-images", filename.Substring(0, 1), filename); - } - + => Path.Combine(_appPaths.CachePath, "remote-images", filename.Substring(0, 1), filename); } } diff --git a/MediaBrowser.Api/ItemRefreshService.cs b/MediaBrowser.Api/ItemRefreshService.cs index 8238ad19c5..a1d69cd2b0 100644 --- a/MediaBrowser.Api/ItemRefreshService.cs +++ b/MediaBrowser.Api/ItemRefreshService.cs @@ -63,7 +63,7 @@ namespace MediaBrowser.Api private MetadataRefreshOptions GetRefreshOptions(RefreshItem request) { - return new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)) + return new MetadataRefreshOptions(new DirectoryService(_fileSystem)) { MetadataRefreshMode = request.MetadataRefreshMode, ImageRefreshMode = request.ImageRefreshMode, diff --git a/MediaBrowser.Api/ItemUpdateService.cs b/MediaBrowser.Api/ItemUpdateService.cs index d6514d62e9..5d524b1859 100644 --- a/MediaBrowser.Api/ItemUpdateService.cs +++ b/MediaBrowser.Api/ItemUpdateService.cs @@ -225,13 +225,15 @@ namespace MediaBrowser.Api if (displayOrderChanged) { - _providerManager.QueueRefresh(series.Id, new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem)) - { - MetadataRefreshMode = MetadataRefreshMode.FullRefresh, - ImageRefreshMode = MetadataRefreshMode.FullRefresh, - ReplaceAllMetadata = true - - }, RefreshPriority.High); + _providerManager.QueueRefresh( + series.Id, + new MetadataRefreshOptions(new DirectoryService(_fileSystem)) + { + MetadataRefreshMode = MetadataRefreshMode.FullRefresh, + ImageRefreshMode = MetadataRefreshMode.FullRefresh, + ReplaceAllMetadata = true + }, + RefreshPriority.High); } } diff --git a/MediaBrowser.Api/LiveTv/LiveTvService.cs b/MediaBrowser.Api/LiveTv/LiveTvService.cs index b05e8c9495..2b9a64e975 100644 --- a/MediaBrowser.Api/LiveTv/LiveTvService.cs +++ b/MediaBrowser.Api/LiveTv/LiveTvService.cs @@ -8,6 +8,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Api.UserLibrary; +using MediaBrowser.Common; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; @@ -25,7 +26,6 @@ using MediaBrowser.Model.LiveTv; using MediaBrowser.Model.Querying; using MediaBrowser.Model.Services; using Microsoft.Net.Http.Headers; -using static MediaBrowser.Common.HexHelper; namespace MediaBrowser.Api.LiveTv { @@ -887,8 +887,9 @@ namespace MediaBrowser.Api.LiveTv { // SchedulesDirect requires a SHA1 hash of the user's password // https://github.com/SchedulesDirect/JSON-Service/wiki/API-20141201#obtain-a-token - using (SHA1 sha = SHA1.Create()) { - return ToHexString( + using (SHA1 sha = SHA1.Create()) + { + return Hex.Encode( sha.ComputeHash(Encoding.UTF8.GetBytes(str))); } } diff --git a/MediaBrowser.Api/MediaBrowser.Api.csproj b/MediaBrowser.Api/MediaBrowser.Api.csproj index f653270a6c..0d62cf8c59 100644 --- a/MediaBrowser.Api/MediaBrowser.Api.csproj +++ b/MediaBrowser.Api/MediaBrowser.Api.csproj @@ -10,7 +10,7 @@ - netstandard2.0 + netstandard2.1 false true diff --git a/MediaBrowser.Api/PackageService.cs b/MediaBrowser.Api/PackageService.cs index baa6f7bb97..1e5a932107 100644 --- a/MediaBrowser.Api/PackageService.cs +++ b/MediaBrowser.Api/PackageService.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common; using MediaBrowser.Common.Extensions; -using MediaBrowser.Common.Progress; using MediaBrowser.Common.Updates; using MediaBrowser.Controller.Net; using MediaBrowser.Model.Services; @@ -126,12 +126,6 @@ namespace MediaBrowser.Api _appHost = appHost; } - /// - /// Gets the specified request. - /// - /// The request. - /// System.Object. - /// /// /// Gets the specified request. /// @@ -139,7 +133,7 @@ namespace MediaBrowser.Api /// System.Object. public object Get(GetPackage request) { - var packages = _installationManager.GetAvailablePackages(CancellationToken.None, applicationVersion: typeof(PackageService).Assembly.GetName().Version).Result; + var packages = _installationManager.GetAvailablePackages().Result; var result = packages.FirstOrDefault(p => string.Equals(p.guid, request.AssemblyGuid ?? "none", StringComparison.OrdinalIgnoreCase)) ?? packages.FirstOrDefault(p => p.name.Equals(request.Name, StringComparison.OrdinalIgnoreCase)); @@ -154,7 +148,7 @@ namespace MediaBrowser.Api /// System.Object. public async Task Get(GetPackages request) { - IEnumerable packages = await _installationManager.GetAvailablePackages(CancellationToken.None, false, request.PackageType, typeof(PackageService).Assembly.GetName().Version).ConfigureAwait(false); + IEnumerable packages = await _installationManager.GetAvailablePackages().ConfigureAwait(false); if (!string.IsNullOrEmpty(request.TargetSystems)) { @@ -163,11 +157,6 @@ namespace MediaBrowser.Api packages = packages.Where(p => apps.Contains(p.targetSystem)); } - if (request.IsPremium.HasValue) - { - packages = packages.Where(p => p.isPremium == request.IsPremium.Value); - } - if (request.IsAdult.HasValue) { packages = packages.Where(p => p.adult == request.IsAdult.Value); @@ -188,13 +177,21 @@ namespace MediaBrowser.Api /// public async Task Post(InstallPackage request) { - var package = string.IsNullOrEmpty(request.Version) ? - await _installationManager.GetLatestCompatibleVersion(request.Name, request.AssemblyGuid, typeof(PackageService).Assembly.GetName().Version, request.UpdateClass).ConfigureAwait(false) : - await _installationManager.GetPackage(request.Name, request.AssemblyGuid, request.UpdateClass, Version.Parse(request.Version)).ConfigureAwait(false); + var packages = await _installationManager.GetAvailablePackages().ConfigureAwait(false); + var package = _installationManager.GetCompatibleVersions( + packages, + request.Name, + new Guid(request.AssemblyGuid), + string.IsNullOrEmpty(request.Version) ? null : Version.Parse(request.Version), + request.UpdateClass).FirstOrDefault(); if (package == null) { - throw new ResourceNotFoundException(string.Format("Package not found: {0}", request.Name)); + throw new ResourceNotFoundException( + string.Format( + CultureInfo.InvariantCulture, + "Package not found: {0}", + request.Name)); } await _installationManager.InstallPackage(package); diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index 8c4ccfa22c..4bd729aac8 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -7,6 +7,7 @@ using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Devices; @@ -141,7 +142,7 @@ namespace MediaBrowser.Api.Playback var filename = data.GetMD5().ToString("N", CultureInfo.InvariantCulture); var ext = outputFileExtension.ToLowerInvariant(); - var folder = ServerConfigurationManager.ApplicationPaths.TranscodingTempPath; + var folder = ServerConfigurationManager.GetTranscodePath(); if (EnableOutputInSubFolder) { @@ -215,7 +216,7 @@ namespace MediaBrowser.Api.Playback } } - var encodingOptions = ApiEntryPoint.Instance.GetEncodingOptions(); + var encodingOptions = ServerConfigurationManager.GetEncodingOptions(); var process = new Process() { @@ -289,17 +290,22 @@ namespace MediaBrowser.Api.Playback throw; } + Logger.LogDebug("Launched ffmpeg process"); state.TranscodingJob = transcodingJob; // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback _ = new JobLogger(Logger).StartStreamingLog(state, process.StandardError.BaseStream, logStream); // Wait for the file to exist before proceeeding - while (!File.Exists(state.WaitForPath ?? outputPath) && !transcodingJob.HasExited) + var ffmpegTargetFile = state.WaitForPath ?? outputPath; + Logger.LogDebug("Waiting for the creation of {0}", ffmpegTargetFile); + while (!File.Exists(ffmpegTargetFile) && !transcodingJob.HasExited) { await Task.Delay(100, cancellationTokenSource.Token).ConfigureAwait(false); } + Logger.LogDebug("File {0} created or transcoding has finished", ffmpegTargetFile); + if (state.IsInputVideo && transcodingJob.Type == TranscodingJobType.Progressive && !transcodingJob.HasExited) { await Task.Delay(1000, cancellationTokenSource.Token).ConfigureAwait(false); @@ -314,6 +320,7 @@ namespace MediaBrowser.Api.Playback { StartThrottler(state, transcodingJob); } + Logger.LogDebug("StartFfMpeg() finished successfully"); return transcodingJob; } @@ -582,7 +589,7 @@ namespace MediaBrowser.Api.Playback /// /// Parses query parameters as StreamOptions - /// + /// /// The stream request. private void ParseStreamOptions(StreamRequest request) { @@ -839,7 +846,7 @@ namespace MediaBrowser.Api.Playback ? GetOutputFileExtension(state) : ('.' + state.OutputContainer); - var encodingOptions = ApiEntryPoint.Instance.GetEncodingOptions(); + var encodingOptions = ServerConfigurationManager.GetEncodingOptions(); state.OutputFilePath = GetOutputFilePath(state, encodingOptions, ext); diff --git a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs index f5f7536843..9ecb5fe8c5 100644 --- a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs @@ -192,6 +192,7 @@ namespace MediaBrowser.Api.Playback.Hls if (File.Exists(segmentPath)) { job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); + Logger.LogDebug("returning {0} [it exists, try 1]", segmentPath); return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, requestedIndex, job, cancellationToken).ConfigureAwait(false); } @@ -207,6 +208,7 @@ namespace MediaBrowser.Api.Playback.Hls job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); transcodingLock.Release(); released = true; + Logger.LogDebug("returning {0} [it exists, try 2]", segmentPath); return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, requestedIndex, job, cancellationToken).ConfigureAwait(false); } else @@ -243,6 +245,7 @@ namespace MediaBrowser.Api.Playback.Hls request.StartTimeTicks = GetStartPositionTicks(state, requestedIndex); + state.WaitForPath = segmentPath; job = await StartFfMpeg(state, playlistPath, cancellationTokenSource).ConfigureAwait(false); } catch @@ -277,7 +280,7 @@ namespace MediaBrowser.Api.Playback.Hls // await Task.Delay(50, cancellationToken).ConfigureAwait(false); //} - Logger.LogInformation("returning {0}", segmentPath); + Logger.LogDebug("returning {0} [general case]", segmentPath); job = job ?? ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, requestedIndex, job, cancellationToken).ConfigureAwait(false); } @@ -458,56 +461,68 @@ namespace MediaBrowser.Api.Playback.Hls TranscodingJob transcodingJob, CancellationToken cancellationToken) { - var segmentFileExists = File.Exists(segmentPath); - - // If all transcoding has completed, just return immediately - if (transcodingJob != null && transcodingJob.HasExited && segmentFileExists) + var segmentExists = File.Exists(segmentPath); + if (segmentExists) { - return await GetSegmentResult(state, segmentPath, segmentIndex, transcodingJob).ConfigureAwait(false); - } + if (transcodingJob != null && transcodingJob.HasExited) + { + // Transcoding job is over, so assume all existing files are ready + Logger.LogDebug("serving up {0} as transcode is over", segmentPath); + return await GetSegmentResult(state, segmentPath, segmentIndex, transcodingJob).ConfigureAwait(false); + } - if (segmentFileExists) - { var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension); // If requested segment is less than transcoding position, we can't transcode backwards, so assume it's ready if (segmentIndex < currentTranscodingIndex) { + Logger.LogDebug("serving up {0} as transcode index {1} is past requested point {2}", segmentPath, currentTranscodingIndex, segmentIndex); return await GetSegmentResult(state, segmentPath, segmentIndex, transcodingJob).ConfigureAwait(false); } } - var segmentFilename = Path.GetFileName(segmentPath); - - while (!cancellationToken.IsCancellationRequested) + var nextSegmentPath = GetSegmentPath(state, playlistPath, segmentIndex + 1); + if (transcodingJob != null) { - try + while (!cancellationToken.IsCancellationRequested && !transcodingJob.HasExited) { - var text = File.ReadAllText(playlistPath, Encoding.UTF8); - - // If it appears in the playlist, it's done - if (text.IndexOf(segmentFilename, StringComparison.OrdinalIgnoreCase) != -1) + // To be considered ready, the segment file has to exist AND + // either the transcoding job should be done or next segment should also exist + if (segmentExists) { - if (!segmentFileExists) - { - segmentFileExists = File.Exists(segmentPath); - } - if (segmentFileExists) + if (transcodingJob.HasExited || File.Exists(nextSegmentPath)) { + Logger.LogDebug("serving up {0} as it deemed ready", segmentPath); return await GetSegmentResult(state, segmentPath, segmentIndex, transcodingJob).ConfigureAwait(false); } - //break; } - } - catch (IOException) - { - // May get an error if the file is locked + else + { + segmentExists = File.Exists(segmentPath); + if (segmentExists) + { + continue; // avoid unnecessary waiting if segment just became available + } + } + + await Task.Delay(100, cancellationToken).ConfigureAwait(false); } - await Task.Delay(100, cancellationToken).ConfigureAwait(false); + if (!File.Exists(segmentPath)) + { + Logger.LogWarning("cannot serve {0} as transcoding quit before we got there", segmentPath); + } + else + { + Logger.LogDebug("serving {0} as it's on disk and transcoding stopped", segmentPath); + } + cancellationToken.ThrowIfCancellationRequested(); + } + else + { + Logger.LogWarning("cannot serve {0} as it doesn't exist and no transcode is running", segmentPath); } - cancellationToken.ThrowIfCancellationRequested(); return await GetSegmentResult(state, segmentPath, segmentIndex, transcodingJob).ConfigureAwait(false); } @@ -521,6 +536,7 @@ namespace MediaBrowser.Api.Playback.Hls FileShare = FileShareMode.ReadWrite, OnComplete = () => { + Logger.LogDebug("finished serving {0}", segmentPath); if (transcodingJob != null) { transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPositionTicks, segmentEndingPositionTicks); @@ -909,9 +925,23 @@ namespace MediaBrowser.Api.Playback.Hls else { var keyFrameArg = string.Format( + CultureInfo.InvariantCulture, " -force_key_frames:0 \"expr:gte(t,{0}+n_forced*{1})\"", GetStartNumber(state) * state.SegmentLength, - state.SegmentLength.ToString(CultureInfo.InvariantCulture)); + state.SegmentLength); + if (state.TargetFramerate.HasValue) + { + // This is to make sure keyframe interval is limited to our segment, + // as forcing keyframes is not enough. + // Example: we encoded half of desired length, then codec detected + // scene cut and inserted a keyframe; next forced keyframe would + // be created outside of segment, which breaks seeking. + keyFrameArg += string.Format( + CultureInfo.InvariantCulture, + " -g {0} -keyint_min {0}", + (int)(state.SegmentLength * state.TargetFramerate) + ); + } var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode; @@ -955,6 +985,15 @@ namespace MediaBrowser.Api.Playback.Hls var threads = EncodingHelper.GetNumberOfThreads(state, encodingOptions, videoCodec); + if (state.BaseRequest.BreakOnNonKeyFrames) + { + // FIXME: this is actually a workaround, as ideally it really should be the client which decides whether non-keyframe + // breakpoints are supported; but current implementation always uses "ffmpeg input seeking" which is liable + // to produce a missing part of video stream before first keyframe is encountered, which may lead to + // awkward cases like a few starting HLS segments having no video whatsoever, which breaks hls.js + Logger.LogInformation("Current HLS implementation doesn't support non-keyframe breaks but one is requested, ignoring that request"); + state.BaseRequest.BreakOnNonKeyFrames = false; + } var inputModifier = EncodingHelper.GetInputModifier(state, encodingOptions); // If isEncoding is true we're actually starting ffmpeg @@ -965,14 +1004,6 @@ namespace MediaBrowser.Api.Playback.Hls var outputTsArg = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state.Request); - var timeDeltaParam = string.Empty; - - if (isEncoding && state.TargetFramerate > 0) - { - float startTime = 1 / (state.TargetFramerate.Value * 2); - timeDeltaParam = string.Format(CultureInfo.InvariantCulture, "-segment_time_delta {0:F3}", startTime); - } - var segmentFormat = GetSegmentFileExtension(state.Request).TrimStart('.'); if (string.Equals(segmentFormat, "ts", StringComparison.OrdinalIgnoreCase)) { @@ -980,7 +1011,7 @@ namespace MediaBrowser.Api.Playback.Hls } return string.Format( - "{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -f segment -max_delay 5000000 -avoid_negative_ts disabled -start_at_zero -segment_time {6} {10} -individual_header_trailer 0 -segment_format {11} -segment_list_type m3u8 -segment_start_number {7} -segment_list \"{8}\" -y \"{9}\"", + "{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -f hls -max_delay 5000000 -avoid_negative_ts disabled -start_at_zero -hls_time {6} -individual_header_trailer 0 -hls_segment_type {7} -start_number {8} -hls_segment_filename \"{9}\" -hls_playlist_type vod -hls_list_size 0 -y \"{10}\"", inputModifier, EncodingHelper.GetInputArgument(state, encodingOptions), threads, @@ -988,11 +1019,10 @@ namespace MediaBrowser.Api.Playback.Hls GetVideoArguments(state, encodingOptions), GetAudioArguments(state, encodingOptions), state.SegmentLength.ToString(CultureInfo.InvariantCulture), + segmentFormat, startNumberParam, - outputPath, outputTsArg, - timeDeltaParam, - segmentFormat + outputPath ).Trim(); } } diff --git a/MediaBrowser.Api/Playback/Hls/HlsSegmentService.cs b/MediaBrowser.Api/Playback/Hls/HlsSegmentService.cs index 6a2c7ae038..ca5a73ff1b 100644 --- a/MediaBrowser.Api/Playback/Hls/HlsSegmentService.cs +++ b/MediaBrowser.Api/Playback/Hls/HlsSegmentService.cs @@ -2,7 +2,7 @@ using System; using System.IO; using System.Linq; using System.Threading.Tasks; -using MediaBrowser.Controller; +using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Net; @@ -83,13 +83,11 @@ namespace MediaBrowser.Api.Playback.Hls public class HlsSegmentService : BaseApiService { - private readonly IServerApplicationPaths _appPaths; private readonly IServerConfigurationManager _config; private readonly IFileSystem _fileSystem; - public HlsSegmentService(IServerApplicationPaths appPaths, IServerConfigurationManager config, IFileSystem fileSystem) + public HlsSegmentService(IServerConfigurationManager config, IFileSystem fileSystem) { - _appPaths = appPaths; _config = config; _fileSystem = fileSystem; } @@ -97,7 +95,7 @@ namespace MediaBrowser.Api.Playback.Hls public Task Get(GetHlsPlaylistLegacy request) { var file = request.PlaylistId + Path.GetExtension(Request.PathInfo); - file = Path.Combine(_appPaths.TranscodingTempPath, file); + file = Path.Combine(_config.GetTranscodePath(), file); return GetFileResult(file, file); } @@ -115,8 +113,7 @@ namespace MediaBrowser.Api.Playback.Hls public Task Get(GetHlsVideoSegmentLegacy request) { var file = request.SegmentId + Path.GetExtension(Request.PathInfo); - - var transcodeFolderPath = _config.ApplicationPaths.TranscodingTempPath; + var transcodeFolderPath = _config.GetTranscodePath(); file = Path.Combine(transcodeFolderPath, file); var normalizedPlaylistId = request.PlaylistId; @@ -136,7 +133,7 @@ namespace MediaBrowser.Api.Playback.Hls { // TODO: Deprecate with new iOS app var file = request.SegmentId + Path.GetExtension(Request.PathInfo); - file = Path.Combine(_appPaths.TranscodingTempPath, file); + file = Path.Combine(_config.GetTranscodePath(), file); return ResultFactory.GetStaticFileResult(Request, file, FileShareMode.ReadWrite); } diff --git a/MediaBrowser.Api/Session/SessionsService.cs b/MediaBrowser.Api/Session/SessionsService.cs index 76392e27c9..6caf3b4809 100644 --- a/MediaBrowser.Api/Session/SessionsService.cs +++ b/MediaBrowser.Api/Session/SessionsService.cs @@ -321,7 +321,7 @@ namespace MediaBrowser.Api.Session DateCreated = DateTime.UtcNow, DeviceId = _appHost.SystemId, DeviceName = _appHost.FriendlyName, - AppVersion = _appHost.ApplicationVersion + AppVersion = _appHost.ApplicationVersionString }); } diff --git a/MediaBrowser.Api/StartupWizardService.cs b/MediaBrowser.Api/StartupWizardService.cs index 3a9eb7a55e..e69de29bb2 100644 --- a/MediaBrowser.Api/StartupWizardService.cs +++ b/MediaBrowser.Api/StartupWizardService.cs @@ -1,135 +0,0 @@ -using System.Linq; -using System.Threading.Tasks; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.MediaEncoding; -using MediaBrowser.Controller.Net; -using MediaBrowser.Model.Services; - -namespace MediaBrowser.Api -{ - [Route("/Startup/Complete", "POST", Summary = "Reports that the startup wizard has been completed", IsHidden = true)] - public class ReportStartupWizardComplete : IReturnVoid - { - } - - [Route("/Startup/Configuration", "GET", Summary = "Gets initial server configuration", IsHidden = true)] - public class GetStartupConfiguration : IReturn - { - } - - [Route("/Startup/Configuration", "POST", Summary = "Updates initial server configuration", IsHidden = true)] - public class UpdateStartupConfiguration : StartupConfiguration, IReturnVoid - { - } - - [Route("/Startup/RemoteAccess", "POST", Summary = "Updates initial server configuration", IsHidden = true)] - public class UpdateRemoteAccessConfiguration : IReturnVoid - { - public bool EnableRemoteAccess { get; set; } - public bool EnableAutomaticPortMapping { get; set; } - } - - [Route("/Startup/User", "GET", Summary = "Gets initial user info", IsHidden = true)] - public class GetStartupUser : IReturn - { - } - - [Route("/Startup/User", "POST", Summary = "Updates initial user info", IsHidden = true)] - public class UpdateStartupUser : StartupUser - { - } - - [Authenticated(AllowBeforeStartupWizard = true, Roles = "Admin")] - public class StartupWizardService : BaseApiService - { - private readonly IServerConfigurationManager _config; - private readonly IServerApplicationHost _appHost; - private readonly IUserManager _userManager; - private readonly IMediaEncoder _mediaEncoder; - private readonly IHttpClient _httpClient; - - public StartupWizardService(IServerConfigurationManager config, IHttpClient httpClient, IServerApplicationHost appHost, IUserManager userManager, IMediaEncoder mediaEncoder) - { - _config = config; - _appHost = appHost; - _userManager = userManager; - _mediaEncoder = mediaEncoder; - _httpClient = httpClient; - } - - public void Post(ReportStartupWizardComplete request) - { - _config.Configuration.IsStartupWizardCompleted = true; - _config.SetOptimalValues(); - _config.SaveConfiguration(); - } - - public object Get(GetStartupConfiguration request) - { - var result = new StartupConfiguration - { - UICulture = _config.Configuration.UICulture, - MetadataCountryCode = _config.Configuration.MetadataCountryCode, - PreferredMetadataLanguage = _config.Configuration.PreferredMetadataLanguage - }; - - return result; - } - - public void Post(UpdateStartupConfiguration request) - { - _config.Configuration.UICulture = request.UICulture; - _config.Configuration.MetadataCountryCode = request.MetadataCountryCode; - _config.Configuration.PreferredMetadataLanguage = request.PreferredMetadataLanguage; - _config.SaveConfiguration(); - } - - public void Post(UpdateRemoteAccessConfiguration request) - { - _config.Configuration.EnableRemoteAccess = request.EnableRemoteAccess; - _config.Configuration.EnableUPnP = request.EnableAutomaticPortMapping; - _config.SaveConfiguration(); - } - - public object Get(GetStartupUser request) - { - var user = _userManager.Users.First(); - - return new StartupUser - { - Name = user.Name, - Password = user.Password - }; - } - - public async Task Post(UpdateStartupUser request) - { - var user = _userManager.Users.First(); - - user.Name = request.Name; - - _userManager.UpdateUser(user); - - if (!string.IsNullOrEmpty(request.Password)) - { - await _userManager.ChangePassword(user, request.Password).ConfigureAwait(false); - } - } - } - - public class StartupConfiguration - { - public string UICulture { get; set; } - public string MetadataCountryCode { get; set; } - public string PreferredMetadataLanguage { get; set; } - } - - public class StartupUser - { - public string Name { get; set; } - public string Password { get; set; } - } -} diff --git a/MediaBrowser.Api/Subtitles/SubtitleService.cs b/MediaBrowser.Api/Subtitles/SubtitleService.cs index 52043d3df6..1878f51d05 100644 --- a/MediaBrowser.Api/Subtitles/SubtitleService.cs +++ b/MediaBrowser.Api/Subtitles/SubtitleService.cs @@ -279,13 +279,12 @@ namespace MediaBrowser.Api.Subtitles await _subtitleManager.DownloadSubtitles(video, request.SubtitleId, CancellationToken.None) .ConfigureAwait(false); - _providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem)), RefreshPriority.High); + _providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.High); } catch (Exception ex) { Logger.LogError(ex, "Error downloading subtitles"); } - }); } } diff --git a/MediaBrowser.Api/UserLibrary/PersonsService.cs b/MediaBrowser.Api/UserLibrary/PersonsService.cs index c264577788..2024e9e637 100644 --- a/MediaBrowser.Api/UserLibrary/PersonsService.cs +++ b/MediaBrowser.Api/UserLibrary/PersonsService.cs @@ -109,6 +109,11 @@ namespace MediaBrowser.Api.UserLibrary NameContains = query.NameContains ?? query.SearchTerm }); + if ((query.IsFavorite ?? false) && query.User != null) + { + items = items.Where(i => UserDataRepository.GetUserData(query.User, i).IsFavorite).ToList(); + } + return new QueryResult<(BaseItem, ItemCounts)> { TotalRecordCount = items.Count, diff --git a/MediaBrowser.Api/UserLibrary/UserLibraryService.cs b/MediaBrowser.Api/UserLibrary/UserLibraryService.cs index 45694a6780..da0bf6dcb0 100644 --- a/MediaBrowser.Api/UserLibrary/UserLibraryService.cs +++ b/MediaBrowser.Api/UserLibrary/UserLibraryService.cs @@ -413,7 +413,7 @@ namespace MediaBrowser.Api.UserLibrary if (!hasMetdata) { - var options = new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem)) + var options = new MetadataRefreshOptions(new DirectoryService(_fileSystem)) { MetadataRefreshMode = MetadataRefreshMode.FullRefresh, ImageRefreshMode = MetadataRefreshMode.FullRefresh, diff --git a/MediaBrowser.Api/UserLibrary/UserViewsService.cs b/MediaBrowser.Api/UserLibrary/UserViewsService.cs index 2fa5d8933c..d62049ce9e 100644 --- a/MediaBrowser.Api/UserLibrary/UserViewsService.cs +++ b/MediaBrowser.Api/UserLibrary/UserViewsService.cs @@ -10,6 +10,7 @@ using MediaBrowser.Model.Entities; using MediaBrowser.Model.Library; using MediaBrowser.Model.Querying; using MediaBrowser.Model.Services; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Api.UserLibrary { @@ -49,7 +50,12 @@ namespace MediaBrowser.Api.UserLibrary private readonly IAuthorizationContext _authContext; private readonly ILibraryManager _libraryManager; - public UserViewsService(IUserManager userManager, IUserViewManager userViewManager, IDtoService dtoService, IAuthorizationContext authContext, ILibraryManager libraryManager) + public UserViewsService( + IUserManager userManager, + IUserViewManager userViewManager, + IDtoService dtoService, + IAuthorizationContext authContext, + ILibraryManager libraryManager) { _userManager = userManager; _userViewManager = userViewManager; diff --git a/MediaBrowser.Common/Configuration/EncodingConfigurationExtensions.cs b/MediaBrowser.Common/Configuration/EncodingConfigurationExtensions.cs new file mode 100644 index 0000000000..ccf9658988 --- /dev/null +++ b/MediaBrowser.Common/Configuration/EncodingConfigurationExtensions.cs @@ -0,0 +1,35 @@ +using System.IO; +using MediaBrowser.Model.Configuration; + +namespace MediaBrowser.Common.Configuration +{ + /// + /// Class containing extension methods for working with the encoding configuration. + /// + public static class EncodingConfigurationExtensions + { + /// + /// Gets the encoding options. + /// + /// The configuration manager. + /// The encoding options. + public static EncodingOptions GetEncodingOptions(this IConfigurationManager configurationManager) + => configurationManager.GetConfiguration("encoding"); + + /// + /// Retrieves the transcoding temp path from the encoding configuration. + /// + /// The Configuration manager. + /// The transcoding temp path. + public static string GetTranscodePath(this IConfigurationManager configurationManager) + { + var transcodingTempPath = configurationManager.GetEncodingOptions().TranscodingTempPath; + if (string.IsNullOrEmpty(transcodingTempPath)) + { + return Path.Combine(configurationManager.CommonApplicationPaths.ProgramDataPath, "transcodes"); + } + + return transcodingTempPath; + } + } +} diff --git a/MediaBrowser.Common/Cryptography/PasswordHash.cs b/MediaBrowser.Common/Cryptography/PasswordHash.cs index 7741571db9..19b8be47a9 100644 --- a/MediaBrowser.Common/Cryptography/PasswordHash.cs +++ b/MediaBrowser.Common/Cryptography/PasswordHash.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.IO; using System.Text; -using static MediaBrowser.Common.HexHelper; namespace MediaBrowser.Common.Cryptography { @@ -61,13 +60,13 @@ namespace MediaBrowser.Common.Cryptography /// Return the hashed password. public byte[] Hash { get; } - public static PasswordHash Parse(string storageString) + public static PasswordHash Parse(string hashString) { - string[] splitted = storageString.Split('$'); + string[] splitted = hashString.Split('$'); // The string should at least contain the hash function and the hash itself if (splitted.Length < 3) { - throw new ArgumentException("String doesn't contain enough segments", nameof(storageString)); + throw new ArgumentException("String doesn't contain enough segments", nameof(hashString)); } // Start at 1, the first index shouldn't contain any data @@ -102,13 +101,13 @@ namespace MediaBrowser.Common.Cryptography // Check if the string also contains a salt if (splitted.Length - index == 2) { - salt = FromHexString(splitted[index++]); - hash = FromHexString(splitted[index++]); + salt = Hex.Decode(splitted[index++]); + hash = Hex.Decode(splitted[index++]); } else { salt = Array.Empty(); - hash = FromHexString(splitted[index++]); + hash = Hex.Decode(splitted[index++]); } return new PasswordHash(id, hash, salt, parameters); @@ -124,10 +123,10 @@ namespace MediaBrowser.Common.Cryptography stringBuilder.Append('$'); foreach (var pair in _parameters) { - stringBuilder.Append(pair.Key); - stringBuilder.Append('='); - stringBuilder.Append(pair.Value); - stringBuilder.Append(','); + stringBuilder.Append(pair.Key) + .Append('=') + .Append(pair.Value) + .Append(','); } // Remove last ',' @@ -137,21 +136,19 @@ namespace MediaBrowser.Common.Cryptography /// public override string ToString() { - var str = new StringBuilder(); - str.Append('$'); - str.Append(Id); + var str = new StringBuilder() + .Append('$') + .Append(Id); SerializeParameters(str); if (Salt.Length != 0) { - str.Append('$'); - str.Append(ToHexString(Salt)); + str.Append('$') + .Append(Hex.Encode(Salt, false)); } - str.Append('$'); - str.Append(ToHexString(Hash)); - - return str.ToString(); + return str.Append('$') + .Append(Hex.Encode(Hash, false)).ToString(); } } } diff --git a/MediaBrowser.Common/Extensions/CollectionExtensions.cs b/MediaBrowser.Common/Extensions/CopyToExtensions.cs similarity index 52% rename from MediaBrowser.Common/Extensions/CollectionExtensions.cs rename to MediaBrowser.Common/Extensions/CopyToExtensions.cs index a12b2833f1..78a73f07e0 100644 --- a/MediaBrowser.Common/Extensions/CollectionExtensions.cs +++ b/MediaBrowser.Common/Extensions/CopyToExtensions.cs @@ -1,39 +1,12 @@ -#pragma warning disable CS1591 - -using System; using System.Collections.Generic; namespace MediaBrowser.Common.Extensions { - // The MS CollectionExtensions are only available in netcoreapp + /// + /// Provides CopyTo extensions methods for . + /// public static class CollectionExtensions { - private static readonly Random _rng = new Random(); - - /// - /// Shuffles the items in a list. - /// - /// The list that should get shuffled. - /// The type. - public static void Shuffle(this IList list) - { - int n = list.Count; - while (n > 1) - { - n--; - int k = _rng.Next(n + 1); - T value = list[k]; - list[k] = list[n]; - list[n] = value; - } - } - - public static TValue GetValueOrDefault(this IReadOnlyDictionary dictionary, TKey key) - { - dictionary.TryGetValue(key, out var ret); - return ret; - } - /// /// Copies all the elements of the current collection to the specified list /// starting at the specified destination array index. The index is specified as a 32-bit integer. diff --git a/MediaBrowser.Common/Extensions/ShuffleExtensions.cs b/MediaBrowser.Common/Extensions/ShuffleExtensions.cs new file mode 100644 index 0000000000..5889d09c4b --- /dev/null +++ b/MediaBrowser.Common/Extensions/ShuffleExtensions.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; + +namespace MediaBrowser.Common.Extensions +{ + /// + /// Provides Shuffle extensions methods for . + /// + public static class ShuffleExtensions + { + private static readonly Random _rng = new Random(); + + /// + /// Shuffles the items in a list. + /// + /// The list that should get shuffled. + /// The type. + public static void Shuffle(this IList list) + { + int n = list.Count; + while (n > 1) + { + n--; + int k = _rng.Next(n + 1); + T value = list[k]; + list[k] = list[n]; + list[n] = value; + } + } + } +} diff --git a/MediaBrowser.Common/Hex.cs b/MediaBrowser.Common/Hex.cs new file mode 100644 index 0000000000..b2d9aea3a7 --- /dev/null +++ b/MediaBrowser.Common/Hex.cs @@ -0,0 +1,94 @@ +using System; +using System.Diagnostics.CodeAnalysis; + +namespace MediaBrowser.Common +{ + /// + /// Encoding and decoding hex strings. + /// + public static class Hex + { + internal const string HexCharsLower = "0123456789abcdef"; + internal const string HexCharsUpper = "0123456789ABCDEF"; + + internal const int LastHexSymbol = 0x66; // 102: f + + /// + /// Map from an ASCII char to its hex value shifted, + /// e.g. b -> 11. 0xFF means it's not a hex symbol. + /// + /// + internal static ReadOnlySpan HexLookup => new byte[] { + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f + }; + + /// + /// Encodes bytes as a hex string. + /// + /// + /// + /// bytes as a hex string. + public static string Encode(ReadOnlySpan bytes, bool lowercase = true) + { + var hexChars = lowercase ? HexCharsLower : HexCharsUpper; + + // TODO: use string.Create when it's supports spans + // Ref: https://github.com/dotnet/corefx/issues/29120 + char[] s = new char[bytes.Length * 2]; + int j = 0; + for (int i = 0; i < bytes.Length; i++) + { + s[j++] = hexChars[bytes[i] >> 4]; + s[j++] = hexChars[bytes[i] & 0x0f]; + } + + return new string(s); + } + + /// + /// Decodes a hex string into bytes. + /// + /// The . + /// The decoded bytes. + public static byte[] Decode(ReadOnlySpan str) + { + if (str.Length == 0) + { + return Array.Empty(); + } + + var unHex = HexLookup; + + int byteLen = str.Length / 2; + byte[] bytes = new byte[byteLen]; + int i = 0; + for (int j = 0; j < byteLen; j++) + { + byte a; + byte b; + if (str[i] > LastHexSymbol + || (a = unHex[str[i++]]) == 0xFF + || str[i] > LastHexSymbol + || (b = unHex[str[i++]]) == 0xFF) + { + ThrowArgumentException(nameof(str)); + break; // Unreachable + } + + bytes[j] = (byte)((a * 16) | b); + } + + return bytes; + } + + [DoesNotReturn] + private static void ThrowArgumentException(string paramName) + => throw new ArgumentException("Character is not a hex symbol.", paramName); + } +} diff --git a/MediaBrowser.Common/HexHelper.cs b/MediaBrowser.Common/HexHelper.cs deleted file mode 100644 index 61007b5b2e..0000000000 --- a/MediaBrowser.Common/HexHelper.cs +++ /dev/null @@ -1,24 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using System.Globalization; - -namespace MediaBrowser.Common -{ - public static class HexHelper - { - public static byte[] FromHexString(string str) - { - byte[] bytes = new byte[str.Length / 2]; - for (int i = 0; i < str.Length; i += 2) - { - bytes[i / 2] = byte.Parse(str.Substring(i, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture); - } - - return bytes; - } - - public static string ToHexString(byte[] bytes) - => BitConverter.ToString(bytes).Replace("-", ""); - } -} diff --git a/MediaBrowser.Common/IApplicationHost.cs b/MediaBrowser.Common/IApplicationHost.cs index c8da100f64..6668e98aa5 100644 --- a/MediaBrowser.Common/IApplicationHost.cs +++ b/MediaBrowser.Common/IApplicationHost.cs @@ -67,7 +67,13 @@ namespace MediaBrowser.Common /// Gets the application version. /// /// The application version. - string ApplicationVersion { get; } + Version ApplicationVersion { get; } + + /// + /// Gets the application version. + /// + /// The application version. + string ApplicationVersionString { get; } /// /// Gets the application user agent. diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index 263cc75813..889fbfa5ab 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -12,9 +12,8 @@ - + - @@ -22,7 +21,7 @@ - netstandard2.0 + netstandard2.1 false true true diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 97504a471f..0b99dc9103 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -4,8 +4,6 @@ using System; using System.Collections.Generic; using System.Net; using System.Net.NetworkInformation; -using MediaBrowser.Model.IO; -using MediaBrowser.Model.Net; namespace MediaBrowser.Common.Net { @@ -36,19 +34,6 @@ namespace MediaBrowser.Common.Net /// true if [is in private address space] [the specified endpoint]; otherwise, false. bool IsInPrivateAddressSpace(string endpoint); - /// - /// Gets the network shares. - /// - /// The path. - /// IEnumerable{NetworkShare}. - IEnumerable GetNetworkShares(string path); - - /// - /// Gets available devices within the domain - /// - /// PC's in the Domain - IEnumerable GetNetworkDevices(); - /// /// Determines whether [is in local network] [the specified endpoint]. /// diff --git a/MediaBrowser.Common/Updates/IInstallationManager.cs b/MediaBrowser.Common/Updates/IInstallationManager.cs index b3367f71d0..e49812f150 100644 --- a/MediaBrowser.Common/Updates/IInstallationManager.cs +++ b/MediaBrowser.Common/Updates/IInstallationManager.cs @@ -13,87 +13,86 @@ namespace MediaBrowser.Common.Updates public interface IInstallationManager : IDisposable { event EventHandler PackageInstalling; + event EventHandler PackageInstallationCompleted; + event EventHandler PackageInstallationFailed; + event EventHandler PackageInstallationCancelled; /// - /// The completed installations - /// - IEnumerable CompletedInstallations { get; } - - /// - /// Occurs when [plugin uninstalled]. + /// Occurs when a plugin is uninstalled. /// event EventHandler> PluginUninstalled; /// - /// Occurs when [plugin updated]. + /// Occurs when a plugin is updated. /// event EventHandler> PluginUpdated; /// - /// Occurs when [plugin updated]. + /// Occurs when a plugin is installed. /// event EventHandler> PluginInstalled; + /// + /// Gets the completed installations. + /// + IEnumerable CompletedInstallations { get; } + /// /// Gets all available packages. /// /// The cancellation token. - /// if set to true [with registration]. - /// Type of the package. - /// The application version. - /// Task{List{PackageInfo}}. - Task> GetAvailablePackages(CancellationToken cancellationToken, - bool withRegistration = true, string packageType = null, Version applicationVersion = null); + /// Task{IReadOnlyList{PackageInfo}}. + Task> GetAvailablePackages(CancellationToken cancellationToken = default); /// - /// Gets all available packages from a static resource. + /// Returns all plugins matching the requirements. /// - /// The cancellation token. - /// Task{List{PackageInfo}}. - Task> GetAvailablePackagesWithoutRegistrationInfo(CancellationToken cancellationToken); + /// The available packages. + /// The name of the plugin. + /// The id of the plugin. + /// All plugins matching the requirements. + IEnumerable FilterPackages( + IEnumerable availablePackages, + string name = null, + Guid guid = default); /// - /// Gets the package. + /// Returns all compatible versions ordered from newest to oldest. /// - /// The name. - /// The assembly guid - /// The classification. - /// The version. - /// Task{PackageVersionInfo}. - Task GetPackage(string name, string guid, PackageVersionClass classification, Version version); + /// The available version of the plugin. + /// The minimum required version of the plugin. + /// The classification of updates. + /// All compatible versions ordered from newest to oldest. + IEnumerable GetCompatibleVersions( + IEnumerable availableVersions, + Version minVersion = null, + PackageVersionClass classification = PackageVersionClass.Release); /// - /// Gets the latest compatible version. - /// - /// The name. - /// The assembly guid - /// The current server version. - /// The classification. - /// Task{PackageVersionInfo}. - Task GetLatestCompatibleVersion(string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release); - - /// - /// Gets the latest compatible version. + /// Returns all compatible versions ordered from newest to oldest. /// /// The available packages. /// The name. - /// The assembly guid - /// The current server version. + /// The guid of the plugin. + /// The minimum required version of the plugin. /// The classification. - /// PackageVersionInfo. - PackageVersionInfo GetLatestCompatibleVersion(IEnumerable availablePackages, string name, string guid, Version currentServerVersion, PackageVersionClass classification = PackageVersionClass.Release); + /// All compatible versions ordered from newest to oldest. + IEnumerable GetCompatibleVersions( + IEnumerable availablePackages, + string name = null, + Guid guid = default, + Version minVersion = null, + PackageVersionClass classification = PackageVersionClass.Release); /// - /// Gets the available plugin updates. + /// Returns the available plugin updates. /// - /// The current server version. - /// if set to true [with auto update enabled]. /// The cancellation token. - /// Task{IEnumerable{PackageVersionInfo}}. - Task> GetAvailablePluginUpdates(Version applicationVersion, bool withAutoUpdateEnabled, CancellationToken cancellationToken); + /// The available plugin updates. + IAsyncEnumerable GetAvailablePluginUpdates(CancellationToken cancellationToken = default); /// /// Installs the package. diff --git a/MediaBrowser.Controller/Channels/Channel.cs b/MediaBrowser.Controller/Channels/Channel.cs index 89159973b8..cdf2ca69e6 100644 --- a/MediaBrowser.Controller/Channels/Channel.cs +++ b/MediaBrowser.Controller/Channels/Channel.cs @@ -1,11 +1,11 @@ using System; using System.Globalization; using System.Linq; +using System.Text.Json.Serialization; using System.Threading; using MediaBrowser.Common.Progress; using MediaBrowser.Controller.Entities; using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.Channels { @@ -31,10 +31,10 @@ namespace MediaBrowser.Controller.Channels return base.IsVisible(user); } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsInheritedParentImages => false; - [IgnoreDataMember] + [JsonIgnore] public override SourceType SourceType => SourceType.Channel; protected override QueryResult GetItemsInternal(InternalItemsQuery query) diff --git a/MediaBrowser.Controller/Entities/AggregateFolder.cs b/MediaBrowser.Controller/Entities/AggregateFolder.cs index 054df21e52..54540e8921 100644 --- a/MediaBrowser.Controller/Entities/AggregateFolder.cs +++ b/MediaBrowser.Controller/Entities/AggregateFolder.cs @@ -2,13 +2,13 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.Entities { @@ -23,7 +23,7 @@ namespace MediaBrowser.Controller.Entities PhysicalLocationsList = Array.Empty(); } - [IgnoreDataMember] + [JsonIgnore] public override bool IsPhysicalRoot => true; public override bool CanDelete() @@ -31,7 +31,7 @@ namespace MediaBrowser.Controller.Entities return false; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPlayedStatus => false; /// @@ -45,7 +45,7 @@ namespace MediaBrowser.Controller.Entities /// The virtual children. public ConcurrentBag VirtualChildren => _virtualChildren; - [IgnoreDataMember] + [JsonIgnore] public override string[] PhysicalLocations => PhysicalLocationsList; public string[] PhysicalLocationsList { get; set; } @@ -89,7 +89,7 @@ namespace MediaBrowser.Controller.Entities { var locations = PhysicalLocations; - var newLocations = CreateResolveArgs(new DirectoryService(Logger, FileSystem), false).PhysicalLocations; + var newLocations = CreateResolveArgs(new DirectoryService(FileSystem), false).PhysicalLocations; if (!locations.SequenceEqual(newLocations)) { diff --git a/MediaBrowser.Controller/Entities/Audio/Audio.cs b/MediaBrowser.Controller/Entities/Audio/Audio.cs index 67b21068ae..a700d0be48 100644 --- a/MediaBrowser.Controller/Entities/Audio/Audio.cs +++ b/MediaBrowser.Controller/Entities/Audio/Audio.cs @@ -1,12 +1,12 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text.Json.Serialization; using MediaBrowser.Controller.Persistence; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.Entities.Audio { @@ -21,11 +21,11 @@ namespace MediaBrowser.Controller.Entities.Audio IHasMediaSources { /// - [IgnoreDataMember] + [JsonIgnore] public IReadOnlyList Artists { get; set; } /// - [IgnoreDataMember] + [JsonIgnore] public IReadOnlyList AlbumArtists { get; set; } public Audio() @@ -39,22 +39,22 @@ namespace MediaBrowser.Controller.Entities.Audio return 1; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPlayedStatus => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPeople => false; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsAddingToPlaylist => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsInheritedParentImages => true; - [IgnoreDataMember] + [JsonIgnore] protected override bool SupportsOwnedItems => false; - [IgnoreDataMember] + [JsonIgnore] public override Folder LatestItemsIndexContainer => AlbumEntity; public override bool CanDownload() @@ -62,14 +62,14 @@ namespace MediaBrowser.Controller.Entities.Audio return IsFileProtocol; } - [IgnoreDataMember] + [JsonIgnore] public MusicAlbum AlbumEntity => FindParent(); /// /// Gets the type of the media. /// /// The type of the media. - [IgnoreDataMember] + [JsonIgnore] public override string MediaType => Model.Entities.MediaType.Audio; /// diff --git a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs index edf6ffa213..c216176e7f 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Dto; @@ -8,7 +9,6 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Users; namespace MediaBrowser.Controller.Entities.Audio @@ -30,13 +30,13 @@ namespace MediaBrowser.Controller.Entities.Audio AlbumArtists = Array.Empty(); } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsAddingToPlaylist => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsInheritedParentImages => true; - [IgnoreDataMember] + [JsonIgnore] public MusicArtist MusicArtist => GetMusicArtist(new DtoOptions(true)); public MusicArtist GetMusicArtist(DtoOptions options) @@ -58,23 +58,23 @@ namespace MediaBrowser.Controller.Entities.Audio return null; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPlayedStatus => false; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsCumulativeRunTimeTicks => true; - [IgnoreDataMember] + [JsonIgnore] public string AlbumArtist => AlbumArtists.FirstOrDefault(); - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPeople => false; /// /// Gets the tracks. /// /// The tracks. - [IgnoreDataMember] + [JsonIgnore] public IEnumerable public class MusicArtist : Folder, IItemByName, IHasMusicGenres, IHasDualAccess, IHasLookupInfo { - [IgnoreDataMember] + [JsonIgnore] public bool IsAccessedByName => ParentId.Equals(Guid.Empty); - [IgnoreDataMember] + [JsonIgnore] public override bool IsFolder => !IsAccessedByName; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsInheritedParentImages => false; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsCumulativeRunTimeTicks => true; - [IgnoreDataMember] + [JsonIgnore] public override bool IsDisplayedAsFolder => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsAddingToPlaylist => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPlayedStatus => false; public override double GetDefaultPrimaryImageAspectRatio() @@ -60,7 +60,7 @@ namespace MediaBrowser.Controller.Entities.Audio return LibraryManager.GetItemList(query); } - [IgnoreDataMember] + [JsonIgnore] public override IEnumerable Children { get @@ -117,7 +117,7 @@ namespace MediaBrowser.Controller.Entities.Audio /// If the item is a folder, it returns the folder itself /// /// The containing folder path. - [IgnoreDataMember] + [JsonIgnore] public override string ContainingFolderPath => Path; /// @@ -164,7 +164,7 @@ namespace MediaBrowser.Controller.Entities.Audio return info; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPeople => false; public static string GetPath(string name) diff --git a/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs b/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs index d26aaf2bb1..537e9630be 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; +using System.Text.Json.Serialization; using MediaBrowser.Controller.Extensions; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities.Audio @@ -23,13 +23,13 @@ namespace MediaBrowser.Controller.Entities.Audio return GetUserDataKeys()[0]; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsAddingToPlaylist => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsAncestors => false; - [IgnoreDataMember] + [JsonIgnore] public override bool IsDisplayedAsFolder => true; /// @@ -37,7 +37,7 @@ namespace MediaBrowser.Controller.Entities.Audio /// If the item is a folder, it returns the folder itself /// /// The containing folder path. - [IgnoreDataMember] + [JsonIgnore] public override string ContainingFolderPath => Path; public override double GetDefaultPrimaryImageAspectRatio() @@ -55,7 +55,7 @@ namespace MediaBrowser.Controller.Entities.Audio return true; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPeople => false; public IList GetTaggedItems(InternalItemsQuery query) diff --git a/MediaBrowser.Controller/Entities/AudioBook.cs b/MediaBrowser.Controller/Entities/AudioBook.cs index 65c8a5fdd0..a13873bf96 100644 --- a/MediaBrowser.Controller/Entities/AudioBook.cs +++ b/MediaBrowser.Controller/Entities/AudioBook.cs @@ -1,23 +1,23 @@ using System; +using System.Text.Json.Serialization; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.Entities { public class AudioBook : Audio.Audio, IHasSeries, IHasLookupInfo { - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPositionTicksResume => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPlayedStatus => true; - [IgnoreDataMember] + [JsonIgnore] public string SeriesPresentationUniqueKey { get; set; } - [IgnoreDataMember] + [JsonIgnore] public string SeriesName { get; set; } - [IgnoreDataMember] + [JsonIgnore] public Guid SeriesId { get; set; } public string FindSeriesSortName() diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index c3dc6f7f2d..1fd706857a 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -4,6 +4,7 @@ using System.Globalization; using System.IO; using System.Linq; using System.Text; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Extensions; @@ -25,7 +26,6 @@ using MediaBrowser.Model.Library; using MediaBrowser.Model.LiveTv; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Providers; -using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Users; using Microsoft.Extensions.Logging; @@ -40,7 +40,7 @@ namespace MediaBrowser.Controller.Entities /// The supported image extensions /// public static readonly string[] SupportedImageExtensions - = new [] { ".png", ".jpg", ".jpeg", ".tbn", ".gif" }; + = new[] { ".png", ".jpg", ".jpeg", ".tbn", ".gif" }; private static readonly List _supportedExtensions = new List(SupportedImageExtensions) { @@ -98,62 +98,62 @@ namespace MediaBrowser.Controller.Entities SampleFolderName }; - [IgnoreDataMember] + [JsonIgnore] public Guid[] ThemeSongIds { get; set; } - [IgnoreDataMember] + [JsonIgnore] public Guid[] ThemeVideoIds { get; set; } - [IgnoreDataMember] + [JsonIgnore] public string PreferredMetadataCountryCode { get; set; } - [IgnoreDataMember] + [JsonIgnore] public string PreferredMetadataLanguage { get; set; } public long? Size { get; set; } public string Container { get; set; } - [IgnoreDataMember] + [JsonIgnore] public string Tagline { get; set; } - [IgnoreDataMember] + [JsonIgnore] public virtual ItemImageInfo[] ImageInfos { get; set; } - [IgnoreDataMember] + [JsonIgnore] public bool IsVirtualItem { get; set; } /// /// Gets or sets the album. /// /// The album. - [IgnoreDataMember] + [JsonIgnore] public string Album { get; set; } /// /// Gets or sets the channel identifier. /// /// The channel identifier. - [IgnoreDataMember] + [JsonIgnore] public Guid ChannelId { get; set; } - [IgnoreDataMember] + [JsonIgnore] public virtual bool SupportsAddingToPlaylist => false; - [IgnoreDataMember] + [JsonIgnore] public virtual bool AlwaysScanInternalMetadataPath => false; /// /// Gets a value indicating whether this instance is in mixed folder. /// /// true if this instance is in mixed folder; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public bool IsInMixedFolder { get; set; } - [IgnoreDataMember] + [JsonIgnore] public virtual bool SupportsPlayedStatus => false; - [IgnoreDataMember] + [JsonIgnore] public virtual bool SupportsPositionTicksResume => false; - [IgnoreDataMember] + [JsonIgnore] public virtual bool SupportsRemoteImageDownloading => true; private string _name; @@ -161,7 +161,7 @@ namespace MediaBrowser.Controller.Entities /// Gets or sets the name. /// /// The name. - [IgnoreDataMember] + [JsonIgnore] public virtual string Name { get => _name; @@ -174,35 +174,35 @@ namespace MediaBrowser.Controller.Entities } } - [IgnoreDataMember] + [JsonIgnore] public bool IsUnaired => PremiereDate.HasValue && PremiereDate.Value.ToLocalTime().Date >= DateTime.Now.Date; - [IgnoreDataMember] + [JsonIgnore] public int? TotalBitrate { get; set; } - [IgnoreDataMember] + [JsonIgnore] public ExtraType? ExtraType { get; set; } - [IgnoreDataMember] + [JsonIgnore] public bool IsThemeMedia => ExtraType.HasValue && (ExtraType.Value == Model.Entities.ExtraType.ThemeSong || ExtraType.Value == Model.Entities.ExtraType.ThemeVideo); - [IgnoreDataMember] + [JsonIgnore] public string OriginalTitle { get; set; } /// /// Gets or sets the id. /// /// The id. - [IgnoreDataMember] + [JsonIgnore] public Guid Id { get; set; } - [IgnoreDataMember] + [JsonIgnore] public Guid OwnerId { get; set; } /// /// Gets or sets the audio. /// /// The audio. - [IgnoreDataMember] + [JsonIgnore] public ProgramAudio? Audio { get; set; } /// @@ -210,7 +210,7 @@ namespace MediaBrowser.Controller.Entities /// Default is based on the type for everything except actual generic folders. /// /// The display prefs id. - [IgnoreDataMember] + [JsonIgnore] public virtual Guid DisplayPreferencesId { get @@ -224,10 +224,10 @@ namespace MediaBrowser.Controller.Entities /// Gets or sets the path. /// /// The path. - [IgnoreDataMember] + [JsonIgnore] public virtual string Path { get; set; } - [IgnoreDataMember] + [JsonIgnore] public virtual SourceType SourceType { get @@ -245,7 +245,7 @@ namespace MediaBrowser.Controller.Entities /// Returns the folder containing the item. /// If the item is a folder, it returns the folder itself /// - [IgnoreDataMember] + [JsonIgnore] public virtual string ContainingFolderPath { get @@ -263,26 +263,26 @@ namespace MediaBrowser.Controller.Entities /// Gets or sets the name of the service. /// /// The name of the service. - [IgnoreDataMember] + [JsonIgnore] public string ServiceName { get; set; } /// /// If this content came from an external service, the id of the content on that service /// - [IgnoreDataMember] + [JsonIgnore] public string ExternalId { get; set; } - [IgnoreDataMember] + [JsonIgnore] public string ExternalSeriesId { get; set; } /// /// Gets or sets the etag. /// /// The etag. - [IgnoreDataMember] + [JsonIgnore] public string ExternalEtag { get; set; } - [IgnoreDataMember] + [JsonIgnore] public virtual bool IsHidden => false; public BaseItem GetOwner() @@ -295,7 +295,7 @@ namespace MediaBrowser.Controller.Entities /// Gets or sets the type of the location. /// /// The type of the location. - [IgnoreDataMember] + [JsonIgnore] public virtual LocationType LocationType { get @@ -320,7 +320,7 @@ namespace MediaBrowser.Controller.Entities } } - [IgnoreDataMember] + [JsonIgnore] public MediaProtocol? PathProtocol { get @@ -343,13 +343,13 @@ namespace MediaBrowser.Controller.Entities return current.HasValue && current.Value == protocol; } - [IgnoreDataMember] + [JsonIgnore] public bool IsFileProtocol => IsPathProtocol(MediaProtocol.File); - [IgnoreDataMember] + [JsonIgnore] public bool HasPathProtocol => PathProtocol.HasValue; - [IgnoreDataMember] + [JsonIgnore] public virtual bool SupportsLocalMetadata { get @@ -363,7 +363,7 @@ namespace MediaBrowser.Controller.Entities } } - [IgnoreDataMember] + [JsonIgnore] public virtual string FileNameWithoutExtension { get @@ -377,7 +377,7 @@ namespace MediaBrowser.Controller.Entities } } - [IgnoreDataMember] + [JsonIgnore] public virtual bool EnableAlphaNumericSorting => true; private List> GetSortChunks(string s1) @@ -418,7 +418,7 @@ namespace MediaBrowser.Controller.Entities /// This is just a helper for convenience /// /// The primary image path. - [IgnoreDataMember] + [JsonIgnore] public string PrimaryImagePath => this.GetImagePath(ImageType.Primary); public bool IsMetadataFetcherEnabled(LibraryOptions libraryOptions, string name) @@ -544,20 +544,20 @@ namespace MediaBrowser.Controller.Entities /// Gets or sets the date created. /// /// The date created. - [IgnoreDataMember] + [JsonIgnore] public DateTime DateCreated { get; set; } /// /// Gets or sets the date modified. /// /// The date modified. - [IgnoreDataMember] + [JsonIgnore] public DateTime DateModified { get; set; } - [IgnoreDataMember] + [JsonIgnore] public DateTime DateLastSaved { get; set; } - [IgnoreDataMember] + [JsonIgnore] public DateTime DateLastRefreshed { get; set; } /// @@ -583,24 +583,24 @@ namespace MediaBrowser.Controller.Entities return Name; } - [IgnoreDataMember] + [JsonIgnore] public bool IsLocked { get; set; } /// /// Gets or sets the locked fields. /// /// The locked fields. - [IgnoreDataMember] + [JsonIgnore] public MetadataFields[] LockedFields { get; set; } /// /// Gets the type of the media. /// /// The type of the media. - [IgnoreDataMember] + [JsonIgnore] public virtual string MediaType => null; - [IgnoreDataMember] + [JsonIgnore] public virtual string[] PhysicalLocations { get @@ -619,7 +619,7 @@ namespace MediaBrowser.Controller.Entities /// Gets or sets the name of the forced sort. /// /// The name of the forced sort. - [IgnoreDataMember] + [JsonIgnore] public string ForcedSortName { get => _forcedSortName; @@ -631,7 +631,7 @@ namespace MediaBrowser.Controller.Entities /// Gets the name of the sort. /// /// The name of the sort. - [IgnoreDataMember] + [JsonIgnore] public string SortName { get @@ -744,7 +744,7 @@ namespace MediaBrowser.Controller.Entities return builder.ToString().RemoveDiacritics(); } - [IgnoreDataMember] + [JsonIgnore] public bool EnableMediaSourceDisplay { get @@ -758,14 +758,14 @@ namespace MediaBrowser.Controller.Entities } } - [IgnoreDataMember] + [JsonIgnore] public Guid ParentId { get; set; } /// /// Gets or sets the parent. /// /// The parent. - [IgnoreDataMember] + [JsonIgnore] public Folder Parent { get => GetParent() as Folder; @@ -822,7 +822,7 @@ namespace MediaBrowser.Controller.Entities return null; } - [IgnoreDataMember] + [JsonIgnore] public virtual Guid DisplayParentId { get @@ -832,7 +832,7 @@ namespace MediaBrowser.Controller.Entities } } - [IgnoreDataMember] + [JsonIgnore] public BaseItem DisplayParent { get @@ -850,97 +850,97 @@ namespace MediaBrowser.Controller.Entities /// When the item first debuted. For movies this could be premiere date, episodes would be first aired /// /// The premiere date. - [IgnoreDataMember] + [JsonIgnore] public DateTime? PremiereDate { get; set; } /// /// Gets or sets the end date. /// /// The end date. - [IgnoreDataMember] + [JsonIgnore] public DateTime? EndDate { get; set; } /// /// Gets or sets the official rating. /// /// The official rating. - [IgnoreDataMember] + [JsonIgnore] public string OfficialRating { get; set; } - [IgnoreDataMember] + [JsonIgnore] public int InheritedParentalRatingValue { get; set; } /// /// Gets or sets the critic rating. /// /// The critic rating. - [IgnoreDataMember] + [JsonIgnore] public float? CriticRating { get; set; } /// /// Gets or sets the custom rating. /// /// The custom rating. - [IgnoreDataMember] + [JsonIgnore] public string CustomRating { get; set; } /// /// Gets or sets the overview. /// /// The overview. - [IgnoreDataMember] + [JsonIgnore] public string Overview { get; set; } /// /// Gets or sets the studios. /// /// The studios. - [IgnoreDataMember] + [JsonIgnore] public string[] Studios { get; set; } /// /// Gets or sets the genres. /// /// The genres. - [IgnoreDataMember] + [JsonIgnore] public string[] Genres { get; set; } /// /// Gets or sets the tags. /// /// The tags. - [IgnoreDataMember] + [JsonIgnore] public string[] Tags { get; set; } - [IgnoreDataMember] + [JsonIgnore] public string[] ProductionLocations { get; set; } /// /// Gets or sets the home page URL. /// /// The home page URL. - [IgnoreDataMember] + [JsonIgnore] public string HomePageUrl { get; set; } /// /// Gets or sets the community rating. /// /// The community rating. - [IgnoreDataMember] + [JsonIgnore] public float? CommunityRating { get; set; } /// /// Gets or sets the run time ticks. /// /// The run time ticks. - [IgnoreDataMember] + [JsonIgnore] public long? RunTimeTicks { get; set; } /// /// Gets or sets the production year. /// /// The production year. - [IgnoreDataMember] + [JsonIgnore] public int? ProductionYear { get; set; } /// @@ -948,20 +948,20 @@ namespace MediaBrowser.Controller.Entities /// This could be episode number, album track number, etc. /// /// The index number. - [IgnoreDataMember] + [JsonIgnore] public int? IndexNumber { get; set; } /// /// For an episode this could be the season number, or for a song this could be the disc number. /// /// The parent index number. - [IgnoreDataMember] + [JsonIgnore] public int? ParentIndexNumber { get; set; } - [IgnoreDataMember] + [JsonIgnore] public virtual bool HasLocalAlternateVersions => false; - [IgnoreDataMember] + [JsonIgnore] public string OfficialRatingForComparison { get @@ -982,7 +982,7 @@ namespace MediaBrowser.Controller.Entities } } - [IgnoreDataMember] + [JsonIgnore] public string CustomRatingForComparison { get @@ -1344,7 +1344,7 @@ namespace MediaBrowser.Controller.Entities public Task RefreshMetadata(CancellationToken cancellationToken) { - return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem)), cancellationToken); + return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken); } protected virtual void TriggerOnRefreshStart() @@ -1407,13 +1407,13 @@ namespace MediaBrowser.Controller.Entities } } - [IgnoreDataMember] + [JsonIgnore] protected virtual bool SupportsOwnedItems => !ParentId.Equals(Guid.Empty) && IsFileProtocol; - [IgnoreDataMember] + [JsonIgnore] public virtual bool SupportsPeople => false; - [IgnoreDataMember] + [JsonIgnore] public virtual bool SupportsThemeMedia => false; /// @@ -1613,10 +1613,10 @@ namespace MediaBrowser.Controller.Entities /// Gets or sets the provider ids. /// /// The provider ids. - [IgnoreDataMember] + [JsonIgnore] public Dictionary ProviderIds { get; set; } - [IgnoreDataMember] + [JsonIgnore] public virtual Folder LatestItemsIndexContainer => null; public virtual double GetDefaultPrimaryImageAspectRatio() @@ -1629,7 +1629,7 @@ namespace MediaBrowser.Controller.Entities return Id.ToString("N", CultureInfo.InvariantCulture); } - [IgnoreDataMember] + [JsonIgnore] public string PresentationUniqueKey { get; set; } public string GetPresentationUniqueKey() @@ -1934,7 +1934,7 @@ namespace MediaBrowser.Controller.Entities return IsVisibleStandaloneInternal(user, true); } - [IgnoreDataMember] + [JsonIgnore] public virtual bool SupportsInheritedParentImages => false; protected bool IsVisibleStandaloneInternal(User user, bool checkFolders) @@ -1977,10 +1977,10 @@ namespace MediaBrowser.Controller.Entities /// Gets a value indicating whether this instance is folder. /// /// true if this instance is folder; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public virtual bool IsFolder => false; - [IgnoreDataMember] + [JsonIgnore] public virtual bool IsDisplayedAsFolder => false; public virtual string GetClientTypeName() @@ -2066,7 +2066,7 @@ namespace MediaBrowser.Controller.Entities return null; } - [IgnoreDataMember] + [JsonIgnore] public virtual bool EnableRememberingTrackSelections => true; /// @@ -2197,7 +2197,7 @@ namespace MediaBrowser.Controller.Entities /// Task. public virtual void ChangedExternally() { - ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem)) + ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(new DirectoryService(FileSystem)) { }, RefreshPriority.High); @@ -2776,7 +2776,7 @@ namespace MediaBrowser.Controller.Entities return null; } - [IgnoreDataMember] + [JsonIgnore] public virtual bool IsTopParent { get @@ -2804,10 +2804,10 @@ namespace MediaBrowser.Controller.Entities } } - [IgnoreDataMember] + [JsonIgnore] public virtual bool SupportsAncestors => true; - [IgnoreDataMember] + [JsonIgnore] public virtual bool StopRefreshIfLocalMetadataFound => true; public virtual IEnumerable GetIdsForAncestorQuery() diff --git a/MediaBrowser.Controller/Entities/BasePluginFolder.cs b/MediaBrowser.Controller/Entities/BasePluginFolder.cs index 8cdb9695cc..62d172fcc1 100644 --- a/MediaBrowser.Controller/Entities/BasePluginFolder.cs +++ b/MediaBrowser.Controller/Entities/BasePluginFolder.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Serialization; +using System.Text.Json.Serialization; namespace MediaBrowser.Controller.Entities { @@ -8,7 +8,7 @@ namespace MediaBrowser.Controller.Entities /// public abstract class BasePluginFolder : Folder, ICollectionFolder { - [IgnoreDataMember] + [JsonIgnore] public virtual string CollectionType => null; public override bool CanDelete() @@ -21,10 +21,10 @@ namespace MediaBrowser.Controller.Entities return true; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsInheritedParentImages => false; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPeople => false; //public override double? GetDefaultPrimaryImageAspectRatio() diff --git a/MediaBrowser.Controller/Entities/Book.cs b/MediaBrowser.Controller/Entities/Book.cs index 7a23d9a663..44c35374d7 100644 --- a/MediaBrowser.Controller/Entities/Book.cs +++ b/MediaBrowser.Controller/Entities/Book.cs @@ -1,21 +1,21 @@ using System; using System.Linq; +using System.Text.Json.Serialization; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.Entities { public class Book : BaseItem, IHasLookupInfo, IHasSeries { - [IgnoreDataMember] + [JsonIgnore] public override string MediaType => Model.Entities.MediaType.Book; - [IgnoreDataMember] + [JsonIgnore] public string SeriesPresentationUniqueKey { get; set; } - [IgnoreDataMember] + [JsonIgnore] public string SeriesName { get; set; } - [IgnoreDataMember] + [JsonIgnore] public Guid SeriesId { get; set; } public string FindSeriesSortName() diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs index 275052d48a..e5adf88d12 100644 --- a/MediaBrowser.Controller/Entities/CollectionFolder.cs +++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs @@ -2,14 +2,13 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; - using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; -using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; using MediaBrowser.Model.Serialization; @@ -33,10 +32,10 @@ namespace MediaBrowser.Controller.Entities PhysicalFolderIds = Array.Empty(); } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPlayedStatus => false; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsInheritedParentImages => false; public override bool CanDelete() @@ -144,10 +143,10 @@ namespace MediaBrowser.Controller.Entities /// Allow different display preferences for each collection folder /// /// The display prefs id. - [IgnoreDataMember] + [JsonIgnore] public override Guid DisplayPreferencesId => Id; - [IgnoreDataMember] + [JsonIgnore] public override string[] PhysicalLocations => PhysicalLocationsList; public override bool IsSaveLocalMetadataEnabled() @@ -172,7 +171,7 @@ namespace MediaBrowser.Controller.Entities { var locations = PhysicalLocations; - var newLocations = CreateResolveArgs(new DirectoryService(Logger, FileSystem), false).PhysicalLocations; + var newLocations = CreateResolveArgs(new DirectoryService(FileSystem), false).PhysicalLocations; if (!locations.SequenceEqual(newLocations)) { @@ -311,7 +310,7 @@ namespace MediaBrowser.Controller.Entities /// Our children are actually just references to the ones in the physical root... /// /// The actual children. - [IgnoreDataMember] + [JsonIgnore] public override IEnumerable Children => GetActualChildren(); public IEnumerable GetActualChildren() @@ -361,7 +360,7 @@ namespace MediaBrowser.Controller.Entities return result; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPeople => false; } } diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 8e9d110122..07fbe60350 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Progress; @@ -18,7 +19,6 @@ using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Dto; using MediaBrowser.Model.IO; using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities @@ -39,7 +39,7 @@ namespace MediaBrowser.Controller.Entities public LinkedChild[] LinkedChildren { get; set; } - [IgnoreDataMember] + [JsonIgnore] public DateTime? DateLastMediaAdded { get; set; } public Folder() @@ -47,35 +47,35 @@ namespace MediaBrowser.Controller.Entities LinkedChildren = Array.Empty(); } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsThemeMedia => true; - [IgnoreDataMember] + [JsonIgnore] public virtual bool IsPreSorted => false; - [IgnoreDataMember] + [JsonIgnore] public virtual bool IsPhysicalRoot => false; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsInheritedParentImages => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPlayedStatus => true; /// /// Gets a value indicating whether this instance is folder. /// /// true if this instance is folder; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public override bool IsFolder => true; - [IgnoreDataMember] + [JsonIgnore] public override bool IsDisplayedAsFolder => true; - [IgnoreDataMember] + [JsonIgnore] public virtual bool SupportsCumulativeRunTimeTicks => false; - [IgnoreDataMember] + [JsonIgnore] public virtual bool SupportsDateLastMediaAdded => false; public override bool CanDelete() @@ -100,7 +100,7 @@ namespace MediaBrowser.Controller.Entities return baseResult; } - [IgnoreDataMember] + [JsonIgnore] public override string FileNameWithoutExtension { get @@ -127,7 +127,7 @@ namespace MediaBrowser.Controller.Entities return true; } - [IgnoreDataMember] + [JsonIgnore] protected virtual bool SupportsShortcutChildren => false; /// @@ -162,14 +162,14 @@ namespace MediaBrowser.Controller.Entities /// Gets the actual children. /// /// The actual children. - [IgnoreDataMember] + [JsonIgnore] public virtual IEnumerable Children => LoadChildren(); /// /// thread-safe access to all recursive children of this folder - without regard to user /// /// The recursive children. - [IgnoreDataMember] + [JsonIgnore] public IEnumerable RecursiveChildren => GetRecursiveChildren(); public override bool IsVisible(User user) @@ -216,7 +216,7 @@ namespace MediaBrowser.Controller.Entities public Task ValidateChildren(IProgress progress, CancellationToken cancellationToken) { - return ValidateChildren(progress, cancellationToken, new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem))); + return ValidateChildren(progress, cancellationToken, new MetadataRefreshOptions(new DirectoryService(FileSystem))); } /// @@ -1152,6 +1152,11 @@ namespace MediaBrowser.Controller.Entities public List GetChildren(User user, bool includeLinkedChildren) { + if (user == null) + { + throw new ArgumentNullException(nameof(user)); + } + return GetChildren(user, includeLinkedChildren, null); } @@ -1431,7 +1436,7 @@ namespace MediaBrowser.Controller.Entities .Where(i => i.Item2 != null); } - [IgnoreDataMember] + [JsonIgnore] protected override bool SupportsOwnedItems => base.SupportsOwnedItems || SupportsShortcutChildren; protected override async Task RefreshedOwnedItems(MetadataRefreshOptions options, List fileSystemChildren, CancellationToken cancellationToken) @@ -1598,7 +1603,7 @@ namespace MediaBrowser.Controller.Entities return !IsPlayed(user); } - [IgnoreDataMember] + [JsonIgnore] public virtual bool SupportsUserDataFromChildren { get diff --git a/MediaBrowser.Controller/Entities/Genre.cs b/MediaBrowser.Controller/Entities/Genre.cs index 44cb62d225..773c7df341 100644 --- a/MediaBrowser.Controller/Entities/Genre.cs +++ b/MediaBrowser.Controller/Entities/Genre.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; +using System.Text.Json.Serialization; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Extensions; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities @@ -34,13 +34,13 @@ namespace MediaBrowser.Controller.Entities /// If the item is a folder, it returns the folder itself /// /// The containing folder path. - [IgnoreDataMember] + [JsonIgnore] public override string ContainingFolderPath => Path; - [IgnoreDataMember] + [JsonIgnore] public override bool IsDisplayedAsFolder => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsAncestors => false; public override bool IsSaveLocalMetadataEnabled() @@ -61,7 +61,7 @@ namespace MediaBrowser.Controller.Entities return LibraryManager.GetItemList(query); } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPeople => false; public static string GetPath(string name) diff --git a/MediaBrowser.Controller/Entities/ICollectionFolder.cs b/MediaBrowser.Controller/Entities/ICollectionFolder.cs index a6a9a07836..4f0760746e 100644 --- a/MediaBrowser.Controller/Entities/ICollectionFolder.cs +++ b/MediaBrowser.Controller/Entities/ICollectionFolder.cs @@ -8,8 +8,11 @@ namespace MediaBrowser.Controller.Entities public interface ICollectionFolder : IHasCollectionType { string Path { get; } + string Name { get; } + Guid Id { get; } + string[] PhysicalLocations { get; } } diff --git a/MediaBrowser.Controller/Entities/ItemImageInfo.cs b/MediaBrowser.Controller/Entities/ItemImageInfo.cs index 8484938642..fc46dec2ef 100644 --- a/MediaBrowser.Controller/Entities/ItemImageInfo.cs +++ b/MediaBrowser.Controller/Entities/ItemImageInfo.cs @@ -1,6 +1,6 @@ using System; +using System.Text.Json.Serialization; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.Entities { @@ -28,7 +28,7 @@ namespace MediaBrowser.Controller.Entities public int Height { get; set; } - [IgnoreDataMember] + [JsonIgnore] public bool IsLocalFile => Path == null || !Path.StartsWith("http", StringComparison.OrdinalIgnoreCase); } } diff --git a/MediaBrowser.Controller/Entities/LinkedChild.cs b/MediaBrowser.Controller/Entities/LinkedChild.cs index 8230604888..d88c31007a 100644 --- a/MediaBrowser.Controller/Entities/LinkedChild.cs +++ b/MediaBrowser.Controller/Entities/LinkedChild.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.Globalization; +using System.Text.Json.Serialization; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.Entities { @@ -12,7 +12,7 @@ namespace MediaBrowser.Controller.Entities public LinkedChildType Type { get; set; } public string LibraryItemId { get; set; } - [IgnoreDataMember] + [JsonIgnore] public string Id { get; set; } /// diff --git a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs index e7ac2a05c2..feaf8c45ac 100644 --- a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs +++ b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text.Json.Serialization; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Users; namespace MediaBrowser.Controller.Entities.Movies @@ -24,13 +24,13 @@ namespace MediaBrowser.Controller.Entities.Movies DisplayOrder = ItemSortBy.PremiereDate; } - [IgnoreDataMember] + [JsonIgnore] protected override bool FilterLinkedChildrenPerUser => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsInheritedParentImages => false; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPeople => true; /// @@ -79,7 +79,7 @@ namespace MediaBrowser.Controller.Entities.Movies return new List(); } - [IgnoreDataMember] + [JsonIgnore] private bool IsLegacyBoxSet { get @@ -98,7 +98,7 @@ namespace MediaBrowser.Controller.Entities.Movies } } - [IgnoreDataMember] + [JsonIgnore] public override bool IsPreSorted => true; public override bool IsAuthorizedToDelete(User user, List allCollectionFolders) diff --git a/MediaBrowser.Controller/Entities/Movies/Movie.cs b/MediaBrowser.Controller/Entities/Movies/Movie.cs index 184528fdc1..11dc472b61 100644 --- a/MediaBrowser.Controller/Entities/Movies/Movie.cs +++ b/MediaBrowser.Controller/Entities/Movies/Movie.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Providers; @@ -8,7 +9,6 @@ using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.Providers; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.Entities.Movies { @@ -39,7 +39,7 @@ namespace MediaBrowser.Controller.Entities.Movies /// The name of the TMDB collection. public string TmdbCollectionName { get; set; } - [IgnoreDataMember] + [JsonIgnore] public string CollectionName { get => TmdbCollectionName; @@ -186,7 +186,7 @@ namespace MediaBrowser.Controller.Entities.Movies return list; } - [IgnoreDataMember] + [JsonIgnore] public override bool StopRefreshIfLocalMetadataFound => false; } } diff --git a/MediaBrowser.Controller/Entities/MusicVideo.cs b/MediaBrowser.Controller/Entities/MusicVideo.cs index 94fe11e9da..6032420635 100644 --- a/MediaBrowser.Controller/Entities/MusicVideo.cs +++ b/MediaBrowser.Controller/Entities/MusicVideo.cs @@ -1,16 +1,16 @@ using System; using System.Collections.Generic; +using System.Text.Json.Serialization; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.Entities { public class MusicVideo : Video, IHasArtist, IHasMusicGenres, IHasLookupInfo { /// - [IgnoreDataMember] + [JsonIgnore] public IReadOnlyList Artists { get; set; } public MusicVideo() diff --git a/MediaBrowser.Controller/Entities/Person.cs b/MediaBrowser.Controller/Entities/Person.cs index dd01834898..d9b4b22067 100644 --- a/MediaBrowser.Controller/Entities/Person.cs +++ b/MediaBrowser.Controller/Entities/Person.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; +using System.Text.Json.Serialization; using MediaBrowser.Controller.Extensions; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities @@ -50,7 +50,7 @@ namespace MediaBrowser.Controller.Entities /// If the item is a folder, it returns the folder itself /// /// The containing folder path. - [IgnoreDataMember] + [JsonIgnore] public override string ContainingFolderPath => Path; public override bool CanDelete() @@ -63,13 +63,13 @@ namespace MediaBrowser.Controller.Entities return true; } - [IgnoreDataMember] + [JsonIgnore] public override bool EnableAlphaNumericSorting => false; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPeople => false; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsAncestors => false; public static string GetPath(string name) diff --git a/MediaBrowser.Controller/Entities/Photo.cs b/MediaBrowser.Controller/Entities/Photo.cs index 60c8321893..86d62add97 100644 --- a/MediaBrowser.Controller/Entities/Photo.cs +++ b/MediaBrowser.Controller/Entities/Photo.cs @@ -1,21 +1,21 @@ +using System.Text.Json.Serialization; using MediaBrowser.Model.Drawing; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.Entities { public class Photo : BaseItem { - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsLocalMetadata => false; - [IgnoreDataMember] + [JsonIgnore] public override string MediaType => Model.Entities.MediaType.Photo; - [IgnoreDataMember] + [JsonIgnore] public override Folder LatestItemsIndexContainer => AlbumEntity; - [IgnoreDataMember] + [JsonIgnore] public PhotoAlbum AlbumEntity { get diff --git a/MediaBrowser.Controller/Entities/PhotoAlbum.cs b/MediaBrowser.Controller/Entities/PhotoAlbum.cs index 4cd0c8b668..b86f1ac2ae 100644 --- a/MediaBrowser.Controller/Entities/PhotoAlbum.cs +++ b/MediaBrowser.Controller/Entities/PhotoAlbum.cs @@ -1,16 +1,16 @@ -using MediaBrowser.Model.Serialization; +using System.Text.Json.Serialization; namespace MediaBrowser.Controller.Entities { public class PhotoAlbum : Folder { - [IgnoreDataMember] + [JsonIgnore] public override bool AlwaysScanInternalMetadataPath => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPlayedStatus => false; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsInheritedParentImages => false; } } diff --git a/MediaBrowser.Controller/Entities/Studio.cs b/MediaBrowser.Controller/Entities/Studio.cs index d6da0d48c7..068032317d 100644 --- a/MediaBrowser.Controller/Entities/Studio.cs +++ b/MediaBrowser.Controller/Entities/Studio.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; +using System.Text.Json.Serialization; using MediaBrowser.Controller.Extensions; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities @@ -28,13 +28,13 @@ namespace MediaBrowser.Controller.Entities /// If the item is a folder, it returns the folder itself /// /// The containing folder path. - [IgnoreDataMember] + [JsonIgnore] public override string ContainingFolderPath => Path; - [IgnoreDataMember] + [JsonIgnore] public override bool IsDisplayedAsFolder => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsAncestors => false; public override double GetDefaultPrimaryImageAspectRatio() @@ -62,7 +62,7 @@ namespace MediaBrowser.Controller.Entities return LibraryManager.GetItemList(query); } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPeople => false; public static string GetPath(string name) diff --git a/MediaBrowser.Controller/Entities/TV/Episode.cs b/MediaBrowser.Controller/Entities/TV/Episode.cs index e67c00fed9..49229fa4be 100644 --- a/MediaBrowser.Controller/Entities/TV/Episode.cs +++ b/MediaBrowser.Controller/Entities/TV/Episode.cs @@ -2,11 +2,11 @@ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Text.Json.Serialization; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities.TV @@ -49,25 +49,25 @@ namespace MediaBrowser.Controller.Entities.TV return series == null ? SeriesName : series.SortName; } - [IgnoreDataMember] + [JsonIgnore] protected override bool SupportsOwnedItems => IsStacked || MediaSourceCount > 1; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsInheritedParentImages => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPeople => true; - [IgnoreDataMember] + [JsonIgnore] public int? AiredSeasonNumber => AirsAfterSeasonNumber ?? AirsBeforeSeasonNumber ?? ParentIndexNumber; - [IgnoreDataMember] + [JsonIgnore] public override Folder LatestItemsIndexContainer => Series; - [IgnoreDataMember] + [JsonIgnore] public override Guid DisplayParentId => SeasonId; - [IgnoreDataMember] + [JsonIgnore] protected override bool EnableDefaultVideoUserDataKeys => false; public override double GetDefaultPrimaryImageAspectRatio() @@ -104,7 +104,7 @@ namespace MediaBrowser.Controller.Entities.TV /// This Episode's Series Instance /// /// The series. - [IgnoreDataMember] + [JsonIgnore] public Series Series { get @@ -118,7 +118,7 @@ namespace MediaBrowser.Controller.Entities.TV } } - [IgnoreDataMember] + [JsonIgnore] public Season Season { get @@ -132,16 +132,16 @@ namespace MediaBrowser.Controller.Entities.TV } } - [IgnoreDataMember] + [JsonIgnore] public bool IsInSeasonFolder => FindParent() != null; - [IgnoreDataMember] + [JsonIgnore] public string SeriesPresentationUniqueKey { get; set; } - [IgnoreDataMember] + [JsonIgnore] public string SeriesName { get; set; } - [IgnoreDataMember] + [JsonIgnore] public string SeasonName { get; set; } public string FindSeriesPresentationUniqueKey() @@ -224,7 +224,7 @@ namespace MediaBrowser.Controller.Entities.TV return false; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsRemoteImageDownloading { get @@ -238,12 +238,12 @@ namespace MediaBrowser.Controller.Entities.TV } } - [IgnoreDataMember] + [JsonIgnore] public bool IsMissingEpisode => LocationType == LocationType.Virtual; - [IgnoreDataMember] + [JsonIgnore] public Guid SeasonId { get; set; } - [IgnoreDataMember] + [JsonIgnore] public Guid SeriesId { get; set; } public Guid FindSeriesId() diff --git a/MediaBrowser.Controller/Entities/TV/Season.cs b/MediaBrowser.Controller/Entities/TV/Season.cs index 5d7c260d15..9c8a469e26 100644 --- a/MediaBrowser.Controller/Entities/TV/Season.cs +++ b/MediaBrowser.Controller/Entities/TV/Season.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text.Json.Serialization; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Users; namespace MediaBrowser.Controller.Entities.TV @@ -15,22 +15,22 @@ namespace MediaBrowser.Controller.Entities.TV /// public class Season : Folder, IHasSeries, IHasLookupInfo { - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsAddingToPlaylist => true; - [IgnoreDataMember] + [JsonIgnore] public override bool IsPreSorted => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsDateLastMediaAdded => false; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPeople => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsInheritedParentImages => true; - [IgnoreDataMember] + [JsonIgnore] public override Guid DisplayParentId => SeriesId; public override double GetDefaultPrimaryImageAspectRatio() @@ -71,7 +71,7 @@ namespace MediaBrowser.Controller.Entities.TV /// This Episode's Series Instance /// /// The series. - [IgnoreDataMember] + [JsonIgnore] public Series Series { get @@ -85,7 +85,7 @@ namespace MediaBrowser.Controller.Entities.TV } } - [IgnoreDataMember] + [JsonIgnore] public string SeriesPath { get @@ -179,13 +179,13 @@ namespace MediaBrowser.Controller.Entities.TV return UnratedItem.Series; } - [IgnoreDataMember] + [JsonIgnore] public string SeriesPresentationUniqueKey { get; set; } - [IgnoreDataMember] + [JsonIgnore] public string SeriesName { get; set; } - [IgnoreDataMember] + [JsonIgnore] public Guid SeriesId { get; set; } public string FindSeriesPresentationUniqueKey() diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs index d435551023..2475b2b7ec 100644 --- a/MediaBrowser.Controller/Entities/TV/Series.cs +++ b/MediaBrowser.Controller/Entities/TV/Series.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Dto; @@ -10,7 +11,6 @@ using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Users; namespace MediaBrowser.Controller.Entities.TV @@ -31,19 +31,19 @@ namespace MediaBrowser.Controller.Entities.TV public DayOfWeek[] AirDays { get; set; } public string AirTime { get; set; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsAddingToPlaylist => true; - [IgnoreDataMember] + [JsonIgnore] public override bool IsPreSorted => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsDateLastMediaAdded => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsInheritedParentImages => false; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPeople => true; /// @@ -506,7 +506,7 @@ namespace MediaBrowser.Controller.Entities.TV return list; } - [IgnoreDataMember] + [JsonIgnore] public override bool StopRefreshIfLocalMetadataFound => false; } } diff --git a/MediaBrowser.Controller/Entities/Trailer.cs b/MediaBrowser.Controller/Entities/Trailer.cs index 5bf22d7bc8..0b8be90cd1 100644 --- a/MediaBrowser.Controller/Entities/Trailer.cs +++ b/MediaBrowser.Controller/Entities/Trailer.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; +using System.Text.Json.Serialization; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Providers; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.Entities { @@ -93,7 +93,7 @@ namespace MediaBrowser.Controller.Entities return list; } - [IgnoreDataMember] + [JsonIgnore] public override bool StopRefreshIfLocalMetadataFound => false; } } diff --git a/MediaBrowser.Controller/Entities/User.cs b/MediaBrowser.Controller/Entities/User.cs index 7d245d4aab..53601a6104 100644 --- a/MediaBrowser.Controller/Entities/User.cs +++ b/MediaBrowser.Controller/Entities/User.cs @@ -1,12 +1,12 @@ using System; using System.Globalization; using System.IO; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; -using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Users; namespace MediaBrowser.Controller.Entities @@ -25,7 +25,7 @@ namespace MediaBrowser.Controller.Entities public string Password { get; set; } public string EasyPassword { get; set; } - // Strictly to remove IgnoreDataMember + // Strictly to remove JsonIgnore public override ItemImageInfo[] ImageInfos { get => base.ImageInfos; @@ -36,7 +36,7 @@ namespace MediaBrowser.Controller.Entities /// Gets or sets the path. /// /// The path. - [IgnoreDataMember] + [JsonIgnore] public override string Path { get => ConfigurationDirectoryPath; @@ -65,14 +65,14 @@ namespace MediaBrowser.Controller.Entities /// If the item is a folder, it returns the folder itself /// /// The containing folder path. - [IgnoreDataMember] + [JsonIgnore] public override string ContainingFolderPath => Path; /// /// Gets the root folder. /// /// The root folder. - [IgnoreDataMember] + [JsonIgnore] public Folder RootFolder => LibraryManager.GetUserRootFolder(); /// @@ -88,7 +88,7 @@ namespace MediaBrowser.Controller.Entities private volatile UserConfiguration _config; private readonly object _configSyncLock = new object(); - [IgnoreDataMember] + [JsonIgnore] public UserConfiguration Configuration { get @@ -111,7 +111,7 @@ namespace MediaBrowser.Controller.Entities private volatile UserPolicy _policy; private readonly object _policySyncLock = new object(); - [IgnoreDataMember] + [JsonIgnore] public UserPolicy Policy { get @@ -148,7 +148,7 @@ namespace MediaBrowser.Controller.Entities Name = newName; return RefreshMetadata( - new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem)) + new MetadataRefreshOptions(new DirectoryService(FileSystem)) { ReplaceAllMetadata = true, ImageRefreshMode = MetadataRefreshMode.FullRefresh, @@ -168,7 +168,7 @@ namespace MediaBrowser.Controller.Entities /// Gets the path to the user's configuration directory /// /// The configuration directory path. - [IgnoreDataMember] + [JsonIgnore] public string ConfigurationDirectoryPath => GetConfigurationDirectoryPath(Name); public override double GetDefaultPrimaryImageAspectRatio() @@ -252,7 +252,7 @@ namespace MediaBrowser.Controller.Entities return false; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPeople => false; public long InternalId { get; set; } diff --git a/MediaBrowser.Controller/Entities/UserItemData.cs b/MediaBrowser.Controller/Entities/UserItemData.cs index f7136bdf2e..ab425ee0f9 100644 --- a/MediaBrowser.Controller/Entities/UserItemData.cs +++ b/MediaBrowser.Controller/Entities/UserItemData.cs @@ -1,5 +1,5 @@ using System; -using MediaBrowser.Model.Serialization; +using System.Text.Json.Serialization; namespace MediaBrowser.Controller.Entities { @@ -93,7 +93,7 @@ namespace MediaBrowser.Controller.Entities /// This should never be serialized. /// /// null if [likes] contains no value, true if [likes]; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public bool? Likes { get diff --git a/MediaBrowser.Controller/Entities/UserRootFolder.cs b/MediaBrowser.Controller/Entities/UserRootFolder.cs index 7fe8df8af3..7fcf48a48f 100644 --- a/MediaBrowser.Controller/Entities/UserRootFolder.cs +++ b/MediaBrowser.Controller/Entities/UserRootFolder.cs @@ -1,12 +1,12 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Library; using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.Entities { @@ -33,10 +33,10 @@ namespace MediaBrowser.Controller.Entities } } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsInheritedParentImages => false; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPlayedStatus => false; private void ClearCache() @@ -75,10 +75,10 @@ namespace MediaBrowser.Controller.Entities return GetChildren(user, true).Count; } - [IgnoreDataMember] + [JsonIgnore] protected override bool SupportsShortcutChildren => true; - [IgnoreDataMember] + [JsonIgnore] public override bool IsPreSorted => true; protected override IEnumerable GetEligibleChildrenForRecursiveChildren(User user) diff --git a/MediaBrowser.Controller/Entities/UserView.cs b/MediaBrowser.Controller/Entities/UserView.cs index 4a6d32dcec..4ce9ec6f82 100644 --- a/MediaBrowser.Controller/Entities/UserView.cs +++ b/MediaBrowser.Controller/Entities/UserView.cs @@ -1,49 +1,51 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text.Json.Serialization; using System.Threading.Tasks; using MediaBrowser.Controller.TV; using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.Entities { public class UserView : Folder, IHasCollectionType { + /// public string ViewType { get; set; } + + /// public new Guid DisplayParentId { get; set; } + /// public Guid? UserId { get; set; } public static ITVSeriesManager TVSeriesManager; - [IgnoreDataMember] + /// + [JsonIgnore] public string CollectionType => ViewType; + /// public override IEnumerable GetIdsForAncestorQuery() { - var list = new List(); - if (!DisplayParentId.Equals(Guid.Empty)) { - list.Add(DisplayParentId); + yield return DisplayParentId; } else if (!ParentId.Equals(Guid.Empty)) { - list.Add(ParentId); + yield return ParentId; } else { - list.Add(Id); + yield return Id; } - - return list; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsInheritedParentImages => false; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPlayedStatus => false; public override int GetChildCount(User user) @@ -167,7 +169,7 @@ namespace MediaBrowser.Controller.Entities return Task.CompletedTask; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPeople => false; } } diff --git a/MediaBrowser.Controller/Entities/Video.cs b/MediaBrowser.Controller/Entities/Video.cs index 8379dcc090..60906bdb08 100644 --- a/MediaBrowser.Controller/Entities/Video.cs +++ b/MediaBrowser.Controller/Entities/Video.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Library; @@ -13,7 +14,6 @@ using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.Entities { @@ -25,23 +25,23 @@ namespace MediaBrowser.Controller.Entities ISupportsPlaceHolders, IHasMediaSources { - [IgnoreDataMember] + [JsonIgnore] public string PrimaryVersionId { get; set; } public string[] AdditionalParts { get; set; } public string[] LocalAlternateVersions { get; set; } public LinkedChild[] LinkedAlternateVersions { get; set; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPlayedStatus => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPeople => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsInheritedParentImages => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPositionTicksResume { get @@ -90,7 +90,7 @@ namespace MediaBrowser.Controller.Entities return base.CreatePresentationUniqueKey(); } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsThemeMedia => true; /// @@ -180,10 +180,10 @@ namespace MediaBrowser.Controller.Entities return IsFileProtocol; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsAddingToPlaylist => true; - [IgnoreDataMember] + [JsonIgnore] public int MediaSourceCount { get @@ -200,10 +200,10 @@ namespace MediaBrowser.Controller.Entities } } - [IgnoreDataMember] + [JsonIgnore] public bool IsStacked => AdditionalParts.Length > 0; - [IgnoreDataMember] + [JsonIgnore] public override bool HasLocalAlternateVersions => LocalAlternateVersions.Length > 0; public IEnumerable GetAdditionalPartIds() @@ -218,7 +218,7 @@ namespace MediaBrowser.Controller.Entities public static ILiveTvManager LiveTvManager { get; set; } - [IgnoreDataMember] + [JsonIgnore] public override SourceType SourceType { get @@ -247,7 +247,7 @@ namespace MediaBrowser.Controller.Entities return base.CanDelete(); } - [IgnoreDataMember] + [JsonIgnore] public bool IsCompleteMedia { get @@ -261,7 +261,7 @@ namespace MediaBrowser.Controller.Entities } } - [IgnoreDataMember] + [JsonIgnore] protected virtual bool EnableDefaultVideoUserDataKeys => true; public override List GetUserDataKeys() @@ -338,7 +338,7 @@ namespace MediaBrowser.Controller.Entities .OrderBy(i => i.SortName); } - [IgnoreDataMember] + [JsonIgnore] public override string ContainingFolderPath { get @@ -360,7 +360,7 @@ namespace MediaBrowser.Controller.Entities } } - [IgnoreDataMember] + [JsonIgnore] public override string FileNameWithoutExtension { get @@ -432,14 +432,14 @@ namespace MediaBrowser.Controller.Entities /// Gets a value indicating whether [is3 D]. /// /// true if [is3 D]; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public bool Is3D => Video3DFormat.HasValue; /// /// Gets the type of the media. /// /// The type of the media. - [IgnoreDataMember] + [JsonIgnore] public override string MediaType => Model.Entities.MediaType.Video; protected override async Task RefreshedOwnedItems(MetadataRefreshOptions options, List fileSystemChildren, CancellationToken cancellationToken) diff --git a/MediaBrowser.Controller/Entities/Year.cs b/MediaBrowser.Controller/Entities/Year.cs index 13e82fada3..a01ef5c316 100644 --- a/MediaBrowser.Controller/Entities/Year.cs +++ b/MediaBrowser.Controller/Entities/Year.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using System.Globalization; -using MediaBrowser.Model.Serialization; +using System.Text.Json.Serialization; using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Entities @@ -24,7 +24,7 @@ namespace MediaBrowser.Controller.Entities /// If the item is a folder, it returns the folder itself /// /// The containing folder path. - [IgnoreDataMember] + [JsonIgnore] public override string ContainingFolderPath => Path; public override double GetDefaultPrimaryImageAspectRatio() @@ -35,7 +35,7 @@ namespace MediaBrowser.Controller.Entities return value; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsAncestors => false; public override bool CanDelete() @@ -72,7 +72,7 @@ namespace MediaBrowser.Controller.Entities return null; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPeople => false; public static string GetPath(string name) diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs index 61b2c15ae2..b3c56bdd5f 100644 --- a/MediaBrowser.Controller/IServerApplicationHost.cs +++ b/MediaBrowser.Controller/IServerApplicationHost.cs @@ -5,6 +5,7 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common; using MediaBrowser.Model.System; +using Microsoft.AspNetCore.Http; namespace MediaBrowser.Controller { @@ -87,5 +88,9 @@ namespace MediaBrowser.Controller string ExpandVirtualPath(string path); string ReverseVirtualPath(string path); + + Task ExecuteHttpHandlerAsync(HttpContext context, Func next); + + Task ExecuteWebsocketHandlerAsync(HttpContext context, Func next); } } diff --git a/MediaBrowser.Controller/IServerApplicationPaths.cs b/MediaBrowser.Controller/IServerApplicationPaths.cs index 15d7e9f625..5d7c60910a 100644 --- a/MediaBrowser.Controller/IServerApplicationPaths.cs +++ b/MediaBrowser.Controller/IServerApplicationPaths.cs @@ -10,24 +10,12 @@ namespace MediaBrowser.Controller /// The root folder path. string RootFolderPath { get; } - /// - /// Gets the application resources path. This is the path to the folder containing resources that are deployed as part of the application - /// - /// The application resources path. - string ApplicationResourcesPath { get; } - /// /// Gets the path to the default user view directory. Used if no specific user view is defined. /// /// The default user views path. string DefaultUserViewsPath { get; } - /// - /// Gets the path to localization data. - /// - /// The localization path. - string LocalizationPath { get; } - /// /// Gets the path to the People directory /// @@ -82,21 +70,18 @@ namespace MediaBrowser.Controller /// The user configuration directory path. string UserConfigurationDirectoryPath { get; } - /// - /// Gets the transcoding temporary path. - /// - /// The transcoding temporary path. - string TranscodingTempPath { get; } - /// /// Gets the internal metadata path. /// /// The internal metadata path. string InternalMetadataPath { get; } + string VirtualInternalMetadataPath { get; } + /// + /// Gets the path to the artists directory. + /// + /// The artists path. string ArtistsPath { get; } - - string GetTranscodingTempPath(); } } diff --git a/MediaBrowser.Controller/Library/IUserManager.cs b/MediaBrowser.Controller/Library/IUserManager.cs index bbedc04425..eea2e3a718 100644 --- a/MediaBrowser.Controller/Library/IUserManager.cs +++ b/MediaBrowser.Controller/Library/IUserManager.cs @@ -39,17 +39,21 @@ namespace MediaBrowser.Controller.Library event EventHandler> UserDeleted; event EventHandler> UserCreated; + event EventHandler> UserPolicyUpdated; + event EventHandler> UserConfigurationUpdated; + event EventHandler> UserPasswordChanged; + event EventHandler> UserLockedOut; /// - /// Gets a User by Id + /// Gets a User by Id. /// /// The id. - /// User. - /// + /// The user with the specified Id, or null if the user doesn't exist. + /// id is an empty Guid. User GetUserById(Guid id); /// diff --git a/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs b/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs index 351662b294..60391bb83f 100644 --- a/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs +++ b/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs @@ -2,13 +2,13 @@ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Text.Json.Serialization; using MediaBrowser.Controller.Entities; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; using MediaBrowser.Model.MediaInfo; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.LiveTv { @@ -31,13 +31,13 @@ namespace MediaBrowser.Controller.LiveTv return UnratedItem.LiveTvChannel; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPositionTicksResume => false; - [IgnoreDataMember] + [JsonIgnore] public override SourceType SourceType => SourceType.LiveTV; - [IgnoreDataMember] + [JsonIgnore] public override bool EnableRememberingTrackSelections => false; /// @@ -52,7 +52,7 @@ namespace MediaBrowser.Controller.LiveTv /// The type of the channel. public ChannelType ChannelType { get; set; } - [IgnoreDataMember] + [JsonIgnore] public override LocationType LocationType => LocationType.Remote; protected override string CreateSortName() @@ -70,7 +70,7 @@ namespace MediaBrowser.Controller.LiveTv return (Number ?? string.Empty) + "-" + (Name ?? string.Empty); } - [IgnoreDataMember] + [JsonIgnore] public override string MediaType => ChannelType == ChannelType.Radio ? Model.Entities.MediaType.Audio : Model.Entities.MediaType.Video; public override string GetClientTypeName() @@ -119,45 +119,45 @@ namespace MediaBrowser.Controller.LiveTv return false; } - [IgnoreDataMember] + [JsonIgnore] public bool IsMovie { get; set; } /// /// Gets or sets a value indicating whether this instance is sports. /// /// true if this instance is sports; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public bool IsSports { get; set; } /// /// Gets or sets a value indicating whether this instance is series. /// /// true if this instance is series; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public bool IsSeries { get; set; } /// /// Gets or sets a value indicating whether this instance is news. /// /// true if this instance is news; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public bool IsNews { get; set; } /// /// Gets or sets a value indicating whether this instance is kids. /// /// true if this instance is kids; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public bool IsKids => Tags.Contains("Kids", StringComparer.OrdinalIgnoreCase); - [IgnoreDataMember] + [JsonIgnore] public bool IsRepeat { get; set; } /// /// Gets or sets the episode title. /// /// The episode title. - [IgnoreDataMember] + [JsonIgnore] public string EpisodeTitle { get; set; } } } diff --git a/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs b/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs index bdaf10d005..13df85aeda 100644 --- a/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs +++ b/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Text.Json.Serialization; using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; @@ -9,7 +10,6 @@ using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; using MediaBrowser.Model.Providers; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.LiveTv { @@ -63,79 +63,79 @@ namespace MediaBrowser.Controller.LiveTv } } - [IgnoreDataMember] + [JsonIgnore] public override SourceType SourceType => SourceType.LiveTV; /// /// The start date of the program, in UTC. /// - [IgnoreDataMember] + [JsonIgnore] public DateTime StartDate { get; set; } /// /// Gets or sets a value indicating whether this instance is repeat. /// /// true if this instance is repeat; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public bool IsRepeat { get; set; } /// /// Gets or sets the episode title. /// /// The episode title. - [IgnoreDataMember] + [JsonIgnore] public string EpisodeTitle { get; set; } - [IgnoreDataMember] + [JsonIgnore] public string ShowId { get; set; } /// /// Gets or sets a value indicating whether this instance is movie. /// /// true if this instance is movie; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public bool IsMovie { get; set; } /// /// Gets or sets a value indicating whether this instance is sports. /// /// true if this instance is sports; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public bool IsSports => Tags.Contains("Sports", StringComparer.OrdinalIgnoreCase); /// /// Gets or sets a value indicating whether this instance is series. /// /// true if this instance is series; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public bool IsSeries { get; set; } /// /// Gets or sets a value indicating whether this instance is live. /// /// true if this instance is live; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public bool IsLive => Tags.Contains("Live", StringComparer.OrdinalIgnoreCase); /// /// Gets or sets a value indicating whether this instance is news. /// /// true if this instance is news; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public bool IsNews => Tags.Contains("News", StringComparer.OrdinalIgnoreCase); /// /// Gets or sets a value indicating whether this instance is kids. /// /// true if this instance is kids; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public bool IsKids => Tags.Contains("Kids", StringComparer.OrdinalIgnoreCase); /// /// Gets or sets a value indicating whether this instance is premiere. /// /// true if this instance is premiere; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public bool IsPremiere => Tags.Contains("Premiere", StringComparer.OrdinalIgnoreCase); /// @@ -143,10 +143,10 @@ namespace MediaBrowser.Controller.LiveTv /// If the item is a folder, it returns the folder itself /// /// The containing folder path. - [IgnoreDataMember] + [JsonIgnore] public override string ContainingFolderPath => Path; - //[IgnoreDataMember] + //[JsonIgnore] //public override string MediaType //{ // get @@ -155,7 +155,7 @@ namespace MediaBrowser.Controller.LiveTv // } //} - [IgnoreDataMember] + [JsonIgnore] public bool IsAiring { get @@ -166,7 +166,7 @@ namespace MediaBrowser.Controller.LiveTv } } - [IgnoreDataMember] + [JsonIgnore] public bool HasAired { get @@ -197,7 +197,7 @@ namespace MediaBrowser.Controller.LiveTv return false; } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPeople { get @@ -212,7 +212,7 @@ namespace MediaBrowser.Controller.LiveTv } } - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsAncestors => false; private LiveTvOptions GetConfiguration() diff --git a/MediaBrowser.Controller/LiveTv/TimerInfo.cs b/MediaBrowser.Controller/LiveTv/TimerInfo.cs index 2fea6a8cb5..46774b2b7a 100644 --- a/MediaBrowser.Controller/LiveTv/TimerInfo.cs +++ b/MediaBrowser.Controller/LiveTv/TimerInfo.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text.Json.Serialization; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.LiveTv { @@ -129,10 +129,10 @@ namespace MediaBrowser.Controller.LiveTv /// Gets or sets a value indicating whether this instance is live. /// /// true if this instance is live; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public bool IsLive => Tags.Contains("Live", StringComparer.OrdinalIgnoreCase); - [IgnoreDataMember] + [JsonIgnore] public bool IsPremiere => Tags.Contains("Premiere", StringComparer.OrdinalIgnoreCase); public int? ProductionYear { get; set; } diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index c6bca25182..276eb71bcf 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -17,7 +17,7 @@ - netstandard2.0 + netstandard2.1 false true diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 991fc0b001..0664bdd984 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -10,7 +10,6 @@ using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; @@ -1173,17 +1172,17 @@ namespace MediaBrowser.Controller.MediaEncoding { bitrate = GetMinBitrate(videoStream.BitRate.Value, bitrate.Value); } - } - if (bitrate.HasValue) - { - var inputVideoCodec = videoStream.Codec; - bitrate = ScaleBitrate(bitrate.Value, inputVideoCodec, outputVideoCodec); - - // If a max bitrate was requested, don't let the scaled bitrate exceed it - if (request.VideoBitRate.HasValue) + if (bitrate.HasValue) { - bitrate = Math.Min(bitrate.Value, request.VideoBitRate.Value); + var inputVideoCodec = videoStream.Codec; + bitrate = ScaleBitrate(bitrate.Value, inputVideoCodec, outputVideoCodec); + + // If a max bitrate was requested, don't let the scaled bitrate exceed it + if (request.VideoBitRate.HasValue) + { + bitrate = Math.Min(bitrate.Value, request.VideoBitRate.Value); + } } } @@ -2168,7 +2167,8 @@ namespace MediaBrowser.Controller.MediaEncoding // Important: If this is ever re-enabled, make sure not to use it with wtv because it breaks seeking if (!string.Equals(state.InputContainer, "wtv", StringComparison.OrdinalIgnoreCase) && state.TranscodingType != TranscodingJobType.Progressive - && state.EnableBreakOnNonKeyFrames(outputVideoCodec)) + && !state.EnableBreakOnNonKeyFrames(outputVideoCodec) + && (state.BaseRequest.StartTimeTicks ?? 0) > 0) { inputModifier += " -noaccurate_seek"; } @@ -2529,13 +2529,25 @@ namespace MediaBrowser.Controller.MediaEncoding case "h264": if (_mediaEncoder.SupportsDecoder("h264_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase)) { - return "-c:v h264_mmal"; + return "-c:v h264_mmal "; } break; case "mpeg2video": if (_mediaEncoder.SupportsDecoder("mpeg2_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase)) { - return "-c:v mpeg2_mmal"; + return "-c:v mpeg2_mmal "; + } + break; + case "mpeg4": + if (_mediaEncoder.SupportsDecoder("mpeg4_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase)) + { + return "-c:v mpeg4_mmal "; + } + break; + case "vc1": + if (_mediaEncoder.SupportsDecoder("vc1_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase)) + { + return "-c:v vc1_mmal "; } break; } diff --git a/MediaBrowser.Controller/Net/IAuthService.cs b/MediaBrowser.Controller/Net/IAuthService.cs index 142f1d91c3..4c9120e0c9 100644 --- a/MediaBrowser.Controller/Net/IAuthService.cs +++ b/MediaBrowser.Controller/Net/IAuthService.cs @@ -1,9 +1,12 @@ +using MediaBrowser.Controller.Entities; using MediaBrowser.Model.Services; +using Microsoft.AspNetCore.Http; namespace MediaBrowser.Controller.Net { public interface IAuthService { void Authenticate(IRequest request, IAuthenticationAttributes authAttribtues); + User Authenticate(HttpRequest request, IAuthenticationAttributes authAttribtues); } } diff --git a/MediaBrowser.Controller/Playlists/Playlist.cs b/MediaBrowser.Controller/Playlists/Playlist.cs index bef7eff064..3b08e72b92 100644 --- a/MediaBrowser.Controller/Playlists/Playlist.cs +++ b/MediaBrowser.Controller/Playlists/Playlist.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Dto; @@ -10,7 +11,6 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Controller.Playlists { @@ -34,7 +34,7 @@ namespace MediaBrowser.Controller.Playlists Shares = Array.Empty(); } - [IgnoreDataMember] + [JsonIgnore] public bool IsFile => IsPlaylistFile(Path); public static bool IsPlaylistFile(string path) @@ -42,7 +42,7 @@ namespace MediaBrowser.Controller.Playlists return System.IO.Path.HasExtension(path); } - [IgnoreDataMember] + [JsonIgnore] public override string ContainingFolderPath { get @@ -58,19 +58,19 @@ namespace MediaBrowser.Controller.Playlists } } - [IgnoreDataMember] + [JsonIgnore] protected override bool FilterLinkedChildrenPerUser => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsInheritedParentImages => false; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsPlayedStatus => string.Equals(MediaType, "Video", StringComparison.OrdinalIgnoreCase); - [IgnoreDataMember] + [JsonIgnore] public override bool AlwaysScanInternalMetadataPath => true; - [IgnoreDataMember] + [JsonIgnore] public override bool SupportsCumulativeRunTimeTicks => true; public override double GetDefaultPrimaryImageAspectRatio() @@ -193,12 +193,12 @@ namespace MediaBrowser.Controller.Playlists return new[] { item }; } - [IgnoreDataMember] + [JsonIgnore] public override bool IsPreSorted => true; public string PlaylistMediaType { get; set; } - [IgnoreDataMember] + [JsonIgnore] public override string MediaType => PlaylistMediaType; public void SetMediaType(string value) @@ -206,7 +206,7 @@ namespace MediaBrowser.Controller.Playlists PlaylistMediaType = value; } - [IgnoreDataMember] + [JsonIgnore] private bool IsSharedItem { get diff --git a/MediaBrowser.Controller/Providers/DirectoryService.cs b/MediaBrowser.Controller/Providers/DirectoryService.cs index 133e7c115a..303b03a216 100644 --- a/MediaBrowser.Controller/Providers/DirectoryService.cs +++ b/MediaBrowser.Controller/Providers/DirectoryService.cs @@ -2,13 +2,11 @@ using System; using System.Collections.Generic; using System.Linq; using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.Providers { public class DirectoryService : IDirectoryService { - private readonly ILogger _logger; private readonly IFileSystem _fileSystem; private readonly Dictionary _cache = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -17,9 +15,8 @@ namespace MediaBrowser.Controller.Providers private readonly Dictionary> _filePathCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); - public DirectoryService(ILogger logger, IFileSystem fileSystem) + public DirectoryService(IFileSystem fileSystem) { - _logger = logger; _fileSystem = fileSystem; } @@ -27,8 +24,6 @@ namespace MediaBrowser.Controller.Providers { if (!_cache.TryGetValue(path, out FileSystemMetadata[] entries)) { - //_logger.LogDebug("Getting files for " + path); - entries = _fileSystem.GetFileSystemEntries(path).ToArray(); //_cache.TryAdd(path, entries); @@ -49,6 +44,7 @@ namespace MediaBrowser.Controller.Providers list.Add(item); } } + return list; } @@ -89,6 +85,5 @@ namespace MediaBrowser.Controller.Providers return result; } - } } diff --git a/MediaBrowser.Controller/Session/SessionInfo.cs b/MediaBrowser.Controller/Session/SessionInfo.cs index f0e81e8e7a..acda6a4166 100644 --- a/MediaBrowser.Controller/Session/SessionInfo.cs +++ b/MediaBrowser.Controller/Session/SessionInfo.cs @@ -1,9 +1,9 @@ using System; using System.Linq; +using System.Text.Json.Serialization; using System.Threading; using MediaBrowser.Controller.Entities; using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Session; using Microsoft.Extensions.Logging; @@ -123,7 +123,7 @@ namespace MediaBrowser.Controller.Session /// Gets or sets the session controller. /// /// The session controller. - [IgnoreDataMember] + [JsonIgnore] public ISessionController[] SessionControllers { get; set; } /// diff --git a/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs b/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs index 0872335c55..39538aacd7 100644 --- a/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs +++ b/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs @@ -24,7 +24,8 @@ namespace MediaBrowser.Controller.Subtitles /// /// Searches the subtitles. /// - Task SearchSubtitles(Video video, + Task SearchSubtitles( + Video video, string language, bool? isPerfectMatch, CancellationToken cancellationToken); @@ -34,8 +35,9 @@ namespace MediaBrowser.Controller.Subtitles /// /// The request. /// The cancellation token. - /// Task{IEnumerable{RemoteSubtitleInfo}}. - Task SearchSubtitles(SubtitleSearchRequest request, + /// Task{RemoteSubtitleInfo[]}. + Task SearchSubtitles( + SubtitleSearchRequest request, CancellationToken cancellationToken); /// @@ -53,7 +55,7 @@ namespace MediaBrowser.Controller.Subtitles /// /// The identifier. /// The cancellation token. - /// Task{SubtitleResponse}. + /// . Task GetRemoteSubtitles(string id, CancellationToken cancellationToken); /// diff --git a/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj b/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj index a8f8da9b83..71eb62693c 100644 --- a/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj +++ b/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj @@ -10,7 +10,7 @@ - netstandard2.0 + netstandard2.1 false true diff --git a/MediaBrowser.MediaEncoding/Configuration/EncodingConfigurationFactory.cs b/MediaBrowser.MediaEncoding/Configuration/EncodingConfigurationFactory.cs index bb806ee55c..75534b5bdd 100644 --- a/MediaBrowser.MediaEncoding/Configuration/EncodingConfigurationFactory.cs +++ b/MediaBrowser.MediaEncoding/Configuration/EncodingConfigurationFactory.cs @@ -1,54 +1,46 @@ +using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using MediaBrowser.Common.Configuration; using MediaBrowser.Model.Configuration; -using MediaBrowser.Model.IO; namespace MediaBrowser.MediaEncoding.Configuration { public class EncodingConfigurationFactory : IConfigurationFactory { - private readonly IFileSystem _fileSystem; - - public EncodingConfigurationFactory(IFileSystem fileSystem) - { - _fileSystem = fileSystem; - } - public IEnumerable GetConfigurations() { return new[] { - new EncodingConfigurationStore(_fileSystem) + new EncodingConfigurationStore() }; } } public class EncodingConfigurationStore : ConfigurationStore, IValidatingConfiguration { - private readonly IFileSystem _fileSystem; - - public EncodingConfigurationStore(IFileSystem fileSystem) + public EncodingConfigurationStore() { ConfigurationType = typeof(EncodingOptions); Key = "encoding"; - _fileSystem = fileSystem; } public void Validate(object oldConfig, object newConfig) { - var oldEncodingConfig = (EncodingOptions)oldConfig; - var newEncodingConfig = (EncodingOptions)newConfig; - - var newPath = newEncodingConfig.TranscodingTempPath; + var newPath = ((EncodingOptions)newConfig).TranscodingTempPath; if (!string.IsNullOrWhiteSpace(newPath) - && !string.Equals(oldEncodingConfig.TranscodingTempPath ?? string.Empty, newPath)) + && !string.Equals(((EncodingOptions)oldConfig).TranscodingTempPath, newPath, StringComparison.Ordinal)) { // Validate if (!Directory.Exists(newPath)) { - throw new FileNotFoundException(string.Format("{0} does not exist.", newPath)); + throw new DirectoryNotFoundException( + string.Format( + CultureInfo.InvariantCulture, + "{0} does not exist.", + newPath)); } } } diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index 3620abfee7..1feca0ec92 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -18,7 +18,10 @@ namespace MediaBrowser.MediaEncoding.Encoder "h264_qsv", "hevc_qsv", "mpeg2_qsv", + "mpeg2_mmal", + "mpeg4_mmal", "vc1_qsv", + "vc1_mmal", "h264_cuvid", "hevc_cuvid", "dts", @@ -26,6 +29,7 @@ namespace MediaBrowser.MediaEncoding.Encoder "aac", "mp3", "h264", + "h264_mmal", "hevc" }; diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj index 264f31f3c9..e977bd8fe5 100644 --- a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj +++ b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj @@ -1,7 +1,7 @@  - netstandard2.0 + netstandard2.1 false true @@ -18,8 +18,8 @@ - - + + diff --git a/MediaBrowser.Model/Cryptography/ICryptoProvider.cs b/MediaBrowser.Model/Cryptography/ICryptoProvider.cs index ce6493232f..2d75c9b3ec 100644 --- a/MediaBrowser.Model/Cryptography/ICryptoProvider.cs +++ b/MediaBrowser.Model/Cryptography/ICryptoProvider.cs @@ -8,10 +8,6 @@ namespace MediaBrowser.Model.Cryptography IEnumerable GetSupportedHashMethods(); - byte[] ComputeHash(string HashMethod, byte[] bytes); - - byte[] ComputeHashWithDefaultMethod(byte[] bytes); - byte[] ComputeHash(string HashMethod, byte[] bytes, byte[] salt); byte[] ComputeHashWithDefaultMethod(byte[] bytes, byte[] salt); diff --git a/MediaBrowser.Model/Dto/BaseItemPerson.cs b/MediaBrowser.Model/Dto/BaseItemPerson.cs index 7011ff8ea5..270a4683a7 100644 --- a/MediaBrowser.Model/Dto/BaseItemPerson.cs +++ b/MediaBrowser.Model/Dto/BaseItemPerson.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Model.Serialization; +using System.Text.Json.Serialization; namespace MediaBrowser.Model.Dto { @@ -41,7 +41,7 @@ namespace MediaBrowser.Model.Dto /// Gets a value indicating whether this instance has primary image. /// /// true if this instance has primary image; otherwise, false. - [IgnoreDataMember] + [JsonIgnore] public bool HasPrimaryImage => PrimaryImageTag != null; } } diff --git a/MediaBrowser.Model/Dto/MediaSourceInfo.cs b/MediaBrowser.Model/Dto/MediaSourceInfo.cs index 92e40fb01f..5bdc4809a9 100644 --- a/MediaBrowser.Model/Dto/MediaSourceInfo.cs +++ b/MediaBrowser.Model/Dto/MediaSourceInfo.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; +using System.Text.Json.Serialization; using MediaBrowser.Model.Entities; using MediaBrowser.Model.MediaInfo; -using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Session; namespace MediaBrowser.Model.Dto @@ -108,7 +108,7 @@ namespace MediaBrowser.Model.Dto } } - [IgnoreDataMember] + [JsonIgnore] public TranscodeReason[] TranscodeReasons { get; set; } public int? DefaultAudioStreamIndex { get; set; } @@ -148,7 +148,7 @@ namespace MediaBrowser.Model.Dto return null; } - [IgnoreDataMember] + [JsonIgnore] public MediaStream VideoStream { get diff --git a/MediaBrowser.Model/Globalization/ILocalizationManager.cs b/MediaBrowser.Model/Globalization/ILocalizationManager.cs index 91d946db83..0b6cfe1b71 100644 --- a/MediaBrowser.Model/Globalization/ILocalizationManager.cs +++ b/MediaBrowser.Model/Globalization/ILocalizationManager.cs @@ -64,10 +64,10 @@ namespace MediaBrowser.Model.Globalization bool HasUnicodeCategory(string value, UnicodeCategory category); /// - /// Returns the correct for the given language. + /// Returns the correct for the given language. /// /// The language. - /// The correct for the given language. + /// The correct for the given language. CultureDto FindLanguageInfo(string language); } } diff --git a/MediaBrowser.Model/IO/StreamDefaults.cs b/MediaBrowser.Model/IO/StreamDefaults.cs index 1dc29e06ef..4b55ce1f30 100644 --- a/MediaBrowser.Model/IO/StreamDefaults.cs +++ b/MediaBrowser.Model/IO/StreamDefaults.cs @@ -1,17 +1,17 @@ namespace MediaBrowser.Model.IO { /// - /// Class StreamDefaults + /// Class StreamDefaults. /// public static class StreamDefaults { /// - /// The default copy to buffer size + /// The default copy to buffer size. /// public const int DefaultCopyToBufferSize = 81920; /// - /// The default file stream buffer size + /// The default file stream buffer size. /// public const int DefaultFileStreamBufferSize = 4096; } diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index e9f43ea56b..53cd08fbd0 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -1,4 +1,4 @@ - + Jellyfin Contributors @@ -15,7 +15,9 @@ - + + + diff --git a/MediaBrowser.Model/Net/SocketReceiveResult.cs b/MediaBrowser.Model/Net/SocketReceiveResult.cs index cd7a2e55f8..3a4ad3738e 100644 --- a/MediaBrowser.Model/Net/SocketReceiveResult.cs +++ b/MediaBrowser.Model/Net/SocketReceiveResult.cs @@ -18,7 +18,7 @@ namespace MediaBrowser.Model.Net public int ReceivedBytes { get; set; } /// - /// The the data was received from. + /// The the data was received from. /// public IPEndPoint RemoteEndPoint { get; set; } public IPAddress LocalIPAddress { get; set; } diff --git a/MediaBrowser.Model/Serialization/IgnoreDataMemberAttribute.cs b/MediaBrowser.Model/Serialization/IgnoreDataMemberAttribute.cs deleted file mode 100644 index b43949fe38..0000000000 --- a/MediaBrowser.Model/Serialization/IgnoreDataMemberAttribute.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace MediaBrowser.Model.Serialization -{ - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false, AllowMultiple = false)] - public sealed class IgnoreDataMemberAttribute : Attribute - { - public IgnoreDataMemberAttribute() - { - } - } -} diff --git a/MediaBrowser.Model/System/SystemInfo.cs b/MediaBrowser.Model/System/SystemInfo.cs index 3f73cc4e0b..7014a5c87c 100644 --- a/MediaBrowser.Model/System/SystemInfo.cs +++ b/MediaBrowser.Model/System/SystemInfo.cs @@ -110,9 +110,9 @@ namespace MediaBrowser.Model.System public string InternalMetadataPath { get; set; } /// - /// Gets or sets the transcoding temporary path. + /// Gets or sets the transcode path. /// - /// The transcoding temporary path. + /// The transcode path. public string TranscodingTempPath { get; set; } /// diff --git a/MediaBrowser.Model/Updates/PackageInfo.cs b/MediaBrowser.Model/Updates/PackageInfo.cs index ff4ed26d31..5dd9c65918 100644 --- a/MediaBrowser.Model/Updates/PackageInfo.cs +++ b/MediaBrowser.Model/Updates/PackageInfo.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; namespace MediaBrowser.Model.Updates { @@ -150,7 +151,7 @@ namespace MediaBrowser.Model.Updates /// Gets or sets the versions. /// /// The versions. - public PackageVersionInfo[] versions { get; set; } + public IReadOnlyList versions { get; set; } /// /// Gets or sets a value indicating whether [enable in application store]. diff --git a/MediaBrowser.Model/Updates/PackageVersionInfo.cs b/MediaBrowser.Model/Updates/PackageVersionInfo.cs index 7ef07c0dfd..c0790317d5 100644 --- a/MediaBrowser.Model/Updates/PackageVersionInfo.cs +++ b/MediaBrowser.Model/Updates/PackageVersionInfo.cs @@ -1,5 +1,5 @@ using System; -using MediaBrowser.Model.Serialization; +using System.Text.Json.Serialization; namespace MediaBrowser.Model.Updates { @@ -36,7 +36,7 @@ namespace MediaBrowser.Model.Updates /// Had to make this an interpreted property since Protobuf can't handle Version /// /// The version. - [IgnoreDataMember] + [JsonIgnore] public Version Version { get diff --git a/MediaBrowser.Providers/Books/AudioBookMetadataService.cs b/MediaBrowser.Providers/Books/AudioBookMetadataService.cs index 0062d5ab3b..309241bfaa 100644 --- a/MediaBrowser.Providers/Books/AudioBookMetadataService.cs +++ b/MediaBrowser.Providers/Books/AudioBookMetadataService.cs @@ -16,9 +16,8 @@ namespace MediaBrowser.Providers.Books ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, - IUserDataManager userDataManager, ILibraryManager libraryManager) - : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager) + : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager) { } diff --git a/MediaBrowser.Providers/Books/BookMetadataService.cs b/MediaBrowser.Providers/Books/BookMetadataService.cs index 358f87a0fc..9d6a1ef59d 100644 --- a/MediaBrowser.Providers/Books/BookMetadataService.cs +++ b/MediaBrowser.Providers/Books/BookMetadataService.cs @@ -11,6 +11,17 @@ namespace MediaBrowser.Providers.Books { public class BookMetadataService : MetadataService { + public BookMetadataService( + IServerConfigurationManager serverConfigurationManager, + ILogger logger, + IProviderManager providerManager, + IFileSystem fileSystem, + ILibraryManager libraryManager) + : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager) + { + } + + /// protected override void MergeData(MetadataResult source, MetadataResult target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings) { ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings); @@ -20,9 +31,5 @@ namespace MediaBrowser.Providers.Books target.Item.SeriesName = source.Item.SeriesName; } } - - public BookMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager) - { - } } } diff --git a/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs b/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs index 693edb1435..5bf01232cd 100644 --- a/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs +++ b/MediaBrowser.Providers/BoxSets/BoxSetMetadataService.cs @@ -14,11 +14,35 @@ namespace MediaBrowser.Providers.BoxSets { public class BoxSetMetadataService : MetadataService { + public BoxSetMetadataService( + IServerConfigurationManager serverConfigurationManager, + ILogger logger, + IProviderManager providerManager, + IFileSystem fileSystem, + ILibraryManager libraryManager) + : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager) + { + } + + /// + protected override bool EnableUpdatingGenresFromChildren => true; + + /// + protected override bool EnableUpdatingOfficialRatingFromChildren => true; + + /// + protected override bool EnableUpdatingStudiosFromChildren => true; + + /// + protected override bool EnableUpdatingPremiereDateFromChildren => true; + + /// protected override IList GetChildrenForMetadataUpdates(BoxSet item) { return item.GetLinkedChildren(); } + /// protected override void MergeData(MetadataResult source, MetadataResult target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings) { ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings); @@ -32,6 +56,7 @@ namespace MediaBrowser.Providers.BoxSets } } + /// protected override ItemUpdateType BeforeSaveInternal(BoxSet item, bool isFullRefresh, ItemUpdateType currentUpdateType) { var updateType = base.BeforeSaveInternal(item, isFullRefresh, currentUpdateType); @@ -47,17 +72,5 @@ namespace MediaBrowser.Providers.BoxSets return updateType; } - - public BoxSetMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager) - { - } - - protected override bool EnableUpdatingGenresFromChildren => true; - - protected override bool EnableUpdatingOfficialRatingFromChildren => true; - - protected override bool EnableUpdatingStudiosFromChildren => true; - - protected override bool EnableUpdatingPremiereDateFromChildren => true; } } diff --git a/MediaBrowser.Providers/Channels/ChannelMetadataService.cs b/MediaBrowser.Providers/Channels/ChannelMetadataService.cs index 0763a01635..da41f208c6 100644 --- a/MediaBrowser.Providers/Channels/ChannelMetadataService.cs +++ b/MediaBrowser.Providers/Channels/ChannelMetadataService.cs @@ -11,13 +11,20 @@ namespace MediaBrowser.Providers.Channels { public class ChannelMetadataService : MetadataService { + public ChannelMetadataService( + IServerConfigurationManager serverConfigurationManager, + ILogger logger, + IProviderManager providerManager, + IFileSystem fileSystem, + ILibraryManager libraryManager) + : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager) + { + } + + /// protected override void MergeData(MetadataResult source, MetadataResult target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings) { ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings); } - - public ChannelMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager) - { - } } } diff --git a/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs b/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs index 2c28b3e35c..dd1b4709d3 100644 --- a/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs +++ b/MediaBrowser.Providers/Folders/CollectionFolderMetadataService.cs @@ -12,13 +12,20 @@ namespace MediaBrowser.Providers.Folders { public class CollectionFolderMetadataService : MetadataService { + public CollectionFolderMetadataService( + IServerConfigurationManager serverConfigurationManager, + ILogger logger, + IProviderManager providerManager, + IFileSystem fileSystem, + ILibraryManager libraryManager) + : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager) + { + } + + /// protected override void MergeData(MetadataResult source, MetadataResult target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings) { ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings); } - - public CollectionFolderMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager) - { - } } } diff --git a/MediaBrowser.Providers/Folders/FolderMetadataService.cs b/MediaBrowser.Providers/Folders/FolderMetadataService.cs index bb16344223..8409e03fdc 100644 --- a/MediaBrowser.Providers/Folders/FolderMetadataService.cs +++ b/MediaBrowser.Providers/Folders/FolderMetadataService.cs @@ -11,16 +11,24 @@ namespace MediaBrowser.Providers.Folders { public class FolderMetadataService : MetadataService { + public FolderMetadataService( + IServerConfigurationManager serverConfigurationManager, + ILogger logger, + IProviderManager providerManager, + IFileSystem fileSystem, + ILibraryManager libraryManager) + : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager) + { + } + + /// // Make sure the type-specific services get picked first public override int Order => 10; + /// protected override void MergeData(MetadataResult source, MetadataResult target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings) { ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings); } - - public FolderMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager) - { - } } } diff --git a/MediaBrowser.Providers/Folders/UserViewMetadataService.cs b/MediaBrowser.Providers/Folders/UserViewMetadataService.cs index 8d6e77aeb3..2ceb71afc4 100644 --- a/MediaBrowser.Providers/Folders/UserViewMetadataService.cs +++ b/MediaBrowser.Providers/Folders/UserViewMetadataService.cs @@ -11,13 +11,20 @@ namespace MediaBrowser.Providers.Folders { public class UserViewMetadataService : MetadataService { + public UserViewMetadataService( + IServerConfigurationManager serverConfigurationManager, + ILogger logger, + IProviderManager providerManager, + IFileSystem fileSystem, + ILibraryManager libraryManager) + : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager) + { + } + + /// protected override void MergeData(MetadataResult source, MetadataResult target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings) { ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings); } - - public UserViewMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager) - { - } } } diff --git a/MediaBrowser.Providers/Genres/GenreMetadataService.cs b/MediaBrowser.Providers/Genres/GenreMetadataService.cs index 28a46b0080..932eb368cf 100644 --- a/MediaBrowser.Providers/Genres/GenreMetadataService.cs +++ b/MediaBrowser.Providers/Genres/GenreMetadataService.cs @@ -11,13 +11,20 @@ namespace MediaBrowser.Providers.Genres { public class GenreMetadataService : MetadataService { + public GenreMetadataService( + IServerConfigurationManager serverConfigurationManager, + ILogger logger, + IProviderManager providerManager, + IFileSystem fileSystem, + ILibraryManager libraryManager) + : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager) + { + } + + /// protected override void MergeData(MetadataResult source, MetadataResult target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings) { ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings); } - - public GenreMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager) - { - } } } diff --git a/MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs b/MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs index 6009d3a580..13dd972151 100644 --- a/MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs +++ b/MediaBrowser.Providers/LiveTv/ProgramMetadataService.cs @@ -11,13 +11,20 @@ namespace MediaBrowser.Providers.LiveTv { public class LiveTvMetadataService : MetadataService { + public LiveTvMetadataService( + IServerConfigurationManager serverConfigurationManager, + ILogger logger, + IProviderManager providerManager, + IFileSystem fileSystem, + ILibraryManager libraryManager) + : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager) + { + } + + /// protected override void MergeData(MetadataResult source, MetadataResult target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings) { ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings); } - - public LiveTvMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager) - { - } } } diff --git a/MediaBrowser.Providers/Manager/ItemImageProvider.cs b/MediaBrowser.Providers/Manager/ItemImageProvider.cs index 033aea1465..e9179815e7 100644 --- a/MediaBrowser.Providers/Manager/ItemImageProvider.cs +++ b/MediaBrowser.Providers/Manager/ItemImageProvider.cs @@ -340,7 +340,7 @@ namespace MediaBrowser.Providers.Manager if (deleted) { - item.ValidateImages(new DirectoryService(_logger, _fileSystem)); + item.ValidateImages(new DirectoryService(_fileSystem)); } } diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index f0716f2017..c3401f12b9 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -23,16 +23,14 @@ namespace MediaBrowser.Providers.Manager protected readonly ILogger Logger; protected readonly IProviderManager ProviderManager; protected readonly IFileSystem FileSystem; - protected readonly IUserDataManager UserDataManager; protected readonly ILibraryManager LibraryManager; - protected MetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) + protected MetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, ILibraryManager libraryManager) { ServerConfigurationManager = serverConfigurationManager; Logger = logger; ProviderManager = providerManager; FileSystem = fileSystem; - UserDataManager = userDataManager; LibraryManager = libraryManager; } @@ -44,7 +42,7 @@ namespace MediaBrowser.Providers.Manager } catch (Exception ex) { - Logger.LogError(ex, "Error getting file {path}", path); + Logger.LogError(ex, "Error getting file {Path}", path); return null; } } diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index 6a8d03f6d5..631d063a54 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -328,7 +328,7 @@ namespace MediaBrowser.Providers.Manager return GetImageProviders(item, libraryOptions, options, new ImageRefreshOptions( - new DirectoryService(_logger, _fileSystem)), + new DirectoryService(_fileSystem)), includeDisabled) .OfType(); } @@ -507,7 +507,7 @@ namespace MediaBrowser.Providers.Manager var imageProviders = GetImageProviders(dummy, libraryOptions, options, new ImageRefreshOptions( - new DirectoryService(_logger, _fileSystem)), + new DirectoryService(_fileSystem)), true) .ToList(); diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj index c7ecc59c9f..8d373be289 100644 --- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj +++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj @@ -11,22 +11,17 @@ - - + + - netstandard2.0 + netstandard2.1 false true - - - latest - - diff --git a/MediaBrowser.Providers/Movies/MovieExternalIds.cs b/MediaBrowser.Providers/Movies/MovieExternalIds.cs index 09ed6034c8..55810b1ed8 100644 --- a/MediaBrowser.Providers/Movies/MovieExternalIds.cs +++ b/MediaBrowser.Providers/Movies/MovieExternalIds.cs @@ -9,17 +9,20 @@ namespace MediaBrowser.Providers.Movies { public class ImdbExternalId : IExternalId { + /// public string Name => "IMDb"; + /// public string Key => MetadataProviders.Imdb.ToString(); + /// public string UrlFormatString => "https://www.imdb.com/title/{0}"; + /// public bool Supports(IHasProviderIds item) { // Supports images for tv movies - var tvProgram = item as LiveTvProgram; - if (tvProgram != null && tvProgram.IsMovie) + if (item is LiveTvProgram tvProgram && tvProgram.IsMovie) { return true; } @@ -28,18 +31,18 @@ namespace MediaBrowser.Providers.Movies } } - public class ImdbPersonExternalId : IExternalId { + /// public string Name => "IMDb"; + /// public string Key => MetadataProviders.Imdb.ToString(); + /// public string UrlFormatString => "https://www.imdb.com/name/{0}"; - public bool Supports(IHasProviderIds item) - { - return item is Person; - } + /// + public bool Supports(IHasProviderIds item) => item is Person; } } diff --git a/MediaBrowser.Providers/Movies/MovieMetadataService.cs b/MediaBrowser.Providers/Movies/MovieMetadataService.cs index 41806e49b6..c6cc5c7dc0 100644 --- a/MediaBrowser.Providers/Movies/MovieMetadataService.cs +++ b/MediaBrowser.Providers/Movies/MovieMetadataService.cs @@ -1,5 +1,4 @@ using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; @@ -12,6 +11,17 @@ namespace MediaBrowser.Providers.Movies { public class MovieMetadataService : MetadataService { + public MovieMetadataService( + IServerConfigurationManager serverConfigurationManager, + ILogger logger, + IProviderManager providerManager, + IFileSystem fileSystem, + ILibraryManager libraryManager) + : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager) + { + } + + /// protected override bool IsFullLocalMetadata(Movie item) { if (string.IsNullOrWhiteSpace(item.Overview)) @@ -25,6 +35,7 @@ namespace MediaBrowser.Providers.Movies return base.IsFullLocalMetadata(item); } + /// protected override void MergeData(MetadataResult source, MetadataResult target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings) { ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings); @@ -37,40 +48,5 @@ namespace MediaBrowser.Providers.Movies targetItem.CollectionName = sourceItem.CollectionName; } } - - public MovieMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager) - { - } } - - public class TrailerMetadataService : MetadataService - { - protected override bool IsFullLocalMetadata(Trailer item) - { - if (string.IsNullOrWhiteSpace(item.Overview)) - { - return false; - } - if (!item.ProductionYear.HasValue) - { - return false; - } - return base.IsFullLocalMetadata(item); - } - - protected override void MergeData(MetadataResult source, MetadataResult target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings) - { - ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings); - - if (replaceData || target.Item.TrailerTypes.Length == 0) - { - target.Item.TrailerTypes = source.Item.TrailerTypes; - } - } - - public TrailerMetadataService(IServerConfigurationManager serverConfigurationManager, ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, IUserDataManager userDataManager, ILibraryManager libraryManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager) - { - } - } - } diff --git a/MediaBrowser.Providers/Movies/TrailerMetadataService.cs b/MediaBrowser.Providers/Movies/TrailerMetadataService.cs new file mode 100644 index 0000000000..53b556940b --- /dev/null +++ b/MediaBrowser.Providers/Movies/TrailerMetadataService.cs @@ -0,0 +1,49 @@ +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.IO; +using MediaBrowser.Providers.Manager; +using Microsoft.Extensions.Logging; + +namespace MediaBrowser.Providers.Movies +{ + public class TrailerMetadataService : MetadataService + { + public TrailerMetadataService( + IServerConfigurationManager serverConfigurationManager, + ILogger logger, + IProviderManager providerManager, + IFileSystem fileSystem, + ILibraryManager libraryManager) + : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager) + { + } + + /// + protected override bool IsFullLocalMetadata(Trailer item) + { + if (string.IsNullOrWhiteSpace(item.Overview)) + { + return false; + } + if (!item.ProductionYear.HasValue) + { + return false; + } + return base.IsFullLocalMetadata(item); + } + + /// + protected override void MergeData(MetadataResult source, MetadataResult target, MetadataFields[] lockedFields, bool replaceData, bool mergeMetadataSettings) + { + ProviderUtils.MergeBaseItemData(source, target, lockedFields, replaceData, mergeMetadataSettings); + + if (replaceData || target.Item.TrailerTypes.Length == 0) + { + target.Item.TrailerTypes = source.Item.TrailerTypes; + } + } + } +} diff --git a/MediaBrowser.Providers/Music/AlbumMetadataService.cs b/MediaBrowser.Providers/Music/AlbumMetadataService.cs index 4e59b4119b..69133c1c16 100644 --- a/MediaBrowser.Providers/Music/AlbumMetadataService.cs +++ b/MediaBrowser.Providers/Music/AlbumMetadataService.cs @@ -20,9 +20,8 @@ namespace MediaBrowser.Providers.Music ILogger logger, IProviderManager providerManager, IFileSystem fileSystem, - IUserDataManager userDataManager, ILibraryManager libraryManager) - : base(serverConfigurationManager, logger, providerManager, fileSystem, userDataManager, libraryManager) + : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager) { } @@ -37,10 +36,7 @@ namespace MediaBrowser.Providers.Music /// protected override IList GetChildrenForMetadataUpdates(MusicAlbum item) - { - return item.GetRecursiveChildren(i => i is Audio) - .ToList(); - } + => item.GetRecursiveChildren(i => i is Audio); /// protected override ItemUpdateType UpdateMetadataFromChildren(MusicAlbum item, IList children, bool isFullRefresh, ItemUpdateType currentUpdateType) @@ -53,20 +49,18 @@ namespace MediaBrowser.Providers.Music { var name = children.Select(i => i.Album).FirstOrDefault(i => !string.IsNullOrEmpty(i)); - if (!string.IsNullOrEmpty(name)) + if (!string.IsNullOrEmpty(name) + && !string.Equals(item.Name, name, StringComparison.Ordinal)) { - if (!string.Equals(item.Name, name, StringComparison.Ordinal)) - { - item.Name = name; - updateType = updateType | ItemUpdateType.MetadataEdit; - } + item.Name = name; + updateType |= ItemUpdateType.MetadataEdit; } } var songs = children.Cast