From da9a59de1e0837d2a4b030d59fa8d009b4457439 Mon Sep 17 00:00:00 2001 From: Steve Hayles Date: Thu, 31 Oct 2019 18:48:34 +0000 Subject: [PATCH 001/881] Allow valid https requests in .NET Core ServerCertificateValidationCallback on the ServicePointManager is not supported in .NET Core and outgoing https requests will fail if the certificate is not trusted. This adds the equivalent functionality --- .../HttpClientManager/HttpClientManager.cs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs index 0e6083773d..c465030906 100644 --- a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs +++ b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs @@ -59,7 +59,17 @@ namespace Emby.Server.Implementations.HttpClientManager if (!_httpClients.TryGetValue(key, out var client)) { - client = new HttpClient() + var httpClientHandler = new HttpClientHandler() + { + ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => + { + var success = errors == System.Net.Security.SslPolicyErrors.None; + _logger.LogDebug("Validating certificate {Cert}. Success {1}", cert, success); + return success; + } + }; + + client = new HttpClient(httpClientHandler) { BaseAddress = new Uri(url) }; From be956dfd0270c010ef6ed6904b4bada628717155 Mon Sep 17 00:00:00 2001 From: Artiume Date: Sun, 15 Dec 2019 23:52:07 -0500 Subject: [PATCH 002/881] Update MediaInfoService.cs --- MediaBrowser.Api/Playback/MediaInfoService.cs | 143 ++++++++++++------ 1 file changed, 93 insertions(+), 50 deletions(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index c3032416b8..1730db89a7 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -407,8 +407,13 @@ namespace MediaBrowser.Api.Playback if (mediaSource.SupportsDirectPlay) { - if (mediaSource.IsRemote && forceDirectPlayRemoteMediaSource) + if (mediaSource.IsRemote && forceDirectPlayRemoteMediaSource && user.Policy.ForceRemoteSourceTranscoding) { + mediaSource.SupportsDirectPlay = false; + } + else if (mediaSource.IsRemote && user.Policy.ForceRemoteSourceTranscoding) + { + mediaSource.SupportsDirectPlay = false; } else { @@ -455,74 +460,112 @@ namespace MediaBrowser.Api.Playback if (mediaSource.SupportsDirectStream) { - options.MaxBitrate = GetMaxBitrate(maxBitrate, user); - - if (item is Audio) - { - if (!user.Policy.EnableAudioPlaybackTranscoding) - { - options.ForceDirectStream = true; - } - } - else if (item is Video) - { - if (!user.Policy.EnableAudioPlaybackTranscoding && !user.Policy.EnableVideoPlaybackTranscoding && !user.Policy.EnablePlaybackRemuxing) - { - options.ForceDirectStream = true; - } - } - - // The MediaSource supports direct stream, now test to see if the client supports it - var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ? - streamBuilder.BuildAudioItem(options) : - streamBuilder.BuildVideoItem(options); - - if (streamInfo == null || !streamInfo.IsDirectStream) + if (mediaSource.IsRemote && forceDirectPlayRemoteMediaSource && user.Policy.ForceRemoteSourceTranscoding) { mediaSource.SupportsDirectStream = false; } - - if (streamInfo != null) + else if (mediaSource.IsRemote && user.Policy.ForceRemoteSourceTranscoding) { - SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); + mediaSource.SupportsDirectStream = false; } - } + } + else + { + options.MaxBitrate = GetMaxBitrate(maxBitrate, user); + { + if (item is Audio) + if (!user.Policy.EnableAudioPlaybackTranscoding) + { + options.ForceDirectStream = true; + } + } + else if (item is Video) + { + if (!user.Policy.EnableAudioPlaybackTranscoding && !user.Policy.EnableVideoPlaybackTranscoding && !user.Policy.EnablePlaybackRemuxing) + { + options.ForceDirectStream = true; + } + } + // The MediaSource supports direct stream, now test to see if the client supports it + var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ? + streamBuilder.BuildAudioItem(options) : + streamBuilder.BuildVideoItem(options); + if (streamInfo == null || !streamInfo.IsDirectStream) + { + mediaSource.SupportsDirectStream = false; + } + if (streamInfo != null) + { + SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); + } + } + } if (mediaSource.SupportsTranscoding) { - options.MaxBitrate = GetMaxBitrate(maxBitrate, user); - + if (mediaSource.IsRemote && user.Policy.ForceRemoteSourceTranscoding) + { + if (GetMaxBitrate(maxBitrate, user) < mediaSource.Bitrate) + { + options.MaxBitrate = GetMaxBitrate(maxBitrate, user); + } + else + { + options.MaxBitrate = mediaSource.Bitrate; + } + } + else + { + options.MaxBitrate = GetMaxBitrate(maxBitrate, user); + } + // The MediaSource supports direct stream, now test to see if the client supports it var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ? streamBuilder.BuildAudioItem(options) : streamBuilder.BuildVideoItem(options); - if (streamInfo != null) - { - streamInfo.PlaySessionId = playSessionId; - - if (streamInfo.PlayMethod == PlayMethod.Transcode) + if (mediaSource.IsRemote && user.Policy.ForceRemoteSourceTranscoding) + { + if (streamInfo != null) { + streamInfo.PlaySessionId = playSessionId; streamInfo.StartPositionTicks = startTimeTicks; mediaSource.TranscodingUrl = streamInfo.ToUrl("-", auth.Token).TrimStart('-'); - - if (!allowVideoStreamCopy) - { - mediaSource.TranscodingUrl += "&allowVideoStreamCopy=false"; - } - if (!allowAudioStreamCopy) - { - mediaSource.TranscodingUrl += "&allowAudioStreamCopy=false"; - } + mediaSource.TranscodingUrl += "&allowVideoStreamCopy=false"; + mediaSource.TranscodingUrl += "&allowAudioStreamCopy=false"; mediaSource.TranscodingContainer = streamInfo.Container; mediaSource.TranscodingSubProtocol = streamInfo.SubProtocol; - } + + // Do this after the above so that StartPositionTicks is set + SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); + } + } + else + { + if (streamInfo != null) + { + streamInfo.PlaySessionId = playSessionId; + if (streamInfo.PlayMethod == PlayMethod.Transcode) + { + streamInfo.StartPositionTicks = startTimeTicks; + mediaSource.TranscodingUrl = streamInfo.ToUrl("-", auth.Token).TrimStart('-'); - // Do this after the above so that StartPositionTicks is set - SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); - } - } - } + if (!allowVideoStreamCopy) + { + mediaSource.TranscodingUrl += "&allowVideoStreamCopy=false"; + } + if (!allowAudioStreamCopy) + { + mediaSource.TranscodingUrl += "&allowAudioStreamCopy=false"; + } + mediaSource.TranscodingContainer = streamInfo.Container; + mediaSource.TranscodingSubProtocol = streamInfo.SubProtocol; + } + // Do this after the above so that StartPositionTicks is set + SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); + } + } + } private long? GetMaxBitrate(long? clientMaxBitrate, User user) { From 77fc77eb823da523a9d37695adf00561781c0c8e Mon Sep 17 00:00:00 2001 From: Artiume Date: Sun, 15 Dec 2019 23:59:46 -0500 Subject: [PATCH 003/881] Update UserPolicy.cs --- MediaBrowser.Model/Users/UserPolicy.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Model/Users/UserPolicy.cs b/MediaBrowser.Model/Users/UserPolicy.cs index 9c3e1f9808..8a6b49d8b2 100644 --- a/MediaBrowser.Model/Users/UserPolicy.cs +++ b/MediaBrowser.Model/Users/UserPolicy.cs @@ -44,6 +44,7 @@ namespace MediaBrowser.Model.Users public bool EnableAudioPlaybackTranscoding { get; set; } public bool EnableVideoPlaybackTranscoding { get; set; } public bool EnablePlaybackRemuxing { get; set; } + public bool ForceRemoteSourceTranscoding { get; set; } public bool EnableContentDeletion { get; set; } public string[] EnableContentDeletionFromFolders { get; set; } @@ -91,7 +92,8 @@ namespace MediaBrowser.Model.Users EnableAudioPlaybackTranscoding = true; EnableVideoPlaybackTranscoding = true; EnablePlaybackRemuxing = true; - + ForceRemoteSourceTranscoding = false; + EnableLiveTvManagement = true; EnableLiveTvAccess = true; From 64c313a8fb007b7002d0de4e67eb90941e06fd06 Mon Sep 17 00:00:00 2001 From: Artiume Date: Mon, 16 Dec 2019 00:27:48 -0500 Subject: [PATCH 004/881] Update MediaInfoService.cs --- MediaBrowser.Api/Playback/MediaInfoService.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 1730db89a7..78e7bf454c 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -564,9 +564,10 @@ namespace MediaBrowser.Api.Playback // Do this after the above so that StartPositionTicks is set SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); } - } - } - + } + } + } + private long? GetMaxBitrate(long? clientMaxBitrate, User user) { var maxBitrate = clientMaxBitrate; From 3fb7aabfde0e3c67d6abe8345de8ef92279b038e Mon Sep 17 00:00:00 2001 From: Artiume Date: Mon, 16 Dec 2019 00:40:25 -0500 Subject: [PATCH 005/881] Update MediaInfoService.cs --- MediaBrowser.Api/Playback/MediaInfoService.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 78e7bf454c..4cf29d72c4 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -671,5 +671,4 @@ namespace MediaBrowser.Api.Playback }).ThenBy(originalList.IndexOf) .ToArray(); } - } } From 46442e24f8e2fadc1e0e762631fd1f75da009ba5 Mon Sep 17 00:00:00 2001 From: Artiume Date: Mon, 16 Dec 2019 00:43:03 -0500 Subject: [PATCH 006/881] Update MediaInfoService.cs --- MediaBrowser.Api/Playback/MediaInfoService.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 4cf29d72c4..78e7bf454c 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -671,4 +671,5 @@ namespace MediaBrowser.Api.Playback }).ThenBy(originalList.IndexOf) .ToArray(); } + } } From 2457e43decdc17758a2822227611d7f06bb4b7b8 Mon Sep 17 00:00:00 2001 From: Artiume Date: Mon, 16 Dec 2019 00:44:10 -0500 Subject: [PATCH 007/881] Update Dockerfile --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 2a60bf1845..b633e56893 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ ARG FFMPEG_VERSION=latest FROM node:alpine as web-builder ARG JELLYFIN_WEB_VERSION=master RUN apk add curl \ - && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \ + && curl -L https://github.com/artiume/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \ && cd jellyfin-web-* \ && yarn install \ && yarn build \ From 0d571b3ad1506a5dd40bdcb2bf73f85ae7415a24 Mon Sep 17 00:00:00 2001 From: Artiume Date: Mon, 16 Dec 2019 00:59:38 -0500 Subject: [PATCH 008/881] Update Dockerfile --- Dockerfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index b633e56893..f100c27a34 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,8 +4,8 @@ ARG FFMPEG_VERSION=latest FROM node:alpine as web-builder ARG JELLYFIN_WEB_VERSION=master RUN apk add curl \ - && curl -L https://github.com/artiume/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \ - && cd jellyfin-web-* \ + && curl -L https://github.com/artiume/jellyfin-web \ + && cd jellyfin-web \ && yarn install \ && yarn build \ && mv dist /dist From c96d3c35a0fc6f919554156473466eef5a7faebf Mon Sep 17 00:00:00 2001 From: Artiume Date: Mon, 16 Dec 2019 01:09:45 -0500 Subject: [PATCH 009/881] Update Dockerfile --- Dockerfile | 1 - 1 file changed, 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index f100c27a34..e7d36316de 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,6 @@ ARG FFMPEG_VERSION=latest FROM node:alpine as web-builder ARG JELLYFIN_WEB_VERSION=master RUN apk add curl \ - && curl -L https://github.com/artiume/jellyfin-web \ && cd jellyfin-web \ && yarn install \ && yarn build \ From 4e43c70439605b6d92991ddb69387b7d17b3f501 Mon Sep 17 00:00:00 2001 From: Artiume Date: Mon, 16 Dec 2019 01:12:50 -0500 Subject: [PATCH 010/881] Update Dockerfile --- Dockerfile | 1 + 1 file changed, 1 insertion(+) diff --git a/Dockerfile b/Dockerfile index e7d36316de..ea5669eaac 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,6 +3,7 @@ ARG FFMPEG_VERSION=latest FROM node:alpine as web-builder ARG JELLYFIN_WEB_VERSION=master +COPY --from=builder /jellyfin/jellyfin-web /jellyfin/jellyfin-web RUN apk add curl \ && cd jellyfin-web \ && yarn install \ From 5a9e08e0de3b088f6a7b4067cfee92f7d20fb64b Mon Sep 17 00:00:00 2001 From: Artiume Date: Mon, 16 Dec 2019 01:26:36 -0500 Subject: [PATCH 011/881] Update Dockerfile --- Dockerfile | 1 - 1 file changed, 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index ea5669eaac..e7d36316de 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,7 +3,6 @@ ARG FFMPEG_VERSION=latest FROM node:alpine as web-builder ARG JELLYFIN_WEB_VERSION=master -COPY --from=builder /jellyfin/jellyfin-web /jellyfin/jellyfin-web RUN apk add curl \ && cd jellyfin-web \ && yarn install \ From b31f4ccbc2299b8b327b3ffa3ffc0d40f8b08bf5 Mon Sep 17 00:00:00 2001 From: Artiume Date: Mon, 16 Dec 2019 14:53:42 -0500 Subject: [PATCH 012/881] Update MediaInfoService.cs --- MediaBrowser.Api/Playback/MediaInfoService.cs | 156 +++++++----------- 1 file changed, 56 insertions(+), 100 deletions(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 78e7bf454c..c3032416b8 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -407,13 +407,8 @@ namespace MediaBrowser.Api.Playback if (mediaSource.SupportsDirectPlay) { - if (mediaSource.IsRemote && forceDirectPlayRemoteMediaSource && user.Policy.ForceRemoteSourceTranscoding) + if (mediaSource.IsRemote && forceDirectPlayRemoteMediaSource) { - mediaSource.SupportsDirectPlay = false; - } - else if (mediaSource.IsRemote && user.Policy.ForceRemoteSourceTranscoding) - { - mediaSource.SupportsDirectPlay = false; } else { @@ -460,114 +455,75 @@ namespace MediaBrowser.Api.Playback if (mediaSource.SupportsDirectStream) { - if (mediaSource.IsRemote && forceDirectPlayRemoteMediaSource && user.Policy.ForceRemoteSourceTranscoding) - { - mediaSource.SupportsDirectStream = false; - } - else if (mediaSource.IsRemote && user.Policy.ForceRemoteSourceTranscoding) - { - mediaSource.SupportsDirectStream = false; - } - } - else - { - options.MaxBitrate = GetMaxBitrate(maxBitrate, user); - { - if (item is Audio) - if (!user.Policy.EnableAudioPlaybackTranscoding) - { - options.ForceDirectStream = true; - } - } - else if (item is Video) - { - if (!user.Policy.EnableAudioPlaybackTranscoding && !user.Policy.EnableVideoPlaybackTranscoding && !user.Policy.EnablePlaybackRemuxing) - { - options.ForceDirectStream = true; - } - } - // The MediaSource supports direct stream, now test to see if the client supports it - var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ? - streamBuilder.BuildAudioItem(options) : - streamBuilder.BuildVideoItem(options); - if (streamInfo == null || !streamInfo.IsDirectStream) - { - mediaSource.SupportsDirectStream = false; - } - if (streamInfo != null) - { - SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); - } - } - } + options.MaxBitrate = GetMaxBitrate(maxBitrate, user); + + if (item is Audio) + { + if (!user.Policy.EnableAudioPlaybackTranscoding) + { + options.ForceDirectStream = true; + } + } + else if (item is Video) + { + if (!user.Policy.EnableAudioPlaybackTranscoding && !user.Policy.EnableVideoPlaybackTranscoding && !user.Policy.EnablePlaybackRemuxing) + { + options.ForceDirectStream = true; + } + } - if (mediaSource.SupportsTranscoding) - { - if (mediaSource.IsRemote && user.Policy.ForceRemoteSourceTranscoding) - { - if (GetMaxBitrate(maxBitrate, user) < mediaSource.Bitrate) - { - options.MaxBitrate = GetMaxBitrate(maxBitrate, user); - } - else - { - options.MaxBitrate = mediaSource.Bitrate; - } - } - else - { - options.MaxBitrate = GetMaxBitrate(maxBitrate, user); - } - // The MediaSource supports direct stream, now test to see if the client supports it var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ? streamBuilder.BuildAudioItem(options) : streamBuilder.BuildVideoItem(options); - if (mediaSource.IsRemote && user.Policy.ForceRemoteSourceTranscoding) - { - if (streamInfo != null) + if (streamInfo == null || !streamInfo.IsDirectStream) + { + mediaSource.SupportsDirectStream = false; + } + + if (streamInfo != null) + { + SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); + } + } + + if (mediaSource.SupportsTranscoding) + { + options.MaxBitrate = GetMaxBitrate(maxBitrate, user); + + // The MediaSource supports direct stream, now test to see if the client supports it + var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ? + streamBuilder.BuildAudioItem(options) : + streamBuilder.BuildVideoItem(options); + + if (streamInfo != null) + { + streamInfo.PlaySessionId = playSessionId; + + if (streamInfo.PlayMethod == PlayMethod.Transcode) { - streamInfo.PlaySessionId = playSessionId; streamInfo.StartPositionTicks = startTimeTicks; mediaSource.TranscodingUrl = streamInfo.ToUrl("-", auth.Token).TrimStart('-'); - mediaSource.TranscodingUrl += "&allowVideoStreamCopy=false"; - mediaSource.TranscodingUrl += "&allowAudioStreamCopy=false"; + + if (!allowVideoStreamCopy) + { + mediaSource.TranscodingUrl += "&allowVideoStreamCopy=false"; + } + if (!allowAudioStreamCopy) + { + mediaSource.TranscodingUrl += "&allowAudioStreamCopy=false"; + } mediaSource.TranscodingContainer = streamInfo.Container; mediaSource.TranscodingSubProtocol = streamInfo.SubProtocol; - - // Do this after the above so that StartPositionTicks is set - SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); - } - } - else - { - if (streamInfo != null) - { - streamInfo.PlaySessionId = playSessionId; - if (streamInfo.PlayMethod == PlayMethod.Transcode) - { - streamInfo.StartPositionTicks = startTimeTicks; - mediaSource.TranscodingUrl = streamInfo.ToUrl("-", auth.Token).TrimStart('-'); - - if (!allowVideoStreamCopy) - { - mediaSource.TranscodingUrl += "&allowVideoStreamCopy=false"; - } - if (!allowAudioStreamCopy) - { - mediaSource.TranscodingUrl += "&allowAudioStreamCopy=false"; - } - mediaSource.TranscodingContainer = streamInfo.Container; - mediaSource.TranscodingSubProtocol = streamInfo.SubProtocol; - } - // Do this after the above so that StartPositionTicks is set - SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); } - } + + // Do this after the above so that StartPositionTicks is set + SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); + } } } - + private long? GetMaxBitrate(long? clientMaxBitrate, User user) { var maxBitrate = clientMaxBitrate; From f3e7c72bacb0c5682064b9cb3492b33a96dcc697 Mon Sep 17 00:00:00 2001 From: Artiume Date: Mon, 16 Dec 2019 15:22:18 -0500 Subject: [PATCH 013/881] Update MediaInfoService.cs --- MediaBrowser.Api/Playback/MediaInfoService.cs | 144 ++++++++++++------ 1 file changed, 97 insertions(+), 47 deletions(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index c3032416b8..09805b8054 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -407,8 +407,13 @@ namespace MediaBrowser.Api.Playback if (mediaSource.SupportsDirectPlay) { - if (mediaSource.IsRemote && forceDirectPlayRemoteMediaSource) + if (mediaSource.IsRemote && forceDirectPlayRemoteMediaSource && user.Policy.ForceRemoteSourceTranscoding) { + mediaSource.SupportsDirectPlay = false; + } + else if (mediaSource.IsRemote && user.Policy.ForceRemoteSourceTranscoding) + { + mediaSource.SupportsDirectPlay = false; } else { @@ -455,72 +460,117 @@ namespace MediaBrowser.Api.Playback if (mediaSource.SupportsDirectStream) { - options.MaxBitrate = GetMaxBitrate(maxBitrate, user); - - if (item is Audio) - { - if (!user.Policy.EnableAudioPlaybackTranscoding) - { - options.ForceDirectStream = true; - } - } - else if (item is Video) - { - if (!user.Policy.EnableAudioPlaybackTranscoding && !user.Policy.EnableVideoPlaybackTranscoding && !user.Policy.EnablePlaybackRemuxing) - { - options.ForceDirectStream = true; - } - } - - // The MediaSource supports direct stream, now test to see if the client supports it - var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ? - streamBuilder.BuildAudioItem(options) : - streamBuilder.BuildVideoItem(options); - - if (streamInfo == null || !streamInfo.IsDirectStream) + if (mediaSource.IsRemote && forceDirectPlayRemoteMediaSource && user.Policy.ForceRemoteSourceTranscoding) { mediaSource.SupportsDirectStream = false; } - - if (streamInfo != null) + else if (mediaSource.IsRemote && user.Policy.ForceRemoteSourceTranscoding) { - SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); + mediaSource.SupportsDirectStream = false; } + else + { + options.MaxBitrate = GetMaxBitrate(maxBitrate, user); + + if (item is Audio) + { + if (!user.Policy.EnableAudioPlaybackTranscoding) + { + options.ForceDirectStream = true; + } + } + else if (item is Video) + { + if (!user.Policy.EnableAudioPlaybackTranscoding && !user.Policy.EnableVideoPlaybackTranscoding && !user.Policy.EnablePlaybackRemuxing) + { + options.ForceDirectStream = true; + } + } + + // The MediaSource supports direct stream, now test to see if the client supports it + var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ? + streamBuilder.BuildAudioItem(options) : + streamBuilder.BuildVideoItem(options); + + if (streamInfo == null || !streamInfo.IsDirectStream) + { + mediaSource.SupportsDirectStream = false; + } + + if (streamInfo != null) + { + SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); + } + } } if (mediaSource.SupportsTranscoding) { - options.MaxBitrate = GetMaxBitrate(maxBitrate, user); - + if (mediaSource.IsRemote && user.Policy.ForceRemoteSourceTranscoding) + { + if (GetMaxBitrate(maxBitrate, user) < mediaSource.Bitrate) + { + options.MaxBitrate = GetMaxBitrate(maxBitrate, user); + } + else + { + options.MaxBitrate = mediaSource.Bitrate; + } + } + else + { + options.MaxBitrate = GetMaxBitrate(maxBitrate, user); + } + // The MediaSource supports direct stream, now test to see if the client supports it var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ? streamBuilder.BuildAudioItem(options) : streamBuilder.BuildVideoItem(options); + - if (streamInfo != null) - { - streamInfo.PlaySessionId = playSessionId; - - if (streamInfo.PlayMethod == PlayMethod.Transcode) + if (mediaSource.IsRemote && user.Policy.ForceRemoteSourceTranscoding) + { + if (streamInfo != null) { + streamInfo.PlaySessionId = playSessionId; streamInfo.StartPositionTicks = startTimeTicks; mediaSource.TranscodingUrl = streamInfo.ToUrl("-", auth.Token).TrimStart('-'); - - if (!allowVideoStreamCopy) - { - mediaSource.TranscodingUrl += "&allowVideoStreamCopy=false"; - } - if (!allowAudioStreamCopy) - { - mediaSource.TranscodingUrl += "&allowAudioStreamCopy=false"; - } + mediaSource.TranscodingUrl += "&allowVideoStreamCopy=false"; + mediaSource.TranscodingUrl += "&allowAudioStreamCopy=false"; mediaSource.TranscodingContainer = streamInfo.Container; mediaSource.TranscodingSubProtocol = streamInfo.SubProtocol; - } + + // Do this after the above so that StartPositionTicks is set + SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); + } + } + else + { + if (streamInfo != null) + { + streamInfo.PlaySessionId = playSessionId; - // Do this after the above so that StartPositionTicks is set - SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); - } + if (streamInfo.PlayMethod == PlayMethod.Transcode) + { + streamInfo.StartPositionTicks = startTimeTicks; + mediaSource.TranscodingUrl = streamInfo.ToUrl("-", auth.Token).TrimStart('-'); + + if (!allowVideoStreamCopy) + { + mediaSource.TranscodingUrl += "&allowVideoStreamCopy=false"; + } + if (!allowAudioStreamCopy) + { + mediaSource.TranscodingUrl += "&allowAudioStreamCopy=false"; + } + mediaSource.TranscodingContainer = streamInfo.Container; + mediaSource.TranscodingSubProtocol = streamInfo.SubProtocol; + } + + // Do this after the above so that StartPositionTicks is set + SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); + } + } } } From b626508bc8f51e1a6e6ac385dad0cfe4dc6a21b2 Mon Sep 17 00:00:00 2001 From: Artiume Date: Mon, 16 Dec 2019 15:23:43 -0500 Subject: [PATCH 014/881] Update Dockerfile --- Dockerfile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index e7d36316de..2a60bf1845 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,8 @@ ARG FFMPEG_VERSION=latest FROM node:alpine as web-builder ARG JELLYFIN_WEB_VERSION=master RUN apk add curl \ - && cd jellyfin-web \ + && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \ + && cd jellyfin-web-* \ && yarn install \ && yarn build \ && mv dist /dist From 5dc3874ebdeac26d7be885b9a44ca1321b4b25cf Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 20 Dec 2019 21:30:51 +0100 Subject: [PATCH 015/881] Enable nullable reference types for Emby.Photos and Emby.Notifications * Enable TreatWarningsAsErrors for Emby.Notifications * Add analyzers to Emby.Notifications --- .../Api/NotificationsService.cs | 115 ++--------------- Emby.Notifications/CoreNotificationTypes.cs | 4 +- Emby.Notifications/Emby.Notifications.csproj | 14 ++ .../NotificationConfigurationFactory.cs | 5 +- ...fications.cs => NotificationEntryPoint.cs} | 121 +++++++++++------- Emby.Notifications/NotificationManager.cs | 37 ++++-- Emby.Photos/Emby.Photos.csproj | 1 + 7 files changed, 138 insertions(+), 159 deletions(-) rename Emby.Notifications/{Notifications.cs => NotificationEntryPoint.cs} (69%) diff --git a/Emby.Notifications/Api/NotificationsService.cs b/Emby.Notifications/Api/NotificationsService.cs index 83845558ad..5591809712 100644 --- a/Emby.Notifications/Api/NotificationsService.cs +++ b/Emby.Notifications/Api/NotificationsService.cs @@ -1,3 +1,8 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1402 +#pragma warning disable SA1600 +#pragma warning disable SA1649 + using System; using System.Collections.Generic; using System.Linq; @@ -12,60 +17,6 @@ using MediaBrowser.Model.Services; namespace Emby.Notifications.Api { - [Route("/Notifications/{UserId}", "GET", Summary = "Gets notifications")] - public class GetNotifications : IReturn - { - [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] - public string UserId { get; set; } - - [ApiMember(Name = "IsRead", Description = "An optional filter by IsRead", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")] - public bool? IsRead { get; set; } - - [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")] - public int? StartIndex { get; set; } - - [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")] - public int? Limit { get; set; } - } - - public class Notification - { - public string Id { get; set; } - - public string UserId { get; set; } - - public DateTime Date { get; set; } - - public bool IsRead { get; set; } - - public string Name { get; set; } - - public string Description { get; set; } - - public string Url { get; set; } - - public NotificationLevel Level { get; set; } - } - - public class NotificationResult - { - public Notification[] Notifications { get; set; } - public int TotalRecordCount { get; set; } - } - - public class NotificationsSummary - { - public int UnreadCount { get; set; } - public NotificationLevel MaxUnreadNotificationLevel { get; set; } - } - - [Route("/Notifications/{UserId}/Summary", "GET", Summary = "Gets a notification summary for a user")] - public class GetNotificationsSummary : IReturn - { - [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] - public string UserId { get; set; } - } - [Route("/Notifications/Types", "GET", Summary = "Gets notification types")] public class GetNotificationTypes : IReturn> { @@ -80,41 +31,21 @@ namespace Emby.Notifications.Api public class AddAdminNotification : IReturnVoid { [ApiMember(Name = "Name", Description = "The notification's name", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")] - public string Name { get; set; } + public string Name { get; set; } = string.Empty; [ApiMember(Name = "Description", Description = "The notification's description", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")] - public string Description { get; set; } + public string Description { get; set; } = string.Empty; [ApiMember(Name = "ImageUrl", Description = "The notification's image url", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")] - public string ImageUrl { get; set; } + public string? ImageUrl { get; set; } [ApiMember(Name = "Url", Description = "The notification's info url", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")] - public string Url { get; set; } + public string? Url { get; set; } [ApiMember(Name = "Level", Description = "The notification level", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")] public NotificationLevel Level { get; set; } } - [Route("/Notifications/{UserId}/Read", "POST", Summary = "Marks notifications as read")] - public class MarkRead : IReturnVoid - { - [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] - public string UserId { get; set; } - - [ApiMember(Name = "Ids", Description = "A list of notification ids, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)] - public string Ids { get; set; } - } - - [Route("/Notifications/{UserId}/Unread", "POST", Summary = "Marks notifications as unread")] - public class MarkUnread : IReturnVoid - { - [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] - public string UserId { get; set; } - - [ApiMember(Name = "Ids", Description = "A list of notification ids, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)] - public string Ids { get; set; } - } - [Authenticated] public class NotificationsService : IService { @@ -129,30 +60,19 @@ namespace Emby.Notifications.Api public object Get(GetNotificationTypes request) { + _ = request; // Silence unused variable warning return _notificationManager.GetNotificationTypes(); } public object Get(GetNotificationServices request) { + _ = request; // Silence unused variable warning return _notificationManager.GetNotificationServices().ToList(); } - public object Get(GetNotificationsSummary request) - { - return new NotificationsSummary - { - - }; - } - public Task Post(AddAdminNotification request) { // This endpoint really just exists as post of a real with sickbeard - return AddNotification(request); - } - - private Task AddNotification(AddAdminNotification request) - { var notification = new NotificationRequest { Date = DateTime.UtcNow, @@ -165,18 +85,5 @@ namespace Emby.Notifications.Api return _notificationManager.SendNotification(notification, CancellationToken.None); } - - public void Post(MarkRead request) - { - } - - public void Post(MarkUnread request) - { - } - - public object Get(GetNotifications request) - { - return new NotificationResult(); - } } } diff --git a/Emby.Notifications/CoreNotificationTypes.cs b/Emby.Notifications/CoreNotificationTypes.cs index 0f9fc08d99..73e0b0256a 100644 --- a/Emby.Notifications/CoreNotificationTypes.cs +++ b/Emby.Notifications/CoreNotificationTypes.cs @@ -1,7 +1,9 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.Linq; -using MediaBrowser.Controller; using MediaBrowser.Controller.Notifications; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.Notifications; diff --git a/Emby.Notifications/Emby.Notifications.csproj b/Emby.Notifications/Emby.Notifications.csproj index 004ded77b1..e6bf785bff 100644 --- a/Emby.Notifications/Emby.Notifications.csproj +++ b/Emby.Notifications/Emby.Notifications.csproj @@ -4,6 +4,8 @@ netstandard2.1 false true + true + enable @@ -16,4 +18,16 @@ + + + + + + + + + + ../jellyfin.ruleset + + diff --git a/Emby.Notifications/NotificationConfigurationFactory.cs b/Emby.Notifications/NotificationConfigurationFactory.cs index d08475f7d2..b168ed221b 100644 --- a/Emby.Notifications/NotificationConfigurationFactory.cs +++ b/Emby.Notifications/NotificationConfigurationFactory.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Collections.Generic; using MediaBrowser.Common.Configuration; using MediaBrowser.Model.Notifications; @@ -13,7 +16,7 @@ namespace Emby.Notifications new ConfigurationStore { Key = "notifications", - ConfigurationType = typeof (NotificationOptions) + ConfigurationType = typeof(NotificationOptions) } }; } diff --git a/Emby.Notifications/Notifications.cs b/Emby.Notifications/NotificationEntryPoint.cs similarity index 69% rename from Emby.Notifications/Notifications.cs rename to Emby.Notifications/NotificationEntryPoint.cs index 7aa1e7ae89..ab92822fa2 100644 --- a/Emby.Notifications/Notifications.cs +++ b/Emby.Notifications/NotificationEntryPoint.cs @@ -21,70 +21,85 @@ using Microsoft.Extensions.Logging; namespace Emby.Notifications { /// - /// Creates notifications for various system events + /// Creates notifications for various system events. /// - public class Notifications : IServerEntryPoint + public class NotificationEntryPoint : IServerEntryPoint { private readonly ILogger _logger; - + private readonly IActivityManager _activityManager; + private readonly ILocalizationManager _localization; private readonly INotificationManager _notificationManager; - private readonly ILibraryManager _libraryManager; private readonly IServerApplicationHost _appHost; - - private Timer LibraryUpdateTimer { get; set; } - private readonly object _libraryChangedSyncLock = new object(); - private readonly IConfigurationManager _config; - private readonly ILocalizationManager _localization; - private readonly IActivityManager _activityManager; + + private readonly object _libraryChangedSyncLock = new object(); + private readonly List _itemsAdded = new List(); + + private Timer? _libraryUpdateTimer; private string[] _coreNotificationTypes; - public Notifications( + private bool _disposed = false; + + /// + /// Initializes a new instance of the class. + /// + /// The logger. + /// The activity manager. + /// The localization manager. + /// The notification manager. + /// The library manager. + /// The application host. + /// The configuration manager. + public NotificationEntryPoint( + ILogger logger, IActivityManager activityManager, ILocalizationManager localization, - ILogger logger, INotificationManager notificationManager, ILibraryManager libraryManager, IServerApplicationHost appHost, IConfigurationManager config) { _logger = logger; + _activityManager = activityManager; + _localization = localization; _notificationManager = notificationManager; _libraryManager = libraryManager; _appHost = appHost; _config = config; - _localization = localization; - _activityManager = activityManager; _coreNotificationTypes = new CoreNotificationTypes(localization).GetNotificationTypes().Select(i => i.Type).ToArray(); } + /// public Task RunAsync() { - _libraryManager.ItemAdded += _libraryManager_ItemAdded; - _appHost.HasPendingRestartChanged += _appHost_HasPendingRestartChanged; - _appHost.HasUpdateAvailableChanged += _appHost_HasUpdateAvailableChanged; - _activityManager.EntryCreated += _activityManager_EntryCreated; + _libraryManager.ItemAdded += OnLibraryManagerItemAdded; + _appHost.HasPendingRestartChanged += OnAppHostHasPendingRestartChanged; + _appHost.HasUpdateAvailableChanged += OnAppHostHasUpdateAvailableChanged; + _activityManager.EntryCreated += OnActivityManagerEntryCreated; return Task.CompletedTask; } - private async void _appHost_HasPendingRestartChanged(object sender, EventArgs e) + private async void OnAppHostHasPendingRestartChanged(object sender, EventArgs e) { var type = NotificationType.ServerRestartRequired.ToString(); var notification = new NotificationRequest { NotificationType = type, - Name = string.Format(_localization.GetLocalizedString("ServerNameNeedsToBeRestarted"), _appHost.Name) + Name = string.Format( + CultureInfo.InvariantCulture, + _localization.GetLocalizedString("ServerNameNeedsToBeRestarted"), + _appHost.Name) }; await SendNotification(notification, null).ConfigureAwait(false); } - private async void _activityManager_EntryCreated(object sender, GenericEventArgs e) + private async void OnActivityManagerEntryCreated(object sender, GenericEventArgs e) { var entry = e.Argument; @@ -117,7 +132,7 @@ namespace Emby.Notifications return _config.GetConfiguration("notifications"); } - private async void _appHost_HasUpdateAvailableChanged(object sender, EventArgs e) + private async void OnAppHostHasUpdateAvailableChanged(object sender, EventArgs e) { if (!_appHost.HasUpdateAvailable) { @@ -136,8 +151,7 @@ namespace Emby.Notifications await SendNotification(notification, null).ConfigureAwait(false); } - private readonly List _itemsAdded = new List(); - private void _libraryManager_ItemAdded(object sender, ItemChangeEventArgs e) + private void OnLibraryManagerItemAdded(object sender, ItemChangeEventArgs e) { if (!FilterItem(e.Item)) { @@ -146,14 +160,17 @@ namespace Emby.Notifications lock (_libraryChangedSyncLock) { - if (LibraryUpdateTimer == null) + if (_libraryUpdateTimer == null) { - LibraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, 5000, - Timeout.Infinite); + _libraryUpdateTimer = new Timer( + LibraryUpdateTimerCallback, + null, + 5000, + Timeout.Infinite); } else { - LibraryUpdateTimer.Change(5000, Timeout.Infinite); + _libraryUpdateTimer.Change(5000, Timeout.Infinite); } _itemsAdded.Add(e.Item); @@ -188,7 +205,8 @@ namespace Emby.Notifications { items = _itemsAdded.ToList(); _itemsAdded.Clear(); - DisposeLibraryUpdateTimer(); + _libraryUpdateTimer!.Dispose(); // Shouldn't be null as it just set off this callback + _libraryUpdateTimer = null; } items = items.Take(10).ToList(); @@ -198,7 +216,10 @@ namespace Emby.Notifications var notification = new NotificationRequest { NotificationType = NotificationType.NewLibraryContent.ToString(), - Name = string.Format(_localization.GetLocalizedString("ValueHasBeenAddedToLibrary"), GetItemName(item)), + Name = string.Format( + CultureInfo.InvariantCulture, + _localization.GetLocalizedString("ValueHasBeenAddedToLibrary"), + GetItemName(item)), Description = item.Overview }; @@ -206,7 +227,7 @@ namespace Emby.Notifications } } - public static string GetItemName(BaseItem item) + private static string GetItemName(BaseItem item) { var name = item.Name; if (item is Episode episode) @@ -219,6 +240,7 @@ namespace Emby.Notifications episode.IndexNumber.Value, name); } + if (episode.ParentIndexNumber.HasValue) { name = string.Format( @@ -229,7 +251,6 @@ namespace Emby.Notifications } } - if (item is IHasSeries hasSeries) { name = hasSeries.SeriesName + " - " + name; @@ -257,7 +278,7 @@ namespace Emby.Notifications return name; } - private async Task SendNotification(NotificationRequest notification, BaseItem relatedItem) + private async Task SendNotification(NotificationRequest notification, BaseItem? relatedItem) { try { @@ -269,23 +290,37 @@ namespace Emby.Notifications } } + /// public void Dispose() { - DisposeLibraryUpdateTimer(); - - _libraryManager.ItemAdded -= _libraryManager_ItemAdded; - _appHost.HasPendingRestartChanged -= _appHost_HasPendingRestartChanged; - _appHost.HasUpdateAvailableChanged -= _appHost_HasUpdateAvailableChanged; - _activityManager.EntryCreated -= _activityManager_EntryCreated; + Dispose(true); + GC.SuppressFinalize(this); } - private void DisposeLibraryUpdateTimer() + /// + /// 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 disposing) { - if (LibraryUpdateTimer != null) + if (_disposed) { - LibraryUpdateTimer.Dispose(); - LibraryUpdateTimer = null; + return; } + + if (disposing) + { + _libraryUpdateTimer?.Dispose(); + } + + _libraryUpdateTimer = null; + + _libraryManager.ItemAdded -= OnLibraryManagerItemAdded; + _appHost.HasPendingRestartChanged -= OnAppHostHasPendingRestartChanged; + _appHost.HasUpdateAvailableChanged -= OnAppHostHasUpdateAvailableChanged; + _activityManager.EntryCreated -= OnActivityManagerEntryCreated; + + _disposed = true; } } } diff --git a/Emby.Notifications/NotificationManager.cs b/Emby.Notifications/NotificationManager.cs index eecbbea071..836aa3e729 100644 --- a/Emby.Notifications/NotificationManager.cs +++ b/Emby.Notifications/NotificationManager.cs @@ -16,20 +16,32 @@ using Microsoft.Extensions.Logging; namespace Emby.Notifications { + /// + /// NotificationManager class. + /// public class NotificationManager : INotificationManager { private readonly ILogger _logger; private readonly IUserManager _userManager; private readonly IServerConfigurationManager _config; - private INotificationService[] _services; - private INotificationTypeFactory[] _typeFactories; + private INotificationService[] _services = Array.Empty(); + private INotificationTypeFactory[] _typeFactories = Array.Empty(); - public NotificationManager(ILoggerFactory loggerFactory, IUserManager userManager, IServerConfigurationManager config) + /// + /// Initializes a new instance of the class. + /// + /// The logger. + /// the user manager. + /// The server configuration manager. + public NotificationManager( + ILogger logger, + IUserManager userManager, + IServerConfigurationManager config) { + _logger = logger; _userManager = userManager; _config = config; - _logger = loggerFactory.CreateLogger(GetType().Name); } private NotificationOptions GetConfiguration() @@ -37,12 +49,14 @@ namespace Emby.Notifications return _config.GetConfiguration("notifications"); } + /// public Task SendNotification(NotificationRequest request, CancellationToken cancellationToken) { return SendNotification(request, null, cancellationToken); } - public Task SendNotification(NotificationRequest request, BaseItem relatedItem, CancellationToken cancellationToken) + /// + public Task SendNotification(NotificationRequest request, BaseItem? relatedItem, CancellationToken cancellationToken) { var notificationType = request.NotificationType; @@ -64,7 +78,8 @@ namespace Emby.Notifications return Task.WhenAll(tasks); } - private Task SendNotification(NotificationRequest request, + private Task SendNotification( + NotificationRequest request, INotificationService service, IEnumerable users, string title, @@ -79,7 +94,7 @@ namespace Emby.Notifications return Task.WhenAll(tasks); } - private IEnumerable GetUserIds(NotificationRequest request, NotificationOption options) + private IEnumerable GetUserIds(NotificationRequest request, NotificationOption? options) { if (request.SendToUserMode.HasValue) { @@ -109,7 +124,8 @@ namespace Emby.Notifications return request.UserIds; } - private async Task SendNotification(NotificationRequest request, + private async Task SendNotification( + NotificationRequest request, INotificationService service, string title, string description, @@ -161,12 +177,14 @@ namespace Emby.Notifications return GetConfiguration().IsServiceEnabled(service.Name, notificationType); } + /// public void AddParts(IEnumerable services, IEnumerable notificationTypeFactories) { _services = services.ToArray(); _typeFactories = notificationTypeFactories.ToArray(); } + /// public List GetNotificationTypes() { var list = _typeFactories.Select(i => @@ -180,7 +198,6 @@ namespace Emby.Notifications _logger.LogError(ex, "Error in GetNotificationTypes"); return new List(); } - }).SelectMany(i => i).ToList(); var config = GetConfiguration(); @@ -193,13 +210,13 @@ namespace Emby.Notifications return list; } + /// public IEnumerable GetNotificationServices() { return _services.Select(i => new NameIdPair { Name = i.Name, Id = i.Name.GetMD5().ToString("N", CultureInfo.InvariantCulture) - }).OrderBy(i => i.Name); } } diff --git a/Emby.Photos/Emby.Photos.csproj b/Emby.Photos/Emby.Photos.csproj index 64692c3703..8fd18466a1 100644 --- a/Emby.Photos/Emby.Photos.csproj +++ b/Emby.Photos/Emby.Photos.csproj @@ -18,6 +18,7 @@ false true true + enable From 963b69c7b2dd2682b95dcab25602a151e6a6f48a Mon Sep 17 00:00:00 2001 From: Artiume Date: Fri, 20 Dec 2019 23:17:01 -0500 Subject: [PATCH 016/881] Update MediaInfoService.cs --- MediaBrowser.Api/Playback/MediaInfoService.cs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 09805b8054..df6dd82390 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -405,6 +405,7 @@ namespace MediaBrowser.Api.Playback user.Policy.EnableAudioPlaybackTranscoding); } + // Beginning of Playback Determination: Attempt DirectPlay first if (mediaSource.SupportsDirectPlay) { if (mediaSource.IsRemote && forceDirectPlayRemoteMediaSource && user.Policy.ForceRemoteSourceTranscoding) @@ -460,13 +461,13 @@ namespace MediaBrowser.Api.Playback if (mediaSource.SupportsDirectStream) { - if (mediaSource.IsRemote && forceDirectPlayRemoteMediaSource && user.Policy.ForceRemoteSourceTranscoding) + if (mediaSource.IsRemote && forceDirectPlayRemoteMediaSource)// && user.Policy.ForceRemoteSourceTranscoding) { - mediaSource.SupportsDirectStream = false; - } - else if (mediaSource.IsRemote && user.Policy.ForceRemoteSourceTranscoding) - { - mediaSource.SupportsDirectStream = false; + mediaSource.SupportsDirectStream = true; //false + // } + // else if (mediaSource.IsRemote && user.Policy.ForceRemoteSourceTranscoding) + // { + // mediaSource.SupportsDirectStream = false; } else { From 0e920a6d5f18dc6a012908444ce9766acba2dd63 Mon Sep 17 00:00:00 2001 From: Artiume Date: Fri, 20 Dec 2019 23:40:36 -0500 Subject: [PATCH 017/881] Update MediaInfoService.cs --- MediaBrowser.Api/Playback/MediaInfoService.cs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index df6dd82390..187e664756 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -461,13 +461,13 @@ namespace MediaBrowser.Api.Playback if (mediaSource.SupportsDirectStream) { - if (mediaSource.IsRemote && forceDirectPlayRemoteMediaSource)// && user.Policy.ForceRemoteSourceTranscoding) + if (mediaSource.IsRemote && forceDirectPlayRemoteMediaSource && user.Policy.ForceRemoteSourceTranscoding) { - mediaSource.SupportsDirectStream = true; //false - // } - // else if (mediaSource.IsRemote && user.Policy.ForceRemoteSourceTranscoding) - // { - // mediaSource.SupportsDirectStream = false; + mediaSource.SupportsDirectStream = false; + } + else if (mediaSource.IsRemote && user.Policy.ForceRemoteSourceTranscoding) + { + mediaSource.SupportsDirectStream = false; } else { @@ -527,7 +527,6 @@ namespace MediaBrowser.Api.Playback var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ? streamBuilder.BuildAudioItem(options) : streamBuilder.BuildVideoItem(options); - if (mediaSource.IsRemote && user.Policy.ForceRemoteSourceTranscoding) { From 1bab76d80c24bc090322eea3389fda98a7a99d69 Mon Sep 17 00:00:00 2001 From: Artiume Date: Sat, 21 Dec 2019 00:01:43 -0500 Subject: [PATCH 018/881] Revert "Allow valid https requests in .NET Core" --- .../HttpClientManager/HttpClientManager.cs | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs index ff51820ca1..50233ea485 100644 --- a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs +++ b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs @@ -59,17 +59,7 @@ namespace Emby.Server.Implementations.HttpClientManager if (!_httpClients.TryGetValue(key, out var client)) { - var httpClientHandler = new HttpClientHandler() - { - ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => - { - var success = errors == System.Net.Security.SslPolicyErrors.None; - _logger.LogDebug("Validating certificate {Cert}. Success {1}", cert, success); - return success; - } - }; - - client = new HttpClient(httpClientHandler) + client = new HttpClient() { BaseAddress = new Uri(url) }; From f47c7959af72a971d1b812194bf03098e671364f Mon Sep 17 00:00:00 2001 From: Ben Magee Date: Sun, 22 Dec 2019 09:46:09 +0000 Subject: [PATCH 019/881] Wrote tests to cover CustomAuthenticationHandler --- .../Auth/CustomAuthenticationHandlerTests.cs | 170 ++++++++++++++++++ .../Jellyfin.Api.Tests.csproj | 11 ++ 2 files changed, 181 insertions(+) create mode 100644 tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs diff --git a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs new file mode 100644 index 0000000000..bd23ca869b --- /dev/null +++ b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs @@ -0,0 +1,170 @@ +using System; +using System.Linq; +using System.Security.Claims; +using System.Text.Encodings.Web; +using System.Threading.Tasks; +using AutoFixture; +using AutoFixture.AutoMoq; +using Jellyfin.Api.Auth; +using Jellyfin.Api.Constants; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Net; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using Moq; +using Xunit; + +namespace Jellyfin.Api.Tests.Auth +{ + public class CustomAuthenticationHandlerTests + { + private readonly IFixture _fixture; + + private readonly Mock _authServiceMock; + private readonly Mock> _optionsMock; + private readonly Mock _clockMock; + private readonly Mock _serviceProviderMock; + private readonly Mock _authenticationServiceMock; + private readonly UrlEncoder _urlEncoder; + private readonly HttpContext _context; + + private readonly CustomAuthenticationHandler _sut; + private readonly AuthenticationScheme _scheme; + + public CustomAuthenticationHandlerTests() + { + _fixture = new Fixture().Customize(new AutoMoqCustomization {ConfigureMembers = true}); + AllowFixtureCircularDependencies(); + + _authServiceMock = _fixture.Freeze>(); + _optionsMock = _fixture.Freeze>>(); + _clockMock = _fixture.Freeze>(); + _serviceProviderMock = _fixture.Freeze>(); + _authenticationServiceMock = _fixture.Freeze>(); + _fixture.Register(() => new NullLoggerFactory()); + + _urlEncoder = UrlEncoder.Default; + + _serviceProviderMock.Setup(s => s.GetService(typeof(IAuthenticationService))) + .Returns(_authenticationServiceMock.Object); + + _optionsMock.Setup(o => o.Get(It.IsAny())) + .Returns(new AuthenticationSchemeOptions + { + ForwardAuthenticate = null + }); + + _context = new DefaultHttpContext + { + RequestServices = _serviceProviderMock.Object + }; + + _scheme = new AuthenticationScheme( + _fixture.Create(), + null, + typeof(CustomAuthenticationHandler)); + + _sut = _fixture.Create(); + _sut.InitializeAsync(_scheme, _context).Wait(); + } + + [Fact] + public async Task HandleAuthenticateAsyncShouldFailWithNullUser() + { + _authServiceMock.Setup( + a => a.Authenticate( + It.IsAny(), + It.IsAny())) + .Returns((User) null); + + var authenticateResult = await _sut.AuthenticateAsync(); + + Assert.False(authenticateResult.Succeeded); + Assert.Equal("Invalid user", authenticateResult.Failure.Message); + } + + [Fact] + public async Task HandleAuthenticateAsyncShouldFailOnSecurityException() + { + var errorMessage = _fixture.Create(); + + _authServiceMock.Setup( + a => a.Authenticate( + It.IsAny(), + It.IsAny())) + .Throws(new SecurityException(errorMessage)); + + var authenticateResult = await _sut.AuthenticateAsync(); + + Assert.False(authenticateResult.Succeeded); + Assert.Equal(errorMessage, authenticateResult.Failure.Message); + } + + [Fact] + public async Task HandleAuthenticateAsyncShouldSucceedWithUser() + { + SetupUser(); + var authenticateResult = await _sut.AuthenticateAsync(); + + Assert.True(authenticateResult.Succeeded); + Assert.Null(authenticateResult.Failure); + } + + [Fact] + public async Task HandleAuthenticateAsyncShouldAssignNameClaim() + { + var user = SetupUser(); + var authenticateResult = await _sut.AuthenticateAsync(); + + Assert.True(authenticateResult.Principal.HasClaim(ClaimTypes.Name, user.Name)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task HandleAuthenticateAsyncShouldAssignRoleClaim(bool isAdmin) + { + var user = SetupUser(isAdmin); + var authenticateResult = await _sut.AuthenticateAsync(); + + var expectedRole = user.Policy.IsAdministrator ? UserRoles.Administrator : UserRoles.User; + Assert.True(authenticateResult.Principal.HasClaim(ClaimTypes.Role, expectedRole)); + } + + [Fact] + public async Task HandleAuthenticateAsyncShouldAssignTicketCorrectScheme() + { + SetupUser(); + var authenticatedResult = await _sut.AuthenticateAsync(); + + Assert.Equal(_scheme.Name, authenticatedResult.Ticket.AuthenticationScheme); + } + + private User SetupUser(bool isAdmin=false) + { + var user = _fixture.Create(); + user.Policy.IsAdministrator = isAdmin; + + _authServiceMock.Setup( + a => a.Authenticate( + It.IsAny(), + It.IsAny())) + .Returns(user); + + return user; + } + + private void AllowFixtureCircularDependencies() + { + // A circular dependency exists in the User entity around parent folders, + // this allows Autofixture to generate a User regardless, rather than throw + // an error. + _fixture.Behaviors.OfType().ToList() + .ForEach(b => _fixture.Behaviors.Remove(b)); + _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); + } + } +} diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 1671b8d797..77c58040e4 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -6,6 +6,10 @@ + + + + @@ -15,6 +19,13 @@ + + + + + + ..\..\..\..\..\..\usr\local\share\dotnet\packs\Microsoft.AspNetCore.App.Ref\3.0.0\ref\netcoreapp3.0\Microsoft.AspNetCore.Authentication.dll + From 57aec873d08159d0e5ffb43ecf1e0a05f43038be Mon Sep 17 00:00:00 2001 From: Waldemar Tomme Date: Sun, 22 Dec 2019 13:01:18 +0100 Subject: [PATCH 020/881] Add check if output container supports "global_header" flag --- .../MediaEncoding/EncodingHelper.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 020f0553ed..424dd0dbe8 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2750,6 +2750,8 @@ namespace MediaBrowser.Controller.MediaEncoding args += " -mpegts_m2ts_mode 1"; } + var supportsGlobalHeaderFlag = state.OutputContainer != "mkv"; + if (string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase)) { if (state.VideoStream != null @@ -2770,7 +2772,12 @@ namespace MediaBrowser.Controller.MediaEncoding if (!state.RunTimeTicks.HasValue) { - args += " -flags -global_header -fflags +genpts"; + if(supportsGlobalHeaderFlag) + { + args += " -flags -global_header"; + } + + args += " -fflags +genpts"; } } else @@ -2816,7 +2823,7 @@ namespace MediaBrowser.Controller.MediaEncoding args += " " + qualityParam.Trim(); } - if (!state.RunTimeTicks.HasValue) + if (supportsGlobalHeaderFlag && !state.RunTimeTicks.HasValue) { args += " -flags -global_header"; } From 8c4e679ff4c78e5361d14f151bf4d40b2312478c Mon Sep 17 00:00:00 2001 From: Ben Magee Date: Sun, 22 Dec 2019 22:36:11 +0000 Subject: [PATCH 021/881] PR style comments --- .../Auth/CustomAuthenticationHandlerTests.cs | 9 +++++++-- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs index bd23ca869b..f202f59e61 100644 --- a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs +++ b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs @@ -36,7 +36,12 @@ namespace Jellyfin.Api.Tests.Auth public CustomAuthenticationHandlerTests() { - _fixture = new Fixture().Customize(new AutoMoqCustomization {ConfigureMembers = true}); + var fixtureCustomizations = new AutoMoqCustomization + { + ConfigureMembers = true + }; + + _fixture = new Fixture().Customize(fixtureCustomizations); AllowFixtureCircularDependencies(); _authServiceMock = _fixture.Freeze>(); @@ -143,7 +148,7 @@ namespace Jellyfin.Api.Tests.Auth Assert.Equal(_scheme.Name, authenticatedResult.Ticket.AuthenticationScheme); } - private User SetupUser(bool isAdmin=false) + private User SetupUser(bool isAdmin = false) { var user = _fixture.Create(); user.Policy.IsAdministrator = isAdmin; diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 77c58040e4..208a7bb30d 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -19,7 +19,7 @@ - + From 8d06d0dbdf7bbb156df0c002f2f0af6806be2b8b Mon Sep 17 00:00:00 2001 From: Ben Magee Date: Sun, 22 Dec 2019 22:39:29 +0000 Subject: [PATCH 022/881] Removed unneeded dependency --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 6 ------ 1 file changed, 6 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 208a7bb30d..ac54cb26e3 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -22,10 +22,4 @@ - - - ..\..\..\..\..\..\usr\local\share\dotnet\packs\Microsoft.AspNetCore.App.Ref\3.0.0\ref\netcoreapp3.0\Microsoft.AspNetCore.Authentication.dll - - - From ef75455178dda5542cbe9b32cafc4705de299723 Mon Sep 17 00:00:00 2001 From: Ben Magee Date: Sun, 22 Dec 2019 22:54:46 +0000 Subject: [PATCH 023/881] Test RequiresElevationHandler for all roles --- .../RequiresElevationHandlerTests.cs | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 tests/Jellyfin.Api.Tests/Auth/RequiresElevationPolicy/RequiresElevationHandlerTests.cs diff --git a/tests/Jellyfin.Api.Tests/Auth/RequiresElevationPolicy/RequiresElevationHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/RequiresElevationPolicy/RequiresElevationHandlerTests.cs new file mode 100644 index 0000000000..e2beea1ad8 --- /dev/null +++ b/tests/Jellyfin.Api.Tests/Auth/RequiresElevationPolicy/RequiresElevationHandlerTests.cs @@ -0,0 +1,38 @@ +using System.Collections.Generic; +using System.Security.Claims; +using System.Threading.Tasks; +using Jellyfin.Api.Auth.RequiresElevationPolicy; +using Jellyfin.Api.Constants; +using Microsoft.AspNetCore.Authorization; +using Xunit; + +namespace Jellyfin.Api.Tests.Auth.RequiresElevationPolicy +{ + public class RequiresElevationHandlerTests + { + private readonly RequiresElevationHandler _sut; + + public RequiresElevationHandlerTests() + { + _sut = new RequiresElevationHandler(); + } + + [Theory] + [InlineData(UserRoles.Administrator, true)] + [InlineData(UserRoles.User, false)] + [InlineData(UserRoles.Guest, false)] + public async Task ShouldHandleRolesCorrectly(string role, bool shouldSucceed) + { + var requirements = new List {new RequiresElevationRequirement()}; + + var claims = new[] {new Claim(ClaimTypes.Role, role)}; + var identity = new ClaimsIdentity(claims); + var user = new ClaimsPrincipal(identity); + + var context = new AuthorizationHandlerContext(requirements, user, null); + + await _sut.HandleAsync(context); + Assert.Equal(shouldSucceed, context.HasSucceeded); + } + } +} From 00c6d392a13bb6a54b27c4c8c177eac5d8de5652 Mon Sep 17 00:00:00 2001 From: Ben Magee Date: Sun, 22 Dec 2019 23:18:42 +0000 Subject: [PATCH 024/881] Added tests for FirstTimeSetupOrElevatedHandler --- .../FirstTimeSetupOrElevatedHandlerTests.cs | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 tests/Jellyfin.Api.Tests/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandlerTests.cs diff --git a/tests/Jellyfin.Api.Tests/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandlerTests.cs new file mode 100644 index 0000000000..84cdbe360d --- /dev/null +++ b/tests/Jellyfin.Api.Tests/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandlerTests.cs @@ -0,0 +1,77 @@ +using System.Collections.Generic; +using System.Security.Claims; +using System.Threading.Tasks; +using AutoFixture; +using AutoFixture.AutoMoq; +using Jellyfin.Api.Auth.FirstTimeSetupOrElevatedPolicy; +using Jellyfin.Api.Constants; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Model.Configuration; +using Microsoft.AspNetCore.Authorization; +using Moq; +using Xunit; + +namespace Jellyfin.Api.Tests.Auth.FirstTimeSetupOrElevatedPolicy +{ + public class FirstTimeSetupOrElevatedHandlerTests + { + private readonly Mock _configurationManagerMock; + private readonly List _requirements; + private readonly FirstTimeSetupOrElevatedHandler _sut; + + public FirstTimeSetupOrElevatedHandlerTests() + { + var fixture = new Fixture().Customize(new AutoMoqCustomization()); + _configurationManagerMock = fixture.Freeze>(); + _requirements = new List {new FirstTimeSetupOrElevatedRequirement()}; + + _sut = fixture.Create(); + } + + [Theory] + [InlineData(UserRoles.Administrator)] + [InlineData(UserRoles.Guest)] + [InlineData(UserRoles.User)] + public async Task ShouldSucceedIfStartupWizardIncomplete(string userRole) + { + SetupConfigurationManager(false); + var user = SetupUser(userRole); + var context = new AuthorizationHandlerContext(_requirements, user, null); + + await _sut.HandleAsync(context); + Assert.True(context.HasSucceeded); + } + + [Theory] + [InlineData(UserRoles.Administrator, true)] + [InlineData(UserRoles.Guest, false)] + [InlineData(UserRoles.User, false)] + public async Task ShouldRequireAdministratorIfStartupWizardComplete(string userRole, bool shouldSucceed) + { + SetupConfigurationManager(true); + var user = SetupUser(userRole); + var context = new AuthorizationHandlerContext(_requirements, user, null); + + await _sut.HandleAsync(context); + Assert.Equal(shouldSucceed, context.HasSucceeded); + } + + private static ClaimsPrincipal SetupUser(string role) + { + var claims = new[] {new Claim(ClaimTypes.Role, role)}; + var identity = new ClaimsIdentity(claims); + return new ClaimsPrincipal(identity); + } + + private void SetupConfigurationManager(bool startupWizardCompleted) + { + var commonConfiguration = new BaseApplicationConfiguration + { + IsStartupWizardCompleted = startupWizardCompleted + }; + + _configurationManagerMock.Setup(c => c.CommonConfiguration) + .Returns(commonConfiguration); + } + } +} From d1461b4238cdaee32137787e1eef5c3a7db697fa Mon Sep 17 00:00:00 2001 From: Ben Magee Date: Sun, 22 Dec 2019 23:21:20 +0000 Subject: [PATCH 025/881] Changed cast style as suggested, improved some member names to make them less ambiguous --- .../Auth/CustomAuthenticationHandlerTests.cs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs index f202f59e61..a2f5c25016 100644 --- a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs +++ b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs @@ -23,8 +23,8 @@ namespace Jellyfin.Api.Tests.Auth { private readonly IFixture _fixture; - private readonly Mock _authServiceMock; - private readonly Mock> _optionsMock; + private readonly Mock _jellyfinAuthServiceMock; + private readonly Mock> _optionsMonitorMock; private readonly Mock _clockMock; private readonly Mock _serviceProviderMock; private readonly Mock _authenticationServiceMock; @@ -44,8 +44,8 @@ namespace Jellyfin.Api.Tests.Auth _fixture = new Fixture().Customize(fixtureCustomizations); AllowFixtureCircularDependencies(); - _authServiceMock = _fixture.Freeze>(); - _optionsMock = _fixture.Freeze>>(); + _jellyfinAuthServiceMock = _fixture.Freeze>(); + _optionsMonitorMock = _fixture.Freeze>>(); _clockMock = _fixture.Freeze>(); _serviceProviderMock = _fixture.Freeze>(); _authenticationServiceMock = _fixture.Freeze>(); @@ -56,7 +56,7 @@ namespace Jellyfin.Api.Tests.Auth _serviceProviderMock.Setup(s => s.GetService(typeof(IAuthenticationService))) .Returns(_authenticationServiceMock.Object); - _optionsMock.Setup(o => o.Get(It.IsAny())) + _optionsMonitorMock.Setup(o => o.Get(It.IsAny())) .Returns(new AuthenticationSchemeOptions { ForwardAuthenticate = null @@ -79,11 +79,11 @@ namespace Jellyfin.Api.Tests.Auth [Fact] public async Task HandleAuthenticateAsyncShouldFailWithNullUser() { - _authServiceMock.Setup( + _jellyfinAuthServiceMock.Setup( a => a.Authenticate( It.IsAny(), It.IsAny())) - .Returns((User) null); + .Returns((User)null); var authenticateResult = await _sut.AuthenticateAsync(); @@ -96,7 +96,7 @@ namespace Jellyfin.Api.Tests.Auth { var errorMessage = _fixture.Create(); - _authServiceMock.Setup( + _jellyfinAuthServiceMock.Setup( a => a.Authenticate( It.IsAny(), It.IsAny())) @@ -153,7 +153,7 @@ namespace Jellyfin.Api.Tests.Auth var user = _fixture.Create(); user.Policy.IsAdministrator = isAdmin; - _authServiceMock.Setup( + _jellyfinAuthServiceMock.Setup( a => a.Authenticate( It.IsAny(), It.IsAny())) From 43c76b48c9f90afc34a5fd40aa1a28c8ae7b736a Mon Sep 17 00:00:00 2001 From: Ben Magee Date: Wed, 8 Jan 2020 22:52:33 +0000 Subject: [PATCH 026/881] Added a test to prevent a regression of the issue seen in #1874. This issue was fixed in PR#2240 --- MediaBrowser.sln | 9 +++++- .../Emby.Server.Implementations.Tests.csproj | 23 ++++++++++++++ .../IO/ManagedFileSystemTests.cs | 31 +++++++++++++++++++ 3 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 tests/Emby.Server.Implementations.Tests/Emby.Server.Implementations.Tests.csproj create mode 100644 tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs diff --git a/MediaBrowser.sln b/MediaBrowser.sln index 416a434f47..cf1bab11c6 100644 --- a/MediaBrowser.sln +++ b/MediaBrowser.sln @@ -1,4 +1,4 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 +Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26730.3 MinimumVisualStudioVersion = 10.0.40219.1 @@ -58,6 +58,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Naming.Tests", "te EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Api.Tests", "tests\Jellyfin.Api.Tests\Jellyfin.Api.Tests.csproj", "{A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Emby.Server.Implementations.Tests", "tests\Emby.Server.Implementations.Tests\Emby.Server.Implementations.Tests.csproj", "{2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -164,6 +166,10 @@ Global {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}.Debug|Any CPU.Build.0 = Debug|Any CPU {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}.Release|Any CPU.ActiveCfg = Release|Any CPU {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}.Release|Any CPU.Build.0 = Release|Any CPU + {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -194,5 +200,6 @@ Global {28464062-0939-4AA7-9F7B-24DDDA61A7C0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {3998657B-1CCC-49DD-A19F-275DC8495F57} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} EndGlobalSection EndGlobal diff --git a/tests/Emby.Server.Implementations.Tests/Emby.Server.Implementations.Tests.csproj b/tests/Emby.Server.Implementations.Tests/Emby.Server.Implementations.Tests.csproj new file mode 100644 index 0000000000..c635a90f17 --- /dev/null +++ b/tests/Emby.Server.Implementations.Tests/Emby.Server.Implementations.Tests.csproj @@ -0,0 +1,23 @@ + + + + netcoreapp3.1 + + false + + + + + + + + + + + + + + + + + diff --git a/tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs new file mode 100644 index 0000000000..586c50db6a --- /dev/null +++ b/tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs @@ -0,0 +1,31 @@ +using AutoFixture; +using AutoFixture.AutoMoq; +using Emby.Server.Implementations.IO; +using Xunit; + +namespace Emby.Server.Implementations.Tests.IO +{ + public class ManagedFileSystemTests + { + private readonly IFixture _fixture; + private readonly ManagedFileSystem _sut; + + public ManagedFileSystemTests() + { + _fixture = new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true }); + _sut = _fixture.Create(); + } + + [Theory] + [InlineData("/Volumes/Library/Sample/Music/Playlists/", "../Beethoven/Misc/Moonlight Sonata.mp3", "/Volumes/Library/Sample/Music/Beethoven/Misc/Moonlight Sonata.mp3")] + [InlineData("/Volumes/Library/Sample/Music/Playlists/", "../../Beethoven/Misc/Moonlight Sonata.mp3", "/Volumes/Library/Sample/Beethoven/Misc/Moonlight Sonata.mp3")] + public void MakeAbsolutePathCorrectlyHandlesRelativeFilePaths( + string folderPath, + string filePath, + string expectedAbsolutePath) + { + var generatedPath = _sut.MakeAbsolutePath(folderPath, filePath); + Assert.Equal(expectedAbsolutePath, generatedPath); + } + } +} From 140673fcf6186c559c97829a14991f7f81d22430 Mon Sep 17 00:00:00 2001 From: Ben Magee Date: Wed, 8 Jan 2020 23:03:17 +0000 Subject: [PATCH 027/881] Add a test case which doesn't specify the parent directory. --- .../IO/ManagedFileSystemTests.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs index 586c50db6a..0044196a7f 100644 --- a/tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs +++ b/tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs @@ -19,6 +19,7 @@ namespace Emby.Server.Implementations.Tests.IO [Theory] [InlineData("/Volumes/Library/Sample/Music/Playlists/", "../Beethoven/Misc/Moonlight Sonata.mp3", "/Volumes/Library/Sample/Music/Beethoven/Misc/Moonlight Sonata.mp3")] [InlineData("/Volumes/Library/Sample/Music/Playlists/", "../../Beethoven/Misc/Moonlight Sonata.mp3", "/Volumes/Library/Sample/Beethoven/Misc/Moonlight Sonata.mp3")] + [InlineData("/Volumes/Library/Sample/Music/Playlists/", "Beethoven/Misc/Moonlight Sonata.mp3", "/Volumes/Library/Sample/Music/Playlists/Beethoven/Misc/Moonlight Sonata.mp3")] public void MakeAbsolutePathCorrectlyHandlesRelativeFilePaths( string folderPath, string filePath, From fdbb32911835b5ed8e39f518ccc20b0a26bd8bab Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Thu, 9 Jan 2020 17:07:13 +0100 Subject: [PATCH 028/881] Remove StringHelper functions --- DvdLib/DvdLib.csproj | 2 +- Emby.Dlna/Didl/Filter.cs | 2 +- .../LiveTv/EmbyTV/EmbyTV.cs | 2 +- MediaBrowser.Model/Dlna/ConditionProcessor.cs | 4 +- MediaBrowser.Model/Dlna/DeviceProfile.cs | 6 +- .../Dlna/MediaFormatProfileResolver.cs | 144 +++++++++--------- .../Dlna/ResolutionNormalizer.cs | 6 +- MediaBrowser.Model/Dlna/SearchCriteria.cs | 12 +- MediaBrowser.Model/Dlna/StreamBuilder.cs | 10 +- MediaBrowser.Model/Dlna/StreamInfo.cs | 28 ++-- MediaBrowser.Model/Entities/MediaStream.cs | 16 +- MediaBrowser.Model/Extensions/ListHelper.cs | 1 + MediaBrowser.Model/Extensions/StringHelper.cs | 63 +++----- MediaBrowser.Model/MediaBrowser.Model.csproj | 2 +- MediaBrowser.Model/Net/MimeTypes.cs | 10 +- .../Notifications/NotificationOptions.cs | 2 +- 16 files changed, 146 insertions(+), 164 deletions(-) diff --git a/DvdLib/DvdLib.csproj b/DvdLib/DvdLib.csproj index 9dbaa9e2f0..f4df6a9f52 100644 --- a/DvdLib/DvdLib.csproj +++ b/DvdLib/DvdLib.csproj @@ -9,7 +9,7 @@ - netstandard2.0 + netstandard2.1 false true diff --git a/Emby.Dlna/Didl/Filter.cs b/Emby.Dlna/Didl/Filter.cs index a0e67870e9..e7f9577ee6 100644 --- a/Emby.Dlna/Didl/Filter.cs +++ b/Emby.Dlna/Didl/Filter.cs @@ -16,7 +16,7 @@ namespace Emby.Dlna.Didl public Filter(string filter) { - _all = StringHelper.EqualsIgnoreCase(filter, "*"); + _all = string.Equals(filter, "*", StringComparison.OrdinalIgnoreCase); _fields = (filter ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 3b6bfce6a7..4e09f90b4b 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -458,7 +458,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { foreach (NameValuePair mapping in mappings) { - if (StringHelper.EqualsIgnoreCase(mapping.Name, channelId)) + if (string.Equals(mapping.Name, channelId, StringComparison.OrdinalIgnoreCase)) { return mapping.Value; } diff --git a/MediaBrowser.Model/Dlna/ConditionProcessor.cs b/MediaBrowser.Model/Dlna/ConditionProcessor.cs index 3629d15470..caaceda1bc 100644 --- a/MediaBrowser.Model/Dlna/ConditionProcessor.cs +++ b/MediaBrowser.Model/Dlna/ConditionProcessor.cs @@ -169,9 +169,9 @@ namespace MediaBrowser.Model.Dlna return ListHelper.ContainsIgnoreCase(expected.Split('|'), currentValue); } case ProfileConditionType.Equals: - return StringHelper.EqualsIgnoreCase(currentValue, expected); + return string.Equals(currentValue, expected, StringComparison.OrdinalIgnoreCase); case ProfileConditionType.NotEquals: - return !StringHelper.EqualsIgnoreCase(currentValue, expected); + return !string.Equals(currentValue, expected, StringComparison.OrdinalIgnoreCase); default: throw new InvalidOperationException("Unexpected ProfileConditionType: " + condition.Condition); } diff --git a/MediaBrowser.Model/Dlna/DeviceProfile.cs b/MediaBrowser.Model/Dlna/DeviceProfile.cs index 8d8fe9eb5b..f152ee8808 100644 --- a/MediaBrowser.Model/Dlna/DeviceProfile.cs +++ b/MediaBrowser.Model/Dlna/DeviceProfile.cs @@ -122,7 +122,7 @@ namespace MediaBrowser.Model.Dlna continue; } - if (!StringHelper.EqualsIgnoreCase(container, i.Container)) + if (!string.Equals(container, i.Container, StringComparison.OrdinalIgnoreCase)) { continue; } @@ -148,7 +148,7 @@ namespace MediaBrowser.Model.Dlna continue; } - if (!StringHelper.EqualsIgnoreCase(container, i.Container)) + if (!string.Equals(container, i.Container, StringComparison.OrdinalIgnoreCase)) { continue; } @@ -158,7 +158,7 @@ namespace MediaBrowser.Model.Dlna continue; } - if (!StringHelper.EqualsIgnoreCase(videoCodec, i.VideoCodec ?? string.Empty)) + if (!string.Equals(videoCodec, i.VideoCodec ?? string.Empty, StringComparison.OrdinalIgnoreCase)) { continue; } diff --git a/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs b/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs index 672784589f..333cab60da 100644 --- a/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs +++ b/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs @@ -17,53 +17,53 @@ namespace MediaBrowser.Model.Dlna private MediaFormatProfile[] ResolveVideoFormatInternal(string container, string videoCodec, string audioCodec, int? width, int? height, TransportStreamTimestamp timestampType) { - if (StringHelper.EqualsIgnoreCase(container, "asf")) + if (string.Equals(container, "asf", StringComparison.OrdinalIgnoreCase)) { MediaFormatProfile? val = ResolveVideoASFFormat(videoCodec, audioCodec, width, height); return val.HasValue ? new MediaFormatProfile[] { val.Value } : new MediaFormatProfile[] { }; } - if (StringHelper.EqualsIgnoreCase(container, "mp4")) + if (string.Equals(container, "mp4", StringComparison.OrdinalIgnoreCase)) { MediaFormatProfile? val = ResolveVideoMP4Format(videoCodec, audioCodec, width, height); return val.HasValue ? new MediaFormatProfile[] { val.Value } : new MediaFormatProfile[] { }; } - if (StringHelper.EqualsIgnoreCase(container, "avi")) + if (string.Equals(container, "avi", StringComparison.OrdinalIgnoreCase)) return new MediaFormatProfile[] { MediaFormatProfile.AVI }; - if (StringHelper.EqualsIgnoreCase(container, "mkv")) + if (string.Equals(container, "mkv", StringComparison.OrdinalIgnoreCase)) return new MediaFormatProfile[] { MediaFormatProfile.MATROSKA }; - if (StringHelper.EqualsIgnoreCase(container, "mpeg2ps") || - StringHelper.EqualsIgnoreCase(container, "ts")) + if (string.Equals(container, "mpeg2ps", StringComparison.OrdinalIgnoreCase) || + string.Equals(container, "ts", StringComparison.OrdinalIgnoreCase)) return new MediaFormatProfile[] { MediaFormatProfile.MPEG_PS_NTSC, MediaFormatProfile.MPEG_PS_PAL }; - if (StringHelper.EqualsIgnoreCase(container, "mpeg1video")) + if (string.Equals(container, "mpeg1video", StringComparison.OrdinalIgnoreCase)) return new MediaFormatProfile[] { MediaFormatProfile.MPEG1 }; - if (StringHelper.EqualsIgnoreCase(container, "mpeg2ts") || - StringHelper.EqualsIgnoreCase(container, "mpegts") || - StringHelper.EqualsIgnoreCase(container, "m2ts")) + if (string.Equals(container, "mpeg2ts", StringComparison.OrdinalIgnoreCase) || + string.Equals(container, "mpegts", StringComparison.OrdinalIgnoreCase) || + string.Equals(container, "m2ts", StringComparison.OrdinalIgnoreCase)) { return ResolveVideoMPEG2TSFormat(videoCodec, audioCodec, width, height, timestampType); } - if (StringHelper.EqualsIgnoreCase(container, "flv")) + if (string.Equals(container, "flv", StringComparison.OrdinalIgnoreCase)) return new MediaFormatProfile[] { MediaFormatProfile.FLV }; - if (StringHelper.EqualsIgnoreCase(container, "wtv")) + if (string.Equals(container, "wtv", StringComparison.OrdinalIgnoreCase)) return new MediaFormatProfile[] { MediaFormatProfile.WTV }; - if (StringHelper.EqualsIgnoreCase(container, "3gp")) + if (string.Equals(container, "3gp", StringComparison.OrdinalIgnoreCase)) { MediaFormatProfile? val = ResolveVideo3GPFormat(videoCodec, audioCodec); return val.HasValue ? new MediaFormatProfile[] { val.Value } : new MediaFormatProfile[] { }; } - if (StringHelper.EqualsIgnoreCase(container, "ogv") || StringHelper.EqualsIgnoreCase(container, "ogg")) + if (string.Equals(container, "ogv", StringComparison.OrdinalIgnoreCase) || string.Equals(container, "ogg", StringComparison.OrdinalIgnoreCase)) return new MediaFormatProfile[] { MediaFormatProfile.OGV }; return new MediaFormatProfile[] { }; @@ -89,7 +89,7 @@ namespace MediaBrowser.Model.Dlna resolution = "H"; } - if (StringHelper.EqualsIgnoreCase(videoCodec, "mpeg2video")) + if (string.Equals(videoCodec, "mpeg2video", StringComparison.OrdinalIgnoreCase)) { var list = new List(); @@ -97,18 +97,18 @@ namespace MediaBrowser.Model.Dlna list.Add(ValueOf("MPEG_TS_SD_EU" + suffix)); list.Add(ValueOf("MPEG_TS_SD_KO" + suffix)); - if ((timestampType == TransportStreamTimestamp.Valid) && StringHelper.EqualsIgnoreCase(audioCodec, "aac")) + if ((timestampType == TransportStreamTimestamp.Valid) && string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)) { list.Add(MediaFormatProfile.MPEG_TS_JP_T); } return list.ToArray(); } - if (StringHelper.EqualsIgnoreCase(videoCodec, "h264")) + if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase)) { - if (StringHelper.EqualsIgnoreCase(audioCodec, "lpcm")) + if (string.Equals(audioCodec, "lpcm", StringComparison.OrdinalIgnoreCase)) return new MediaFormatProfile[] { MediaFormatProfile.AVC_TS_HD_50_LPCM_T }; - if (StringHelper.EqualsIgnoreCase(audioCodec, "dts")) + if (string.Equals(audioCodec, "dts", StringComparison.OrdinalIgnoreCase)) { if (timestampType == TransportStreamTimestamp.None) { @@ -117,7 +117,7 @@ namespace MediaBrowser.Model.Dlna return new MediaFormatProfile[] { MediaFormatProfile.AVC_TS_HD_DTS_T }; } - if (StringHelper.EqualsIgnoreCase(audioCodec, "mp2")) + if (string.Equals(audioCodec, "mp2", StringComparison.OrdinalIgnoreCase)) { if (timestampType == TransportStreamTimestamp.None) { @@ -127,19 +127,19 @@ namespace MediaBrowser.Model.Dlna return new MediaFormatProfile[] { ValueOf(string.Format("AVC_TS_HP_{0}D_MPEG1_L2_T", resolution)) }; } - if (StringHelper.EqualsIgnoreCase(audioCodec, "aac")) + if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)) return new MediaFormatProfile[] { ValueOf(string.Format("AVC_TS_MP_{0}D_AAC_MULT5{1}", resolution, suffix)) }; - if (StringHelper.EqualsIgnoreCase(audioCodec, "mp3")) + if (string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase)) return new MediaFormatProfile[] { ValueOf(string.Format("AVC_TS_MP_{0}D_MPEG1_L3{1}", resolution, suffix)) }; if (string.IsNullOrEmpty(audioCodec) || - StringHelper.EqualsIgnoreCase(audioCodec, "ac3")) + string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase)) return new MediaFormatProfile[] { ValueOf(string.Format("AVC_TS_MP_{0}D_AC3{1}", resolution, suffix)) }; } - else if (StringHelper.EqualsIgnoreCase(videoCodec, "vc1")) + else if (string.Equals(videoCodec, "vc1", StringComparison.OrdinalIgnoreCase)) { - if (string.IsNullOrEmpty(audioCodec) || StringHelper.EqualsIgnoreCase(audioCodec, "ac3")) + if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase)) { if ((width.HasValue && width.Value > 720) || (height.HasValue && height.Value > 576)) { @@ -147,23 +147,23 @@ namespace MediaBrowser.Model.Dlna } return new MediaFormatProfile[] { MediaFormatProfile.VC1_TS_AP_L1_AC3_ISO }; } - if (StringHelper.EqualsIgnoreCase(audioCodec, "dts")) + if (string.Equals(audioCodec, "dts", StringComparison.OrdinalIgnoreCase)) { - suffix = StringHelper.EqualsIgnoreCase(suffix, "_ISO") ? suffix : "_T"; + suffix = string.Equals(suffix, "_ISO", StringComparison.OrdinalIgnoreCase) ? suffix : "_T"; return new MediaFormatProfile[] { ValueOf(string.Format("VC1_TS_HD_DTS{0}", suffix)) }; } } - else if (StringHelper.EqualsIgnoreCase(videoCodec, "mpeg4") || StringHelper.EqualsIgnoreCase(videoCodec, "msmpeg4")) + else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase) || string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase)) { - if (StringHelper.EqualsIgnoreCase(audioCodec, "aac")) + if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)) return new MediaFormatProfile[] { ValueOf(string.Format("MPEG4_P2_TS_ASP_AAC{0}", suffix)) }; - if (StringHelper.EqualsIgnoreCase(audioCodec, "mp3")) + if (string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase)) return new MediaFormatProfile[] { ValueOf(string.Format("MPEG4_P2_TS_ASP_MPEG1_L3{0}", suffix)) }; - if (StringHelper.EqualsIgnoreCase(audioCodec, "mp2")) + if (string.Equals(audioCodec, "mp2", StringComparison.OrdinalIgnoreCase)) return new MediaFormatProfile[] { ValueOf(string.Format("MPEG4_P2_TS_ASP_MPEG2_L2{0}", suffix)) }; - if (StringHelper.EqualsIgnoreCase(audioCodec, "ac3")) + if (string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase)) return new MediaFormatProfile[] { ValueOf(string.Format("MPEG4_P2_TS_ASP_AC3{0}", suffix)) }; } @@ -177,16 +177,16 @@ namespace MediaBrowser.Model.Dlna private MediaFormatProfile? ResolveVideoMP4Format(string videoCodec, string audioCodec, int? width, int? height) { - if (StringHelper.EqualsIgnoreCase(videoCodec, "h264")) + if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase)) { - if (StringHelper.EqualsIgnoreCase(audioCodec, "lpcm")) + if (string.Equals(audioCodec, "lpcm", StringComparison.OrdinalIgnoreCase)) return MediaFormatProfile.AVC_MP4_LPCM; if (string.IsNullOrEmpty(audioCodec) || - StringHelper.EqualsIgnoreCase(audioCodec, "ac3")) + string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase)) { return MediaFormatProfile.AVC_MP4_MP_SD_AC3; } - if (StringHelper.EqualsIgnoreCase(audioCodec, "mp3")) + if (string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase)) { return MediaFormatProfile.AVC_MP4_MP_SD_MPEG1_L3; } @@ -194,41 +194,41 @@ namespace MediaBrowser.Model.Dlna { if ((width.Value <= 720) && (height.Value <= 576)) { - if (StringHelper.EqualsIgnoreCase(audioCodec, "aac")) + if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)) return MediaFormatProfile.AVC_MP4_MP_SD_AAC_MULT5; } else if ((width.Value <= 1280) && (height.Value <= 720)) { - if (StringHelper.EqualsIgnoreCase(audioCodec, "aac")) + if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)) return MediaFormatProfile.AVC_MP4_MP_HD_720p_AAC; } else if ((width.Value <= 1920) && (height.Value <= 1080)) { - if (StringHelper.EqualsIgnoreCase(audioCodec, "aac")) + if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)) { return MediaFormatProfile.AVC_MP4_MP_HD_1080i_AAC; } } } } - else if (StringHelper.EqualsIgnoreCase(videoCodec, "mpeg4") || - StringHelper.EqualsIgnoreCase(videoCodec, "msmpeg4")) + else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase) || + string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase)) { if (width.HasValue && height.HasValue && width.Value <= 720 && height.Value <= 576) { - if (string.IsNullOrEmpty(audioCodec) || StringHelper.EqualsIgnoreCase(audioCodec, "aac")) + if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)) return MediaFormatProfile.MPEG4_P2_MP4_ASP_AAC; - if (StringHelper.EqualsIgnoreCase(audioCodec, "ac3") || StringHelper.EqualsIgnoreCase(audioCodec, "mp3")) + if (string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase) || string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase)) { return MediaFormatProfile.MPEG4_P2_MP4_NDSD; } } - else if (string.IsNullOrEmpty(audioCodec) || StringHelper.EqualsIgnoreCase(audioCodec, "aac")) + else if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)) { return MediaFormatProfile.MPEG4_P2_MP4_SP_L6_AAC; } } - else if (StringHelper.EqualsIgnoreCase(videoCodec, "h263") && StringHelper.EqualsIgnoreCase(audioCodec, "aac")) + else if (string.Equals(videoCodec, "h263", StringComparison.OrdinalIgnoreCase) && string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)) { return MediaFormatProfile.MPEG4_H263_MP4_P0_L10_AAC; } @@ -238,20 +238,20 @@ namespace MediaBrowser.Model.Dlna private MediaFormatProfile? ResolveVideo3GPFormat(string videoCodec, string audioCodec) { - if (StringHelper.EqualsIgnoreCase(videoCodec, "h264")) + if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase)) { - if (string.IsNullOrEmpty(audioCodec) || StringHelper.EqualsIgnoreCase(audioCodec, "aac")) + if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)) return MediaFormatProfile.AVC_3GPP_BL_QCIF15_AAC; } - else if (StringHelper.EqualsIgnoreCase(videoCodec, "mpeg4") || - StringHelper.EqualsIgnoreCase(videoCodec, "msmpeg4")) + else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase) || + string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase)) { - if (string.IsNullOrEmpty(audioCodec) || StringHelper.EqualsIgnoreCase(audioCodec, "wma")) + if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "wma", StringComparison.OrdinalIgnoreCase)) return MediaFormatProfile.MPEG4_P2_3GPP_SP_L0B_AAC; - if (StringHelper.EqualsIgnoreCase(audioCodec, "amrnb")) + if (string.Equals(audioCodec, "amrnb", StringComparison.OrdinalIgnoreCase)) return MediaFormatProfile.MPEG4_P2_3GPP_SP_L0B_AMR; } - else if (StringHelper.EqualsIgnoreCase(videoCodec, "h263") && StringHelper.EqualsIgnoreCase(audioCodec, "amrnb")) + else if (string.Equals(videoCodec, "h263", StringComparison.OrdinalIgnoreCase) && string.Equals(audioCodec, "amrnb", StringComparison.OrdinalIgnoreCase)) { return MediaFormatProfile.MPEG4_H263_3GPP_P0_L10_AMR; } @@ -261,15 +261,15 @@ namespace MediaBrowser.Model.Dlna private MediaFormatProfile? ResolveVideoASFFormat(string videoCodec, string audioCodec, int? width, int? height) { - if (StringHelper.EqualsIgnoreCase(videoCodec, "wmv") && - (string.IsNullOrEmpty(audioCodec) || StringHelper.EqualsIgnoreCase(audioCodec, "wma") || StringHelper.EqualsIgnoreCase(videoCodec, "wmapro"))) + if (string.Equals(videoCodec, "wmv", StringComparison.OrdinalIgnoreCase) && + (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "wma", StringComparison.OrdinalIgnoreCase) || string.Equals(videoCodec, "wmapro", StringComparison.OrdinalIgnoreCase))) { if (width.HasValue && height.HasValue) { if ((width.Value <= 720) && (height.Value <= 576)) { - if (string.IsNullOrEmpty(audioCodec) || StringHelper.EqualsIgnoreCase(audioCodec, "wma")) + if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "wma", StringComparison.OrdinalIgnoreCase)) { return MediaFormatProfile.WMVMED_FULL; } @@ -277,14 +277,14 @@ namespace MediaBrowser.Model.Dlna } } - if (string.IsNullOrEmpty(audioCodec) || StringHelper.EqualsIgnoreCase(audioCodec, "wma")) + if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "wma", StringComparison.OrdinalIgnoreCase)) { return MediaFormatProfile.WMVHIGH_FULL; } return MediaFormatProfile.WMVHIGH_PRO; } - if (StringHelper.EqualsIgnoreCase(videoCodec, "vc1")) + if (string.Equals(videoCodec, "vc1", StringComparison.OrdinalIgnoreCase)) { if (width.HasValue && height.HasValue) { @@ -296,7 +296,7 @@ namespace MediaBrowser.Model.Dlna return MediaFormatProfile.VC1_ASF_AP_L3_WMA; } } - else if (StringHelper.EqualsIgnoreCase(videoCodec, "mpeg2video")) + else if (string.Equals(videoCodec, "mpeg2video", StringComparison.OrdinalIgnoreCase)) { return MediaFormatProfile.DVR_MS; } @@ -306,27 +306,27 @@ namespace MediaBrowser.Model.Dlna public MediaFormatProfile? ResolveAudioFormat(string container, int? bitrate, int? frequency, int? channels) { - if (StringHelper.EqualsIgnoreCase(container, "asf")) + if (string.Equals(container, "asf", StringComparison.OrdinalIgnoreCase)) return ResolveAudioASFFormat(bitrate); - if (StringHelper.EqualsIgnoreCase(container, "mp3")) + if (string.Equals(container, "mp3", StringComparison.OrdinalIgnoreCase)) return MediaFormatProfile.MP3; - if (StringHelper.EqualsIgnoreCase(container, "lpcm")) + if (string.Equals(container, "lpcm", StringComparison.OrdinalIgnoreCase)) return ResolveAudioLPCMFormat(frequency, channels); - if (StringHelper.EqualsIgnoreCase(container, "mp4") || - StringHelper.EqualsIgnoreCase(container, "aac")) + if (string.Equals(container, "mp4", StringComparison.OrdinalIgnoreCase) || + string.Equals(container, "aac", StringComparison.OrdinalIgnoreCase)) return ResolveAudioMP4Format(bitrate); - if (StringHelper.EqualsIgnoreCase(container, "adts")) + if (string.Equals(container, "adts", StringComparison.OrdinalIgnoreCase)) return ResolveAudioADTSFormat(bitrate); - if (StringHelper.EqualsIgnoreCase(container, "flac")) + if (string.Equals(container, "flac", StringComparison.OrdinalIgnoreCase)) return MediaFormatProfile.FLAC; - if (StringHelper.EqualsIgnoreCase(container, "oga") || - StringHelper.EqualsIgnoreCase(container, "ogg")) + if (string.Equals(container, "oga", StringComparison.OrdinalIgnoreCase) || + string.Equals(container, "ogg", StringComparison.OrdinalIgnoreCase)) return MediaFormatProfile.OGG; return null; @@ -388,17 +388,17 @@ namespace MediaBrowser.Model.Dlna public MediaFormatProfile? ResolveImageFormat(string container, int? width, int? height) { - if (StringHelper.EqualsIgnoreCase(container, "jpeg") || - StringHelper.EqualsIgnoreCase(container, "jpg")) + if (string.Equals(container, "jpeg", StringComparison.OrdinalIgnoreCase) || + string.Equals(container, "jpg", StringComparison.OrdinalIgnoreCase)) return ResolveImageJPGFormat(width, height); - if (StringHelper.EqualsIgnoreCase(container, "png")) + if (string.Equals(container, "png", StringComparison.OrdinalIgnoreCase)) return ResolveImagePNGFormat(width, height); - if (StringHelper.EqualsIgnoreCase(container, "gif")) + if (string.Equals(container, "gif", StringComparison.OrdinalIgnoreCase)) return MediaFormatProfile.GIF_LRG; - if (StringHelper.EqualsIgnoreCase(container, "raw")) + if (string.Equals(container, "raw", StringComparison.OrdinalIgnoreCase)) return MediaFormatProfile.RAW; return null; diff --git a/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs b/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs index cf92633c31..8a00f4ae4f 100644 --- a/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs +++ b/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs @@ -76,9 +76,9 @@ namespace MediaBrowser.Model.Dlna private static double GetVideoBitrateScaleFactor(string codec) { - if (StringHelper.EqualsIgnoreCase(codec, "h265") || - StringHelper.EqualsIgnoreCase(codec, "hevc") || - StringHelper.EqualsIgnoreCase(codec, "vp9")) + if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase) || + string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase) || + string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase)) { return .5; } diff --git a/MediaBrowser.Model/Dlna/SearchCriteria.cs b/MediaBrowser.Model/Dlna/SearchCriteria.cs index 4f47c28219..8919938814 100644 --- a/MediaBrowser.Model/Dlna/SearchCriteria.cs +++ b/MediaBrowser.Model/Dlna/SearchCriteria.cs @@ -48,22 +48,22 @@ namespace MediaBrowser.Model.Dlna if (subFactors.Length == 3) { - if (StringHelper.EqualsIgnoreCase("upnp:class", subFactors[0]) && - (StringHelper.EqualsIgnoreCase("=", subFactors[1]) || StringHelper.EqualsIgnoreCase("derivedfrom", subFactors[1]))) + if (string.Equals("upnp:class", subFactors[0], StringComparison.OrdinalIgnoreCase) && + (string.Equals("=", subFactors[1]) || string.Equals("derivedfrom", subFactors[1], StringComparison.OrdinalIgnoreCase))) { - if (StringHelper.EqualsIgnoreCase("\"object.item.imageItem\"", subFactors[2]) || StringHelper.EqualsIgnoreCase("\"object.item.imageItem.photo\"", subFactors[2])) + if (string.Equals("\"object.item.imageItem\"", subFactors[2]) || string.Equals("\"object.item.imageItem.photo\"", subFactors[2], StringComparison.OrdinalIgnoreCase)) { SearchType = SearchType.Image; } - else if (StringHelper.EqualsIgnoreCase("\"object.item.videoItem\"", subFactors[2])) + else if (string.Equals("\"object.item.videoItem\"", subFactors[2], StringComparison.OrdinalIgnoreCase)) { SearchType = SearchType.Video; } - else if (StringHelper.EqualsIgnoreCase("\"object.container.playlistContainer\"", subFactors[2])) + else if (string.Equals("\"object.container.playlistContainer\"", subFactors[2], StringComparison.OrdinalIgnoreCase)) { SearchType = SearchType.Playlist; } - else if (StringHelper.EqualsIgnoreCase("\"object.container.album.musicAlbum\"", subFactors[2])) + else if (string.Equals("\"object.container.album.musicAlbum\"", subFactors[2], StringComparison.OrdinalIgnoreCase)) { SearchType = SearchType.MusicAlbum; } diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 586e322e48..e039ac5d6f 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -35,7 +35,7 @@ namespace MediaBrowser.Model.Dlna foreach (MediaSourceInfo i in options.MediaSources) { if (string.IsNullOrEmpty(options.MediaSourceId) || - StringHelper.EqualsIgnoreCase(i.Id, options.MediaSourceId)) + string.Equals(i.Id, options.MediaSourceId, StringComparison.OrdinalIgnoreCase)) { mediaSources.Add(i); } @@ -68,7 +68,7 @@ namespace MediaBrowser.Model.Dlna foreach (MediaSourceInfo i in options.MediaSources) { if (string.IsNullOrEmpty(options.MediaSourceId) || - StringHelper.EqualsIgnoreCase(i.Id, options.MediaSourceId)) + string.Equals(i.Id, options.MediaSourceId, StringComparison.OrdinalIgnoreCase)) { mediaSources.Add(i); } @@ -582,7 +582,7 @@ namespace MediaBrowser.Model.Dlna { foreach (var profile in subtitleProfiles) { - if (profile.Method == SubtitleDeliveryMethod.External && StringHelper.EqualsIgnoreCase(profile.Format, stream.Codec)) + if (profile.Method == SubtitleDeliveryMethod.External && string.Equals(profile.Format, stream.Codec, StringComparison.OrdinalIgnoreCase)) { return stream.Index; } @@ -1198,7 +1198,7 @@ namespace MediaBrowser.Model.Dlna continue; } - if (subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format) && StringHelper.EqualsIgnoreCase(profile.Format, subtitleStream.Codec)) + if (subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format) && string.Equals(profile.Format, subtitleStream.Codec, StringComparison.OrdinalIgnoreCase)) { return profile; } @@ -1292,7 +1292,7 @@ namespace MediaBrowser.Model.Dlna if ((profile.Method == SubtitleDeliveryMethod.External && subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format)) || (profile.Method == SubtitleDeliveryMethod.Hls && subtitleStream.IsTextSubtitleStream)) { - bool requiresConversion = !StringHelper.EqualsIgnoreCase(subtitleStream.Codec, profile.Format); + bool requiresConversion = !string.Equals(subtitleStream.Codec, profile.Format, StringComparison.OrdinalIgnoreCase); if (!requiresConversion) { diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs index 10efb9b383..7962b51ce2 100644 --- a/MediaBrowser.Model/Dlna/StreamInfo.cs +++ b/MediaBrowser.Model/Dlna/StreamInfo.cs @@ -153,18 +153,18 @@ namespace MediaBrowser.Model.Dlna } // Try to keep the url clean by omitting defaults - if (StringHelper.EqualsIgnoreCase(pair.Name, "StartTimeTicks") && - StringHelper.EqualsIgnoreCase(pair.Value, "0")) + if (string.Equals(pair.Name, "StartTimeTicks", StringComparison.OrdinalIgnoreCase) && + string.Equals(pair.Value, "0", StringComparison.OrdinalIgnoreCase)) { continue; } - if (StringHelper.EqualsIgnoreCase(pair.Name, "SubtitleStreamIndex") && - StringHelper.EqualsIgnoreCase(pair.Value, "-1")) + if (string.Equals(pair.Name, "SubtitleStreamIndex", StringComparison.OrdinalIgnoreCase) && + string.Equals(pair.Value, "-1", StringComparison.OrdinalIgnoreCase)) { continue; } - if (StringHelper.EqualsIgnoreCase(pair.Name, "Static") && - StringHelper.EqualsIgnoreCase(pair.Value, "false")) + if (string.Equals(pair.Name, "Static", StringComparison.OrdinalIgnoreCase) && + string.Equals(pair.Value, "false", StringComparison.OrdinalIgnoreCase)) { continue; } @@ -192,7 +192,7 @@ namespace MediaBrowser.Model.Dlna if (MediaType == DlnaProfileType.Audio) { - if (StringHelper.EqualsIgnoreCase(SubProtocol, "hls")) + if (string.Equals(SubProtocol, "hls", StringComparison.OrdinalIgnoreCase)) { return string.Format("{0}/audio/{1}/master.m3u8?{2}", baseUrl, ItemId, queryString); } @@ -200,7 +200,7 @@ namespace MediaBrowser.Model.Dlna return string.Format("{0}/audio/{1}/stream{2}?{3}", baseUrl, ItemId, extension, queryString); } - if (StringHelper.EqualsIgnoreCase(SubProtocol, "hls")) + if (string.Equals(SubProtocol, "hls", StringComparison.OrdinalIgnoreCase)) { return string.Format("{0}/videos/{1}/master.m3u8?{2}", baseUrl, ItemId, queryString); } @@ -237,7 +237,7 @@ namespace MediaBrowser.Model.Dlna long startPositionTicks = item.StartPositionTicks; - var isHls = StringHelper.EqualsIgnoreCase(item.SubProtocol, "hls"); + var isHls = string.Equals(item.SubProtocol, "hls", StringComparison.OrdinalIgnoreCase); if (isHls) { @@ -370,7 +370,7 @@ namespace MediaBrowser.Model.Dlna var list = new List(); // HLS will preserve timestamps so we can just grab the full subtitle stream - long startPositionTicks = StringHelper.EqualsIgnoreCase(SubProtocol, "hls") + long startPositionTicks = string.Equals(SubProtocol, "hls", StringComparison.OrdinalIgnoreCase) ? 0 : (PlayMethod == PlayMethod.Transcode && !CopyTimestamps ? StartPositionTicks : 0); @@ -435,7 +435,7 @@ namespace MediaBrowser.Model.Dlna if (info.DeliveryMethod == SubtitleDeliveryMethod.External) { - if (MediaSource.Protocol == MediaProtocol.File || !StringHelper.EqualsIgnoreCase(stream.Codec, subtitleProfile.Format) || !stream.IsExternal) + if (MediaSource.Protocol == MediaProtocol.File || !string.Equals(stream.Codec, subtitleProfile.Format, StringComparison.OrdinalIgnoreCase) || !stream.IsExternal) { info.Url = string.Format("{0}/Videos/{1}/{2}/Subtitles/{3}/{4}/Stream.{5}", baseUrl, @@ -802,7 +802,7 @@ namespace MediaBrowser.Model.Dlna foreach (string codec in AudioCodecs) { - if (StringHelper.EqualsIgnoreCase(codec, inputCodec)) + if (string.Equals(codec, inputCodec, StringComparison.OrdinalIgnoreCase)) { return string.IsNullOrEmpty(codec) ? new string[] { } : new[] { codec }; } @@ -827,7 +827,7 @@ namespace MediaBrowser.Model.Dlna foreach (string codec in VideoCodecs) { - if (StringHelper.EqualsIgnoreCase(codec, inputCodec)) + if (string.Equals(codec, inputCodec, StringComparison.OrdinalIgnoreCase)) { return string.IsNullOrEmpty(codec) ? new string[] { } : new[] { codec }; } @@ -884,7 +884,7 @@ namespace MediaBrowser.Model.Dlna { get { - var defaultValue = StringHelper.EqualsIgnoreCase(Container, "m2ts") + var defaultValue = string.Equals(Container, "m2ts", StringComparison.OrdinalIgnoreCase) ? TransportStreamTimestamp.Valid : TransportStreamTimestamp.None; diff --git a/MediaBrowser.Model/Entities/MediaStream.cs b/MediaBrowser.Model/Entities/MediaStream.cs index 5652962daf..5122f42b8a 100644 --- a/MediaBrowser.Model/Entities/MediaStream.cs +++ b/MediaBrowser.Model/Entities/MediaStream.cs @@ -88,11 +88,11 @@ namespace MediaBrowser.Model.Entities { attributes.Add(StringHelper.FirstToUpper(Language)); } - if (!string.IsNullOrEmpty(Codec) && !StringHelper.EqualsIgnoreCase(Codec, "dca")) + if (!string.IsNullOrEmpty(Codec) && !string.Equals(Codec, "dca", StringComparison.OrdinalIgnoreCase)) { attributes.Add(AudioCodec.GetFriendlyName(Codec)); } - else if (!string.IsNullOrEmpty(Profile) && !StringHelper.EqualsIgnoreCase(Profile, "lc")) + else if (!string.IsNullOrEmpty(Profile) && !string.Equals(Profile, "lc", StringComparison.OrdinalIgnoreCase)) { attributes.Add(Profile); } @@ -394,8 +394,8 @@ namespace MediaBrowser.Model.Entities return codec.IndexOf("pgs", StringComparison.OrdinalIgnoreCase) == -1 && codec.IndexOf("dvd", StringComparison.OrdinalIgnoreCase) == -1 && codec.IndexOf("dvbsub", StringComparison.OrdinalIgnoreCase) == -1 && - !StringHelper.EqualsIgnoreCase(codec, "sub") && - !StringHelper.EqualsIgnoreCase(codec, "dvb_subtitle"); + !string.Equals(codec, "sub", StringComparison.OrdinalIgnoreCase) && + !string.Equals(codec, "dvb_subtitle", StringComparison.OrdinalIgnoreCase); } public bool SupportsSubtitleConversionTo(string toCodec) @@ -408,21 +408,21 @@ namespace MediaBrowser.Model.Entities var fromCodec = Codec; // Can't convert from this - if (StringHelper.EqualsIgnoreCase(fromCodec, "ass")) + if (string.Equals(fromCodec, "ass", StringComparison.OrdinalIgnoreCase)) { return false; } - if (StringHelper.EqualsIgnoreCase(fromCodec, "ssa")) + if (string.Equals(fromCodec, "ssa", StringComparison.OrdinalIgnoreCase)) { return false; } // Can't convert to this - if (StringHelper.EqualsIgnoreCase(toCodec, "ass")) + if (string.Equals(toCodec, "ass", StringComparison.OrdinalIgnoreCase)) { return false; } - if (StringHelper.EqualsIgnoreCase(toCodec, "ssa")) + if (string.Equals(toCodec, "ssa", StringComparison.OrdinalIgnoreCase)) { return false; } diff --git a/MediaBrowser.Model/Extensions/ListHelper.cs b/MediaBrowser.Model/Extensions/ListHelper.cs index b5bd077028..d751f77a77 100644 --- a/MediaBrowser.Model/Extensions/ListHelper.cs +++ b/MediaBrowser.Model/Extensions/ListHelper.cs @@ -2,6 +2,7 @@ using System; namespace MediaBrowser.Model.Extensions { + // TODO: @bond remove public static class ListHelper { public static bool ContainsIgnoreCase(string[] list, string value) diff --git a/MediaBrowser.Model/Extensions/StringHelper.cs b/MediaBrowser.Model/Extensions/StringHelper.cs index 75ba12a178..9ce1cf79ff 100644 --- a/MediaBrowser.Model/Extensions/StringHelper.cs +++ b/MediaBrowser.Model/Extensions/StringHelper.cs @@ -1,57 +1,38 @@ -using System; -using System.Text; - namespace MediaBrowser.Model.Extensions { /// - /// Isolating these helpers allow this entire project to be easily converted to Java + /// Helper methods for manipulating strings. /// public static class StringHelper { /// - /// Equalses the ignore case. + /// Returns the string with the first character inheritdoc uppercase. /// - /// The STR1. - /// The STR2. - /// true if XXXX, false otherwise. - public static bool EqualsIgnoreCase(string str1, string str2) + /// The input string. + /// The string with the first character inheritdoc uppercase. + public static string FirstToUpper(string str) { - return string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase); - } - - /// - /// Replaces the specified STR. - /// - /// The STR. - /// The old value. - /// The new value. - /// The comparison. - /// System.String. - public static string Replace(this string str, string oldValue, string newValue, StringComparison comparison) - { - var sb = new StringBuilder(); - - var previousIndex = 0; - var index = str.IndexOf(oldValue, comparison); - - while (index != -1) + if (string.IsNullOrEmpty(str)) { - sb.Append(str.Substring(previousIndex, index - previousIndex)); - sb.Append(newValue); - index += oldValue.Length; - - previousIndex = index; - index = str.IndexOf(oldValue, index, comparison); + return string.Empty; } - sb.Append(str.Substring(previousIndex)); + if (char.IsUpper(str[0])) + { + return str; + } - return sb.ToString(); - } - - public static string FirstToUpper(this string str) - { - return string.IsNullOrEmpty(str) ? string.Empty : str.Substring(0, 1).ToUpperInvariant() + str.Substring(1); + return string.Create( + str.Length, + str, + (chars, buf) => + { + chars[0] = char.ToUpperInvariant(buf[0]); + for (int i = 1; i - netstandard2.0 + netstandard2.1 false true diff --git a/MediaBrowser.Model/Net/MimeTypes.cs b/MediaBrowser.Model/Net/MimeTypes.cs index de5e58d220..42fff3775a 100644 --- a/MediaBrowser.Model/Net/MimeTypes.cs +++ b/MediaBrowser.Model/Net/MimeTypes.cs @@ -165,20 +165,20 @@ namespace MediaBrowser.Model.Net } // Type text - if (StringHelper.EqualsIgnoreCase(ext, ".html") - || StringHelper.EqualsIgnoreCase(ext, ".htm")) + if (string.Equals(ext, ".html", StringComparison.OrdinalIgnoreCase) + || string.Equals(ext, ".htm", StringComparison.OrdinalIgnoreCase)) { return "text/html; charset=UTF-8"; } - if (StringHelper.EqualsIgnoreCase(ext, ".log") - || StringHelper.EqualsIgnoreCase(ext, ".srt")) + if (string.Equals(ext, ".log", StringComparison.OrdinalIgnoreCase) + || string.Equals(ext, ".srt", StringComparison.OrdinalIgnoreCase)) { return "text/plain"; } // Misc - if (StringHelper.EqualsIgnoreCase(ext, ".dll")) + if (string.Equals(ext, ".dll", StringComparison.OrdinalIgnoreCase)) { return "application/octet-stream"; } diff --git a/MediaBrowser.Model/Notifications/NotificationOptions.cs b/MediaBrowser.Model/Notifications/NotificationOptions.cs index f48b5ee7fc..38600b9c87 100644 --- a/MediaBrowser.Model/Notifications/NotificationOptions.cs +++ b/MediaBrowser.Model/Notifications/NotificationOptions.cs @@ -79,7 +79,7 @@ namespace MediaBrowser.Model.Notifications { foreach (NotificationOption i in Options) { - if (StringHelper.EqualsIgnoreCase(type, i.Type)) return i; + if (string.Equals(type, i.Type, StringComparison.OrdinalIgnoreCase)) return i; } return null; } From 64baca9facae83832fc45f627f9249b38e37d168 Mon Sep 17 00:00:00 2001 From: Ben Magee Date: Thu, 9 Jan 2020 22:03:57 +0000 Subject: [PATCH 029/881] Renamed project and namespace --- MediaBrowser.sln | 2 +- .../IO/ManagedFileSystemTests.cs | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj} | 2 ++ 3 files changed, 4 insertions(+), 2 deletions(-) rename tests/{Emby.Server.Implementations.Tests => Jellyfin.Server.Implementations.Tests}/IO/ManagedFileSystemTests.cs (96%) rename tests/{Emby.Server.Implementations.Tests/Emby.Server.Implementations.Tests.csproj => Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj} (91%) diff --git a/MediaBrowser.sln b/MediaBrowser.sln index cf1bab11c6..50570deecf 100644 --- a/MediaBrowser.sln +++ b/MediaBrowser.sln @@ -58,7 +58,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Naming.Tests", "te EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Api.Tests", "tests\Jellyfin.Api.Tests\Jellyfin.Api.Tests.csproj", "{A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Emby.Server.Implementations.Tests", "tests\Emby.Server.Implementations.Tests\Emby.Server.Implementations.Tests.csproj", "{2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Implementations.Tests", "tests\Jellyfin.Server.Implementations.Tests\Jellyfin.Server.Implementations.Tests.csproj", "{2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs similarity index 96% rename from tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs rename to tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs index 0044196a7f..f2a8e447fa 100644 --- a/tests/Emby.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs @@ -3,7 +3,7 @@ using AutoFixture.AutoMoq; using Emby.Server.Implementations.IO; using Xunit; -namespace Emby.Server.Implementations.Tests.IO +namespace Jellyfin.Server.Implementations.Tests.IO { public class ManagedFileSystemTests { diff --git a/tests/Emby.Server.Implementations.Tests/Emby.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj similarity index 91% rename from tests/Emby.Server.Implementations.Tests/Emby.Server.Implementations.Tests.csproj rename to tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index c635a90f17..bb2afea168 100644 --- a/tests/Emby.Server.Implementations.Tests/Emby.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -4,6 +4,8 @@ netcoreapp3.1 false + + Jellyfin.Server.Implementations.Tests From c3ff4e0b9f52827872d50b890ea4e4fbab22b604 Mon Sep 17 00:00:00 2001 From: Narfinger Date: Fri, 10 Jan 2020 19:42:07 +0900 Subject: [PATCH 030/881] fixes dockerfile building on recent linux installations --- Dockerfile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 53a4252627..1cd864e0b3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,7 +14,9 @@ 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" +# because of changes in docker and systemd we need to not build in parallel at the moment +# see https://success.docker.com/article/how-to-reserve-resource-temporarily-unavailable-errors-due-to-tasksmax-setting +RUN dotnet publish Jellyfin.Server --disable-parallel --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 e95239e28132b4d6486ee9272d20ec5ada46b66c Mon Sep 17 00:00:00 2001 From: Nyanmisaka <799610810@qq.com> Date: Sat, 11 Jan 2020 01:36:25 +0800 Subject: [PATCH 031/881] add support for AMD h264_amf & hevc_amf --- MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index 1feca0ec92..993cd3f747 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -55,7 +55,9 @@ namespace MediaBrowser.MediaEncoding.Encoder "h264_vaapi", "hevc_vaapi", "h264_v4l2m2m", - "ac3" + "ac3", + "h264_amf", + "hevc_amf" }; // Try and use the individual library versions to determine a FFmpeg version From a647dc57052182a6171dae9ffba3026b66b26be7 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 11 Jan 2020 19:39:11 +0100 Subject: [PATCH 032/881] Cleanup tests --- Emby.Naming/Common/NamingOptions.cs | 2 +- .../Jellyfin.Naming.Tests/Video/StackTests.cs | 26 ------------------- 2 files changed, 1 insertion(+), 27 deletions(-) diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index a2105889b9..71521e1fd8 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -340,7 +340,7 @@ namespace Emby.Naming.Common // *** End Kodi Standard Naming -                // [bar] Foo - 1 [baz] + // [bar] Foo - 1 [baz] new EpisodeExpression(@".*?(\[.*?\])+.*?(?[\w\s]+?)[-\s_]+(?\d+).*$") { IsNamed = true diff --git a/tests/Jellyfin.Naming.Tests/Video/StackTests.cs b/tests/Jellyfin.Naming.Tests/Video/StackTests.cs index 5faef0e3db..5c121d7387 100644 --- a/tests/Jellyfin.Naming.Tests/Video/StackTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/StackTests.cs @@ -382,32 +382,6 @@ namespace Jellyfin.Naming.Tests.Video TestStackInfo(result.Stacks[1], "Bad Boys (2006)", 2); } - [Fact] - public void TestDirectories2() - { - //TestDirectory(@"blah blah", false, @"blah blah"); - //TestDirectory(@"d:/music/weezer/03 Pinkerton", false, "03 Pinkerton"); - //TestDirectory(@"d:/music/michael jackson/Bad (2012 Remaster)", false, "Bad (2012 Remaster)"); - - //TestDirectory(@"blah blah - cd1", true, "blah blah"); - //TestDirectory(@"blah blah - disc1", true, "blah blah"); - //TestDirectory(@"blah blah - disk1", true, "blah blah"); - //TestDirectory(@"blah blah - pt1", true, "blah blah"); - //TestDirectory(@"blah blah - part1", true, "blah blah"); - //TestDirectory(@"blah blah - dvd1", true, "blah blah"); - - //// Add a space - //TestDirectory(@"blah blah - cd 1", true, "blah blah"); - //TestDirectory(@"blah blah - disc 1", true, "blah blah"); - //TestDirectory(@"blah blah - disk 1", true, "blah blah"); - //TestDirectory(@"blah blah - pt 1", true, "blah blah"); - //TestDirectory(@"blah blah - part 1", true, "blah blah"); - //TestDirectory(@"blah blah - dvd 1", true, "blah blah"); - - //// Not case sensitive - //TestDirectory(@"blah blah - Disc1", true, "blah blah"); - } - [Fact] public void TestNamesWithoutParts() { From b1dc595be1a7cf331702fd645b1441ac86afa464 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 11 Jan 2020 20:25:06 +0100 Subject: [PATCH 033/881] Fix a couple of tests --- Emby.Naming/Common/NamingOptions.cs | 2 +- Emby.Naming/Video/CleanDateTimeParser.cs | 6 +- Emby.Naming/Video/CleanStringParser.cs | 4 +- Emby.Naming/Video/VideoResolver.cs | 2 +- .../Video/BaseVideoTest.cs | 8 +- .../Video/CleanDateTimeTests.cs | 170 +++++------------- .../Video/CleanStringTests.cs | 150 +++------------- .../Video/MultiVersionTests.cs | 1 - 8 files changed, 80 insertions(+), 263 deletions(-) diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 71521e1fd8..07259e00a1 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -182,7 +182,7 @@ namespace Emby.Naming.Common CleanStrings = new[] { - @"[ _\,\.\(\)\[\]\-](ac3|dts|custom|dc|divx|divx5|dsr|dsrip|dutch|dvd|dvdrip|dvdscr|dvdscreener|screener|dvdivx|cam|fragment|fs|hdtv|hdrip|hdtvrip|internal|limited|multisubs|ntsc|ogg|ogm|pal|pdtv|proper|repack|rerip|retail|cd[1-9]|r3|r5|bd5|se|svcd|swedish|german|read.nfo|nfofix|unrated|ws|telesync|ts|telecine|tc|brrip|bdrip|480p|480i|576p|576i|720p|720i|1080p|1080i|2160p|hrhd|hrhdtv|hddvd|bluray|x264|h264|xvid|xvidvd|xxx|www.www|\[.*\])([ _\,\.\(\)\[\]\-]|$)", + @"[ _\,\.\(\)\[\]\-](HDR|HDC|UHD|UltraHD|4k|ac3|dts|custom|dc|divx|divx5|dsr|dsrip|dutch|dvd|dvdrip|dvdscr|dvdscreener|screener|dvdivx|cam|fragment|fs|hdtv|hdrip|hdtvrip|internal|limited|multisubs|ntsc|ogg|ogm|pal|pdtv|proper|repack|rerip|retail|cd[1-9]|r3|r5|bd5|se|svcd|swedish|german|read.nfo|nfofix|unrated|ws|telesync|ts|telecine|tc|brrip|bdrip|480p|480i|576p|576i|720p|720i|1080p|1080i|2160p|hrhd|hrhdtv|hddvd|bluray|x264|h264|xvid|xvidvd|xxx|www.www|\[.*\])([ _\,\.\(\)\[\]\-]|$)", @"[ _\,\.\(\)\[\]\-](3d|sbs|tab|hsbs|htab|mvc|\[.*\])([ _\,\.\(\)\[\]\-]|$)", @"(\[.*\])" }; diff --git a/Emby.Naming/Video/CleanDateTimeParser.cs b/Emby.Naming/Video/CleanDateTimeParser.cs index a9db4ccccd..9edb14a074 100644 --- a/Emby.Naming/Video/CleanDateTimeParser.cs +++ b/Emby.Naming/Video/CleanDateTimeParser.cs @@ -53,7 +53,7 @@ namespace Emby.Naming.Video } // Make a second pass, running clean string first - var cleanStringResult = new CleanStringParser().Clean(name, _options.CleanStringRegexes); + var cleanStringResult = CleanStringParser.Clean(name, _options.CleanStringRegexes); if (!cleanStringResult.HasChanged) { @@ -72,12 +72,12 @@ namespace Emby.Naming.Video var match = expression.Match(name); if (match.Success - && match.Groups.Count == 4 + && match.Groups.Count == 5 && match.Groups[1].Success && match.Groups[2].Success && int.TryParse(match.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var year)) { - name = match.Groups[1].Value; + name = match.Groups[1].Value.TrimEnd(); result.Year = year; result.HasChanged = true; } diff --git a/Emby.Naming/Video/CleanStringParser.cs b/Emby.Naming/Video/CleanStringParser.cs index fcd4b65c75..fe2a91bdb9 100644 --- a/Emby.Naming/Video/CleanStringParser.cs +++ b/Emby.Naming/Video/CleanStringParser.cs @@ -9,9 +9,9 @@ namespace Emby.Naming.Video /// /// . /// - public class CleanStringParser + public static class CleanStringParser { - public CleanStringResult Clean(string name, IEnumerable expressions) + public static CleanStringResult Clean(string name, IEnumerable expressions) { var hasChanged = false; diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index 41b79697cc..97f59121b1 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -132,7 +132,7 @@ namespace Emby.Naming.Video public CleanStringResult CleanString(string name) { - return new CleanStringParser().Clean(name, _options.CleanStringRegexes); + return CleanStringParser.Clean(name, _options.CleanStringRegexes); } public CleanDateTimeResult CleanDateTime(string name) diff --git a/tests/Jellyfin.Naming.Tests/Video/BaseVideoTest.cs b/tests/Jellyfin.Naming.Tests/Video/BaseVideoTest.cs index b993e241c0..0c2978aca9 100644 --- a/tests/Jellyfin.Naming.Tests/Video/BaseVideoTest.cs +++ b/tests/Jellyfin.Naming.Tests/Video/BaseVideoTest.cs @@ -5,11 +5,9 @@ namespace Jellyfin.Naming.Tests.Video { public abstract class BaseVideoTest { - protected VideoResolver GetParser() - { - var options = new NamingOptions(); + private readonly NamingOptions _namingOptions = new NamingOptions(); - return new VideoResolver(options); - } + protected VideoResolver GetParser() + => new VideoResolver(_namingOptions); } } diff --git a/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs b/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs index bba73ad918..a2ef2dcd64 100644 --- a/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs @@ -1,143 +1,59 @@ using System.IO; +using Emby.Naming.Common; +using Emby.Naming.Video; using Xunit; namespace Jellyfin.Naming.Tests.Video { - public class CleanDateTimeTests : BaseVideoTest + public sealed class CleanDateTimeTests { - // FIXME - // [Fact] - public void TestCleanDateTime() - { - Test(@"The Wolf of Wall Street (2013).mkv", "The Wolf of Wall Street", 2013); - Test(@"The Wolf of Wall Street 2 (2013).mkv", "The Wolf of Wall Street 2", 2013); - Test(@"The Wolf of Wall Street - 2 (2013).mkv", "The Wolf of Wall Street - 2", 2013); - Test(@"The Wolf of Wall Street 2001 (2013).mkv", "The Wolf of Wall Street 2001", 2013); + private readonly NamingOptions _namingOptions = new NamingOptions(); - Test(@"300 (2006).mkv", "300", 2006); - Test(@"d:/movies/300 (2006).mkv", "300", 2006); - Test(@"300 2 (2006).mkv", "300 2", 2006); - Test(@"300 - 2 (2006).mkv", "300 - 2", 2006); - Test(@"300 2001 (2006).mkv", "300 2001", 2006); - - Test(@"curse.of.chucky.2013.stv.unrated.multi.1080p.bluray.x264-rough", "curse.of.chucky", 2013); - Test(@"curse.of.chucky.2013.stv.unrated.multi.2160p.bluray.x264-rough", "curse.of.chucky", 2013); - - Test(@"/server/Movies/300 (2007)/300 (2006).bluray.disc", "300", 2006); - } - - // FIXME - // [Fact] - public void TestCleanDateTime1() - { - Test(@"Arrival.2016.2160p.Blu-Ray.HEVC.mkv", "Arrival", 2016); - } - - // FIXME - // [Fact] - public void TestCleanDateTimeWithoutFileExtension() - { - Test(@"The Wolf of Wall Street (2013)", "The Wolf of Wall Street", 2013); - Test(@"The Wolf of Wall Street 2 (2013)", "The Wolf of Wall Street 2", 2013); - Test(@"The Wolf of Wall Street - 2 (2013)", "The Wolf of Wall Street - 2", 2013); - Test(@"The Wolf of Wall Street 2001 (2013)", "The Wolf of Wall Street 2001", 2013); - - Test(@"300 (2006)", "300", 2006); - Test(@"d:/movies/300 (2006)", "300", 2006); - Test(@"300 2 (2006)", "300 2", 2006); - Test(@"300 - 2 (2006)", "300 - 2", 2006); - Test(@"300 2001 (2006)", "300 2001", 2006); - - Test(@"/server/Movies/300 (2007)/300 (2006)", "300", 2006); - Test(@"/server/Movies/300 (2007)/300 (2006).mkv", "300", 2006); - } - - [Fact] - public void TestCleanDateTimeWithoutDate() - { - Test(@"American.Psycho.mkv", "American.Psycho.mkv", null); - Test(@"American Psycho.mkv", "American Psycho.mkv", null); - } - - [Fact] - public void TestCleanDateTimeWithBracketedName() - { - Test(@"[rec].mkv", "[rec].mkv", null); - } - - // FIXME - // [Fact] - public void TestCleanDateTimeWithoutExtension() - { - Test(@"St. Vincent (2014)", "St. Vincent", 2014); - } - - // FIXME - // [Fact] - public void TestCleanDateTimeWithoutDate1() - { - Test("Super movie(2009).mp4", "Super movie", 2009); - } - - // FIXME - // [Fact] - public void TestCleanDateTimeWithoutParenthesis() - { - Test("Drug War 2013.mp4", "Drug War", 2013); - } - - // FIXME - // [Fact] - public void TestCleanDateTimeWithMultipleYears() - { - Test("My Movie (1997) - GreatestReleaseGroup 2019.mp4", "My Movie", 1997); - } - - // FIXME - // [Fact] - public void TestCleanDateTimeWithYearAndResolution() - { - Test("First Man 2018 1080p.mkv", "First Man", 2018); - } - - // FIXME - // [Fact] - public void TestCleanDateTimeWithYearAndResolution1() - { - Test("First Man (2018) 1080p.mkv", "First Man", 2018); - } - - // FIXME - // [Fact] - public void TestCleanDateTimeWithSceneRelease() - { - Test("Maximum Ride - 2016 - WEBDL-1080p - x264 AC3.mkv", "Maximum Ride", 2016); - } - - // FIXME - // [Fact] - public void TestYearInBrackets() - { - Test("Robin Hood [Multi-Subs] [2018].mkv", "Robin Hood", 2018); - } - - private void Test(string input, string expectedName, int? expectedYear) + [Theory] + [InlineData(@"The Wolf of Wall Street (2013).mkv", "The Wolf of Wall Street", 2013)] + [InlineData(@"The Wolf of Wall Street 2 (2013).mkv", "The Wolf of Wall Street 2", 2013)] + [InlineData(@"The Wolf of Wall Street - 2 (2013).mkv", "The Wolf of Wall Street - 2", 2013)] + [InlineData(@"The Wolf of Wall Street 2001 (2013).mkv", "The Wolf of Wall Street 2001", 2013)] + [InlineData(@"300 (2006).mkv", "300", 2006)] + [InlineData(@"d:/movies/300 (2006).mkv", "300", 2006)] + [InlineData(@"300 2 (2006).mkv", "300 2", 2006)] + [InlineData(@"300 - 2 (2006).mkv", "300 - 2", 2006)] + [InlineData(@"300 2001 (2006).mkv", "300 2001", 2006)] + [InlineData(@"curse.of.chucky.2013.stv.unrated.multi.1080p.bluray.x264-rough", "curse.of.chucky", 2013)] + [InlineData(@"curse.of.chucky.2013.stv.unrated.multi.2160p.bluray.x264-rough", "curse.of.chucky", 2013)] + [InlineData(@"/server/Movies/300 (2007)/300 (2006).bluray.disc", "300", 2006)] + [InlineData(@"Arrival.2016.2160p.Blu-Ray.HEVC.mkv", "Arrival", 2016)] + [InlineData(@"The Wolf of Wall Street (2013)", "The Wolf of Wall Street", 2013)] + [InlineData(@"The Wolf of Wall Street 2 (2013)", "The Wolf of Wall Street 2", 2013)] + [InlineData(@"The Wolf of Wall Street - 2 (2013)", "The Wolf of Wall Street - 2", 2013)] + [InlineData(@"The Wolf of Wall Street 2001 (2013)", "The Wolf of Wall Street 2001", 2013)] + [InlineData(@"300 (2006)", "300", 2006)] + [InlineData(@"d:/movies/300 (2006)", "300", 2006)] + [InlineData(@"300 2 (2006)", "300 2", 2006)] + [InlineData(@"300 - 2 (2006)", "300 - 2", 2006)] + [InlineData(@"300 2001 (2006)", "300 2001", 2006)] + [InlineData(@"/server/Movies/300 (2007)/300 (2006)", "300", 2006)] + [InlineData(@"/server/Movies/300 (2007)/300 (2006).mkv", "300", 2006)] + [InlineData(@"American.Psycho.mkv", "American.Psycho.mkv", null)] + [InlineData(@"American Psycho.mkv", "American Psycho.mkv", null)] + [InlineData(@"[rec].mkv", "[rec].mkv", null)] + [InlineData(@"St. Vincent (2014)", "St. Vincent", 2014)] + [InlineData("Super movie(2009).mp4", "Super movie", 2009)] + // FIXME: [InlineData("Drug War 2013.mp4", "Drug War", 2013)] + [InlineData("My Movie (1997) - GreatestReleaseGroup 2019.mp4", "My Movie", 1997)] + // FIXME: [InlineData("First Man 2018 1080p.mkv", "First Man", 2018)] + [InlineData("First Man (2018) 1080p.mkv", "First Man", 2018)] + // FIXME: [InlineData("Maximum Ride - 2016 - WEBDL-1080p - x264 AC3.mkv", "Maximum Ride", 2016)] + // FIXME: [InlineData("Robin Hood [Multi-Subs] [2018].mkv", "Robin Hood", 2018)] + [InlineData(@"3.Days.to.Kill.2014.720p.BluRay.x264.YIFY.mkv", "3.Days.to.Kill", 2014)] // In this test case, running CleanDateTime first produces no date, so it will attempt to run CleanString first and then CleanDateTime again + public void CleanDateTimeTest(string input, string expectedName, int? expectedYear) { input = Path.GetFileName(input); - var result = GetParser().CleanDateTime(input); + var result = new VideoResolver(_namingOptions).CleanDateTime(input); Assert.Equal(expectedName, result.Name, true); Assert.Equal(expectedYear, result.Year); } - - // FIXME - // [Fact] - public void TestCleanDateAndStringsSequence() - { - // In this test case, running CleanDateTime first produces no date, so it will attempt to run CleanString first and then CleanDateTime again - - Test(@"3.Days.to.Kill.2014.720p.BluRay.x264.YIFY.mkv", "3.Days.to.Kill", 2014); - } } } diff --git a/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs b/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs index cd90ac236c..7c3270ebcc 100644 --- a/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs @@ -1,133 +1,37 @@ -using System; -using System.Globalization; +using Emby.Naming.Common; +using Emby.Naming.Video; using Xunit; namespace Jellyfin.Naming.Tests.Video { - public class CleanStringTests : BaseVideoTest + public sealed class CleanStringTests { - // FIXME - // [Fact] - public void TestCleanString() - { - Test("Super movie 480p.mp4", "Super movie"); - Test("Super movie 480p 2001.mp4", "Super movie"); - Test("Super movie [480p].mp4", "Super movie"); - Test("480 Super movie [tmdbid=12345].mp4", "480 Super movie"); - } + private readonly NamingOptions _namingOptions = new NamingOptions(); - // FIXME - // [Fact] - public void TestCleanString1() + [Theory] + [InlineData("Super movie 480p.mp4", "Super movie")] + [InlineData("Super movie 480p 2001.mp4", "Super movie")] + [InlineData("Super movie [480p].mp4", "Super movie")] + [InlineData("480 Super movie [tmdbid=12345].mp4", "480 Super movie")] + [InlineData("Super movie(2009).mp4", "Super movie(2009).mp4")] + [InlineData("Run lola run (lola rennt) (2009).mp4", "Run lola run (lola rennt) (2009).mp4")] + [InlineData(@"American.Psycho.mkv", "American.Psycho.mkv")] + [InlineData(@"American Psycho.mkv", "American Psycho.mkv")] + [InlineData(@"[rec].mkv", "[rec].mkv")] + [InlineData("Crouching.Tiger.Hidden.Dragon.4k.mkv", "Crouching.Tiger.Hidden.Dragon")] + [InlineData("Crouching.Tiger.Hidden.Dragon.UltraHD.mkv", "Crouching.Tiger.Hidden.Dragon")] + [InlineData("Crouching.Tiger.Hidden.Dragon.UHD.mkv", "Crouching.Tiger.Hidden.Dragon")] + [InlineData("Crouching.Tiger.Hidden.Dragon.HDR.mkv", "Crouching.Tiger.Hidden.Dragon")] + [InlineData("Crouching.Tiger.Hidden.Dragon.HDC.mkv", "Crouching.Tiger.Hidden.Dragon")] + [InlineData("Crouching.Tiger.Hidden.Dragon-HDC.mkv", "Crouching.Tiger.Hidden.Dragon")] + [InlineData("Crouching.Tiger.Hidden.Dragon.BDrip.mkv", "Crouching.Tiger.Hidden.Dragon")] + [InlineData("Crouching.Tiger.Hidden.Dragon.BDrip-HDC.mkv", "Crouching.Tiger.Hidden.Dragon")] + [InlineData("Crouching.Tiger.Hidden.Dragon.4K.UltraHD.HDR.BDrip-HDC.mkv", "Crouching.Tiger.Hidden.Dragon")] + // FIXME: [InlineData("After The Sunset - [0004].mkv", "After The Sunset")] + public void CleanStringTest(string input, string expectedName) { - Test("Super movie(2009).mp4", "Super movie(2009).mp4"); - } - - // FIXME - // [Fact] - public void TestCleanString2() - { - Test("Run lola run (lola rennt) (2009).mp4", "Run lola run (lola rennt) (2009).mp4"); - } - - // FIXME - // [Fact] - public void TestStringWithoutDate() - { - Test(@"American.Psycho.mkv", "American.Psycho.mkv"); - Test(@"American Psycho.mkv", "American Psycho.mkv"); - } - - // FIXME - // [Fact] - public void TestNameWithBrackets() - { - Test(@"[rec].mkv", "[rec].mkv"); - } - - // FIXME - // [Fact] - public void Test4k() - { - Test("Crouching.Tiger.Hidden.Dragon.4k.mkv", "Crouching.Tiger.Hidden.Dragon"); - } - - // FIXME - // [Fact] - public void TestUltraHd() - { - Test("Crouching.Tiger.Hidden.Dragon.UltraHD.mkv", "Crouching.Tiger.Hidden.Dragon"); - } - - // FIXME - // [Fact] - public void TestUHd() - { - Test("Crouching.Tiger.Hidden.Dragon.UHD.mkv", "Crouching.Tiger.Hidden.Dragon"); - } - - // FIXME - // [Fact] - public void TestHDR() - { - Test("Crouching.Tiger.Hidden.Dragon.HDR.mkv", "Crouching.Tiger.Hidden.Dragon"); - } - - // FIXME - // [Fact] - public void TestHDC() - { - Test("Crouching.Tiger.Hidden.Dragon.HDC.mkv", "Crouching.Tiger.Hidden.Dragon"); - } - - // FIXME - // [Fact] - public void TestHDC1() - { - Test("Crouching.Tiger.Hidden.Dragon-HDC.mkv", "Crouching.Tiger.Hidden.Dragon"); - } - - // FIXME - // [Fact] - public void TestBDrip() - { - Test("Crouching.Tiger.Hidden.Dragon.BDrip.mkv", "Crouching.Tiger.Hidden.Dragon"); - } - - // FIXME - // [Fact] - public void TestBDripHDC() - { - Test("Crouching.Tiger.Hidden.Dragon.BDrip-HDC.mkv", "Crouching.Tiger.Hidden.Dragon"); - } - - // FIXME - // [Fact] - public void TestMulti() - { - Test("Crouching.Tiger.Hidden.Dragon.4K.UltraHD.HDR.BDrip-HDC.mkv", "Crouching.Tiger.Hidden.Dragon"); - } - - // FIXME - // [Fact] - public void TestLeadingBraces() - { - // Not actually supported, just reported by a user - Test("[0004] - After The Sunset.el.mkv", "After The Sunset"); - } - - // FIXME - // [Fact] - public void TestTrailingBraces() - { - Test("After The Sunset - [0004].mkv", "After The Sunset"); - } - - private void Test(string input, string expectedName) - { - var result = GetParser().CleanString(input).ToString(); - - Assert.Equal(expectedName, result, true); + var result = new VideoResolver(_namingOptions).CleanString(input); + Assert.Equal(expectedName, result.Name); } } } diff --git a/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs b/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs index b8674ec495..b8fbb2cb25 100644 --- a/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs @@ -62,7 +62,6 @@ namespace Jellyfin.Naming.Tests.Video [Fact] public void TestMultiEdition3() { - // This is currently not supported and will fail, but we should try to figure it out var files = new[] { @"/movies/The Phantom of the Opera (1925)/The Phantom of the Opera (1925) - 1925 version.mkv", From dd254eddac4b805f0020e5899fb903ef10714527 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 11 Jan 2020 20:31:59 +0100 Subject: [PATCH 034/881] Simplify CleanDateTimeParser --- Emby.Naming/Video/CleanDateTimeParser.cs | 44 ++---------------------- 1 file changed, 2 insertions(+), 42 deletions(-) diff --git a/Emby.Naming/Video/CleanDateTimeParser.cs b/Emby.Naming/Video/CleanDateTimeParser.cs index 9edb14a074..9723fb71a3 100644 --- a/Emby.Naming/Video/CleanDateTimeParser.cs +++ b/Emby.Naming/Video/CleanDateTimeParser.cs @@ -1,9 +1,7 @@ #pragma warning disable CS1591 #pragma warning disable SA1600 -using System; using System.Globalization; -using System.IO; using System.Linq; using System.Text.RegularExpressions; using Emby.Naming.Common; @@ -23,47 +21,9 @@ namespace Emby.Naming.Video } public CleanDateTimeResult Clean(string name) - { - var originalName = name; - - try - { - var extension = Path.GetExtension(name) ?? string.Empty; - // Check supported extensions - if (!_options.VideoFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase) - && !_options.AudioFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)) - { - // Dummy up a file extension because the expressions will fail without one - // This is tricky because we can't just check Path.GetExtension for empty - // If the input is "St. Vincent (2014)", it will produce ". Vincent (2014)" as the extension - name += ".mkv"; - } - } - catch (ArgumentException) - { - } - - var result = _options.CleanDateTimeRegexes.Select(i => Clean(name, i)) + => _options.CleanDateTimeRegexes.Select(i => Clean(name, i)) .FirstOrDefault(i => i.HasChanged) ?? - new CleanDateTimeResult { Name = originalName }; - - if (result.HasChanged) - { - return result; - } - - // Make a second pass, running clean string first - var cleanStringResult = CleanStringParser.Clean(name, _options.CleanStringRegexes); - - if (!cleanStringResult.HasChanged) - { - return result; - } - - return _options.CleanDateTimeRegexes.Select(i => Clean(cleanStringResult.Name, i)) - .FirstOrDefault(i => i.HasChanged) ?? - result; - } + new CleanDateTimeResult { Name = name }; private static CleanDateTimeResult Clean(string name, Regex expression) { From cd0592ea8f4a373a4318d2aba42349a1b89d4b32 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 11 Jan 2020 21:16:36 +0100 Subject: [PATCH 035/881] Improve parsers --- Emby.Naming/Common/NamingOptions.cs | 3 +- Emby.Naming/Video/CleanDateTimeParser.cs | 36 +++++++++++------ Emby.Naming/Video/CleanDateTimeResult.cs | 29 ++++++++------ Emby.Naming/Video/CleanStringParser.cs | 39 ++++++++----------- Emby.Naming/Video/CleanStringResult.cs | 20 ---------- Emby.Naming/Video/VideoResolver.cs | 9 +++-- .../Video/CleanStringTests.cs | 14 +++++-- 7 files changed, 75 insertions(+), 75 deletions(-) delete mode 100644 Emby.Naming/Video/CleanStringResult.cs diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 07259e00a1..41060426fa 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -182,8 +182,7 @@ namespace Emby.Naming.Common CleanStrings = new[] { - @"[ _\,\.\(\)\[\]\-](HDR|HDC|UHD|UltraHD|4k|ac3|dts|custom|dc|divx|divx5|dsr|dsrip|dutch|dvd|dvdrip|dvdscr|dvdscreener|screener|dvdivx|cam|fragment|fs|hdtv|hdrip|hdtvrip|internal|limited|multisubs|ntsc|ogg|ogm|pal|pdtv|proper|repack|rerip|retail|cd[1-9]|r3|r5|bd5|se|svcd|swedish|german|read.nfo|nfofix|unrated|ws|telesync|ts|telecine|tc|brrip|bdrip|480p|480i|576p|576i|720p|720i|1080p|1080i|2160p|hrhd|hrhdtv|hddvd|bluray|x264|h264|xvid|xvidvd|xxx|www.www|\[.*\])([ _\,\.\(\)\[\]\-]|$)", - @"[ _\,\.\(\)\[\]\-](3d|sbs|tab|hsbs|htab|mvc|\[.*\])([ _\,\.\(\)\[\]\-]|$)", + @"[ _\,\.\(\)\[\]\-](3d|sbs|tab|hsbs|htab|mvc|HDR|HDC|UHD|UltraHD|4k|ac3|dts|custom|dc|divx|divx5|dsr|dsrip|dutch|dvd|dvdrip|dvdscr|dvdscreener|screener|dvdivx|cam|fragment|fs|hdtv|hdrip|hdtvrip|internal|limited|multisubs|ntsc|ogg|ogm|pal|pdtv|proper|repack|rerip|retail|cd[1-9]|r3|r5|bd5|se|svcd|swedish|german|read.nfo|nfofix|unrated|ws|telesync|ts|telecine|tc|brrip|bdrip|480p|480i|576p|576i|720p|720i|1080p|1080i|2160p|hrhd|hrhdtv|hddvd|bluray|x264|h264|xvid|xvidvd|xxx|www.www|\[.*\])([ _\,\.\(\)\[\]\-]|$)", @"(\[.*\])" }; diff --git a/Emby.Naming/Video/CleanDateTimeParser.cs b/Emby.Naming/Video/CleanDateTimeParser.cs index 9723fb71a3..8638dddd42 100644 --- a/Emby.Naming/Video/CleanDateTimeParser.cs +++ b/Emby.Naming/Video/CleanDateTimeParser.cs @@ -1,8 +1,8 @@ #pragma warning disable CS1591 #pragma warning disable SA1600 +#nullable enable using System.Globalization; -using System.Linq; using System.Text.RegularExpressions; using Emby.Naming.Common; @@ -21,14 +21,28 @@ namespace Emby.Naming.Video } public CleanDateTimeResult Clean(string name) - => _options.CleanDateTimeRegexes.Select(i => Clean(name, i)) - .FirstOrDefault(i => i.HasChanged) ?? - new CleanDateTimeResult { Name = name }; - - private static CleanDateTimeResult Clean(string name, Regex expression) { - var result = new CleanDateTimeResult(); + var regexes = _options.CleanDateTimeRegexes; + var len = regexes.Length; + CleanDateTimeResult result = new CleanDateTimeResult(name); + if (len == 0) + { + return result; + } + for (int i = 0; i < len; i++) + { + if (TryClean(name, regexes[i], ref result)) + { + return result; + } + } + + return result; + } + + private static bool TryClean(string name, Regex expression, ref CleanDateTimeResult result) + { var match = expression.Match(name); if (match.Success @@ -37,13 +51,11 @@ namespace Emby.Naming.Video && match.Groups[2].Success && int.TryParse(match.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var year)) { - name = match.Groups[1].Value.TrimEnd(); - result.Year = year; - result.HasChanged = true; + result = new CleanDateTimeResult(match.Groups[1].Value.TrimEnd(), year); + return true; } - result.Name = name; - return result; + return false; } } } diff --git a/Emby.Naming/Video/CleanDateTimeResult.cs b/Emby.Naming/Video/CleanDateTimeResult.cs index a7581972e4..73a445612b 100644 --- a/Emby.Naming/Video/CleanDateTimeResult.cs +++ b/Emby.Naming/Video/CleanDateTimeResult.cs @@ -1,26 +1,33 @@ #pragma warning disable CS1591 #pragma warning disable SA1600 +#nullable enable namespace Emby.Naming.Video { - public class CleanDateTimeResult + public readonly struct CleanDateTimeResult { + public CleanDateTimeResult(string name, int? year) + { + Name = name; + Year = year; + } + + public CleanDateTimeResult(string name) + { + Name = name; + Year = null; + } + /// - /// Gets or sets the name. + /// Gets the name. /// /// The name. - public string Name { get; set; } + public string Name { get; } /// - /// Gets or sets the year. + /// Gets the year. /// /// The year. - public int? Year { get; set; } - - /// - /// Gets or sets a value indicating whether this instance has changed. - /// - /// true if this instance has changed; otherwise, false. - public bool HasChanged { get; set; } + public int? Year { get; } } } diff --git a/Emby.Naming/Video/CleanStringParser.cs b/Emby.Naming/Video/CleanStringParser.cs index fe2a91bdb9..b7b65d8228 100644 --- a/Emby.Naming/Video/CleanStringParser.cs +++ b/Emby.Naming/Video/CleanStringParser.cs @@ -1,6 +1,8 @@ #pragma warning disable CS1591 #pragma warning disable SA1600 +#nullable enable +using System; using System.Collections.Generic; using System.Text.RegularExpressions; @@ -11,42 +13,33 @@ namespace Emby.Naming.Video /// public static class CleanStringParser { - public static CleanStringResult Clean(string name, IEnumerable expressions) + public static bool TryClean(string name, IReadOnlyList expressions, out ReadOnlySpan newName) { - var hasChanged = false; - - foreach (var exp in expressions) + var len = expressions.Count; + for (int i = 0; i < len; i++) { - var result = Clean(name, exp); - - if (!string.IsNullOrEmpty(result.Name)) + if (TryClean(name, expressions[i], out newName)) { - name = result.Name; - hasChanged = hasChanged || result.HasChanged; + return true; } } - return new CleanStringResult - { - Name = name, - HasChanged = hasChanged - }; + newName = ReadOnlySpan.Empty; + return false; } - private static CleanStringResult Clean(string name, Regex expression) + private static bool TryClean(string name, Regex expression, out ReadOnlySpan newName) { - var result = new CleanStringResult(); - var match = expression.Match(name); - - if (match.Success) + int index = match.Index; + if (match.Success && index != 0) { - result.HasChanged = true; - name = name.Substring(0, match.Index); + newName = name.AsSpan().Slice(0, match.Index); + return true; } - result.Name = name; - return result; + newName = string.Empty; + return false; } } } diff --git a/Emby.Naming/Video/CleanStringResult.cs b/Emby.Naming/Video/CleanStringResult.cs deleted file mode 100644 index 786fe9e028..0000000000 --- a/Emby.Naming/Video/CleanStringResult.cs +++ /dev/null @@ -1,20 +0,0 @@ -#pragma warning disable CS1591 -#pragma warning disable SA1600 - -namespace Emby.Naming.Video -{ - public class CleanStringResult - { - /// - /// Gets or sets the name. - /// - /// The name. - public string Name { get; set; } - - /// - /// Gets or sets a value indicating whether this instance has changed. - /// - /// true if this instance has changed; otherwise, false. - public bool HasChanged { get; set; } - } -} diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index 97f59121b1..76e0a5a0ec 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -94,9 +94,10 @@ namespace Emby.Naming.Video { var cleanDateTimeResult = CleanDateTime(name); - if (extraResult.ExtraType == null) + if (extraResult.ExtraType == null + && TryCleanString(cleanDateTimeResult.Name, out ReadOnlySpan newName)) { - name = CleanString(cleanDateTimeResult.Name).Name; + name = newName.ToString(); } year = cleanDateTimeResult.Year; @@ -130,9 +131,9 @@ namespace Emby.Naming.Video return _options.StubFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase); } - public CleanStringResult CleanString(string name) + public bool TryCleanString(string name, out ReadOnlySpan newName) { - return CleanStringParser.Clean(name, _options.CleanStringRegexes); + return CleanStringParser.TryClean(name, _options.CleanStringRegexes, out newName); } public CleanDateTimeResult CleanDateTime(string name) diff --git a/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs b/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs index 7c3270ebcc..fde06c5a17 100644 --- a/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs @@ -1,4 +1,5 @@ -using Emby.Naming.Common; +using System; +using Emby.Naming.Common; using Emby.Naming.Video; using Xunit; @@ -30,8 +31,15 @@ namespace Jellyfin.Naming.Tests.Video // FIXME: [InlineData("After The Sunset - [0004].mkv", "After The Sunset")] public void CleanStringTest(string input, string expectedName) { - var result = new VideoResolver(_namingOptions).CleanString(input); - Assert.Equal(expectedName, result.Name); + if (new VideoResolver(_namingOptions).TryCleanString(input, out ReadOnlySpan newName)) + { + // TODO: compare spans when XUnit supports it + Assert.Equal(expectedName, newName.ToString()); + } + else + { + Assert.Equal(expectedName, input); + } } } } From ec0ef2a2c5a20b7e6aaa5959b52bf399b0b6dde2 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 11 Jan 2020 21:18:30 +0100 Subject: [PATCH 036/881] Remove useless statement --- Emby.Naming/Video/CleanDateTimeParser.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Emby.Naming/Video/CleanDateTimeParser.cs b/Emby.Naming/Video/CleanDateTimeParser.cs index 8638dddd42..84a14a54f5 100644 --- a/Emby.Naming/Video/CleanDateTimeParser.cs +++ b/Emby.Naming/Video/CleanDateTimeParser.cs @@ -24,12 +24,8 @@ namespace Emby.Naming.Video { var regexes = _options.CleanDateTimeRegexes; var len = regexes.Length; - CleanDateTimeResult result = new CleanDateTimeResult(name); - if (len == 0) - { - return result; - } + CleanDateTimeResult result = new CleanDateTimeResult(name); for (int i = 0; i < len; i++) { if (TryClean(name, regexes[i], ref result)) From abf03f7d3ad14f026fd439f522403353a7ecec86 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 11 Jan 2020 21:31:35 +0100 Subject: [PATCH 037/881] Clean up some more --- Emby.Naming/Video/CleanDateTimeParser.cs | 19 +++++------------ Emby.Naming/Video/VideoResolver.cs | 2 +- .../Library/LibraryManager.cs | 21 ++++++------------- 3 files changed, 12 insertions(+), 30 deletions(-) diff --git a/Emby.Naming/Video/CleanDateTimeParser.cs b/Emby.Naming/Video/CleanDateTimeParser.cs index 84a14a54f5..6c74c07d55 100644 --- a/Emby.Naming/Video/CleanDateTimeParser.cs +++ b/Emby.Naming/Video/CleanDateTimeParser.cs @@ -2,33 +2,24 @@ #pragma warning disable SA1600 #nullable enable +using System.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; -using Emby.Naming.Common; namespace Emby.Naming.Video { /// /// . /// - public class CleanDateTimeParser + public static class CleanDateTimeParser { - private readonly NamingOptions _options; - - public CleanDateTimeParser(NamingOptions options) + public static CleanDateTimeResult Clean(string name, IReadOnlyList cleanDateTimeRegexes) { - _options = options; - } - - public CleanDateTimeResult Clean(string name) - { - var regexes = _options.CleanDateTimeRegexes; - var len = regexes.Length; - CleanDateTimeResult result = new CleanDateTimeResult(name); + var len = cleanDateTimeRegexes.Count; for (int i = 0; i < len; i++) { - if (TryClean(name, regexes[i], ref result)) + if (TryClean(name, cleanDateTimeRegexes[i], ref result)) { return result; } diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index 76e0a5a0ec..f93db24866 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -138,7 +138,7 @@ namespace Emby.Naming.Video public CleanDateTimeResult CleanDateTime(string name) { - return new CleanDateTimeParser(_options).Clean(name); + return CleanDateTimeParser.Clean(name, _options.CleanDateTimeRegexes); } } } diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index ae3cdece91..6fb6235541 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -36,7 +36,6 @@ using MediaBrowser.Controller.Sorting; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; using MediaBrowser.Model.Library; using MediaBrowser.Model.Net; @@ -54,6 +53,9 @@ namespace Emby.Server.Implementations.Library /// public class LibraryManager : ILibraryManager { + private NamingOptions _namingOptions; + private string[] _videoFileExtensions; + /// /// Gets or sets the postscan tasks. /// @@ -2508,21 +2510,11 @@ namespace Emby.Server.Implementations.Library } public NamingOptions GetNamingOptions() - { - return GetNamingOptionsInternal(); - } - - private NamingOptions _namingOptions; - private string[] _videoFileExtensions; - - private NamingOptions GetNamingOptionsInternal() { if (_namingOptions == null) { - var options = new NamingOptions(); - - _namingOptions = options; - _videoFileExtensions = _namingOptions.VideoFileExtensions.ToArray(); + _namingOptions = new NamingOptions(); + _videoFileExtensions = _namingOptions.VideoFileExtensions; } return _namingOptions; @@ -2533,11 +2525,10 @@ namespace Emby.Server.Implementations.Library var resolver = new VideoResolver(GetNamingOptions()); var result = resolver.CleanDateTime(name); - var cleanName = resolver.CleanString(result.Name); return new ItemLookupInfo { - Name = cleanName.Name, + Name = resolver.TryCleanString(result.Name, out var newName) ? newName.ToString() : result.Name, Year = result.Year }; } From 9f5bbb126e55b23243d22bcfd85fbbb17e10ec17 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 11 Jan 2020 22:29:46 +0100 Subject: [PATCH 038/881] Fix tests --- Emby.Naming/Common/NamingOptions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 41060426fa..9ce503b8e4 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -177,7 +177,7 @@ namespace Emby.Naming.Common CleanDateTimes = new[] { - @"(.+[^_\,\.\(\)\[\]\-])[_\.\(\)\[\]\-](\d{4})([ _\,\.\(\)\[\]\-][^\d]|).*(\d{4})*" + @"(.+[^_\,\.\(\)\[\]\-])[_\.\(\)\[\]\-](19\d{2}|20\d{2})([ _\,\.\(\)\[\]\-][^0-9]|).*(19\d{2}|20\d{2})*" }; CleanStrings = new[] From 081d942d0361a4ad8aa918edcbb2f20c4c3f8471 Mon Sep 17 00:00:00 2001 From: Maximilian Marschall Date: Sun, 12 Jan 2020 00:31:17 +0100 Subject: [PATCH 039/881] Enable Throttling when transcoding without Hardware-Acceleration --- CONTRIBUTORS.md | 1 + MediaBrowser.Api/Playback/BaseStreamingService.cs | 12 ++++++++++++ 2 files changed, 13 insertions(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 458944778e..2d2e5712a5 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -32,6 +32,7 @@ - [nevado](https://github.com/nevado) - [mark-monteiro](https://github.com/mark-monteiro) - [ullmie02](https://github.com/ullmie02) + - [geilername](https://github.com/geilername) # Emby Contributors diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index 5881e22a7c..023d373d5b 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -327,6 +327,18 @@ namespace MediaBrowser.Api.Playback private bool EnableThrottling(StreamState state) { + var encodingOptions = ServerConfigurationManager.GetEncodingOptions(); + + // enable throttling when not using hardware acceleration + if (encodingOptions.HardwareAccelerationType == string.Empty) + { + return state.InputProtocol == MediaProtocol.File && + state.RunTimeTicks.HasValue && + state.RunTimeTicks.Value >= TimeSpan.FromMinutes(5).Ticks && + state.IsInputVideo && + state.VideoType == VideoType.VideoFile && + !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase); + } return false; //// do not use throttling with hardware encoders //return state.InputProtocol == MediaProtocol.File && From 08c4d3797fd2bb54936d4cba1b71de915432ebd1 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <799610810@qq.com> Date: Sun, 12 Jan 2020 21:38:28 +0800 Subject: [PATCH 040/881] add support for AMF hardware encoding on Linux. 1) h264_amf is now supported on linux with 'amdgpu-pro' installed and '--enable-amf' when compiling ffmpeg. 2) Using vaapi decode and h264_amf encode on linux platform can avoid some weird transcoding errors in h264_vaapi with amd gpu. --- .../MediaEncoding/EncodingHelper.cs | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 020f0553ed..a099087628 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2642,22 +2642,11 @@ namespace MediaBrowser.Controller.MediaEncoding else return "-hwaccel dxva2"; } - - switch (videoStream.Codec.ToLowerInvariant()) + else { - case "avc": - case "h264": - if (_mediaEncoder.SupportsDecoder("h264_amf") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v h264_amf"; - } - break; - case "mpeg2video": - if (_mediaEncoder.SupportsDecoder("hevc_amf") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v mpeg2_mmal"; - } - break; + //h264_amf is now supported on linux with 'amdgpu-pro' installed and '--enable-amf' when compiling ffmpeg + //using vaapi decode and h264_amf encode on linux platform can avoid some weird transcoding errors in h264_vaapi with amd gpu + return "-hwaccel vaapi"; } } } From ded9857f45388ce5499d09b537c56157c48ca759 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Sun, 12 Jan 2020 18:59:10 +0100 Subject: [PATCH 041/881] Clean up server discovery code --- .../EntryPoints/UdpServerEntryPoint.cs | 58 ++-- .../Net/SocketFactory.cs | 29 -- Emby.Server.Implementations/Net/UdpSocket.cs | 9 - Emby.Server.Implementations/Udp/UdpServer.cs | 273 ++++-------------- MediaBrowser.Model/Net/ISocket.cs | 2 - MediaBrowser.Model/Net/ISocketFactory.cs | 9 - 6 files changed, 78 insertions(+), 302 deletions(-) diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index 9ee219854d..a83817cb96 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -1,4 +1,5 @@ using System; +using System.Threading; using System.Threading.Tasks; using Emby.Server.Implementations.Udp; using MediaBrowser.Controller; @@ -12,7 +13,7 @@ namespace Emby.Server.Implementations.EntryPoints /// /// Class UdpServerEntryPoint. /// - public class UdpServerEntryPoint : IServerEntryPoint + public sealed class UdpServerEntryPoint : IServerEntryPoint { /// /// The port of the UDP server. @@ -31,61 +32,44 @@ namespace Emby.Server.Implementations.EntryPoints /// The UDP server. /// private UdpServer _udpServer; + private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + private bool _disposed = false; /// /// Initializes a new instance of the class. /// public UdpServerEntryPoint( - ILogger logger, - IServerApplicationHost appHost, - IJsonSerializer json, - ISocketFactory socketFactory) + ILogger logger, + IServerApplicationHost appHost) { _logger = logger; _appHost = appHost; - _json = json; - _socketFactory = socketFactory; + + } /// - public Task RunAsync() + public async Task RunAsync() { - var udpServer = new UdpServer(_logger, _appHost, _json, _socketFactory); - - try - { - udpServer.Start(PortNumber); - - _udpServer = udpServer; - } - catch (Exception ex) - { - _logger.LogError(ex, "Failed to start UDP Server"); - } - - return Task.CompletedTask; + _udpServer = new UdpServer(_logger, _appHost); + _udpServer.Start(PortNumber, _cancellationTokenSource.Token); } /// public void Dispose() { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// 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) - { - if (dispose) + if (_disposed) { - if (_udpServer != null) - { - _udpServer.Dispose(); - } + return; } + + _cancellationTokenSource.Cancel(); + _udpServer.Dispose(); + + _cancellationTokenSource = null; + _udpServer = null; + + _disposed = true; } } } diff --git a/Emby.Server.Implementations/Net/SocketFactory.cs b/Emby.Server.Implementations/Net/SocketFactory.cs index 0870db003f..4e04cde78c 100644 --- a/Emby.Server.Implementations/Net/SocketFactory.cs +++ b/Emby.Server.Implementations/Net/SocketFactory.cs @@ -8,32 +8,6 @@ namespace Emby.Server.Implementations.Net { public class SocketFactory : ISocketFactory { - /// - /// Creates a new UDP acceptSocket and binds it to the specified local port. - /// - /// An integer specifying the local port to bind the acceptSocket to. - public ISocket CreateUdpSocket(int localPort) - { - if (localPort < 0) - { - throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort)); - } - - var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); - - try - { - retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); - return new UdpSocket(retVal, localPort, IPAddress.Any); - } - catch - { - retVal?.Dispose(); - - throw; - } - } - public ISocket CreateUdpBroadcastSocket(int localPort) { if (localPort < 0) @@ -156,8 +130,5 @@ namespace Emby.Server.Implementations.Net throw; } } - - public Stream CreateNetworkStream(ISocket socket, bool ownsSocket) - => new NetworkStream(((UdpSocket)socket).Socket, ownsSocket); } } diff --git a/Emby.Server.Implementations/Net/UdpSocket.cs b/Emby.Server.Implementations/Net/UdpSocket.cs index dde4a2a34c..211ca67841 100644 --- a/Emby.Server.Implementations/Net/UdpSocket.cs +++ b/Emby.Server.Implementations/Net/UdpSocket.cs @@ -181,15 +181,6 @@ namespace Emby.Server.Implementations.Net return taskCompletion.Task; } - public Task ReceiveAsync(CancellationToken cancellationToken) - { - ThrowIfDisposed(); - - var buffer = new byte[8192]; - - return ReceiveAsync(buffer, 0, buffer.Length, cancellationToken); - } - public Task SendToAsync(byte[] buffer, int offset, int size, IPEndPoint endPoint, CancellationToken cancellationToken) { ThrowIfDisposed(); diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs index 185a282ac4..19fc1e316d 100644 --- a/Emby.Server.Implementations/Udp/UdpServer.cs +++ b/Emby.Server.Implementations/Udp/UdpServer.cs @@ -1,112 +1,47 @@ using System; -using System.Collections.Generic; -using System.Linq; using System.Net; +using System.Net.Sockets; using System.Text; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller; using MediaBrowser.Model.ApiClient; -using MediaBrowser.Model.Events; -using MediaBrowser.Model.Net; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Udp { /// - /// Provides a Udp Server + /// Provides a Udp Server. /// - public class UdpServer : IDisposable + public sealed class UdpServer : IDisposable { /// /// The _logger /// private readonly ILogger _logger; - - private bool _isDisposed; - - private readonly List>> _responders = new List>>(); - private readonly IServerApplicationHost _appHost; - private readonly IJsonSerializer _json; + + /// + /// The _udp client. + /// + private Socket _udpSocket; + private IPEndPoint _endpoint; + private readonly byte[] _receiveBuffer = new byte[8192]; + + private bool _disposed = false; /// /// Initializes a new instance of the class. /// - public UdpServer(ILogger logger, IServerApplicationHost appHost, IJsonSerializer json, ISocketFactory socketFactory) + public UdpServer(ILogger logger, IServerApplicationHost appHost) { _logger = logger; _appHost = appHost; - _json = json; - _socketFactory = socketFactory; - - AddMessageResponder("who is JellyfinServer?", true, RespondToV2Message); } - private void AddMessageResponder(string message, bool isSubstring, Func responder) + private async Task RespondToV2Message(string messageText, EndPoint endpoint, CancellationToken cancellationToken) { - _responders.Add(new Tuple>(message, isSubstring, responder)); - } - - /// - /// Raises the event. - /// - private async void OnMessageReceived(GenericEventArgs e) - { - var message = e.Argument; - - var encoding = Encoding.UTF8; - var responder = GetResponder(message.Buffer, message.ReceivedBytes, encoding); - - if (responder == null) - { - encoding = Encoding.Unicode; - responder = GetResponder(message.Buffer, message.ReceivedBytes, encoding); - } - - if (responder != null) - { - var cancellationToken = CancellationToken.None; - - try - { - await responder.Item2.Item3(responder.Item1, message.RemoteEndPoint, encoding, cancellationToken).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - - } - catch (Exception ex) - { - _logger.LogError(ex, "Error in OnMessageReceived"); - } - } - } - - private Tuple>> GetResponder(byte[] buffer, int bytesReceived, Encoding encoding) - { - var text = encoding.GetString(buffer, 0, bytesReceived); - var responder = _responders.FirstOrDefault(i => - { - if (i.Item2) - { - return text.IndexOf(i.Item1, StringComparison.OrdinalIgnoreCase) != -1; - } - return string.Equals(i.Item1, text, StringComparison.OrdinalIgnoreCase); - }); - - if (responder == null) - { - return null; - } - return new Tuple>>(text, responder); - } - - private async Task RespondToV2Message(string messageText, IPEndPoint endpoint, Encoding encoding, CancellationToken cancellationToken) - { - var parts = messageText.Split('|'); - var localUrl = await _appHost.GetLocalApiUrl(cancellationToken).ConfigureAwait(false); if (!string.IsNullOrEmpty(localUrl)) @@ -118,8 +53,16 @@ namespace Emby.Server.Implementations.Udp Name = _appHost.FriendlyName }; - await SendAsync(encoding.GetBytes(_json.SerializeToString(response)), endpoint, cancellationToken).ConfigureAwait(false); + try + { + await _udpSocket.SendToAsync(JsonSerializer.SerializeToUtf8Bytes(response), SocketFlags.None, endpoint).ConfigureAwait(false); + } + catch (SocketException ex) + { + _logger.LogError(ex, "Error sending response message"); + } + var parts = messageText.Split('|'); if (parts.Length > 1) { _appHost.EnableLoopback(parts[1]); @@ -131,162 +74,60 @@ namespace Emby.Server.Implementations.Udp } } - /// - /// The _udp client - /// - private ISocket _udpClient; - private readonly ISocketFactory _socketFactory; - /// /// Starts the specified port. /// /// The port. - public void Start(int port) + /// + public void Start(int port, CancellationToken cancellationToken) { - _udpClient = _socketFactory.CreateUdpSocket(port); + _endpoint = new IPEndPoint(IPAddress.Any, port); - Task.Run(() => BeginReceive()); + _udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + _udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + _udpSocket.Bind(_endpoint); + + _ = Task.Run(async () => await BeginReceiveAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); } - private readonly byte[] _receiveBuffer = new byte[8192]; - - private void BeginReceive() + private async Task BeginReceiveAsync(CancellationToken cancellationToken) { - if (_isDisposed) + while (!cancellationToken.IsCancellationRequested) { - return; - } - - try - { - var result = _udpClient.BeginReceive(_receiveBuffer, 0, _receiveBuffer.Length, OnReceiveResult); - - if (result.CompletedSynchronously) + try { - OnReceiveResult(result); + var result = await _udpSocket.ReceiveFromAsync(_receiveBuffer, SocketFlags.None, _endpoint).ConfigureAwait(false); + + cancellationToken.ThrowIfCancellationRequested(); + + var text = Encoding.UTF8.GetString(_receiveBuffer, 0, result.ReceivedBytes); + if (text.Contains("who is JellyfinServer?", StringComparison.OrdinalIgnoreCase)) + { + await RespondToV2Message(text, result.RemoteEndPoint, cancellationToken).ConfigureAwait(false); + } + } + catch (SocketException ex) + { + _logger.LogError(ex, "Failed to receive data drom socket"); + } + catch (OperationCanceledException) + { + // Don't throw } } - catch (ObjectDisposedException) - { - //TODO Investigate and properly fix. - } - catch (Exception ex) - { - _logger.LogError(ex, "Error receiving udp message"); - } } - private void OnReceiveResult(IAsyncResult result) - { - if (_isDisposed) - { - return; - } - - try - { - var socketResult = _udpClient.EndReceive(result); - - OnMessageReceived(socketResult); - } - catch (ObjectDisposedException) - { - //TODO Investigate and properly fix. - } - catch (Exception ex) - { - _logger.LogError(ex, "Error receiving udp message"); - } - - BeginReceive(); - } - - /// - /// Called when [message received]. - /// - /// The message. - private void OnMessageReceived(SocketReceiveResult message) - { - if (_isDisposed) - { - return; - } - - if (message.RemoteEndPoint.Port == 0) - { - return; - } - - try - { - OnMessageReceived(new GenericEventArgs - { - Argument = message - }); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error handling UDP message"); - } - } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// + /// public void Dispose() { - Dispose(true); - } - - /// - /// 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) - { - if (dispose) + if (_disposed) { - _isDisposed = true; - - if (_udpClient != null) - { - _udpClient.Dispose(); - } - } - } - - public async Task SendAsync(byte[] bytes, IPEndPoint remoteEndPoint, CancellationToken cancellationToken) - { - if (_isDisposed) - { - throw new ObjectDisposedException(GetType().Name); + return; } - if (bytes == null) - { - throw new ArgumentNullException(nameof(bytes)); - } + _udpSocket?.Dispose(); - if (remoteEndPoint == null) - { - throw new ArgumentNullException(nameof(remoteEndPoint)); - } - - try - { - await _udpClient.SendToAsync(bytes, 0, bytes.Length, remoteEndPoint, cancellationToken).ConfigureAwait(false); - - _logger.LogInformation("Udp message sent to {remoteEndPoint}", remoteEndPoint); - } - catch (OperationCanceledException) - { - - } - catch (Exception ex) - { - _logger.LogError(ex, "Error sending message to {remoteEndPoint}", remoteEndPoint); - } + GC.SuppressFinalize(this); } } - } diff --git a/MediaBrowser.Model/Net/ISocket.cs b/MediaBrowser.Model/Net/ISocket.cs index f80de5524c..3fdc40bbe2 100644 --- a/MediaBrowser.Model/Net/ISocket.cs +++ b/MediaBrowser.Model/Net/ISocket.cs @@ -14,8 +14,6 @@ namespace MediaBrowser.Model.Net Task ReceiveAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken); - int Receive(byte[] buffer, int offset, int count); - IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback); SocketReceiveResult EndReceive(IAsyncResult result); diff --git a/MediaBrowser.Model/Net/ISocketFactory.cs b/MediaBrowser.Model/Net/ISocketFactory.cs index 2f857f1af0..dc69b1fb25 100644 --- a/MediaBrowser.Model/Net/ISocketFactory.cs +++ b/MediaBrowser.Model/Net/ISocketFactory.cs @@ -8,13 +8,6 @@ namespace MediaBrowser.Model.Net /// public interface ISocketFactory { - /// - /// Creates a new unicast socket using the specified local port number. - /// - /// The local port to bind to. - /// A implementation. - ISocket CreateUdpSocket(int localPort); - ISocket CreateUdpBroadcastSocket(int localPort); /// @@ -30,7 +23,5 @@ namespace MediaBrowser.Model.Net /// The local port to bind to. /// A implementation. ISocket CreateUdpMulticastSocket(string ipAddress, int multicastTimeToLive, int localPort); - - Stream CreateNetworkStream(ISocket socket, bool ownsSocket); } } From da5893b0f14c6d1efec77e105a6240b241a1c412 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 12 Jan 2020 21:21:20 +0100 Subject: [PATCH 042/881] Try to fix nullreff --- MediaBrowser.Api/Playback/MediaInfoService.cs | 38 +++++++++---------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 4b9bb80103..4fa0e31406 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -266,8 +266,7 @@ namespace MediaBrowser.Api.Playback private T Clone(T obj) { - // Since we're going to be setting properties on MediaSourceInfos that come out of _mediaSourceManager, we should clone it - // Should we move this directly into MediaSourceManager? + var json = JsonSerializer.SerializeToUtf8Bytes(obj); return JsonSerializer.Deserialize(json); } @@ -278,27 +277,20 @@ namespace MediaBrowser.Api.Playback var item = _libraryManager.GetItemById(id); var result = new PlaybackInfoResponse(); + MediaSourceInfo[] mediaSources; if (string.IsNullOrWhiteSpace(liveStreamId)) { - IEnumerable mediaSources; - try - { - // TODO handle supportedLiveMediaTypes ? - mediaSources = await _mediaSourceManager.GetPlaybackMediaSources(item, user, true, false, CancellationToken.None).ConfigureAwait(false); - } - catch (Exception ex) - { - mediaSources = new List(); - Logger.LogError(ex, "Could not find media sources for item id {id}", id); - // TODO PlaybackException ?? - //result.ErrorCode = ex.ErrorCode; - } - result.MediaSources = mediaSources.ToArray(); + // TODO handle supportedLiveMediaTypes ? + var mediaSourcesList = await _mediaSourceManager.GetPlaybackMediaSources(item, user, true, false, CancellationToken.None).ConfigureAwait(false); - if (!string.IsNullOrWhiteSpace(mediaSourceId)) + if (string.IsNullOrWhiteSpace(mediaSourceId)) { - result.MediaSources = result.MediaSources + mediaSources = mediaSourcesList.ToArray(); + } + else + { + mediaSources = mediaSourcesList .Where(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase)) .ToArray(); } @@ -307,11 +299,13 @@ namespace MediaBrowser.Api.Playback { var mediaSource = await _mediaSourceManager.GetLiveStream(liveStreamId, CancellationToken.None).ConfigureAwait(false); - result.MediaSources = new MediaSourceInfo[] { mediaSource }; + mediaSources = new MediaSourceInfo[] { mediaSource }; } - if (result.MediaSources.Count == 0) + if (mediaSources.Length == 0) { + result.MediaSources = Array.Empty(); + if (!result.ErrorCode.HasValue) { result.ErrorCode = PlaybackErrorCode.NoCompatibleStream; @@ -319,7 +313,9 @@ namespace MediaBrowser.Api.Playback } else { - result.MediaSources = Clone(result.MediaSources); + // Since we're going to be setting properties on MediaSourceInfos that come out of _mediaSourceManager, we should clone it + // Should we move this directly into MediaSourceManager? + result.MediaSources = JsonSerializer.Deserialize(JsonSerializer.SerializeToUtf8Bytes(mediaSources)); result.PlaySessionId = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture); } From 84d1b12530b4c53910b300b040fe5f316523427e Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 12 Jan 2020 21:55:04 +0100 Subject: [PATCH 043/881] Attempt #2 --- MediaBrowser.Api/Playback/MediaInfoService.cs | 7 ------- MediaBrowser.Model/Dto/MediaSourceInfo.cs | 1 + 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 4fa0e31406..53823943f3 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -264,13 +264,6 @@ namespace MediaBrowser.Api.Playback return ToOptimizedResult(result); } - private T Clone(T obj) - { - - var json = JsonSerializer.SerializeToUtf8Bytes(obj); - return JsonSerializer.Deserialize(json); - } - private async Task GetPlaybackInfo(Guid id, Guid userId, string[] supportedLiveMediaTypes, string mediaSourceId = null, string liveStreamId = null) { var user = _userManager.GetUserById(userId); diff --git a/MediaBrowser.Model/Dto/MediaSourceInfo.cs b/MediaBrowser.Model/Dto/MediaSourceInfo.cs index 5cb0565666..16a212a81b 100644 --- a/MediaBrowser.Model/Dto/MediaSourceInfo.cs +++ b/MediaBrowser.Model/Dto/MediaSourceInfo.cs @@ -76,6 +76,7 @@ namespace MediaBrowser.Model.Dto { Formats = Array.Empty(); MediaStreams = new List(); + MediaAttachments = Array.Empty(); RequiredHttpHeaders = new Dictionary(); SupportsTranscoding = true; SupportsDirectStream = true; From 93ab829df523c36a44ffa2f9caaf96505a2b2e5c Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 12 Jan 2020 23:25:57 +0100 Subject: [PATCH 044/881] Attempt #3 --- MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs b/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs index 7fa7afa5b3..0b2f1d231e 100644 --- a/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs +++ b/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs @@ -225,7 +225,7 @@ namespace MediaBrowser.MediaEncoding.Probing /// /// The start_pts. [JsonPropertyName("start_pts")] - public int StartPts { get; set; } + public long StartPts { get; set; } /// /// Gets or sets the is_avc. From 56f580cdf6eb1a84275a582c4dc7dfb8245cc347 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 12 Jan 2020 23:57:13 +0100 Subject: [PATCH 045/881] Add test to prevent regressions --- .../EncoderValidatorTestsData.cs | 6 +- .../FFprobeParserTests.cs | 22 ++++ .../Jellyfin.MediaEncoding.Tests.csproj | 6 + .../Test Data/ffprobe1.json | 105 ++++++++++++++++++ 4 files changed, 136 insertions(+), 3 deletions(-) create mode 100644 tests/Jellyfin.MediaEncoding.Tests/FFprobeParserTests.cs create mode 100644 tests/Jellyfin.MediaEncoding.Tests/Test Data/ffprobe1.json diff --git a/tests/Jellyfin.MediaEncoding.Tests/EncoderValidatorTestsData.cs b/tests/Jellyfin.MediaEncoding.Tests/EncoderValidatorTestsData.cs index 12fde07705..c46c9578b9 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/EncoderValidatorTestsData.cs +++ b/tests/Jellyfin.MediaEncoding.Tests/EncoderValidatorTestsData.cs @@ -26,7 +26,7 @@ libswscale 5. 5.100 / 5. 5.100 libswresample 3. 5.100 / 3. 5.100 libpostproc 55. 5.100 / 55. 5.100"; - public const string FFmpegV414Output = @"ffmpeg version 4.1.4-1~deb10u1 Copyright (c) 2000-2019 the FFmpeg developers + public const string FFmpegV414Output = @"ffmpeg version 4.1.4-1~deb10u1 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 8 (Raspbian 8.3.0-6+rpi1) configuration: --prefix=/usr --extra-version='1~deb10u1' --toolchain=hardened --libdir=/usr/lib/arm-linux-gnueabihf --incdir=/usr/include/arm-linux-gnueabihf --arch=arm --enable-gpl --disable-stripping --enable-avresample --disable-filter=resample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libcodec2 --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libjack --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librsvg --enable-librubberband --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-lv2 --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libx264 --enable-shared libavutil 56. 22.100 / 56. 22.100 @@ -39,7 +39,7 @@ libswscale 5. 3.100 / 5. 3.100 libswresample 3. 3.100 / 3. 3.100 libpostproc 55. 3.100 / 55. 3.100"; - public const string FFmpegV404Output = @"ffmpeg version 4.0.4 Copyright (c) 2000-2019 the FFmpeg developers + public const string FFmpegV404Output = @"ffmpeg version 4.0.4 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 8 (Debian 8.3.0-6) configuration: --toolchain=hardened --prefix=/usr --target-os=linux --enable-cross-compile --extra-cflags=--static --enable-gpl --enable-static --disable-doc --disable-ffplay --disable-shared --disable-libxcb --disable-sdl2 --disable-xlib --enable-libfontconfig --enable-fontconfig --enable-gmp --enable-gnutls --enable-libass --enable-libbluray --enable-libdrm --enable-libfreetype --enable-libfribidi --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvorbis --enable-libwebp --enable-libx264 --enable-libx265 --enable-libzvbi --enable-omx --enable-omx-rpi --enable-version3 --enable-vaapi --enable-vdpau --arch=amd64 --enable-nvenc --enable-nvdec libavutil 56. 14.100 / 56. 14.100 @@ -51,7 +51,7 @@ libswscale 5. 1.100 / 5. 1.100 libswresample 3. 1.100 / 3. 1.100 libpostproc 55. 1.100 / 55. 1.100"; - public const string FFmpegGitUnknownOutput = @"ffmpeg version N-94303-g7cb4f8c962 Copyright (c) 2000-2019 the FFmpeg developers + public const string FFmpegGitUnknownOutput = @"ffmpeg version N-94303-g7cb4f8c962 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 9.1.1 (GCC) 20190716 configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt libavutil 56. 30.100 / 56. 30.100 diff --git a/tests/Jellyfin.MediaEncoding.Tests/FFprobeParserTests.cs b/tests/Jellyfin.MediaEncoding.Tests/FFprobeParserTests.cs new file mode 100644 index 0000000000..2032f6cecd --- /dev/null +++ b/tests/Jellyfin.MediaEncoding.Tests/FFprobeParserTests.cs @@ -0,0 +1,22 @@ +using System.IO; +using System.Text.Json; +using System.Threading.Tasks; +using MediaBrowser.MediaEncoding.Probing; +using Xunit; + +namespace Jellyfin.MediaEncoding.Tests +{ + public class FFprobeParserTests + { + [Theory] + [InlineData("ffprobe1.json")] + public async Task Test(string fileName) + { + var path = Path.Join("Test Data", fileName); + using (var stream = File.OpenRead(path)) + { + await JsonSerializer.DeserializeAsync(stream).ConfigureAwait(false); + } + } + } +} diff --git a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj index 7f6b905332..5d9b32086c 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj +++ b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj @@ -5,6 +5,12 @@ false + + + PreserveNewest + + + diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/ffprobe1.json b/tests/Jellyfin.MediaEncoding.Tests/Test Data/ffprobe1.json new file mode 100644 index 0000000000..cdad5df502 --- /dev/null +++ b/tests/Jellyfin.MediaEncoding.Tests/Test Data/ffprobe1.json @@ -0,0 +1,105 @@ +{ + "streams": [ + { + "index": 0, + "codec_name": "h264", + "codec_long_name": "H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10", + "profile": "Main", + "codec_type": "video", + "codec_time_base": "1/50", + "codec_tag_string": "[27][0][0][0]", + "codec_tag": "0x001b", + "width": 1920, + "height": 1080, + "coded_width": 1920, + "coded_height": 1080, + "has_b_frames": 0, + "sample_aspect_ratio": "0:1", + "display_aspect_ratio": "0:1", + "pix_fmt": "yuvj420p", + "level": 42, + "color_range": "pc", + "color_space": "bt709", + "color_transfer": "bt709", + "color_primaries": "bt709", + "chroma_location": "left", + "field_order": "progressive", + "refs": 1, + "is_avc": "false", + "nal_length_size": "0", + "id": "0x1", + "r_frame_rate": "25/1", + "avg_frame_rate": "25/1", + "time_base": "1/90000", + "start_pts": 8570867078, + "start_time": "95231.856422", + "duration_ts": 31694552, + "duration": "352.161689", + "bits_per_raw_sample": "8", + "disposition": { + "default": 0, + "dub": 0, + "original": 0, + "comment": 0, + "lyrics": 0, + "karaoke": 0, + "forced": 0, + "hearing_impaired": 0, + "visual_impaired": 0, + "clean_effects": 0, + "attached_pic": 0, + "timed_thumbnails": 0 + } + }, + { + "index": 1, + "codec_name": "aac", + "codec_long_name": "AAC (Advanced Audio Coding)", + "profile": "LC", + "codec_type": "audio", + "codec_time_base": "1/44100", + "codec_tag_string": "[15][0][0][0]", + "codec_tag": "0x000f", + "sample_fmt": "fltp", + "sample_rate": "44100", + "channels": 2, + "channel_layout": "stereo", + "bits_per_sample": 0, + "id": "0x2", + "r_frame_rate": "0/0", + "avg_frame_rate": "0/0", + "time_base": "1/90000", + "start_pts": 8570867697, + "start_time": "95231.863300", + "duration_ts": 31695687, + "duration": "352.174300", + "bit_rate": "98191", + "disposition": { + "default": 0, + "dub": 0, + "original": 0, + "comment": 0, + "lyrics": 0, + "karaoke": 0, + "forced": 0, + "hearing_impaired": 0, + "visual_impaired": 0, + "clean_effects": 0, + "attached_pic": 0, + "timed_thumbnails": 0 + } + } + ], + "format": { + "filename": "TS Test record.ts", + "nb_streams": 2, + "nb_programs": 1, + "format_name": "mpegts", + "format_long_name": "MPEG-TS (MPEG-2 Transport Stream)", + "start_time": "95231.856422", + "duration": "352.181178", + "size": "179003772", + "bit_rate": "4066174", + "probe_score": 50 + } +} From a8cd963d468ba4fb4caa003d9eb927117a3afa77 Mon Sep 17 00:00:00 2001 From: dkanada Date: Mon, 13 Jan 2020 15:25:54 +0900 Subject: [PATCH 046/881] fix tests for absolute paths --- .ci/azure-pipelines.yml | 2 +- .../IO/ManagedFileSystem.cs | 35 +++++++++---------- 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml index 7bcaed70cd..d69cc4943e 100644 --- a/.ci/azure-pipelines.yml +++ b/.ci/azure-pipelines.yml @@ -112,7 +112,7 @@ jobs: - job: main_test displayName: Main Test pool: - vmImage: windows-latest + vmImage: ubuntu-latest steps: - checkout: self clean: true diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index e27081c45a..bf2173d79b 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -3,8 +3,8 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -17,7 +17,7 @@ using OperatingSystem = MediaBrowser.Common.System.OperatingSystem; namespace Emby.Server.Implementations.IO { /// - /// Class ManagedFileSystem + /// Class ManagedFileSystem. /// public class ManagedFileSystem : IFileSystem { @@ -80,20 +80,20 @@ namespace Emby.Server.Implementations.IO public virtual string MakeAbsolutePath(string folderPath, string filePath) { - if (string.IsNullOrWhiteSpace(filePath) - // stream - || filePath.Contains("://")) + // path is actually a stream + if (string.IsNullOrWhiteSpace(filePath) || filePath.Contains("://", StringComparison.InvariantCulture)) { return filePath; } if (filePath.Length > 3 && filePath[1] == ':' && filePath[2] == '/') { - return filePath; // absolute local path + // absolute local path + return filePath; } // unc path - if (filePath.StartsWith("\\\\")) + if (filePath.StartsWith("\\\\", StringComparison.InvariantCulture)) { return filePath; } @@ -101,13 +101,16 @@ namespace Emby.Server.Implementations.IO var firstChar = filePath[0]; if (firstChar == '/') { - // For this we don't really know. + // for this we don't really know return filePath; } - if (firstChar == '\\') //relative path + + // relative path + if (firstChar == '\\') { filePath = filePath.Substring(1); } + try { return Path.GetFullPath(Path.Combine(folderPath, filePath)); @@ -131,11 +134,7 @@ namespace Emby.Server.Implementations.IO /// /// The shortcut path. /// The target. - /// - /// shortcutPath - /// or - /// target - /// + /// The shortcutPath or target is null. public virtual void CreateShortcut(string shortcutPath, string target) { if (string.IsNullOrEmpty(shortcutPath)) @@ -281,11 +280,11 @@ namespace Emby.Server.Implementations.IO } /// - /// Takes a filename and removes invalid characters + /// Takes a filename and removes invalid characters. /// /// The filename. /// System.String. - /// filename + /// The filename is null. public virtual string GetValidFilename(string filename) { var builder = new StringBuilder(filename); @@ -473,7 +472,7 @@ namespace Emby.Server.Implementations.IO public virtual void SetReadOnly(string path, bool isReadOnly) { - if (OperatingSystem.Id != MediaBrowser.Model.System.OperatingSystemId.Windows) + if (OperatingSystem.Id != OperatingSystemId.Windows) { return; } @@ -497,7 +496,7 @@ namespace Emby.Server.Implementations.IO public virtual void SetAttributes(string path, bool isHidden, bool isReadOnly) { - if (OperatingSystem.Id != MediaBrowser.Model.System.OperatingSystemId.Windows) + if (OperatingSystem.Id != OperatingSystemId.Windows) { return; } From 65e9a705d303ebfadbc58035f9763966141ee437 Mon Sep 17 00:00:00 2001 From: dkanada Date: Mon, 13 Jan 2020 15:34:50 +0900 Subject: [PATCH 047/881] check operating system for absolute path test --- .ci/azure-pipelines.yml | 2 +- Emby.Server.Implementations/IO/ManagedFileSystem.cs | 4 ++-- .../IO/ManagedFileSystemTests.cs | 13 ++++++++++++- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml index d69cc4943e..7bcaed70cd 100644 --- a/.ci/azure-pipelines.yml +++ b/.ci/azure-pipelines.yml @@ -112,7 +112,7 @@ jobs: - job: main_test displayName: Main Test pool: - vmImage: ubuntu-latest + vmImage: windows-latest steps: - checkout: self clean: true diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index bf2173d79b..1fd8ddc4d4 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -448,7 +448,7 @@ namespace Emby.Server.Implementations.IO public virtual void SetHidden(string path, bool isHidden) { - if (OperatingSystem.Id != MediaBrowser.Model.System.OperatingSystemId.Windows) + if (OperatingSystem.Id != OperatingSystemId.Windows) { return; } @@ -779,7 +779,7 @@ namespace Emby.Server.Implementations.IO public virtual void SetExecutable(string path) { - if (OperatingSystem.Id == MediaBrowser.Model.System.OperatingSystemId.Darwin) + if (OperatingSystem.Id == OperatingSystemId.Darwin) { RunProcess("chmod", "+x \"" + path + "\"", Path.GetDirectoryName(path)); } diff --git a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs index f2a8e447fa..b2aa01e655 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs @@ -1,6 +1,8 @@ +using System; using AutoFixture; using AutoFixture.AutoMoq; using Emby.Server.Implementations.IO; +using MediaBrowser.Model.System; using Xunit; namespace Jellyfin.Server.Implementations.Tests.IO @@ -26,7 +28,16 @@ namespace Jellyfin.Server.Implementations.Tests.IO string expectedAbsolutePath) { var generatedPath = _sut.MakeAbsolutePath(folderPath, filePath); - Assert.Equal(expectedAbsolutePath, generatedPath); + + if (MediaBrowser.Common.System.OperatingSystem.Id == OperatingSystemId.Windows) + { + var windowsPath = "d:" + generatedPath.Replace('/', '\\'); + Assert.Equal(expectedAbsolutePath, windowsPath); + } + else + { + Assert.Equal(expectedAbsolutePath, generatedPath); + } } } } From d00fd7ca82d33e90c87a5a6c02a1eb8505babfcf Mon Sep 17 00:00:00 2001 From: dkanada Date: Mon, 13 Jan 2020 15:43:06 +0900 Subject: [PATCH 048/881] switch two incorrectly used variables --- .../IO/ManagedFileSystemTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs index b2aa01e655..182c709982 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs @@ -31,8 +31,8 @@ namespace Jellyfin.Server.Implementations.Tests.IO if (MediaBrowser.Common.System.OperatingSystem.Id == OperatingSystemId.Windows) { - var windowsPath = "d:" + generatedPath.Replace('/', '\\'); - Assert.Equal(expectedAbsolutePath, windowsPath); + var expectedWindowsPath = "d:" + expectedAbsolutePath.Replace('/', '\\'); + Assert.Equal(expectedWindowsPath, generatedPath); } else { From 665ca5cf1fcd6c757f214998d121e3f6a50fb8f3 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Mon, 13 Jan 2020 09:00:30 +0100 Subject: [PATCH 049/881] Update UdpServer.cs --- Emby.Server.Implementations/Udp/UdpServer.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs index 19fc1e316d..c91d137a72 100644 --- a/Emby.Server.Implementations/Udp/UdpServer.cs +++ b/Emby.Server.Implementations/Udp/UdpServer.cs @@ -22,9 +22,6 @@ namespace Emby.Server.Implementations.Udp private readonly ILogger _logger; private readonly IServerApplicationHost _appHost; - /// - /// The _udp client. - /// private Socket _udpSocket; private IPEndPoint _endpoint; private readonly byte[] _receiveBuffer = new byte[8192]; From cf13e89ad6d086cc20acd877a76df23900b222a9 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Mon, 13 Jan 2020 09:01:14 +0100 Subject: [PATCH 050/881] Update MediaBrowser.Api/Playback/MediaInfoService.cs Co-Authored-By: dkanada --- MediaBrowser.Api/Playback/MediaInfoService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 53823943f3..10f10a15ec 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -274,7 +274,7 @@ namespace MediaBrowser.Api.Playback if (string.IsNullOrWhiteSpace(liveStreamId)) { - // TODO handle supportedLiveMediaTypes ? + // TODO handle supportedLiveMediaTypes? var mediaSourcesList = await _mediaSourceManager.GetPlaybackMediaSources(item, user, true, false, CancellationToken.None).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(mediaSourceId)) From 9eac19c75ad9c69c0c30ae90c0772856e7b0ce9e Mon Sep 17 00:00:00 2001 From: dkanada Date: Mon, 13 Jan 2020 17:09:22 +0900 Subject: [PATCH 051/881] change invariant culture to ordinal --- Emby.Server.Implementations/IO/ManagedFileSystem.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 1fd8ddc4d4..68417876cf 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -81,7 +81,7 @@ namespace Emby.Server.Implementations.IO public virtual string MakeAbsolutePath(string folderPath, string filePath) { // path is actually a stream - if (string.IsNullOrWhiteSpace(filePath) || filePath.Contains("://", StringComparison.InvariantCulture)) + if (string.IsNullOrWhiteSpace(filePath) || filePath.Contains("://", StringComparison.Ordinal)) { return filePath; } @@ -93,7 +93,7 @@ namespace Emby.Server.Implementations.IO } // unc path - if (filePath.StartsWith("\\\\", StringComparison.InvariantCulture)) + if (filePath.StartsWith("\\\\", StringComparison.Ordinal)) { return filePath; } From d461f46befb06dae742ab523a3b28dadbff853f3 Mon Sep 17 00:00:00 2001 From: dkanada Date: Mon, 13 Jan 2020 17:31:14 +0900 Subject: [PATCH 052/881] ignore drive name in windows environments --- .../IO/ManagedFileSystemTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs index 182c709982..de227cd859 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs @@ -31,7 +31,7 @@ namespace Jellyfin.Server.Implementations.Tests.IO if (MediaBrowser.Common.System.OperatingSystem.Id == OperatingSystemId.Windows) { - var expectedWindowsPath = "d:" + expectedAbsolutePath.Replace('/', '\\'); + var expectedWindowsPath = expectedAbsolutePath.Replace('/', '\\').Split(':')[1]; Assert.Equal(expectedWindowsPath, generatedPath); } else From 536237c35dc74205e25593667add97695a27f0f2 Mon Sep 17 00:00:00 2001 From: dkanada Date: Mon, 13 Jan 2020 17:37:07 +0900 Subject: [PATCH 053/881] move the split usage to the proper location --- .../IO/ManagedFileSystemTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs index de227cd859..e324002f0c 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs @@ -31,8 +31,8 @@ namespace Jellyfin.Server.Implementations.Tests.IO if (MediaBrowser.Common.System.OperatingSystem.Id == OperatingSystemId.Windows) { - var expectedWindowsPath = expectedAbsolutePath.Replace('/', '\\').Split(':')[1]; - Assert.Equal(expectedWindowsPath, generatedPath); + var expectedWindowsPath = expectedAbsolutePath.Replace('/', '\\'); + Assert.Equal(expectedWindowsPath, generatedPath.Split(':')[1]); } else { From 9c2c31b0c63b12ff303790f1294eeccb6adea252 Mon Sep 17 00:00:00 2001 From: punkch Date: Fri, 10 Jan 2020 23:42:06 +0000 Subject: [PATCH 054/881] Translated using Weblate (Bulgarian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/bg/ --- Emby.Server.Implementations/Localization/Core/bg-BG.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/bg-BG.json b/Emby.Server.Implementations/Localization/Core/bg-BG.json index 46c10d912e..9441da5915 100644 --- a/Emby.Server.Implementations/Localization/Core/bg-BG.json +++ b/Emby.Server.Implementations/Localization/Core/bg-BG.json @@ -16,7 +16,7 @@ "Folders": "Папки", "Genres": "Жанрове", "HeaderAlbumArtists": "Изпълнители на албуми", - "HeaderCameraUploads": "", + "HeaderCameraUploads": "Качени от камера", "HeaderContinueWatching": "Продължаване на гледането", "HeaderFavoriteAlbums": "Любими албуми", "HeaderFavoriteArtists": "Любими изпълнители", @@ -25,7 +25,7 @@ "HeaderFavoriteSongs": "Любими песни", "HeaderLiveTV": "Телевизия на живо", "HeaderNextUp": "Следва", - "HeaderRecordingGroups": "", + "HeaderRecordingGroups": "Запис групи", "HomeVideos": "Домашни клипове", "Inherit": "Наследяване", "ItemAddedWithName": "{0} е добавено към библиотеката", @@ -34,7 +34,7 @@ "LabelRunningTimeValue": "", "Latest": "Последни", "MessageApplicationUpdated": "Сървърът е обновен", - "MessageApplicationUpdatedTo": "", + "MessageApplicationUpdatedTo": "Сървърът е обновен до {0}", "MessageNamedServerConfigurationUpdatedWithValue": "", "MessageServerConfigurationUpdated": "", "MixedContent": "Смесено съдържание", From 31347de792cec994ac9796628e161eaac4bbaf4a Mon Sep 17 00:00:00 2001 From: Philmo67 Date: Fri, 10 Jan 2020 15:17:30 +0000 Subject: [PATCH 055/881] Translated using Weblate (French) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fr/ --- Emby.Server.Implementations/Localization/Core/fr.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/fr.json b/Emby.Server.Implementations/Localization/Core/fr.json index 6b25e3df0f..ff70733359 100644 --- a/Emby.Server.Implementations/Localization/Core/fr.json +++ b/Emby.Server.Implementations/Localization/Core/fr.json @@ -11,11 +11,11 @@ "Collections": "Collections", "DeviceOfflineWithName": "{0} s'est déconnecté", "DeviceOnlineWithName": "{0} est connecté", - "FailedLoginAttemptWithUserName": "Échec d'une tentative de connexion de {0}", + "FailedLoginAttemptWithUserName": "Échec de connexion de {0}", "Favorites": "Favoris", "Folders": "Dossiers", "Genres": "Genres", - "HeaderAlbumArtists": "Artistes de l'album", + "HeaderAlbumArtists": "Artistes d'album", "HeaderCameraUploads": "Photos transférées", "HeaderContinueWatching": "Continuer à regarder", "HeaderFavoriteAlbums": "Albums favoris", From faf898ea0d8fc5d0dcd6d98a0d4cfc95d4126a6d Mon Sep 17 00:00:00 2001 From: hbo Date: Fri, 10 Jan 2020 15:18:30 +0000 Subject: [PATCH 056/881] Translated using Weblate (French) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fr/ --- Emby.Server.Implementations/Localization/Core/fr.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/fr.json b/Emby.Server.Implementations/Localization/Core/fr.json index ff70733359..90754e4155 100644 --- a/Emby.Server.Implementations/Localization/Core/fr.json +++ b/Emby.Server.Implementations/Localization/Core/fr.json @@ -34,7 +34,7 @@ "LabelRunningTimeValue": "Durée : {0}", "Latest": "Derniers", "MessageApplicationUpdated": "Le serveur Jellyfin a été mis à jour", - "MessageApplicationUpdatedTo": "Le serveur Jellyfin a été mis à jour vers {0}", + "MessageApplicationUpdatedTo": "Le serveur Jellyfin a été mis à jour en version {0}", "MessageNamedServerConfigurationUpdatedWithValue": "La configuration de la section {0} du serveur a été mise à jour", "MessageServerConfigurationUpdated": "La configuration du serveur a été mise à jour", "MixedContent": "Contenu mixte", From 7b91df199401e299463264b3b6bbae729bf51499 Mon Sep 17 00:00:00 2001 From: Alexander Brissman Date: Fri, 10 Jan 2020 21:46:39 +0000 Subject: [PATCH 057/881] =?UTF-8?q?Translated=20using=20Weblate=20(Norwegi?= =?UTF-8?q?an=20Bokm=C3=A5l)=20Translation:=20Jellyfin/Jellyfin=20Translat?= =?UTF-8?q?e-URL:=20https://translate.jellyfin.org/projects/jellyfin/jelly?= =?UTF-8?q?fin-core/nb=5FNO/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Emby.Server.Implementations/Localization/Core/nb.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/nb.json b/Emby.Server.Implementations/Localization/Core/nb.json index 7d4b2bdac1..f9fa1b68cd 100644 --- a/Emby.Server.Implementations/Localization/Core/nb.json +++ b/Emby.Server.Implementations/Localization/Core/nb.json @@ -62,7 +62,7 @@ "NotificationOptionVideoPlayback": "Videoavspilling startet", "NotificationOptionVideoPlaybackStopped": "Videoavspilling stoppet", "Photos": "Bilder", - "Playlists": "Spliielister", + "Playlists": "Spillelister", "Plugin": "Plugin", "PluginInstalledWithName": "{0} ble installert", "PluginUninstalledWithName": "{0} ble avinstallert", From ab0130e9e288c92d8e11abc8067c69c6bb13e468 Mon Sep 17 00:00:00 2001 From: Z Yang Date: Sat, 11 Jan 2020 13:18:35 +0000 Subject: [PATCH 058/881] Translated using Weblate (Chinese (Simplified)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/zh_Hans/ --- Emby.Server.Implementations/Localization/Core/zh-CN.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/zh-CN.json b/Emby.Server.Implementations/Localization/Core/zh-CN.json index a4d53c57e9..a567e6e2d3 100644 --- a/Emby.Server.Implementations/Localization/Core/zh-CN.json +++ b/Emby.Server.Implementations/Localization/Core/zh-CN.json @@ -3,9 +3,9 @@ "AppDeviceValues": "应用: {0}, 设备: {1}", "Application": "应用程序", "Artists": "艺术家", - "AuthenticationSucceededWithUserName": "{0} 认证成功", + "AuthenticationSucceededWithUserName": "{0} 验证成功", "Books": "书籍", - "CameraImageUploadedFrom": "已从 {0} 上传了一张新的相片", + "CameraImageUploadedFrom": "新的相机图像已从 {0} 上传", "Channels": "频道", "ChapterNameValue": "章节 {0}", "Collections": "合集", @@ -18,7 +18,7 @@ "HeaderAlbumArtists": "专辑作家", "HeaderCameraUploads": "相机上传", "HeaderContinueWatching": "继续观看", - "HeaderFavoriteAlbums": "最爱的专辑", + "HeaderFavoriteAlbums": "收藏的专辑", "HeaderFavoriteArtists": "最爱的艺术家", "HeaderFavoriteEpisodes": "最爱的剧集", "HeaderFavoriteShows": "最爱的节目", From 138bff43270279f46358c39cc03666fb3ee331b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Slobodan=20Simi=C4=87?= Date: Fri, 10 Jan 2020 20:27:47 +0000 Subject: [PATCH 059/881] Translated using Weblate (Serbian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sr/ --- .../Localization/Core/sr.json | 97 ++++++++++++++++++- 1 file changed, 96 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/sr.json b/Emby.Server.Implementations/Localization/Core/sr.json index 0967ef424b..da0088991b 100644 --- a/Emby.Server.Implementations/Localization/Core/sr.json +++ b/Emby.Server.Implementations/Localization/Core/sr.json @@ -1 +1,96 @@ -{} +{ + "UserPolicyUpdatedWithName": "Корисничке смернице ажуриране за {0}", + "NotificationOptionUserLockedOut": "Корисник закључан", + "VersionNumber": "Верзија {0}", + "ValueSpecialEpisodeName": "Специјал - {0}", + "ValueHasBeenAddedToLibrary": "{0} је додато у вашу медијску библиотеку", + "UserStoppedPlayingItemWithValues": "{0} заврши пуштање {1} на {2}", + "UserStartedPlayingItemWithValues": "{0} пушта {1} на {2}", + "UserPasswordChangedWithName": "Лозинка је промењена за корисника {0}", + "UserOnlineFromDevice": "{0} је на вези од {1}", + "UserOfflineFromDevice": "{0} се одвезао са {1}", + "UserLockedOutWithName": "Корисник {0} је закључан", + "UserDownloadingItemWithValues": "{0} преузима {1}", + "UserDeletedWithName": "Корисник {0} је обрисан", + "UserCreatedWithName": "Корисник {0} је направљен", + "User": "Корисник", + "TvShows": "ТВ серије", + "System": "Систем", + "Sync": "Усклади", + "SubtitlesDownloadedForItem": "Титлови преузети за {0}", + "SubtitleDownloadFailureFromForItem": "Неуспело преузимање титлова за {1} са {0}", + "StartupEmbyServerIsLoading": "Џелифин сервер се подиже. Покушајте поново убрзо.", + "Songs": "Песме", + "Shows": "Серије", + "ServerNameNeedsToBeRestarted": "{0} треба поново покренути", + "ScheduledTaskStartedWithName": "{0} покренуто", + "ScheduledTaskFailedWithName": "{0} неуспело", + "ProviderValue": "Пружалац: {0}", + "PluginUpdatedWithName": "{0} ажуриран", + "PluginUninstalledWithName": "{0} деинсталиран", + "PluginInstalledWithName": "{0} инсталиран", + "Plugin": "Прикључак", + "Playlists": "Листе", + "Photos": "Фотографије", + "NotificationOptionVideoPlaybackStopped": "Заустављено пуштање видеа", + "NotificationOptionVideoPlayback": "Покренуто пуштање видеа", + "NotificationOptionTaskFailed": "Неуспешан заказани посао", + "NotificationOptionServerRestartRequired": "Потребан је рестарт сервера", + "NotificationOptionPluginUpdateInstalled": "Ажурирање прикључка инсталирано", + "NotificationOptionPluginUninstalled": "Прикључак уклоњен", + "NotificationOptionPluginInstalled": "Прикључак инсталиран", + "NotificationOptionPluginError": "Грешка прикључка", + "NotificationOptionNewLibraryContent": "Додат нови садржај", + "NotificationOptionInstallationFailed": "Неуспела инсталација", + "NotificationOptionCameraImageUploaded": "Слика са камере послата", + "NotificationOptionAudioPlaybackStopped": "Заустављено пуштање звука", + "NotificationOptionAudioPlayback": "Покренуто пуштање звука", + "NotificationOptionApplicationUpdateInstalled": "Ажурирање инсталирано", + "NotificationOptionApplicationUpdateAvailable": "Доступно је ажурирање за апликацију", + "NewVersionIsAvailable": "Нова верзија Џелифин сервера је доступна за преузимање.", + "NameSeasonUnknown": "Непозната сезона", + "NameSeasonNumber": "Сезона {0}", + "NameInstallFailed": "Инсталација {0} није успела", + "MusicVideos": "Музички спотови", + "Music": "Музика", + "Movies": "Филмови", + "MixedContent": "Мешовит садржај", + "MessageServerConfigurationUpdated": "Серверска поставка је ажурирана", + "MessageNamedServerConfigurationUpdatedWithValue": "Одељак серверске поставке {0} је ажуриран", + "MessageApplicationUpdatedTo": "Џелифин сервер је ажуриран на {0}", + "MessageApplicationUpdated": "Џелифин сервер је ажуриран", + "Latest": "Последње", + "LabelRunningTimeValue": "Време рада: {0}", + "LabelIpAddressValue": "ИП адреса: {0}", + "ItemRemovedWithName": "{0} уклоњено из библиотеке", + "ItemAddedWithName": "{0} додато у библиотеку", + "Inherit": "Наследи", + "HomeVideos": "Кућни видео", + "HeaderRecordingGroups": "Групе снимања", + "HeaderNextUp": "Следеће горе", + "HeaderLiveTV": "ТВ уживо", + "HeaderFavoriteSongs": "Омиљене песме", + "HeaderFavoriteShows": "Омиљене серије", + "HeaderFavoriteEpisodes": "Омиљене епизоде", + "HeaderFavoriteArtists": "Омиљени извођачи", + "HeaderFavoriteAlbums": "Омиљени албуми", + "HeaderContinueWatching": "Настави гледање", + "HeaderCameraUploads": "Слања са камере", + "HeaderAlbumArtists": "Извођачи албума", + "Genres": "Жанрови", + "Folders": "Фасцикле", + "Favorites": "Омиљено", + "FailedLoginAttemptWithUserName": "Неуспела пријава са {0}", + "DeviceOnlineWithName": "{0} се повезао", + "DeviceOfflineWithName": "{0} се одвезао", + "Collections": "Колекције", + "ChapterNameValue": "Поглавље {0}", + "Channels": "Канали", + "CameraImageUploadedFrom": "Нова фотографија је послата са {0}", + "Books": "Књиге", + "AuthenticationSucceededWithUserName": "{0} успешно проверено", + "Artists": "Извођач", + "Application": "Апликација", + "AppDeviceValues": "Апл: {0}, уређај: {1}", + "Albums": "Албуми" +} From 65fe243afbcc4b596cf8726708c1965cd34b5f68 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Mon, 13 Jan 2020 19:44:17 +0100 Subject: [PATCH 060/881] Add thread ID and source to logging --- Jellyfin.Server/Jellyfin.Server.csproj | 1 + Jellyfin.Server/Program.cs | 6 ++++-- Jellyfin.Server/Resources/Configuration/logging.json | 7 ++++--- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index 166e22909d..62bf5b0fbd 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -42,6 +42,7 @@ + diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 712990a1ee..8f44327971 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -475,17 +475,19 @@ namespace Jellyfin.Server Serilog.Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .Enrich.FromLogContext() + .Enrich.WithThreadId() .CreateLogger(); } catch (Exception ex) { Serilog.Log.Logger = new LoggerConfiguration() - .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}") + .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {ThreadId} {SourceContext}: {Message:lj} {NewLine}{Exception}") .WriteTo.Async(x => x.File( Path.Combine(appPaths.LogDirectoryPath, "log_.log"), rollingInterval: RollingInterval.Day, - outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}")) + outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {ThreadId} {SourceContext}:{Message} {NewLine}{Exception}")) .Enrich.FromLogContext() + .Enrich.WithThreadId() .CreateLogger(); Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration"); diff --git a/Jellyfin.Server/Resources/Configuration/logging.json b/Jellyfin.Server/Resources/Configuration/logging.json index e85ef05afd..6bc2ed2ee4 100644 --- a/Jellyfin.Server/Resources/Configuration/logging.json +++ b/Jellyfin.Server/Resources/Configuration/logging.json @@ -5,7 +5,7 @@ { "Name": "Console", "Args": { - "outputTemplate": "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}" + "outputTemplate": "[{Timestamp:HH:mm:ss}] [{Level:u3}] {ThreadId} {SourceContext}: {Message:lj} {NewLine}{Exception}" } }, { @@ -20,12 +20,13 @@ "retainedFileCountLimit": 3, "rollOnFileSizeLimit": true, "fileSizeLimitBytes": 100000000, - "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}" + "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {ThreadId} {SourceContext}:{Message} {NewLine}{Exception}" } } ] } } - ] + ], + "Enrich": [ "FromLogContext", "WithThreadId" ] } } From 402691b5e1e1b753ba88fda64ffc877b96c78ecf Mon Sep 17 00:00:00 2001 From: Artiume Date: Mon, 13 Jan 2020 17:16:43 -0500 Subject: [PATCH 061/881] Explicitly ask for ffmpeg logs gimme yo ffmpeg logs, yo --- .github/ISSUE_TEMPLATE/media_playback.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/media_playback.md b/.github/ISSUE_TEMPLATE/media_playback.md index 93af33fbfd..5b3cb834e2 100644 --- a/.github/ISSUE_TEMPLATE/media_playback.md +++ b/.github/ISSUE_TEMPLATE/media_playback.md @@ -11,7 +11,10 @@ assignees: '' **Logs** - + + +**FFmpeg Logs** + **Stats for Nerds Screenshots** From cd5e5cda61fe1da1501bc0e5956684ac851eefd1 Mon Sep 17 00:00:00 2001 From: Artiume Date: Mon, 13 Jan 2020 21:25:21 -0500 Subject: [PATCH 062/881] Update .github/ISSUE_TEMPLATE/media_playback.md Co-Authored-By: dkanada --- .github/ISSUE_TEMPLATE/media_playback.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/media_playback.md b/.github/ISSUE_TEMPLATE/media_playback.md index 5b3cb834e2..b2bd717b04 100644 --- a/.github/ISSUE_TEMPLATE/media_playback.md +++ b/.github/ISSUE_TEMPLATE/media_playback.md @@ -11,7 +11,7 @@ assignees: '' **Logs** - + **FFmpeg Logs** @@ -32,4 +32,3 @@ assignees: '' - Client: [e.g. Web/Browser, webOS, Android, Android TV, Electron] - Browser (if Web client): [e.g. Firefox, Chrome, Safari] - Client and Browser Version: [e.g. 10.3.4 and 68.0] - From c1350f30d20029932c1e6734c7fb9e85c6a0b75a Mon Sep 17 00:00:00 2001 From: Artiume Date: Mon, 13 Jan 2020 21:25:41 -0500 Subject: [PATCH 063/881] Update .github/ISSUE_TEMPLATE/media_playback.md Co-Authored-By: dkanada --- .github/ISSUE_TEMPLATE/media_playback.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/media_playback.md b/.github/ISSUE_TEMPLATE/media_playback.md index b2bd717b04..97e3785910 100644 --- a/.github/ISSUE_TEMPLATE/media_playback.md +++ b/.github/ISSUE_TEMPLATE/media_playback.md @@ -14,7 +14,7 @@ assignees: '' **FFmpeg Logs** - + **Stats for Nerds Screenshots** From da91b4fa4c10e6d2579291895bc32cd3a41f7bbd Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Mon, 13 Jan 2020 16:22:52 +0100 Subject: [PATCH 064/881] Split CI testing files Switch to cobertura for code coverage Switch to dotnet test for tests Add matrix run for different platforms Add extra variables for easier maintenance --- .ci/azure-pipelines-compat.yml | 96 ++++++++++ .ci/azure-pipelines-main.yml | 101 ++++++++++ .ci/azure-pipelines-test.yml | 68 +++++++ .ci/azure-pipelines-windows.yml | 82 ++++++++ .ci/azure-pipelines.yml | 320 +++----------------------------- .ci/publish-nightly.yml | 46 ----- .ci/publish-release.yml | 48 ----- tests/coverletArgs.runsettings | 17 ++ 8 files changed, 386 insertions(+), 392 deletions(-) create mode 100644 .ci/azure-pipelines-compat.yml create mode 100644 .ci/azure-pipelines-main.yml create mode 100644 .ci/azure-pipelines-test.yml create mode 100644 .ci/azure-pipelines-windows.yml delete mode 100644 .ci/publish-nightly.yml delete mode 100644 .ci/publish-release.yml create mode 100644 tests/coverletArgs.runsettings diff --git a/.ci/azure-pipelines-compat.yml b/.ci/azure-pipelines-compat.yml new file mode 100644 index 0000000000..ac23e0b6db --- /dev/null +++ b/.ci/azure-pipelines-compat.yml @@ -0,0 +1,96 @@ +parameters: + - name: Packages + type: object + default: {} + - name: LinuxImage + type: string + default: "ubuntu-latest" + - name: DotNetSdkVersion + type: string + default: 3.1.100 + +jobs: + - job: CompatibilityCheck + displayName: Compatibility Check + pool: + vmImage: "${{ parameters.LinuxImage}}" + # only execute for pull requests + condition: and(succeeded(), variables['System.PullRequest.PullRequestNumber']) + strategy: + matrix: + ${{ each Package in parameters.Packages }}: + ${{ Package.key }}: + NugetPackageName: ${{ Package.value.NugetPackageName }} + AssemblyFileName: ${{ Package.value.AssemblyFileName }} + maxParallel: 2 + dependsOn: MainBuild + steps: + - checkout: none + + - task: UseDotNet@2 + displayName: "Update DotNet" + inputs: + packageType: sdk + version: ${{ parameters.DotNetSdkVersion }} + + - task: DownloadPipelineArtifact@2 + displayName: "Download New Assembly Build Artifact" + inputs: + source: "current" # Options: current, specific + artifact: "$(NugetPackageName)" # Optional + path: "$(System.ArtifactsDirectory)/new-artifacts" + runVersion: "latest" # Required when source == Specific. Options: latest, latestFromBranch, specific + + - task: CopyFiles@2 + displayName: "Copy New Assembly Build Artifact" + inputs: + sourceFolder: $(System.ArtifactsDirectory)/new-artifacts # Optional + contents: "**/*.dll" + targetFolder: $(System.ArtifactsDirectory)/new-release + cleanTargetFolder: true # Optional + overWrite: true # Optional + flattenFolders: true # Optional + + - task: DownloadPipelineArtifact@2 + displayName: "Download Reference Assembly Build Artifact" + inputs: + source: "specific" # Options: current, specific + artifact: "$(NugetPackageName)" # Optional + path: "$(System.ArtifactsDirectory)/current-artifacts" + project: "$(System.TeamProjectId)" # Required when source == Specific + pipeline: "$(System.DefinitionId)" # Required when source == Specific + runVersion: "latestFromBranch" # Required when source == Specific. Options: latest, latestFromBranch, specific + runBranch: "refs/heads/$(System.PullRequest.TargetBranch)" # Required when source == Specific && runVersion == LatestFromBranch + + - task: CopyFiles@2 + displayName: "Copy Reference Assembly Build Artifact" + inputs: + sourceFolder: $(System.ArtifactsDirectory)/current-artifacts # Optional + contents: "**/*.dll" + targetFolder: $(System.ArtifactsDirectory)/current-release + cleanTargetFolder: true # Optional + overWrite: true # Optional + flattenFolders: true # Optional + + - task: DownloadGitHubRelease@0 + displayName: "Download ABI Compatibility Check Tool" + inputs: + connection: Jellyfin Release Download + userRepository: EraYaN/dotnet-compatibility + defaultVersionType: "latest" # Options: latest, specificVersion, specificTag + itemPattern: "**-ci.zip" # Optional + downloadPath: "$(System.ArtifactsDirectory)" + + - task: ExtractFiles@1 + displayName: "Extract ABI Compatibility Check Tool" + inputs: + archiveFilePatterns: "$(System.ArtifactsDirectory)/*-ci.zip" + destinationFolder: $(System.ArtifactsDirectory)/tools + cleanDestinationFolder: true + + # The `--warnings-only` switch will swallow the return code and not emit any errors. + - task: CmdLine@2 + displayName: "Execute ABI Compatibility Check Tool" + inputs: + script: "dotnet tools/CompatibilityCheckerCLI.dll current-release/$(AssemblyFileName) new-release/$(AssemblyFileName) --azure-pipelines --warnings-only" + workingDirectory: $(System.ArtifactsDirectory) # Optional \ No newline at end of file diff --git a/.ci/azure-pipelines-main.yml b/.ci/azure-pipelines-main.yml new file mode 100644 index 0000000000..fd263e20f9 --- /dev/null +++ b/.ci/azure-pipelines-main.yml @@ -0,0 +1,101 @@ +parameters: + LinuxImage: "ubuntu-latest" + RestoreBuildProjects: "Jellyfin.Server/Jellyfin.Server.csproj" + DotNetSdkVersion: 3.1.100 + +jobs: + - job: MainBuild + displayName: Main Build + strategy: + matrix: + Release: + BuildConfiguration: Release + Debug: + BuildConfiguration: Debug + maxParallel: 2 + pool: + vmImage: "${{ parameters.LinuxImage }}" + steps: + - checkout: self + clean: true + submodules: true + persistCredentials: true + + - task: CmdLine@2 + displayName: "Clone Web Client (Master, Release, or Tag)" + condition: and(succeeded(), or(contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + inputs: + script: "git clone --single-branch --branch $(Build.SourceBranchName) --depth=1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web" + + - task: CmdLine@2 + displayName: "Clone Web Client (PR)" + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest')) + inputs: + script: "git clone --single-branch --branch $(System.PullRequest.TargetBranch) --depth 1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web" + + - task: NodeTool@0 + displayName: "Install Node" + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + inputs: + versionSpec: "10.x" + + - task: CmdLine@2 + displayName: "Build Web Client" + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + inputs: + script: yarn install + workingDirectory: $(Agent.TempDirectory)/jellyfin-web + + - task: CopyFiles@2 + displayName: "Copy Web Client" + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + inputs: + sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist # Optional + contents: "**" + targetFolder: $(Build.SourcesDirectory)/MediaBrowser.WebDashboard/jellyfin-web + cleanTargetFolder: true # Optional + overWrite: true # Optional + flattenFolders: false # Optional + + - task: UseDotNet@2 + displayName: "Update DotNet" + inputs: + packageType: sdk + version: ${{ parameters.DotNetSdkVersion }} + + - task: DotNetCoreCLI@2 + displayName: "Publish Server" + inputs: + command: publish + publishWebProjects: false + projects: "${{ parameters.RestoreBuildProjects }}" + arguments: "--configuration $(BuildConfiguration) --output $(build.artifactstagingdirectory)" + zipAfterPublish: false + + - task: PublishPipelineArtifact@0 + displayName: "Publish Artifact Naming" + condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) + inputs: + targetPath: "$(build.artifactstagingdirectory)/Jellyfin.Server/Emby.Naming.dll" + artifactName: "Jellyfin.Naming" + + - task: PublishPipelineArtifact@0 + displayName: "Publish Artifact Controller" + condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) + inputs: + targetPath: "$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Controller.dll" + artifactName: "Jellyfin.Controller" + + - task: PublishPipelineArtifact@0 + displayName: "Publish Artifact Model" + condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) + inputs: + targetPath: "$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Model.dll" + artifactName: "Jellyfin.Model" + + - task: PublishPipelineArtifact@0 + displayName: "Publish Artifact Common" + condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) + inputs: + targetPath: "$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Common.dll" + artifactName: "Jellyfin.Common" \ No newline at end of file diff --git a/.ci/azure-pipelines-test.yml b/.ci/azure-pipelines-test.yml new file mode 100644 index 0000000000..eec02ff3be --- /dev/null +++ b/.ci/azure-pipelines-test.yml @@ -0,0 +1,68 @@ +parameters: + - name: ImageNames + type: object + default: + Linux: "ubuntu-latest" + Windows: "windows-latest" + macOS: "macos-latest" + - name: TestProjects + type: string + default: "tests/**/*Tests.csproj" + - name: DotNetSdkVersion + type: string + default: 3.1.100 + +jobs: + - job: MainTest + displayName: Main Test + strategy: + matrix: + ${{ each imageName in parameters.ImageNames }}: + ${{ imageName.key }}: + ImageName: ${{ imageName.value }} + maxParallel: 3 + pool: + vmImage: "$(ImageName)" + steps: + - checkout: self + clean: true + submodules: true + persistCredentials: false + + - task: UseDotNet@2 + displayName: "Update DotNet" + inputs: + packageType: sdk + version: ${{ parameters.DotNetSdkVersion }} + + - task: DotNetCoreCLI@2 + displayName: Run .NET Core CLI tests + inputs: + command: "test" + projects: ${{ parameters.TestProjects }} + arguments: "--configuration Release --collect:\"XPlat Code Coverage\" --settings tests/coverletArgs.runsettings --verbosity minimal \"-p:GenerateDocumentationFile=False\"" + publishTestResults: true + testRunTitle: $(Agent.JobName) + workingDirectory: "$(Build.SourcesDirectory)" + + + - task: Palmmedia.reportgenerator.reportgenerator-build-release-task.reportgenerator@4 + condition: and(succeeded(), eq(variables['Agent.OS'], 'Linux')) # !! THIS is for V1 only V2 will/should support merging + displayName: ReportGenerator (merge) + inputs: + reports: '$(Agent.TempDirectory)/**/coverage.cobertura.xml' + targetdir: '$(Agent.TempDirectory)/merged/' + reporttypes: 'Cobertura' + + ## V2 is already in the repository but it does not work "wrong number of segments" YAML error. + - task: PublishCodeCoverageResults@1 + condition: and(succeeded(), eq(variables['Agent.OS'], 'Linux')) # !! THIS is for V1 only V2 will/should support merging + displayName: Publish Code Coverage + inputs: + codeCoverageTool: 'cobertura' + #summaryFileLocation: '$(Agent.TempDirectory)/**/coverage.cobertura.xml' # !!THIS IS FOR V2 + summaryFileLocation: '$(Agent.TempDirectory)/merged/**.xml' + pathToSources: $(Build.SourcesDirectory) # Optional + #reportDirectory: # Optional + #additionalCodeCoverageFiles: # Optional + failIfCoverageEmpty: true # Optional diff --git a/.ci/azure-pipelines-windows.yml b/.ci/azure-pipelines-windows.yml new file mode 100644 index 0000000000..c6ff3736a4 --- /dev/null +++ b/.ci/azure-pipelines-windows.yml @@ -0,0 +1,82 @@ +parameters: + WindowsImage: "windows-latest" + TestProjects: "tests/**/*Tests.csproj" + DotNetSdkVersion: 3.1.100 + +jobs: + - job: PublishWindows + displayName: Publish Windows + pool: + vmImage: ${{ parameters.WindowsImage }} + steps: + - checkout: self + clean: true + submodules: true + persistCredentials: true + + - task: CmdLine@2 + displayName: "Clone Web Client (Master, Release, or Tag)" + condition: and(succeeded(), or(contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master'), contains(variables['Build.SourceBranch'], 'tag')), in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + inputs: + script: "git clone --single-branch --branch $(Build.SourceBranchName) --depth=1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web" + + - task: CmdLine@2 + displayName: "Clone Web Client (PR)" + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master')), in(variables['Build.Reason'], 'PullRequest')) + inputs: + script: "git clone --single-branch --branch $(System.PullRequest.TargetBranch) --depth 1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web" + + - task: NodeTool@0 + displayName: "Install Node" + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + inputs: + versionSpec: "10.x" + + - task: CmdLine@2 + displayName: "Build Web Client" + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + inputs: + script: yarn install + workingDirectory: $(Agent.TempDirectory)/jellyfin-web + + - task: CopyFiles@2 + displayName: "Copy Web Client" + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + inputs: + sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist # Optional + contents: "**" + targetFolder: $(Build.SourcesDirectory)/MediaBrowser.WebDashboard/jellyfin-web + cleanTargetFolder: true # Optional + overWrite: true # Optional + flattenFolders: false # Optional + + - task: CmdLine@2 + displayName: "Clone UX Repository" + inputs: + script: git clone --depth=1 https://github.com/jellyfin/jellyfin-ux $(Agent.TempDirectory)\jellyfin-ux + + - task: PowerShell@2 + displayName: "Build NSIS Installer" + inputs: + targetType: "filePath" # Optional. Options: filePath, inline + filePath: ./deployment/windows/build-jellyfin.ps1 # Required when targetType == FilePath + arguments: -InstallFFMPEG -InstallNSSM -MakeNSIS -InstallTrayApp -UXLocation $(Agent.TempDirectory)\jellyfin-ux -InstallLocation $(build.artifactstagingdirectory) + errorActionPreference: "stop" # Optional. Options: stop, continue, silentlyContinue + workingDirectory: $(Build.SourcesDirectory) # Optional + + - task: CopyFiles@2 + displayName: "Copy NSIS Installer" + inputs: + sourceFolder: $(Build.SourcesDirectory)/deployment/windows/ # Optional + contents: "jellyfin*.exe" + targetFolder: $(System.ArtifactsDirectory)/setup + cleanTargetFolder: true # Optional + overWrite: true # Optional + flattenFolders: true # Optional + + - task: PublishPipelineArtifact@0 + displayName: "Publish Artifact Setup" + condition: succeeded() + inputs: + targetPath: "$(build.artifactstagingdirectory)/setup" + artifactName: "Jellyfin Server Setup" \ No newline at end of file diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml index 7bcaed70cd..221db162ac 100644 --- a/.ci/azure-pipelines.yml +++ b/.ci/azure-pipelines.yml @@ -2,9 +2,11 @@ name: $(Date:yyyyMMdd)$(Rev:.r) variables: - name: TestProjects - value: 'tests/**/*Tests.csproj' + value: "tests/**/*Tests.csproj" - name: RestoreBuildProjects - value: 'Jellyfin.Server/Jellyfin.Server.csproj' + value: "Jellyfin.Server/Jellyfin.Server.csproj" + - name: DotNetSdkVersion + value: 3.1.100 pr: autoCancel: true @@ -13,234 +15,26 @@ trigger: batch: true jobs: - - job: main_build - displayName: Main Build - pool: - vmImage: ubuntu-latest - strategy: - matrix: - Release: - BuildConfiguration: Release - Debug: - BuildConfiguration: Debug - maxParallel: 2 - steps: - - checkout: self - clean: true - submodules: true - persistCredentials: true + - template: azure-pipelines-main.yml + parameters: + LinuxImage: 'ubuntu-latest' + RestoreBuildProjects: $(RestoreBuildProjects) - - task: CmdLine@2 - displayName: "Clone Web Client (Master, Release, or Tag)" - condition: and(succeeded(), or(contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI', 'BuildCompletion')) - inputs: - script: 'git clone --single-branch --branch $(Build.SourceBranchName) --depth=1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web' + - template: azure-pipelines-test.yml + parameters: + ImageNames: + Linux: 'ubuntu-latest' + Windows: 'windows-latest' + macOS: 'macos-latest' - - task: CmdLine@2 - displayName: "Clone Web Client (PR)" - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest')) - inputs: - script: 'git clone --single-branch --branch $(System.PullRequest.TargetBranch) --depth 1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web' + - template: azure-pipelines-windows.yml + parameters: + WindowsImage: 'windows-latest' + TestProjects: $(TestProjects) - - task: NodeTool@0 - displayName: 'Install Node' - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) - inputs: - versionSpec: '10.x' - - - task: CmdLine@2 - displayName: "Build Web Client" - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) - inputs: - script: yarn install - workingDirectory: $(Agent.TempDirectory)/jellyfin-web - - - task: CopyFiles@2 - displayName: 'Copy Web Client' - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) - inputs: - sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist # Optional - contents: '**' - targetFolder: $(Build.SourcesDirectory)/MediaBrowser.WebDashboard/jellyfin-web - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: false # Optional - - - task: UseDotNet@2 - displayName: 'Update DotNet' - inputs: - packageType: sdk - version: 3.1.100 - - - task: DotNetCoreCLI@2 - displayName: 'Publish Server' - inputs: - command: publish - publishWebProjects: false - projects: '$(RestoreBuildProjects)' - arguments: '--configuration $(BuildConfiguration) --output $(build.artifactstagingdirectory)' - zipAfterPublish: false - - - task: PublishPipelineArtifact@0 - displayName: 'Publish Artifact Naming' - condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) - inputs: - targetPath: '$(build.artifactstagingdirectory)/Jellyfin.Server/Emby.Naming.dll' - artifactName: 'Jellyfin.Naming' - - - task: PublishPipelineArtifact@0 - displayName: 'Publish Artifact Controller' - condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) - inputs: - targetPath: '$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Controller.dll' - artifactName: 'Jellyfin.Controller' - - - task: PublishPipelineArtifact@0 - displayName: 'Publish Artifact Model' - condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) - inputs: - targetPath: '$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Model.dll' - artifactName: 'Jellyfin.Model' - - - task: PublishPipelineArtifact@0 - displayName: 'Publish Artifact Common' - condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) - inputs: - targetPath: '$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Common.dll' - artifactName: 'Jellyfin.Common' - - - job: main_test - displayName: Main Test - pool: - vmImage: windows-latest - steps: - - checkout: self - clean: true - submodules: true - persistCredentials: false - - - task: DotNetCoreCLI@2 - displayName: Build - inputs: - command: build - publishWebProjects: false - projects: '$(TestProjects)' - arguments: '--configuration $(BuildConfiguration)' - zipAfterPublish: false - - - task: VisualStudioTestPlatformInstaller@1 - inputs: - packageFeedSelector: 'nugetOrg' # Options: nugetOrg, customFeed, netShare - versionSelector: 'latestPreRelease' # Required when packageFeedSelector == NugetOrg || PackageFeedSelector == CustomFeed# Options: latestPreRelease, latestStable, specificVersion - - task: VSTest@2 - inputs: - testSelector: 'testAssemblies' # Options: testAssemblies, testPlan, testRun - testAssemblyVer2: | # Required when testSelector == TestAssemblies - **\bin\$(BuildConfiguration)\**\*tests.dll - **\bin\$(BuildConfiguration)\**\*test.dll - !**\obj\** - !**\xunit.runner.visualstudio.testadapter.dll - !**\xunit.runner.visualstudio.dotnetcore.testadapter.dll - searchFolder: '$(System.DefaultWorkingDirectory)' - runInParallel: True # Optional - runTestsInIsolation: True # Optional - codeCoverageEnabled: True # Optional - configuration: 'Debug' # Optional - publishRunAttachments: true # Optional - testRunTitle: $(Agent.JobName) - otherConsoleOptions: '/platform:x64 /Framework:.NETCoreApp,Version=v3.1 /logger:console;verbosity="normal"' - - - job: main_build_win - displayName: Publish Windows - pool: - vmImage: windows-latest - strategy: - matrix: - Release: - BuildConfiguration: Release - maxParallel: 2 - steps: - - checkout: self - clean: true - submodules: true - persistCredentials: true - - - task: CmdLine@2 - displayName: "Clone Web Client (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' - - - task: CmdLine@2 - displayName: "Clone Web Client (PR)" - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest')) - inputs: - script: 'git clone --single-branch --branch $(System.PullRequest.TargetBranch) --depth 1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web' - - - task: NodeTool@0 - displayName: 'Install Node' - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) - inputs: - versionSpec: '10.x' - - - task: CmdLine@2 - displayName: "Build Web Client" - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) - inputs: - script: yarn install - workingDirectory: $(Agent.TempDirectory)/jellyfin-web - - - task: CopyFiles@2 - displayName: 'Copy Web Client' - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) - inputs: - sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist # Optional - contents: '**' - targetFolder: $(Build.SourcesDirectory)/MediaBrowser.WebDashboard/jellyfin-web - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: false # Optional - - - task: CmdLine@2 - displayName: 'Clone UX Repository' - inputs: - script: git clone --depth=1 https://github.com/jellyfin/jellyfin-ux $(Agent.TempDirectory)\jellyfin-ux - - - task: PowerShell@2 - displayName: 'Build NSIS Installer' - inputs: - targetType: 'filePath' # Optional. Options: filePath, inline - filePath: ./deployment/windows/build-jellyfin.ps1 # Required when targetType == FilePath - arguments: -InstallFFMPEG -InstallNSSM -MakeNSIS -InstallTrayApp -UXLocation $(Agent.TempDirectory)\jellyfin-ux -InstallLocation $(build.artifactstagingdirectory) - errorActionPreference: 'stop' # Optional. Options: stop, continue, silentlyContinue - workingDirectory: $(Build.SourcesDirectory) # Optional - - - task: CopyFiles@2 - displayName: 'Copy NSIS Installer' - inputs: - sourceFolder: $(Build.SourcesDirectory)/deployment/windows/ # Optional - contents: 'jellyfin*.exe' - targetFolder: $(System.ArtifactsDirectory)/setup - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: true # Optional - - - task: PublishPipelineArtifact@0 - displayName: 'Publish Artifact Setup' - condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) - inputs: - targetPath: '$(build.artifactstagingdirectory)/setup' - artifactName: 'Jellyfin Server Setup' - - - job: dotnet_compat - displayName: Compatibility Check - pool: - vmImage: ubuntu-latest - dependsOn: main_build - # only execute for pull requests - condition: and(succeeded(), variables['System.PullRequest.PullRequestNumber']) - strategy: - matrix: + - template: azure-pipelines-compat.yml + parameters: + Packages: Naming: NugetPackageName: Jellyfin.Naming AssemblyFileName: Emby.Naming.dll @@ -253,74 +47,4 @@ jobs: Common: NugetPackageName: Jellyfin.Common AssemblyFileName: MediaBrowser.Common.dll - maxParallel: 2 - steps: - - checkout: none - - - task: UseDotNet@2 - displayName: 'Update DotNet' - inputs: - packageType: sdk - version: 3.1.100 - - - task: DownloadPipelineArtifact@2 - displayName: 'Download New Assembly Build Artifact' - inputs: - source: 'current' # Options: current, specific - artifact: '$(NugetPackageName)' # Optional - path: '$(System.ArtifactsDirectory)/new-artifacts' - runVersion: 'latest' # Required when source == Specific. Options: latest, latestFromBranch, specific - - - task: CopyFiles@2 - displayName: 'Copy New Assembly Build Artifact' - inputs: - sourceFolder: $(System.ArtifactsDirectory)/new-artifacts # Optional - contents: '**/*.dll' - targetFolder: $(System.ArtifactsDirectory)/new-release - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: true # Optional - - - task: DownloadPipelineArtifact@2 - displayName: 'Download Reference Assembly Build Artifact' - inputs: - source: 'specific' # Options: current, specific - artifact: '$(NugetPackageName)' # Optional - path: '$(System.ArtifactsDirectory)/current-artifacts' - project: '$(System.TeamProjectId)' # Required when source == Specific - pipeline: '$(System.DefinitionId)' # Required when source == Specific - runVersion: 'latestFromBranch' # Required when source == Specific. Options: latest, latestFromBranch, specific - runBranch: 'refs/heads/$(System.PullRequest.TargetBranch)' # Required when source == Specific && runVersion == LatestFromBranch - - - task: CopyFiles@2 - displayName: 'Copy Reference Assembly Build Artifact' - inputs: - sourceFolder: $(System.ArtifactsDirectory)/current-artifacts # Optional - contents: '**/*.dll' - targetFolder: $(System.ArtifactsDirectory)/current-release - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: true # Optional - - - task: DownloadGitHubRelease@0 - displayName: 'Download ABI Compatibility Check Tool' - inputs: - connection: Jellyfin Release Download - userRepository: EraYaN/dotnet-compatibility - defaultVersionType: 'latest' # Options: latest, specificVersion, specificTag - itemPattern: '**-ci.zip' # Optional - downloadPath: '$(System.ArtifactsDirectory)' - - - task: ExtractFiles@1 - displayName: 'Extract ABI Compatibility Check Tool' - inputs: - archiveFilePatterns: '$(System.ArtifactsDirectory)/*-ci.zip' - destinationFolder: $(System.ArtifactsDirectory)/tools - cleanDestinationFolder: true - - # The `--warnings-only` switch will swallow the return code and not emit any errors. - - task: CmdLine@2 - displayName: 'Execute ABI Compatibility Check Tool' - inputs: - script: 'dotnet tools/CompatibilityCheckerCLI.dll current-release/$(AssemblyFileName) new-release/$(AssemblyFileName) --azure-pipelines --warnings-only' - workingDirectory: $(System.ArtifactsDirectory) # Optional + LinuxImage: 'ubuntu-latest' \ No newline at end of file diff --git a/.ci/publish-nightly.yml b/.ci/publish-nightly.yml deleted file mode 100644 index a693e10f6c..0000000000 --- a/.ci/publish-nightly.yml +++ /dev/null @@ -1,46 +0,0 @@ -name: Nightly-$(date:yyyyMMdd).$(rev:r) - -variables: - - name: Version - value: '1.0.0' - -trigger: none -pr: none - -jobs: - - job: publish_artifacts_nightly - displayName: Publish Artifacts Nightly - pool: - vmImage: ubuntu-latest - steps: - - checkout: none - - task: DownloadPipelineArtifact@2 - displayName: Download the Windows Setup Artifact - inputs: - source: 'specific' # Options: current, specific - artifact: 'Jellyfin Server Setup' # Optional - path: '$(System.ArtifactsDirectory)/win-installer' - project: '$(System.TeamProjectId)' # Required when source == Specific - pipelineId: 1 # Required when source == Specific - runVersion: 'latestFromBranch' # Required when source == Specific. Options: latest, latestFromBranch, specific - runBranch: 'refs/heads/master' # Required when source == Specific && runVersion == LatestFromBranch - - - task: SSH@0 - displayName: 'Create Drop directory' - inputs: - sshEndpoint: 'Jellyfin Build Server' - commands: 'mkdir -p /srv/incoming/jellyfin_$(Version)/win-installer && ln -s /srv/incoming/jellyfin_$(Version) /srv/incoming/jellyfin_nightly_azure_upload' - - - task: CopyFilesOverSSH@0 - displayName: 'Copy the Windows Setup to the Repo' - inputs: - sshEndpoint: 'Jellyfin Build Server' - sourceFolder: '$(System.ArtifactsDirectory)/win-installer' - contents: 'jellyfin_*.exe' - targetFolder: '/srv/incoming/jellyfin_nightly_azure_upload/win-installer' - - - task: SSH@0 - displayName: 'Clean up SCP symlink' - inputs: - sshEndpoint: 'Jellyfin Build Server' - commands: 'rm -f /srv/incoming/jellyfin_nightly_azure_upload' diff --git a/.ci/publish-release.yml b/.ci/publish-release.yml deleted file mode 100644 index 57e77ae5aa..0000000000 --- a/.ci/publish-release.yml +++ /dev/null @@ -1,48 +0,0 @@ -name: Release-$(Version)-$(date:yyyyMMdd).$(rev:r) - -variables: - - name: Version - value: '1.0.0' - - name: UsedRunId - value: 0 - -trigger: none -pr: none - -jobs: - - job: publish_artifacts_release - displayName: Publish Artifacts Release - pool: - vmImage: ubuntu-latest - steps: - - checkout: none - - task: DownloadPipelineArtifact@2 - displayName: Download the Windows Setup Artifact - inputs: - source: 'specific' # Options: current, specific - artifact: 'Jellyfin Server Setup' # Optional - path: '$(System.ArtifactsDirectory)/win-installer' - project: '$(System.TeamProjectId)' # Required when source == Specific - pipelineId: 1 # Required when source == Specific - runVersion: 'specific' # Required when source == Specific. Options: latest, latestFromBranch, specific - runId: $(UsedRunId) - - - task: SSH@0 - displayName: 'Create Drop directory' - inputs: - sshEndpoint: 'Jellyfin Build Server' - commands: 'mkdir -p /srv/incoming/jellyfin_$(Version)/win-installer && ln -s /srv/incoming/jellyfin_$(Version) /srv/incoming/jellyfin_release_azure_upload' - - - task: CopyFilesOverSSH@0 - displayName: 'Copy the Windows Setup to the Repo' - inputs: - sshEndpoint: 'Jellyfin Build Server' - sourceFolder: '$(System.ArtifactsDirectory)/win-installer' - contents: 'jellyfin_*.exe' - targetFolder: '/srv/incoming/jellyfin_release_azure_upload/win-installer' - - - task: SSH@0 - displayName: 'Clean up SCP symlink' - inputs: - sshEndpoint: 'Jellyfin Build Server' - commands: 'rm -f /srv/incoming/jellyfin_release_azure_upload' diff --git a/tests/coverletArgs.runsettings b/tests/coverletArgs.runsettings new file mode 100644 index 0000000000..3113957e0a --- /dev/null +++ b/tests/coverletArgs.runsettings @@ -0,0 +1,17 @@ + + + + + + + cobertura + [coverlet.*.tests?]*,[*]Coverlet.Core*,[*]Moq* + Obsolete,GeneratedCodeAttribute,CompilerGeneratedAttribute + false + true + false + + + + + \ No newline at end of file From 22f408201a1ba827c7dd92f1d10b6f75656f0b13 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Wed, 15 Jan 2020 11:20:01 +0100 Subject: [PATCH 065/881] Less output and lesser compression. --- deployment/windows/jellyfin.nsi | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/deployment/windows/jellyfin.nsi b/deployment/windows/jellyfin.nsi index 5666d30f06..d3b75482cc 100644 --- a/deployment/windows/jellyfin.nsi +++ b/deployment/windows/jellyfin.nsi @@ -1,7 +1,7 @@ ; Shows a lot of debug information while compiling ; This can be removed once stable. -!verbose 4 -SetCompressor lzma +!verbose 2 +SetCompressor bzip2 ShowInstDetails show ShowUninstDetails show ;-------------------------------- From d3bd22d7a27949d1053c8be75d160adadf3c767b Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Wed, 15 Jan 2020 11:36:22 +0100 Subject: [PATCH 066/881] Enable Unicode ANSI targets are deprecated --- deployment/windows/jellyfin.nsi | 2 ++ 1 file changed, 2 insertions(+) diff --git a/deployment/windows/jellyfin.nsi b/deployment/windows/jellyfin.nsi index d3b75482cc..dbce29e84c 100644 --- a/deployment/windows/jellyfin.nsi +++ b/deployment/windows/jellyfin.nsi @@ -4,6 +4,8 @@ SetCompressor bzip2 ShowInstDetails show ShowUninstDetails show +Unicode True + ;-------------------------------- !define SF_USELECTED 0 ; used to check selected options status, rest are inherited from Sections.nsh From 9aa870cf246916abe985aba1da4a63daf4137b92 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Wed, 15 Jan 2020 11:36:54 +0100 Subject: [PATCH 067/881] Enable /SOLID switch for compression --- deployment/windows/jellyfin.nsi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment/windows/jellyfin.nsi b/deployment/windows/jellyfin.nsi index dbce29e84c..5629fcf12e 100644 --- a/deployment/windows/jellyfin.nsi +++ b/deployment/windows/jellyfin.nsi @@ -1,7 +1,7 @@ ; Shows a lot of debug information while compiling ; This can be removed once stable. !verbose 2 -SetCompressor bzip2 +SetCompressor bzip2 /SOLID ShowInstDetails show ShowUninstDetails show Unicode True From 1ad6f016172cb094b0ead5ff3517568d027708e7 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Wed, 15 Jan 2020 11:37:37 +0100 Subject: [PATCH 068/881] Switch to slightly more verbose logging. --- deployment/windows/jellyfin.nsi | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/deployment/windows/jellyfin.nsi b/deployment/windows/jellyfin.nsi index 5629fcf12e..3e8d687e79 100644 --- a/deployment/windows/jellyfin.nsi +++ b/deployment/windows/jellyfin.nsi @@ -1,6 +1,4 @@ -; Shows a lot of debug information while compiling -; This can be removed once stable. -!verbose 2 +!verbose 3 SetCompressor bzip2 /SOLID ShowInstDetails show ShowUninstDetails show From 67cae3730897318233179bd32945125d676e74a8 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Wed, 15 Jan 2020 11:27:38 +0100 Subject: [PATCH 069/881] Formatting and comment removal. --- .ci/azure-pipelines-compat.yml | 44 ++++++++++++++++----------------- .ci/azure-pipelines-main.yml | 10 ++++---- .ci/azure-pipelines-test.yml | 21 +++++++--------- .ci/azure-pipelines-windows.yml | 26 +++++++++---------- .ci/azure-pipelines.yml | 16 ++++++------ 5 files changed, 57 insertions(+), 60 deletions(-) diff --git a/.ci/azure-pipelines-compat.yml b/.ci/azure-pipelines-compat.yml index ac23e0b6db..6af956e1a7 100644 --- a/.ci/azure-pipelines-compat.yml +++ b/.ci/azure-pipelines-compat.yml @@ -21,8 +21,8 @@ jobs: ${{ each Package in parameters.Packages }}: ${{ Package.key }}: NugetPackageName: ${{ Package.value.NugetPackageName }} - AssemblyFileName: ${{ Package.value.AssemblyFileName }} - maxParallel: 2 + AssemblyFileName: ${{ Package.value.AssemblyFileName }} + maxParallel: 2 dependsOn: MainBuild steps: - checkout: none @@ -36,49 +36,49 @@ jobs: - task: DownloadPipelineArtifact@2 displayName: "Download New Assembly Build Artifact" inputs: - source: "current" # Options: current, specific - artifact: "$(NugetPackageName)" # Optional + source: "current" + artifact: "$(NugetPackageName)" path: "$(System.ArtifactsDirectory)/new-artifacts" - runVersion: "latest" # Required when source == Specific. Options: latest, latestFromBranch, specific + runVersion: "latest" - task: CopyFiles@2 displayName: "Copy New Assembly Build Artifact" inputs: - sourceFolder: $(System.ArtifactsDirectory)/new-artifacts # Optional + sourceFolder: $(System.ArtifactsDirectory)/new-artifacts contents: "**/*.dll" targetFolder: $(System.ArtifactsDirectory)/new-release - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: true # Optional + cleanTargetFolder: true + overWrite: true + flattenFolders: true - task: DownloadPipelineArtifact@2 displayName: "Download Reference Assembly Build Artifact" inputs: - source: "specific" # Options: current, specific - artifact: "$(NugetPackageName)" # Optional + source: "specific" + artifact: "$(NugetPackageName)" path: "$(System.ArtifactsDirectory)/current-artifacts" - project: "$(System.TeamProjectId)" # Required when source == Specific - pipeline: "$(System.DefinitionId)" # Required when source == Specific - runVersion: "latestFromBranch" # Required when source == Specific. Options: latest, latestFromBranch, specific - runBranch: "refs/heads/$(System.PullRequest.TargetBranch)" # Required when source == Specific && runVersion == LatestFromBranch + project: "$(System.TeamProjectId)" + pipeline: "$(System.DefinitionId)" + runVersion: "latestFromBranch" + runBranch: "refs/heads/$(System.PullRequest.TargetBranch)" - task: CopyFiles@2 displayName: "Copy Reference Assembly Build Artifact" inputs: - sourceFolder: $(System.ArtifactsDirectory)/current-artifacts # Optional + sourceFolder: $(System.ArtifactsDirectory)/current-artifacts contents: "**/*.dll" targetFolder: $(System.ArtifactsDirectory)/current-release - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: true # Optional + cleanTargetFolder: true + overWrite: true + flattenFolders: true - task: DownloadGitHubRelease@0 displayName: "Download ABI Compatibility Check Tool" inputs: connection: Jellyfin Release Download userRepository: EraYaN/dotnet-compatibility - defaultVersionType: "latest" # Options: latest, specificVersion, specificTag - itemPattern: "**-ci.zip" # Optional + defaultVersionType: "latest" + itemPattern: "**-ci.zip" downloadPath: "$(System.ArtifactsDirectory)" - task: ExtractFiles@1 @@ -93,4 +93,4 @@ jobs: displayName: "Execute ABI Compatibility Check Tool" inputs: script: "dotnet tools/CompatibilityCheckerCLI.dll current-release/$(AssemblyFileName) new-release/$(AssemblyFileName) --azure-pipelines --warnings-only" - workingDirectory: $(System.ArtifactsDirectory) # Optional \ No newline at end of file + workingDirectory: $(System.ArtifactsDirectory) diff --git a/.ci/azure-pipelines-main.yml b/.ci/azure-pipelines-main.yml index fd263e20f9..9880bbfaa2 100644 --- a/.ci/azure-pipelines-main.yml +++ b/.ci/azure-pipelines-main.yml @@ -50,12 +50,12 @@ jobs: displayName: "Copy Web Client" condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) inputs: - sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist # Optional + sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist contents: "**" targetFolder: $(Build.SourcesDirectory)/MediaBrowser.WebDashboard/jellyfin-web - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: false # Optional + cleanTargetFolder: true + overWrite: true + flattenFolders: false - task: UseDotNet@2 displayName: "Update DotNet" @@ -98,4 +98,4 @@ jobs: condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) inputs: targetPath: "$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Common.dll" - artifactName: "Jellyfin.Common" \ No newline at end of file + artifactName: "Jellyfin.Common" diff --git a/.ci/azure-pipelines-test.yml b/.ci/azure-pipelines-test.yml index eec02ff3be..4455632e15 100644 --- a/.ci/azure-pipelines-test.yml +++ b/.ci/azure-pipelines-test.yml @@ -1,7 +1,7 @@ parameters: - name: ImageNames type: object - default: + default: Linux: "ubuntu-latest" Windows: "windows-latest" macOS: "macos-latest" @@ -40,29 +40,26 @@ jobs: inputs: command: "test" projects: ${{ parameters.TestProjects }} - arguments: "--configuration Release --collect:\"XPlat Code Coverage\" --settings tests/coverletArgs.runsettings --verbosity minimal \"-p:GenerateDocumentationFile=False\"" + arguments: '--configuration Release --collect:"XPlat Code Coverage" --settings tests/coverletArgs.runsettings --verbosity minimal "-p:GenerateDocumentationFile=False"' publishTestResults: true testRunTitle: $(Agent.JobName) workingDirectory: "$(Build.SourcesDirectory)" - - task: Palmmedia.reportgenerator.reportgenerator-build-release-task.reportgenerator@4 condition: and(succeeded(), eq(variables['Agent.OS'], 'Linux')) # !! THIS is for V1 only V2 will/should support merging displayName: ReportGenerator (merge) inputs: - reports: '$(Agent.TempDirectory)/**/coverage.cobertura.xml' - targetdir: '$(Agent.TempDirectory)/merged/' - reporttypes: 'Cobertura' + reports: "$(Agent.TempDirectory)/**/coverage.cobertura.xml" + targetdir: "$(Agent.TempDirectory)/merged/" + reporttypes: "Cobertura" ## V2 is already in the repository but it does not work "wrong number of segments" YAML error. - task: PublishCodeCoverageResults@1 condition: and(succeeded(), eq(variables['Agent.OS'], 'Linux')) # !! THIS is for V1 only V2 will/should support merging displayName: Publish Code Coverage inputs: - codeCoverageTool: 'cobertura' + codeCoverageTool: "cobertura" #summaryFileLocation: '$(Agent.TempDirectory)/**/coverage.cobertura.xml' # !!THIS IS FOR V2 - summaryFileLocation: '$(Agent.TempDirectory)/merged/**.xml' - pathToSources: $(Build.SourcesDirectory) # Optional - #reportDirectory: # Optional - #additionalCodeCoverageFiles: # Optional - failIfCoverageEmpty: true # Optional + summaryFileLocation: "$(Agent.TempDirectory)/merged/**.xml" + pathToSources: $(Build.SourcesDirectory) + failIfCoverageEmpty: true diff --git a/.ci/azure-pipelines-windows.yml b/.ci/azure-pipelines-windows.yml index c6ff3736a4..32d1d1382d 100644 --- a/.ci/azure-pipelines-windows.yml +++ b/.ci/azure-pipelines-windows.yml @@ -43,12 +43,12 @@ jobs: displayName: "Copy Web Client" condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) inputs: - sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist # Optional + sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist contents: "**" targetFolder: $(Build.SourcesDirectory)/MediaBrowser.WebDashboard/jellyfin-web - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: false # Optional + cleanTargetFolder: true + overWrite: true + flattenFolders: false - task: CmdLine@2 displayName: "Clone UX Repository" @@ -58,25 +58,25 @@ jobs: - task: PowerShell@2 displayName: "Build NSIS Installer" inputs: - targetType: "filePath" # Optional. Options: filePath, inline - filePath: ./deployment/windows/build-jellyfin.ps1 # Required when targetType == FilePath + targetType: "filePath" + filePath: ./deployment/windows/build-jellyfin.ps1 arguments: -InstallFFMPEG -InstallNSSM -MakeNSIS -InstallTrayApp -UXLocation $(Agent.TempDirectory)\jellyfin-ux -InstallLocation $(build.artifactstagingdirectory) - errorActionPreference: "stop" # Optional. Options: stop, continue, silentlyContinue - workingDirectory: $(Build.SourcesDirectory) # Optional + errorActionPreference: "stop" + workingDirectory: $(Build.SourcesDirectory) - task: CopyFiles@2 displayName: "Copy NSIS Installer" inputs: - sourceFolder: $(Build.SourcesDirectory)/deployment/windows/ # Optional + sourceFolder: $(Build.SourcesDirectory)/deployment/windows/ contents: "jellyfin*.exe" targetFolder: $(System.ArtifactsDirectory)/setup - cleanTargetFolder: true # Optional - overWrite: true # Optional - flattenFolders: true # Optional + cleanTargetFolder: true + overWrite: true + flattenFolders: true - task: PublishPipelineArtifact@0 displayName: "Publish Artifact Setup" condition: succeeded() inputs: targetPath: "$(build.artifactstagingdirectory)/setup" - artifactName: "Jellyfin Server Setup" \ No newline at end of file + artifactName: "Jellyfin Server Setup" diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml index 221db162ac..f79a85b210 100644 --- a/.ci/azure-pipelines.yml +++ b/.ci/azure-pipelines.yml @@ -17,24 +17,24 @@ trigger: jobs: - template: azure-pipelines-main.yml parameters: - LinuxImage: 'ubuntu-latest' + LinuxImage: "ubuntu-latest" RestoreBuildProjects: $(RestoreBuildProjects) - template: azure-pipelines-test.yml parameters: - ImageNames: - Linux: 'ubuntu-latest' - Windows: 'windows-latest' - macOS: 'macos-latest' + ImageNames: + Linux: "ubuntu-latest" + Windows: "windows-latest" + macOS: "macos-latest" - template: azure-pipelines-windows.yml parameters: - WindowsImage: 'windows-latest' + WindowsImage: "windows-latest" TestProjects: $(TestProjects) - template: azure-pipelines-compat.yml parameters: - Packages: + Packages: Naming: NugetPackageName: Jellyfin.Naming AssemblyFileName: Emby.Naming.dll @@ -47,4 +47,4 @@ jobs: Common: NugetPackageName: Jellyfin.Common AssemblyFileName: MediaBrowser.Common.dll - LinuxImage: 'ubuntu-latest' \ No newline at end of file + LinuxImage: "ubuntu-latest" From 8868ff2ffa7d50d19779e5e8c1f661ece9fd0321 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <799610810@qq.com> Date: Wed, 15 Jan 2020 18:40:58 +0800 Subject: [PATCH 070/881] remove useless comment --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index a099087628..3b8cb93fcc 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2644,8 +2644,6 @@ namespace MediaBrowser.Controller.MediaEncoding } else { - //h264_amf is now supported on linux with 'amdgpu-pro' installed and '--enable-amf' when compiling ffmpeg - //using vaapi decode and h264_amf encode on linux platform can avoid some weird transcoding errors in h264_vaapi with amd gpu return "-hwaccel vaapi"; } } From 2c10891b66bf5963d2bfca34b704607a3bc0de85 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <799610810@qq.com> Date: Wed, 15 Jan 2020 18:45:28 +0800 Subject: [PATCH 071/881] turn on indentation. --- MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index 993cd3f747..f5decdc0db 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -56,8 +56,8 @@ namespace MediaBrowser.MediaEncoding.Encoder "hevc_vaapi", "h264_v4l2m2m", "ac3", - "h264_amf", - "hevc_amf" + "h264_amf", + "hevc_amf" }; // Try and use the individual library versions to determine a FFmpeg version From ec8baaf48d28526e888d2301c5eaf207455c3dfd Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Wed, 15 Jan 2020 12:17:42 +0100 Subject: [PATCH 072/881] Switch around SetCompressor arguments. Hide progress bars for powershell. --- deployment/windows/build-jellyfin.ps1 | 2 ++ deployment/windows/jellyfin.nsi | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/deployment/windows/build-jellyfin.ps1 b/deployment/windows/build-jellyfin.ps1 index dde6eb8fcf..bb2f509192 100644 --- a/deployment/windows/build-jellyfin.ps1 +++ b/deployment/windows/build-jellyfin.ps1 @@ -15,6 +15,8 @@ param( [ValidateSet('x64','x86', 'arm', 'arm64')][string]$Architecture = 'x64' ) +$ProgressPreference = 'SilentlyContinue' # Speedup all downloads by hiding progress bars. + #PowershellCore and *nix check to make determine which temp dir to use. if(($PSVersionTable.PSEdition -eq 'Core') -and (-not $IsWindows)){ $TempDir = mktemp -d diff --git a/deployment/windows/jellyfin.nsi b/deployment/windows/jellyfin.nsi index 3e8d687e79..86724b8f49 100644 --- a/deployment/windows/jellyfin.nsi +++ b/deployment/windows/jellyfin.nsi @@ -1,5 +1,5 @@ !verbose 3 -SetCompressor bzip2 /SOLID +SetCompressor /SOLID bzip2 ShowInstDetails show ShowUninstDetails show Unicode True From 2cad58e5cd4c16dfe9e3ad2267d4f5734dc9d7a1 Mon Sep 17 00:00:00 2001 From: artiume Date: Wed, 15 Jan 2020 10:02:01 -0500 Subject: [PATCH 073/881] Update .github/ISSUE_TEMPLATE/media_playback.md Co-Authored-By: dkanada --- .github/ISSUE_TEMPLATE/media_playback.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/media_playback.md b/.github/ISSUE_TEMPLATE/media_playback.md index 97e3785910..b51500f870 100644 --- a/.github/ISSUE_TEMPLATE/media_playback.md +++ b/.github/ISSUE_TEMPLATE/media_playback.md @@ -11,7 +11,7 @@ assignees: '' **Logs** - + **FFmpeg Logs** From d4745957b3dc0b1cc5f5baac299883a89df4cfb6 Mon Sep 17 00:00:00 2001 From: nextlooper42 Date: Tue, 14 Jan 2020 10:29:23 +0000 Subject: [PATCH 074/881] Translated using Weblate (Slovak) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sk/ --- .../Localization/Core/sk.json | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/sk.json b/Emby.Server.Implementations/Localization/Core/sk.json index 9bac305a27..1988bda526 100644 --- a/Emby.Server.Implementations/Localization/Core/sk.json +++ b/Emby.Server.Implementations/Localization/Core/sk.json @@ -15,7 +15,7 @@ "Favorites": "Obľúbené", "Folders": "Priečinky", "Genres": "Žánre", - "HeaderAlbumArtists": "Albumy umelcov", + "HeaderAlbumArtists": "Umelci albumu", "HeaderCameraUploads": "Nahrané fotografie", "HeaderContinueWatching": "Pokračovať v pozeraní", "HeaderFavoriteAlbums": "Obľúbené albumy", @@ -45,25 +45,25 @@ "NameSeasonNumber": "Séria {0}", "NameSeasonUnknown": "Neznáma séria", "NewVersionIsAvailable": "Nová verzia Jellyfin Serveru je dostupná na stiahnutie.", - "NotificationOptionApplicationUpdateAvailable": "Aktualizácia aplikácie je dostupná", - "NotificationOptionApplicationUpdateInstalled": "Aktualizácia aplikácie nainštalovaná", - "NotificationOptionAudioPlayback": "Prehrávanie audia bolo spustené", - "NotificationOptionAudioPlaybackStopped": "Prehrávanie audia bolo zastavené", + "NotificationOptionApplicationUpdateAvailable": "Je dostupná aktualizácia aplikácie", + "NotificationOptionApplicationUpdateInstalled": "Aktualizácia aplikácie bola nainštalovaná", + "NotificationOptionAudioPlayback": "Prehrávanie zvuku bolo spustené", + "NotificationOptionAudioPlaybackStopped": "Prehrávanie zvuku bolo zastavené", "NotificationOptionCameraImageUploaded": "Obrázok z fotoaparátu bol nahraný", "NotificationOptionInstallationFailed": "Chyba inštalácie", - "NotificationOptionNewLibraryContent": "Nový obsah bol pridaný", - "NotificationOptionPluginError": "Chyba rozšírenia", - "NotificationOptionPluginInstalled": "Rozšírenie nainštalované", - "NotificationOptionPluginUninstalled": "Rozšírenie odinštalované", - "NotificationOptionPluginUpdateInstalled": "Aktualizácia rozšírenia nainštalovaná", + "NotificationOptionNewLibraryContent": "Bol pridaný nový obsah", + "NotificationOptionPluginError": "Chyba zásuvného modulu", + "NotificationOptionPluginInstalled": "Bol nainštalovaný zásuvný modul", + "NotificationOptionPluginUninstalled": "Zásuvný modul bol odinštalovaný", + "NotificationOptionPluginUpdateInstalled": "Bola nainštalovaná aktualizácia zásuvného modulu", "NotificationOptionServerRestartRequired": "Vyžaduje sa reštart servera", "NotificationOptionTaskFailed": "Naplánovaná úloha zlyhala", "NotificationOptionUserLockedOut": "Používateľ je uzamknutý", "NotificationOptionVideoPlayback": "Spustené prehrávanie videa", "NotificationOptionVideoPlaybackStopped": "Zastavené prehrávanie videa", "Photos": "Fotky", - "Playlists": "Zoznamy skladieb", - "Plugin": "Rozšírenie", + "Playlists": "Playlisty", + "Plugin": "Zásuvný modul", "PluginInstalledWithName": "{0} bol nainštalovaný", "PluginUninstalledWithName": "{0} bol odinštalovaný", "PluginUpdatedWithName": "{0} bol aktualizovaný", @@ -72,8 +72,8 @@ "ScheduledTaskStartedWithName": "{0} zahájených", "ServerNameNeedsToBeRestarted": "{0} vyžaduje reštart", "Shows": "Seriály", - "Songs": "Skladby", - "StartupEmbyServerIsLoading": "Jellyfin Server sa spúšťa. Skúste to prosím o chvíľu znova.", + "Songs": "Piesne", + "StartupEmbyServerIsLoading": "Jellyfin Server sa spúšťa. Prosím, skúste to o chvíľu znova.", "SubtitleDownloadFailureForItem": "Sťahovanie titulkov pre {0} zlyhalo", "SubtitleDownloadFailureFromForItem": "Sťahovanie titulkov z {0} pre {1} zlyhalo", "SubtitlesDownloadedForItem": "Titulky pre {0} stiahnuté", @@ -87,11 +87,11 @@ "UserLockedOutWithName": "Používateľ {0} bol vymknutý", "UserOfflineFromDevice": "{0} sa odpojil od {1}", "UserOnlineFromDevice": "{0} je online z {1}", - "UserPasswordChangedWithName": "Heslo používateľa {0} zmenené", + "UserPasswordChangedWithName": "Heslo používateľa {0} bolo zmenené", "UserPolicyUpdatedWithName": "Používateľské zásady pre {0} boli aktualizované", - "UserStartedPlayingItemWithValues": "{0} spustil prehrávanie {1}", - "UserStoppedPlayingItemWithValues": "{0} zastavil prehrávanie {1}", - "ValueHasBeenAddedToLibrary": "{0} bolo pridané do vašej knižnice médií", + "UserStartedPlayingItemWithValues": "{0} spustil prehrávanie {1} na {2}", + "UserStoppedPlayingItemWithValues": "{0} ukončil prehrávanie {1} na {2}", + "ValueHasBeenAddedToLibrary": "{0} bol pridané do vašej knižnice médií", "ValueSpecialEpisodeName": "Špeciál - {0}", "VersionNumber": "Verzia {0}" } From 42213d94e5126a9966c5a555d4d9cce87451c481 Mon Sep 17 00:00:00 2001 From: 4d1m Date: Wed, 15 Jan 2020 06:58:17 +0000 Subject: [PATCH 075/881] Translated using Weblate (Romanian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ro/ --- Emby.Server.Implementations/Localization/Core/ro.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ro.json b/Emby.Server.Implementations/Localization/Core/ro.json index b871626f0d..1a4756e3de 100644 --- a/Emby.Server.Implementations/Localization/Core/ro.json +++ b/Emby.Server.Implementations/Localization/Core/ro.json @@ -65,7 +65,7 @@ "LabelIpAddressValue": "Adresa IP: {0}", "ItemRemovedWithName": "{0} a fost eliminat din bibliotecă", "ItemAddedWithName": "{0} a fost adăugat în bibliotecă", - "Inherit": "moștenit", + "Inherit": "Moștenit", "HomeVideos": "Videoclipuri personale", "HeaderRecordingGroups": "Grupuri de înregistrare", "HeaderLiveTV": "TV în Direct", From 15c52867eae01487a3f32a94adad9042f17b9101 Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Thu, 16 Jan 2020 16:32:04 +0800 Subject: [PATCH 076/881] New upstream ffmpeg version 4.2.1 on windows --- deployment/win-x64/docker-build.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment/win-x64/docker-build.sh b/deployment/win-x64/docker-build.sh index 3f1ad78b50..77372a66f7 100755 --- a/deployment/win-x64/docker-build.sh +++ b/deployment/win-x64/docker-build.sh @@ -8,7 +8,7 @@ set -o xtrace # Version variables NSSM_VERSION="nssm-2.24-101-g897c7ad" NSSM_URL="http://files.evilt.win/nssm/${NSSM_VERSION}.zip" -FFMPEG_VERSION="ffmpeg-4.0.2-win64-static" +FFMPEG_VERSION="ffmpeg-4.2.1-win64-static" FFMPEG_URL="https://ffmpeg.zeranoe.com/builds/win64/static/${FFMPEG_VERSION}.zip" # Move to source directory From ac0b30285e22eff5e9ab36c08fe8cd24a6c3ef4a Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Thu, 16 Jan 2020 16:32:07 +0800 Subject: [PATCH 077/881] New upstream ffmpeg version 4.2.1 on windows --- deployment/win-x86/docker-build.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment/win-x86/docker-build.sh b/deployment/win-x86/docker-build.sh index 7d79ba4958..dd411756a8 100755 --- a/deployment/win-x86/docker-build.sh +++ b/deployment/win-x86/docker-build.sh @@ -8,7 +8,7 @@ set -o xtrace # Version variables NSSM_VERSION="nssm-2.24-101-g897c7ad" NSSM_URL="http://files.evilt.win/nssm/${NSSM_VERSION}.zip" -FFMPEG_VERSION="ffmpeg-4.0.2-win32-static" +FFMPEG_VERSION="ffmpeg-4.2.1-win32-static" FFMPEG_URL="https://ffmpeg.zeranoe.com/builds/win32/static/${FFMPEG_VERSION}.zip" # Move to source directory From e92e105c420660f59ad3671852a4a57bb04b7c67 Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Thu, 16 Jan 2020 17:57:19 +0800 Subject: [PATCH 078/881] New upstream ffmpeg version 4.2.1 on windows --- deployment/windows/build-jellyfin.ps1 | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/deployment/windows/build-jellyfin.ps1 b/deployment/windows/build-jellyfin.ps1 index dde6eb8fcf..0be832f373 100644 --- a/deployment/windows/build-jellyfin.ps1 +++ b/deployment/windows/build-jellyfin.ps1 @@ -44,7 +44,8 @@ function Build-JellyFin { function Install-FFMPEG { param( [string]$ResolvedInstallLocation, - [string]$Architecture + [string]$Architecture, + [string]$FFMPEGVersionX86 = "ffmpeg-4.2.1-win32-shared", ) Write-Verbose "Checking Architecture" if($Architecture -notin @('x86','x64')){ @@ -55,7 +56,7 @@ function Install-FFMPEG { Invoke-WebRequest -Uri https://repo.jellyfin.org/releases/server/windows/ffmpeg/jellyfin-ffmpeg.zip -UseBasicParsing -OutFile "$tempdir/ffmpeg.zip" | Write-Verbose }else{ Write-Verbose "Downloading 32 bit FFMPEG" - Invoke-WebRequest -Uri https://ffmpeg.zeranoe.com/builds/win32/shared/ffmpeg-4.0.2-win32-shared.zip -UseBasicParsing -OutFile "$tempdir/ffmpeg.zip" | Write-Verbose + Invoke-WebRequest -Uri https://ffmpeg.zeranoe.com/builds/win32/shared/$FFMPEGVersionX86.zip -UseBasicParsing -OutFile "$tempdir/ffmpeg.zip" | Write-Verbose } Expand-Archive "$tempdir/ffmpeg.zip" -DestinationPath "$tempdir/ffmpeg/" -Force | Write-Verbose @@ -66,7 +67,7 @@ function Install-FFMPEG { } }else{ Write-Verbose "Copying Binaries to Jellyfin location" - Get-ChildItem "$tempdir/ffmpeg/ffmpeg-4.0.2-win32-shared/bin" | ForEach-Object { + Get-ChildItem "$tempdir/ffmpeg/$FFMPEGVersionX86/bin" | ForEach-Object { Copy-Item $_.FullName -Destination $installLocation | Write-Verbose } } From 0a7ea36c68e8f7b013dd9148d1356c031bd53e1e Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Thu, 16 Jan 2020 18:10:14 +0800 Subject: [PATCH 079/881] Update build-jellyfin.ps1 --- deployment/windows/build-jellyfin.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment/windows/build-jellyfin.ps1 b/deployment/windows/build-jellyfin.ps1 index 0be832f373..9fd86e84d8 100644 --- a/deployment/windows/build-jellyfin.ps1 +++ b/deployment/windows/build-jellyfin.ps1 @@ -45,7 +45,7 @@ function Install-FFMPEG { param( [string]$ResolvedInstallLocation, [string]$Architecture, - [string]$FFMPEGVersionX86 = "ffmpeg-4.2.1-win32-shared", + [string]$FFMPEGVersionX86 = "ffmpeg-4.2.1-win32-shared" ) Write-Verbose "Checking Architecture" if($Architecture -notin @('x86','x64')){ From 2ce16d4bb5d98677ac972739983c39b67518038f Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Thu, 16 Jan 2020 18:47:54 +0800 Subject: [PATCH 080/881] fix indentation --- deployment/windows/build-jellyfin.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/deployment/windows/build-jellyfin.ps1 b/deployment/windows/build-jellyfin.ps1 index 9fd86e84d8..7afc385eac 100644 --- a/deployment/windows/build-jellyfin.ps1 +++ b/deployment/windows/build-jellyfin.ps1 @@ -44,8 +44,8 @@ function Build-JellyFin { function Install-FFMPEG { param( [string]$ResolvedInstallLocation, - [string]$Architecture, - [string]$FFMPEGVersionX86 = "ffmpeg-4.2.1-win32-shared" + [string]$Architecture, + [string]$FFMPEGVersionX86 = "ffmpeg-4.2.1-win32-shared" ) Write-Verbose "Checking Architecture" if($Architecture -notin @('x86','x64')){ From 96c9af590494aa8137d5a061aaf1e68feee60b67 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Thu, 16 Jan 2020 13:20:01 +0100 Subject: [PATCH 081/881] Add brackets around thread id --- Jellyfin.Server/Program.cs | 4 ++-- Jellyfin.Server/Resources/Configuration/logging.json | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 8f44327971..fa9b626744 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -481,11 +481,11 @@ namespace Jellyfin.Server catch (Exception ex) { Serilog.Log.Logger = new LoggerConfiguration() - .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {ThreadId} {SourceContext}: {Message:lj} {NewLine}{Exception}") + .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}") .WriteTo.Async(x => x.File( Path.Combine(appPaths.LogDirectoryPath, "log_.log"), rollingInterval: RollingInterval.Day, - outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {ThreadId} {SourceContext}:{Message} {NewLine}{Exception}")) + outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}:{Message}{NewLine}{Exception}")) .Enrich.FromLogContext() .Enrich.WithThreadId() .CreateLogger(); diff --git a/Jellyfin.Server/Resources/Configuration/logging.json b/Jellyfin.Server/Resources/Configuration/logging.json index 6bc2ed2ee4..e9f71afd49 100644 --- a/Jellyfin.Server/Resources/Configuration/logging.json +++ b/Jellyfin.Server/Resources/Configuration/logging.json @@ -5,7 +5,7 @@ { "Name": "Console", "Args": { - "outputTemplate": "[{Timestamp:HH:mm:ss}] [{Level:u3}] {ThreadId} {SourceContext}: {Message:lj} {NewLine}{Exception}" + "outputTemplate": "[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}" } }, { @@ -20,7 +20,7 @@ "retainedFileCountLimit": 3, "rollOnFileSizeLimit": true, "fileSizeLimitBytes": 100000000, - "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {ThreadId} {SourceContext}:{Message} {NewLine}{Exception}" + "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}:{Message}{NewLine}{Exception}" } } ] From e882b03e817715bd14223cb2b9495e983ff5ac2f Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Thu, 16 Jan 2020 13:30:38 +0100 Subject: [PATCH 082/881] Add back support for DVDs copied as folders --- .../Encoder/MediaEncoder.cs | 77 ++++++++++++++++++- 1 file changed, 76 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index e0f7b992ce..deab0715cf 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -849,14 +849,89 @@ namespace MediaBrowser.MediaEncoding.Encoder } } + /// public Task ConvertImage(string inputPath, string outputPath) { throw new NotImplementedException(); } + /// public IEnumerable GetPrimaryPlaylistVobFiles(string path, IIsoMount isoMount, uint? titleNumber) { - throw new NotImplementedException(); + // min size 300 mb + const long MinPlayableSize = 314572800; + + var root = isoMount != null ? isoMount.MountedPath : path; + + // Try to eliminate menus and intros by skipping all files at the front of the list that are less than the minimum size + // Once we reach a file that is at least the minimum, return all subsequent ones + var allVobs = _fileSystem.GetFiles(root, true) + .Where(file => string.Equals(file.Extension, ".vob", StringComparison.OrdinalIgnoreCase)) + .OrderBy(i => i.FullName) + .ToList(); + + // If we didn't find any satisfying the min length, just take them all + if (allVobs.Count == 0) + { + _logger.LogWarning("No vobs found in dvd structure."); + return Enumerable.Empty(); + } + + if (titleNumber.HasValue) + { + var prefix = string.Format("VTS_0{0}_", titleNumber.Value.ToString(CultureInfo.InvariantCulture)); + var vobs = allVobs.Where(i => i.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList(); + + if (vobs.Count > 0) + { + var minSizeVobs = vobs + .SkipWhile(f => f.Length < MinPlayableSize) + .ToList(); + + return minSizeVobs.Count == 0 ? vobs.Select(i => i.FullName) : minSizeVobs.Select(i => i.FullName); + } + + _logger.LogWarning("Could not determine vob file list for {0} using DvdLib. Will scan using file sizes.", video.Path); + } + + var files = allVobs + .SkipWhile(f => f.Length < MinPlayableSize) + .ToList(); + + // If we didn't find any satisfying the min length, just take them all + if (files.Count == 0) + { + _logger.LogWarning("Vob size filter resulted in zero matches. Taking all vobs."); + files = allVobs; + } + + // Assuming they're named "vts_05_01", take all files whose second part matches that of the first file + if (files.Count > 0) + { + var parts = _fileSystem.GetFileNameWithoutExtension(files[0]).Split('_'); + + if (parts.Length == 3) + { + var title = parts[1]; + + files = files.TakeWhile(f => + { + var fileParts = _fileSystem.GetFileNameWithoutExtension(f).Split('_'); + + return fileParts.Length == 3 && string.Equals(title, fileParts[1], StringComparison.OrdinalIgnoreCase); + + }).ToList(); + + // If this resulted in not getting any vobs, just take them all + if (files.Count == 0) + { + _logger.LogWarning("Vob filename filter resulted in zero matches. Taking all vobs."); + files = allVobs; + } + } + } + + return files.Select(i => i.FullName); } public bool CanExtractSubtitles(string codec) From f3a1729964f8ff582aaa9f31eb415114340035ce Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Thu, 16 Jan 2020 15:02:50 +0100 Subject: [PATCH 083/881] Address comments --- MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index deab0715cf..4123f0203a 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -879,7 +879,10 @@ namespace MediaBrowser.MediaEncoding.Encoder if (titleNumber.HasValue) { - var prefix = string.Format("VTS_0{0}_", titleNumber.Value.ToString(CultureInfo.InvariantCulture)); + var prefix = string.Format( + CultureInfo.InvariantCulture, + titleNumber.Value >= 10 ? "VTS_{0}_" : "VTS_0{0}_", + titleNumber.Value); var vobs = allVobs.Where(i => i.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList(); if (vobs.Count > 0) @@ -891,7 +894,7 @@ namespace MediaBrowser.MediaEncoding.Encoder return minSizeVobs.Count == 0 ? vobs.Select(i => i.FullName) : minSizeVobs.Select(i => i.FullName); } - _logger.LogWarning("Could not determine vob file list for {0} using DvdLib. Will scan using file sizes.", video.Path); + _logger.LogWarning("Could not determine vob file list for {0} using DvdLib. Will scan using file sizes.", path); } var files = allVobs From dcd6ceb9a2a971ec10fe22c94880d643910a21ab Mon Sep 17 00:00:00 2001 From: Anthony Lavado Date: Thu, 16 Jan 2020 09:31:20 -0500 Subject: [PATCH 084/881] Update SQLitePCL to new version --- Emby.Server.Implementations/Emby.Server.Implementations.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 03cbe00b7a..77333a03d0 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -35,7 +35,7 @@ - + From 0cbae4a06d49acccfd7a757039f7f6725cdc53a5 Mon Sep 17 00:00:00 2001 From: artiume Date: Thu, 16 Jan 2020 12:51:34 -0500 Subject: [PATCH 085/881] Tcoding https://github.com/jellyfin/jellyfin/pull/2184 --- .../MediaEncoding/EncodingHelper.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 020f0553ed..765932023b 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2750,6 +2750,8 @@ namespace MediaBrowser.Controller.MediaEncoding args += " -mpegts_m2ts_mode 1"; } + var supportsGlobalHeaderFlag = state.OutputContainer != "mkv"; + if (string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase)) { if (state.VideoStream != null @@ -2770,7 +2772,12 @@ namespace MediaBrowser.Controller.MediaEncoding if (!state.RunTimeTicks.HasValue) { - args += " -flags -global_header -fflags +genpts"; + if(supportsGlobalHeaderFlag) + { + args += " -flags -global_header"; + } + + args += " -fflags +genpts"; } } else @@ -2816,7 +2823,7 @@ namespace MediaBrowser.Controller.MediaEncoding args += " " + qualityParam.Trim(); } - if (!state.RunTimeTicks.HasValue) + if (supportsGlobalHeaderFlag && !state.RunTimeTicks.HasValue) { args += " -flags -global_header"; } From 47d3337124ca83c72133b28b0a745971c797f3ae Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Thu, 16 Jan 2020 23:22:42 +0100 Subject: [PATCH 086/881] Update StringHelper.cs --- MediaBrowser.Model/Extensions/StringHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Model/Extensions/StringHelper.cs b/MediaBrowser.Model/Extensions/StringHelper.cs index 9ce1cf79ff..a4ba4b0693 100644 --- a/MediaBrowser.Model/Extensions/StringHelper.cs +++ b/MediaBrowser.Model/Extensions/StringHelper.cs @@ -6,7 +6,7 @@ namespace MediaBrowser.Model.Extensions public static class StringHelper { /// - /// Returns the string with the first character inheritdoc uppercase. + /// Returns the string with the first character as uppercase. /// /// The input string. /// The string with the first character inheritdoc uppercase. From 686d1ff9fb68fbb4b05022bdd141d17f2f720515 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Thu, 16 Jan 2020 23:23:06 +0100 Subject: [PATCH 087/881] Update StringHelper.cs --- MediaBrowser.Model/Extensions/StringHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Model/Extensions/StringHelper.cs b/MediaBrowser.Model/Extensions/StringHelper.cs index a4ba4b0693..5864120544 100644 --- a/MediaBrowser.Model/Extensions/StringHelper.cs +++ b/MediaBrowser.Model/Extensions/StringHelper.cs @@ -9,7 +9,7 @@ namespace MediaBrowser.Model.Extensions /// Returns the string with the first character as uppercase. /// /// The input string. - /// The string with the first character inheritdoc uppercase. + /// The string with the first character as uppercase. public static string FirstToUpper(string str) { if (string.IsNullOrEmpty(str)) From c601def4847cb0ada323a9da8d152c8c8d7b834b Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 17 Jan 2020 00:19:58 +0100 Subject: [PATCH 088/881] Fix warnings in SessionManager --- .../ApplicationHost.cs | 13 +- .../Session/SessionManager.cs | 274 +++++++++--------- 2 files changed, 156 insertions(+), 131 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 0bb1d832fb..e93337c2fc 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -808,7 +808,18 @@ namespace Emby.Server.Implementations ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, ProviderManager); serviceCollection.AddSingleton(ChannelManager); - SessionManager = new SessionManager(UserDataManager, LoggerFactory, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, this, AuthenticationRepository, DeviceManager, MediaSourceManager); + SessionManager = new SessionManager( + LoggerFactory.CreateLogger(), + UserDataManager, + LibraryManager, + UserManager, + musicManager, + DtoService, + ImageProcessor, + this, + AuthenticationRepository, + DeviceManager, + MediaSourceManager); serviceCollection.AddSingleton(SessionManager); serviceCollection.AddSingleton( diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index b1d513dd4f..bb0836614e 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -30,17 +30,17 @@ using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Session { /// - /// Class SessionManager + /// Class SessionManager. /// public class SessionManager : ISessionManager, IDisposable { /// - /// The _user data repository + /// The _user data repository. /// private readonly IUserDataManager _userDataManager; /// - /// The _logger + /// The _logger. /// private readonly ILogger _logger; @@ -57,36 +57,19 @@ namespace Emby.Server.Implementations.Session private readonly IDeviceManager _deviceManager; /// - /// The _active connections + /// The _active connections. /// private readonly ConcurrentDictionary _activeConnections = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - public event EventHandler> AuthenticationFailed; + private Timer _idleTimer; - public event EventHandler> AuthenticationSucceeded; - - /// - /// Occurs when [playback start]. - /// - public event EventHandler PlaybackStart; - /// - /// Occurs when [playback progress]. - /// - public event EventHandler PlaybackProgress; - /// - /// Occurs when [playback stopped]. - /// - public event EventHandler PlaybackStopped; - - public event EventHandler SessionStarted; - public event EventHandler CapabilitiesChanged; - public event EventHandler SessionEnded; - public event EventHandler SessionActivity; + private DtoOptions _itemInfoDtoOptions; + private bool _disposed = false; public SessionManager( + ILogger logger, IUserDataManager userDataManager, - ILoggerFactory loggerFactory, ILibraryManager libraryManager, IUserManager userManager, IMusicManager musicManager, @@ -97,8 +80,8 @@ namespace Emby.Server.Implementations.Session IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager) { + _logger = logger; _userDataManager = userDataManager; - _logger = loggerFactory.CreateLogger(nameof(SessionManager)); _libraryManager = libraryManager; _userManager = userManager; _musicManager = musicManager; @@ -108,9 +91,49 @@ namespace Emby.Server.Implementations.Session _authRepo = authRepo; _deviceManager = deviceManager; _mediaSourceManager = mediaSourceManager; + _deviceManager.DeviceOptionsUpdated += OnDeviceManagerDeviceOptionsUpdated; } + /// + public event EventHandler> AuthenticationFailed; + + /// + public event EventHandler> AuthenticationSucceeded; + + /// + /// Occurs when [playback start]. + /// + public event EventHandler PlaybackStart; + + /// + /// Occurs when [playback progress]. + /// + public event EventHandler PlaybackProgress; + + /// + /// Occurs when [playback stopped]. + /// + public event EventHandler PlaybackStopped; + + /// + public event EventHandler SessionStarted; + + /// + public event EventHandler CapabilitiesChanged; + + /// + public event EventHandler SessionEnded; + + /// + public event EventHandler SessionActivity; + + /// + /// Gets all connections. + /// + /// All connections. + public IEnumerable Sessions => _activeConnections.Values.OrderByDescending(c => c.LastActivityDate); + private void OnDeviceManagerDeviceOptionsUpdated(object sender, GenericEventArgs> e) { foreach (var session in Sessions) @@ -130,14 +153,17 @@ namespace Emby.Server.Implementations.Session } } - private bool _disposed = false; - + /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } + /// + /// 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 disposing) { if (_disposed) @@ -147,15 +173,17 @@ namespace Emby.Server.Implementations.Session if (disposing) { - // TODO: dispose stuff + _idleTimer?.Dispose(); } + _idleTimer = null; + _deviceManager.DeviceOptionsUpdated -= OnDeviceManagerDeviceOptionsUpdated; _disposed = true; } - public void CheckDisposed() + private void CheckDisposed() { if (_disposed) { @@ -163,12 +191,6 @@ namespace Emby.Server.Implementations.Session } } - /// - /// Gets all connections. - /// - /// All connections. - public IEnumerable Sessions => _activeConnections.Values.OrderByDescending(c => c.LastActivityDate); - private void OnSessionStarted(SessionInfo info) { if (!string.IsNullOrEmpty(info.DeviceId)) @@ -199,13 +221,13 @@ namespace Emby.Server.Implementations.Session new SessionEventArgs { SessionInfo = info - }, _logger); info.Dispose(); } + /// public void UpdateDeviceName(string sessionId, string deviceName) { var session = GetSession(sessionId); @@ -225,7 +247,6 @@ namespace Emby.Server.Implementations.Session /// The remote end point. /// The user. /// SessionInfo. - /// user public SessionInfo LogSessionActivity( string appName, string appVersion, @@ -263,14 +284,7 @@ namespace Emby.Server.Implementations.Session if ((activityDate - userLastActivityDate).TotalSeconds > 60) { - try - { - _userManager.UpdateUser(user); - } - catch (Exception ex) - { - _logger.LogError("Error updating user", ex); - } + _userManager.UpdateUser(user); } } @@ -287,18 +301,20 @@ namespace Emby.Server.Implementations.Session return session; } + /// public void CloseIfNeeded(SessionInfo session) { if (!session.SessionControllers.Any(i => i.IsSessionActive)) { var key = GetSessionKey(session.Client, session.DeviceId); - _activeConnections.TryRemove(key, out var removed); + _activeConnections.TryRemove(key, out _); OnSessionEnded(session); } } + /// public void ReportSessionEnded(string sessionId) { CheckDisposed(); @@ -308,7 +324,7 @@ namespace Emby.Server.Implementations.Session { var key = GetSessionKey(session.Client, session.DeviceId); - _activeConnections.TryRemove(key, out var removed); + _activeConnections.TryRemove(key, out _); OnSessionEnded(session); } @@ -339,7 +355,7 @@ namespace Emby.Server.Implementations.Session var runtimeTicks = libraryItem.RunTimeTicks; MediaSourceInfo mediaSource = null; - if (libraryItem is IHasMediaSources hasMediaSources) + if (libraryItem is IHasMediaSources) { mediaSource = await GetMediaSource(libraryItem, info.MediaSourceId, info.LiveStreamId).ConfigureAwait(false); @@ -391,7 +407,6 @@ namespace Emby.Server.Implementations.Session /// Removes the now playing item id. /// /// The session. - /// item private void RemoveNowPlayingItem(SessionInfo session) { session.NowPlayingItem = null; @@ -404,9 +419,7 @@ namespace Emby.Server.Implementations.Session } private static string GetSessionKey(string appName, string deviceId) - { - return appName + deviceId; - } + => appName + deviceId; /// /// Gets the connection. @@ -426,6 +439,7 @@ namespace Emby.Server.Implementations.Session { throw new ArgumentNullException(nameof(deviceId)); } + var key = GetSessionKey(appName, deviceId); CheckDisposed(); @@ -498,7 +512,7 @@ namespace Emby.Server.Implementations.Session { var users = new List(); - if (!session.UserId.Equals(Guid.Empty)) + if (session.UserId != Guid.Empty) { var user = _userManager.GetUserById(session.UserId); @@ -517,8 +531,6 @@ namespace Emby.Server.Implementations.Session return users; } - private Timer _idleTimer; - private void StartIdleCheckTimer() { if (_idleTimer == null) @@ -594,11 +606,11 @@ namespace Emby.Server.Implementations.Session } /// - /// Used to report that playback has started for an item + /// Used to report that playback has started for an item. /// /// The info. /// Task. - /// info + /// info is null. public async Task OnPlaybackStart(PlaybackStartInfo info) { CheckDisposed(); @@ -610,7 +622,7 @@ namespace Emby.Server.Implementations.Session var session = GetSession(info.SessionId); - var libraryItem = info.ItemId.Equals(Guid.Empty) + var libraryItem = info.ItemId == Guid.Empty ? null : GetNowPlayingItem(session, info.ItemId); @@ -648,7 +660,6 @@ namespace Emby.Server.Implementations.Session ClientName = session.Client, DeviceId = session.DeviceId, Session = session - }, _logger); @@ -679,13 +690,14 @@ namespace Emby.Server.Implementations.Session _userDataManager.SaveUserData(user, item, data, UserDataSaveReason.PlaybackStart, CancellationToken.None); } + /// public Task OnPlaybackProgress(PlaybackProgressInfo info) { return OnPlaybackProgress(info, false); } /// - /// Used to report playback progress for an item + /// Used to report playback progress for an item. /// /// Task. public async Task OnPlaybackProgress(PlaybackProgressInfo info, bool isAutomated) @@ -852,7 +864,7 @@ namespace Emby.Server.Implementations.Session { MediaSourceInfo mediaSource = null; - if (libraryItem is IHasMediaSources hasMediaSources) + if (libraryItem is IHasMediaSources) { mediaSource = await GetMediaSource(libraryItem, info.MediaSourceId, info.LiveStreamId).ConfigureAwait(false); } @@ -924,7 +936,6 @@ namespace Emby.Server.Implementations.Session ClientName = session.Client, DeviceId = session.DeviceId, Session = session - }, _logger); } @@ -962,13 +973,17 @@ namespace Emby.Server.Implementations.Session /// The session identifier. /// if set to true [throw on missing]. /// SessionInfo. - /// sessionId + /// + /// No session with an Id equal to sessionId was found + /// and throwOnMissing is true. + /// private SessionInfo GetSession(string sessionId, bool throwOnMissing = true) { var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId, StringComparison.Ordinal)); if (session == null && throwOnMissing) { - throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId)); + throw new ResourceNotFoundException( + string.Format(CultureInfo.InvariantCulture, "Session {0} not found.", sessionId)); } return session; @@ -981,12 +996,14 @@ namespace Emby.Server.Implementations.Session if (session == null) { - throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId)); + throw new ResourceNotFoundException( + string.Format(CultureInfo.InvariantCulture, "Session {0} not found.", sessionId)); } return session; } + /// public Task SendMessageCommand(string controllingSessionId, string sessionId, MessageCommand command, CancellationToken cancellationToken) { CheckDisposed(); @@ -1007,6 +1024,7 @@ namespace Emby.Server.Implementations.Session return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken); } + /// public Task SendGeneralCommand(string controllingSessionId, string sessionId, GeneralCommand command, CancellationToken cancellationToken) { CheckDisposed(); @@ -1051,6 +1069,7 @@ namespace Emby.Server.Implementations.Session return Task.WhenAll(GetTasks()); } + /// public async Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken) { CheckDisposed(); @@ -1092,7 +1111,8 @@ namespace Emby.Server.Implementations.Session { if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full)) { - throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name)); + throw new ArgumentException( + string.Format(CultureInfo.InvariantCulture, "{0} is not allowed to play media.", user.Name)); } } @@ -1200,6 +1220,7 @@ namespace Emby.Server.Implementations.Session return _musicManager.GetInstantMixFromItem(item, user, new DtoOptions(false) { EnableImages = false }); } + /// public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken) { var generalCommand = new GeneralCommand @@ -1216,6 +1237,7 @@ namespace Emby.Server.Implementations.Session return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken); } + /// public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken) { CheckDisposed(); @@ -1299,12 +1321,12 @@ namespace Emby.Server.Implementations.Session var session = GetSession(sessionId); - if (session.UserId.Equals(userId)) + if (session.UserId == userId) { throw new ArgumentException("The requested user is already the primary user of the session."); } - if (session.AdditionalUsers.All(i => !i.UserId.Equals(userId))) + if (session.AdditionalUsers.All(i => i.UserId != userId)) { var user = _userManager.GetUserById(userId); @@ -1430,19 +1452,19 @@ namespace Emby.Server.Implementations.Session private string GetAuthorizationToken(User user, string deviceId, string app, string appVersion, string deviceName) { - var existing = _authRepo.Get(new AuthenticationInfoQuery - { - DeviceId = deviceId, - UserId = user.Id, - Limit = 1 + var existing = _authRepo.Get( + new AuthenticationInfoQuery + { + DeviceId = deviceId, + UserId = user.Id, + Limit = 1 + }).Items.FirstOrDefault(); - }).Items.FirstOrDefault(); - - var allExistingForDevice = _authRepo.Get(new AuthenticationInfoQuery - { - DeviceId = deviceId - - }).Items; + var allExistingForDevice = _authRepo.Get( + new AuthenticationInfoQuery + { + DeviceId = deviceId + }).Items; foreach (var auth in allExistingForDevice) { @@ -1461,7 +1483,7 @@ namespace Emby.Server.Implementations.Session if (existing != null) { - _logger.LogInformation("Reissuing access token: " + existing.AccessToken); + _logger.LogInformation("Reissuing access token: {Token}", existing.AccessToken); return existing.AccessToken; } @@ -1486,6 +1508,7 @@ namespace Emby.Server.Implementations.Session return newToken.AccessToken; } + /// public void Logout(string accessToken) { CheckDisposed(); @@ -1495,19 +1518,20 @@ namespace Emby.Server.Implementations.Session throw new ArgumentNullException(nameof(accessToken)); } - var existing = _authRepo.Get(new AuthenticationInfoQuery - { - Limit = 1, - AccessToken = accessToken + var existing = _authRepo.Get( + new AuthenticationInfoQuery + { + Limit = 1, + AccessToken = accessToken + }).Items; - }).Items.FirstOrDefault(); - - if (existing != null) + if (existing.Count > 0) { - Logout(existing); + Logout(existing[0]); } } + /// public void Logout(AuthenticationInfo existing) { CheckDisposed(); @@ -1533,6 +1557,7 @@ namespace Emby.Server.Implementations.Session } } + /// public void RevokeUserTokens(Guid userId, string currentAccessToken) { CheckDisposed(); @@ -1551,6 +1576,7 @@ namespace Emby.Server.Implementations.Session } } + /// public void RevokeToken(string token) { Logout(token); @@ -1607,10 +1633,8 @@ namespace Emby.Server.Implementations.Session _deviceManager.SaveCapabilities(deviceId, capabilities); } - private DtoOptions _itemInfoDtoOptions; - /// - /// Converts a BaseItem to a BaseItemInfo + /// Converts a BaseItem to a BaseItemInfo. /// private BaseItemDto GetItemInfo(BaseItem item, MediaSourceInfo mediaSource) { @@ -1685,6 +1709,7 @@ namespace Emby.Server.Implementations.Session } } + /// public void ReportNowViewingItem(string sessionId, string itemId) { if (string.IsNullOrEmpty(itemId)) @@ -1692,23 +1717,26 @@ namespace Emby.Server.Implementations.Session throw new ArgumentNullException(nameof(itemId)); } - //var item = _libraryManager.GetItemById(new Guid(itemId)); + var item = _libraryManager.GetItemById(new Guid(itemId)); - //var info = GetItemInfo(item, null, null); + var info = GetItemInfo(item, null); - //ReportNowViewingItem(sessionId, info); + ReportNowViewingItem(sessionId, info); } + /// public void ReportNowViewingItem(string sessionId, BaseItemDto item) { - //var session = GetSession(sessionId); + throw new NotImplementedException(); - //session.NowViewingItem = item; + // var session = GetSession(sessionId); + // session.NowViewingItem = item; } + /// public void ReportTranscodingInfo(string deviceId, TranscodingInfo info) { - var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId)); + var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId, StringComparison.Ordinal)); if (session != null) { @@ -1716,17 +1744,18 @@ namespace Emby.Server.Implementations.Session } } + /// public void ClearTranscodingInfo(string deviceId) { ReportTranscodingInfo(deviceId, null); } + /// public SessionInfo GetSession(string deviceId, string client, string version) - { - return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) && - string.Equals(i.Client, client)); - } + => Sessions.FirstOrDefault( + i => string.Equals(i.DeviceId, deviceId, StringComparison.Ordinal) && string.Equals(i.Client, client, StringComparison.Ordinal)); + /// public SessionInfo GetSessionByAuthenticationToken(AuthenticationInfo info, string deviceId, string remoteEndpoint, string appVersion) { if (info == null) @@ -1759,23 +1788,24 @@ namespace Emby.Server.Implementations.Session return LogSessionActivity(appName, appVersion, deviceId, deviceName, remoteEndpoint, user); } + /// public SessionInfo GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint) { - var result = _authRepo.Get(new AuthenticationInfoQuery + var items = _authRepo.Get(new AuthenticationInfoQuery { - AccessToken = token - }); + AccessToken = token, + Limit = 1 + }).Items; - var info = result.Items.FirstOrDefault(); - - if (info == null) + if (items.Count == 0) { return null; } - return GetSessionByAuthenticationToken(info, deviceId, remoteEndpoint, null); + return GetSessionByAuthenticationToken(items[0], deviceId, remoteEndpoint, null); } + /// public Task SendMessageToAdminSessions(string name, T data, CancellationToken cancellationToken) { CheckDisposed(); @@ -1785,6 +1815,7 @@ namespace Emby.Server.Implementations.Session return SendMessageToUserSessions(adminUserIds, name, data, cancellationToken); } + /// public Task SendMessageToUserSessions(List userIds, string name, Func dataFn, CancellationToken cancellationToken) { CheckDisposed(); @@ -1796,11 +1827,10 @@ namespace Emby.Server.Implementations.Session return Task.CompletedTask; } - var data = dataFn(); - - return SendMessageToSessions(sessions, name, data, cancellationToken); + return SendMessageToSessions(sessions, name, dataFn(), cancellationToken); } + /// public Task SendMessageToUserSessions(List userIds, string name, T data, CancellationToken cancellationToken) { CheckDisposed(); @@ -1809,6 +1839,7 @@ namespace Emby.Server.Implementations.Session return SendMessageToSessions(sessions, name, data, cancellationToken); } + /// public Task SendMessageToUserDeviceSessions(string deviceId, string name, T data, CancellationToken cancellationToken) { CheckDisposed(); @@ -1817,22 +1848,5 @@ namespace Emby.Server.Implementations.Session return SendMessageToSessions(sessions, name, data, cancellationToken); } - - public Task SendMessageToUserDeviceAndAdminSessions(string deviceId, string name, T data, CancellationToken cancellationToken) - { - CheckDisposed(); - - var sessions = Sessions - .Where(i => string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase) || IsAdminSession(i)); - - return SendMessageToSessions(sessions, name, data, cancellationToken); - } - - private bool IsAdminSession(SessionInfo s) - { - var user = _userManager.GetUserById(s.UserId); - - return user != null && user.Policy.IsAdministrator; - } } } From 73a47e934d1699c5969167c0b614216f108defd3 Mon Sep 17 00:00:00 2001 From: artiume Date: Fri, 17 Jan 2020 00:35:41 -0500 Subject: [PATCH 089/881] Fix Docker Arm Nightly (#2286) * Fix Docker Arm Nightly Updated image base. There was an error for libssl missing. I attempted to add libssl1.0.0 but it wasn't found so I fell back to libssl-dev. Much more work needs to be done. ffmpeg is still debian based. I attempted to add jellyfin-ffmpeg but I was having too many issues so I'm saving it for another day, but it at least builds out successfully. * Fix docker arm64 nightly --- Dockerfile.arm | 3 ++- Dockerfile.arm64 | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Dockerfile.arm b/Dockerfile.arm index 4d8fbb77d1..0e62366288 100644 --- a/Dockerfile.arm +++ b/Dockerfile.arm @@ -24,10 +24,11 @@ RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" FROM multiarch/qemu-user-static:x86_64-arm as qemu -FROM debian:stretch-slim-arm32v7 +FROM debian:stretch-slim 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 \ + libssl-dev \ && rm -rf /var/lib/apt/lists/* \ && mkdir -p /cache /config /media \ && chmod 777 /cache /config /media diff --git a/Dockerfile.arm64 b/Dockerfile.arm64 index d41268f13e..796d12f980 100644 --- a/Dockerfile.arm64 +++ b/Dockerfile.arm64 @@ -24,10 +24,11 @@ RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" FROM multiarch/qemu-user-static:x86_64-aarch64 as qemu -FROM debian:stretch-slim-arm64v8 +FROM debian:stretch-slim 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 \ + libssl-dev \ && rm -rf /var/lib/apt/lists/* \ && mkdir -p /cache /config /media \ && chmod 777 /cache /config /media From 8e71046a3c7b2e39bbdbfda8518730df21120ef8 Mon Sep 17 00:00:00 2001 From: 4d1m Date: Thu, 16 Jan 2020 08:34:40 +0000 Subject: [PATCH 090/881] Translated using Weblate (Romanian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ro/ --- Emby.Server.Implementations/Localization/Core/ro.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ro.json b/Emby.Server.Implementations/Localization/Core/ro.json index 1a4756e3de..71bffffc6b 100644 --- a/Emby.Server.Implementations/Localization/Core/ro.json +++ b/Emby.Server.Implementations/Localization/Core/ro.json @@ -66,7 +66,7 @@ "ItemRemovedWithName": "{0} a fost eliminat din bibliotecă", "ItemAddedWithName": "{0} a fost adăugat în bibliotecă", "Inherit": "Moștenit", - "HomeVideos": "Videoclipuri personale", + "HomeVideos": "Filme personale", "HeaderRecordingGroups": "Grupuri de înregistrare", "HeaderLiveTV": "TV în Direct", "HeaderFavoriteSongs": "Melodii Favorite", From 549a2d8b6d51d9ea8c3a319e3ca37da8ea4c088c Mon Sep 17 00:00:00 2001 From: Denis Date: Fri, 17 Jan 2020 22:48:28 +0300 Subject: [PATCH 091/881] Enable path mapping in `PlaybackInfo` endpoint --- MediaBrowser.Api/Playback/MediaInfoService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 10f10a15ec..15880a9a16 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -275,7 +275,7 @@ namespace MediaBrowser.Api.Playback { // TODO handle supportedLiveMediaTypes? - var mediaSourcesList = await _mediaSourceManager.GetPlaybackMediaSources(item, user, true, false, CancellationToken.None).ConfigureAwait(false); + var mediaSourcesList = await _mediaSourceManager.GetPlaybackMediaSources(item, user, true, true, CancellationToken.None).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(mediaSourceId)) { From 2610f377c0a15788badffd0720175109117af1ed Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 18 Jan 2020 00:09:25 +0100 Subject: [PATCH 092/881] Kestrel doesn't like sync IO operations --- Emby.Dlna/Service/BaseControlHandler.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs index 067d5fa43f..79f03fed9f 100644 --- a/Emby.Dlna/Service/BaseControlHandler.cs +++ b/Emby.Dlna/Service/BaseControlHandler.cs @@ -63,7 +63,8 @@ namespace Emby.Dlna.Service ValidationType = ValidationType.None, CheckCharacters = false, IgnoreProcessingInstructions = true, - IgnoreComments = true + IgnoreComments = true, + Async = true }; using (var reader = XmlReader.Create(streamReader, readerSettings)) @@ -79,7 +80,8 @@ namespace Emby.Dlna.Service var settings = new XmlWriterSettings { Encoding = Encoding.UTF8, - CloseOutput = false + CloseOutput = false, + Async = true }; StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8); From e700fc8a076769d8f2bc29dac232a2bf8faaa0cf Mon Sep 17 00:00:00 2001 From: dkanada Date: Sun, 19 Jan 2020 00:18:55 +0900 Subject: [PATCH 093/881] fix and remove a few more tests --- Emby.Naming/Subtitles/SubtitleParser.cs | 3 +-- Emby.Naming/TV/EpisodePathParser.cs | 2 +- .../Music/MultiDiscAlbumTests.cs | 21 ++++++++++----- .../Subtitles/SubtitleParserTests.cs | 1 - .../TV/EpisodeNumberTests.cs | 27 +++---------------- ...llyfin.Server.Implementations.Tests.csproj | 2 -- 6 files changed, 21 insertions(+), 35 deletions(-) diff --git a/Emby.Naming/Subtitles/SubtitleParser.cs b/Emby.Naming/Subtitles/SubtitleParser.cs index 99680c6221..b055b1a6c2 100644 --- a/Emby.Naming/Subtitles/SubtitleParser.cs +++ b/Emby.Naming/Subtitles/SubtitleParser.cs @@ -31,7 +31,6 @@ namespace Emby.Naming.Subtitles } var flags = GetFlags(path); - var info = new SubtitleInfo { Path = path, @@ -45,7 +44,7 @@ namespace Emby.Naming.Subtitles // Should have a name, language and file extension if (parts.Count >= 3) { - info.Language = parts[parts.Count - 2]; + info.Language = parts[^2]; } return info; diff --git a/Emby.Naming/TV/EpisodePathParser.cs b/Emby.Naming/TV/EpisodePathParser.cs index 4fac543f92..6b557d2e19 100644 --- a/Emby.Naming/TV/EpisodePathParser.cs +++ b/Emby.Naming/TV/EpisodePathParser.cs @@ -131,7 +131,7 @@ namespace Emby.Naming.TV var endingNumberGroup = match.Groups["endingepnumber"]; if (endingNumberGroup.Success) { - // Will only set EndingEpsiodeNumber if the captured number is not followed by additional numbers + // Will only set EndingEpisodeNumber if the captured number is not followed by additional numbers // or a 'p' or 'i' as what you would get with a pixel resolution specification. // It avoids erroneous parsing of something like "series-s09e14-1080p.mkv" as a multi-episode from E14 to E108 int nextIndex = endingNumberGroup.Index + endingNumberGroup.Length; diff --git a/tests/Jellyfin.Naming.Tests/Music/MultiDiscAlbumTests.cs b/tests/Jellyfin.Naming.Tests/Music/MultiDiscAlbumTests.cs index eb69d915ca..a79e2cf614 100644 --- a/tests/Jellyfin.Naming.Tests/Music/MultiDiscAlbumTests.cs +++ b/tests/Jellyfin.Naming.Tests/Music/MultiDiscAlbumTests.cs @@ -10,18 +10,27 @@ namespace Jellyfin.Naming.Tests.Music public void TestMultiDiscAlbums() { Assert.False(IsMultiDiscAlbumFolder(@"blah blah")); - Assert.False(IsMultiDiscAlbumFolder(@"d:/music\weezer/03 Pinkerton")); - Assert.False(IsMultiDiscAlbumFolder(@"d:/music/michael jackson/Bad (2012 Remaster)")); + Assert.False(IsMultiDiscAlbumFolder(@"D:/music/weezer/03 Pinkerton")); + Assert.False(IsMultiDiscAlbumFolder(@"D:/music/michael jackson/Bad (2012 Remaster)")); Assert.True(IsMultiDiscAlbumFolder(@"cd1")); - Assert.True(IsMultiDiscAlbumFolder(@"disc1")); - Assert.True(IsMultiDiscAlbumFolder(@"disk1")); + Assert.True(IsMultiDiscAlbumFolder(@"disc18")); + Assert.True(IsMultiDiscAlbumFolder(@"disk10")); + Assert.True(IsMultiDiscAlbumFolder(@"vol7")); + Assert.True(IsMultiDiscAlbumFolder(@"volume1")); - // Add a space Assert.True(IsMultiDiscAlbumFolder(@"cd 1")); Assert.True(IsMultiDiscAlbumFolder(@"disc 1")); Assert.True(IsMultiDiscAlbumFolder(@"disk 1")); + Assert.False(IsMultiDiscAlbumFolder(@"disk")); + Assert.False(IsMultiDiscAlbumFolder(@"disk ·")); + Assert.False(IsMultiDiscAlbumFolder(@"disk a")); + + Assert.False(IsMultiDiscAlbumFolder(@"disk volume")); + Assert.False(IsMultiDiscAlbumFolder(@"disc disc")); + Assert.False(IsMultiDiscAlbumFolder(@"disk disc 6")); + Assert.True(IsMultiDiscAlbumFolder(@"cd - 1")); Assert.True(IsMultiDiscAlbumFolder(@"disc- 1")); Assert.True(IsMultiDiscAlbumFolder(@"disk - 1")); @@ -38,7 +47,7 @@ namespace Jellyfin.Naming.Tests.Music [Fact] public void TestMultiDiscAlbums1() { - Assert.False(IsMultiDiscAlbumFolder(@"[1985] Oppurtunities (Let's make lots of money) (1985)")); + Assert.False(IsMultiDiscAlbumFolder(@"[1985] Opportunities (Let's make lots of money) (1985)")); } [Fact] diff --git a/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs b/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs index e8f14cdc45..41da889c28 100644 --- a/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs +++ b/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs @@ -22,7 +22,6 @@ namespace Jellyfin.Naming.Tests.Subtitles Test("The Skin I Live In (2011).eng.forced.srt", "eng", false, true); Test("The Skin I Live In (2011).eng.foreign.srt", "eng", false, true); Test("The Skin I Live In (2011).eng.default.foreign.srt", "eng", true, true); - Test("The Skin I Live In (2011).default.foreign.eng.srt", "eng", true, true); } diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs index 1ae6372817..837b23455c 100644 --- a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs @@ -60,21 +60,6 @@ namespace Jellyfin.Naming.Tests.TV Assert.Equal(36, GetEpisodeNumberFromFile(@"Season 2/[HorribleSubs] Hunter X Hunter - 136 [720p].mkv")); } - [Fact] - public void TestEpisodeNumber50() - { - // This convention is not currently supported, just adding in case we want to look at it in the future - Assert.Equal(1, GetEpisodeNumberFromFile(@"2016/Season s2016e1.mp4")); - } - - // FIXME - // [Fact] - public void TestEpisodeNumber51() - { - // This convention is not currently supported, just adding in case we want to look at it in the future - Assert.Equal(1, GetEpisodeNumberFromFile(@"2016/Season 2016x1.mp4")); - } - [Fact] public void TestEpisodeNumber52() { @@ -84,29 +69,25 @@ namespace Jellyfin.Naming.Tests.TV [Fact] public void TestEpisodeNumber53() { - // This is not supported. Expected to fail, although it would be a good one to add support for. Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Episode 16.avi")); } [Fact] public void TestEpisodeNumber54() { - // This is not supported. Expected to fail, although it would be a good one to add support for. Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Episode 16 - Some Title.avi")); } - // [Fact] + [Fact] public void TestEpisodeNumber55() { - // This is not supported. Expected to fail, although it would be a good one to add support for. - Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Season 3 Episode 16.avi")); + Assert.NotEqual(16, GetEpisodeNumberFromFile(@"Season 2/Season 3 Episode 16.avi")); } - // [Fact] + [Fact] public void TestEpisodeNumber56() { - // This is not supported. Expected to fail, although it would be a good one to add support for. - Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Season 3 Episode 16 - Some Title.avi")); + Assert.NotEqual(16, GetEpisodeNumberFromFile(@"Season 2/Season 3 Episode 16 - Some Title.avi")); } [Fact] diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index bb2afea168..f62d3dcbc5 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -2,9 +2,7 @@ netcoreapp3.1 - false - Jellyfin.Server.Implementations.Tests From a562a4d5053edd2943f22dfb45f7ad5bb0ae8cfa Mon Sep 17 00:00:00 2001 From: dkanada Date: Sun, 19 Jan 2020 00:19:19 +0900 Subject: [PATCH 094/881] minor linting for ci files --- .ci/azure-pipelines-compat.yml | 2 +- .ci/azure-pipelines-main.yml | 18 +++++++++--------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.ci/azure-pipelines-compat.yml b/.ci/azure-pipelines-compat.yml index 6af956e1a7..762bbdcb2e 100644 --- a/.ci/azure-pipelines-compat.yml +++ b/.ci/azure-pipelines-compat.yml @@ -13,7 +13,7 @@ jobs: - job: CompatibilityCheck displayName: Compatibility Check pool: - vmImage: "${{ parameters.LinuxImage}}" + vmImage: "${{ parameters.LinuxImage }}" # only execute for pull requests condition: and(succeeded(), variables['System.PullRequest.PullRequestNumber']) strategy: diff --git a/.ci/azure-pipelines-main.yml b/.ci/azure-pipelines-main.yml index 9880bbfaa2..09901b2a6a 100644 --- a/.ci/azure-pipelines-main.yml +++ b/.ci/azure-pipelines-main.yml @@ -23,32 +23,32 @@ jobs: - task: CmdLine@2 displayName: "Clone Web Client (Master, Release, or Tag)" - 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')) + condition: and(succeeded(), or(contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')), eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'IndividualCI', 'BatchedCI', 'BuildCompletion')) inputs: script: "git clone --single-branch --branch $(Build.SourceBranchName) --depth=1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web" - task: CmdLine@2 displayName: "Clone Web Client (PR)" - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest')) + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master')), eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest')) inputs: script: "git clone --single-branch --branch $(System.PullRequest.TargetBranch) --depth 1 https://github.com/jellyfin/jellyfin-web.git $(Agent.TempDirectory)/jellyfin-web" - task: NodeTool@0 displayName: "Install Node" - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')), eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) inputs: versionSpec: "10.x" - task: CmdLine@2 displayName: "Build Web Client" - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')), eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) inputs: script: yarn install workingDirectory: $(Agent.TempDirectory)/jellyfin-web - task: CopyFiles@2 displayName: "Copy Web Client" - condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')) ,eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) + condition: and(succeeded(), or(contains(variables['System.PullRequest.TargetBranch'], 'release'), contains(variables['System.PullRequest.TargetBranch'], 'master'), contains(variables['Build.SourceBranch'], 'release'), contains(variables['Build.SourceBranch'], 'master')), eq(variables['BuildConfiguration'], 'Release'), in(variables['Build.Reason'], 'PullRequest', 'IndividualCI', 'BatchedCI', 'BuildCompletion')) inputs: sourceFolder: $(Agent.TempDirectory)/jellyfin-web/dist contents: "**" @@ -74,28 +74,28 @@ jobs: - task: PublishPipelineArtifact@0 displayName: "Publish Artifact Naming" - condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) + condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release')) inputs: targetPath: "$(build.artifactstagingdirectory)/Jellyfin.Server/Emby.Naming.dll" artifactName: "Jellyfin.Naming" - task: PublishPipelineArtifact@0 displayName: "Publish Artifact Controller" - condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) + condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release')) inputs: targetPath: "$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Controller.dll" artifactName: "Jellyfin.Controller" - task: PublishPipelineArtifact@0 displayName: "Publish Artifact Model" - condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) + condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release')) inputs: targetPath: "$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Model.dll" artifactName: "Jellyfin.Model" - task: PublishPipelineArtifact@0 displayName: "Publish Artifact Common" - condition: and(eq(variables['BuildConfiguration'], 'Release'), succeeded()) + condition: and(succeeded(), eq(variables['BuildConfiguration'], 'Release')) inputs: targetPath: "$(build.artifactstagingdirectory)/Jellyfin.Server/MediaBrowser.Common.dll" artifactName: "Jellyfin.Common" From f2eea89ff084111a4a90bfefdb6def68165e6025 Mon Sep 17 00:00:00 2001 From: Carey Metcalfe Date: Sun, 19 Jan 2020 00:51:02 -0500 Subject: [PATCH 095/881] Fix pagination for DLNA root folder list Previously, when responding to a DLNA "Browse" request, the `StartingIndex` was not respected and all of the root items were returned each time. This caused infinite loops with in DLNA clients that ignored the `TotalMatches` data in the response and just continued asking for the next page until they got an empty response. This fix makes the root folder list respect the `StartingIndex` and `RequestedCount` parameters like all other responses. Fixes issue #2303 --- CONTRIBUTORS.md | 1 + Emby.Dlna/ContentDirectory/ControlHandler.cs | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 458944778e..800b3d51ff 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -32,6 +32,7 @@ - [nevado](https://github.com/nevado) - [mark-monteiro](https://github.com/mark-monteiro) - [ullmie02](https://github.com/ullmie02) + - [pR0Ps](https://github.com/pR0Ps) # Emby Contributors diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs index 4f74bb222e..2068e1d2aa 100644 --- a/Emby.Dlna/ContentDirectory/ControlHandler.cs +++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs @@ -771,11 +771,11 @@ namespace Emby.Dlna.ContentDirectory }) .ToArray(); - return new QueryResult + return ApplyPaging(new QueryResult { Items = folders, TotalRecordCount = folders.Length - }; + }, startIndex, limit); } private QueryResult GetTvFolders(BaseItem item, User user, StubType? stubType, SortCriteria sort, int? startIndex, int? limit) From 075dad87208fa7fdf2bdaaa54a7be842a038d422 Mon Sep 17 00:00:00 2001 From: Andrew Rabert <6550543+nvllsvm@users.noreply.github.com> Date: Sun, 19 Jan 2020 07:51:38 -0500 Subject: [PATCH 096/881] Fix ARM images (#2302) Allow for native building of Docker images. Use buildx if cross-compilation is needed. --- Dockerfile.arm | 4 ---- Dockerfile.arm64 | 4 ---- 2 files changed, 8 deletions(-) diff --git a/Dockerfile.arm b/Dockerfile.arm index 0e62366288..97e02a17d9 100644 --- a/Dockerfile.arm +++ b/Dockerfile.arm @@ -1,5 +1,3 @@ -# Requires binfm_misc registration -# https://github.com/multiarch/qemu-user-static#binfmt_misc-register ARG DOTNET_VERSION=3.1 @@ -23,9 +21,7 @@ RUN find . -type d -name obj | xargs -r rm -r RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" --self-contained --runtime linux-arm "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none" -FROM multiarch/qemu-user-static:x86_64-arm as qemu FROM debian:stretch-slim -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 \ libssl-dev \ diff --git a/Dockerfile.arm64 b/Dockerfile.arm64 index 796d12f980..445a39add7 100644 --- a/Dockerfile.arm64 +++ b/Dockerfile.arm64 @@ -1,5 +1,3 @@ -# Requires binfm_misc registration -# https://github.com/multiarch/qemu-user-static#binfmt_misc-register ARG DOTNET_VERSION=3.1 @@ -23,9 +21,7 @@ RUN find . -type d -name obj | xargs -r rm -r RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" --self-contained --runtime linux-arm64 "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none" -FROM multiarch/qemu-user-static:x86_64-aarch64 as qemu FROM debian:stretch-slim -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 \ libssl-dev \ From da2c998e28e8428cd96951eb58ced81ba59db32f Mon Sep 17 00:00:00 2001 From: Andrew Rabert <6550543+nvllsvm@users.noreply.github.com> Date: Sun, 19 Jan 2020 12:34:33 -0500 Subject: [PATCH 097/881] Update ARM images to debian buster (#2313) Also has the effect of updating ffmpeg to 4.1 --- Dockerfile.arm | 2 +- Dockerfile.arm64 | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Dockerfile.arm b/Dockerfile.arm index 97e02a17d9..551aa177a2 100644 --- a/Dockerfile.arm +++ b/Dockerfile.arm @@ -21,7 +21,7 @@ RUN find . -type d -name obj | xargs -r rm -r RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" --self-contained --runtime linux-arm "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none" -FROM debian:stretch-slim +FROM debian:buster-slim RUN apt-get update \ && apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \ libssl-dev \ diff --git a/Dockerfile.arm64 b/Dockerfile.arm64 index 445a39add7..4c2ca12a66 100644 --- a/Dockerfile.arm64 +++ b/Dockerfile.arm64 @@ -21,7 +21,7 @@ RUN find . -type d -name obj | xargs -r rm -r RUN dotnet publish Jellyfin.Server --configuration Release --output="/jellyfin" --self-contained --runtime linux-arm64 "-p:GenerateDocumentationFile=false;DebugSymbols=false;DebugType=none" -FROM debian:stretch-slim +FROM debian:buster-slim RUN apt-get update \ && apt-get install --no-install-recommends --no-install-suggests -y ffmpeg \ libssl-dev \ From 11c758b6bea2e15ac14b6b6975a5d2e83f55ae55 Mon Sep 17 00:00:00 2001 From: dkanada Date: Tue, 21 Jan 2020 00:20:24 +0900 Subject: [PATCH 098/881] remove unsupported test cases --- tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs index 837b23455c..93c59c9cab 100644 --- a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs @@ -78,18 +78,6 @@ namespace Jellyfin.Naming.Tests.TV Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Episode 16 - Some Title.avi")); } - [Fact] - public void TestEpisodeNumber55() - { - Assert.NotEqual(16, GetEpisodeNumberFromFile(@"Season 2/Season 3 Episode 16.avi")); - } - - [Fact] - public void TestEpisodeNumber56() - { - Assert.NotEqual(16, GetEpisodeNumberFromFile(@"Season 2/Season 3 Episode 16 - Some Title.avi")); - } - [Fact] public void TestEpisodeNumber57() { From ef487441d1545a21ff4e11d40c37a9ecf200f2e5 Mon Sep 17 00:00:00 2001 From: Waldemar Tomme Date: Tue, 21 Jan 2020 06:48:25 +0100 Subject: [PATCH 099/881] Remove configuration of global_header flag --- .../MediaEncoding/EncodingHelper.cs | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 424dd0dbe8..7022459461 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2750,8 +2750,6 @@ namespace MediaBrowser.Controller.MediaEncoding args += " -mpegts_m2ts_mode 1"; } - var supportsGlobalHeaderFlag = state.OutputContainer != "mkv"; - if (string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase)) { if (state.VideoStream != null @@ -2772,11 +2770,6 @@ namespace MediaBrowser.Controller.MediaEncoding if (!state.RunTimeTicks.HasValue) { - if(supportsGlobalHeaderFlag) - { - args += " -flags -global_header"; - } - args += " -fflags +genpts"; } } @@ -2822,11 +2815,6 @@ namespace MediaBrowser.Controller.MediaEncoding { args += " " + qualityParam.Trim(); } - - if (supportsGlobalHeaderFlag && !state.RunTimeTicks.HasValue) - { - args += " -flags -global_header"; - } } if (!string.IsNullOrEmpty(state.OutputVideoSync)) From ac3b958c6791a48217cda5625a68ffeb18fbcae6 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Tue, 21 Jan 2020 17:59:41 +0100 Subject: [PATCH 100/881] Use async methods --- Emby.Dlna/Api/DlnaServerService.cs | 16 ++-- .../ConnectionManager/ConnectionManager.cs | 7 +- .../ContentDirectory/ContentDirectory.cs | 7 +- Emby.Dlna/ContentDirectory/ControlHandler.cs | 4 +- Emby.Dlna/IUpnpService.cs | 4 +- .../MediaReceiverRegistrar.cs | 7 +- Emby.Dlna/Service/BaseControlHandler.cs | 94 ++++++++----------- Emby.Dlna/Service/ControlErrorHandler.cs | 4 +- 8 files changed, 68 insertions(+), 75 deletions(-) diff --git a/Emby.Dlna/Api/DlnaServerService.cs b/Emby.Dlna/Api/DlnaServerService.cs index a451bbcf91..a7ff6e9cfd 100644 --- a/Emby.Dlna/Api/DlnaServerService.cs +++ b/Emby.Dlna/Api/DlnaServerService.cs @@ -170,32 +170,32 @@ namespace Emby.Dlna.Api return _resultFactory.GetResult(Request, xml, XMLContentType); } - public object Post(ProcessMediaReceiverRegistrarControlRequest request) + public async Task Post(ProcessMediaReceiverRegistrarControlRequest request) { - var response = PostAsync(request.RequestStream, MediaReceiverRegistrar); + var response = await PostAsync(request.RequestStream, MediaReceiverRegistrar).ConfigureAwait(false); return _resultFactory.GetResult(Request, response.Xml, XMLContentType); } - public object Post(ProcessContentDirectoryControlRequest request) + public async Task Post(ProcessContentDirectoryControlRequest request) { - var response = PostAsync(request.RequestStream, ContentDirectory); + var response = await PostAsync(request.RequestStream, ContentDirectory).ConfigureAwait(false); return _resultFactory.GetResult(Request, response.Xml, XMLContentType); } - public object Post(ProcessConnectionManagerControlRequest request) + public async Task Post(ProcessConnectionManagerControlRequest request) { - var response = PostAsync(request.RequestStream, ConnectionManager); + var response = await PostAsync(request.RequestStream, ConnectionManager).ConfigureAwait(false); return _resultFactory.GetResult(Request, response.Xml, XMLContentType); } - private ControlResponse PostAsync(Stream requestStream, IUpnpService service) + private Task PostAsync(Stream requestStream, IUpnpService service) { var id = GetPathValue(2).ToString(); - return service.ProcessControlRequest(new ControlRequest + return service.ProcessControlRequestAsync(new ControlRequest { Headers = Request.Headers, InputXml = requestStream, diff --git a/Emby.Dlna/ConnectionManager/ConnectionManager.cs b/Emby.Dlna/ConnectionManager/ConnectionManager.cs index 83011fbabd..934b353c28 100644 --- a/Emby.Dlna/ConnectionManager/ConnectionManager.cs +++ b/Emby.Dlna/ConnectionManager/ConnectionManager.cs @@ -1,3 +1,4 @@ +using System.Threading.Tasks; using Emby.Dlna.Service; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; @@ -20,17 +21,19 @@ namespace Emby.Dlna.ConnectionManager _logger = logger; } + /// public string GetServiceXml() { return new ConnectionManagerXmlBuilder().GetXml(); } - public ControlResponse ProcessControlRequest(ControlRequest request) + /// + public Task ProcessControlRequestAsync(ControlRequest request) { var profile = _dlna.GetProfile(request.Headers) ?? _dlna.GetDefaultProfile(); - return new ControlHandler(_config, _logger, profile).ProcessControlRequest(request); + return new ControlHandler(_config, _logger, profile).ProcessControlRequestAsync(request); } } } diff --git a/Emby.Dlna/ContentDirectory/ContentDirectory.cs b/Emby.Dlna/ContentDirectory/ContentDirectory.cs index 78d69b3380..a3062b18fd 100644 --- a/Emby.Dlna/ContentDirectory/ContentDirectory.cs +++ b/Emby.Dlna/ContentDirectory/ContentDirectory.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Emby.Dlna.Service; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; @@ -66,12 +67,14 @@ namespace Emby.Dlna.ContentDirectory } } + /// public string GetServiceXml() { return new ContentDirectoryXmlBuilder().GetXml(); } - public ControlResponse ProcessControlRequest(ControlRequest request) + /// + public Task ProcessControlRequestAsync(ControlRequest request) { var profile = _dlna.GetProfile(request.Headers) ?? _dlna.GetDefaultProfile(); @@ -96,7 +99,7 @@ namespace Emby.Dlna.ContentDirectory _userViewManager, _mediaEncoder, _tvSeriesManager) - .ProcessControlRequest(request); + .ProcessControlRequestAsync(request); } private User GetUser(DeviceProfile profile) diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs index 4f74bb222e..7ed46984ad 100644 --- a/Emby.Dlna/ContentDirectory/ControlHandler.cs +++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs @@ -76,7 +76,7 @@ namespace Emby.Dlna.ContentDirectory _profile = profile; _config = config; - _didlBuilder = new DidlBuilder(profile, user, imageProcessor, serverAddress, accessToken, userDataManager, localization, mediaSourceManager, _logger, mediaEncoder); + _didlBuilder = new DidlBuilder(profile, user, imageProcessor, serverAddress, accessToken, userDataManager, localization, mediaSourceManager, Logger, mediaEncoder); } protected override IEnumerable> GetResult(string methodName, IDictionary methodParams) @@ -1336,7 +1336,7 @@ namespace Emby.Dlna.ContentDirectory }; } - _logger.LogError("Error parsing item Id: {id}. Returning user root folder.", id); + Logger.LogError("Error parsing item Id: {id}. Returning user root folder.", id); return new ServerItem(_libraryManager.GetUserRootFolder()); } diff --git a/Emby.Dlna/IUpnpService.cs b/Emby.Dlna/IUpnpService.cs index ae90e95c79..0f3d327ed2 100644 --- a/Emby.Dlna/IUpnpService.cs +++ b/Emby.Dlna/IUpnpService.cs @@ -1,3 +1,5 @@ +using System.Threading.Tasks; + namespace Emby.Dlna { public interface IUpnpService @@ -13,6 +15,6 @@ namespace Emby.Dlna /// /// The request. /// ControlResponse. - ControlResponse ProcessControlRequest(ControlRequest request); + Task ProcessControlRequestAsync(ControlRequest request); } } diff --git a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs index b565cb631e..5eab6aee0c 100644 --- a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs +++ b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs @@ -1,3 +1,4 @@ +using System.Threading.Tasks; using Emby.Dlna.Service; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; @@ -15,17 +16,19 @@ namespace Emby.Dlna.MediaReceiverRegistrar _config = config; } + /// public string GetServiceXml() { return new MediaReceiverRegistrarXmlBuilder().GetXml(); } - public ControlResponse ProcessControlRequest(ControlRequest request) + /// + public Task ProcessControlRequestAsync(ControlRequest request) { return new ControlHandler( _config, Logger) - .ProcessControlRequest(request); + .ProcessControlRequestAsync(request); } } } diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs index 79f03fed9f..d56f54149f 100644 --- a/Emby.Dlna/Service/BaseControlHandler.cs +++ b/Emby.Dlna/Service/BaseControlHandler.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; +using System.Threading.Tasks; using System.Xml; using Emby.Dlna.Didl; using MediaBrowser.Controller.Configuration; @@ -15,44 +16,34 @@ namespace Emby.Dlna.Service { private const string NS_SOAPENV = "http://schemas.xmlsoap.org/soap/envelope/"; - protected readonly IServerConfigurationManager Config; - protected readonly ILogger _logger; + protected IServerConfigurationManager Config { get; } + protected ILogger Logger { get; } protected BaseControlHandler(IServerConfigurationManager config, ILogger logger) { Config = config; - _logger = logger; + Logger = logger; } - public ControlResponse ProcessControlRequest(ControlRequest request) + public async Task ProcessControlRequestAsync(ControlRequest request) { try { - var enableDebugLogging = Config.GetDlnaConfiguration().EnableDebugLog; - - if (enableDebugLogging) - { - LogRequest(request); - } - - var response = ProcessControlRequestInternal(request); - - if (enableDebugLogging) - { - LogResponse(response); - } + LogRequest(request); + var response = await ProcessControlRequestInternalAsync(request).ConfigureAwait(false); + LogResponse(response); return response; } catch (Exception ex) { - _logger.LogError(ex, "Error processing control request"); + Logger.LogError(ex, "Error processing control request"); - return new ControlErrorHandler().GetResponse(ex); + return ControlErrorHandler.GetResponse(ex); } } - private ControlResponse ProcessControlRequestInternal(ControlRequest request) + private async Task ProcessControlRequestInternalAsync(ControlRequest request) { ControlRequestInfo requestInfo = null; @@ -69,19 +60,18 @@ namespace Emby.Dlna.Service using (var reader = XmlReader.Create(streamReader, readerSettings)) { - requestInfo = ParseRequest(reader); + requestInfo = await ParseRequestAsync(reader).ConfigureAwait(false); } } - _logger.LogDebug("Received control request {0}", requestInfo.LocalName); + Logger.LogDebug("Received control request {0}", requestInfo.LocalName); var result = GetResult(requestInfo.LocalName, requestInfo.Headers); var settings = new XmlWriterSettings { Encoding = Encoding.UTF8, - CloseOutput = false, - Async = true + CloseOutput = false }; StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8); @@ -116,17 +106,15 @@ namespace Emby.Dlna.Service IsSuccessful = true }; - //logger.LogDebug(xml); - controlResponse.Headers.Add("EXT", string.Empty); return controlResponse; } - private ControlRequestInfo ParseRequest(XmlReader reader) + private async Task ParseRequestAsync(XmlReader reader) { - reader.MoveToContent(); - reader.Read(); + await reader.MoveToContentAsync().ConfigureAwait(false); + await reader.ReadAsync().ConfigureAwait(false); // Loop through each element while (!reader.EOF && reader.ReadState == ReadState.Interactive) @@ -141,37 +129,38 @@ namespace Emby.Dlna.Service { using (var subReader = reader.ReadSubtree()) { - return ParseBodyTag(subReader); + return await ParseBodyTagAsync(subReader).ConfigureAwait(false); } } else { - reader.Read(); + await reader.ReadAsync().ConfigureAwait(false); } + break; } default: { - reader.Skip(); + await reader.SkipAsync().ConfigureAwait(false); break; } } } else { - reader.Read(); + await reader.ReadAsync().ConfigureAwait(false); } } return new ControlRequestInfo(); } - private ControlRequestInfo ParseBodyTag(XmlReader reader) + private async Task ParseBodyTagAsync(XmlReader reader) { var result = new ControlRequestInfo(); - reader.MoveToContent(); - reader.Read(); + await reader.MoveToContentAsync().ConfigureAwait(false); + await reader.ReadAsync().ConfigureAwait(false); // Loop through each element while (!reader.EOF && reader.ReadState == ReadState.Interactive) @@ -185,28 +174,28 @@ namespace Emby.Dlna.Service { using (var subReader = reader.ReadSubtree()) { - ParseFirstBodyChild(subReader, result.Headers); + await ParseFirstBodyChildAsync(subReader, result.Headers).ConfigureAwait(false); return result; } } else { - reader.Read(); + await reader.ReadAsync().ConfigureAwait(false); } } else { - reader.Read(); + await reader.ReadAsync().ConfigureAwait(false); } } return result; } - private void ParseFirstBodyChild(XmlReader reader, IDictionary headers) + private async Task ParseFirstBodyChildAsync(XmlReader reader, IDictionary headers) { - reader.MoveToContent(); - reader.Read(); + await reader.MoveToContentAsync().ConfigureAwait(false); + await reader.ReadAsync().ConfigureAwait(false); // Loop through each element while (!reader.EOF && reader.ReadState == ReadState.Interactive) @@ -214,20 +203,20 @@ namespace Emby.Dlna.Service if (reader.NodeType == XmlNodeType.Element) { // TODO: Should we be doing this here, or should it be handled earlier when decoding the request? - headers[reader.LocalName.RemoveDiacritics()] = reader.ReadElementContentAsString(); + headers[reader.LocalName.RemoveDiacritics()] = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); } else { - reader.Read(); + await reader.ReadAsync().ConfigureAwait(false); } } } private class ControlRequestInfo { - public string LocalName; - public string NamespaceURI; - public IDictionary Headers = new Dictionary(StringComparer.OrdinalIgnoreCase); + public string LocalName { get; set; } + public string NamespaceURI { get; set; } + public Dictionary Headers { get; } = new Dictionary(StringComparer.OrdinalIgnoreCase); } protected abstract IEnumerable> GetResult(string methodName, IDictionary methodParams); @@ -239,10 +228,7 @@ namespace Emby.Dlna.Service return; } - var originalHeaders = request.Headers; - var headers = string.Join(", ", originalHeaders.Select(i => string.Format("{0}={1}", i.Key, i.Value)).ToArray()); - - _logger.LogDebug("Control request. Headers: {0}", headers); + Logger.LogDebug("Control request. Headers: {@Header}", request.Headers); } private void LogResponse(ControlResponse response) @@ -252,11 +238,7 @@ namespace Emby.Dlna.Service return; } - var originalHeaders = response.Headers; - var headers = string.Join(", ", originalHeaders.Select(i => string.Format("{0}={1}", i.Key, i.Value)).ToArray()); - //builder.Append(response.Xml); - - _logger.LogDebug("Control response. Headers: {0}", headers); + Logger.LogDebug("Control response. Headers: {@Headers}\n{Xml}", response.Headers, response.Xml); } } } diff --git a/Emby.Dlna/Service/ControlErrorHandler.cs b/Emby.Dlna/Service/ControlErrorHandler.cs index d5eb4a8879..bbf975f384 100644 --- a/Emby.Dlna/Service/ControlErrorHandler.cs +++ b/Emby.Dlna/Service/ControlErrorHandler.cs @@ -6,11 +6,11 @@ using Emby.Dlna.Didl; namespace Emby.Dlna.Service { - public class ControlErrorHandler + public static class ControlErrorHandler { private const string NS_SOAPENV = "http://schemas.xmlsoap.org/soap/envelope/"; - public ControlResponse GetResponse(Exception ex) + public static ControlResponse GetResponse(Exception ex) { var settings = new XmlWriterSettings { From ddf9b38799fa4a0e227ae3c2516a72ec48f13854 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 21 Jan 2020 20:26:30 +0100 Subject: [PATCH 101/881] Simplify image processing by removing image enhancers --- Emby.Drawing/Emby.Drawing.csproj | 12 + Emby.Drawing/ImageProcessor.cs | 353 ++---------------- .../ApplicationHost.cs | 2 - Emby.Server.Implementations/Dto/DtoService.cs | 51 +-- Jellyfin.Drawing.Skia/SkiaEncoder.cs | 20 +- Jellyfin.Server/Program.cs | 11 +- MediaBrowser.Api/Images/ImageService.cs | 26 +- .../Drawing/IImageProcessor.cs | 35 -- .../Drawing/ImageHelper.cs | 2 - .../Drawing/ImageProcessingOptions.cs | 3 - .../MediaEncoding/EncodingJobInfo.cs | 12 +- .../Providers/IImageEnhancer.cs | 61 --- MediaBrowser.Model/Drawing/ImageDimensions.cs | 37 +- 13 files changed, 103 insertions(+), 522 deletions(-) delete mode 100644 MediaBrowser.Controller/Providers/IImageEnhancer.cs diff --git a/Emby.Drawing/Emby.Drawing.csproj b/Emby.Drawing/Emby.Drawing.csproj index 85cecdc44e..b7090b2629 100644 --- a/Emby.Drawing/Emby.Drawing.csproj +++ b/Emby.Drawing/Emby.Drawing.csproj @@ -17,4 +17,16 @@ + + + + + + + + + + ../jellyfin.ruleset + + diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs index ce8089e59c..8f68509364 100644 --- a/Emby.Drawing/ImageProcessor.cs +++ b/Emby.Drawing/ImageProcessor.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; -using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller; @@ -11,10 +10,8 @@ using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; -using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; using MediaBrowser.Model.Net; using Microsoft.Extensions.Logging; @@ -24,7 +21,7 @@ namespace Emby.Drawing /// /// Class ImageProcessor. /// - public class ImageProcessor : IImageProcessor, IDisposable + public sealed class ImageProcessor : IImageProcessor, IDisposable { // Increment this when there's a change requiring caches to be invalidated private const string Version = "3"; @@ -32,28 +29,24 @@ namespace Emby.Drawing private static readonly HashSet _transparentImageTypes = new HashSet(StringComparer.OrdinalIgnoreCase) { ".png", ".webp", ".gif" }; - /// - /// The _logger - /// private readonly ILogger _logger; private readonly IFileSystem _fileSystem; private readonly IServerApplicationPaths _appPaths; - private IImageEncoder _imageEncoder; + private readonly IImageEncoder _imageEncoder; private readonly Func _libraryManager; private readonly Func _mediaEncoder; - private readonly Dictionary _locks = new Dictionary(); private bool _disposed = false; /// - /// + /// Initializes a new instance of the class. /// - /// - /// - /// - /// - /// - /// + /// The logger. + /// The server application paths. + /// The filesystem. + /// The image encoder. + /// The library manager. + /// The media encoder. public ImageProcessor( ILogger logger, IServerApplicationPaths appPaths, @@ -68,16 +61,10 @@ namespace Emby.Drawing _libraryManager = libraryManager; _mediaEncoder = mediaEncoder; _appPaths = appPaths; - - ImageEnhancers = Array.Empty(); - - ImageHelper.ImageProcessor = this; } private string ResizedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "resized-images"); - private string EnhancedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "enhanced-images"); - /// public IReadOnlyCollection SupportedInputFormats => new HashSet(StringComparer.OrdinalIgnoreCase) @@ -90,9 +77,7 @@ namespace Emby.Drawing "aiff", "cr2", "crw", - - // Remove until supported - //"nef", + "nef", "orf", "pef", "arw", @@ -111,19 +96,9 @@ namespace Emby.Drawing "wbmp" }; - /// - public IReadOnlyCollection ImageEnhancers { get; set; } - /// public bool SupportsImageCollageCreation => _imageEncoder.SupportsImageCollageCreation; - /// - public IImageEncoder ImageEncoder - { - get => _imageEncoder; - set => _imageEncoder = value ?? throw new ArgumentNullException(nameof(value)); - } - /// public async Task ProcessImage(ImageProcessingOptions options, Stream toStream) { @@ -151,6 +126,8 @@ namespace Emby.Drawing throw new ArgumentNullException(nameof(options)); } + var libraryManager = _libraryManager(); + ItemImageInfo originalImage = options.Image; BaseItem item = options.Item; @@ -158,9 +135,10 @@ namespace Emby.Drawing { if (item == null) { - item = _libraryManager().GetItemById(options.ItemId); + item = libraryManager.GetItemById(options.ItemId); } - originalImage = await _libraryManager().ConvertImageToLocal(item, originalImage, options.ImageIndex).ConfigureAwait(false); + + originalImage = await libraryManager.ConvertImageToLocal(item, originalImage, options.ImageIndex).ConfigureAwait(false); } string originalImagePath = originalImage.Path; @@ -187,27 +165,6 @@ namespace Emby.Drawing dateModified = supportedImageInfo.dateModified; bool requiresTransparency = _transparentImageTypes.Contains(Path.GetExtension(originalImagePath)); - if (options.Enhancers.Count > 0) - { - if (item == null) - { - item = _libraryManager().GetItemById(options.ItemId); - } - - var tuple = await GetEnhancedImage(new ItemImageInfo - { - DateModified = dateModified, - Type = originalImage.Type, - Path = originalImagePath - }, requiresTransparency, item, options.ImageIndex, options.Enhancers, CancellationToken.None).ConfigureAwait(false); - - originalImagePath = tuple.path; - dateModified = tuple.dateModified; - requiresTransparency = tuple.transparent; - // TODO: Get this info - originalImageSize = null; - } - bool autoOrient = false; ImageOrientation? orientation = null; if (item is Photo photo) @@ -240,12 +197,6 @@ namespace Emby.Drawing ImageFormat outputFormat = GetOutputFormat(options.SupportedOutputFormats, requiresTransparency); string cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.Blur, options.BackgroundColor, options.ForegroundLayer); - CheckDisposed(); - - LockInfo lockInfo = GetLock(cacheFilePath); - - await lockInfo.Lock.WaitAsync().ConfigureAwait(false); - try { if (!File.Exists(cacheFilePath)) @@ -271,10 +222,6 @@ namespace Emby.Drawing _logger.LogError(ex, "Error encoding image"); return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); } - finally - { - ReleaseLock(cacheFilePath, lockInfo); - } } private ImageFormat GetOutputFormat(IReadOnlyCollection clientSupportedFormats, bool requiresTransparency) @@ -306,20 +253,18 @@ namespace Emby.Drawing } private string GetMimeType(ImageFormat format, string path) - { - switch(format) + => format switch { - case ImageFormat.Bmp: return MimeTypes.GetMimeType("i.bmp"); - case ImageFormat.Gif: return MimeTypes.GetMimeType("i.gif"); - case ImageFormat.Jpg: return MimeTypes.GetMimeType("i.jpg"); - case ImageFormat.Png: return MimeTypes.GetMimeType("i.png"); - case ImageFormat.Webp: return MimeTypes.GetMimeType("i.webp"); - default: return MimeTypes.GetMimeType(path); - } - } + ImageFormat.Bmp => MimeTypes.GetMimeType("i.bmp"), + ImageFormat.Gif => MimeTypes.GetMimeType("i.gif"), + ImageFormat.Jpg => MimeTypes.GetMimeType("i.jpg"), + ImageFormat.Png => MimeTypes.GetMimeType("i.png"), + ImageFormat.Webp => MimeTypes.GetMimeType("i.webp"), + _ => MimeTypes.GetMimeType(path) + }; /// - /// Gets the cache file path based on a set of parameters + /// Gets the cache file path based on a set of parameters. /// private string GetCacheFilePath(string originalPath, ImageDimensions outputSize, int quality, DateTime dateModified, ImageFormat format, bool addPlayedIndicator, double percentPlayed, int? unwatchedCount, int? blur, string backgroundColor, string foregroundLayer) { @@ -401,11 +346,7 @@ namespace Emby.Drawing /// public string GetImageCacheTag(BaseItem item, ItemImageInfo image) - { - var supportedEnhancers = GetSupportedEnhancers(item, image.Type).ToArray(); - - return GetImageCacheTag(item, image, supportedEnhancers); - } + => (item.Path + image.DateModified.Ticks).GetMD5().ToString("N", CultureInfo.InvariantCulture); /// public string GetImageCacheTag(BaseItem item, ChapterInfo chapter) @@ -425,26 +366,6 @@ namespace Emby.Drawing } } - /// - public string GetImageCacheTag(BaseItem item, ItemImageInfo image, IReadOnlyCollection imageEnhancers) - { - string originalImagePath = image.Path; - DateTime dateModified = image.DateModified; - ImageType imageType = image.Type; - - // Optimization - if (imageEnhancers.Count == 0) - { - return (originalImagePath + dateModified.Ticks).GetMD5().ToString("N", CultureInfo.InvariantCulture); - } - - // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes - var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList(); - cacheKeys.Add(originalImagePath + dateModified.Ticks); - - return string.Join("|", cacheKeys).GetMD5().ToString("N", CultureInfo.InvariantCulture); - } - private async Task<(string path, DateTime dateModified)> GetSupportedImage(string originalImagePath, DateTime dateModified) { var inputFormat = Path.GetExtension(originalImagePath) @@ -488,154 +409,6 @@ namespace Emby.Drawing return (originalImagePath, dateModified); } - /// - public async Task GetEnhancedImage(BaseItem item, ImageType imageType, int imageIndex) - { - var enhancers = GetSupportedEnhancers(item, imageType).ToArray(); - - ItemImageInfo imageInfo = item.GetImageInfo(imageType, imageIndex); - - bool inputImageSupportsTransparency = SupportsTransparency(imageInfo.Path); - - var result = await GetEnhancedImage(imageInfo, inputImageSupportsTransparency, item, imageIndex, enhancers, CancellationToken.None); - - return result.path; - } - - private async Task<(string path, DateTime dateModified, bool transparent)> GetEnhancedImage( - ItemImageInfo image, - bool inputImageSupportsTransparency, - BaseItem item, - int imageIndex, - IReadOnlyCollection enhancers, - CancellationToken cancellationToken) - { - var originalImagePath = image.Path; - var dateModified = image.DateModified; - var imageType = image.Type; - - try - { - var cacheGuid = GetImageCacheTag(item, image, enhancers); - - // Enhance if we have enhancers - var enhancedImageInfo = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid, cancellationToken).ConfigureAwait(false); - - string enhancedImagePath = enhancedImageInfo.path; - - // If the path changed update dateModified - if (!string.Equals(enhancedImagePath, originalImagePath, StringComparison.OrdinalIgnoreCase)) - { - var treatmentRequiresTransparency = enhancedImageInfo.transparent; - - return (enhancedImagePath, _fileSystem.GetLastWriteTimeUtc(enhancedImagePath), treatmentRequiresTransparency); - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Error enhancing image"); - } - - return (originalImagePath, dateModified, inputImageSupportsTransparency); - } - - /// - /// Gets the enhanced image internal. - /// - /// The original image path. - /// The item. - /// Type of the image. - /// Index of the image. - /// The supported enhancers. - /// The cache unique identifier. - /// The cancellation token. - /// Task<System.String>. - /// - /// originalImagePath - /// or - /// item - /// - private async Task<(string path, bool transparent)> GetEnhancedImageInternal( - string originalImagePath, - BaseItem item, - ImageType imageType, - int imageIndex, - IReadOnlyCollection supportedEnhancers, - string cacheGuid, - CancellationToken cancellationToken = default) - { - if (string.IsNullOrEmpty(originalImagePath)) - { - throw new ArgumentNullException(nameof(originalImagePath)); - } - - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } - - var treatmentRequiresTransparency = false; - foreach (var enhancer in supportedEnhancers) - { - if (!treatmentRequiresTransparency) - { - treatmentRequiresTransparency = enhancer.GetEnhancedImageInfo(item, originalImagePath, imageType, imageIndex).RequiresTransparency; - } - } - - // All enhanced images are saved as png to allow transparency - string cacheExtension = _imageEncoder.SupportedOutputFormats.Contains(ImageFormat.Webp) ? - ".webp" : - (treatmentRequiresTransparency ? ".png" : ".jpg"); - - string enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + cacheExtension); - - LockInfo lockInfo = GetLock(enhancedImagePath); - - await lockInfo.Lock.WaitAsync(cancellationToken).ConfigureAwait(false); - - try - { - // Check again in case of contention - if (File.Exists(enhancedImagePath)) - { - return (enhancedImagePath, treatmentRequiresTransparency); - } - - Directory.CreateDirectory(Path.GetDirectoryName(enhancedImagePath)); - - await ExecuteImageEnhancers(supportedEnhancers, originalImagePath, enhancedImagePath, item, imageType, imageIndex).ConfigureAwait(false); - - return (enhancedImagePath, treatmentRequiresTransparency); - } - finally - { - ReleaseLock(enhancedImagePath, lockInfo); - } - } - - /// - /// Executes the image enhancers. - /// - /// The image enhancers. - /// The input path. - /// The output path. - /// The item. - /// Type of the image. - /// Index of the image. - /// Task{EnhancedImage}. - private static async Task ExecuteImageEnhancers(IEnumerable imageEnhancers, string inputPath, string outputPath, BaseItem item, ImageType imageType, int imageIndex) - { - // Run the enhancers sequentially in order of priority - foreach (var enhancer in imageEnhancers) - { - await enhancer.EnhanceImageAsync(item, inputPath, outputPath, imageType, imageIndex).ConfigureAwait(false); - - // Feed the output into the next enhancer as input - inputPath = outputPath; - } - } - /// /// Gets the cache path. /// @@ -648,7 +421,7 @@ namespace Emby.Drawing /// or /// uniqueName /// or - /// fileExtension + /// fileExtension. /// public string GetCachePath(string path, string uniqueName, string fileExtension) { @@ -681,7 +454,7 @@ namespace Emby.Drawing /// /// path /// or - /// filename + /// filename. /// public string GetCachePath(string path, string filename) { @@ -689,6 +462,7 @@ namespace Emby.Drawing { throw new ArgumentNullException(nameof(path)); } + if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException(nameof(filename)); @@ -709,75 +483,20 @@ namespace Emby.Drawing _logger.LogInformation("Completed creation of image collage and saved to {Path}", options.OutputPath); } - /// - public IEnumerable GetSupportedEnhancers(BaseItem item, ImageType imageType) - { - foreach (var i in ImageEnhancers) - { - if (i.Supports(item, imageType)) - { - yield return i; - } - } - } - - - private class LockInfo - { - public SemaphoreSlim Lock = new SemaphoreSlim(1, 1); - public int Count = 1; - } - - private LockInfo GetLock(string key) - { - lock (_locks) - { - if (_locks.TryGetValue(key, out LockInfo info)) - { - info.Count++; - } - else - { - info = new LockInfo(); - _locks[key] = info; - } - return info; - } - } - - private void ReleaseLock(string key, LockInfo info) - { - info.Lock.Release(); - - lock (_locks) - { - info.Count--; - if (info.Count <= 0) - { - _locks.Remove(key); - info.Lock.Dispose(); - } - } - } - /// public void Dispose() - { - _disposed = true; - - var disposable = _imageEncoder as IDisposable; - if (disposable != null) - { - disposable.Dispose(); - } - } - - private void CheckDisposed() { if (_disposed) { - throw new ObjectDisposedException(GetType().Name); + return; } + + if (_imageEncoder is IDisposable disposable) + { + disposable.Dispose(); + } + + _disposed = true; } } } diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 0bb1d832fb..4f47874439 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1074,8 +1074,6 @@ namespace Emby.Server.Implementations GetExports(), GetExports()); - ImageProcessor.ImageEnhancers = GetExports(); - LiveTvManager.AddParts(GetExports(), GetExports(), GetExports()); SubtitleManager.AddParts(GetExports()); diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index fcf0360c79..960f3f2d67 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -1362,56 +1362,33 @@ namespace Emby.Server.Implementations.Dto return null; } - var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToArray(); - ImageDimensions size; var defaultAspectRatio = item.GetDefaultPrimaryImageAspectRatio(); if (defaultAspectRatio > 0) { - if (supportedEnhancers.Length == 0) - { - return defaultAspectRatio; - } - - int dummyWidth = 200; - int dummyHeight = Convert.ToInt32(dummyWidth / defaultAspectRatio); - size = new ImageDimensions(dummyWidth, dummyHeight); + return defaultAspectRatio; } - else + + if (!imageInfo.IsLocalFile) { - if (!imageInfo.IsLocalFile) + return null; + } + + try + { + size = _imageProcessor.GetImageDimensions(item, imageInfo); + + if (size.Width <= 0 || size.Height <= 0) { return null; } - - try - { - size = _imageProcessor.GetImageDimensions(item, imageInfo); - - if (size.Width <= 0 || size.Height <= 0) - { - return null; - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Failed to determine primary image aspect ratio for {0}", imageInfo.Path); - return null; - } } - - foreach (var enhancer in supportedEnhancers) + catch (Exception ex) { - try - { - size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error in image enhancer: {0}", enhancer.GetType().Name); - } + _logger.LogError(ex, "Failed to determine primary image aspect ratio for {0}", imageInfo.Path); + return null; } var width = size.Width; diff --git a/Jellyfin.Drawing.Skia/SkiaEncoder.cs b/Jellyfin.Drawing.Skia/SkiaEncoder.cs index b080b3e6a5..2ea690650b 100644 --- a/Jellyfin.Drawing.Skia/SkiaEncoder.cs +++ b/Jellyfin.Drawing.Skia/SkiaEncoder.cs @@ -6,7 +6,6 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Extensions; using MediaBrowser.Model.Drawing; -using MediaBrowser.Model.Globalization; using Microsoft.Extensions.Logging; using SkiaSharp; using static Jellyfin.Drawing.Skia.SkiaHelper; @@ -18,27 +17,23 @@ namespace Jellyfin.Drawing.Skia /// public class SkiaEncoder : IImageEncoder { - private readonly ILogger _logger; - private readonly IApplicationPaths _appPaths; - private readonly ILocalizationManager _localizationManager; - private static readonly HashSet _transparentImageTypes = new HashSet(StringComparer.OrdinalIgnoreCase) { ".png", ".gif", ".webp" }; + private readonly ILogger _logger; + private readonly IApplicationPaths _appPaths; + /// /// Initializes a new instance of the class. /// /// The application logger. /// The application paths. - /// The application localization manager. public SkiaEncoder( ILogger logger, - IApplicationPaths appPaths, - ILocalizationManager localizationManager) + IApplicationPaths appPaths) { _logger = logger; _appPaths = appPaths; - _localizationManager = localizationManager; } /// @@ -235,9 +230,12 @@ namespace Jellyfin.Drawing.Skia private bool RequiresSpecialCharacterHack(string path) { - if (_localizationManager.HasUnicodeCategory(path, UnicodeCategory.OtherLetter)) + for (int i = 0; i < path.Length; i++) { - return true; + if (char.GetUnicodeCategory(path[i]) == UnicodeCategory.OtherLetter) + { + return true; + } } if (HasDiacritics(path)) diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index fa9b626744..c0621ba144 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -169,7 +169,7 @@ namespace Jellyfin.Server _loggerFactory, options, new ManagedFileSystem(_loggerFactory.CreateLogger(), appPaths), - new NullImageEncoder(), + GetImageEncoder(appPaths), new NetworkManager(_loggerFactory.CreateLogger()), appConfig); try @@ -193,8 +193,6 @@ namespace Jellyfin.Server throw; } - appHost.ImageProcessor.ImageEncoder = GetImageEncoder(appPaths, appHost.LocalizationManager); - await appHost.RunStartupTasksAsync().ConfigureAwait(false); stopWatch.Stop(); @@ -494,9 +492,7 @@ namespace Jellyfin.Server } } - private static IImageEncoder GetImageEncoder( - IApplicationPaths appPaths, - ILocalizationManager localizationManager) + private static IImageEncoder GetImageEncoder(IApplicationPaths appPaths) { try { @@ -505,8 +501,7 @@ namespace Jellyfin.Server return new SkiaEncoder( _loggerFactory.CreateLogger(), - appPaths, - localizationManager); + appPaths); } catch (Exception ex) { diff --git a/MediaBrowser.Api/Images/ImageService.cs b/MediaBrowser.Api/Images/ImageService.cs index e94c1321f4..4060bf4cce 100644 --- a/MediaBrowser.Api/Images/ImageService.cs +++ b/MediaBrowser.Api/Images/ImageService.cs @@ -24,7 +24,7 @@ using Microsoft.Net.Http.Headers; namespace MediaBrowser.Api.Images { /// - /// Class GetItemImage + /// Class GetItemImage. /// [Route("/Items/{Id}/Images", "GET", Summary = "Gets information about an item's images")] [Authenticated] @@ -558,21 +558,6 @@ namespace MediaBrowser.Api.Images throw new ResourceNotFoundException(string.Format("{0} does not have an image of type {1}", displayText, request.Type)); } - IImageEnhancer[] supportedImageEnhancers; - if (_imageProcessor.ImageEnhancers.Count > 0) - { - if (item == null) - { - item = _libraryManager.GetItemById(itemId); - } - - supportedImageEnhancers = request.EnableImageEnhancers ? _imageProcessor.GetSupportedEnhancers(item, request.Type).ToArray() : Array.Empty(); - } - else - { - supportedImageEnhancers = Array.Empty(); - } - bool cropwhitespace; if (request.CropWhitespace.HasValue) { @@ -598,25 +583,25 @@ namespace MediaBrowser.Api.Images {"realTimeInfo.dlna.org", "DLNA.ORG_TLAG=*"} }; - return GetImageResult(item, + return GetImageResult( + item, itemId, request, imageInfo, cropwhitespace, outputFormats, - supportedImageEnhancers, cacheDuration, responseHeaders, isHeadRequest); } - private async Task GetImageResult(BaseItem item, + private async Task GetImageResult( + BaseItem item, Guid itemId, ImageRequest request, ItemImageInfo image, bool cropwhitespace, IReadOnlyCollection supportedFormats, - IReadOnlyCollection enhancers, TimeSpan? cacheDuration, IDictionary headers, bool isHeadRequest) @@ -624,7 +609,6 @@ namespace MediaBrowser.Api.Images var options = new ImageProcessingOptions { CropWhiteSpace = cropwhitespace, - Enhancers = enhancers, Height = request.Height, ImageIndex = request.Index ?? 0, Image = image, diff --git a/MediaBrowser.Controller/Drawing/IImageProcessor.cs b/MediaBrowser.Controller/Drawing/IImageProcessor.cs index a58a11bd1f..79399807fd 100644 --- a/MediaBrowser.Controller/Drawing/IImageProcessor.cs +++ b/MediaBrowser.Controller/Drawing/IImageProcessor.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Entities; @@ -20,20 +19,12 @@ namespace MediaBrowser.Controller.Drawing /// The supported input formats. IReadOnlyCollection SupportedInputFormats { get; } - /// - /// Gets the image enhancers. - /// - /// The image enhancers. - IReadOnlyCollection ImageEnhancers { get; set; } - /// /// Gets a value indicating whether [supports image collage creation]. /// /// true if [supports image collage creation]; otherwise, false. bool SupportsImageCollageCreation { get; } - IImageEncoder ImageEncoder { get; set; } - /// /// Gets the dimensions of the image. /// @@ -58,14 +49,6 @@ namespace MediaBrowser.Controller.Drawing /// ImageDimensions ImageDimensions GetImageDimensions(BaseItem item, ItemImageInfo info, bool updateItem); - /// - /// Gets the supported enhancers. - /// - /// The item. - /// Type of the image. - /// IEnumerable{IImageEnhancer}. - IEnumerable GetSupportedEnhancers(BaseItem item, ImageType imageType); - /// /// Gets the image cache tag. /// @@ -75,15 +58,6 @@ namespace MediaBrowser.Controller.Drawing string GetImageCacheTag(BaseItem item, ItemImageInfo image); string GetImageCacheTag(BaseItem item, ChapterInfo info); - /// - /// Gets the image cache tag. - /// - /// The item. - /// The image. - /// The image enhancers. - /// Guid. - string GetImageCacheTag(BaseItem item, ItemImageInfo image, IReadOnlyCollection imageEnhancers); - /// /// Processes the image. /// @@ -99,15 +73,6 @@ namespace MediaBrowser.Controller.Drawing /// Task. Task<(string path, string mimeType, DateTime dateModified)> ProcessImage(ImageProcessingOptions options); - /// - /// Gets the enhanced image. - /// - /// The item. - /// Type of the image. - /// Index of the image. - /// Task{System.String}. - Task GetEnhancedImage(BaseItem item, ImageType imageType, int imageIndex); - /// /// Gets the supported image output formats. /// diff --git a/MediaBrowser.Controller/Drawing/ImageHelper.cs b/MediaBrowser.Controller/Drawing/ImageHelper.cs index 432cf80423..d5a5f547ea 100644 --- a/MediaBrowser.Controller/Drawing/ImageHelper.cs +++ b/MediaBrowser.Controller/Drawing/ImageHelper.cs @@ -19,8 +19,6 @@ namespace MediaBrowser.Controller.Drawing return GetSizeEstimate(options); } - public static IImageProcessor ImageProcessor { get; set; } - private static ImageDimensions GetSizeEstimate(ImageProcessingOptions options) { if (options.Width.HasValue && options.Height.HasValue) diff --git a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs index 29addf6e65..870e0278e4 100644 --- a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs +++ b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Drawing; namespace MediaBrowser.Controller.Drawing @@ -34,8 +33,6 @@ namespace MediaBrowser.Controller.Drawing public int Quality { get; set; } - public IReadOnlyCollection Enhancers { get; set; } - public IReadOnlyCollection SupportedOutputFormats { get; set; } public bool AddPlayedIndicator { get; set; } diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs index 34af3b1568..6b3fb4144e 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs @@ -316,11 +316,7 @@ namespace MediaBrowser.Controller.MediaEncoding { if (VideoStream != null && VideoStream.Width.HasValue && VideoStream.Height.HasValue) { - var size = new ImageDimensions - { - Width = VideoStream.Width.Value, - Height = VideoStream.Height.Value - }; + var size = new ImageDimensions(VideoStream.Width.Value, VideoStream.Height.Value); var newSize = DrawingUtils.Resize(size, BaseRequest.Width ?? 0, @@ -346,11 +342,7 @@ namespace MediaBrowser.Controller.MediaEncoding { if (VideoStream != null && VideoStream.Width.HasValue && VideoStream.Height.HasValue) { - var size = new ImageDimensions - { - Width = VideoStream.Width.Value, - Height = VideoStream.Height.Value - }; + var size = new ImageDimensions(VideoStream.Width.Value, VideoStream.Height.Value); var newSize = DrawingUtils.Resize(size, BaseRequest.Width ?? 0, diff --git a/MediaBrowser.Controller/Providers/IImageEnhancer.cs b/MediaBrowser.Controller/Providers/IImageEnhancer.cs deleted file mode 100644 index c27c00ca26..0000000000 --- a/MediaBrowser.Controller/Providers/IImageEnhancer.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System.Threading.Tasks; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Model.Drawing; -using MediaBrowser.Model.Entities; - -namespace MediaBrowser.Controller.Providers -{ - public interface IImageEnhancer - { - /// - /// Return true only if the given image for the given item will be enhanced by this enhancer. - /// - /// The item. - /// Type of the image. - /// true if this enhancer will enhance the supplied image for the supplied item, false otherwise - bool Supports(BaseItem item, ImageType imageType); - - /// - /// Gets the priority or order in which this enhancer should be run. - /// - /// The priority. - MetadataProviderPriority Priority { get; } - - /// - /// Return a key incorporating all configuration information related to this item - /// - /// The item. - /// Type of the image. - /// Cache key relating to the current state of this item and configuration - string GetConfigurationCacheKey(BaseItem item, ImageType imageType); - - /// - /// Gets the size of the enhanced image. - /// - /// The item. - /// Type of the image. - /// Index of the image. - /// Size of the original image. - /// ImageSize. - ImageDimensions GetEnhancedImageSize(BaseItem item, ImageType imageType, int imageIndex, ImageDimensions originalImageSize); - - EnhancedImageInfo GetEnhancedImageInfo(BaseItem item, string inputFile, ImageType imageType, int imageIndex); - - /// - /// Enhances the image async. - /// - /// The item. - /// The input file. - /// The output file. - /// Type of the image. - /// Index of the image. - /// Task{Image}. - /// - Task EnhanceImageAsync(BaseItem item, string inputFile, string outputFile, ImageType imageType, int imageIndex); - } - - public class EnhancedImageInfo - { - public bool RequiresTransparency { get; set; } - } -} diff --git a/MediaBrowser.Model/Drawing/ImageDimensions.cs b/MediaBrowser.Model/Drawing/ImageDimensions.cs index e7805ac494..4bd8d85d4f 100644 --- a/MediaBrowser.Model/Drawing/ImageDimensions.cs +++ b/MediaBrowser.Model/Drawing/ImageDimensions.cs @@ -1,36 +1,43 @@ +using System.Globalization; + namespace MediaBrowser.Model.Drawing { /// /// Struct ImageDimensions /// - public struct ImageDimensions + public readonly struct ImageDimensions { - /// - /// Gets or sets the height. - /// - /// The height. - public int Height { get; set; } + public ImageDimensions(int width, int height) + { + Width = width; + Height = height; + } /// - /// Gets or sets the width. + /// Gets the height. + /// + /// The height. + public int Height { get; } + + /// + /// Gets the width. /// /// The width. - public int Width { get; set; } + public int Width { get; } public bool Equals(ImageDimensions size) { return Width.Equals(size.Width) && Height.Equals(size.Height); } + /// public override string ToString() { - return string.Format("{0}-{1}", Width, Height); - } - - public ImageDimensions(int width, int height) - { - Width = width; - Height = height; + return string.Format( + CultureInfo.InvariantCulture, + "{0}-{1}", + Width, + Height); } } } From 5340eb9363f006e61b4574a30091bfdd43a0772b Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Wed, 22 Jan 2020 17:46:26 +0100 Subject: [PATCH 102/881] Update Emby.Dlna/Service/BaseControlHandler.cs Co-Authored-By: dkanada --- Emby.Dlna/Service/BaseControlHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs index d56f54149f..49129f6ffd 100644 --- a/Emby.Dlna/Service/BaseControlHandler.cs +++ b/Emby.Dlna/Service/BaseControlHandler.cs @@ -228,7 +228,7 @@ namespace Emby.Dlna.Service return; } - Logger.LogDebug("Control request. Headers: {@Header}", request.Headers); + Logger.LogDebug("Control request. Headers: {@Headers}", request.Headers); } private void LogResponse(ControlResponse response) From 6eac7f0fa7e753731e3d65c0b6c0323eb730ccd8 Mon Sep 17 00:00:00 2001 From: Marco Date: Tue, 21 Jan 2020 16:40:09 +0000 Subject: [PATCH 103/881] Translated using Weblate (Italian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/it/ --- Emby.Server.Implementations/Localization/Core/it.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/it.json b/Emby.Server.Implementations/Localization/Core/it.json index 8f91effb92..c1c40c18e1 100644 --- a/Emby.Server.Implementations/Localization/Core/it.json +++ b/Emby.Server.Implementations/Localization/Core/it.json @@ -9,7 +9,7 @@ "Channels": "Canali", "ChapterNameValue": "Capitolo {0}", "Collections": "Collezioni", - "DeviceOfflineWithName": "{0} ha disconnesso", + "DeviceOfflineWithName": "{0} si è disconnesso", "DeviceOnlineWithName": "{0} è connesso", "FailedLoginAttemptWithUserName": "Tentativo di accesso fallito da {0}", "Favorites": "Preferiti", From 82112b67880265c34f2dcca1ee7f0acf52a156df Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 22 Jan 2020 21:00:07 +0100 Subject: [PATCH 104/881] Improvements to dlna server * Improve response writer * Add analyzers * Error on warnings in release mode * Disable doc warnings --- Emby.Dlna/Api/DlnaServerService.cs | 3 + Emby.Dlna/Api/DlnaService.cs | 3 + Emby.Dlna/Common/Argument.cs | 2 + Emby.Dlna/Common/DeviceIcon.cs | 11 +- Emby.Dlna/Common/DeviceService.cs | 7 +- Emby.Dlna/Common/ServiceAction.cs | 22 +- Emby.Dlna/Common/StateVariable.cs | 18 +- Emby.Dlna/Configuration/DlnaOptions.cs | 27 +- Emby.Dlna/ConfigurationExtension.cs | 3 + .../ConnectionManager/ConnectionManager.cs | 3 + .../ConnectionManagerXmlBuilder.cs | 3 + Emby.Dlna/ConnectionManager/ControlHandler.cs | 40 +- .../ServiceActionListBuilder.cs | 3 + .../ContentDirectory/ContentDirectory.cs | 3 + .../ContentDirectoryXmlBuilder.cs | 3 + Emby.Dlna/ContentDirectory/ControlHandler.cs | 368 ++++++++---------- .../ServiceActionListBuilder.cs | 3 + Emby.Dlna/ControlRequest.cs | 3 + Emby.Dlna/ControlResponse.cs | 13 +- Emby.Dlna/Didl/DidlBuilder.cs | 4 +- Emby.Dlna/Didl/Filter.cs | 3 + Emby.Dlna/Didl/StringWriterWithEncoding.cs | 3 + Emby.Dlna/DlnaManager.cs | 3 + Emby.Dlna/Emby.Dlna.csproj | 13 + Emby.Dlna/EventSubscriptionResponse.cs | 14 +- Emby.Dlna/Eventing/EventManager.cs | 6 +- Emby.Dlna/Eventing/EventSubscription.cs | 7 +- Emby.Dlna/IConnectionManager.cs | 2 + Emby.Dlna/IContentDirectory.cs | 2 + Emby.Dlna/IEventManager.cs | 2 + Emby.Dlna/IMediaReceiverRegistrar.cs | 2 + Emby.Dlna/IUpnpService.cs | 3 + Emby.Dlna/Main/DlnaEntryPoint.cs | 3 + .../MediaReceiverRegistrar/ControlHandler.cs | 54 +-- .../MediaReceiverRegistrar.cs | 3 + .../MediaReceiverRegistrarXmlBuilder.cs | 3 + .../ServiceActionListBuilder.cs | 3 + Emby.Dlna/PlayTo/Device.cs | 33 +- Emby.Dlna/PlayTo/DeviceInfo.cs | 3 + Emby.Dlna/PlayTo/PlayToController.cs | 3 + Emby.Dlna/PlayTo/PlayToManager.cs | 11 +- Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs | 3 + Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs | 3 + Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs | 3 + Emby.Dlna/PlayTo/PlaylistItem.cs | 3 + Emby.Dlna/PlayTo/PlaylistItemFactory.cs | 3 + Emby.Dlna/PlayTo/SsdpHttpClient.cs | 15 +- Emby.Dlna/PlayTo/TRANSPORTSTATE.cs | 3 + Emby.Dlna/PlayTo/TransportCommands.cs | 3 + Emby.Dlna/PlayTo/UpnpContainer.cs | 3 + Emby.Dlna/PlayTo/uBaseObject.cs | 3 + Emby.Dlna/PlayTo/uPnpNamespaces.cs | 3 + Emby.Dlna/Profiles/DefaultProfile.cs | 3 + Emby.Dlna/Profiles/DenonAvrProfile.cs | 3 + Emby.Dlna/Profiles/DirectTvProfile.cs | 3 + Emby.Dlna/Profiles/DishHopperJoeyProfile.cs | 3 + Emby.Dlna/Profiles/Foobar2000Profile.cs | 3 + Emby.Dlna/Profiles/LgTvProfile.cs | 3 + Emby.Dlna/Profiles/LinksysDMA2100Profile.cs | 3 + Emby.Dlna/Profiles/MarantzProfile.cs | 3 + Emby.Dlna/Profiles/MediaMonkeyProfile.cs | 3 + Emby.Dlna/Profiles/PanasonicVieraProfile.cs | 3 + Emby.Dlna/Profiles/PopcornHourProfile.cs | 3 + Emby.Dlna/Profiles/SamsungSmartTvProfile.cs | 3 + Emby.Dlna/Profiles/SharpSmartTvProfile.cs | 3 + Emby.Dlna/Profiles/SonyBlurayPlayer2013.cs | 3 + Emby.Dlna/Profiles/SonyBlurayPlayer2014.cs | 3 + Emby.Dlna/Profiles/SonyBlurayPlayer2015.cs | 3 + Emby.Dlna/Profiles/SonyBlurayPlayer2016.cs | 3 + Emby.Dlna/Profiles/SonyBlurayPlayerProfile.cs | 3 + Emby.Dlna/Profiles/SonyBravia2010Profile.cs | 3 + Emby.Dlna/Profiles/SonyBravia2011Profile.cs | 3 + Emby.Dlna/Profiles/SonyBravia2012Profile.cs | 3 + Emby.Dlna/Profiles/SonyBravia2013Profile.cs | 3 + Emby.Dlna/Profiles/SonyBravia2014Profile.cs | 3 + Emby.Dlna/Profiles/SonyPs3Profile.cs | 3 + Emby.Dlna/Profiles/SonyPs4Profile.cs | 3 + Emby.Dlna/Profiles/WdtvLiveProfile.cs | 3 + Emby.Dlna/Profiles/XboxOneProfile.cs | 3 + Emby.Dlna/Server/DescriptionXmlBuilder.cs | 3 + Emby.Dlna/Service/BaseControlHandler.cs | 17 +- Emby.Dlna/Service/BaseService.cs | 3 + Emby.Dlna/Service/ControlErrorHandler.cs | 3 + Emby.Dlna/Service/ServiceXmlBuilder.cs | 3 + Emby.Dlna/Ssdp/DeviceDiscovery.cs | 15 +- Emby.Dlna/Ssdp/Extensions.cs | 3 + 86 files changed, 564 insertions(+), 327 deletions(-) diff --git a/Emby.Dlna/Api/DlnaServerService.cs b/Emby.Dlna/Api/DlnaServerService.cs index a7ff6e9cfd..4d9933a0cb 100644 --- a/Emby.Dlna/Api/DlnaServerService.cs +++ b/Emby.Dlna/Api/DlnaServerService.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.IO; using System.Text; diff --git a/Emby.Dlna/Api/DlnaService.cs b/Emby.Dlna/Api/DlnaService.cs index 7f51f477a7..f10695541d 100644 --- a/Emby.Dlna/Api/DlnaService.cs +++ b/Emby.Dlna/Api/DlnaService.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Linq; using MediaBrowser.Controller.Dlna; using MediaBrowser.Controller.Net; diff --git a/Emby.Dlna/Common/Argument.cs b/Emby.Dlna/Common/Argument.cs index 3e325c41ce..c6ab9959e0 100644 --- a/Emby.Dlna/Common/Argument.cs +++ b/Emby.Dlna/Common/Argument.cs @@ -1,3 +1,5 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 namespace Emby.Dlna.Common { diff --git a/Emby.Dlna/Common/DeviceIcon.cs b/Emby.Dlna/Common/DeviceIcon.cs index 3a91b952ec..49d19992d8 100644 --- a/Emby.Dlna/Common/DeviceIcon.cs +++ b/Emby.Dlna/Common/DeviceIcon.cs @@ -1,3 +1,7 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + +using System.Globalization; namespace Emby.Dlna.Common { @@ -13,9 +17,14 @@ namespace Emby.Dlna.Common public string Depth { get; set; } + /// public override string ToString() { - return string.Format("{0}x{1}", Height, Width); + return string.Format( + CultureInfo.InvariantCulture, + "{0}x{1}", + Height, + Width); } } } diff --git a/Emby.Dlna/Common/DeviceService.cs b/Emby.Dlna/Common/DeviceService.cs index c60d652913..9947ec6b9a 100644 --- a/Emby.Dlna/Common/DeviceService.cs +++ b/Emby.Dlna/Common/DeviceService.cs @@ -1,3 +1,5 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 namespace Emby.Dlna.Common { @@ -13,9 +15,8 @@ namespace Emby.Dlna.Common public string EventSubUrl { get; set; } + /// public override string ToString() - { - return string.Format("{0}", ServiceId); - } + => ServiceId; } } diff --git a/Emby.Dlna/Common/ServiceAction.cs b/Emby.Dlna/Common/ServiceAction.cs index 5e030d396a..15c4be8092 100644 --- a/Emby.Dlna/Common/ServiceAction.cs +++ b/Emby.Dlna/Common/ServiceAction.cs @@ -1,21 +1,25 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Collections.Generic; namespace Emby.Dlna.Common { public class ServiceAction { - public string Name { get; set; } - - public List ArgumentList { get; set; } - - public override string ToString() - { - return Name; - } - public ServiceAction() { ArgumentList = new List(); } + + public string Name { get; set; } + + public List ArgumentList { get; set; } + + /// + public override string ToString() + { + return Name; + } } } diff --git a/Emby.Dlna/Common/StateVariable.cs b/Emby.Dlna/Common/StateVariable.cs index 4ca84bf51c..bade28e4bc 100644 --- a/Emby.Dlna/Common/StateVariable.cs +++ b/Emby.Dlna/Common/StateVariable.cs @@ -1,9 +1,17 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; namespace Emby.Dlna.Common { public class StateVariable { + public StateVariable() + { + AllowedValues = Array.Empty(); + } + public string Name { get; set; } public string DataType { get; set; } @@ -12,14 +20,8 @@ namespace Emby.Dlna.Common public string[] AllowedValues { get; set; } + /// public override string ToString() - { - return Name; - } - - public StateVariable() - { - AllowedValues = Array.Empty(); - } + => Name; } } diff --git a/Emby.Dlna/Configuration/DlnaOptions.cs b/Emby.Dlna/Configuration/DlnaOptions.cs index c7cb364a83..84587a7cee 100644 --- a/Emby.Dlna/Configuration/DlnaOptions.cs +++ b/Emby.Dlna/Configuration/DlnaOptions.cs @@ -1,17 +1,10 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 namespace Emby.Dlna.Configuration { public class DlnaOptions { - public bool EnablePlayTo { get; set; } - public bool EnableServer { get; set; } - public bool EnableDebugLog { get; set; } - public bool BlastAliveMessages { get; set; } - public bool SendOnlyMatchedHost { get; set; } - public int ClientDiscoveryIntervalSeconds { get; set; } - public int BlastAliveMessageIntervalSeconds { get; set; } - public string DefaultUserId { get; set; } - public DlnaOptions() { EnablePlayTo = true; @@ -21,5 +14,21 @@ namespace Emby.Dlna.Configuration ClientDiscoveryIntervalSeconds = 60; BlastAliveMessageIntervalSeconds = 1800; } + + public bool EnablePlayTo { get; set; } + + public bool EnableServer { get; set; } + + public bool EnableDebugLog { get; set; } + + public bool BlastAliveMessages { get; set; } + + public bool SendOnlyMatchedHost { get; set; } + + public int ClientDiscoveryIntervalSeconds { get; set; } + + public int BlastAliveMessageIntervalSeconds { get; set; } + + public string DefaultUserId { get; set; } } } diff --git a/Emby.Dlna/ConfigurationExtension.cs b/Emby.Dlna/ConfigurationExtension.cs index 82d726e018..f8125c12c3 100644 --- a/Emby.Dlna/ConfigurationExtension.cs +++ b/Emby.Dlna/ConfigurationExtension.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Collections.Generic; using Emby.Dlna.Configuration; using MediaBrowser.Common.Configuration; diff --git a/Emby.Dlna/ConnectionManager/ConnectionManager.cs b/Emby.Dlna/ConnectionManager/ConnectionManager.cs index 934b353c28..365249c54a 100644 --- a/Emby.Dlna/ConnectionManager/ConnectionManager.cs +++ b/Emby.Dlna/ConnectionManager/ConnectionManager.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Threading.Tasks; using Emby.Dlna.Service; using MediaBrowser.Common.Net; diff --git a/Emby.Dlna/ConnectionManager/ConnectionManagerXmlBuilder.cs b/Emby.Dlna/ConnectionManager/ConnectionManagerXmlBuilder.cs index f5873455a6..c8c97c79c0 100644 --- a/Emby.Dlna/ConnectionManager/ConnectionManagerXmlBuilder.cs +++ b/Emby.Dlna/ConnectionManager/ConnectionManagerXmlBuilder.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Collections.Generic; using Emby.Dlna.Common; using Emby.Dlna.Service; diff --git a/Emby.Dlna/ConnectionManager/ControlHandler.cs b/Emby.Dlna/ConnectionManager/ControlHandler.cs index 2e11047487..7e6c7eb228 100644 --- a/Emby.Dlna/ConnectionManager/ControlHandler.cs +++ b/Emby.Dlna/ConnectionManager/ControlHandler.cs @@ -1,5 +1,9 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; +using System.Xml; using Emby.Dlna.Service; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; @@ -12,29 +16,27 @@ namespace Emby.Dlna.ConnectionManager { private readonly DeviceProfile _profile; - protected override IEnumerable> GetResult(string methodName, IDictionary methodParams) - { - if (string.Equals(methodName, "GetProtocolInfo", StringComparison.OrdinalIgnoreCase)) - { - return HandleGetProtocolInfo(); - } - - throw new ResourceNotFoundException("Unexpected control request name: " + methodName); - } - - private IEnumerable> HandleGetProtocolInfo() - { - return new Dictionary(StringComparer.OrdinalIgnoreCase) - { - { "Source", _profile.ProtocolInfo }, - { "Sink", "" } - }; - } - public ControlHandler(IServerConfigurationManager config, ILogger logger, DeviceProfile profile) : base(config, logger) { _profile = profile; } + + /// + protected override void WriteResult(string methodName, IDictionary methodParams, XmlWriter xmlWriter) + { + if (string.Equals(methodName, "GetProtocolInfo", StringComparison.OrdinalIgnoreCase)) + { + HandleGetProtocolInfo(xmlWriter); + } + + throw new ResourceNotFoundException("Unexpected control request name: " + methodName); + } + + private void HandleGetProtocolInfo(XmlWriter xmlWriter) + { + xmlWriter.WriteElementString("Source", _profile.ProtocolInfo); + xmlWriter.WriteElementString("Sink", string.Empty); + } } } diff --git a/Emby.Dlna/ConnectionManager/ServiceActionListBuilder.cs b/Emby.Dlna/ConnectionManager/ServiceActionListBuilder.cs index b7727b5580..019a0f80f4 100644 --- a/Emby.Dlna/ConnectionManager/ServiceActionListBuilder.cs +++ b/Emby.Dlna/ConnectionManager/ServiceActionListBuilder.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Collections.Generic; using Emby.Dlna.Common; diff --git a/Emby.Dlna/ContentDirectory/ContentDirectory.cs b/Emby.Dlna/ContentDirectory/ContentDirectory.cs index a3062b18fd..523430e430 100644 --- a/Emby.Dlna/ContentDirectory/ContentDirectory.cs +++ b/Emby.Dlna/ContentDirectory/ContentDirectory.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Threading.Tasks; using Emby.Dlna.Service; diff --git a/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs b/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs index 15fdb36c4c..282a47c738 100644 --- a/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs +++ b/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Collections.Generic; using Emby.Dlna.Common; using Emby.Dlna.Service; diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs index 396649c5ea..e5acb92db5 100644 --- a/Emby.Dlna/ContentDirectory/ControlHandler.cs +++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs @@ -1,7 +1,9 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.Globalization; -using System.IO; using System.Linq; using System.Text; using System.Threading; @@ -79,114 +81,129 @@ namespace Emby.Dlna.ContentDirectory _didlBuilder = new DidlBuilder(profile, user, imageProcessor, serverAddress, accessToken, userDataManager, localization, mediaSourceManager, Logger, mediaEncoder); } - protected override IEnumerable> GetResult(string methodName, IDictionary methodParams) + /// + protected override void WriteResult(string methodName, IDictionary methodParams, XmlWriter xmlWriter) { - var deviceId = "test"; - - var user = _user; + const string DeviceId = "test"; if (string.Equals(methodName, "GetSearchCapabilities", StringComparison.OrdinalIgnoreCase)) - return HandleGetSearchCapabilities(); + { + HandleGetSearchCapabilities(xmlWriter); + return; + } if (string.Equals(methodName, "GetSortCapabilities", StringComparison.OrdinalIgnoreCase)) - return HandleGetSortCapabilities(); + { + HandleGetSortCapabilities(xmlWriter); + return; + } if (string.Equals(methodName, "GetSortExtensionCapabilities", StringComparison.OrdinalIgnoreCase)) - return HandleGetSortExtensionCapabilities(); + { + HandleGetSortExtensionCapabilities(xmlWriter); + return; + } if (string.Equals(methodName, "GetSystemUpdateID", StringComparison.OrdinalIgnoreCase)) - return HandleGetSystemUpdateID(); + { + HandleGetSystemUpdateID(xmlWriter); + return; + } if (string.Equals(methodName, "Browse", StringComparison.OrdinalIgnoreCase)) - return HandleBrowse(methodParams, user, deviceId); + { + HandleBrowse(xmlWriter, methodParams, DeviceId); + return; + } if (string.Equals(methodName, "X_GetFeatureList", StringComparison.OrdinalIgnoreCase)) - return HandleXGetFeatureList(); + { + HandleXGetFeatureList(xmlWriter); + return; + } if (string.Equals(methodName, "GetFeatureList", StringComparison.OrdinalIgnoreCase)) - return HandleGetFeatureList(); + { + HandleGetFeatureList(xmlWriter); + return; + } if (string.Equals(methodName, "X_SetBookmark", StringComparison.OrdinalIgnoreCase)) - return HandleXSetBookmark(methodParams, user); + { + HandleXSetBookmark(methodParams); + return; + } if (string.Equals(methodName, "Search", StringComparison.OrdinalIgnoreCase)) - return HandleSearch(methodParams, user, deviceId); + { + HandleSearch(xmlWriter, methodParams, DeviceId); + return; + } if (string.Equals(methodName, "X_BrowseByLetter", StringComparison.OrdinalIgnoreCase)) - return HandleX_BrowseByLetter(methodParams, user, deviceId); + { + HandleXBrowseByLetter(xmlWriter, methodParams, DeviceId); + return; + } throw new ResourceNotFoundException("Unexpected control request name: " + methodName); } - private IEnumerable> HandleXSetBookmark(IDictionary sparams, User user) + private void HandleXSetBookmark(IDictionary sparams) { var id = sparams["ObjectID"]; - var serverItem = GetItemFromObjectId(id, user); + var serverItem = GetItemFromObjectId(id, _user); var item = serverItem.Item; var newbookmark = int.Parse(sparams["PosSecond"], _usCulture); - var userdata = _userDataManager.GetUserData(user, item); + var userdata = _userDataManager.GetUserData(_user, item); userdata.PlaybackPositionTicks = TimeSpan.FromSeconds(newbookmark).Ticks; - _userDataManager.SaveUserData(user, item, userdata, UserDataSaveReason.TogglePlayed, + _userDataManager.SaveUserData(_user, item, userdata, UserDataSaveReason.TogglePlayed, CancellationToken.None); - - return new Dictionary(StringComparer.OrdinalIgnoreCase); } - private IEnumerable> HandleGetSearchCapabilities() + private void HandleGetSearchCapabilities(XmlWriter xmlWriter) { - return new Dictionary(StringComparer.OrdinalIgnoreCase) - { - { "SearchCaps", "res@resolution,res@size,res@duration,dc:title,dc:creator,upnp:actor,upnp:artist,upnp:genre,upnp:album,dc:date,upnp:class,@id,@refID,@protocolInfo,upnp:author,dc:description,pv:avKeywords" } - }; + xmlWriter.WriteElementString( + "SearchCaps", + "res@resolution,res@size,res@duration,dc:title,dc:creator,upnp:actor,upnp:artist,upnp:genre,upnp:album,dc:date,upnp:class,@id,@refID,@protocolInfo,upnp:author,dc:description,pv:avKeywords"); } - private IEnumerable> HandleGetSortCapabilities() + private void HandleGetSortCapabilities(XmlWriter xmlWriter) { - return new Dictionary(StringComparer.OrdinalIgnoreCase) - { - { "SortCaps", "res@duration,res@size,res@bitrate,dc:date,dc:title,dc:size,upnp:album,upnp:artist,upnp:albumArtist,upnp:episodeNumber,upnp:genre,upnp:originalTrackNumber,upnp:rating" } - }; + xmlWriter.WriteElementString( + "SortCaps", + "res@duration,res@size,res@bitrate,dc:date,dc:title,dc:size,upnp:album,upnp:artist,upnp:albumArtist,upnp:episodeNumber,upnp:genre,upnp:originalTrackNumber,upnp:rating"); } - private IEnumerable> HandleGetSortExtensionCapabilities() + private void HandleGetSortExtensionCapabilities(XmlWriter xmlWriter) { - return new Dictionary(StringComparer.OrdinalIgnoreCase) - { - { "SortExtensionCaps", "res@duration,res@size,res@bitrate,dc:date,dc:title,dc:size,upnp:album,upnp:artist,upnp:albumArtist,upnp:episodeNumber,upnp:genre,upnp:originalTrackNumber,upnp:rating" } - }; + xmlWriter.WriteElementString( + "SortExtensionCaps", + "res@duration,res@size,res@bitrate,dc:date,dc:title,dc:size,upnp:album,upnp:artist,upnp:albumArtist,upnp:episodeNumber,upnp:genre,upnp:originalTrackNumber,upnp:rating"); } - private IEnumerable> HandleGetSystemUpdateID() + private void HandleGetSystemUpdateID(XmlWriter xmlWriter) { - var headers = new Dictionary(StringComparer.OrdinalIgnoreCase); - headers.Add("Id", _systemUpdateId.ToString(_usCulture)); - return headers; + xmlWriter.WriteElementString("Id", _systemUpdateId.ToString(CultureInfo.InvariantCulture)); } - private IEnumerable> HandleGetFeatureList() + private void HandleGetFeatureList(XmlWriter xmlWriter) { - return new Dictionary(StringComparer.OrdinalIgnoreCase) - { - { "FeatureList", GetFeatureListXml() } - }; + xmlWriter.WriteElementString("FeatureList", WriteFeatureListXml()); } - private IEnumerable> HandleXGetFeatureList() - { - return new Dictionary(StringComparer.OrdinalIgnoreCase) - { - { "FeatureList", GetFeatureListXml() } - }; - } + private void HandleXGetFeatureList(XmlWriter xmlWriter) + => HandleGetFeatureList(xmlWriter); - private string GetFeatureListXml() + private string WriteFeatureListXml() { + // TODO: clean this up var builder = new StringBuilder(); builder.Append(""); @@ -213,7 +230,7 @@ namespace Emby.Dlna.ContentDirectory return defaultValue; } - private IEnumerable> HandleBrowse(IDictionary sparams, User user, string deviceId) + private void HandleBrowse(XmlWriter xmlWriter, IDictionary sparams, string deviceId) { var id = sparams["ObjectID"]; var flag = sparams["BrowseFlag"]; @@ -237,101 +254,81 @@ namespace Emby.Dlna.ContentDirectory start = startVal; } - var settings = new XmlWriterSettings - { - Encoding = Encoding.UTF8, - CloseOutput = false, - OmitXmlDeclaration = true, - ConformanceLevel = ConformanceLevel.Fragment - }; + xmlWriter.WriteStartElement("Result"); - StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8); + xmlWriter.WriteStartElement(string.Empty, "DIDL-Lite", NS_DIDL); + + xmlWriter.WriteAttributeString("xmlns", "dc", null, NS_DC); + xmlWriter.WriteAttributeString("xmlns", "dlna", null, NS_DLNA); + xmlWriter.WriteAttributeString("xmlns", "upnp", null, NS_UPNP); + //didl.SetAttribute("xmlns:sec", NS_SEC); + + DidlBuilder.WriteXmlRootAttributes(_profile, xmlWriter); + + var serverItem = GetItemFromObjectId(id, _user); + var item = serverItem.Item; int totalCount; - - var dlnaOptions = _config.GetDlnaConfiguration(); - - using (var writer = XmlWriter.Create(builder, settings)) + if (string.Equals(flag, "BrowseMetadata")) { - //writer.WriteStartDocument(); + totalCount = 1; - writer.WriteStartElement(string.Empty, "DIDL-Lite", NS_DIDL); - - writer.WriteAttributeString("xmlns", "dc", null, NS_DC); - writer.WriteAttributeString("xmlns", "dlna", null, NS_DLNA); - writer.WriteAttributeString("xmlns", "upnp", null, NS_UPNP); - //didl.SetAttribute("xmlns:sec", NS_SEC); - - DidlBuilder.WriteXmlRootAttributes(_profile, writer); - - var serverItem = GetItemFromObjectId(id, user); - var item = serverItem.Item; - - if (string.Equals(flag, "BrowseMetadata")) + if (item.IsDisplayedAsFolder || serverItem.StubType.HasValue) { - totalCount = 1; + var childrenResult = GetUserItems(item, serverItem.StubType, _user, sortCriteria, start, requestedCount); - if (item.IsDisplayedAsFolder || serverItem.StubType.HasValue) - { - var childrenResult = GetUserItems(item, serverItem.StubType, user, sortCriteria, start, requestedCount); - - _didlBuilder.WriteFolderElement(writer, item, serverItem.StubType, null, childrenResult.TotalRecordCount, filter, id); - } - else - { - _didlBuilder.WriteItemElement(dlnaOptions, writer, item, user, null, null, deviceId, filter); - } - - provided++; + _didlBuilder.WriteFolderElement(xmlWriter, item, serverItem.StubType, null, childrenResult.TotalRecordCount, filter, id); } else { - var childrenResult = GetUserItems(item, serverItem.StubType, user, sortCriteria, start, requestedCount); - totalCount = childrenResult.TotalRecordCount; - - provided = childrenResult.Items.Count; - - foreach (var i in childrenResult.Items) - { - var childItem = i.Item; - var displayStubType = i.StubType; - - if (childItem.IsDisplayedAsFolder || displayStubType.HasValue) - { - var childCount = (GetUserItems(childItem, displayStubType, user, sortCriteria, null, 0)) - .TotalRecordCount; - - _didlBuilder.WriteFolderElement(writer, childItem, displayStubType, item, childCount, filter); - } - else - { - _didlBuilder.WriteItemElement(dlnaOptions, writer, childItem, user, item, serverItem.StubType, deviceId, filter); - } - } + var dlnaOptions = _config.GetDlnaConfiguration(); + _didlBuilder.WriteItemElement(dlnaOptions, xmlWriter, item, _user, null, null, deviceId, filter); } - writer.WriteFullEndElement(); - //writer.WriteEndDocument(); + provided++; + } + else + { + var childrenResult = GetUserItems(item, serverItem.StubType, _user, sortCriteria, start, requestedCount); + totalCount = childrenResult.TotalRecordCount; + + provided = childrenResult.Items.Count; + + var dlnaOptions = _config.GetDlnaConfiguration(); + foreach (var i in childrenResult.Items) + { + var childItem = i.Item; + var displayStubType = i.StubType; + + if (childItem.IsDisplayedAsFolder || displayStubType.HasValue) + { + var childCount = GetUserItems(childItem, displayStubType, _user, sortCriteria, null, 0) + .TotalRecordCount; + + _didlBuilder.WriteFolderElement(xmlWriter, childItem, displayStubType, item, childCount, filter); + } + else + { + _didlBuilder.WriteItemElement(dlnaOptions, xmlWriter, childItem, _user, item, serverItem.StubType, deviceId, filter); + } + } } - var resXML = builder.ToString(); + xmlWriter.WriteFullEndElement(); + xmlWriter.WriteFullEndElement(); - return new[] - { - new KeyValuePair("Result", resXML), - new KeyValuePair("NumberReturned", provided.ToString(_usCulture)), - new KeyValuePair("TotalMatches", totalCount.ToString(_usCulture)), - new KeyValuePair("UpdateID", _systemUpdateId.ToString(_usCulture)) - }; + xmlWriter.WriteElementString("NumberReturned", provided.ToString(_usCulture)); + xmlWriter.WriteElementString("TotalMatches", totalCount.ToString(_usCulture)); + xmlWriter.WriteElementString("UpdateID", _systemUpdateId.ToString(_usCulture)); } - private IEnumerable> HandleX_BrowseByLetter(IDictionary sparams, User user, string deviceId) + private void HandleXBrowseByLetter(XmlWriter xmlWriter, IDictionary sparams, string deviceId) { // TODO: Implement this method - return HandleSearch(sparams, user, deviceId); + HandleSearch(xmlWriter, sparams, deviceId); } - private IEnumerable> HandleSearch(IDictionary sparams, User user, string deviceId) + private void HandleSearch(XmlWriter xmlWriter, IDictionary sparams, string deviceId) { var searchCriteria = new SearchCriteria(GetValueOrDefault(sparams, "SearchCriteria", "")); var sortCriteria = new SortCriteria(GetValueOrDefault(sparams, "SortCriteria", "")); @@ -354,99 +351,74 @@ namespace Emby.Dlna.ContentDirectory start = startVal; } - var settings = new XmlWriterSettings + xmlWriter.WriteStartElement("Result"); + + xmlWriter.WriteStartElement(string.Empty, "DIDL-Lite", NS_DIDL); + + xmlWriter.WriteAttributeString("xmlns", "dc", null, NS_DC); + xmlWriter.WriteAttributeString("xmlns", "dlna", null, NS_DLNA); + xmlWriter.WriteAttributeString("xmlns", "upnp", null, NS_UPNP); + //didl.SetAttribute("xmlns:sec", NS_SEC); + + DidlBuilder.WriteXmlRootAttributes(_profile, xmlWriter); + + var serverItem = GetItemFromObjectId(sparams["ContainerID"], _user); + + var item = serverItem.Item; + + var childrenResult = GetChildrenSorted(item, _user, searchCriteria, sortCriteria, start, requestedCount); + + var dlnaOptions = _config.GetDlnaConfiguration(); + + foreach (var i in childrenResult.Items) { - Encoding = Encoding.UTF8, - CloseOutput = false, - OmitXmlDeclaration = true, - ConformanceLevel = ConformanceLevel.Fragment - }; - - StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8); - int totalCount = 0; - int provided = 0; - - using (var writer = XmlWriter.Create(builder, settings)) - { - //writer.WriteStartDocument(); - - writer.WriteStartElement(string.Empty, "DIDL-Lite", NS_DIDL); - - writer.WriteAttributeString("xmlns", "dc", null, NS_DC); - writer.WriteAttributeString("xmlns", "dlna", null, NS_DLNA); - writer.WriteAttributeString("xmlns", "upnp", null, NS_UPNP); - //didl.SetAttribute("xmlns:sec", NS_SEC); - - DidlBuilder.WriteXmlRootAttributes(_profile, writer); - - var serverItem = GetItemFromObjectId(sparams["ContainerID"], user); - - var item = serverItem.Item; - - var childrenResult = (GetChildrenSorted(item, user, searchCriteria, sortCriteria, start, requestedCount)); - - totalCount = childrenResult.TotalRecordCount; - - provided = childrenResult.Items.Count; - - var dlnaOptions = _config.GetDlnaConfiguration(); - - foreach (var i in childrenResult.Items) + if (i.IsDisplayedAsFolder) { - if (i.IsDisplayedAsFolder) - { - var childCount = (GetChildrenSorted(i, user, searchCriteria, sortCriteria, null, 0)) - .TotalRecordCount; + var childCount = GetChildrenSorted(i, _user, searchCriteria, sortCriteria, null, 0) + .TotalRecordCount; - _didlBuilder.WriteFolderElement(writer, i, null, item, childCount, filter); - } - else - { - _didlBuilder.WriteItemElement(dlnaOptions, writer, i, user, item, serverItem.StubType, deviceId, filter); - } + _didlBuilder.WriteFolderElement(xmlWriter, i, null, item, childCount, filter); + } + else + { + _didlBuilder.WriteItemElement(dlnaOptions, xmlWriter, i, _user, item, serverItem.StubType, deviceId, filter); } - - writer.WriteFullEndElement(); - //writer.WriteEndDocument(); } - var resXML = builder.ToString(); + xmlWriter.WriteFullEndElement(); + xmlWriter.WriteFullEndElement(); - return new List> - { - new KeyValuePair("Result", resXML), - new KeyValuePair("NumberReturned", provided.ToString(_usCulture)), - new KeyValuePair("TotalMatches", totalCount.ToString(_usCulture)), - new KeyValuePair("UpdateID", _systemUpdateId.ToString(_usCulture)) - }; + xmlWriter.WriteElementString("NumberReturned", childrenResult.Items.Count.ToString(_usCulture)); + xmlWriter.WriteElementString("TotalMatches", childrenResult.TotalRecordCount.ToString(_usCulture)); + xmlWriter.WriteElementString("UpdateID", _systemUpdateId.ToString(_usCulture)); } private QueryResult GetChildrenSorted(BaseItem item, User user, SearchCriteria search, SortCriteria sort, int? startIndex, int? limit) { var folder = (Folder)item; - var sortOrders = new List<(string, SortOrder)>(); - if (!folder.IsPreSorted) + var sortOrders = folder.IsPreSorted switch { - sortOrders.Add((ItemSortBy.SortName, sort.SortOrder)); - } + true => Array.Empty<(string, SortOrder)>(), + false => new[] { (ItemSortBy.SortName, sort.SortOrder) } + }; - var mediaTypes = new List(); + string[] mediaTypes = Array.Empty(); bool? isFolder = null; if (search.SearchType == SearchType.Audio) { - mediaTypes.Add(MediaType.Audio); + mediaTypes = new[] { MediaType.Audio }; isFolder = false; } else if (search.SearchType == SearchType.Video) { - mediaTypes.Add(MediaType.Video); + mediaTypes = new[] { MediaType.Video }; isFolder = false; } else if (search.SearchType == SearchType.Image) { - mediaTypes.Add(MediaType.Photo); + mediaTypes = new[] { MediaType.Photo }; isFolder = false; } else if (search.SearchType == SearchType.Playlist) @@ -470,7 +442,7 @@ namespace Emby.Dlna.ContentDirectory IsMissing = false, ExcludeItemTypes = new[] { typeof(Book).Name }, IsFolder = isFolder, - MediaTypes = mediaTypes.ToArray(), + MediaTypes = mediaTypes, DtoOptions = GetDtoOptions() }); } @@ -1304,11 +1276,11 @@ namespace Emby.Dlna.ContentDirectory StubType? stubType = null; // After using PlayTo, MediaMonkey sends a request to the server trying to get item info - const string paramsSrch = "Params="; - var paramsIndex = id.IndexOf(paramsSrch, StringComparison.OrdinalIgnoreCase); + const string ParamsSrch = "Params="; + var paramsIndex = id.IndexOf(ParamsSrch, StringComparison.OrdinalIgnoreCase); if (paramsIndex != -1) { - id = id.Substring(paramsIndex + paramsSrch.Length); + id = id.Substring(paramsIndex + ParamsSrch.Length); var parts = id.Split(';'); id = parts[23]; diff --git a/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs b/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs index e999314fa6..a385a74cfb 100644 --- a/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs +++ b/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Collections.Generic; using Emby.Dlna.Common; diff --git a/Emby.Dlna/ControlRequest.cs b/Emby.Dlna/ControlRequest.cs index 8c227159c4..97ad41c834 100644 --- a/Emby.Dlna/ControlRequest.cs +++ b/Emby.Dlna/ControlRequest.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.IO; using Microsoft.AspNetCore.Http; diff --git a/Emby.Dlna/ControlResponse.cs b/Emby.Dlna/ControlResponse.cs index d2b79fc585..0215a5e387 100644 --- a/Emby.Dlna/ControlResponse.cs +++ b/Emby.Dlna/ControlResponse.cs @@ -1,18 +1,21 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Collections.Generic; namespace Emby.Dlna { public class ControlResponse { + public ControlResponse() + { + Headers = new Dictionary(); + } + public IDictionary Headers { get; set; } public string Xml { get; set; } public bool IsSuccessful { get; set; } - - public ControlResponse() - { - Headers = new Dictionary(); - } } } diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs index 85ef9d4829..f2128d9c6d 100644 --- a/Emby.Dlna/Didl/DidlBuilder.cs +++ b/Emby.Dlna/Didl/DidlBuilder.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Globalization; using System.IO; @@ -18,7 +21,6 @@ using MediaBrowser.Controller.Playlists; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.Net; using Microsoft.Extensions.Logging; diff --git a/Emby.Dlna/Didl/Filter.cs b/Emby.Dlna/Didl/Filter.cs index a0e67870e9..88cf7cb5a6 100644 --- a/Emby.Dlna/Didl/Filter.cs +++ b/Emby.Dlna/Didl/Filter.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using MediaBrowser.Model.Extensions; diff --git a/Emby.Dlna/Didl/StringWriterWithEncoding.cs b/Emby.Dlna/Didl/StringWriterWithEncoding.cs index c3c4bd393b..edc2588995 100644 --- a/Emby.Dlna/Didl/StringWriterWithEncoding.cs +++ b/Emby.Dlna/Didl/StringWriterWithEncoding.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.IO; using System.Text; diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index d5d788021d..14602485af 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.Globalization; diff --git a/Emby.Dlna/Emby.Dlna.csproj b/Emby.Dlna/Emby.Dlna.csproj index 8d6fabdb44..0cabe43d51 100644 --- a/Emby.Dlna/Emby.Dlna.csproj +++ b/Emby.Dlna/Emby.Dlna.csproj @@ -15,6 +15,19 @@ netstandard2.1 false true + true + + + + + + + + + + + + ../jellyfin.ruleset diff --git a/Emby.Dlna/EventSubscriptionResponse.cs b/Emby.Dlna/EventSubscriptionResponse.cs index 6dc1aacf4f..f90d273c4b 100644 --- a/Emby.Dlna/EventSubscriptionResponse.cs +++ b/Emby.Dlna/EventSubscriptionResponse.cs @@ -1,17 +1,21 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Collections.Generic; namespace Emby.Dlna { public class EventSubscriptionResponse { - public string Content { get; set; } - public string ContentType { get; set; } - - public Dictionary Headers { get; set; } - public EventSubscriptionResponse() { Headers = new Dictionary(); } + + public string Content { get; set; } + + public string ContentType { get; set; } + + public Dictionary Headers { get; set; } } } diff --git a/Emby.Dlna/Eventing/EventManager.cs b/Emby.Dlna/Eventing/EventManager.cs index b76a0066d1..7881898803 100644 --- a/Emby.Dlna/Eventing/EventManager.cs +++ b/Emby.Dlna/Eventing/EventManager.cs @@ -1,8 +1,12 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Net.Http; using System.Text; using System.Threading.Tasks; using MediaBrowser.Common.Extensions; @@ -164,7 +168,7 @@ namespace Emby.Dlna.Eventing try { - using (await _httpClient.SendAsync(options, "NOTIFY").ConfigureAwait(false)) + using (await _httpClient.SendAsync(options, new HttpMethod("NOTIFY")).ConfigureAwait(false)) { } diff --git a/Emby.Dlna/Eventing/EventSubscription.cs b/Emby.Dlna/Eventing/EventSubscription.cs index eb8781e0cd..108ab48303 100644 --- a/Emby.Dlna/Eventing/EventSubscription.cs +++ b/Emby.Dlna/Eventing/EventSubscription.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; namespace Emby.Dlna.Eventing @@ -13,6 +16,8 @@ namespace Emby.Dlna.Eventing public long TriggerCount { get; set; } + public bool IsExpired => SubscriptionTime.AddSeconds(TimeoutSeconds) >= DateTime.UtcNow; + public void IncrementTriggerCount() { if (TriggerCount == long.MaxValue) @@ -22,7 +27,5 @@ namespace Emby.Dlna.Eventing TriggerCount++; } - - public bool IsExpired => SubscriptionTime.AddSeconds(TimeoutSeconds) >= DateTime.UtcNow; } } diff --git a/Emby.Dlna/IConnectionManager.cs b/Emby.Dlna/IConnectionManager.cs index 855c4454d9..01fb869f57 100644 --- a/Emby.Dlna/IConnectionManager.cs +++ b/Emby.Dlna/IConnectionManager.cs @@ -1,3 +1,5 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 namespace Emby.Dlna { diff --git a/Emby.Dlna/IContentDirectory.cs b/Emby.Dlna/IContentDirectory.cs index b54a17c009..a28ad2b9c8 100644 --- a/Emby.Dlna/IContentDirectory.cs +++ b/Emby.Dlna/IContentDirectory.cs @@ -1,3 +1,5 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 namespace Emby.Dlna { diff --git a/Emby.Dlna/IEventManager.cs b/Emby.Dlna/IEventManager.cs index 4f67a1b9b6..d0960aa16c 100644 --- a/Emby.Dlna/IEventManager.cs +++ b/Emby.Dlna/IEventManager.cs @@ -1,3 +1,5 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 namespace Emby.Dlna { diff --git a/Emby.Dlna/IMediaReceiverRegistrar.cs b/Emby.Dlna/IMediaReceiverRegistrar.cs index 5dde01f58b..d2aaa8f553 100644 --- a/Emby.Dlna/IMediaReceiverRegistrar.cs +++ b/Emby.Dlna/IMediaReceiverRegistrar.cs @@ -1,3 +1,5 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 namespace Emby.Dlna { diff --git a/Emby.Dlna/IUpnpService.cs b/Emby.Dlna/IUpnpService.cs index 0f3d327ed2..289e2df78c 100644 --- a/Emby.Dlna/IUpnpService.cs +++ b/Emby.Dlna/IUpnpService.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Threading.Tasks; namespace Emby.Dlna diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 77bde0ca24..1ee4151e4b 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Net.Sockets; using System.Globalization; diff --git a/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs b/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs index 7381e52582..815aac5c7c 100644 --- a/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs +++ b/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs @@ -1,5 +1,9 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; +using System.Xml; using Emby.Dlna.Service; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; @@ -9,35 +13,33 @@ namespace Emby.Dlna.MediaReceiverRegistrar { public class ControlHandler : BaseControlHandler { - protected override IEnumerable> GetResult(string methodName, IDictionary methodParams) - { - if (string.Equals(methodName, "IsAuthorized", StringComparison.OrdinalIgnoreCase)) - return HandleIsAuthorized(); - if (string.Equals(methodName, "IsValidated", StringComparison.OrdinalIgnoreCase)) - return HandleIsValidated(); - - throw new ResourceNotFoundException("Unexpected control request name: " + methodName); - } - - private static IEnumerable> HandleIsAuthorized() - { - return new Dictionary(StringComparer.OrdinalIgnoreCase) - { - { "Result", "1" } - }; - } - - private static IEnumerable> HandleIsValidated() - { - return new Dictionary(StringComparer.OrdinalIgnoreCase) - { - { "Result", "1" } - }; - } - public ControlHandler(IServerConfigurationManager config, ILogger logger) : base(config, logger) { } + + /// + protected override void WriteResult(string methodName, IDictionary methodParams, XmlWriter xmlWriter) + { + if (string.Equals(methodName, "IsAuthorized", StringComparison.OrdinalIgnoreCase)) + { + HandleIsAuthorized(xmlWriter); + return; + } + + if (string.Equals(methodName, "IsValidated", StringComparison.OrdinalIgnoreCase)) + { + HandleIsValidated(xmlWriter); + return; + } + + throw new ResourceNotFoundException("Unexpected control request name: " + methodName); + } + + private static void HandleIsAuthorized(XmlWriter xmlWriter) + => xmlWriter.WriteElementString("Result", "1"); + + private static void HandleIsValidated(XmlWriter xmlWriter) + => xmlWriter.WriteElementString("Result", "1"); } } diff --git a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs index 5eab6aee0c..e2d48bc01f 100644 --- a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs +++ b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrar.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Threading.Tasks; using Emby.Dlna.Service; using MediaBrowser.Common.Net; diff --git a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs index 6413411851..465b08f58e 100644 --- a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs +++ b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Collections.Generic; using Emby.Dlna.Common; using Emby.Dlna.Service; diff --git a/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs b/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs index 86429f6051..3e8b2dbd88 100644 --- a/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs +++ b/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Collections.Generic; using Emby.Dlna.Common; diff --git a/Emby.Dlna/PlayTo/Device.cs b/Emby.Dlna/PlayTo/Device.cs index 0c5ddee654..61db264a2f 100644 --- a/Emby.Dlna/PlayTo/Device.cs +++ b/Emby.Dlna/PlayTo/Device.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.Globalization; @@ -221,7 +224,7 @@ namespace Emby.Dlna.PlayTo _logger.LogDebug("Setting mute"); var value = mute ? 1 : 0; - await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType, value)) + await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType, value)) .ConfigureAwait(false); IsMuted = mute; @@ -251,7 +254,7 @@ namespace Emby.Dlna.PlayTo // Remote control will perform better Volume = value; - await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType, value)) + await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType, value)) .ConfigureAwait(false); } @@ -270,7 +273,7 @@ namespace Emby.Dlna.PlayTo throw new InvalidOperationException("Unable to find service"); } - await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType, string.Format("{0:hh}:{0:mm}:{0:ss}", value), "REL_TIME")) + await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType, string.Format("{0:hh}:{0:mm}:{0:ss}", value), "REL_TIME")) .ConfigureAwait(false); RestartTimer(true); @@ -302,7 +305,7 @@ namespace Emby.Dlna.PlayTo } var post = avCommands.BuildPost(command, service.ServiceType, url, dictionary); - await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, post, header: header) + await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, post, header: header) .ConfigureAwait(false); await Task.Delay(50).ConfigureAwait(false); @@ -344,7 +347,7 @@ namespace Emby.Dlna.PlayTo throw new InvalidOperationException("Unable to find service"); } - return new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType, 1)); + return new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType, 1)); } public async Task SetPlay(CancellationToken cancellationToken) @@ -368,7 +371,7 @@ namespace Emby.Dlna.PlayTo var service = GetAvTransportService(); - await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType, 1)) + await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType, 1)) .ConfigureAwait(false); RestartTimer(true); @@ -386,7 +389,7 @@ namespace Emby.Dlna.PlayTo var service = GetAvTransportService(); - await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType, 1)) + await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType, 1)) .ConfigureAwait(false); TransportState = TRANSPORTSTATE.PAUSED; @@ -513,7 +516,7 @@ namespace Emby.Dlna.PlayTo return; } - var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType), true) + var result = await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType), true) .ConfigureAwait(false); if (result == null || result.Document == null) @@ -559,7 +562,7 @@ namespace Emby.Dlna.PlayTo return; } - var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType), true) + var result = await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType), true) .ConfigureAwait(false); if (result == null || result.Document == null) @@ -586,7 +589,7 @@ namespace Emby.Dlna.PlayTo return null; } - var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType), false) + var result = await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, avCommands.BuildPost(command, service.ServiceType), false) .ConfigureAwait(false); if (result == null || result.Document == null) @@ -624,7 +627,7 @@ namespace Emby.Dlna.PlayTo var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false); - var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType), false) + var result = await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType), false) .ConfigureAwait(false); if (result == null || result.Document == null) @@ -687,7 +690,7 @@ namespace Emby.Dlna.PlayTo var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false); - var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType), false) + var result = await new SsdpHttpClient(_httpClient).SendCommandAsync(Properties.BaseUrl, service, command.Name, rendererCommands.BuildPost(command, service.ServiceType), false) .ConfigureAwait(false); if (result == null || result.Document == null) @@ -868,7 +871,7 @@ namespace Emby.Dlna.PlayTo string url = NormalizeUrl(Properties.BaseUrl, avService.ScpdUrl); - var httpClient = new SsdpHttpClient(_httpClient, _config); + var httpClient = new SsdpHttpClient(_httpClient); var document = await httpClient.GetDataAsync(url, cancellationToken).ConfigureAwait(false); @@ -896,7 +899,7 @@ namespace Emby.Dlna.PlayTo string url = NormalizeUrl(Properties.BaseUrl, avService.ScpdUrl); - var httpClient = new SsdpHttpClient(_httpClient, _config); + var httpClient = new SsdpHttpClient(_httpClient); _logger.LogDebug("Dlna Device.GetRenderingProtocolAsync"); var document = await httpClient.GetDataAsync(url, cancellationToken).ConfigureAwait(false); @@ -931,7 +934,7 @@ namespace Emby.Dlna.PlayTo public static async Task CreateuPnpDeviceAsync(Uri url, IHttpClient httpClient, IServerConfigurationManager config, ILogger logger, CancellationToken cancellationToken) { - var ssdpHttpClient = new SsdpHttpClient(httpClient, config); + var ssdpHttpClient = new SsdpHttpClient(httpClient); var document = await ssdpHttpClient.GetDataAsync(url.ToString(), cancellationToken).ConfigureAwait(false); diff --git a/Emby.Dlna/PlayTo/DeviceInfo.cs b/Emby.Dlna/PlayTo/DeviceInfo.cs index 9e7c04bdb3..c36f890966 100644 --- a/Emby.Dlna/PlayTo/DeviceInfo.cs +++ b/Emby.Dlna/PlayTo/DeviceInfo.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Collections.Generic; using Emby.Dlna.Common; using MediaBrowser.Model.Dlna; diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index c58f16438b..ad01f0576d 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.Globalization; diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs index 2ca44b7ea2..5d75e33600 100644 --- a/Emby.Dlna/PlayTo/PlayToManager.cs +++ b/Emby.Dlna/PlayTo/PlayToManager.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Globalization; using System.Linq; @@ -21,7 +24,7 @@ using Microsoft.Extensions.Logging; namespace Emby.Dlna.PlayTo { - class PlayToManager : IDisposable + public class PlayToManager : IDisposable { private readonly ILogger _logger; private readonly ISessionManager _sessionManager; @@ -64,10 +67,10 @@ namespace Emby.Dlna.PlayTo public void Start() { - _deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered; + _deviceDiscovery.DeviceDiscovered += OnDeviceDiscoveryDeviceDiscovered; } - async void _deviceDiscovery_DeviceDiscovered(object sender, GenericEventArgs e) + private async void OnDeviceDiscoveryDeviceDiscovered(object sender, GenericEventArgs e) { if (_disposed) { @@ -231,7 +234,7 @@ namespace Emby.Dlna.PlayTo public void Dispose() { - _deviceDiscovery.DeviceDiscovered -= _deviceDiscovery_DeviceDiscovered; + _deviceDiscovery.DeviceDiscovered -= OnDeviceDiscoveryDeviceDiscovered; try { diff --git a/Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs b/Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs index ffa56419bb..bdd2a6c3e4 100644 --- a/Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs +++ b/Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; namespace Emby.Dlna.PlayTo diff --git a/Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs b/Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs index 8cd8b47acf..485f7ec103 100644 --- a/Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs +++ b/Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; namespace Emby.Dlna.PlayTo diff --git a/Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs b/Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs index 2afdc324d9..2eddb125d4 100644 --- a/Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs +++ b/Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; namespace Emby.Dlna.PlayTo diff --git a/Emby.Dlna/PlayTo/PlaylistItem.cs b/Emby.Dlna/PlayTo/PlaylistItem.cs index 1e62b61e93..42d73c38ca 100644 --- a/Emby.Dlna/PlayTo/PlaylistItem.cs +++ b/Emby.Dlna/PlayTo/PlaylistItem.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.PlayTo diff --git a/Emby.Dlna/PlayTo/PlaylistItemFactory.cs b/Emby.Dlna/PlayTo/PlaylistItemFactory.cs index 446d8e1e6e..8e279da6fc 100644 --- a/Emby.Dlna/PlayTo/PlaylistItemFactory.cs +++ b/Emby.Dlna/PlayTo/PlaylistItemFactory.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Globalization; using System.IO; using System.Linq; diff --git a/Emby.Dlna/PlayTo/SsdpHttpClient.cs b/Emby.Dlna/PlayTo/SsdpHttpClient.cs index 66c634150a..757e713e1c 100644 --- a/Emby.Dlna/PlayTo/SsdpHttpClient.cs +++ b/Emby.Dlna/PlayTo/SsdpHttpClient.cs @@ -1,13 +1,16 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Globalization; using System.IO; +using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Emby.Dlna.Common; using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Configuration; namespace Emby.Dlna.PlayTo { @@ -19,12 +22,10 @@ namespace Emby.Dlna.PlayTo private readonly CultureInfo _usCulture = new CultureInfo("en-US"); private readonly IHttpClient _httpClient; - private readonly IServerConfigurationManager _config; - public SsdpHttpClient(IHttpClient httpClient, IServerConfigurationManager config) + public SsdpHttpClient(IHttpClient httpClient) { _httpClient = httpClient; - _config = config; } public async Task SendCommandAsync( @@ -64,7 +65,9 @@ namespace Emby.Dlna.PlayTo } if (!serviceUrl.StartsWith("/")) + { serviceUrl = "/" + serviceUrl; + } return baseUrl + serviceUrl; } @@ -90,7 +93,7 @@ namespace Emby.Dlna.PlayTo options.RequestHeaders["NT"] = "upnp:event"; options.RequestHeaders["TIMEOUT"] = "Second-" + timeOut.ToString(_usCulture); - using (await _httpClient.SendAsync(options, "SUBSCRIBE").ConfigureAwait(false)) + using (await _httpClient.SendAsync(options, new HttpMethod("SUBSCRIBE")).ConfigureAwait(false)) { } @@ -110,7 +113,7 @@ namespace Emby.Dlna.PlayTo options.RequestHeaders["FriendlyName.DLNA.ORG"] = FriendlyName; - using (var response = await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)) + using (var response = await _httpClient.SendAsync(options, HttpMethod.Get).ConfigureAwait(false)) using (var stream = response.Content) using (var reader = new StreamReader(stream, Encoding.UTF8)) { diff --git a/Emby.Dlna/PlayTo/TRANSPORTSTATE.cs b/Emby.Dlna/PlayTo/TRANSPORTSTATE.cs index 9f1690b04f..b312c8b6ec 100644 --- a/Emby.Dlna/PlayTo/TRANSPORTSTATE.cs +++ b/Emby.Dlna/PlayTo/TRANSPORTSTATE.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + namespace Emby.Dlna.PlayTo { public enum TRANSPORTSTATE diff --git a/Emby.Dlna/PlayTo/TransportCommands.cs b/Emby.Dlna/PlayTo/TransportCommands.cs index 4f9e398e90..a00d154f78 100644 --- a/Emby.Dlna/PlayTo/TransportCommands.cs +++ b/Emby.Dlna/PlayTo/TransportCommands.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.Linq; diff --git a/Emby.Dlna/PlayTo/UpnpContainer.cs b/Emby.Dlna/PlayTo/UpnpContainer.cs index 943e0347b2..9700d8a5d1 100644 --- a/Emby.Dlna/PlayTo/UpnpContainer.cs +++ b/Emby.Dlna/PlayTo/UpnpContainer.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Xml.Linq; using Emby.Dlna.Ssdp; diff --git a/Emby.Dlna/PlayTo/uBaseObject.cs b/Emby.Dlna/PlayTo/uBaseObject.cs index f29a126df7..6e2e31dc47 100644 --- a/Emby.Dlna/PlayTo/uBaseObject.cs +++ b/Emby.Dlna/PlayTo/uBaseObject.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; namespace Emby.Dlna.PlayTo diff --git a/Emby.Dlna/PlayTo/uPnpNamespaces.cs b/Emby.Dlna/PlayTo/uPnpNamespaces.cs index 7132ecd15c..fc0f0f704f 100644 --- a/Emby.Dlna/PlayTo/uPnpNamespaces.cs +++ b/Emby.Dlna/PlayTo/uPnpNamespaces.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Xml.Linq; namespace Emby.Dlna.PlayTo diff --git a/Emby.Dlna/Profiles/DefaultProfile.cs b/Emby.Dlna/Profiles/DefaultProfile.cs index ea50bd4a75..97286e3472 100644 --- a/Emby.Dlna/Profiles/DefaultProfile.cs +++ b/Emby.Dlna/Profiles/DefaultProfile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Linq; using MediaBrowser.Model.Dlna; diff --git a/Emby.Dlna/Profiles/DenonAvrProfile.cs b/Emby.Dlna/Profiles/DenonAvrProfile.cs index a738851915..3be9805288 100644 --- a/Emby.Dlna/Profiles/DenonAvrProfile.cs +++ b/Emby.Dlna/Profiles/DenonAvrProfile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/DirectTvProfile.cs b/Emby.Dlna/Profiles/DirectTvProfile.cs index 317c0976a2..33bcae6044 100644 --- a/Emby.Dlna/Profiles/DirectTvProfile.cs +++ b/Emby.Dlna/Profiles/DirectTvProfile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/DishHopperJoeyProfile.cs b/Emby.Dlna/Profiles/DishHopperJoeyProfile.cs index 8d8ab41cad..26654b803c 100644 --- a/Emby.Dlna/Profiles/DishHopperJoeyProfile.cs +++ b/Emby.Dlna/Profiles/DishHopperJoeyProfile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/Foobar2000Profile.cs b/Emby.Dlna/Profiles/Foobar2000Profile.cs index 947194bce4..c1aece8c8a 100644 --- a/Emby.Dlna/Profiles/Foobar2000Profile.cs +++ b/Emby.Dlna/Profiles/Foobar2000Profile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/LgTvProfile.cs b/Emby.Dlna/Profiles/LgTvProfile.cs index 145685ab12..63b5b6f311 100644 --- a/Emby.Dlna/Profiles/LgTvProfile.cs +++ b/Emby.Dlna/Profiles/LgTvProfile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/LinksysDMA2100Profile.cs b/Emby.Dlna/Profiles/LinksysDMA2100Profile.cs index 3f0bb4263d..3a9744e381 100644 --- a/Emby.Dlna/Profiles/LinksysDMA2100Profile.cs +++ b/Emby.Dlna/Profiles/LinksysDMA2100Profile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/MarantzProfile.cs b/Emby.Dlna/Profiles/MarantzProfile.cs index 162e284be6..05f94a2063 100644 --- a/Emby.Dlna/Profiles/MarantzProfile.cs +++ b/Emby.Dlna/Profiles/MarantzProfile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/MediaMonkeyProfile.cs b/Emby.Dlna/Profiles/MediaMonkeyProfile.cs index 53cae4e2ff..10218fa563 100644 --- a/Emby.Dlna/Profiles/MediaMonkeyProfile.cs +++ b/Emby.Dlna/Profiles/MediaMonkeyProfile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/PanasonicVieraProfile.cs b/Emby.Dlna/Profiles/PanasonicVieraProfile.cs index 5f31ec484e..945ec45187 100644 --- a/Emby.Dlna/Profiles/PanasonicVieraProfile.cs +++ b/Emby.Dlna/Profiles/PanasonicVieraProfile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/PopcornHourProfile.cs b/Emby.Dlna/Profiles/PopcornHourProfile.cs index aefe8c44f3..3765d01dc4 100644 --- a/Emby.Dlna/Profiles/PopcornHourProfile.cs +++ b/Emby.Dlna/Profiles/PopcornHourProfile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/SamsungSmartTvProfile.cs b/Emby.Dlna/Profiles/SamsungSmartTvProfile.cs index 51a1c81735..61c5f4dce9 100644 --- a/Emby.Dlna/Profiles/SamsungSmartTvProfile.cs +++ b/Emby.Dlna/Profiles/SamsungSmartTvProfile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/SharpSmartTvProfile.cs b/Emby.Dlna/Profiles/SharpSmartTvProfile.cs index f840cfb346..8967dc16a9 100644 --- a/Emby.Dlna/Profiles/SharpSmartTvProfile.cs +++ b/Emby.Dlna/Profiles/SharpSmartTvProfile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/SonyBlurayPlayer2013.cs b/Emby.Dlna/Profiles/SonyBlurayPlayer2013.cs index 2af1d3b501..308d74aa84 100644 --- a/Emby.Dlna/Profiles/SonyBlurayPlayer2013.cs +++ b/Emby.Dlna/Profiles/SonyBlurayPlayer2013.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/SonyBlurayPlayer2014.cs b/Emby.Dlna/Profiles/SonyBlurayPlayer2014.cs index 3de0b51922..496c243160 100644 --- a/Emby.Dlna/Profiles/SonyBlurayPlayer2014.cs +++ b/Emby.Dlna/Profiles/SonyBlurayPlayer2014.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/SonyBlurayPlayer2015.cs b/Emby.Dlna/Profiles/SonyBlurayPlayer2015.cs index 889484bea5..987a9af4b1 100644 --- a/Emby.Dlna/Profiles/SonyBlurayPlayer2015.cs +++ b/Emby.Dlna/Profiles/SonyBlurayPlayer2015.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/SonyBlurayPlayer2016.cs b/Emby.Dlna/Profiles/SonyBlurayPlayer2016.cs index acb90bd01b..560193dedd 100644 --- a/Emby.Dlna/Profiles/SonyBlurayPlayer2016.cs +++ b/Emby.Dlna/Profiles/SonyBlurayPlayer2016.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/SonyBlurayPlayerProfile.cs b/Emby.Dlna/Profiles/SonyBlurayPlayerProfile.cs index e1808b2052..c983d98baf 100644 --- a/Emby.Dlna/Profiles/SonyBlurayPlayerProfile.cs +++ b/Emby.Dlna/Profiles/SonyBlurayPlayerProfile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/SonyBravia2010Profile.cs b/Emby.Dlna/Profiles/SonyBravia2010Profile.cs index f8e8faa76d..186c894736 100644 --- a/Emby.Dlna/Profiles/SonyBravia2010Profile.cs +++ b/Emby.Dlna/Profiles/SonyBravia2010Profile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/SonyBravia2011Profile.cs b/Emby.Dlna/Profiles/SonyBravia2011Profile.cs index 111f36e9b5..a29d143f68 100644 --- a/Emby.Dlna/Profiles/SonyBravia2011Profile.cs +++ b/Emby.Dlna/Profiles/SonyBravia2011Profile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/SonyBravia2012Profile.cs b/Emby.Dlna/Profiles/SonyBravia2012Profile.cs index d5efe42707..9bcdd21b8f 100644 --- a/Emby.Dlna/Profiles/SonyBravia2012Profile.cs +++ b/Emby.Dlna/Profiles/SonyBravia2012Profile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/SonyBravia2013Profile.cs b/Emby.Dlna/Profiles/SonyBravia2013Profile.cs index 3b0228694b..900e4ff06e 100644 --- a/Emby.Dlna/Profiles/SonyBravia2013Profile.cs +++ b/Emby.Dlna/Profiles/SonyBravia2013Profile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/SonyBravia2014Profile.cs b/Emby.Dlna/Profiles/SonyBravia2014Profile.cs index e860eae346..963e7993e1 100644 --- a/Emby.Dlna/Profiles/SonyBravia2014Profile.cs +++ b/Emby.Dlna/Profiles/SonyBravia2014Profile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/SonyPs3Profile.cs b/Emby.Dlna/Profiles/SonyPs3Profile.cs index 88d0646955..31a764d8d3 100644 --- a/Emby.Dlna/Profiles/SonyPs3Profile.cs +++ b/Emby.Dlna/Profiles/SonyPs3Profile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/SonyPs4Profile.cs b/Emby.Dlna/Profiles/SonyPs4Profile.cs index 499cf88038..9376a564ba 100644 --- a/Emby.Dlna/Profiles/SonyPs4Profile.cs +++ b/Emby.Dlna/Profiles/SonyPs4Profile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/WdtvLiveProfile.cs b/Emby.Dlna/Profiles/WdtvLiveProfile.cs index bf7b1ab47e..8e056792a6 100644 --- a/Emby.Dlna/Profiles/WdtvLiveProfile.cs +++ b/Emby.Dlna/Profiles/WdtvLiveProfile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Profiles/XboxOneProfile.cs b/Emby.Dlna/Profiles/XboxOneProfile.cs index 710b891e3d..364c433549 100644 --- a/Emby.Dlna/Profiles/XboxOneProfile.cs +++ b/Emby.Dlna/Profiles/XboxOneProfile.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using MediaBrowser.Model.Dlna; namespace Emby.Dlna.Profiles diff --git a/Emby.Dlna/Server/DescriptionXmlBuilder.cs b/Emby.Dlna/Server/DescriptionXmlBuilder.cs index 03d8f80abb..df48246377 100644 --- a/Emby.Dlna/Server/DescriptionXmlBuilder.cs +++ b/Emby.Dlna/Server/DescriptionXmlBuilder.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.Globalization; diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs index 49129f6ffd..0125c0528a 100644 --- a/Emby.Dlna/Service/BaseControlHandler.cs +++ b/Emby.Dlna/Service/BaseControlHandler.cs @@ -1,7 +1,9 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; @@ -66,8 +68,6 @@ namespace Emby.Dlna.Service Logger.LogDebug("Received control request {0}", requestInfo.LocalName); - var result = GetResult(requestInfo.LocalName, requestInfo.Headers); - var settings = new XmlWriterSettings { Encoding = Encoding.UTF8, @@ -85,12 +85,9 @@ namespace Emby.Dlna.Service writer.WriteStartElement("SOAP-ENV", "Body", NS_SOAPENV); writer.WriteStartElement("u", requestInfo.LocalName + "Response", requestInfo.NamespaceURI); - foreach (var i in result) - { - writer.WriteStartElement(i.Key); - writer.WriteString(i.Value); - writer.WriteFullEndElement(); - } + + WriteResult(requestInfo.LocalName, requestInfo.Headers, writer); + writer.WriteFullEndElement(); writer.WriteFullEndElement(); @@ -219,7 +216,7 @@ namespace Emby.Dlna.Service public Dictionary Headers { get; } = new Dictionary(StringComparer.OrdinalIgnoreCase); } - protected abstract IEnumerable> GetResult(string methodName, IDictionary methodParams); + protected abstract void WriteResult(string methodName, IDictionary methodParams, XmlWriter xmlWriter); private void LogRequest(ControlRequest request) { diff --git a/Emby.Dlna/Service/BaseService.cs b/Emby.Dlna/Service/BaseService.cs index 5359e94c44..d7e5c541d9 100644 --- a/Emby.Dlna/Service/BaseService.cs +++ b/Emby.Dlna/Service/BaseService.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using Emby.Dlna.Eventing; using MediaBrowser.Common.Net; using Microsoft.Extensions.Logging; diff --git a/Emby.Dlna/Service/ControlErrorHandler.cs b/Emby.Dlna/Service/ControlErrorHandler.cs index bbf975f384..a2f5057fb0 100644 --- a/Emby.Dlna/Service/ControlErrorHandler.cs +++ b/Emby.Dlna/Service/ControlErrorHandler.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.IO; using System.Text; diff --git a/Emby.Dlna/Service/ServiceXmlBuilder.cs b/Emby.Dlna/Service/ServiceXmlBuilder.cs index bd1f0bf05c..0787b8df94 100644 --- a/Emby.Dlna/Service/ServiceXmlBuilder.cs +++ b/Emby.Dlna/Service/ServiceXmlBuilder.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Collections.Generic; using System.Text; using Emby.Dlna.Common; diff --git a/Emby.Dlna/Ssdp/DeviceDiscovery.cs b/Emby.Dlna/Ssdp/DeviceDiscovery.cs index c5f3593da8..c5e57d0ff0 100644 --- a/Emby.Dlna/Ssdp/DeviceDiscovery.cs +++ b/Emby.Dlna/Ssdp/DeviceDiscovery.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.Linq; @@ -9,16 +12,16 @@ using Rssdp.Infrastructure; namespace Emby.Dlna.Ssdp { - public class DeviceDiscovery : IDeviceDiscovery + public sealed class DeviceDiscovery : IDeviceDiscovery, IDisposable { - private bool _disposed; + private readonly object _syncLock = new object(); private readonly IServerConfigurationManager _config; - private event EventHandler> DeviceDiscoveredInternal; - private int _listenerCount; - private object _syncLock = new object(); + private bool _disposed; + + private event EventHandler> DeviceDiscoveredInternal; /// public event EventHandler> DeviceDiscovered @@ -33,6 +36,7 @@ namespace Emby.Dlna.Ssdp StartInternal(); } + remove { lock (_syncLock) @@ -130,6 +134,7 @@ namespace Emby.Dlna.Ssdp DeviceLeft?.Invoke(this, args); } + /// public void Dispose() { if (!_disposed) diff --git a/Emby.Dlna/Ssdp/Extensions.cs b/Emby.Dlna/Ssdp/Extensions.cs index c680c123ed..836d4abfd2 100644 --- a/Emby.Dlna/Ssdp/Extensions.cs +++ b/Emby.Dlna/Ssdp/Extensions.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Xml.Linq; namespace Emby.Dlna.Ssdp From dc62e436c43362f2193415f4c81280c6c1a8560c Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 22 Jan 2020 22:18:56 +0100 Subject: [PATCH 105/881] Clean up Emby.Naming --- Emby.Naming/Audio/AlbumParser.cs | 11 +- Emby.Naming/Audio/MultiPartResult.cs | 26 ---- Emby.Naming/AudioBook/AudioBookFileInfo.cs | 2 +- .../AudioBook/AudioBookListResolver.cs | 19 +-- Emby.Naming/Common/EpisodeExpression.cs | 36 ++--- Emby.Naming/Common/NamingOptions.cs | 83 +++++------ Emby.Naming/Emby.Naming.csproj | 5 +- Emby.Naming/TV/EpisodePathParser.cs | 5 +- Emby.Naming/TV/EpisodeResolver.cs | 20 +-- Emby.Naming/TV/SeasonPathParser.cs | 39 +++--- Emby.Naming/Video/StackResolver.cs | 21 +-- Emby.Naming/Video/StackResult.cs | 17 --- Emby.Naming/Video/StubResolver.cs | 20 ++- Emby.Naming/Video/VideoFileInfo.cs | 2 +- Emby.Naming/Video/VideoInfo.cs | 18 ++- Emby.Naming/Video/VideoListResolver.cs | 43 +++--- Emby.Naming/Video/VideoResolver.cs | 21 ++- .../Library/LibraryManager.cs | 2 +- .../Resolvers/Audio/MusicAlbumResolver.cs | 20 +-- .../Library/Resolvers/Movies/MovieResolver.cs | 73 +++++----- .../Library/Resolvers/TV/SeasonResolver.cs | 21 ++- .../Library/Resolvers/TV/SeriesResolver.cs | 2 +- Jellyfin.Server/Jellyfin.Server.csproj | 3 - .../Music/MultiDiscAlbumTests.cs | 2 +- .../TV/SeasonFolderTests.cs | 3 +- .../Jellyfin.Naming.Tests/Video/StackTests.cs | 130 +++++++++--------- .../Jellyfin.Naming.Tests/Video/StubTests.cs | 10 +- 27 files changed, 287 insertions(+), 367 deletions(-) delete mode 100644 Emby.Naming/Audio/MultiPartResult.cs delete mode 100644 Emby.Naming/Video/StackResult.cs diff --git a/Emby.Naming/Audio/AlbumParser.cs b/Emby.Naming/Audio/AlbumParser.cs index 4975b8e19d..b807816eba 100644 --- a/Emby.Naming/Audio/AlbumParser.cs +++ b/Emby.Naming/Audio/AlbumParser.cs @@ -19,15 +19,13 @@ namespace Emby.Naming.Audio _options = options; } - public MultiPartResult ParseMultiPart(string path) + public bool IsMultiPart(string path) { - var result = new MultiPartResult(); - var filename = Path.GetFileName(path); if (string.IsNullOrEmpty(filename)) { - return result; + return false; } // TODO: Move this logic into options object @@ -57,12 +55,11 @@ namespace Emby.Naming.Audio if (int.TryParse(tmp, NumberStyles.Integer, CultureInfo.InvariantCulture, out _)) { - result.IsMultiPart = true; - break; + return true; } } - return result; + return false; } } } diff --git a/Emby.Naming/Audio/MultiPartResult.cs b/Emby.Naming/Audio/MultiPartResult.cs deleted file mode 100644 index 8f68d97fa8..0000000000 --- a/Emby.Naming/Audio/MultiPartResult.cs +++ /dev/null @@ -1,26 +0,0 @@ -#pragma warning disable CS1591 -#pragma warning disable SA1600 - -namespace Emby.Naming.Audio -{ - public class MultiPartResult - { - /// - /// Gets or sets the name. - /// - /// The name. - public string Name { get; set; } - - /// - /// Gets or sets the part. - /// - /// The part. - public string Part { get; set; } - - /// - /// Gets or sets a value indicating whether this instance is multi part. - /// - /// true if this instance is multi part; otherwise, false. - public bool IsMultiPart { get; set; } - } -} diff --git a/Emby.Naming/AudioBook/AudioBookFileInfo.cs b/Emby.Naming/AudioBook/AudioBookFileInfo.cs index 769e3d7fac..0bc6ec7e40 100644 --- a/Emby.Naming/AudioBook/AudioBookFileInfo.cs +++ b/Emby.Naming/AudioBook/AudioBookFileInfo.cs @@ -32,7 +32,7 @@ namespace Emby.Naming.AudioBook public int? ChapterNumber { get; set; } /// - /// Gets or sets the type. + /// Gets or sets a value indicating whether this instance is a directory. /// /// The type. public bool IsDirectory { get; set; } diff --git a/Emby.Naming/AudioBook/AudioBookListResolver.cs b/Emby.Naming/AudioBook/AudioBookListResolver.cs index 97f3592857..835e83a081 100644 --- a/Emby.Naming/AudioBook/AudioBookListResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookListResolver.cs @@ -39,9 +39,7 @@ namespace Emby.Naming.AudioBook var stackResult = new StackResolver(_options) .ResolveAudioBooks(metadata); - var list = new List(); - - foreach (var stack in stackResult.Stacks) + foreach (var stack in stackResult) { var stackFiles = stack.Files.Select(i => audioBookResolver.Resolve(i, stack.IsDirectoryStack)).ToList(); stackFiles.Sort(); @@ -50,20 +48,9 @@ namespace Emby.Naming.AudioBook Files = stackFiles, Name = stack.Name }; - list.Add(info); + + yield return info; } - - // Whatever files are left, just add them - /*list.AddRange(remainingFiles.Select(i => new AudioBookInfo - { - Files = new List { i }, - Name = i., - Year = i.Year - }));*/ - - var orderedList = list.OrderBy(i => i.Name); - - return orderedList; } } } diff --git a/Emby.Naming/Common/EpisodeExpression.cs b/Emby.Naming/Common/EpisodeExpression.cs index 30a74fb657..f60f7e84b1 100644 --- a/Emby.Naming/Common/EpisodeExpression.cs +++ b/Emby.Naming/Common/EpisodeExpression.cs @@ -11,6 +11,24 @@ namespace Emby.Naming.Common private string _expression; private Regex _regex; + public EpisodeExpression(string expression, bool byDate) + { + Expression = expression; + IsByDate = byDate; + DateTimeFormats = Array.Empty(); + SupportsAbsoluteEpisodeNumbers = true; + } + + public EpisodeExpression(string expression) + : this(expression, false) + { + } + + public EpisodeExpression() + : this(null) + { + } + public string Expression { get => _expression; @@ -32,23 +50,5 @@ namespace Emby.Naming.Common public string[] DateTimeFormats { get; set; } public Regex Regex => _regex ?? (_regex = new Regex(Expression, RegexOptions.IgnoreCase | RegexOptions.Compiled)); - - public EpisodeExpression(string expression, bool byDate) - { - Expression = expression; - IsByDate = byDate; - DateTimeFormats = Array.Empty(); - SupportsAbsoluteEpisodeNumbers = true; - } - - public EpisodeExpression(string expression) - : this(expression, false) - { - } - - public EpisodeExpression() - : this(null) - { - } } } diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 9ce503b8e4..1554e61d83 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -11,46 +11,6 @@ namespace Emby.Naming.Common { public class NamingOptions { - public string[] AudioFileExtensions { get; set; } - - public string[] AlbumStackingPrefixes { get; set; } - - public string[] SubtitleFileExtensions { get; set; } - - public char[] SubtitleFlagDelimiters { get; set; } - - public string[] SubtitleForcedFlags { get; set; } - - public string[] SubtitleDefaultFlags { get; set; } - - public EpisodeExpression[] EpisodeExpressions { get; set; } - - public string[] EpisodeWithoutSeasonExpressions { get; set; } - - public string[] EpisodeMultiPartExpressions { get; set; } - - public string[] VideoFileExtensions { get; set; } - - public string[] StubFileExtensions { get; set; } - - public string[] AudioBookPartsExpressions { get; set; } - - public StubTypeRule[] StubTypes { get; set; } - - public char[] VideoFlagDelimiters { get; set; } - - public Format3DRule[] Format3DRules { get; set; } - - public string[] VideoFileStackingExpressions { get; set; } - - public string[] CleanDateTimes { get; set; } - - public string[] CleanStrings { get; set; } - - public EpisodeExpression[] MultipleEpisodeExpressions { get; set; } - - public ExtraRule[] VideoExtraRules { get; set; } - public NamingOptions() { VideoFileExtensions = new[] @@ -681,11 +641,54 @@ namespace Emby.Naming.Common Compile(); } + public string[] AudioFileExtensions { get; set; } + + public string[] AlbumStackingPrefixes { get; set; } + + public string[] SubtitleFileExtensions { get; set; } + + public char[] SubtitleFlagDelimiters { get; set; } + + public string[] SubtitleForcedFlags { get; set; } + + public string[] SubtitleDefaultFlags { get; set; } + + public EpisodeExpression[] EpisodeExpressions { get; set; } + + public string[] EpisodeWithoutSeasonExpressions { get; set; } + + public string[] EpisodeMultiPartExpressions { get; set; } + + public string[] VideoFileExtensions { get; set; } + + public string[] StubFileExtensions { get; set; } + + public string[] AudioBookPartsExpressions { get; set; } + + public StubTypeRule[] StubTypes { get; set; } + + public char[] VideoFlagDelimiters { get; set; } + + public Format3DRule[] Format3DRules { get; set; } + + public string[] VideoFileStackingExpressions { get; set; } + + public string[] CleanDateTimes { get; set; } + + public string[] CleanStrings { get; set; } + + public EpisodeExpression[] MultipleEpisodeExpressions { get; set; } + + public ExtraRule[] VideoExtraRules { get; set; } + public Regex[] VideoFileStackingRegexes { get; private set; } + public Regex[] CleanDateTimeRegexes { get; private set; } + public Regex[] CleanStringRegexes { get; private set; } public Regex[] EpisodeWithoutSeasonRegexes { get; private set; } + public Regex[] EpisodeMultiPartRegexes { get; private set; } public void Compile() diff --git a/Emby.Naming/Emby.Naming.csproj b/Emby.Naming/Emby.Naming.csproj index 900b9694c2..4e08170a47 100644 --- a/Emby.Naming/Emby.Naming.csproj +++ b/Emby.Naming/Emby.Naming.csproj @@ -4,9 +4,6 @@ netstandard2.1 false true - - - true @@ -27,7 +24,7 @@ - + diff --git a/Emby.Naming/TV/EpisodePathParser.cs b/Emby.Naming/TV/EpisodePathParser.cs index 6b557d2e19..b97b3137bc 100644 --- a/Emby.Naming/TV/EpisodePathParser.cs +++ b/Emby.Naming/TV/EpisodePathParser.cs @@ -1,5 +1,6 @@ #pragma warning disable CS1591 #pragma warning disable SA1600 +#nullable enable using System; using System.Collections.Generic; @@ -28,7 +29,7 @@ namespace Emby.Naming.TV path += ".mp4"; } - EpisodePathParserResult result = null; + EpisodePathParserResult? result = null; foreach (var expression in _options.EpisodeExpressions) { @@ -136,7 +137,7 @@ namespace Emby.Naming.TV // It avoids erroneous parsing of something like "series-s09e14-1080p.mkv" as a multi-episode from E14 to E108 int nextIndex = endingNumberGroup.Index + endingNumberGroup.Length; if (nextIndex >= name.Length - || "0123456789iIpP".IndexOf(name[nextIndex]) == -1) + || !"0123456789iIpP".Contains(name[nextIndex], StringComparison.Ordinal)) { if (int.TryParse(endingNumberGroup.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out num)) { diff --git a/Emby.Naming/TV/EpisodeResolver.cs b/Emby.Naming/TV/EpisodeResolver.cs index 5e115fc75d..57659ee131 100644 --- a/Emby.Naming/TV/EpisodeResolver.cs +++ b/Emby.Naming/TV/EpisodeResolver.cs @@ -1,5 +1,6 @@ #pragma warning disable CS1591 #pragma warning disable SA1600 +#nullable enable using System; using System.IO; @@ -18,7 +19,7 @@ namespace Emby.Naming.TV _options = options; } - public EpisodeInfo Resolve( + public EpisodeInfo? Resolve( string path, bool isDirectory, bool? isNamed = null, @@ -26,14 +27,9 @@ namespace Emby.Naming.TV bool? supportsAbsoluteNumbers = null, bool fillExtendedInfo = true) { - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentNullException(nameof(path)); - } - bool isStub = false; - string container = null; - string stubType = null; + string? container = null; + string? stubType = null; if (!isDirectory) { @@ -41,17 +37,13 @@ namespace Emby.Naming.TV // Check supported extensions if (!_options.VideoFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)) { - var stubResult = StubResolver.ResolveFile(path, _options); - - isStub = stubResult.IsStub; - // It's not supported. Check stub extensions - if (!isStub) + if (!StubResolver.TryResolveFile(path, _options, out stubType)) { return null; } - stubType = stubResult.StubType; + isStub = true; } container = extension.TrimStart('.'); diff --git a/Emby.Naming/TV/SeasonPathParser.cs b/Emby.Naming/TV/SeasonPathParser.cs index e5f90e9660..7715a16a45 100644 --- a/Emby.Naming/TV/SeasonPathParser.cs +++ b/Emby.Naming/TV/SeasonPathParser.cs @@ -8,9 +8,24 @@ using System.Linq; namespace Emby.Naming.TV { - public class SeasonPathParser + public static class SeasonPathParser { - public SeasonPathParserResult Parse(string path, bool supportSpecialAliases, bool supportNumericSeasonFolders) + /// + /// A season folder must contain one of these somewhere in the name. + /// + private static readonly string[] _seasonFolderNames = + { + "season", + "sæson", + "temporada", + "saison", + "staffel", + "series", + "сезон", + "stagione" + }; + + public static SeasonPathParserResult Parse(string path, bool supportSpecialAliases, bool supportNumericSeasonFolders) { var result = new SeasonPathParserResult(); @@ -27,21 +42,6 @@ namespace Emby.Naming.TV return result; } - /// - /// A season folder must contain one of these somewhere in the name. - /// - private static readonly string[] _seasonFolderNames = - { - "season", - "sæson", - "temporada", - "saison", - "staffel", - "series", - "сезон", - "stagione" - }; - /// /// Gets the season number from path. /// @@ -150,6 +150,7 @@ namespace Emby.Naming.TV { numericStart = i; } + length++; } } @@ -161,11 +162,11 @@ namespace Emby.Naming.TV } var currentChar = path[i]; - if (currentChar.Equals('(')) + if (currentChar == '(') { hasOpenParenth = true; } - else if (currentChar.Equals(')')) + else if (currentChar == ')') { hasOpenParenth = false; } diff --git a/Emby.Naming/Video/StackResolver.cs b/Emby.Naming/Video/StackResolver.cs index e7a769ae6b..8f210fa453 100644 --- a/Emby.Naming/Video/StackResolver.cs +++ b/Emby.Naming/Video/StackResolver.cs @@ -20,7 +20,7 @@ namespace Emby.Naming.Video _options = options; } - public StackResult ResolveDirectories(IEnumerable files) + public IEnumerable ResolveDirectories(IEnumerable files) { return Resolve(files.Select(i => new FileSystemMetadata { @@ -29,7 +29,7 @@ namespace Emby.Naming.Video })); } - public StackResult ResolveFiles(IEnumerable files) + public IEnumerable ResolveFiles(IEnumerable files) { return Resolve(files.Select(i => new FileSystemMetadata { @@ -38,9 +38,8 @@ namespace Emby.Naming.Video })); } - public StackResult ResolveAudioBooks(IEnumerable files) + public IEnumerable ResolveAudioBooks(IEnumerable files) { - var result = new StackResult(); foreach (var directory in files.GroupBy(file => file.IsDirectory ? file.FullName : Path.GetDirectoryName(file.FullName))) { var stack = new FileStack() @@ -58,20 +57,16 @@ namespace Emby.Naming.Video stack.Files.Add(file.FullName); } - result.Stacks.Add(stack); + yield return stack; } - - return result; } - public StackResult Resolve(IEnumerable files) + public IEnumerable Resolve(IEnumerable files) { - var result = new StackResult(); - var resolver = new VideoResolver(_options); var list = files - .Where(i => i.IsDirectory || (resolver.IsVideoFile(i.FullName) || resolver.IsStubFile(i.FullName))) + .Where(i => i.IsDirectory || resolver.IsVideoFile(i.FullName) || resolver.IsStubFile(i.FullName)) .OrderBy(i => i.FullName) .ToList(); @@ -191,14 +186,12 @@ namespace Emby.Naming.Video if (stack.Files.Count > 1) { - result.Stacks.Add(stack); + yield return stack; i += stack.Files.Count - 1; break; } } } - - return result; } private string GetRegexInput(FileSystemMetadata file) diff --git a/Emby.Naming/Video/StackResult.cs b/Emby.Naming/Video/StackResult.cs deleted file mode 100644 index 31ef2d69c5..0000000000 --- a/Emby.Naming/Video/StackResult.cs +++ /dev/null @@ -1,17 +0,0 @@ -#pragma warning disable CS1591 -#pragma warning disable SA1600 - -using System.Collections.Generic; - -namespace Emby.Naming.Video -{ - public class StackResult - { - public List Stacks { get; set; } - - public StackResult() - { - Stacks = new List(); - } - } -} diff --git a/Emby.Naming/Video/StubResolver.cs b/Emby.Naming/Video/StubResolver.cs index 95868e89d2..4024d6d593 100644 --- a/Emby.Naming/Video/StubResolver.cs +++ b/Emby.Naming/Video/StubResolver.cs @@ -1,5 +1,6 @@ #pragma warning disable CS1591 #pragma warning disable SA1600 +#nullable enable using System; using System.IO; @@ -10,25 +11,22 @@ namespace Emby.Naming.Video { public static class StubResolver { - public static StubResult ResolveFile(string path, NamingOptions options) + public static bool TryResolveFile(string path, NamingOptions options, out string? stubType) { + stubType = default; + if (path == null) { - return default; + return false; } var extension = Path.GetExtension(path); if (!options.StubFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)) { - return default; + return false; } - var result = new StubResult() - { - IsStub = true - }; - path = Path.GetFileNameWithoutExtension(path); var token = Path.GetExtension(path).TrimStart('.'); @@ -36,12 +34,12 @@ namespace Emby.Naming.Video { if (string.Equals(rule.Token, token, StringComparison.OrdinalIgnoreCase)) { - result.StubType = rule.StubType; - break; + stubType = rule.StubType; + return true; } } - return result; + return true; } } } diff --git a/Emby.Naming/Video/VideoFileInfo.cs b/Emby.Naming/Video/VideoFileInfo.cs index 90c798da10..aa4f3a35c3 100644 --- a/Emby.Naming/Video/VideoFileInfo.cs +++ b/Emby.Naming/Video/VideoFileInfo.cs @@ -68,7 +68,7 @@ namespace Emby.Naming.Video public string StubType { get; set; } /// - /// Gets or sets the type. + /// Gets or sets a value indicating whether this instance is a directory. /// /// The type. public bool IsDirectory { get; set; } diff --git a/Emby.Naming/Video/VideoInfo.cs b/Emby.Naming/Video/VideoInfo.cs index a585bb99a2..ea74c40e2a 100644 --- a/Emby.Naming/Video/VideoInfo.cs +++ b/Emby.Naming/Video/VideoInfo.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; namespace Emby.Naming.Video @@ -10,11 +11,14 @@ namespace Emby.Naming.Video /// /// Initializes a new instance of the class. /// - public VideoInfo() + /// The name. + public VideoInfo(string name) { - Files = new List(); - Extras = new List(); - AlternateVersions = new List(); + Name = name; + + Files = Array.Empty(); + Extras = Array.Empty(); + AlternateVersions = Array.Empty(); } /// @@ -33,18 +37,18 @@ namespace Emby.Naming.Video /// Gets or sets the files. /// /// The files. - public List Files { get; set; } + public IReadOnlyList Files { get; set; } /// /// Gets or sets the extras. /// /// The extras. - public List Extras { get; set; } + public IReadOnlyList Extras { get; set; } /// /// Gets or sets the alternate versions. /// /// The alternate versions. - public List AlternateVersions { get; set; } + public IReadOnlyList AlternateVersions { get; set; } } } diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index 87498000ce..1366583534 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -41,20 +41,19 @@ namespace Emby.Naming.Video }); var stackResult = new StackResolver(_options) - .Resolve(nonExtras); + .Resolve(nonExtras).ToList(); var remainingFiles = videoInfos - .Where(i => !stackResult.Stacks.Any(s => s.ContainsFile(i.Path, i.IsDirectory))) + .Where(i => !stackResult.Any(s => s.ContainsFile(i.Path, i.IsDirectory))) .ToList(); var list = new List(); - foreach (var stack in stackResult.Stacks) + foreach (var stack in stackResult) { - var info = new VideoInfo + var info = new VideoInfo(stack.Name) { - Files = stack.Files.Select(i => videoResolver.Resolve(i, stack.IsDirectoryStack)).ToList(), - Name = stack.Name + Files = stack.Files.Select(i => videoResolver.Resolve(i, stack.IsDirectoryStack)).ToList() }; info.Year = info.Files[0].Year; @@ -85,10 +84,9 @@ namespace Emby.Naming.Video foreach (var media in standaloneMedia) { - var info = new VideoInfo + var info = new VideoInfo(media.Name) { - Files = new List { media }, - Name = media.Name + Files = new List { media } }; info.Year = info.Files[0].Year; @@ -128,7 +126,8 @@ namespace Emby.Naming.Video .Except(extras) .ToList(); - info.Extras.AddRange(extras); + extras.AddRange(info.Extras); + info.Extras = extras; } } @@ -141,7 +140,8 @@ namespace Emby.Naming.Video .Except(extrasByFileName) .ToList(); - info.Extras.AddRange(extrasByFileName); + extrasByFileName.AddRange(info.Extras); + info.Extras = extrasByFileName; } // If there's only one video, accept all trailers @@ -152,7 +152,8 @@ namespace Emby.Naming.Video .Where(i => i.ExtraType == ExtraType.Trailer) .ToList(); - list[0].Extras.AddRange(trailers); + trailers.AddRange(list[0].Extras); + list[0].Extras = trailers; remainingFiles = remainingFiles .Except(trailers) @@ -160,14 +161,13 @@ namespace Emby.Naming.Video } // Whatever files are left, just add them - list.AddRange(remainingFiles.Select(i => new VideoInfo + list.AddRange(remainingFiles.Select(i => new VideoInfo(i.Name) { Files = new List { i }, - Name = i.Name, Year = i.Year })); - return list.OrderBy(i => i.Name); + return list; } private IEnumerable GetVideosGroupedByVersion(List videos) @@ -191,9 +191,18 @@ namespace Emby.Naming.Video list.Add(ordered[0]); - list[0].AlternateVersions = ordered.Skip(1).Select(i => i.Files[0]).ToList(); + var alternateVersionsLen = ordered.Count - 1; + var alternateVersions = new VideoFileInfo[alternateVersionsLen]; + for (int i = 0; i < alternateVersionsLen; i++) + { + alternateVersions[i] = ordered[i + 1].Files[0]; + } + + list[0].AlternateVersions = alternateVersions; list[0].Name = folderName; - list[0].Extras.AddRange(ordered.Skip(1).SelectMany(i => i.Extras)); + var extras = ordered.Skip(1).SelectMany(i => i.Extras).ToList(); + extras.AddRange(list[0].Extras); + list[0].Extras = extras; return list; } diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index f93db24866..699bbe40a1 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -1,5 +1,6 @@ #pragma warning disable CS1591 #pragma warning disable SA1600 +#nullable enable using System; using System.IO; @@ -22,7 +23,7 @@ namespace Emby.Naming.Video /// /// The path. /// VideoFileInfo. - public VideoFileInfo ResolveDirectory(string path) + public VideoFileInfo? ResolveDirectory(string path) { return Resolve(path, true); } @@ -32,7 +33,7 @@ namespace Emby.Naming.Video /// /// The path. /// VideoFileInfo. - public VideoFileInfo ResolveFile(string path) + public VideoFileInfo? ResolveFile(string path) { return Resolve(path, false); } @@ -42,10 +43,10 @@ namespace Emby.Naming.Video /// /// The path. /// if set to true [is folder]. - /// Whether or not the name should be parsed for info + /// Whether or not the name should be parsed for info. /// VideoFileInfo. /// path is null. - public VideoFileInfo Resolve(string path, bool isDirectory, bool parseName = true) + public VideoFileInfo? Resolve(string path, bool isDirectory, bool parseName = true) { if (string.IsNullOrEmpty(path)) { @@ -53,8 +54,8 @@ namespace Emby.Naming.Video } bool isStub = false; - string container = null; - string stubType = null; + string? container = null; + string? stubType = null; if (!isDirectory) { @@ -63,17 +64,13 @@ namespace Emby.Naming.Video // Check supported extensions if (!_options.VideoFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)) { - var stubResult = StubResolver.ResolveFile(path, _options); - - isStub = stubResult.IsStub; - // It's not supported. Check stub extensions - if (!isStub) + if (!StubResolver.TryResolveFile(path, _options, out stubType)) { return null; } - stubType = stubResult.StubType; + isStub = true; } container = extension.TrimStart('.'); diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 6fb6235541..5c04631da9 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -2384,7 +2384,7 @@ namespace Emby.Server.Implementations.Library public int? GetSeasonNumberFromPath(string path) { - return new SeasonPathParser().Parse(path, true, true).SeasonNumber; + return SeasonPathParser.Parse(path, true, true).SeasonNumber; } public bool FillMissingEpisodeNumbersFromPath(Episode episode, bool forceRefresh) diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs index 4a2d210d5d..9f858f98dd 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs @@ -76,7 +76,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio } /// - /// Determine if the supplied file data points to a music album + /// Determine if the supplied file data points to a music album. /// public bool IsMusicAlbum(string path, IDirectoryService directoryService, LibraryOptions libraryOptions) { @@ -84,7 +84,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio } /// - /// Determine if the supplied resolve args should be considered a music album + /// Determine if the supplied resolve args should be considered a music album. /// /// The args. /// true if [is music album] [the specified args]; otherwise, false. @@ -104,7 +104,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio } /// - /// Determine if the supplied list contains what we should consider music + /// Determine if the supplied list contains what we should consider music. /// private bool ContainsMusic( IEnumerable list, @@ -118,6 +118,8 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio var discSubfolderCount = 0; var notMultiDisc = false; + var namingOptions = ((LibraryManager)_libraryManager).GetNamingOptions(); + var parser = new AlbumParser(namingOptions); foreach (var fileSystemInfo in list) { if (fileSystemInfo.IsDirectory) @@ -134,7 +136,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio if (hasMusic) { - if (IsMultiDiscFolder(path, libraryOptions)) + if (parser.IsMultiPart(path)) { logger.LogDebug("Found multi-disc folder: " + path); discSubfolderCount++; @@ -165,15 +167,5 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio return discSubfolderCount > 0; } - - private bool IsMultiDiscFolder(string path, LibraryOptions libraryOptions) - { - var namingOptions = ((LibraryManager)_libraryManager).GetNamingOptions(); - - var parser = new AlbumParser(namingOptions); - var result = parser.ParseMultiPart(path); - - return result.IsMultiPart; - } } } diff --git a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs index 6c76900557..08db168bc3 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs @@ -21,6 +21,28 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies /// public class MovieResolver : BaseVideoResolver