From 5966ee6d87cf4abbe6cf327286788e7e03fe0592 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Sun, 5 Apr 2020 12:07:43 -0400 Subject: [PATCH 01/11] Convert type checks and null checks into pattern matching --- MediaBrowser.Api/ItemUpdateService.cs | 27 +++++++------------ MediaBrowser.Api/LiveTv/LiveTvService.cs | 3 +-- .../Playback/Hls/DynamicHlsService.cs | 6 ++--- MediaBrowser.Api/PluginService.cs | 4 +-- .../ScheduledTasks/ScheduledTaskService.cs | 8 ++---- MediaBrowser.Api/SearchService.cs | 17 ++++-------- MediaBrowser.Api/TvShowsService.cs | 4 +-- .../UserLibrary/BaseItemsByNameService.cs | 3 +-- MediaBrowser.Api/UserLibrary/ItemsService.cs | 6 ++--- 9 files changed, 24 insertions(+), 54 deletions(-) diff --git a/MediaBrowser.Api/ItemUpdateService.cs b/MediaBrowser.Api/ItemUpdateService.cs index c81e89ca3c..962e4ddf4b 100644 --- a/MediaBrowser.Api/ItemUpdateService.cs +++ b/MediaBrowser.Api/ItemUpdateService.cs @@ -263,8 +263,7 @@ namespace MediaBrowser.Api item.Overview = request.Overview; item.Genres = request.Genres; - var episode = item as Episode; - if (episode != null) + if (item is Episode episode) { episode.AirsAfterSeasonNumber = request.AirsAfterSeasonNumber; episode.AirsBeforeEpisodeNumber = request.AirsBeforeEpisodeNumber; @@ -302,14 +301,12 @@ namespace MediaBrowser.Api item.PreferredMetadataCountryCode = request.PreferredMetadataCountryCode; item.PreferredMetadataLanguage = request.PreferredMetadataLanguage; - var hasDisplayOrder = item as IHasDisplayOrder; - if (hasDisplayOrder != null) + if (item is IHasDisplayOrder hasDisplayOrder) { hasDisplayOrder.DisplayOrder = request.DisplayOrder; } - var hasAspectRatio = item as IHasAspectRatio; - if (hasAspectRatio != null) + if (item is IHasAspectRatio hasAspectRatio) { hasAspectRatio.AspectRatio = request.AspectRatio; } @@ -337,16 +334,14 @@ namespace MediaBrowser.Api item.ProviderIds = request.ProviderIds; - var video = item as Video; - if (video != null) + if (item is Video video) { video.Video3DFormat = request.Video3DFormat; } if (request.AlbumArtists != null) { - var hasAlbumArtists = item as IHasAlbumArtist; - if (hasAlbumArtists != null) + if (item is IHasAlbumArtist hasAlbumArtists) { hasAlbumArtists.AlbumArtists = request .AlbumArtists @@ -357,8 +352,7 @@ namespace MediaBrowser.Api if (request.ArtistItems != null) { - var hasArtists = item as IHasArtist; - if (hasArtists != null) + if (item is IHasArtist hasArtists) { hasArtists.Artists = request .ArtistItems @@ -367,20 +361,17 @@ namespace MediaBrowser.Api } } - var song = item as Audio; - if (song != null) + if (item is Audio song) { song.Album = request.Album; } - var musicVideo = item as MusicVideo; - if (musicVideo != null) + if (item is MusicVideo musicVideo) { musicVideo.Album = request.Album; } - var series = item as Series; - if (series != null) + if (item is Series series) { series.Status = GetSeriesStatus(request); diff --git a/MediaBrowser.Api/LiveTv/LiveTvService.cs b/MediaBrowser.Api/LiveTv/LiveTvService.cs index 4b44961392..c8bbbde469 100644 --- a/MediaBrowser.Api/LiveTv/LiveTvService.cs +++ b/MediaBrowser.Api/LiveTv/LiveTvService.cs @@ -1050,8 +1050,7 @@ namespace MediaBrowser.Api.LiveTv { query.IsSeries = true; - var series = _libraryManager.GetItemById(request.LibrarySeriesId) as Series; - if (series != null) + if (_libraryManager.GetItemById(request.LibrarySeriesId) is Series series) { query.Name = series.Name; } diff --git a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs index 3348a31875..8b8fcb05e6 100644 --- a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs @@ -438,8 +438,7 @@ namespace MediaBrowser.Api.Playback.Hls { var segmentId = "0"; - var segmentRequest = request as GetHlsVideoSegment; - if (segmentRequest != null) + if (request is GetHlsVideoSegment segmentRequest) { segmentId = segmentRequest.SegmentId; } @@ -690,8 +689,7 @@ namespace MediaBrowser.Api.Playback.Hls return false; } - var request = state.Request as IMasterHlsRequest; - if (request != null && !request.EnableAdaptiveBitrateStreaming) + if (state.Request is IMasterHlsRequest request && !request.EnableAdaptiveBitrateStreaming) { return false; } diff --git a/MediaBrowser.Api/PluginService.cs b/MediaBrowser.Api/PluginService.cs index 16d3268b9b..7f74511eec 100644 --- a/MediaBrowser.Api/PluginService.cs +++ b/MediaBrowser.Api/PluginService.cs @@ -243,9 +243,7 @@ namespace MediaBrowser.Api // https://code.google.com/p/servicestack/source/browse/trunk/Common/ServiceStack.Text/ServiceStack.Text/Controller/PathInfo.cs var id = Guid.Parse(GetPathValue(1)); - var plugin = _appHost.Plugins.First(p => p.Id == id) as IHasPluginConfiguration; - - if (plugin == null) + if (!(_appHost.Plugins.First(p => p.Id == id) is IHasPluginConfiguration plugin)) { throw new FileNotFoundException(); } diff --git a/MediaBrowser.Api/ScheduledTasks/ScheduledTaskService.cs b/MediaBrowser.Api/ScheduledTasks/ScheduledTaskService.cs index 2bd387229a..e08a8482e0 100644 --- a/MediaBrowser.Api/ScheduledTasks/ScheduledTaskService.cs +++ b/MediaBrowser.Api/ScheduledTasks/ScheduledTaskService.cs @@ -123,9 +123,7 @@ namespace MediaBrowser.Api.ScheduledTasks { var isHidden = false; - var configurableTask = i.ScheduledTask as IConfigurableScheduledTask; - - if (configurableTask != null) + if (i.ScheduledTask is IConfigurableScheduledTask configurableTask) { isHidden = configurableTask.IsHidden; } @@ -142,9 +140,7 @@ namespace MediaBrowser.Api.ScheduledTasks { var isEnabled = true; - var configurableTask = i.ScheduledTask as IConfigurableScheduledTask; - - if (configurableTask != null) + if (i.ScheduledTask is IConfigurableScheduledTask configurableTask) { isEnabled = configurableTask.IsEnabled; } diff --git a/MediaBrowser.Api/SearchService.cs b/MediaBrowser.Api/SearchService.cs index 0a3dc19dc6..f1df01a096 100644 --- a/MediaBrowser.Api/SearchService.cs +++ b/MediaBrowser.Api/SearchService.cs @@ -234,20 +234,17 @@ namespace MediaBrowser.Api SetThumbImageInfo(result, item); SetBackdropImageInfo(result, item); - var program = item as LiveTvProgram; - if (program != null) + if (item is LiveTvProgram program) { result.StartDate = program.StartDate; } - var hasSeries = item as IHasSeries; - if (hasSeries != null) + if (item is IHasSeries hasSeries) { result.Series = hasSeries.SeriesName; } - var series = item as Series; - if (series != null) + if (item is Series series) { if (series.Status.HasValue) { @@ -255,17 +252,13 @@ namespace MediaBrowser.Api } } - var album = item as MusicAlbum; - - if (album != null) + if (item is MusicAlbum album) { result.Artists = album.Artists; result.AlbumArtist = album.AlbumArtist; } - var song = item as Audio; - - if (song != null) + if (item is Audio song) { result.AlbumArtist = song.AlbumArtists.FirstOrDefault(); result.Artists = song.Artists; diff --git a/MediaBrowser.Api/TvShowsService.cs b/MediaBrowser.Api/TvShowsService.cs index 334d1db512..1282bba8ae 100644 --- a/MediaBrowser.Api/TvShowsService.cs +++ b/MediaBrowser.Api/TvShowsService.cs @@ -424,9 +424,7 @@ namespace MediaBrowser.Api if (!string.IsNullOrWhiteSpace(request.SeasonId)) { - var season = _libraryManager.GetItemById(new Guid(request.SeasonId)) as Season; - - if (season == null) + if (!(_libraryManager.GetItemById(new Guid(request.SeasonId)) is Season season)) { throw new ResourceNotFoundException("No season exists with Id " + request.SeasonId); } diff --git a/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs b/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs index 9fa222d324..7e4e589ea0 100644 --- a/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs +++ b/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs @@ -82,8 +82,7 @@ namespace MediaBrowser.Api.UserLibrary { var parent = GetParentItem(request); - var collectionFolder = parent as IHasCollectionType; - if (collectionFolder != null) + if (parent is IHasCollectionType collectionFolder) { return collectionFolder.CollectionType; } diff --git a/MediaBrowser.Api/UserLibrary/ItemsService.cs b/MediaBrowser.Api/UserLibrary/ItemsService.cs index c7b5051712..5e6cad7875 100644 --- a/MediaBrowser.Api/UserLibrary/ItemsService.cs +++ b/MediaBrowser.Api/UserLibrary/ItemsService.cs @@ -199,14 +199,12 @@ namespace MediaBrowser.Api.UserLibrary item = _libraryManager.GetUserRootFolder(); } - Folder folder = item as Folder; - if (folder == null) + if (!(item is Folder folder)) { folder = _libraryManager.GetUserRootFolder(); } - var hasCollectionType = folder as IHasCollectionType; - if (hasCollectionType != null + if (folder is IHasCollectionType hasCollectionType && string.Equals(hasCollectionType.CollectionType, CollectionType.Playlists, StringComparison.OrdinalIgnoreCase)) { request.Recursive = true; From 6a3f9253db8b7886e020d84ed82d9ad45f3d3350 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Sun, 5 Apr 2020 12:26:11 -0400 Subject: [PATCH 02/11] Convert using statements to using declarations where applicable --- MediaBrowser.Api/Images/ImageService.cs | 26 +++++----- MediaBrowser.Api/Images/RemoteImageService.cs | 28 +++++----- MediaBrowser.Api/LiveTv/LiveTvService.cs | 9 ++-- .../Playback/Hls/BaseHlsService.cs | 51 ++++++++----------- MediaBrowser.Api/Subtitles/SubtitleService.cs | 15 +++--- 5 files changed, 57 insertions(+), 72 deletions(-) diff --git a/MediaBrowser.Api/Images/ImageService.cs b/MediaBrowser.Api/Images/ImageService.cs index af455987bc..7b94ffae4e 100644 --- a/MediaBrowser.Api/Images/ImageService.cs +++ b/MediaBrowser.Api/Images/ImageService.cs @@ -743,24 +743,22 @@ namespace MediaBrowser.Api.Images /// Task. public async Task PostImage(BaseItem entity, Stream inputStream, ImageType imageType, string mimeType) { - using (var reader = new StreamReader(inputStream)) + using var reader = new StreamReader(inputStream); + var text = await reader.ReadToEndAsync().ConfigureAwait(false); + + var bytes = Convert.FromBase64String(text); + + var memoryStream = new MemoryStream(bytes) { - var text = await reader.ReadToEndAsync().ConfigureAwait(false); + Position = 0 + }; - var bytes = Convert.FromBase64String(text); + // Handle image/png; charset=utf-8 + mimeType = mimeType.Split(';').FirstOrDefault(); - var memoryStream = new MemoryStream(bytes) - { - Position = 0 - }; + await _providerManager.SaveImage(entity, memoryStream, mimeType, imageType, null, CancellationToken.None).ConfigureAwait(false); - // Handle image/png; charset=utf-8 - mimeType = mimeType.Split(';').FirstOrDefault(); - - await _providerManager.SaveImage(entity, memoryStream, mimeType, imageType, null, CancellationToken.None).ConfigureAwait(false); - - entity.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None); - } + entity.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None); } } } diff --git a/MediaBrowser.Api/Images/RemoteImageService.cs b/MediaBrowser.Api/Images/RemoteImageService.cs index f03f5efd8d..222bb34d31 100644 --- a/MediaBrowser.Api/Images/RemoteImageService.cs +++ b/MediaBrowser.Api/Images/RemoteImageService.cs @@ -261,27 +261,25 @@ namespace MediaBrowser.Api.Images /// Task. private async Task DownloadImage(string url, Guid urlHash, string pointerCachePath) { - using (var result = await _httpClient.GetResponse(new HttpRequestOptions + using var result = await _httpClient.GetResponse(new HttpRequestOptions { Url = url, BufferContent = false - }).ConfigureAwait(false)) + }).ConfigureAwait(false); + var ext = result.ContentType.Split('/').Last(); + + var fullCachePath = GetFullCachePath(urlHash + "." + ext); + + Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath)); + using (var stream = result.Content) { - var ext = result.ContentType.Split('/').Last(); - - var fullCachePath = GetFullCachePath(urlHash + "." + ext); - - Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath)); - using (var stream = result.Content) - using (var filestream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true)) - { - await stream.CopyToAsync(filestream).ConfigureAwait(false); - } - - Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath)); - File.WriteAllText(pointerCachePath, fullCachePath); + using var filestream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); + await stream.CopyToAsync(filestream).ConfigureAwait(false); } + + Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath)); + File.WriteAllText(pointerCachePath, fullCachePath); } /// diff --git a/MediaBrowser.Api/LiveTv/LiveTvService.cs b/MediaBrowser.Api/LiveTv/LiveTvService.cs index c8bbbde469..5fe4c0cca3 100644 --- a/MediaBrowser.Api/LiveTv/LiveTvService.cs +++ b/MediaBrowser.Api/LiveTv/LiveTvService.cs @@ -885,11 +885,10 @@ namespace MediaBrowser.Api.LiveTv { // SchedulesDirect requires a SHA1 hash of the user's password // https://github.com/SchedulesDirect/JSON-Service/wiki/API-20141201#obtain-a-token - using (SHA1 sha = SHA1.Create()) - { - return Hex.Encode( - sha.ComputeHash(Encoding.UTF8.GetBytes(str))); - } + using SHA1 sha = SHA1.Create(); + + return Hex.Encode( + sha.ComputeHash(Encoding.UTF8.GetBytes(str))); } public void Delete(DeleteListingProvider request) diff --git a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs index 0cbfe4bdfa..af0097682a 100644 --- a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs @@ -168,22 +168,19 @@ namespace MediaBrowser.Api.Playback.Hls private string GetLivePlaylistText(string path, int segmentLength) { - using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) - { - using (var reader = new StreamReader(stream)) - { - var text = reader.ReadToEnd(); + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + using var reader = new StreamReader(stream); - text = text.Replace("#EXTM3U", "#EXTM3U\n#EXT-X-PLAYLIST-TYPE:EVENT"); + var text = reader.ReadToEnd(); - var newDuration = "#EXT-X-TARGETDURATION:" + segmentLength.ToString(CultureInfo.InvariantCulture); + text = text.Replace("#EXTM3U", "#EXTM3U\n#EXT-X-PLAYLIST-TYPE:EVENT"); - text = text.Replace("#EXT-X-TARGETDURATION:" + (segmentLength - 1).ToString(CultureInfo.InvariantCulture), newDuration, StringComparison.OrdinalIgnoreCase); - //text = text.Replace("#EXT-X-TARGETDURATION:" + (segmentLength + 1).ToString(CultureInfo.InvariantCulture), newDuration, StringComparison.OrdinalIgnoreCase); + var newDuration = "#EXT-X-TARGETDURATION:" + segmentLength.ToString(CultureInfo.InvariantCulture); - return text; - } - } + text = text.Replace("#EXT-X-TARGETDURATION:" + (segmentLength - 1).ToString(CultureInfo.InvariantCulture), newDuration, StringComparison.OrdinalIgnoreCase); + //text = text.Replace("#EXT-X-TARGETDURATION:" + (segmentLength + 1).ToString(CultureInfo.InvariantCulture), newDuration, StringComparison.OrdinalIgnoreCase); + + return text; } private string GetMasterPlaylistFileText(string firstPlaylist, int bitrate, int baselineStreamBitrate) @@ -212,29 +209,25 @@ namespace MediaBrowser.Api.Playback.Hls try { // Need to use FileShare.ReadWrite because we're reading the file at the same time it's being written - using (var fileStream = GetPlaylistFileStream(playlist)) + using var fileStream = GetPlaylistFileStream(playlist); + using var reader = new StreamReader(fileStream); + var count = 0; + + while (!reader.EndOfStream) { - using (var reader = new StreamReader(fileStream)) + var line = reader.ReadLine(); + + if (line.IndexOf("#EXTINF:", StringComparison.OrdinalIgnoreCase) != -1) { - var count = 0; - - while (!reader.EndOfStream) + count++; + if (count >= segmentCount) { - var line = reader.ReadLine(); - - if (line.IndexOf("#EXTINF:", StringComparison.OrdinalIgnoreCase) != -1) - { - count++; - if (count >= segmentCount) - { - Logger.LogDebug("Finished waiting for {0} segments in {1}", segmentCount, playlist); - return; - } - } + Logger.LogDebug("Finished waiting for {0} segments in {1}", segmentCount, playlist); + return; } - await Task.Delay(100, cancellationToken).ConfigureAwait(false); } } + await Task.Delay(100, cancellationToken).ConfigureAwait(false); } catch (IOException) { diff --git a/MediaBrowser.Api/Subtitles/SubtitleService.cs b/MediaBrowser.Api/Subtitles/SubtitleService.cs index c4a7ae78e7..f2968c6b5c 100644 --- a/MediaBrowser.Api/Subtitles/SubtitleService.cs +++ b/MediaBrowser.Api/Subtitles/SubtitleService.cs @@ -230,17 +230,14 @@ namespace MediaBrowser.Api.Subtitles if (string.Equals(request.Format, "vtt", StringComparison.OrdinalIgnoreCase) && request.AddVttTimeMap) { - using (var stream = await GetSubtitles(request).ConfigureAwait(false)) - { - using (var reader = new StreamReader(stream)) - { - var text = reader.ReadToEnd(); + using var stream = await GetSubtitles(request).ConfigureAwait(false); + using var reader = new StreamReader(stream); - text = text.Replace("WEBVTT", "WEBVTT\nX-TIMESTAMP-MAP=MPEGTS:900000,LOCAL:00:00:00.000"); + var text = reader.ReadToEnd(); - return ResultFactory.GetResult(Request, text, MimeTypes.GetMimeType("file." + request.Format)); - } - } + text = text.Replace("WEBVTT", "WEBVTT\nX-TIMESTAMP-MAP=MPEGTS:900000,LOCAL:00:00:00.000"); + + return ResultFactory.GetResult(Request, text, MimeTypes.GetMimeType("file." + request.Format)); } return ResultFactory.GetResult(Request, await GetSubtitles(request).ConfigureAwait(false), MimeTypes.GetMimeType("file." + request.Format)); From 961f48f5bcc8e4f1e0c3ac5e3c2757bbd14b6a9d Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Sun, 5 Apr 2020 12:45:01 -0400 Subject: [PATCH 03/11] Use ? and ?? where applicable --- MediaBrowser.Api/ApiEntryPoint.cs | 7 ++-- MediaBrowser.Api/BaseApiService.cs | 36 +++++++------------ MediaBrowser.Api/ItemUpdateService.cs | 1 - .../Library/LibraryStructureService.cs | 12 +++---- .../Playback/BaseStreamingService.cs | 19 ++-------- .../Playback/Hls/BaseHlsService.cs | 4 +-- .../Playback/Hls/DynamicHlsService.cs | 4 +-- MediaBrowser.Api/Playback/MediaInfoService.cs | 2 +- .../Playback/UniversalAudioService.cs | 2 +- MediaBrowser.Api/SearchService.cs | 10 ++---- MediaBrowser.Api/TranscodingJob.cs | 5 +-- MediaBrowser.Api/TvShowsService.cs | 9 +---- MediaBrowser.Api/VideosService.cs | 33 +++++------------ 13 files changed, 42 insertions(+), 102 deletions(-) diff --git a/MediaBrowser.Api/ApiEntryPoint.cs b/MediaBrowser.Api/ApiEntryPoint.cs index 4bd13df003..2215bb5c40 100644 --- a/MediaBrowser.Api/ApiEntryPoint.cs +++ b/MediaBrowser.Api/ApiEntryPoint.cs @@ -258,7 +258,7 @@ namespace MediaBrowser.Api public void ReportTranscodingProgress(TranscodingJob job, StreamState state, TimeSpan? transcodingPosition, float? framerate, double? percentComplete, long? bytesTranscoded, int? bitRate) { - var ticks = transcodingPosition.HasValue ? transcodingPosition.Value.Ticks : (long?)null; + var ticks = transcodingPosition?.Ticks; if (job != null) { @@ -561,10 +561,7 @@ namespace MediaBrowser.Api lock (job.ProcessLock) { - if (job.TranscodingThrottler != null) - { - job.TranscodingThrottler.Stop().GetAwaiter().GetResult(); - } + job.TranscodingThrottler?.Stop().GetAwaiter().GetResult(); var process = job.Process; diff --git a/MediaBrowser.Api/BaseApiService.cs b/MediaBrowser.Api/BaseApiService.cs index 112ee8f79a..154177dca1 100644 --- a/MediaBrowser.Api/BaseApiService.cs +++ b/MediaBrowser.Api/BaseApiService.cs @@ -274,36 +274,26 @@ namespace MediaBrowser.Api private T GetItemFromSlugName(ILibraryManager libraryManager, string name, DtoOptions dtoOptions) where T : BaseItem, new() { - var result = libraryManager.GetItemList(new InternalItemsQuery + var result = (libraryManager.GetItemList(new InternalItemsQuery { Name = name.Replace(BaseItem.SlugChar, '&'), IncludeItemTypes = new[] { typeof(T).Name }, DtoOptions = dtoOptions + }).OfType().FirstOrDefault() ?? libraryManager.GetItemList(new InternalItemsQuery + { + Name = name.Replace(BaseItem.SlugChar, '/'), + IncludeItemTypes = new[] { typeof(T).Name }, + DtoOptions = dtoOptions + + }).OfType().FirstOrDefault()) ?? libraryManager.GetItemList(new InternalItemsQuery + { + Name = name.Replace(BaseItem.SlugChar, '?'), + IncludeItemTypes = new[] { typeof(T).Name }, + DtoOptions = dtoOptions + }).OfType().FirstOrDefault(); - if (result == null) - { - result = libraryManager.GetItemList(new InternalItemsQuery - { - Name = name.Replace(BaseItem.SlugChar, '/'), - IncludeItemTypes = new[] { typeof(T).Name }, - DtoOptions = dtoOptions - - }).OfType().FirstOrDefault(); - } - - if (result == null) - { - result = libraryManager.GetItemList(new InternalItemsQuery - { - Name = name.Replace(BaseItem.SlugChar, '?'), - IncludeItemTypes = new[] { typeof(T).Name }, - DtoOptions = dtoOptions - - }).OfType().FirstOrDefault(); - } - return result; } diff --git a/MediaBrowser.Api/ItemUpdateService.cs b/MediaBrowser.Api/ItemUpdateService.cs index 962e4ddf4b..2db6d717aa 100644 --- a/MediaBrowser.Api/ItemUpdateService.cs +++ b/MediaBrowser.Api/ItemUpdateService.cs @@ -391,7 +391,6 @@ namespace MediaBrowser.Api } return (SeriesStatus)Enum.Parse(typeof(SeriesStatus), item.Status, true); - } } } diff --git a/MediaBrowser.Api/Library/LibraryStructureService.cs b/MediaBrowser.Api/Library/LibraryStructureService.cs index c071b42f75..1e300814f6 100644 --- a/MediaBrowser.Api/Library/LibraryStructureService.cs +++ b/MediaBrowser.Api/Library/LibraryStructureService.cs @@ -327,15 +327,11 @@ namespace MediaBrowser.Api.Library try { - var mediaPath = request.PathInfo; - - if (mediaPath == null) + var mediaPath = request.PathInfo ?? new MediaPathInfo { - mediaPath = new MediaPathInfo - { - Path = request.Path - }; - } + Path = request.Path + }; + _libraryManager.AddMediaPath(request.Name, mediaPath); } finally diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index 5029ce0bb7..6e923768a2 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -248,14 +248,8 @@ namespace MediaBrowser.Api.Playback if (state.VideoRequest != null && string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase)) { - if (string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase)) - { - logFilePrefix = "ffmpeg-remux"; - } - else - { - logFilePrefix = "ffmpeg-directstream"; - } + logFilePrefix = string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase) + ? "ffmpeg-remux" : "ffmpeg-directstream"; } var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + "-" + Guid.NewGuid() + ".txt"); @@ -862,14 +856,7 @@ namespace MediaBrowser.Api.Playback { var caps = DeviceManager.GetCapabilities(state.Request.DeviceId); - if (caps != null) - { - state.DeviceProfile = caps.DeviceProfile; - } - else - { - state.DeviceProfile = DlnaManager.GetProfile(headers); - } + state.DeviceProfile = caps != null ? caps.DeviceProfile : DlnaManager.GetProfile(headers); } } diff --git a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs index af0097682a..566eaf86ea 100644 --- a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs @@ -140,7 +140,7 @@ namespace MediaBrowser.Api.Playback.Hls if (isLive) { - job = job ?? ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType); + job ??= ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType); if (job != null) { @@ -156,7 +156,7 @@ namespace MediaBrowser.Api.Playback.Hls var playlistText = GetMasterPlaylistFileText(playlist, videoBitrate + audioBitrate, baselineStreamBitrate); - job = job ?? ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType); + job ??= ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType); if (job != null) { diff --git a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs index 8b8fcb05e6..20e18cc265 100644 --- a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs @@ -284,7 +284,7 @@ namespace MediaBrowser.Api.Playback.Hls //} Logger.LogDebug("returning {0} [general case]", segmentPath); - job = job ?? ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); + job ??= ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, requestedIndex, job, cancellationToken).ConfigureAwait(false); } @@ -934,7 +934,7 @@ namespace MediaBrowser.Api.Playback.Hls var framerate = state.VideoStream?.RealFrameRate; - if (framerate != null && framerate.HasValue) + if (framerate.HasValue) { // This is to make sure keyframe interval is limited to our segment, // as forcing keyframes is not enough. diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index d74ec3ca63..5f8a86f477 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -583,7 +583,7 @@ namespace MediaBrowser.Api.Playback private long? GetMaxBitrate(long? clientMaxBitrate, User user) { var maxBitrate = clientMaxBitrate; - var remoteClientMaxBitrate = user == null ? 0 : user.Policy.RemoteClientBitrateLimit; + var remoteClientMaxBitrate = user?.Policy.RemoteClientBitrateLimit ?? 0; if (remoteClientMaxBitrate <= 0) { diff --git a/MediaBrowser.Api/Playback/UniversalAudioService.cs b/MediaBrowser.Api/Playback/UniversalAudioService.cs index cbf981dfec..227a630eec 100644 --- a/MediaBrowser.Api/Playback/UniversalAudioService.cs +++ b/MediaBrowser.Api/Playback/UniversalAudioService.cs @@ -167,7 +167,7 @@ namespace MediaBrowser.Api.Playback AudioCodec = request.AudioCodec, Protocol = request.TranscodingProtocol, BreakOnNonKeyFrames = request.BreakOnNonKeyFrames, - MaxAudioChannels = request.TranscodingAudioChannels.HasValue ? request.TranscodingAudioChannels.Value.ToString(CultureInfo.InvariantCulture) : null + MaxAudioChannels = request.TranscodingAudioChannels?.ToString(CultureInfo.InvariantCulture) } }; diff --git a/MediaBrowser.Api/SearchService.cs b/MediaBrowser.Api/SearchService.cs index f1df01a096..c5b78828cb 100644 --- a/MediaBrowser.Api/SearchService.cs +++ b/MediaBrowser.Api/SearchService.cs @@ -279,7 +279,7 @@ namespace MediaBrowser.Api if (!item.ChannelId.Equals(Guid.Empty)) { var channel = _libraryManager.GetItemById(item.ChannelId); - result.ChannelName = channel == null ? null : channel.Name; + result.ChannelName = channel?.Name; } return result; @@ -316,12 +316,8 @@ namespace MediaBrowser.Api private void SetBackdropImageInfo(SearchHint hint, BaseItem item) { - var itemWithImage = item.HasImage(ImageType.Backdrop) ? item : null; - - if (itemWithImage == null) - { - itemWithImage = GetParentWithImage(item, ImageType.Backdrop); - } + var itemWithImage = (item.HasImage(ImageType.Backdrop) ? item : null) + ?? GetParentWithImage(item, ImageType.Backdrop); if (itemWithImage != null) { diff --git a/MediaBrowser.Api/TranscodingJob.cs b/MediaBrowser.Api/TranscodingJob.cs index 6d944d19ea..8c24e3ce18 100644 --- a/MediaBrowser.Api/TranscodingJob.cs +++ b/MediaBrowser.Api/TranscodingJob.cs @@ -92,10 +92,7 @@ namespace MediaBrowser.Api { lock (_timerLock) { - if (KillTimer != null) - { - KillTimer.Change(Timeout.Infinite, Timeout.Infinite); - } + KillTimer?.Change(Timeout.Infinite, Timeout.Infinite); } } diff --git a/MediaBrowser.Api/TvShowsService.cs b/MediaBrowser.Api/TvShowsService.cs index 1282bba8ae..cd8e8dfbe4 100644 --- a/MediaBrowser.Api/TvShowsService.cs +++ b/MediaBrowser.Api/TvShowsService.cs @@ -442,14 +442,7 @@ namespace MediaBrowser.Api var season = series.GetSeasons(user, dtoOptions).FirstOrDefault(i => i.IndexNumber == request.Season.Value); - if (season == null) - { - episodes = new List(); - } - else - { - episodes = ((Season)season).GetEpisodes(user, dtoOptions); - } + episodes = season == null ? new List() : ((Season)season).GetEpisodes(user, dtoOptions); } else { diff --git a/MediaBrowser.Api/VideosService.cs b/MediaBrowser.Api/VideosService.cs index 46b6d5a947..9d7dc2dfc6 100644 --- a/MediaBrowser.Api/VideosService.cs +++ b/MediaBrowser.Api/VideosService.cs @@ -138,32 +138,17 @@ namespace MediaBrowser.Api var videosWithVersions = items.Where(i => i.MediaSourceCount > 1) .ToList(); - var primaryVersion = videosWithVersions.FirstOrDefault(); + var primaryVersion = videosWithVersions.FirstOrDefault() ?? items.OrderBy(i => + { + return (i.Video3DFormat.HasValue || i.VideoType != Model.Entities.VideoType.VideoFile) ? 1 : 0; + }) + .ThenByDescending(i => + { + var stream = i.GetDefaultVideoStream(); - if (primaryVersion == null) - { - primaryVersion = items.OrderBy(i => - { - if (i.Video3DFormat.HasValue) - { - return 1; - } + return stream?.Width ?? 0; - if (i.VideoType != Model.Entities.VideoType.VideoFile) - { - return 1; - } - - return 0; - }) - .ThenByDescending(i => - { - var stream = i.GetDefaultVideoStream(); - - return stream == null || stream.Width == null ? 0 : stream.Width.Value; - - }).First(); - } + }).First(); var list = primaryVersion.LinkedAlternateVersions.ToList(); From 86c06996b16ffa48a63fa364fade5c211be4f294 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Sun, 5 Apr 2020 12:48:22 -0400 Subject: [PATCH 04/11] Remove redundant name qualifiers --- MediaBrowser.Api/BaseApiService.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Api/BaseApiService.cs b/MediaBrowser.Api/BaseApiService.cs index 154177dca1..0312cc57e2 100644 --- a/MediaBrowser.Api/BaseApiService.cs +++ b/MediaBrowser.Api/BaseApiService.cs @@ -138,8 +138,8 @@ namespace MediaBrowser.Api options.Fields = hasFields.GetItemFields(); } - if (!options.ContainsField(Model.Querying.ItemFields.RecursiveItemCount) - || !options.ContainsField(Model.Querying.ItemFields.ChildCount)) + if (!options.ContainsField(ItemFields.RecursiveItemCount) + || !options.ContainsField(ItemFields.ChildCount)) { var client = authContext.GetAuthorizationInfo(Request).Client ?? string.Empty; if (client.IndexOf("kodi", StringComparison.OrdinalIgnoreCase) != -1 || @@ -150,7 +150,7 @@ namespace MediaBrowser.Api int oldLen = options.Fields.Length; var arr = new ItemFields[oldLen + 1]; options.Fields.CopyTo(arr, 0); - arr[oldLen] = Model.Querying.ItemFields.RecursiveItemCount; + arr[oldLen] = ItemFields.RecursiveItemCount; options.Fields = arr; } @@ -166,7 +166,7 @@ namespace MediaBrowser.Api int oldLen = options.Fields.Length; var arr = new ItemFields[oldLen + 1]; options.Fields.CopyTo(arr, 0); - arr[oldLen] = Model.Querying.ItemFields.ChildCount; + arr[oldLen] = ItemFields.ChildCount; options.Fields = arr; } } From 80cfcf5643b50fd1acfdc82cae849948a39233b9 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Sun, 5 Apr 2020 13:00:35 -0400 Subject: [PATCH 05/11] Remove unnecessary casts and explicit array types --- MediaBrowser.Api/ChannelService.cs | 2 +- MediaBrowser.Api/FilterService.cs | 4 ++-- MediaBrowser.Api/Images/ImageService.cs | 2 +- MediaBrowser.Api/Library/LibraryService.cs | 22 +++++++++---------- MediaBrowser.Api/Movies/MoviesService.cs | 2 +- MediaBrowser.Api/Playback/MediaInfoService.cs | 6 ++--- .../Playback/UniversalAudioService.cs | 2 +- 7 files changed, 20 insertions(+), 20 deletions(-) diff --git a/MediaBrowser.Api/ChannelService.cs b/MediaBrowser.Api/ChannelService.cs index 6139ba1560..1d8ef81dfc 100644 --- a/MediaBrowser.Api/ChannelService.cs +++ b/MediaBrowser.Api/ChannelService.cs @@ -241,7 +241,7 @@ namespace MediaBrowser.Api { Limit = request.Limit, StartIndex = request.StartIndex, - ChannelIds = new Guid[] { new Guid(request.Id) }, + ChannelIds = new[] { new Guid(request.Id) }, ParentId = string.IsNullOrWhiteSpace(request.FolderId) ? Guid.Empty : new Guid(request.FolderId), OrderBy = request.GetOrderBy(), DtoOptions = new Controller.Dto.DtoOptions diff --git a/MediaBrowser.Api/FilterService.cs b/MediaBrowser.Api/FilterService.cs index 25f23bcd1e..5eb72cdb19 100644 --- a/MediaBrowser.Api/FilterService.cs +++ b/MediaBrowser.Api/FilterService.cs @@ -133,7 +133,7 @@ namespace MediaBrowser.Api // Non recursive not yet supported for library folders if ((request.Recursive ?? true) || parentItem is UserView || parentItem is ICollectionFolder) { - genreQuery.AncestorIds = parentItem == null ? Array.Empty() : new Guid[] { parentItem.Id }; + genreQuery.AncestorIds = parentItem == null ? Array.Empty() : new[] { parentItem.Id }; } else { @@ -231,7 +231,7 @@ namespace MediaBrowser.Api EnableTotalRecordCount = false, DtoOptions = new Controller.Dto.DtoOptions { - Fields = new ItemFields[] { ItemFields.Genres, ItemFields.Tags }, + Fields = new[] { ItemFields.Genres, ItemFields.Tags }, EnableImages = false, EnableUserData = false } diff --git a/MediaBrowser.Api/Images/ImageService.cs b/MediaBrowser.Api/Images/ImageService.cs index 7b94ffae4e..e8ea312519 100644 --- a/MediaBrowser.Api/Images/ImageService.cs +++ b/MediaBrowser.Api/Images/ImageService.cs @@ -650,7 +650,7 @@ namespace MediaBrowser.Api.Images if (!string.IsNullOrWhiteSpace(request.Format) && Enum.TryParse(request.Format, true, out ImageFormat format)) { - return new ImageFormat[] { format }; + return new[] { format }; } return GetClientSupportedFormats(); diff --git a/MediaBrowser.Api/Library/LibraryService.cs b/MediaBrowser.Api/Library/LibraryService.cs index 15284958d7..b82247fc66 100644 --- a/MediaBrowser.Api/Library/LibraryService.cs +++ b/MediaBrowser.Api/Library/LibraryService.cs @@ -351,24 +351,24 @@ namespace MediaBrowser.Api.Library switch (contentType) { case CollectionType.BoxSets: - return new string[] { "BoxSet" }; + return new[] { "BoxSet" }; case CollectionType.Playlists: - return new string[] { "Playlist" }; + return new[] { "Playlist" }; case CollectionType.Movies: - return new string[] { "Movie" }; + return new[] { "Movie" }; case CollectionType.TvShows: - return new string[] { "Series", "Season", "Episode" }; + return new[] { "Series", "Season", "Episode" }; case CollectionType.Books: - return new string[] { "Book" }; + return new[] { "Book" }; case CollectionType.Music: - return new string[] { "MusicAlbum", "MusicArtist", "Audio", "MusicVideo" }; + return new[] { "MusicAlbum", "MusicArtist", "Audio", "MusicVideo" }; case CollectionType.HomeVideos: case CollectionType.Photos: - return new string[] { "Video", "Photo" }; + return new[] { "Video", "Photo" }; case CollectionType.MusicVideos: - return new string[] { "MusicVideo" }; + return new[] { "MusicVideo" }; default: - return new string[] { "Series", "Season", "Episode", "Movie" }; + return new[] { "Series", "Season", "Episode", "Movie" }; } } @@ -1086,7 +1086,7 @@ namespace MediaBrowser.Api.Library var item = string.IsNullOrEmpty(request.Id) ? (!request.UserId.Equals(Guid.Empty) ? _libraryManager.GetUserRootFolder() - : (Folder)_libraryManager.RootFolder) + : _libraryManager.RootFolder) : _libraryManager.GetItemById(request.Id); if (item == null) @@ -1152,7 +1152,7 @@ namespace MediaBrowser.Api.Library var item = string.IsNullOrEmpty(request.Id) ? (!request.UserId.Equals(Guid.Empty) ? _libraryManager.GetUserRootFolder() - : (Folder)_libraryManager.RootFolder) + : _libraryManager.RootFolder) : _libraryManager.GetItemById(request.Id); if (item == null) diff --git a/MediaBrowser.Api/Movies/MoviesService.cs b/MediaBrowser.Api/Movies/MoviesService.cs index 889ebc9281..46da8b9099 100644 --- a/MediaBrowser.Api/Movies/MoviesService.cs +++ b/MediaBrowser.Api/Movies/MoviesService.cs @@ -394,7 +394,7 @@ namespace MediaBrowser.Api.Movies { var people = _libraryManager.GetPeople(new InternalPeopleQuery { - PersonTypes = new string[] + PersonTypes = new[] { PersonType.Director } diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 5f8a86f477..d30175e762 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -234,7 +234,7 @@ namespace MediaBrowser.Api.Playback OpenToken = mediaSource.OpenToken }).ConfigureAwait(false); - info.MediaSources = new MediaSourceInfo[] { openStreamResult.MediaSource }; + info.MediaSources = new[] { openStreamResult.MediaSource }; } } @@ -289,7 +289,7 @@ namespace MediaBrowser.Api.Playback { var mediaSource = await _mediaSourceManager.GetLiveStream(liveStreamId, CancellationToken.None).ConfigureAwait(false); - mediaSources = new MediaSourceInfo[] { mediaSource }; + mediaSources = new[] { mediaSource }; } if (mediaSources.Length == 0) @@ -366,7 +366,7 @@ namespace MediaBrowser.Api.Playback var options = new VideoOptions { - MediaSources = new MediaSourceInfo[] { mediaSource }, + MediaSources = new[] { mediaSource }, Context = EncodingContext.Streaming, DeviceId = auth.DeviceId, ItemId = item.Id, diff --git a/MediaBrowser.Api/Playback/UniversalAudioService.cs b/MediaBrowser.Api/Playback/UniversalAudioService.cs index 227a630eec..cebd4b49a1 100644 --- a/MediaBrowser.Api/Playback/UniversalAudioService.cs +++ b/MediaBrowser.Api/Playback/UniversalAudioService.cs @@ -300,7 +300,7 @@ namespace MediaBrowser.Api.Playback // hls segment container can only be mpegts or fmp4 per ffmpeg documentation // TODO: remove this when we switch back to the segment muxer - var supportedHLSContainers = new string[] { "mpegts", "fmp4" }; + var supportedHLSContainers = new[] { "mpegts", "fmp4" }; var newRequest = new GetMasterHlsAudioPlaylist { From add0a2088de154137cf547f84c85f59a78e442d8 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Sun, 5 Apr 2020 14:44:14 -0400 Subject: [PATCH 06/11] Simplified Conditionals and returns --- MediaBrowser.Api/ApiEntryPoint.cs | 22 +- MediaBrowser.Api/BaseApiService.cs | 24 +- MediaBrowser.Api/ChannelService.cs | 18 +- MediaBrowser.Api/Devices/DeviceService.cs | 16 +- MediaBrowser.Api/EnvironmentService.cs | 7 +- MediaBrowser.Api/Library/LibraryService.cs | 65 ++- .../Playback/BaseStreamingService.cs | 390 +++++++++--------- MediaBrowser.Api/Playback/MediaInfoService.cs | 12 +- MediaBrowser.Api/SearchService.cs | 73 ++-- MediaBrowser.Api/System/SystemService.cs | 8 +- .../UserLibrary/ArtistsService.cs | 7 +- .../UserLibrary/BaseItemsRequest.cs | 29 +- 12 files changed, 299 insertions(+), 372 deletions(-) diff --git a/MediaBrowser.Api/ApiEntryPoint.cs b/MediaBrowser.Api/ApiEntryPoint.cs index 2215bb5c40..61ad976ec3 100644 --- a/MediaBrowser.Api/ApiEntryPoint.cs +++ b/MediaBrowser.Api/ApiEntryPoint.cs @@ -86,12 +86,9 @@ namespace MediaBrowser.Api return Array.Empty(); } - if (removeEmpty) - { - return value.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries); - } - - return value.Split(separator); + return removeEmpty + ? value.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries) + : value.Split(separator); } public SemaphoreSlim GetTranscodingLock(string outputPath) @@ -487,16 +484,9 @@ namespace MediaBrowser.Api /// Task. internal Task KillTranscodingJobs(string deviceId, string playSessionId, Func deleteFiles) { - return KillTranscodingJobs(j => - { - if (!string.IsNullOrWhiteSpace(playSessionId)) - { - return string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase); - } - - return string.Equals(deviceId, j.DeviceId, StringComparison.OrdinalIgnoreCase); - - }, deleteFiles); + return KillTranscodingJobs(j => !string.IsNullOrWhiteSpace(playSessionId) + ? string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase) + : string.Equals(deviceId, j.DeviceId, StringComparison.OrdinalIgnoreCase), deleteFiles); } /// diff --git a/MediaBrowser.Api/BaseApiService.cs b/MediaBrowser.Api/BaseApiService.cs index 0312cc57e2..b43aed7bfd 100644 --- a/MediaBrowser.Api/BaseApiService.cs +++ b/MediaBrowser.Api/BaseApiService.cs @@ -58,12 +58,9 @@ namespace MediaBrowser.Api public static string[] SplitValue(string value, char delim) { - if (value == null) - { - return Array.Empty(); - } - - return value.Split(new[] { delim }, StringSplitOptions.RemoveEmptyEntries); + return value == null + ? Array.Empty() + : value.Split(new[] { delim }, StringSplitOptions.RemoveEmptyEntries); } public static Guid[] GetGuids(string value) @@ -97,19 +94,10 @@ namespace MediaBrowser.Api var authenticatedUser = auth.User; // If they're going to update the record of another user, they must be an administrator - if (!userId.Equals(auth.UserId)) + if ((!userId.Equals(auth.UserId) && !authenticatedUser.Policy.IsAdministrator) + || (restrictUserPreferences && !authenticatedUser.Policy.EnableUserPreferenceAccess)) { - if (!authenticatedUser.Policy.IsAdministrator) - { - throw new SecurityException("Unauthorized access."); - } - } - else if (restrictUserPreferences) - { - if (!authenticatedUser.Policy.EnableUserPreferenceAccess) - { - throw new SecurityException("Unauthorized access."); - } + throw new SecurityException("Unauthorized access."); } } diff --git a/MediaBrowser.Api/ChannelService.cs b/MediaBrowser.Api/ChannelService.cs index 1d8ef81dfc..e43e34133c 100644 --- a/MediaBrowser.Api/ChannelService.cs +++ b/MediaBrowser.Api/ChannelService.cs @@ -116,12 +116,9 @@ namespace MediaBrowser.Api { var val = Filters; - if (string.IsNullOrEmpty(val)) - { - return new ItemFilter[] { }; - } - - return val.Split(',').Select(v => (ItemFilter)Enum.Parse(typeof(ItemFilter), v, true)); + return string.IsNullOrEmpty(val) + ? new ItemFilter[] { } + : val.Split(',').Select(v => (ItemFilter)Enum.Parse(typeof(ItemFilter), v, true)); } /// @@ -175,12 +172,9 @@ namespace MediaBrowser.Api { var val = Filters; - if (string.IsNullOrEmpty(val)) - { - return new ItemFilter[] { }; - } - - return val.Split(',').Select(v => (ItemFilter)Enum.Parse(typeof(ItemFilter), v, true)); + return string.IsNullOrEmpty(val) + ? new ItemFilter[] { } + : val.Split(',').Select(v => (ItemFilter)Enum.Parse(typeof(ItemFilter), v, true)); } } diff --git a/MediaBrowser.Api/Devices/DeviceService.cs b/MediaBrowser.Api/Devices/DeviceService.cs index 8b63decd22..7004a2559e 100644 --- a/MediaBrowser.Api/Devices/DeviceService.cs +++ b/MediaBrowser.Api/Devices/DeviceService.cs @@ -155,16 +155,14 @@ namespace MediaBrowser.Api.Devices Id = id }); } - else + + return _deviceManager.AcceptCameraUpload(deviceId, request.RequestStream, new LocalFileInfo { - return _deviceManager.AcceptCameraUpload(deviceId, request.RequestStream, new LocalFileInfo - { - MimeType = Request.ContentType, - Album = album, - Name = name, - Id = id - }); - } + MimeType = Request.ContentType, + Album = album, + Name = name, + Id = id + }); } } } diff --git a/MediaBrowser.Api/EnvironmentService.cs b/MediaBrowser.Api/EnvironmentService.cs index 36b03f09ce..d199ce1544 100644 --- a/MediaBrowser.Api/EnvironmentService.cs +++ b/MediaBrowser.Api/EnvironmentService.cs @@ -258,12 +258,7 @@ namespace MediaBrowser.Api return false; } - if (!request.IncludeDirectories && isDirectory) - { - return false; - } - - return true; + return request.IncludeDirectories || !isDirectory; }); return entries.Select(f => new FileSystemEntryInfo diff --git a/MediaBrowser.Api/Library/LibraryService.cs b/MediaBrowser.Api/Library/LibraryService.cs index b82247fc66..291242e458 100644 --- a/MediaBrowser.Api/Library/LibraryService.cs +++ b/MediaBrowser.Api/Library/LibraryService.cs @@ -348,28 +348,19 @@ namespace MediaBrowser.Api.Library private string[] GetRepresentativeItemTypes(string contentType) { - switch (contentType) + return contentType switch { - case CollectionType.BoxSets: - return new[] { "BoxSet" }; - case CollectionType.Playlists: - return new[] { "Playlist" }; - case CollectionType.Movies: - return new[] { "Movie" }; - case CollectionType.TvShows: - return new[] { "Series", "Season", "Episode" }; - case CollectionType.Books: - return new[] { "Book" }; - case CollectionType.Music: - return new[] { "MusicAlbum", "MusicArtist", "Audio", "MusicVideo" }; - case CollectionType.HomeVideos: - case CollectionType.Photos: - return new[] { "Video", "Photo" }; - case CollectionType.MusicVideos: - return new[] { "MusicVideo" }; - default: - return new[] { "Series", "Season", "Episode", "Movie" }; - } + CollectionType.BoxSets => new[] {"BoxSet"}, + CollectionType.Playlists => new[] {"Playlist"}, + CollectionType.Movies => new[] {"Movie"}, + CollectionType.TvShows => new[] {"Series", "Season", "Episode"}, + CollectionType.Books => new[] {"Book"}, + CollectionType.Music => new[] {"MusicAlbum", "MusicArtist", "Audio", "MusicVideo"}, + CollectionType.HomeVideos => new[] {"Video", "Photo"}, + CollectionType.Photos => new[] {"Video", "Photo"}, + CollectionType.MusicVideos => new[] {"MusicVideo"}, + _ => new[] {"Series", "Season", "Episode", "Movie"} + }; } private bool IsSaverEnabledByDefault(string name, string[] itemTypes, bool isNewLibrary) @@ -397,22 +388,18 @@ namespace MediaBrowser.Api.Library { if (string.Equals(name, "TheMovieDb", StringComparison.OrdinalIgnoreCase)) { + if (string.Equals(type, "Series", StringComparison.OrdinalIgnoreCase)) { return true; } - if (string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase)) - { - return false; - } - if (string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase)) - { - return false; - } - if (string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase) + || string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase) + || string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase)) { return false; } + return true; } else if (string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase)) @@ -439,12 +426,8 @@ namespace MediaBrowser.Api.Library .Where(i => string.Equals(i.ItemType, type, StringComparison.OrdinalIgnoreCase)) .ToArray(); - if (metadataOptions.Length == 0) - { - return true; - } - - return metadataOptions.Any(i => !i.DisabledMetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase)); + return metadataOptions.Length == 0 + || metadataOptions.Any(i => !i.DisabledMetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase)); } private bool IsImageFetcherEnabledByDefault(string name, string type, bool isNewLibrary) @@ -919,12 +902,10 @@ namespace MediaBrowser.Api.Library private BaseItem TranslateParentItem(BaseItem item, User user) { - if (item.GetParent() is AggregateFolder) - { - return _libraryManager.GetUserRootFolder().GetChildren(user, true).FirstOrDefault(i => i.PhysicalLocations.Contains(item.Path)); - } - - return item; + return item.GetParent() is AggregateFolder + ? _libraryManager.GetUserRootFolder().GetChildren(user, true) + .FirstOrDefault(i => i.PhysicalLocations.Contains(item.Path)) + : item; } /// diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index 6e923768a2..7c9e65fe7a 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -137,12 +137,7 @@ namespace MediaBrowser.Api.Playback var ext = outputFileExtension.ToLowerInvariant(); var folder = ServerConfigurationManager.GetTranscodePath(); - if (EnableOutputInSubFolder) - { - return Path.Combine(folder, filename, filename + ext); - } - - return Path.Combine(folder, filename + ext); + return EnableOutputInSubFolder ? Path.Combine(folder, filename, filename + ext) : Path.Combine(folder, filename + ext); } protected virtual string GetDefaultEncoderPreset() @@ -383,195 +378,215 @@ namespace MediaBrowser.Api.Playback continue; } - if (i == 0) + switch (i) { - request.DeviceProfileId = val; - } - else if (i == 1) - { - request.DeviceId = val; - } - else if (i == 2) - { - request.MediaSourceId = val; - } - else if (i == 3) - { - request.Static = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); - } - else if (i == 4) - { - if (videoRequest != null) + case 0: + request.DeviceProfileId = val; + break; + case 1: + request.DeviceId = val; + break; + case 2: + request.MediaSourceId = val; + break; + case 3: + request.Static = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); + break; + case 4: { - videoRequest.VideoCodec = val; - } - } - else if (i == 5) - { - request.AudioCodec = val; - } - else if (i == 6) - { - if (videoRequest != null) - { - videoRequest.AudioStreamIndex = int.Parse(val, CultureInfo.InvariantCulture); - } - } - else if (i == 7) - { - if (videoRequest != null) - { - videoRequest.SubtitleStreamIndex = int.Parse(val, CultureInfo.InvariantCulture); - } - } - else if (i == 8) - { - if (videoRequest != null) - { - videoRequest.VideoBitRate = int.Parse(val, CultureInfo.InvariantCulture); - } - } - else if (i == 9) - { - request.AudioBitRate = int.Parse(val, CultureInfo.InvariantCulture); - } - else if (i == 10) - { - request.MaxAudioChannels = int.Parse(val, CultureInfo.InvariantCulture); - } - else if (i == 11) - { - if (videoRequest != null) - { - videoRequest.MaxFramerate = float.Parse(val, CultureInfo.InvariantCulture); - } - } - else if (i == 12) - { - if (videoRequest != null) - { - videoRequest.MaxWidth = int.Parse(val, CultureInfo.InvariantCulture); - } - } - else if (i == 13) - { - if (videoRequest != null) - { - videoRequest.MaxHeight = int.Parse(val, CultureInfo.InvariantCulture); - } - } - else if (i == 14) - { - request.StartTimeTicks = long.Parse(val, CultureInfo.InvariantCulture); - } - else if (i == 15) - { - if (videoRequest != null) - { - videoRequest.Level = val; - } - } - else if (i == 16) - { - if (videoRequest != null) - { - videoRequest.MaxRefFrames = int.Parse(val, CultureInfo.InvariantCulture); - } - } - else if (i == 17) - { - if (videoRequest != null) - { - videoRequest.MaxVideoBitDepth = int.Parse(val, CultureInfo.InvariantCulture); - } - } - else if (i == 18) - { - if (videoRequest != null) - { - videoRequest.Profile = val; - } - } - else if (i == 19) - { - // cabac no longer used - } - else if (i == 20) - { - request.PlaySessionId = val; - } - else if (i == 21) - { - // api_key - } - else if (i == 22) - { - request.LiveStreamId = val; - } - else if (i == 23) - { - // Duplicating ItemId because of MediaMonkey - } - else if (i == 24) - { - if (videoRequest != null) - { - videoRequest.CopyTimestamps = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); - } - } - else if (i == 25) - { - if (!string.IsNullOrWhiteSpace(val) && videoRequest != null) - { - if (Enum.TryParse(val, out SubtitleDeliveryMethod method)) + if (videoRequest != null) { - videoRequest.SubtitleMethod = method; + videoRequest.VideoCodec = val; } + + break; } - } - else if (i == 26) - { - request.TranscodingMaxAudioChannels = int.Parse(val, CultureInfo.InvariantCulture); - } - else if (i == 27) - { - if (videoRequest != null) + case 5: + request.AudioCodec = val; + break; + case 6: { - videoRequest.EnableSubtitlesInManifest = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); + if (videoRequest != null) + { + videoRequest.AudioStreamIndex = int.Parse(val, CultureInfo.InvariantCulture); + } + + break; } - } - else if (i == 28) - { - request.Tag = val; - } - else if (i == 29) - { - if (videoRequest != null) + case 7: { - videoRequest.RequireAvc = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); + if (videoRequest != null) + { + videoRequest.SubtitleStreamIndex = int.Parse(val, CultureInfo.InvariantCulture); + } + + break; } - } - else if (i == 30) - { - request.SubtitleCodec = val; - } - else if (i == 31) - { - if (videoRequest != null) + case 8: { - videoRequest.RequireNonAnamorphic = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); + if (videoRequest != null) + { + videoRequest.VideoBitRate = int.Parse(val, CultureInfo.InvariantCulture); + } + + break; } - } - else if (i == 32) - { - if (videoRequest != null) + case 9: + request.AudioBitRate = int.Parse(val, CultureInfo.InvariantCulture); + break; + case 10: + request.MaxAudioChannels = int.Parse(val, CultureInfo.InvariantCulture); + break; + case 11: { - videoRequest.DeInterlace = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); + if (videoRequest != null) + { + videoRequest.MaxFramerate = float.Parse(val, CultureInfo.InvariantCulture); + } + + break; } - } - else if (i == 33) - { - request.TranscodeReasons = val; + case 12: + { + if (videoRequest != null) + { + videoRequest.MaxWidth = int.Parse(val, CultureInfo.InvariantCulture); + } + + break; + } + case 13: + { + if (videoRequest != null) + { + videoRequest.MaxHeight = int.Parse(val, CultureInfo.InvariantCulture); + } + + break; + } + case 14: + request.StartTimeTicks = long.Parse(val, CultureInfo.InvariantCulture); + break; + case 15: + { + if (videoRequest != null) + { + videoRequest.Level = val; + } + + break; + } + case 16: + { + if (videoRequest != null) + { + videoRequest.MaxRefFrames = int.Parse(val, CultureInfo.InvariantCulture); + } + + break; + } + case 17: + { + if (videoRequest != null) + { + videoRequest.MaxVideoBitDepth = int.Parse(val, CultureInfo.InvariantCulture); + } + + break; + } + case 18: + { + if (videoRequest != null) + { + videoRequest.Profile = val; + } + + break; + } + case 19: + // cabac no longer used + break; + case 20: + request.PlaySessionId = val; + break; + case 21: + // api_key + break; + case 22: + request.LiveStreamId = val; + break; + case 23: + // Duplicating ItemId because of MediaMonkey + break; + case 24: + { + if (videoRequest != null) + { + videoRequest.CopyTimestamps = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); + } + + break; + } + case 25: + { + if (!string.IsNullOrWhiteSpace(val) && videoRequest != null) + { + if (Enum.TryParse(val, out SubtitleDeliveryMethod method)) + { + videoRequest.SubtitleMethod = method; + } + } + + break; + } + case 26: + request.TranscodingMaxAudioChannels = int.Parse(val, CultureInfo.InvariantCulture); + break; + case 27: + { + if (videoRequest != null) + { + videoRequest.EnableSubtitlesInManifest = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); + } + + break; + } + case 28: + request.Tag = val; + break; + case 29: + { + if (videoRequest != null) + { + videoRequest.RequireAvc = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); + } + + break; + } + case 30: + request.SubtitleCodec = val; + break; + case 31: + { + if (videoRequest != null) + { + videoRequest.RequireNonAnamorphic = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); + } + + break; + } + case 32: + { + if (videoRequest != null) + { + videoRequest.DeInterlace = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); + } + + break; + } + case 33: + request.TranscodeReasons = val; + break; } } } @@ -624,14 +639,9 @@ namespace MediaBrowser.Api.Playback throw new ArgumentException("Invalid timeseek header"); } int index = value.IndexOf('-'); - if (index == -1) - { - value = value.Substring(Npt.Length); - } - else - { - value = value.Substring(Npt.Length, index - Npt.Length); - } + value = index == -1 + ? value.Substring(Npt.Length) + : value.Substring(Npt.Length, index - Npt.Length); if (value.IndexOf(':') == -1) { diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index d30175e762..2375e05d02 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -662,17 +662,9 @@ namespace MediaBrowser.Api.Playback }; }).ThenBy(i => { - if (maxBitrate.HasValue) + if (maxBitrate.HasValue && i.Bitrate.HasValue) { - if (i.Bitrate.HasValue) - { - if (i.Bitrate.Value <= maxBitrate.Value) - { - return 0; - } - - return 2; - } + return i.Bitrate.Value <= maxBitrate.Value ? 0 : 2; } return 1; diff --git a/MediaBrowser.Api/SearchService.cs b/MediaBrowser.Api/SearchService.cs index c5b78828cb..d4e2f44df6 100644 --- a/MediaBrowser.Api/SearchService.cs +++ b/MediaBrowser.Api/SearchService.cs @@ -234,46 +234,44 @@ namespace MediaBrowser.Api SetThumbImageInfo(result, item); SetBackdropImageInfo(result, item); - if (item is LiveTvProgram program) + switch (item) { - result.StartDate = program.StartDate; - } - - if (item is IHasSeries hasSeries) - { - result.Series = hasSeries.SeriesName; - } - - if (item is Series series) - { - if (series.Status.HasValue) + case IHasSeries hasSeries: + result.Series = hasSeries.SeriesName; + break; + case LiveTvProgram program: + result.StartDate = program.StartDate; + break; + case Series series: { - result.Status = series.Status.Value.ToString(); + if (series.Status.HasValue) + { + result.Status = series.Status.Value.ToString(); + } + + break; } - } + case MusicAlbum album: + result.Artists = album.Artists; + result.AlbumArtist = album.AlbumArtist; + break; + case Audio song: + result.AlbumArtist = song.AlbumArtists.FirstOrDefault(); + result.Artists = song.Artists; - if (item is MusicAlbum album) - { - result.Artists = album.Artists; - result.AlbumArtist = album.AlbumArtist; - } + MusicAlbum musicAlbum = song.AlbumEntity; - if (item is Audio song) - { - result.AlbumArtist = song.AlbumArtists.FirstOrDefault(); - result.Artists = song.Artists; + if (musicAlbum != null) + { + result.Album = musicAlbum.Name; + result.AlbumId = musicAlbum.Id; + } + else + { + result.Album = song.Album; + } - album = song.AlbumEntity; - - if (album != null) - { - result.Album = album.Name; - result.AlbumId = album.Id; - } - else - { - result.Album = song.Album; - } + break; } if (!item.ChannelId.Equals(Guid.Empty)) @@ -289,12 +287,9 @@ namespace MediaBrowser.Api { var itemWithImage = item.HasImage(ImageType.Thumb) ? item : null; - if (itemWithImage == null) + if (itemWithImage == null && item is Episode) { - if (item is Episode) - { - itemWithImage = GetParentWithImage(item, ImageType.Thumb); - } + itemWithImage = GetParentWithImage(item, ImageType.Thumb); } if (itemWithImage == null) diff --git a/MediaBrowser.Api/System/SystemService.cs b/MediaBrowser.Api/System/SystemService.cs index 3a3eeb8b8f..cfede6f693 100644 --- a/MediaBrowser.Api/System/SystemService.cs +++ b/MediaBrowser.Api/System/SystemService.cs @@ -168,12 +168,8 @@ namespace MediaBrowser.Api.System .First(i => string.Equals(i.Name, request.Name, StringComparison.OrdinalIgnoreCase)); // For older files, assume fully static - if (file.LastWriteTimeUtc < DateTime.UtcNow.AddHours(-1)) - { - return ResultFactory.GetStaticFileResult(Request, file.FullName, FileShare.Read); - } - - return ResultFactory.GetStaticFileResult(Request, file.FullName, FileShare.ReadWrite); + return ResultFactory.GetStaticFileResult(Request, file.FullName, + file.LastWriteTimeUtc < DateTime.UtcNow.AddHours(-1) ? FileShare.Read : FileShare.ReadWrite); } /// diff --git a/MediaBrowser.Api/UserLibrary/ArtistsService.cs b/MediaBrowser.Api/UserLibrary/ArtistsService.cs index adb0a440f6..3d08d5437c 100644 --- a/MediaBrowser.Api/UserLibrary/ArtistsService.cs +++ b/MediaBrowser.Api/UserLibrary/ArtistsService.cs @@ -126,12 +126,7 @@ namespace MediaBrowser.Api.UserLibrary protected override QueryResult<(BaseItem, ItemCounts)> GetItems(GetItemsByName request, InternalItemsQuery query) { - if (request is GetAlbumArtists) - { - return LibraryManager.GetAlbumArtists(query); - } - - return LibraryManager.GetArtists(query); + return request is GetAlbumArtists ? LibraryManager.GetAlbumArtists(query) : LibraryManager.GetArtists(query); } /// diff --git a/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs b/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs index a26f59573c..03cf7cabe5 100644 --- a/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs +++ b/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs @@ -396,12 +396,10 @@ namespace MediaBrowser.Api.UserLibrary public VideoType[] GetVideoTypes() { - if (string.IsNullOrEmpty(VideoTypes)) - { - return Array.Empty(); - } - - return VideoTypes.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(v => (VideoType)Enum.Parse(typeof(VideoType), v, true)).ToArray(); + return string.IsNullOrEmpty(VideoTypes) + ? Array.Empty() + : VideoTypes.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) + .Select(v => (VideoType)Enum.Parse(typeof(VideoType), v, true)).ToArray(); } /// @@ -412,12 +410,10 @@ namespace MediaBrowser.Api.UserLibrary { var val = Filters; - if (string.IsNullOrEmpty(val)) - { - return new ItemFilter[] { }; - } - - return val.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(v => (ItemFilter)Enum.Parse(typeof(ItemFilter), v, true)).ToArray(); + return string.IsNullOrEmpty(val) + ? new ItemFilter[] { } + : val.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries). + Select(v => (ItemFilter)Enum.Parse(typeof(ItemFilter), v, true)).ToArray(); } /// @@ -428,12 +424,9 @@ namespace MediaBrowser.Api.UserLibrary { var val = ImageTypes; - if (string.IsNullOrEmpty(val)) - { - return new ImageType[] { }; - } - - return val.Split(',').Select(v => (ImageType)Enum.Parse(typeof(ImageType), v, true)).ToArray(); + return string.IsNullOrEmpty(val) + ? new ImageType[] { } + : val.Split(',').Select(v => (ImageType)Enum.Parse(typeof(ImageType), v, true)).ToArray(); } /// From e1958e3902ae81931c82a31f355cefc2b02a8a2d Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Sun, 5 Apr 2020 15:56:08 -0400 Subject: [PATCH 07/11] Miscellaneous code cleanup --- MediaBrowser.Api/ItemLookupService.cs | 10 ++- MediaBrowser.Api/Library/LibraryService.cs | 75 +++++-------------- .../Playback/Hls/BaseHlsService.cs | 17 ++--- .../UserLibrary/BaseItemsByNameService.cs | 31 +++----- MediaBrowser.Api/VideosService.cs | 6 +- 5 files changed, 44 insertions(+), 95 deletions(-) diff --git a/MediaBrowser.Api/ItemLookupService.cs b/MediaBrowser.Api/ItemLookupService.cs index a76369a157..5a7b1f37ae 100644 --- a/MediaBrowser.Api/ItemLookupService.cs +++ b/MediaBrowser.Api/ItemLookupService.cs @@ -305,9 +305,15 @@ namespace MediaBrowser.Api Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath)); using (var stream = result.Content) - using (var filestream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true)) { - await stream.CopyToAsync(filestream).ConfigureAwait(false); + using var fileStream = new FileStream(fullCachePath, + FileMode.Create, + FileAccess.Write, + FileShare.Read, + IODefaults.FileStreamBufferSize, + true); + + await stream.CopyToAsync(fileStream).ConfigureAwait(false); } Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath)); diff --git a/MediaBrowser.Api/Library/LibraryService.cs b/MediaBrowser.Api/Library/LibraryService.cs index 291242e458..9251343e8b 100644 --- a/MediaBrowser.Api/Library/LibraryService.cs +++ b/MediaBrowser.Api/Library/LibraryService.cs @@ -544,8 +544,7 @@ namespace MediaBrowser.Api.Library foreach (var type in types) { - ImageOption[] defaultImageOptions = null; - TypeOptions.DefaultImageOptions.TryGetValue(type, out defaultImageOptions); + TypeOptions.DefaultImageOptions.TryGetValue(type, out var defaultImageOptions); typeOptions.Add(new LibraryTypeOptions { @@ -592,8 +591,6 @@ namespace MediaBrowser.Api.Library public object Get(GetSimilarItems request) { - var user = !request.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(request.UserId) : null; - var item = string.IsNullOrEmpty(request.Id) ? (!request.UserId.Equals(Guid.Empty) ? _libraryManager.GetUserRootFolder() : _libraryManager.RootFolder) : _libraryManager.GetItemById(request.Id); @@ -651,7 +648,7 @@ namespace MediaBrowser.Api.Library // ExcludeArtistIds if (!string.IsNullOrEmpty(request.ExcludeArtistIds)) { - query.ExcludeArtistIds = BaseApiService.GetGuids(request.ExcludeArtistIds); + query.ExcludeArtistIds = GetGuids(request.ExcludeArtistIds); } List itemsResult; @@ -672,7 +669,6 @@ namespace MediaBrowser.Api.Library var result = new QueryResult { Items = returnList, - TotalRecordCount = itemsResult.Count }; @@ -1075,36 +1071,18 @@ namespace MediaBrowser.Api.Library throw new ResourceNotFoundException("Item not found."); } - BaseItem[] themeItems = Array.Empty(); + IEnumerable themeItems = item.GetThemeSongs(); - while (true) + while (!themeItems.Any() && request.InheritFromParent && item.GetParent() != null) { - themeItems = item.GetThemeSongs().ToArray(); - - if (themeItems.Length > 0) - { - break; - } - - if (!request.InheritFromParent) - { - break; - } - - var parent = item.GetParent(); - if (parent == null) - { - break; - } - item = parent; + item = item.GetParent(); + themeItems = item.GetThemeSongs(); } var dtoOptions = GetDtoOptions(_authContext, request); - - var dtos = themeItems - .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item)); - - var items = dtos.ToArray(); + var items = themeItems + .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item)) + .ToArray(); return new ThemeMediaResult { @@ -1121,9 +1099,7 @@ namespace MediaBrowser.Api.Library /// System.Object. public object Get(GetThemeVideos request) { - var result = GetThemeVideos(request); - - return ToOptimizedResult(result); + return ToOptimizedResult(GetThemeVideos(request)); } public ThemeMediaResult GetThemeVideos(GetThemeVideos request) @@ -1141,36 +1117,19 @@ namespace MediaBrowser.Api.Library throw new ResourceNotFoundException("Item not found."); } - BaseItem[] themeItems = Array.Empty(); + IEnumerable themeItems = item.GetThemeVideos(); - while (true) + while (!themeItems.Any() && request.InheritFromParent && item.GetParent() != null) { - themeItems = item.GetThemeVideos().ToArray(); - - if (themeItems.Length > 0) - { - break; - } - - if (!request.InheritFromParent) - { - break; - } - - var parent = item.GetParent(); - if (parent == null) - { - break; - } - item = parent; + item = item.GetParent(); + themeItems = item.GetThemeVideos(); } var dtoOptions = GetDtoOptions(_authContext, request); - var dtos = themeItems - .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item)); - - var items = dtos.ToArray(); + var items = themeItems + .Select(i => _dtoService.GetBaseItemDto(i, dtoOptions, user, item)) + .ToArray(); return new ThemeMediaResult { diff --git a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs index 566eaf86ea..8d5d2279ea 100644 --- a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs @@ -240,17 +240,12 @@ namespace MediaBrowser.Api.Playback.Hls protected Stream GetPlaylistFileStream(string path) { - var tmpPath = path + ".tmp"; - tmpPath = path; - - try - { - return new FileStream(tmpPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, FileOptions.SequentialScan); - } - catch (IOException) - { - return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, FileOptions.SequentialScan); - } + return new FileStream(path, + FileMode.Open, + FileAccess.Read, + FileShare.ReadWrite, + IODefaults.FileStreamBufferSize, + FileOptions.SequentialScan); } protected override string GetCommandLineArguments(string outputPath, EncodingOptions encodingOptions, StreamState state, bool isEncoding) diff --git a/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs b/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs index 7e4e589ea0..c4a52d5f52 100644 --- a/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs +++ b/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs @@ -273,7 +273,7 @@ namespace MediaBrowser.Api.UserLibrary DtoOptions = dtoOptions }; - Func filter = i => FilterItem(request, i, excludeItemTypes, includeItemTypes, mediaTypes); + bool Filter(BaseItem i) => FilterItem(request, i, excludeItemTypes, includeItemTypes, mediaTypes); if (parentItem.IsFolder) { @@ -283,18 +283,18 @@ namespace MediaBrowser.Api.UserLibrary { items = request.Recursive ? folder.GetRecursiveChildren(user, query).ToList() : - folder.GetChildren(user, true).Where(filter).ToList(); + folder.GetChildren(user, true).Where(Filter).ToList(); } else { items = request.Recursive ? - folder.GetRecursiveChildren(filter) : - folder.Children.Where(filter).ToList(); + folder.GetRecursiveChildren(Filter) : + folder.Children.Where(Filter).ToList(); } } else { - items = new[] { parentItem }.Where(filter).ToList(); + items = new[] { parentItem }.Where(Filter).ToList(); } var extractedItems = GetAllItems(request, items); @@ -345,30 +345,21 @@ namespace MediaBrowser.Api.UserLibrary private bool FilterItem(GetItemsByName request, BaseItem f, string[] excludeItemTypes, string[] includeItemTypes, string[] mediaTypes) { // Exclude item types - if (excludeItemTypes.Length > 0) + if (excludeItemTypes.Length > 0 && excludeItemTypes.Contains(f.GetType().Name, StringComparer.OrdinalIgnoreCase)) { - if (excludeItemTypes.Contains(f.GetType().Name, StringComparer.OrdinalIgnoreCase)) - { - return false; - } + return false; } // Include item types - if (includeItemTypes.Length > 0) + if (includeItemTypes.Length > 0 && !includeItemTypes.Contains(f.GetType().Name, StringComparer.OrdinalIgnoreCase)) { - if (!includeItemTypes.Contains(f.GetType().Name, StringComparer.OrdinalIgnoreCase)) - { - return false; - } + return false; } // Include MediaTypes - if (mediaTypes.Length > 0) + if (mediaTypes.Length > 0 && !mediaTypes.Contains(f.MediaType ?? string.Empty, StringComparer.OrdinalIgnoreCase)) { - if (!mediaTypes.Contains(f.MediaType ?? string.Empty, StringComparer.OrdinalIgnoreCase)) - { - return false; - } + return false; } return true; diff --git a/MediaBrowser.Api/VideosService.cs b/MediaBrowser.Api/VideosService.cs index 9d7dc2dfc6..76e9f421d0 100644 --- a/MediaBrowser.Api/VideosService.cs +++ b/MediaBrowser.Api/VideosService.cs @@ -138,10 +138,8 @@ namespace MediaBrowser.Api var videosWithVersions = items.Where(i => i.MediaSourceCount > 1) .ToList(); - var primaryVersion = videosWithVersions.FirstOrDefault() ?? items.OrderBy(i => - { - return (i.Video3DFormat.HasValue || i.VideoType != Model.Entities.VideoType.VideoFile) ? 1 : 0; - }) + var primaryVersion = videosWithVersions.FirstOrDefault() ?? items.OrderBy(i + => (i.Video3DFormat.HasValue || i.VideoType != Model.Entities.VideoType.VideoFile) ? 1 : 0) .ThenByDescending(i => { var stream = i.GetDefaultVideoStream(); From 81b4a4c54c63822692cd3936fc3c7d8d6e45397c Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Sun, 5 Apr 2020 17:58:39 -0400 Subject: [PATCH 08/11] Implement various suggestions --- MediaBrowser.Api/ApiEntryPoint.cs | 6 +-- MediaBrowser.Api/ChannelService.cs | 12 ++--- MediaBrowser.Api/ItemLookupService.cs | 3 +- MediaBrowser.Api/Library/LibraryService.cs | 1 + .../Playback/BaseStreamingService.cs | 47 +++---------------- .../Playback/Hls/BaseHlsService.cs | 3 +- MediaBrowser.Api/SearchService.cs | 2 - .../UserLibrary/BaseItemsRequest.cs | 12 +++-- MediaBrowser.Api/VideosService.cs | 24 ++++++---- 9 files changed, 42 insertions(+), 68 deletions(-) diff --git a/MediaBrowser.Api/ApiEntryPoint.cs b/MediaBrowser.Api/ApiEntryPoint.cs index 61ad976ec3..6691080bc8 100644 --- a/MediaBrowser.Api/ApiEntryPoint.cs +++ b/MediaBrowser.Api/ApiEntryPoint.cs @@ -484,9 +484,9 @@ namespace MediaBrowser.Api /// Task. internal Task KillTranscodingJobs(string deviceId, string playSessionId, Func deleteFiles) { - return KillTranscodingJobs(j => !string.IsNullOrWhiteSpace(playSessionId) - ? string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase) - : string.Equals(deviceId, j.DeviceId, StringComparison.OrdinalIgnoreCase), deleteFiles); + return KillTranscodingJobs(j => string.IsNullOrWhiteSpace(playSessionId) + ? string.Equals(deviceId, j.DeviceId, StringComparison.OrdinalIgnoreCase) + : string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase), deleteFiles); } /// diff --git a/MediaBrowser.Api/ChannelService.cs b/MediaBrowser.Api/ChannelService.cs index e43e34133c..fd9b8c3968 100644 --- a/MediaBrowser.Api/ChannelService.cs +++ b/MediaBrowser.Api/ChannelService.cs @@ -117,8 +117,8 @@ namespace MediaBrowser.Api var val = Filters; return string.IsNullOrEmpty(val) - ? new ItemFilter[] { } - : val.Split(',').Select(v => (ItemFilter)Enum.Parse(typeof(ItemFilter), v, true)); + ? Array.Empty() + : val.Split(',').Select(v => Enum.Parse(v, true)); } /// @@ -170,11 +170,9 @@ namespace MediaBrowser.Api /// IEnumerable{ItemFilter}. public IEnumerable GetFilters() { - var val = Filters; - - return string.IsNullOrEmpty(val) - ? new ItemFilter[] { } - : val.Split(',').Select(v => (ItemFilter)Enum.Parse(typeof(ItemFilter), v, true)); + return string.IsNullOrEmpty(Filters) + ? Array.Empty() + : Filters.Split(',').Select(v => Enum.Parse(v, true)); } } diff --git a/MediaBrowser.Api/ItemLookupService.cs b/MediaBrowser.Api/ItemLookupService.cs index 5a7b1f37ae..0bbe7e1cfa 100644 --- a/MediaBrowser.Api/ItemLookupService.cs +++ b/MediaBrowser.Api/ItemLookupService.cs @@ -306,7 +306,8 @@ namespace MediaBrowser.Api Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath)); using (var stream = result.Content) { - using var fileStream = new FileStream(fullCachePath, + using var fileStream = new FileStream( + fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, diff --git a/MediaBrowser.Api/Library/LibraryService.cs b/MediaBrowser.Api/Library/LibraryService.cs index 9251343e8b..6f6c1864ed 100644 --- a/MediaBrowser.Api/Library/LibraryService.cs +++ b/MediaBrowser.Api/Library/LibraryService.cs @@ -393,6 +393,7 @@ namespace MediaBrowser.Api.Library { return true; } + if (string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase) || string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase) || string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase)) diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index 7c9e65fe7a..eb44cb4266 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -137,7 +137,9 @@ namespace MediaBrowser.Api.Playback var ext = outputFileExtension.ToLowerInvariant(); var folder = ServerConfigurationManager.GetTranscodePath(); - return EnableOutputInSubFolder ? Path.Combine(folder, filename, filename + ext) : Path.Combine(folder, filename + ext); + return EnableOutputInSubFolder + ? Path.Combine(folder, filename, filename + ext) + : Path.Combine(folder, filename + ext); } protected virtual string GetDefaultEncoderPreset() @@ -393,44 +395,36 @@ namespace MediaBrowser.Api.Playback request.Static = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); break; case 4: - { if (videoRequest != null) { videoRequest.VideoCodec = val; } break; - } case 5: request.AudioCodec = val; break; case 6: - { if (videoRequest != null) { videoRequest.AudioStreamIndex = int.Parse(val, CultureInfo.InvariantCulture); } break; - } case 7: - { if (videoRequest != null) { videoRequest.SubtitleStreamIndex = int.Parse(val, CultureInfo.InvariantCulture); } break; - } case 8: - { if (videoRequest != null) { videoRequest.VideoBitRate = int.Parse(val, CultureInfo.InvariantCulture); } break; - } case 9: request.AudioBitRate = int.Parse(val, CultureInfo.InvariantCulture); break; @@ -438,71 +432,57 @@ namespace MediaBrowser.Api.Playback request.MaxAudioChannels = int.Parse(val, CultureInfo.InvariantCulture); break; case 11: - { if (videoRequest != null) { videoRequest.MaxFramerate = float.Parse(val, CultureInfo.InvariantCulture); } break; - } case 12: - { if (videoRequest != null) { videoRequest.MaxWidth = int.Parse(val, CultureInfo.InvariantCulture); } break; - } case 13: - { if (videoRequest != null) { videoRequest.MaxHeight = int.Parse(val, CultureInfo.InvariantCulture); } break; - } case 14: request.StartTimeTicks = long.Parse(val, CultureInfo.InvariantCulture); break; case 15: - { if (videoRequest != null) { videoRequest.Level = val; } break; - } case 16: - { if (videoRequest != null) { videoRequest.MaxRefFrames = int.Parse(val, CultureInfo.InvariantCulture); } break; - } case 17: - { if (videoRequest != null) { videoRequest.MaxVideoBitDepth = int.Parse(val, CultureInfo.InvariantCulture); } break; - } case 18: - { if (videoRequest != null) { videoRequest.Profile = val; } break; - } case 19: // cabac no longer used break; @@ -519,16 +499,13 @@ namespace MediaBrowser.Api.Playback // Duplicating ItemId because of MediaMonkey break; case 24: - { if (videoRequest != null) { videoRequest.CopyTimestamps = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); } break; - } case 25: - { if (!string.IsNullOrWhiteSpace(val) && videoRequest != null) { if (Enum.TryParse(val, out SubtitleDeliveryMethod method)) @@ -538,52 +515,43 @@ namespace MediaBrowser.Api.Playback } break; - } case 26: request.TranscodingMaxAudioChannels = int.Parse(val, CultureInfo.InvariantCulture); break; case 27: - { if (videoRequest != null) { videoRequest.EnableSubtitlesInManifest = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); } break; - } case 28: request.Tag = val; break; case 29: - { if (videoRequest != null) { videoRequest.RequireAvc = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); } break; - } case 30: request.SubtitleCodec = val; break; case 31: - { if (videoRequest != null) { videoRequest.RequireNonAnamorphic = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); } break; - } case 32: - { if (videoRequest != null) { videoRequest.DeInterlace = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); } break; - } case 33: request.TranscodeReasons = val; break; @@ -860,14 +828,11 @@ namespace MediaBrowser.Api.Playback { state.DeviceProfile = DlnaManager.GetProfile(state.Request.DeviceProfileId); } - else + else if (!string.IsNullOrWhiteSpace(state.Request.DeviceId)) { - if (!string.IsNullOrWhiteSpace(state.Request.DeviceId)) - { - var caps = DeviceManager.GetCapabilities(state.Request.DeviceId); + var caps = DeviceManager.GetCapabilities(state.Request.DeviceId); - state.DeviceProfile = caps != null ? caps.DeviceProfile : DlnaManager.GetProfile(headers); - } + state.DeviceProfile = caps == null ? DlnaManager.GetProfile(headers) : caps.DeviceProfile; } var profile = state.DeviceProfile; diff --git a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs index 8d5d2279ea..52962366c6 100644 --- a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs @@ -240,7 +240,8 @@ namespace MediaBrowser.Api.Playback.Hls protected Stream GetPlaylistFileStream(string path) { - return new FileStream(path, + return new FileStream( + path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, diff --git a/MediaBrowser.Api/SearchService.cs b/MediaBrowser.Api/SearchService.cs index d4e2f44df6..15148d1c72 100644 --- a/MediaBrowser.Api/SearchService.cs +++ b/MediaBrowser.Api/SearchService.cs @@ -243,14 +243,12 @@ namespace MediaBrowser.Api result.StartDate = program.StartDate; break; case Series series: - { if (series.Status.HasValue) { result.Status = series.Status.Value.ToString(); } break; - } case MusicAlbum album: result.Artists = album.Artists; result.AlbumArtist = album.AlbumArtist; diff --git a/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs b/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs index 03cf7cabe5..eb2f5996ea 100644 --- a/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs +++ b/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs @@ -399,7 +399,7 @@ namespace MediaBrowser.Api.UserLibrary return string.IsNullOrEmpty(VideoTypes) ? Array.Empty() : VideoTypes.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) - .Select(v => (VideoType)Enum.Parse(typeof(VideoType), v, true)).ToArray(); + .Select(v => Enum.Parse(v, true)).ToArray(); } /// @@ -411,9 +411,9 @@ namespace MediaBrowser.Api.UserLibrary var val = Filters; return string.IsNullOrEmpty(val) - ? new ItemFilter[] { } + ? Array.Empty() : val.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries). - Select(v => (ItemFilter)Enum.Parse(typeof(ItemFilter), v, true)).ToArray(); + Select(v => Enum.Parse(v, true)).ToArray(); } /// @@ -426,7 +426,7 @@ namespace MediaBrowser.Api.UserLibrary return string.IsNullOrEmpty(val) ? new ImageType[] { } - : val.Split(',').Select(v => (ImageType)Enum.Parse(typeof(ImageType), v, true)).ToArray(); + : val.Split(',').Select(v => Enum.Parse(v, true)).ToArray(); } /// @@ -462,7 +462,9 @@ namespace MediaBrowser.Api.UserLibrary var sortOrderIndex = sortOrders.Length > i ? i : 0; var sortOrderValue = sortOrders.Length > sortOrderIndex ? sortOrders[sortOrderIndex] : null; - var sortOrder = string.Equals(sortOrderValue, "Descending", StringComparison.OrdinalIgnoreCase) ? MediaBrowser.Model.Entities.SortOrder.Descending : MediaBrowser.Model.Entities.SortOrder.Ascending; + var sortOrder = string.Equals(sortOrderValue, "Descending", StringComparison.OrdinalIgnoreCase) + ? MediaBrowser.Model.Entities.SortOrder.Descending + : MediaBrowser.Model.Entities.SortOrder.Ascending; result[i] = new ValueTuple(vals[i], sortOrder); } diff --git a/MediaBrowser.Api/VideosService.cs b/MediaBrowser.Api/VideosService.cs index 76e9f421d0..b11fd48d3c 100644 --- a/MediaBrowser.Api/VideosService.cs +++ b/MediaBrowser.Api/VideosService.cs @@ -138,15 +138,23 @@ namespace MediaBrowser.Api var videosWithVersions = items.Where(i => i.MediaSourceCount > 1) .ToList(); - var primaryVersion = videosWithVersions.FirstOrDefault() ?? items.OrderBy(i - => (i.Video3DFormat.HasValue || i.VideoType != Model.Entities.VideoType.VideoFile) ? 1 : 0) - .ThenByDescending(i => - { - var stream = i.GetDefaultVideoStream(); + var primaryVersion = videosWithVersions.FirstOrDefault(); + if (primaryVersion == null) + { + primaryVersion = items.OrderBy(i => + { + if (i.Video3DFormat.HasValue || i.VideoType != Model.Entities.VideoType.VideoFile) + { + return 1; + } - return stream?.Width ?? 0; - - }).First(); + return 0; + }) + .ThenByDescending(i => + { + return i.GetDefaultVideoStream()?.Width ?? 0; + }).First(); + } var list = primaryVersion.LinkedAlternateVersions.ToList(); From 47ba4a84cd4b832f999dbefb628ed3eedb7c9e05 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Sun, 5 Apr 2020 18:06:30 -0400 Subject: [PATCH 09/11] Simplified more conditionals --- MediaBrowser.Api/Library/LibraryService.cs | 68 +++++----------------- 1 file changed, 15 insertions(+), 53 deletions(-) diff --git a/MediaBrowser.Api/Library/LibraryService.cs b/MediaBrowser.Api/Library/LibraryService.cs index 6f6c1864ed..d71bf9a0e9 100644 --- a/MediaBrowser.Api/Library/LibraryService.cs +++ b/MediaBrowser.Api/Library/LibraryService.cs @@ -388,12 +388,6 @@ namespace MediaBrowser.Api.Library { if (string.Equals(name, "TheMovieDb", StringComparison.OrdinalIgnoreCase)) { - - if (string.Equals(type, "Series", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - if (string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase) || string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase) || string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase)) @@ -403,19 +397,10 @@ namespace MediaBrowser.Api.Library return true; } - else if (string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - else if (string.Equals(name, "The Open Movie Database", StringComparison.OrdinalIgnoreCase)) - { - return false; - } - else if (string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - else if (string.Equals(name, "MusicBrainz", StringComparison.OrdinalIgnoreCase)) + + if (string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase) + || string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase) + || string.Equals(name, "MusicBrainz", StringComparison.OrdinalIgnoreCase)) { return true; } @@ -437,45 +422,22 @@ namespace MediaBrowser.Api.Library { if (string.Equals(name, "TheMovieDb", StringComparison.OrdinalIgnoreCase)) { - if (string.Equals(type, "Series", StringComparison.OrdinalIgnoreCase)) - { - return false; - } - if (string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase)) - { - return false; - } - if (string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase)) - { - return false; - } - if (string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(type, "Series", StringComparison.OrdinalIgnoreCase) + || string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase) + || string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase) + || string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase)) { return false; } + return true; } - else if (string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - else if (string.Equals(name, "The Open Movie Database", StringComparison.OrdinalIgnoreCase)) - { - return false; - } - else if (string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - else if (string.Equals(name, "Emby Designs", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - else if (string.Equals(name, "Screen Grabber", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - else if (string.Equals(name, "Image Extractor", StringComparison.OrdinalIgnoreCase)) + + if (string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase) + || string.Equals(name, "Screen Grabber", StringComparison.OrdinalIgnoreCase) + || string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase) + || string.Equals(name, "Emby Designs", StringComparison.OrdinalIgnoreCase) + || string.Equals(name, "Image Extractor", StringComparison.OrdinalIgnoreCase)) { return true; } From c9da49ebaa28df3dce6e68078381508cebe4c890 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Sun, 5 Apr 2020 23:12:25 -0400 Subject: [PATCH 10/11] Implemented more suggestions --- MediaBrowser.Api/BaseApiService.cs | 10 ++- MediaBrowser.Api/Library/LibraryService.cs | 84 ++++++++++--------- MediaBrowser.Api/SearchService.cs | 2 +- MediaBrowser.Api/System/SystemService.cs | 5 +- .../UserLibrary/BaseItemsRequest.cs | 2 +- 5 files changed, 55 insertions(+), 48 deletions(-) diff --git a/MediaBrowser.Api/BaseApiService.cs b/MediaBrowser.Api/BaseApiService.cs index b43aed7bfd..1a1d86362a 100644 --- a/MediaBrowser.Api/BaseApiService.cs +++ b/MediaBrowser.Api/BaseApiService.cs @@ -262,19 +262,23 @@ namespace MediaBrowser.Api private T GetItemFromSlugName(ILibraryManager libraryManager, string name, DtoOptions dtoOptions) where T : BaseItem, new() { - var result = (libraryManager.GetItemList(new InternalItemsQuery + var result = libraryManager.GetItemList(new InternalItemsQuery { Name = name.Replace(BaseItem.SlugChar, '&'), IncludeItemTypes = new[] { typeof(T).Name }, DtoOptions = dtoOptions - }).OfType().FirstOrDefault() ?? libraryManager.GetItemList(new InternalItemsQuery + }).OfType().FirstOrDefault(); + + result ??= libraryManager.GetItemList(new InternalItemsQuery { Name = name.Replace(BaseItem.SlugChar, '/'), IncludeItemTypes = new[] { typeof(T).Name }, DtoOptions = dtoOptions - }).OfType().FirstOrDefault()) ?? libraryManager.GetItemList(new InternalItemsQuery + }).OfType().FirstOrDefault(); + + result ??= libraryManager.GetItemList(new InternalItemsQuery { Name = name.Replace(BaseItem.SlugChar, '?'), IncludeItemTypes = new[] { typeof(T).Name }, diff --git a/MediaBrowser.Api/Library/LibraryService.cs b/MediaBrowser.Api/Library/LibraryService.cs index d71bf9a0e9..26be9db832 100644 --- a/MediaBrowser.Api/Library/LibraryService.cs +++ b/MediaBrowser.Api/Library/LibraryService.cs @@ -388,24 +388,14 @@ namespace MediaBrowser.Api.Library { if (string.Equals(name, "TheMovieDb", StringComparison.OrdinalIgnoreCase)) { - if (string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase) - || string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase) - || string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase)) - { - return false; - } - - return true; + return !(string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase) + || string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase) + || string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase)); } - if (string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase) - || string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase) - || string.Equals(name, "MusicBrainz", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - - return false; + return string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase) + || string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase) + || string.Equals(name, "MusicBrainz", StringComparison.OrdinalIgnoreCase); } var metadataOptions = ServerConfigurationManager.Configuration.MetadataOptions @@ -422,27 +412,17 @@ namespace MediaBrowser.Api.Library { if (string.Equals(name, "TheMovieDb", StringComparison.OrdinalIgnoreCase)) { - if (string.Equals(type, "Series", StringComparison.OrdinalIgnoreCase) - || string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase) - || string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase) - || string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase)) - { - return false; - } - - return true; + return !string.Equals(type, "Series", StringComparison.OrdinalIgnoreCase) + && !string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase) + && !string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase) + && !string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase); } - if (string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase) - || string.Equals(name, "Screen Grabber", StringComparison.OrdinalIgnoreCase) - || string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase) - || string.Equals(name, "Emby Designs", StringComparison.OrdinalIgnoreCase) - || string.Equals(name, "Image Extractor", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - - return false; + return string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase) + || string.Equals(name, "Screen Grabber", StringComparison.OrdinalIgnoreCase) + || string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase) + || string.Equals(name, "Emby Designs", StringComparison.OrdinalIgnoreCase) + || string.Equals(name, "Image Extractor", StringComparison.OrdinalIgnoreCase); } var metadataOptions = ServerConfigurationManager.Configuration.MetadataOptions @@ -1034,12 +1014,23 @@ namespace MediaBrowser.Api.Library throw new ResourceNotFoundException("Item not found."); } - IEnumerable themeItems = item.GetThemeSongs(); + IEnumerable themeItems; - while (!themeItems.Any() && request.InheritFromParent && item.GetParent() != null) + while (true) { - item = item.GetParent(); themeItems = item.GetThemeSongs(); + + if (themeItems.Any() || !request.InheritFromParent) + { + break; + } + + var parent = item.GetParent(); + if (parent == null) + { + break; + } + item = parent; } var dtoOptions = GetDtoOptions(_authContext, request); @@ -1080,12 +1071,23 @@ namespace MediaBrowser.Api.Library throw new ResourceNotFoundException("Item not found."); } - IEnumerable themeItems = item.GetThemeVideos(); + IEnumerable themeItems; - while (!themeItems.Any() && request.InheritFromParent && item.GetParent() != null) + while (true) { - item = item.GetParent(); themeItems = item.GetThemeVideos(); + + if (themeItems.Any() || !request.InheritFromParent) + { + break; + } + + var parent = item.GetParent(); + if (parent == null) + { + break; + } + item = parent; } var dtoOptions = GetDtoOptions(_authContext, request); diff --git a/MediaBrowser.Api/SearchService.cs b/MediaBrowser.Api/SearchService.cs index 15148d1c72..e9d339c6e3 100644 --- a/MediaBrowser.Api/SearchService.cs +++ b/MediaBrowser.Api/SearchService.cs @@ -310,7 +310,7 @@ namespace MediaBrowser.Api private void SetBackdropImageInfo(SearchHint hint, BaseItem item) { var itemWithImage = (item.HasImage(ImageType.Backdrop) ? item : null) - ?? GetParentWithImage(item, ImageType.Backdrop); + ?? GetParentWithImage(item, ImageType.Backdrop); if (itemWithImage != null) { diff --git a/MediaBrowser.Api/System/SystemService.cs b/MediaBrowser.Api/System/SystemService.cs index cfede6f693..c57cc93d55 100644 --- a/MediaBrowser.Api/System/SystemService.cs +++ b/MediaBrowser.Api/System/SystemService.cs @@ -168,8 +168,9 @@ namespace MediaBrowser.Api.System .First(i => string.Equals(i.Name, request.Name, StringComparison.OrdinalIgnoreCase)); // For older files, assume fully static - return ResultFactory.GetStaticFileResult(Request, file.FullName, - file.LastWriteTimeUtc < DateTime.UtcNow.AddHours(-1) ? FileShare.Read : FileShare.ReadWrite); + var fileShare = file.LastWriteTimeUtc < DateTime.UtcNow.AddHours(-1) ? FileShare.Read : FileShare.ReadWrite; + + return ResultFactory.GetStaticFileResult(Request, file.FullName, fileShare); } /// diff --git a/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs b/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs index eb2f5996ea..f9f66f135a 100644 --- a/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs +++ b/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs @@ -425,7 +425,7 @@ namespace MediaBrowser.Api.UserLibrary var val = ImageTypes; return string.IsNullOrEmpty(val) - ? new ImageType[] { } + ? Array.Empty() : val.Split(',').Select(v => Enum.Parse(v, true)).ToArray(); } From 555651aae23e788b10760d58840114d8a010da90 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Mon, 6 Apr 2020 23:17:49 -0400 Subject: [PATCH 11/11] Fixed indentation and corrected typo --- MediaBrowser.Api/Library/LibraryService.cs | 10 +++++----- MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/MediaBrowser.Api/Library/LibraryService.cs b/MediaBrowser.Api/Library/LibraryService.cs index 26be9db832..a54640b2fd 100644 --- a/MediaBrowser.Api/Library/LibraryService.cs +++ b/MediaBrowser.Api/Library/LibraryService.cs @@ -389,13 +389,13 @@ namespace MediaBrowser.Api.Library if (string.Equals(name, "TheMovieDb", StringComparison.OrdinalIgnoreCase)) { return !(string.Equals(type, "Season", StringComparison.OrdinalIgnoreCase) - || string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase) - || string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase)); + || string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase) + || string.Equals(type, "MusicVideo", StringComparison.OrdinalIgnoreCase)); } return string.Equals(name, "TheTVDB", StringComparison.OrdinalIgnoreCase) - || string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase) - || string.Equals(name, "MusicBrainz", StringComparison.OrdinalIgnoreCase); + || string.Equals(name, "TheAudioDB", StringComparison.OrdinalIgnoreCase) + || string.Equals(name, "MusicBrainz", StringComparison.OrdinalIgnoreCase); } var metadataOptions = ServerConfigurationManager.Configuration.MetadataOptions @@ -403,7 +403,7 @@ namespace MediaBrowser.Api.Library .ToArray(); return metadataOptions.Length == 0 - || metadataOptions.Any(i => !i.DisabledMetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase)); + || metadataOptions.Any(i => !i.DisabledMetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase)); } private bool IsImageFetcherEnabledByDefault(string name, string type, bool isNewLibrary) diff --git a/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs b/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs index f9f66f135a..7561b5c892 100644 --- a/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs +++ b/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs @@ -412,8 +412,8 @@ namespace MediaBrowser.Api.UserLibrary return string.IsNullOrEmpty(val) ? Array.Empty() - : val.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries). - Select(v => Enum.Parse(v, true)).ToArray(); + : val.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) + .Select(v => Enum.Parse(v, true)).ToArray(); } ///