From 5dc3874ebdeac26d7be885b9a44ca1321b4b25cf Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 20 Dec 2019 21:30:51 +0100 Subject: [PATCH 01/23] Enable nullable reference types for Emby.Photos and Emby.Notifications * Enable TreatWarningsAsErrors for Emby.Notifications * Add analyzers to Emby.Notifications --- .../Api/NotificationsService.cs | 115 ++--------------- Emby.Notifications/CoreNotificationTypes.cs | 4 +- Emby.Notifications/Emby.Notifications.csproj | 14 ++ .../NotificationConfigurationFactory.cs | 5 +- ...fications.cs => NotificationEntryPoint.cs} | 121 +++++++++++------- Emby.Notifications/NotificationManager.cs | 37 ++++-- Emby.Photos/Emby.Photos.csproj | 1 + 7 files changed, 138 insertions(+), 159 deletions(-) rename Emby.Notifications/{Notifications.cs => NotificationEntryPoint.cs} (69%) diff --git a/Emby.Notifications/Api/NotificationsService.cs b/Emby.Notifications/Api/NotificationsService.cs index 83845558ad..5591809712 100644 --- a/Emby.Notifications/Api/NotificationsService.cs +++ b/Emby.Notifications/Api/NotificationsService.cs @@ -1,3 +1,8 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1402 +#pragma warning disable SA1600 +#pragma warning disable SA1649 + using System; using System.Collections.Generic; using System.Linq; @@ -12,60 +17,6 @@ using MediaBrowser.Model.Services; namespace Emby.Notifications.Api { - [Route("/Notifications/{UserId}", "GET", Summary = "Gets notifications")] - public class GetNotifications : IReturn - { - [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] - public string UserId { get; set; } - - [ApiMember(Name = "IsRead", Description = "An optional filter by IsRead", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")] - public bool? IsRead { get; set; } - - [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")] - public int? StartIndex { get; set; } - - [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")] - public int? Limit { get; set; } - } - - public class Notification - { - public string Id { get; set; } - - public string UserId { get; set; } - - public DateTime Date { get; set; } - - public bool IsRead { get; set; } - - public string Name { get; set; } - - public string Description { get; set; } - - public string Url { get; set; } - - public NotificationLevel Level { get; set; } - } - - public class NotificationResult - { - public Notification[] Notifications { get; set; } - public int TotalRecordCount { get; set; } - } - - public class NotificationsSummary - { - public int UnreadCount { get; set; } - public NotificationLevel MaxUnreadNotificationLevel { get; set; } - } - - [Route("/Notifications/{UserId}/Summary", "GET", Summary = "Gets a notification summary for a user")] - public class GetNotificationsSummary : IReturn - { - [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] - public string UserId { get; set; } - } - [Route("/Notifications/Types", "GET", Summary = "Gets notification types")] public class GetNotificationTypes : IReturn> { @@ -80,41 +31,21 @@ namespace Emby.Notifications.Api public class AddAdminNotification : IReturnVoid { [ApiMember(Name = "Name", Description = "The notification's name", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")] - public string Name { get; set; } + public string Name { get; set; } = string.Empty; [ApiMember(Name = "Description", Description = "The notification's description", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")] - public string Description { get; set; } + public string Description { get; set; } = string.Empty; [ApiMember(Name = "ImageUrl", Description = "The notification's image url", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")] - public string ImageUrl { get; set; } + public string? ImageUrl { get; set; } [ApiMember(Name = "Url", Description = "The notification's info url", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")] - public string Url { get; set; } + public string? Url { get; set; } [ApiMember(Name = "Level", Description = "The notification level", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")] public NotificationLevel Level { get; set; } } - [Route("/Notifications/{UserId}/Read", "POST", Summary = "Marks notifications as read")] - public class MarkRead : IReturnVoid - { - [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] - public string UserId { get; set; } - - [ApiMember(Name = "Ids", Description = "A list of notification ids, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)] - public string Ids { get; set; } - } - - [Route("/Notifications/{UserId}/Unread", "POST", Summary = "Marks notifications as unread")] - public class MarkUnread : IReturnVoid - { - [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] - public string UserId { get; set; } - - [ApiMember(Name = "Ids", Description = "A list of notification ids, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)] - public string Ids { get; set; } - } - [Authenticated] public class NotificationsService : IService { @@ -129,30 +60,19 @@ namespace Emby.Notifications.Api public object Get(GetNotificationTypes request) { + _ = request; // Silence unused variable warning return _notificationManager.GetNotificationTypes(); } public object Get(GetNotificationServices request) { + _ = request; // Silence unused variable warning return _notificationManager.GetNotificationServices().ToList(); } - public object Get(GetNotificationsSummary request) - { - return new NotificationsSummary - { - - }; - } - public Task Post(AddAdminNotification request) { // This endpoint really just exists as post of a real with sickbeard - return AddNotification(request); - } - - private Task AddNotification(AddAdminNotification request) - { var notification = new NotificationRequest { Date = DateTime.UtcNow, @@ -165,18 +85,5 @@ namespace Emby.Notifications.Api return _notificationManager.SendNotification(notification, CancellationToken.None); } - - public void Post(MarkRead request) - { - } - - public void Post(MarkUnread request) - { - } - - public object Get(GetNotifications request) - { - return new NotificationResult(); - } } } diff --git a/Emby.Notifications/CoreNotificationTypes.cs b/Emby.Notifications/CoreNotificationTypes.cs index 0f9fc08d99..73e0b0256a 100644 --- a/Emby.Notifications/CoreNotificationTypes.cs +++ b/Emby.Notifications/CoreNotificationTypes.cs @@ -1,7 +1,9 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.Linq; -using MediaBrowser.Controller; using MediaBrowser.Controller.Notifications; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.Notifications; diff --git a/Emby.Notifications/Emby.Notifications.csproj b/Emby.Notifications/Emby.Notifications.csproj index 004ded77b1..e6bf785bff 100644 --- a/Emby.Notifications/Emby.Notifications.csproj +++ b/Emby.Notifications/Emby.Notifications.csproj @@ -4,6 +4,8 @@ netstandard2.1 false true + true + enable @@ -16,4 +18,16 @@ + + + + + + + + + + ../jellyfin.ruleset + + diff --git a/Emby.Notifications/NotificationConfigurationFactory.cs b/Emby.Notifications/NotificationConfigurationFactory.cs index d08475f7d2..b168ed221b 100644 --- a/Emby.Notifications/NotificationConfigurationFactory.cs +++ b/Emby.Notifications/NotificationConfigurationFactory.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Collections.Generic; using MediaBrowser.Common.Configuration; using MediaBrowser.Model.Notifications; @@ -13,7 +16,7 @@ namespace Emby.Notifications new ConfigurationStore { Key = "notifications", - ConfigurationType = typeof (NotificationOptions) + ConfigurationType = typeof(NotificationOptions) } }; } diff --git a/Emby.Notifications/Notifications.cs b/Emby.Notifications/NotificationEntryPoint.cs similarity index 69% rename from Emby.Notifications/Notifications.cs rename to Emby.Notifications/NotificationEntryPoint.cs index 7aa1e7ae89..ab92822fa2 100644 --- a/Emby.Notifications/Notifications.cs +++ b/Emby.Notifications/NotificationEntryPoint.cs @@ -21,70 +21,85 @@ using Microsoft.Extensions.Logging; namespace Emby.Notifications { /// - /// Creates notifications for various system events + /// Creates notifications for various system events. /// - public class Notifications : IServerEntryPoint + public class NotificationEntryPoint : IServerEntryPoint { private readonly ILogger _logger; - + private readonly IActivityManager _activityManager; + private readonly ILocalizationManager _localization; private readonly INotificationManager _notificationManager; - private readonly ILibraryManager _libraryManager; private readonly IServerApplicationHost _appHost; - - private Timer LibraryUpdateTimer { get; set; } - private readonly object _libraryChangedSyncLock = new object(); - private readonly IConfigurationManager _config; - private readonly ILocalizationManager _localization; - private readonly IActivityManager _activityManager; + + private readonly object _libraryChangedSyncLock = new object(); + private readonly List _itemsAdded = new List(); + + private Timer? _libraryUpdateTimer; private string[] _coreNotificationTypes; - public Notifications( + private bool _disposed = false; + + /// + /// Initializes a new instance of the class. + /// + /// The logger. + /// The activity manager. + /// The localization manager. + /// The notification manager. + /// The library manager. + /// The application host. + /// The configuration manager. + public NotificationEntryPoint( + ILogger logger, IActivityManager activityManager, ILocalizationManager localization, - ILogger logger, INotificationManager notificationManager, ILibraryManager libraryManager, IServerApplicationHost appHost, IConfigurationManager config) { _logger = logger; + _activityManager = activityManager; + _localization = localization; _notificationManager = notificationManager; _libraryManager = libraryManager; _appHost = appHost; _config = config; - _localization = localization; - _activityManager = activityManager; _coreNotificationTypes = new CoreNotificationTypes(localization).GetNotificationTypes().Select(i => i.Type).ToArray(); } + /// public Task RunAsync() { - _libraryManager.ItemAdded += _libraryManager_ItemAdded; - _appHost.HasPendingRestartChanged += _appHost_HasPendingRestartChanged; - _appHost.HasUpdateAvailableChanged += _appHost_HasUpdateAvailableChanged; - _activityManager.EntryCreated += _activityManager_EntryCreated; + _libraryManager.ItemAdded += OnLibraryManagerItemAdded; + _appHost.HasPendingRestartChanged += OnAppHostHasPendingRestartChanged; + _appHost.HasUpdateAvailableChanged += OnAppHostHasUpdateAvailableChanged; + _activityManager.EntryCreated += OnActivityManagerEntryCreated; return Task.CompletedTask; } - private async void _appHost_HasPendingRestartChanged(object sender, EventArgs e) + private async void OnAppHostHasPendingRestartChanged(object sender, EventArgs e) { var type = NotificationType.ServerRestartRequired.ToString(); var notification = new NotificationRequest { NotificationType = type, - Name = string.Format(_localization.GetLocalizedString("ServerNameNeedsToBeRestarted"), _appHost.Name) + Name = string.Format( + CultureInfo.InvariantCulture, + _localization.GetLocalizedString("ServerNameNeedsToBeRestarted"), + _appHost.Name) }; await SendNotification(notification, null).ConfigureAwait(false); } - private async void _activityManager_EntryCreated(object sender, GenericEventArgs e) + private async void OnActivityManagerEntryCreated(object sender, GenericEventArgs e) { var entry = e.Argument; @@ -117,7 +132,7 @@ namespace Emby.Notifications return _config.GetConfiguration("notifications"); } - private async void _appHost_HasUpdateAvailableChanged(object sender, EventArgs e) + private async void OnAppHostHasUpdateAvailableChanged(object sender, EventArgs e) { if (!_appHost.HasUpdateAvailable) { @@ -136,8 +151,7 @@ namespace Emby.Notifications await SendNotification(notification, null).ConfigureAwait(false); } - private readonly List _itemsAdded = new List(); - private void _libraryManager_ItemAdded(object sender, ItemChangeEventArgs e) + private void OnLibraryManagerItemAdded(object sender, ItemChangeEventArgs e) { if (!FilterItem(e.Item)) { @@ -146,14 +160,17 @@ namespace Emby.Notifications lock (_libraryChangedSyncLock) { - if (LibraryUpdateTimer == null) + if (_libraryUpdateTimer == null) { - LibraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, 5000, - Timeout.Infinite); + _libraryUpdateTimer = new Timer( + LibraryUpdateTimerCallback, + null, + 5000, + Timeout.Infinite); } else { - LibraryUpdateTimer.Change(5000, Timeout.Infinite); + _libraryUpdateTimer.Change(5000, Timeout.Infinite); } _itemsAdded.Add(e.Item); @@ -188,7 +205,8 @@ namespace Emby.Notifications { items = _itemsAdded.ToList(); _itemsAdded.Clear(); - DisposeLibraryUpdateTimer(); + _libraryUpdateTimer!.Dispose(); // Shouldn't be null as it just set off this callback + _libraryUpdateTimer = null; } items = items.Take(10).ToList(); @@ -198,7 +216,10 @@ namespace Emby.Notifications var notification = new NotificationRequest { NotificationType = NotificationType.NewLibraryContent.ToString(), - Name = string.Format(_localization.GetLocalizedString("ValueHasBeenAddedToLibrary"), GetItemName(item)), + Name = string.Format( + CultureInfo.InvariantCulture, + _localization.GetLocalizedString("ValueHasBeenAddedToLibrary"), + GetItemName(item)), Description = item.Overview }; @@ -206,7 +227,7 @@ namespace Emby.Notifications } } - public static string GetItemName(BaseItem item) + private static string GetItemName(BaseItem item) { var name = item.Name; if (item is Episode episode) @@ -219,6 +240,7 @@ namespace Emby.Notifications episode.IndexNumber.Value, name); } + if (episode.ParentIndexNumber.HasValue) { name = string.Format( @@ -229,7 +251,6 @@ namespace Emby.Notifications } } - if (item is IHasSeries hasSeries) { name = hasSeries.SeriesName + " - " + name; @@ -257,7 +278,7 @@ namespace Emby.Notifications return name; } - private async Task SendNotification(NotificationRequest notification, BaseItem relatedItem) + private async Task SendNotification(NotificationRequest notification, BaseItem? relatedItem) { try { @@ -269,23 +290,37 @@ namespace Emby.Notifications } } + /// public void Dispose() { - DisposeLibraryUpdateTimer(); - - _libraryManager.ItemAdded -= _libraryManager_ItemAdded; - _appHost.HasPendingRestartChanged -= _appHost_HasPendingRestartChanged; - _appHost.HasUpdateAvailableChanged -= _appHost_HasUpdateAvailableChanged; - _activityManager.EntryCreated -= _activityManager_EntryCreated; + Dispose(true); + GC.SuppressFinalize(this); } - private void DisposeLibraryUpdateTimer() + /// + /// Releases unmanaged and - optionally - managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected virtual void Dispose(bool disposing) { - if (LibraryUpdateTimer != null) + if (_disposed) { - LibraryUpdateTimer.Dispose(); - LibraryUpdateTimer = null; + return; } + + if (disposing) + { + _libraryUpdateTimer?.Dispose(); + } + + _libraryUpdateTimer = null; + + _libraryManager.ItemAdded -= OnLibraryManagerItemAdded; + _appHost.HasPendingRestartChanged -= OnAppHostHasPendingRestartChanged; + _appHost.HasUpdateAvailableChanged -= OnAppHostHasUpdateAvailableChanged; + _activityManager.EntryCreated -= OnActivityManagerEntryCreated; + + _disposed = true; } } } diff --git a/Emby.Notifications/NotificationManager.cs b/Emby.Notifications/NotificationManager.cs index eecbbea071..836aa3e729 100644 --- a/Emby.Notifications/NotificationManager.cs +++ b/Emby.Notifications/NotificationManager.cs @@ -16,20 +16,32 @@ using Microsoft.Extensions.Logging; namespace Emby.Notifications { + /// + /// NotificationManager class. + /// public class NotificationManager : INotificationManager { private readonly ILogger _logger; private readonly IUserManager _userManager; private readonly IServerConfigurationManager _config; - private INotificationService[] _services; - private INotificationTypeFactory[] _typeFactories; + private INotificationService[] _services = Array.Empty(); + private INotificationTypeFactory[] _typeFactories = Array.Empty(); - public NotificationManager(ILoggerFactory loggerFactory, IUserManager userManager, IServerConfigurationManager config) + /// + /// Initializes a new instance of the class. + /// + /// The logger. + /// the user manager. + /// The server configuration manager. + public NotificationManager( + ILogger logger, + IUserManager userManager, + IServerConfigurationManager config) { + _logger = logger; _userManager = userManager; _config = config; - _logger = loggerFactory.CreateLogger(GetType().Name); } private NotificationOptions GetConfiguration() @@ -37,12 +49,14 @@ namespace Emby.Notifications return _config.GetConfiguration("notifications"); } + /// public Task SendNotification(NotificationRequest request, CancellationToken cancellationToken) { return SendNotification(request, null, cancellationToken); } - public Task SendNotification(NotificationRequest request, BaseItem relatedItem, CancellationToken cancellationToken) + /// + public Task SendNotification(NotificationRequest request, BaseItem? relatedItem, CancellationToken cancellationToken) { var notificationType = request.NotificationType; @@ -64,7 +78,8 @@ namespace Emby.Notifications return Task.WhenAll(tasks); } - private Task SendNotification(NotificationRequest request, + private Task SendNotification( + NotificationRequest request, INotificationService service, IEnumerable users, string title, @@ -79,7 +94,7 @@ namespace Emby.Notifications return Task.WhenAll(tasks); } - private IEnumerable GetUserIds(NotificationRequest request, NotificationOption options) + private IEnumerable GetUserIds(NotificationRequest request, NotificationOption? options) { if (request.SendToUserMode.HasValue) { @@ -109,7 +124,8 @@ namespace Emby.Notifications return request.UserIds; } - private async Task SendNotification(NotificationRequest request, + private async Task SendNotification( + NotificationRequest request, INotificationService service, string title, string description, @@ -161,12 +177,14 @@ namespace Emby.Notifications return GetConfiguration().IsServiceEnabled(service.Name, notificationType); } + /// public void AddParts(IEnumerable services, IEnumerable notificationTypeFactories) { _services = services.ToArray(); _typeFactories = notificationTypeFactories.ToArray(); } + /// public List GetNotificationTypes() { var list = _typeFactories.Select(i => @@ -180,7 +198,6 @@ namespace Emby.Notifications _logger.LogError(ex, "Error in GetNotificationTypes"); return new List(); } - }).SelectMany(i => i).ToList(); var config = GetConfiguration(); @@ -193,13 +210,13 @@ namespace Emby.Notifications return list; } + /// public IEnumerable GetNotificationServices() { return _services.Select(i => new NameIdPair { Name = i.Name, Id = i.Name.GetMD5().ToString("N", CultureInfo.InvariantCulture) - }).OrderBy(i => i.Name); } } diff --git a/Emby.Photos/Emby.Photos.csproj b/Emby.Photos/Emby.Photos.csproj index 64692c3703..8fd18466a1 100644 --- a/Emby.Photos/Emby.Photos.csproj +++ b/Emby.Photos/Emby.Photos.csproj @@ -18,6 +18,7 @@ false true true + enable From c601def4847cb0ada323a9da8d152c8c8d7b834b Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 17 Jan 2020 00:19:58 +0100 Subject: [PATCH 02/23] Fix warnings in SessionManager --- .../ApplicationHost.cs | 13 +- .../Session/SessionManager.cs | 274 +++++++++--------- 2 files changed, 156 insertions(+), 131 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 0bb1d832fb..e93337c2fc 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -808,7 +808,18 @@ namespace Emby.Server.Implementations ChannelManager = new ChannelManager(UserManager, DtoService, LibraryManager, LoggerFactory, ServerConfigurationManager, FileSystemManager, UserDataManager, JsonSerializer, ProviderManager); serviceCollection.AddSingleton(ChannelManager); - SessionManager = new SessionManager(UserDataManager, LoggerFactory, LibraryManager, UserManager, musicManager, DtoService, ImageProcessor, this, AuthenticationRepository, DeviceManager, MediaSourceManager); + SessionManager = new SessionManager( + LoggerFactory.CreateLogger(), + UserDataManager, + LibraryManager, + UserManager, + musicManager, + DtoService, + ImageProcessor, + this, + AuthenticationRepository, + DeviceManager, + MediaSourceManager); serviceCollection.AddSingleton(SessionManager); serviceCollection.AddSingleton( diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index b1d513dd4f..bb0836614e 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -30,17 +30,17 @@ using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Session { /// - /// Class SessionManager + /// Class SessionManager. /// public class SessionManager : ISessionManager, IDisposable { /// - /// The _user data repository + /// The _user data repository. /// private readonly IUserDataManager _userDataManager; /// - /// The _logger + /// The _logger. /// private readonly ILogger _logger; @@ -57,36 +57,19 @@ namespace Emby.Server.Implementations.Session private readonly IDeviceManager _deviceManager; /// - /// The _active connections + /// The _active connections. /// private readonly ConcurrentDictionary _activeConnections = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - public event EventHandler> AuthenticationFailed; + private Timer _idleTimer; - public event EventHandler> AuthenticationSucceeded; - - /// - /// Occurs when [playback start]. - /// - public event EventHandler PlaybackStart; - /// - /// Occurs when [playback progress]. - /// - public event EventHandler PlaybackProgress; - /// - /// Occurs when [playback stopped]. - /// - public event EventHandler PlaybackStopped; - - public event EventHandler SessionStarted; - public event EventHandler CapabilitiesChanged; - public event EventHandler SessionEnded; - public event EventHandler SessionActivity; + private DtoOptions _itemInfoDtoOptions; + private bool _disposed = false; public SessionManager( + ILogger logger, IUserDataManager userDataManager, - ILoggerFactory loggerFactory, ILibraryManager libraryManager, IUserManager userManager, IMusicManager musicManager, @@ -97,8 +80,8 @@ namespace Emby.Server.Implementations.Session IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager) { + _logger = logger; _userDataManager = userDataManager; - _logger = loggerFactory.CreateLogger(nameof(SessionManager)); _libraryManager = libraryManager; _userManager = userManager; _musicManager = musicManager; @@ -108,9 +91,49 @@ namespace Emby.Server.Implementations.Session _authRepo = authRepo; _deviceManager = deviceManager; _mediaSourceManager = mediaSourceManager; + _deviceManager.DeviceOptionsUpdated += OnDeviceManagerDeviceOptionsUpdated; } + /// + public event EventHandler> AuthenticationFailed; + + /// + public event EventHandler> AuthenticationSucceeded; + + /// + /// Occurs when [playback start]. + /// + public event EventHandler PlaybackStart; + + /// + /// Occurs when [playback progress]. + /// + public event EventHandler PlaybackProgress; + + /// + /// Occurs when [playback stopped]. + /// + public event EventHandler PlaybackStopped; + + /// + public event EventHandler SessionStarted; + + /// + public event EventHandler CapabilitiesChanged; + + /// + public event EventHandler SessionEnded; + + /// + public event EventHandler SessionActivity; + + /// + /// Gets all connections. + /// + /// All connections. + public IEnumerable Sessions => _activeConnections.Values.OrderByDescending(c => c.LastActivityDate); + private void OnDeviceManagerDeviceOptionsUpdated(object sender, GenericEventArgs> e) { foreach (var session in Sessions) @@ -130,14 +153,17 @@ namespace Emby.Server.Implementations.Session } } - private bool _disposed = false; - + /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } + /// + /// Releases unmanaged and - optionally - managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. protected virtual void Dispose(bool disposing) { if (_disposed) @@ -147,15 +173,17 @@ namespace Emby.Server.Implementations.Session if (disposing) { - // TODO: dispose stuff + _idleTimer?.Dispose(); } + _idleTimer = null; + _deviceManager.DeviceOptionsUpdated -= OnDeviceManagerDeviceOptionsUpdated; _disposed = true; } - public void CheckDisposed() + private void CheckDisposed() { if (_disposed) { @@ -163,12 +191,6 @@ namespace Emby.Server.Implementations.Session } } - /// - /// Gets all connections. - /// - /// All connections. - public IEnumerable Sessions => _activeConnections.Values.OrderByDescending(c => c.LastActivityDate); - private void OnSessionStarted(SessionInfo info) { if (!string.IsNullOrEmpty(info.DeviceId)) @@ -199,13 +221,13 @@ namespace Emby.Server.Implementations.Session new SessionEventArgs { SessionInfo = info - }, _logger); info.Dispose(); } + /// public void UpdateDeviceName(string sessionId, string deviceName) { var session = GetSession(sessionId); @@ -225,7 +247,6 @@ namespace Emby.Server.Implementations.Session /// The remote end point. /// The user. /// SessionInfo. - /// user public SessionInfo LogSessionActivity( string appName, string appVersion, @@ -263,14 +284,7 @@ namespace Emby.Server.Implementations.Session if ((activityDate - userLastActivityDate).TotalSeconds > 60) { - try - { - _userManager.UpdateUser(user); - } - catch (Exception ex) - { - _logger.LogError("Error updating user", ex); - } + _userManager.UpdateUser(user); } } @@ -287,18 +301,20 @@ namespace Emby.Server.Implementations.Session return session; } + /// public void CloseIfNeeded(SessionInfo session) { if (!session.SessionControllers.Any(i => i.IsSessionActive)) { var key = GetSessionKey(session.Client, session.DeviceId); - _activeConnections.TryRemove(key, out var removed); + _activeConnections.TryRemove(key, out _); OnSessionEnded(session); } } + /// public void ReportSessionEnded(string sessionId) { CheckDisposed(); @@ -308,7 +324,7 @@ namespace Emby.Server.Implementations.Session { var key = GetSessionKey(session.Client, session.DeviceId); - _activeConnections.TryRemove(key, out var removed); + _activeConnections.TryRemove(key, out _); OnSessionEnded(session); } @@ -339,7 +355,7 @@ namespace Emby.Server.Implementations.Session var runtimeTicks = libraryItem.RunTimeTicks; MediaSourceInfo mediaSource = null; - if (libraryItem is IHasMediaSources hasMediaSources) + if (libraryItem is IHasMediaSources) { mediaSource = await GetMediaSource(libraryItem, info.MediaSourceId, info.LiveStreamId).ConfigureAwait(false); @@ -391,7 +407,6 @@ namespace Emby.Server.Implementations.Session /// Removes the now playing item id. /// /// The session. - /// item private void RemoveNowPlayingItem(SessionInfo session) { session.NowPlayingItem = null; @@ -404,9 +419,7 @@ namespace Emby.Server.Implementations.Session } private static string GetSessionKey(string appName, string deviceId) - { - return appName + deviceId; - } + => appName + deviceId; /// /// Gets the connection. @@ -426,6 +439,7 @@ namespace Emby.Server.Implementations.Session { throw new ArgumentNullException(nameof(deviceId)); } + var key = GetSessionKey(appName, deviceId); CheckDisposed(); @@ -498,7 +512,7 @@ namespace Emby.Server.Implementations.Session { var users = new List(); - if (!session.UserId.Equals(Guid.Empty)) + if (session.UserId != Guid.Empty) { var user = _userManager.GetUserById(session.UserId); @@ -517,8 +531,6 @@ namespace Emby.Server.Implementations.Session return users; } - private Timer _idleTimer; - private void StartIdleCheckTimer() { if (_idleTimer == null) @@ -594,11 +606,11 @@ namespace Emby.Server.Implementations.Session } /// - /// Used to report that playback has started for an item + /// Used to report that playback has started for an item. /// /// The info. /// Task. - /// info + /// info is null. public async Task OnPlaybackStart(PlaybackStartInfo info) { CheckDisposed(); @@ -610,7 +622,7 @@ namespace Emby.Server.Implementations.Session var session = GetSession(info.SessionId); - var libraryItem = info.ItemId.Equals(Guid.Empty) + var libraryItem = info.ItemId == Guid.Empty ? null : GetNowPlayingItem(session, info.ItemId); @@ -648,7 +660,6 @@ namespace Emby.Server.Implementations.Session ClientName = session.Client, DeviceId = session.DeviceId, Session = session - }, _logger); @@ -679,13 +690,14 @@ namespace Emby.Server.Implementations.Session _userDataManager.SaveUserData(user, item, data, UserDataSaveReason.PlaybackStart, CancellationToken.None); } + /// public Task OnPlaybackProgress(PlaybackProgressInfo info) { return OnPlaybackProgress(info, false); } /// - /// Used to report playback progress for an item + /// Used to report playback progress for an item. /// /// Task. public async Task OnPlaybackProgress(PlaybackProgressInfo info, bool isAutomated) @@ -852,7 +864,7 @@ namespace Emby.Server.Implementations.Session { MediaSourceInfo mediaSource = null; - if (libraryItem is IHasMediaSources hasMediaSources) + if (libraryItem is IHasMediaSources) { mediaSource = await GetMediaSource(libraryItem, info.MediaSourceId, info.LiveStreamId).ConfigureAwait(false); } @@ -924,7 +936,6 @@ namespace Emby.Server.Implementations.Session ClientName = session.Client, DeviceId = session.DeviceId, Session = session - }, _logger); } @@ -962,13 +973,17 @@ namespace Emby.Server.Implementations.Session /// The session identifier. /// if set to true [throw on missing]. /// SessionInfo. - /// sessionId + /// + /// No session with an Id equal to sessionId was found + /// and throwOnMissing is true. + /// private SessionInfo GetSession(string sessionId, bool throwOnMissing = true) { var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId, StringComparison.Ordinal)); if (session == null && throwOnMissing) { - throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId)); + throw new ResourceNotFoundException( + string.Format(CultureInfo.InvariantCulture, "Session {0} not found.", sessionId)); } return session; @@ -981,12 +996,14 @@ namespace Emby.Server.Implementations.Session if (session == null) { - throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId)); + throw new ResourceNotFoundException( + string.Format(CultureInfo.InvariantCulture, "Session {0} not found.", sessionId)); } return session; } + /// public Task SendMessageCommand(string controllingSessionId, string sessionId, MessageCommand command, CancellationToken cancellationToken) { CheckDisposed(); @@ -1007,6 +1024,7 @@ namespace Emby.Server.Implementations.Session return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken); } + /// public Task SendGeneralCommand(string controllingSessionId, string sessionId, GeneralCommand command, CancellationToken cancellationToken) { CheckDisposed(); @@ -1051,6 +1069,7 @@ namespace Emby.Server.Implementations.Session return Task.WhenAll(GetTasks()); } + /// public async Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken) { CheckDisposed(); @@ -1092,7 +1111,8 @@ namespace Emby.Server.Implementations.Session { if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full)) { - throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name)); + throw new ArgumentException( + string.Format(CultureInfo.InvariantCulture, "{0} is not allowed to play media.", user.Name)); } } @@ -1200,6 +1220,7 @@ namespace Emby.Server.Implementations.Session return _musicManager.GetInstantMixFromItem(item, user, new DtoOptions(false) { EnableImages = false }); } + /// public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken) { var generalCommand = new GeneralCommand @@ -1216,6 +1237,7 @@ namespace Emby.Server.Implementations.Session return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken); } + /// public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken) { CheckDisposed(); @@ -1299,12 +1321,12 @@ namespace Emby.Server.Implementations.Session var session = GetSession(sessionId); - if (session.UserId.Equals(userId)) + if (session.UserId == userId) { throw new ArgumentException("The requested user is already the primary user of the session."); } - if (session.AdditionalUsers.All(i => !i.UserId.Equals(userId))) + if (session.AdditionalUsers.All(i => i.UserId != userId)) { var user = _userManager.GetUserById(userId); @@ -1430,19 +1452,19 @@ namespace Emby.Server.Implementations.Session private string GetAuthorizationToken(User user, string deviceId, string app, string appVersion, string deviceName) { - var existing = _authRepo.Get(new AuthenticationInfoQuery - { - DeviceId = deviceId, - UserId = user.Id, - Limit = 1 + var existing = _authRepo.Get( + new AuthenticationInfoQuery + { + DeviceId = deviceId, + UserId = user.Id, + Limit = 1 + }).Items.FirstOrDefault(); - }).Items.FirstOrDefault(); - - var allExistingForDevice = _authRepo.Get(new AuthenticationInfoQuery - { - DeviceId = deviceId - - }).Items; + var allExistingForDevice = _authRepo.Get( + new AuthenticationInfoQuery + { + DeviceId = deviceId + }).Items; foreach (var auth in allExistingForDevice) { @@ -1461,7 +1483,7 @@ namespace Emby.Server.Implementations.Session if (existing != null) { - _logger.LogInformation("Reissuing access token: " + existing.AccessToken); + _logger.LogInformation("Reissuing access token: {Token}", existing.AccessToken); return existing.AccessToken; } @@ -1486,6 +1508,7 @@ namespace Emby.Server.Implementations.Session return newToken.AccessToken; } + /// public void Logout(string accessToken) { CheckDisposed(); @@ -1495,19 +1518,20 @@ namespace Emby.Server.Implementations.Session throw new ArgumentNullException(nameof(accessToken)); } - var existing = _authRepo.Get(new AuthenticationInfoQuery - { - Limit = 1, - AccessToken = accessToken + var existing = _authRepo.Get( + new AuthenticationInfoQuery + { + Limit = 1, + AccessToken = accessToken + }).Items; - }).Items.FirstOrDefault(); - - if (existing != null) + if (existing.Count > 0) { - Logout(existing); + Logout(existing[0]); } } + /// public void Logout(AuthenticationInfo existing) { CheckDisposed(); @@ -1533,6 +1557,7 @@ namespace Emby.Server.Implementations.Session } } + /// public void RevokeUserTokens(Guid userId, string currentAccessToken) { CheckDisposed(); @@ -1551,6 +1576,7 @@ namespace Emby.Server.Implementations.Session } } + /// public void RevokeToken(string token) { Logout(token); @@ -1607,10 +1633,8 @@ namespace Emby.Server.Implementations.Session _deviceManager.SaveCapabilities(deviceId, capabilities); } - private DtoOptions _itemInfoDtoOptions; - /// - /// Converts a BaseItem to a BaseItemInfo + /// Converts a BaseItem to a BaseItemInfo. /// private BaseItemDto GetItemInfo(BaseItem item, MediaSourceInfo mediaSource) { @@ -1685,6 +1709,7 @@ namespace Emby.Server.Implementations.Session } } + /// public void ReportNowViewingItem(string sessionId, string itemId) { if (string.IsNullOrEmpty(itemId)) @@ -1692,23 +1717,26 @@ namespace Emby.Server.Implementations.Session throw new ArgumentNullException(nameof(itemId)); } - //var item = _libraryManager.GetItemById(new Guid(itemId)); + var item = _libraryManager.GetItemById(new Guid(itemId)); - //var info = GetItemInfo(item, null, null); + var info = GetItemInfo(item, null); - //ReportNowViewingItem(sessionId, info); + ReportNowViewingItem(sessionId, info); } + /// public void ReportNowViewingItem(string sessionId, BaseItemDto item) { - //var session = GetSession(sessionId); + throw new NotImplementedException(); - //session.NowViewingItem = item; + // var session = GetSession(sessionId); + // session.NowViewingItem = item; } + /// public void ReportTranscodingInfo(string deviceId, TranscodingInfo info) { - var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId)); + var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId, StringComparison.Ordinal)); if (session != null) { @@ -1716,17 +1744,18 @@ namespace Emby.Server.Implementations.Session } } + /// public void ClearTranscodingInfo(string deviceId) { ReportTranscodingInfo(deviceId, null); } + /// public SessionInfo GetSession(string deviceId, string client, string version) - { - return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) && - string.Equals(i.Client, client)); - } + => Sessions.FirstOrDefault( + i => string.Equals(i.DeviceId, deviceId, StringComparison.Ordinal) && string.Equals(i.Client, client, StringComparison.Ordinal)); + /// public SessionInfo GetSessionByAuthenticationToken(AuthenticationInfo info, string deviceId, string remoteEndpoint, string appVersion) { if (info == null) @@ -1759,23 +1788,24 @@ namespace Emby.Server.Implementations.Session return LogSessionActivity(appName, appVersion, deviceId, deviceName, remoteEndpoint, user); } + /// public SessionInfo GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint) { - var result = _authRepo.Get(new AuthenticationInfoQuery + var items = _authRepo.Get(new AuthenticationInfoQuery { - AccessToken = token - }); + AccessToken = token, + Limit = 1 + }).Items; - var info = result.Items.FirstOrDefault(); - - if (info == null) + if (items.Count == 0) { return null; } - return GetSessionByAuthenticationToken(info, deviceId, remoteEndpoint, null); + return GetSessionByAuthenticationToken(items[0], deviceId, remoteEndpoint, null); } + /// public Task SendMessageToAdminSessions(string name, T data, CancellationToken cancellationToken) { CheckDisposed(); @@ -1785,6 +1815,7 @@ namespace Emby.Server.Implementations.Session return SendMessageToUserSessions(adminUserIds, name, data, cancellationToken); } + /// public Task SendMessageToUserSessions(List userIds, string name, Func dataFn, CancellationToken cancellationToken) { CheckDisposed(); @@ -1796,11 +1827,10 @@ namespace Emby.Server.Implementations.Session return Task.CompletedTask; } - var data = dataFn(); - - return SendMessageToSessions(sessions, name, data, cancellationToken); + return SendMessageToSessions(sessions, name, dataFn(), cancellationToken); } + /// public Task SendMessageToUserSessions(List userIds, string name, T data, CancellationToken cancellationToken) { CheckDisposed(); @@ -1809,6 +1839,7 @@ namespace Emby.Server.Implementations.Session return SendMessageToSessions(sessions, name, data, cancellationToken); } + /// public Task SendMessageToUserDeviceSessions(string deviceId, string name, T data, CancellationToken cancellationToken) { CheckDisposed(); @@ -1817,22 +1848,5 @@ namespace Emby.Server.Implementations.Session return SendMessageToSessions(sessions, name, data, cancellationToken); } - - public Task SendMessageToUserDeviceAndAdminSessions(string deviceId, string name, T data, CancellationToken cancellationToken) - { - CheckDisposed(); - - var sessions = Sessions - .Where(i => string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase) || IsAdminSession(i)); - - return SendMessageToSessions(sessions, name, data, cancellationToken); - } - - private bool IsAdminSession(SessionInfo s) - { - var user = _userManager.GetUserById(s.UserId); - - return user != null && user.Policy.IsAdministrator; - } } } From ddf9b38799fa4a0e227ae3c2516a72ec48f13854 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 21 Jan 2020 20:26:30 +0100 Subject: [PATCH 03/23] Simplify image processing by removing image enhancers --- Emby.Drawing/Emby.Drawing.csproj | 12 + Emby.Drawing/ImageProcessor.cs | 353 ++---------------- .../ApplicationHost.cs | 2 - Emby.Server.Implementations/Dto/DtoService.cs | 51 +-- Jellyfin.Drawing.Skia/SkiaEncoder.cs | 20 +- Jellyfin.Server/Program.cs | 11 +- MediaBrowser.Api/Images/ImageService.cs | 26 +- .../Drawing/IImageProcessor.cs | 35 -- .../Drawing/ImageHelper.cs | 2 - .../Drawing/ImageProcessingOptions.cs | 3 - .../MediaEncoding/EncodingJobInfo.cs | 12 +- .../Providers/IImageEnhancer.cs | 61 --- MediaBrowser.Model/Drawing/ImageDimensions.cs | 37 +- 13 files changed, 103 insertions(+), 522 deletions(-) delete mode 100644 MediaBrowser.Controller/Providers/IImageEnhancer.cs diff --git a/Emby.Drawing/Emby.Drawing.csproj b/Emby.Drawing/Emby.Drawing.csproj index 85cecdc44e..b7090b2629 100644 --- a/Emby.Drawing/Emby.Drawing.csproj +++ b/Emby.Drawing/Emby.Drawing.csproj @@ -17,4 +17,16 @@ + + + + + + + + + + ../jellyfin.ruleset + + diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs index ce8089e59c..8f68509364 100644 --- a/Emby.Drawing/ImageProcessor.cs +++ b/Emby.Drawing/ImageProcessor.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; -using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller; @@ -11,10 +10,8 @@ using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; -using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; using MediaBrowser.Model.Net; using Microsoft.Extensions.Logging; @@ -24,7 +21,7 @@ namespace Emby.Drawing /// /// Class ImageProcessor. /// - public class ImageProcessor : IImageProcessor, IDisposable + public sealed class ImageProcessor : IImageProcessor, IDisposable { // Increment this when there's a change requiring caches to be invalidated private const string Version = "3"; @@ -32,28 +29,24 @@ namespace Emby.Drawing private static readonly HashSet _transparentImageTypes = new HashSet(StringComparer.OrdinalIgnoreCase) { ".png", ".webp", ".gif" }; - /// - /// The _logger - /// private readonly ILogger _logger; private readonly IFileSystem _fileSystem; private readonly IServerApplicationPaths _appPaths; - private IImageEncoder _imageEncoder; + private readonly IImageEncoder _imageEncoder; private readonly Func _libraryManager; private readonly Func _mediaEncoder; - private readonly Dictionary _locks = new Dictionary(); private bool _disposed = false; /// - /// + /// Initializes a new instance of the class. /// - /// - /// - /// - /// - /// - /// + /// The logger. + /// The server application paths. + /// The filesystem. + /// The image encoder. + /// The library manager. + /// The media encoder. public ImageProcessor( ILogger logger, IServerApplicationPaths appPaths, @@ -68,16 +61,10 @@ namespace Emby.Drawing _libraryManager = libraryManager; _mediaEncoder = mediaEncoder; _appPaths = appPaths; - - ImageEnhancers = Array.Empty(); - - ImageHelper.ImageProcessor = this; } private string ResizedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "resized-images"); - private string EnhancedImageCachePath => Path.Combine(_appPaths.ImageCachePath, "enhanced-images"); - /// public IReadOnlyCollection SupportedInputFormats => new HashSet(StringComparer.OrdinalIgnoreCase) @@ -90,9 +77,7 @@ namespace Emby.Drawing "aiff", "cr2", "crw", - - // Remove until supported - //"nef", + "nef", "orf", "pef", "arw", @@ -111,19 +96,9 @@ namespace Emby.Drawing "wbmp" }; - /// - public IReadOnlyCollection ImageEnhancers { get; set; } - /// public bool SupportsImageCollageCreation => _imageEncoder.SupportsImageCollageCreation; - /// - public IImageEncoder ImageEncoder - { - get => _imageEncoder; - set => _imageEncoder = value ?? throw new ArgumentNullException(nameof(value)); - } - /// public async Task ProcessImage(ImageProcessingOptions options, Stream toStream) { @@ -151,6 +126,8 @@ namespace Emby.Drawing throw new ArgumentNullException(nameof(options)); } + var libraryManager = _libraryManager(); + ItemImageInfo originalImage = options.Image; BaseItem item = options.Item; @@ -158,9 +135,10 @@ namespace Emby.Drawing { if (item == null) { - item = _libraryManager().GetItemById(options.ItemId); + item = libraryManager.GetItemById(options.ItemId); } - originalImage = await _libraryManager().ConvertImageToLocal(item, originalImage, options.ImageIndex).ConfigureAwait(false); + + originalImage = await libraryManager.ConvertImageToLocal(item, originalImage, options.ImageIndex).ConfigureAwait(false); } string originalImagePath = originalImage.Path; @@ -187,27 +165,6 @@ namespace Emby.Drawing dateModified = supportedImageInfo.dateModified; bool requiresTransparency = _transparentImageTypes.Contains(Path.GetExtension(originalImagePath)); - if (options.Enhancers.Count > 0) - { - if (item == null) - { - item = _libraryManager().GetItemById(options.ItemId); - } - - var tuple = await GetEnhancedImage(new ItemImageInfo - { - DateModified = dateModified, - Type = originalImage.Type, - Path = originalImagePath - }, requiresTransparency, item, options.ImageIndex, options.Enhancers, CancellationToken.None).ConfigureAwait(false); - - originalImagePath = tuple.path; - dateModified = tuple.dateModified; - requiresTransparency = tuple.transparent; - // TODO: Get this info - originalImageSize = null; - } - bool autoOrient = false; ImageOrientation? orientation = null; if (item is Photo photo) @@ -240,12 +197,6 @@ namespace Emby.Drawing ImageFormat outputFormat = GetOutputFormat(options.SupportedOutputFormats, requiresTransparency); string cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.Blur, options.BackgroundColor, options.ForegroundLayer); - CheckDisposed(); - - LockInfo lockInfo = GetLock(cacheFilePath); - - await lockInfo.Lock.WaitAsync().ConfigureAwait(false); - try { if (!File.Exists(cacheFilePath)) @@ -271,10 +222,6 @@ namespace Emby.Drawing _logger.LogError(ex, "Error encoding image"); return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); } - finally - { - ReleaseLock(cacheFilePath, lockInfo); - } } private ImageFormat GetOutputFormat(IReadOnlyCollection clientSupportedFormats, bool requiresTransparency) @@ -306,20 +253,18 @@ namespace Emby.Drawing } private string GetMimeType(ImageFormat format, string path) - { - switch(format) + => format switch { - case ImageFormat.Bmp: return MimeTypes.GetMimeType("i.bmp"); - case ImageFormat.Gif: return MimeTypes.GetMimeType("i.gif"); - case ImageFormat.Jpg: return MimeTypes.GetMimeType("i.jpg"); - case ImageFormat.Png: return MimeTypes.GetMimeType("i.png"); - case ImageFormat.Webp: return MimeTypes.GetMimeType("i.webp"); - default: return MimeTypes.GetMimeType(path); - } - } + ImageFormat.Bmp => MimeTypes.GetMimeType("i.bmp"), + ImageFormat.Gif => MimeTypes.GetMimeType("i.gif"), + ImageFormat.Jpg => MimeTypes.GetMimeType("i.jpg"), + ImageFormat.Png => MimeTypes.GetMimeType("i.png"), + ImageFormat.Webp => MimeTypes.GetMimeType("i.webp"), + _ => MimeTypes.GetMimeType(path) + }; /// - /// Gets the cache file path based on a set of parameters + /// Gets the cache file path based on a set of parameters. /// private string GetCacheFilePath(string originalPath, ImageDimensions outputSize, int quality, DateTime dateModified, ImageFormat format, bool addPlayedIndicator, double percentPlayed, int? unwatchedCount, int? blur, string backgroundColor, string foregroundLayer) { @@ -401,11 +346,7 @@ namespace Emby.Drawing /// public string GetImageCacheTag(BaseItem item, ItemImageInfo image) - { - var supportedEnhancers = GetSupportedEnhancers(item, image.Type).ToArray(); - - return GetImageCacheTag(item, image, supportedEnhancers); - } + => (item.Path + image.DateModified.Ticks).GetMD5().ToString("N", CultureInfo.InvariantCulture); /// public string GetImageCacheTag(BaseItem item, ChapterInfo chapter) @@ -425,26 +366,6 @@ namespace Emby.Drawing } } - /// - public string GetImageCacheTag(BaseItem item, ItemImageInfo image, IReadOnlyCollection imageEnhancers) - { - string originalImagePath = image.Path; - DateTime dateModified = image.DateModified; - ImageType imageType = image.Type; - - // Optimization - if (imageEnhancers.Count == 0) - { - return (originalImagePath + dateModified.Ticks).GetMD5().ToString("N", CultureInfo.InvariantCulture); - } - - // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes - var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList(); - cacheKeys.Add(originalImagePath + dateModified.Ticks); - - return string.Join("|", cacheKeys).GetMD5().ToString("N", CultureInfo.InvariantCulture); - } - private async Task<(string path, DateTime dateModified)> GetSupportedImage(string originalImagePath, DateTime dateModified) { var inputFormat = Path.GetExtension(originalImagePath) @@ -488,154 +409,6 @@ namespace Emby.Drawing return (originalImagePath, dateModified); } - /// - public async Task GetEnhancedImage(BaseItem item, ImageType imageType, int imageIndex) - { - var enhancers = GetSupportedEnhancers(item, imageType).ToArray(); - - ItemImageInfo imageInfo = item.GetImageInfo(imageType, imageIndex); - - bool inputImageSupportsTransparency = SupportsTransparency(imageInfo.Path); - - var result = await GetEnhancedImage(imageInfo, inputImageSupportsTransparency, item, imageIndex, enhancers, CancellationToken.None); - - return result.path; - } - - private async Task<(string path, DateTime dateModified, bool transparent)> GetEnhancedImage( - ItemImageInfo image, - bool inputImageSupportsTransparency, - BaseItem item, - int imageIndex, - IReadOnlyCollection enhancers, - CancellationToken cancellationToken) - { - var originalImagePath = image.Path; - var dateModified = image.DateModified; - var imageType = image.Type; - - try - { - var cacheGuid = GetImageCacheTag(item, image, enhancers); - - // Enhance if we have enhancers - var enhancedImageInfo = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid, cancellationToken).ConfigureAwait(false); - - string enhancedImagePath = enhancedImageInfo.path; - - // If the path changed update dateModified - if (!string.Equals(enhancedImagePath, originalImagePath, StringComparison.OrdinalIgnoreCase)) - { - var treatmentRequiresTransparency = enhancedImageInfo.transparent; - - return (enhancedImagePath, _fileSystem.GetLastWriteTimeUtc(enhancedImagePath), treatmentRequiresTransparency); - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Error enhancing image"); - } - - return (originalImagePath, dateModified, inputImageSupportsTransparency); - } - - /// - /// Gets the enhanced image internal. - /// - /// The original image path. - /// The item. - /// Type of the image. - /// Index of the image. - /// The supported enhancers. - /// The cache unique identifier. - /// The cancellation token. - /// Task<System.String>. - /// - /// originalImagePath - /// or - /// item - /// - private async Task<(string path, bool transparent)> GetEnhancedImageInternal( - string originalImagePath, - BaseItem item, - ImageType imageType, - int imageIndex, - IReadOnlyCollection supportedEnhancers, - string cacheGuid, - CancellationToken cancellationToken = default) - { - if (string.IsNullOrEmpty(originalImagePath)) - { - throw new ArgumentNullException(nameof(originalImagePath)); - } - - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } - - var treatmentRequiresTransparency = false; - foreach (var enhancer in supportedEnhancers) - { - if (!treatmentRequiresTransparency) - { - treatmentRequiresTransparency = enhancer.GetEnhancedImageInfo(item, originalImagePath, imageType, imageIndex).RequiresTransparency; - } - } - - // All enhanced images are saved as png to allow transparency - string cacheExtension = _imageEncoder.SupportedOutputFormats.Contains(ImageFormat.Webp) ? - ".webp" : - (treatmentRequiresTransparency ? ".png" : ".jpg"); - - string enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + cacheExtension); - - LockInfo lockInfo = GetLock(enhancedImagePath); - - await lockInfo.Lock.WaitAsync(cancellationToken).ConfigureAwait(false); - - try - { - // Check again in case of contention - if (File.Exists(enhancedImagePath)) - { - return (enhancedImagePath, treatmentRequiresTransparency); - } - - Directory.CreateDirectory(Path.GetDirectoryName(enhancedImagePath)); - - await ExecuteImageEnhancers(supportedEnhancers, originalImagePath, enhancedImagePath, item, imageType, imageIndex).ConfigureAwait(false); - - return (enhancedImagePath, treatmentRequiresTransparency); - } - finally - { - ReleaseLock(enhancedImagePath, lockInfo); - } - } - - /// - /// Executes the image enhancers. - /// - /// The image enhancers. - /// The input path. - /// The output path. - /// The item. - /// Type of the image. - /// Index of the image. - /// Task{EnhancedImage}. - private static async Task ExecuteImageEnhancers(IEnumerable imageEnhancers, string inputPath, string outputPath, BaseItem item, ImageType imageType, int imageIndex) - { - // Run the enhancers sequentially in order of priority - foreach (var enhancer in imageEnhancers) - { - await enhancer.EnhanceImageAsync(item, inputPath, outputPath, imageType, imageIndex).ConfigureAwait(false); - - // Feed the output into the next enhancer as input - inputPath = outputPath; - } - } - /// /// Gets the cache path. /// @@ -648,7 +421,7 @@ namespace Emby.Drawing /// or /// uniqueName /// or - /// fileExtension + /// fileExtension. /// public string GetCachePath(string path, string uniqueName, string fileExtension) { @@ -681,7 +454,7 @@ namespace Emby.Drawing /// /// path /// or - /// filename + /// filename. /// public string GetCachePath(string path, string filename) { @@ -689,6 +462,7 @@ namespace Emby.Drawing { throw new ArgumentNullException(nameof(path)); } + if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException(nameof(filename)); @@ -709,75 +483,20 @@ namespace Emby.Drawing _logger.LogInformation("Completed creation of image collage and saved to {Path}", options.OutputPath); } - /// - public IEnumerable GetSupportedEnhancers(BaseItem item, ImageType imageType) - { - foreach (var i in ImageEnhancers) - { - if (i.Supports(item, imageType)) - { - yield return i; - } - } - } - - - private class LockInfo - { - public SemaphoreSlim Lock = new SemaphoreSlim(1, 1); - public int Count = 1; - } - - private LockInfo GetLock(string key) - { - lock (_locks) - { - if (_locks.TryGetValue(key, out LockInfo info)) - { - info.Count++; - } - else - { - info = new LockInfo(); - _locks[key] = info; - } - return info; - } - } - - private void ReleaseLock(string key, LockInfo info) - { - info.Lock.Release(); - - lock (_locks) - { - info.Count--; - if (info.Count <= 0) - { - _locks.Remove(key); - info.Lock.Dispose(); - } - } - } - /// public void Dispose() - { - _disposed = true; - - var disposable = _imageEncoder as IDisposable; - if (disposable != null) - { - disposable.Dispose(); - } - } - - private void CheckDisposed() { if (_disposed) { - throw new ObjectDisposedException(GetType().Name); + return; } + + if (_imageEncoder is IDisposable disposable) + { + disposable.Dispose(); + } + + _disposed = true; } } } diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 0bb1d832fb..4f47874439 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1074,8 +1074,6 @@ namespace Emby.Server.Implementations GetExports(), GetExports()); - ImageProcessor.ImageEnhancers = GetExports(); - LiveTvManager.AddParts(GetExports(), GetExports(), GetExports()); SubtitleManager.AddParts(GetExports()); diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index fcf0360c79..960f3f2d67 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -1362,56 +1362,33 @@ namespace Emby.Server.Implementations.Dto return null; } - var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToArray(); - ImageDimensions size; var defaultAspectRatio = item.GetDefaultPrimaryImageAspectRatio(); if (defaultAspectRatio > 0) { - if (supportedEnhancers.Length == 0) - { - return defaultAspectRatio; - } - - int dummyWidth = 200; - int dummyHeight = Convert.ToInt32(dummyWidth / defaultAspectRatio); - size = new ImageDimensions(dummyWidth, dummyHeight); + return defaultAspectRatio; } - else + + if (!imageInfo.IsLocalFile) { - if (!imageInfo.IsLocalFile) + return null; + } + + try + { + size = _imageProcessor.GetImageDimensions(item, imageInfo); + + if (size.Width <= 0 || size.Height <= 0) { return null; } - - try - { - size = _imageProcessor.GetImageDimensions(item, imageInfo); - - if (size.Width <= 0 || size.Height <= 0) - { - return null; - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Failed to determine primary image aspect ratio for {0}", imageInfo.Path); - return null; - } } - - foreach (var enhancer in supportedEnhancers) + catch (Exception ex) { - try - { - size = enhancer.GetEnhancedImageSize(item, ImageType.Primary, 0, size); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error in image enhancer: {0}", enhancer.GetType().Name); - } + _logger.LogError(ex, "Failed to determine primary image aspect ratio for {0}", imageInfo.Path); + return null; } var width = size.Width; diff --git a/Jellyfin.Drawing.Skia/SkiaEncoder.cs b/Jellyfin.Drawing.Skia/SkiaEncoder.cs index b080b3e6a5..2ea690650b 100644 --- a/Jellyfin.Drawing.Skia/SkiaEncoder.cs +++ b/Jellyfin.Drawing.Skia/SkiaEncoder.cs @@ -6,7 +6,6 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Extensions; using MediaBrowser.Model.Drawing; -using MediaBrowser.Model.Globalization; using Microsoft.Extensions.Logging; using SkiaSharp; using static Jellyfin.Drawing.Skia.SkiaHelper; @@ -18,27 +17,23 @@ namespace Jellyfin.Drawing.Skia /// public class SkiaEncoder : IImageEncoder { - private readonly ILogger _logger; - private readonly IApplicationPaths _appPaths; - private readonly ILocalizationManager _localizationManager; - private static readonly HashSet _transparentImageTypes = new HashSet(StringComparer.OrdinalIgnoreCase) { ".png", ".gif", ".webp" }; + private readonly ILogger _logger; + private readonly IApplicationPaths _appPaths; + /// /// Initializes a new instance of the class. /// /// The application logger. /// The application paths. - /// The application localization manager. public SkiaEncoder( ILogger logger, - IApplicationPaths appPaths, - ILocalizationManager localizationManager) + IApplicationPaths appPaths) { _logger = logger; _appPaths = appPaths; - _localizationManager = localizationManager; } /// @@ -235,9 +230,12 @@ namespace Jellyfin.Drawing.Skia private bool RequiresSpecialCharacterHack(string path) { - if (_localizationManager.HasUnicodeCategory(path, UnicodeCategory.OtherLetter)) + for (int i = 0; i < path.Length; i++) { - return true; + if (char.GetUnicodeCategory(path[i]) == UnicodeCategory.OtherLetter) + { + return true; + } } if (HasDiacritics(path)) diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index fa9b626744..c0621ba144 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -169,7 +169,7 @@ namespace Jellyfin.Server _loggerFactory, options, new ManagedFileSystem(_loggerFactory.CreateLogger(), appPaths), - new NullImageEncoder(), + GetImageEncoder(appPaths), new NetworkManager(_loggerFactory.CreateLogger()), appConfig); try @@ -193,8 +193,6 @@ namespace Jellyfin.Server throw; } - appHost.ImageProcessor.ImageEncoder = GetImageEncoder(appPaths, appHost.LocalizationManager); - await appHost.RunStartupTasksAsync().ConfigureAwait(false); stopWatch.Stop(); @@ -494,9 +492,7 @@ namespace Jellyfin.Server } } - private static IImageEncoder GetImageEncoder( - IApplicationPaths appPaths, - ILocalizationManager localizationManager) + private static IImageEncoder GetImageEncoder(IApplicationPaths appPaths) { try { @@ -505,8 +501,7 @@ namespace Jellyfin.Server return new SkiaEncoder( _loggerFactory.CreateLogger(), - appPaths, - localizationManager); + appPaths); } catch (Exception ex) { diff --git a/MediaBrowser.Api/Images/ImageService.cs b/MediaBrowser.Api/Images/ImageService.cs index e94c1321f4..4060bf4cce 100644 --- a/MediaBrowser.Api/Images/ImageService.cs +++ b/MediaBrowser.Api/Images/ImageService.cs @@ -24,7 +24,7 @@ using Microsoft.Net.Http.Headers; namespace MediaBrowser.Api.Images { /// - /// Class GetItemImage + /// Class GetItemImage. /// [Route("/Items/{Id}/Images", "GET", Summary = "Gets information about an item's images")] [Authenticated] @@ -558,21 +558,6 @@ namespace MediaBrowser.Api.Images throw new ResourceNotFoundException(string.Format("{0} does not have an image of type {1}", displayText, request.Type)); } - IImageEnhancer[] supportedImageEnhancers; - if (_imageProcessor.ImageEnhancers.Count > 0) - { - if (item == null) - { - item = _libraryManager.GetItemById(itemId); - } - - supportedImageEnhancers = request.EnableImageEnhancers ? _imageProcessor.GetSupportedEnhancers(item, request.Type).ToArray() : Array.Empty(); - } - else - { - supportedImageEnhancers = Array.Empty(); - } - bool cropwhitespace; if (request.CropWhitespace.HasValue) { @@ -598,25 +583,25 @@ namespace MediaBrowser.Api.Images {"realTimeInfo.dlna.org", "DLNA.ORG_TLAG=*"} }; - return GetImageResult(item, + return GetImageResult( + item, itemId, request, imageInfo, cropwhitespace, outputFormats, - supportedImageEnhancers, cacheDuration, responseHeaders, isHeadRequest); } - private async Task GetImageResult(BaseItem item, + private async Task GetImageResult( + BaseItem item, Guid itemId, ImageRequest request, ItemImageInfo image, bool cropwhitespace, IReadOnlyCollection supportedFormats, - IReadOnlyCollection enhancers, TimeSpan? cacheDuration, IDictionary headers, bool isHeadRequest) @@ -624,7 +609,6 @@ namespace MediaBrowser.Api.Images var options = new ImageProcessingOptions { CropWhiteSpace = cropwhitespace, - Enhancers = enhancers, Height = request.Height, ImageIndex = request.Index ?? 0, Image = image, diff --git a/MediaBrowser.Controller/Drawing/IImageProcessor.cs b/MediaBrowser.Controller/Drawing/IImageProcessor.cs index a58a11bd1f..79399807fd 100644 --- a/MediaBrowser.Controller/Drawing/IImageProcessor.cs +++ b/MediaBrowser.Controller/Drawing/IImageProcessor.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Entities; @@ -20,20 +19,12 @@ namespace MediaBrowser.Controller.Drawing /// The supported input formats. IReadOnlyCollection SupportedInputFormats { get; } - /// - /// Gets the image enhancers. - /// - /// The image enhancers. - IReadOnlyCollection ImageEnhancers { get; set; } - /// /// Gets a value indicating whether [supports image collage creation]. /// /// true if [supports image collage creation]; otherwise, false. bool SupportsImageCollageCreation { get; } - IImageEncoder ImageEncoder { get; set; } - /// /// Gets the dimensions of the image. /// @@ -58,14 +49,6 @@ namespace MediaBrowser.Controller.Drawing /// ImageDimensions ImageDimensions GetImageDimensions(BaseItem item, ItemImageInfo info, bool updateItem); - /// - /// Gets the supported enhancers. - /// - /// The item. - /// Type of the image. - /// IEnumerable{IImageEnhancer}. - IEnumerable GetSupportedEnhancers(BaseItem item, ImageType imageType); - /// /// Gets the image cache tag. /// @@ -75,15 +58,6 @@ namespace MediaBrowser.Controller.Drawing string GetImageCacheTag(BaseItem item, ItemImageInfo image); string GetImageCacheTag(BaseItem item, ChapterInfo info); - /// - /// Gets the image cache tag. - /// - /// The item. - /// The image. - /// The image enhancers. - /// Guid. - string GetImageCacheTag(BaseItem item, ItemImageInfo image, IReadOnlyCollection imageEnhancers); - /// /// Processes the image. /// @@ -99,15 +73,6 @@ namespace MediaBrowser.Controller.Drawing /// Task. Task<(string path, string mimeType, DateTime dateModified)> ProcessImage(ImageProcessingOptions options); - /// - /// Gets the enhanced image. - /// - /// The item. - /// Type of the image. - /// Index of the image. - /// Task{System.String}. - Task GetEnhancedImage(BaseItem item, ImageType imageType, int imageIndex); - /// /// Gets the supported image output formats. /// diff --git a/MediaBrowser.Controller/Drawing/ImageHelper.cs b/MediaBrowser.Controller/Drawing/ImageHelper.cs index 432cf80423..d5a5f547ea 100644 --- a/MediaBrowser.Controller/Drawing/ImageHelper.cs +++ b/MediaBrowser.Controller/Drawing/ImageHelper.cs @@ -19,8 +19,6 @@ namespace MediaBrowser.Controller.Drawing return GetSizeEstimate(options); } - public static IImageProcessor ImageProcessor { get; set; } - private static ImageDimensions GetSizeEstimate(ImageProcessingOptions options) { if (options.Width.HasValue && options.Height.HasValue) diff --git a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs index 29addf6e65..870e0278e4 100644 --- a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs +++ b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Drawing; namespace MediaBrowser.Controller.Drawing @@ -34,8 +33,6 @@ namespace MediaBrowser.Controller.Drawing public int Quality { get; set; } - public IReadOnlyCollection Enhancers { get; set; } - public IReadOnlyCollection SupportedOutputFormats { get; set; } public bool AddPlayedIndicator { get; set; } diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs index 34af3b1568..6b3fb4144e 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs @@ -316,11 +316,7 @@ namespace MediaBrowser.Controller.MediaEncoding { if (VideoStream != null && VideoStream.Width.HasValue && VideoStream.Height.HasValue) { - var size = new ImageDimensions - { - Width = VideoStream.Width.Value, - Height = VideoStream.Height.Value - }; + var size = new ImageDimensions(VideoStream.Width.Value, VideoStream.Height.Value); var newSize = DrawingUtils.Resize(size, BaseRequest.Width ?? 0, @@ -346,11 +342,7 @@ namespace MediaBrowser.Controller.MediaEncoding { if (VideoStream != null && VideoStream.Width.HasValue && VideoStream.Height.HasValue) { - var size = new ImageDimensions - { - Width = VideoStream.Width.Value, - Height = VideoStream.Height.Value - }; + var size = new ImageDimensions(VideoStream.Width.Value, VideoStream.Height.Value); var newSize = DrawingUtils.Resize(size, BaseRequest.Width ?? 0, diff --git a/MediaBrowser.Controller/Providers/IImageEnhancer.cs b/MediaBrowser.Controller/Providers/IImageEnhancer.cs deleted file mode 100644 index c27c00ca26..0000000000 --- a/MediaBrowser.Controller/Providers/IImageEnhancer.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System.Threading.Tasks; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Model.Drawing; -using MediaBrowser.Model.Entities; - -namespace MediaBrowser.Controller.Providers -{ - public interface IImageEnhancer - { - /// - /// Return true only if the given image for the given item will be enhanced by this enhancer. - /// - /// The item. - /// Type of the image. - /// true if this enhancer will enhance the supplied image for the supplied item, false otherwise - bool Supports(BaseItem item, ImageType imageType); - - /// - /// Gets the priority or order in which this enhancer should be run. - /// - /// The priority. - MetadataProviderPriority Priority { get; } - - /// - /// Return a key incorporating all configuration information related to this item - /// - /// The item. - /// Type of the image. - /// Cache key relating to the current state of this item and configuration - string GetConfigurationCacheKey(BaseItem item, ImageType imageType); - - /// - /// Gets the size of the enhanced image. - /// - /// The item. - /// Type of the image. - /// Index of the image. - /// Size of the original image. - /// ImageSize. - ImageDimensions GetEnhancedImageSize(BaseItem item, ImageType imageType, int imageIndex, ImageDimensions originalImageSize); - - EnhancedImageInfo GetEnhancedImageInfo(BaseItem item, string inputFile, ImageType imageType, int imageIndex); - - /// - /// Enhances the image async. - /// - /// The item. - /// The input file. - /// The output file. - /// Type of the image. - /// Index of the image. - /// Task{Image}. - /// - Task EnhanceImageAsync(BaseItem item, string inputFile, string outputFile, ImageType imageType, int imageIndex); - } - - public class EnhancedImageInfo - { - public bool RequiresTransparency { get; set; } - } -} diff --git a/MediaBrowser.Model/Drawing/ImageDimensions.cs b/MediaBrowser.Model/Drawing/ImageDimensions.cs index e7805ac494..4bd8d85d4f 100644 --- a/MediaBrowser.Model/Drawing/ImageDimensions.cs +++ b/MediaBrowser.Model/Drawing/ImageDimensions.cs @@ -1,36 +1,43 @@ +using System.Globalization; + namespace MediaBrowser.Model.Drawing { /// /// Struct ImageDimensions /// - public struct ImageDimensions + public readonly struct ImageDimensions { - /// - /// Gets or sets the height. - /// - /// The height. - public int Height { get; set; } + public ImageDimensions(int width, int height) + { + Width = width; + Height = height; + } /// - /// Gets or sets the width. + /// Gets the height. + /// + /// The height. + public int Height { get; } + + /// + /// Gets the width. /// /// The width. - public int Width { get; set; } + public int Width { get; } public bool Equals(ImageDimensions size) { return Width.Equals(size.Width) && Height.Equals(size.Height); } + /// public override string ToString() { - return string.Format("{0}-{1}", Width, Height); - } - - public ImageDimensions(int width, int height) - { - Width = width; - Height = height; + return string.Format( + CultureInfo.InvariantCulture, + "{0}-{1}", + Width, + Height); } } } From 70bc03c79571f70c2a6281b99554638f76f461c9 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Sat, 1 Feb 2020 12:54:48 +0100 Subject: [PATCH 04/23] Apply suggestions from code review Co-Authored-By: dkanada --- Emby.Server.Implementations/Session/SessionManager.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index bb0836614e..f5bd51c4ae 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -35,12 +35,12 @@ namespace Emby.Server.Implementations.Session public class SessionManager : ISessionManager, IDisposable { /// - /// The _user data repository. + /// The user data repository. /// private readonly IUserDataManager _userDataManager; /// - /// The _logger. + /// The logger. /// private readonly ILogger _logger; @@ -57,7 +57,7 @@ namespace Emby.Server.Implementations.Session private readonly IDeviceManager _deviceManager; /// - /// The _active connections. + /// The active connections. /// private readonly ConcurrentDictionary _activeConnections = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); From 91707f13a877dd4e8b70d0857f0343215be76758 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Tue, 4 Feb 2020 12:29:14 +0100 Subject: [PATCH 05/23] Add endpoints back --- .../Api/NotificationsService.cs | 105 +++++++++++++++++- jellyfin.ruleset | 2 + 2 files changed, 105 insertions(+), 2 deletions(-) diff --git a/Emby.Notifications/Api/NotificationsService.cs b/Emby.Notifications/Api/NotificationsService.cs index 5591809712..f9e923d10b 100644 --- a/Emby.Notifications/Api/NotificationsService.cs +++ b/Emby.Notifications/Api/NotificationsService.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -17,6 +18,62 @@ using MediaBrowser.Model.Services; namespace Emby.Notifications.Api { + [Route("/Notifications/{UserId}", "GET", Summary = "Gets notifications")] + public class GetNotifications : IReturn + { + [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] + public string UserId { get; set; } + + [ApiMember(Name = "IsRead", Description = "An optional filter by IsRead", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")] + public bool? IsRead { get; set; } + + [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")] + public int? StartIndex { get; set; } + + [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")] + public int? Limit { get; set; } + } + + public class Notification + { + public string Id { get; set; } + + public string UserId { get; set; } + + public DateTime Date { get; set; } + + public bool IsRead { get; set; } + + public string Name { get; set; } + + public string Description { get; set; } + + public string Url { get; set; } + + public NotificationLevel Level { get; set; } + } + + public class NotificationResult + { + public IReadOnlyList Notifications { get; set; } + + public int TotalRecordCount { get; set; } + } + + public class NotificationsSummary + { + public int UnreadCount { get; set; } + + public NotificationLevel MaxUnreadNotificationLevel { get; set; } + } + + [Route("/Notifications/{UserId}/Summary", "GET", Summary = "Gets a notification summary for a user")] + public class GetNotificationsSummary : IReturn + { + [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] + public string UserId { get; set; } + } + [Route("/Notifications/Types", "GET", Summary = "Gets notification types")] public class GetNotificationTypes : IReturn> { @@ -46,6 +103,26 @@ namespace Emby.Notifications.Api public NotificationLevel Level { get; set; } } + [Route("/Notifications/{UserId}/Read", "POST", Summary = "Marks notifications as read")] + public class MarkRead : IReturnVoid + { + [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] + public string UserId { get; set; } + + [ApiMember(Name = "Ids", Description = "A list of notification ids, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)] + public string Ids { get; set; } + } + + [Route("/Notifications/{UserId}/Unread", "POST", Summary = "Marks notifications as unread")] + public class MarkUnread : IReturnVoid + { + [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] + public string UserId { get; set; } + + [ApiMember(Name = "Ids", Description = "A list of notification ids, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)] + public string Ids { get; set; } + } + [Authenticated] public class NotificationsService : IService { @@ -58,18 +135,26 @@ namespace Emby.Notifications.Api _userManager = userManager; } + [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "request")] public object Get(GetNotificationTypes request) { - _ = request; // Silence unused variable warning return _notificationManager.GetNotificationTypes(); } + [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "request")] public object Get(GetNotificationServices request) { - _ = request; // Silence unused variable warning return _notificationManager.GetNotificationServices().ToList(); } + [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "request")] + public object Get(GetNotificationsSummary request) + { + return new NotificationsSummary + { + }; + } + public Task Post(AddAdminNotification request) { // This endpoint really just exists as post of a real with sickbeard @@ -85,5 +170,21 @@ namespace Emby.Notifications.Api return _notificationManager.SendNotification(notification, CancellationToken.None); } + + [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "request")] + public void Post(MarkRead request) + { + } + + [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "request")] + public void Post(MarkUnread request) + { + } + + [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "request")] + public object Get(GetNotifications request) + { + return new NotificationResult(); + } } } diff --git a/jellyfin.ruleset b/jellyfin.ruleset index 92b7a03fdd..e4d2831677 100644 --- a/jellyfin.ruleset +++ b/jellyfin.ruleset @@ -5,6 +5,8 @@ + + From 3fe84c3213b8340f86aec0c5c488f7fc303b26cc Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Thu, 6 Feb 2020 13:03:02 +0100 Subject: [PATCH 06/23] Apply suggestions from code review Co-Authored-By: dkanada --- Emby.Server.Implementations/Session/SessionManager.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index f5bd51c4ae..56dd361078 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -102,17 +102,17 @@ namespace Emby.Server.Implementations.Session public event EventHandler> AuthenticationSucceeded; /// - /// Occurs when [playback start]. + /// Occurs when playback has started. /// public event EventHandler PlaybackStart; /// - /// Occurs when [playback progress]. + /// Occurs when playback has progressed. /// public event EventHandler PlaybackProgress; /// - /// Occurs when [playback stopped]. + /// Occurs when playback has stopped. /// public event EventHandler PlaybackStopped; From cefac4f886e82a642380586b3d732e729cd76dd1 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Thu, 6 Feb 2020 13:16:22 +0100 Subject: [PATCH 07/23] Update Emby.Server.Implementations/Session/SessionManager.cs Co-Authored-By: dkanada --- Emby.Server.Implementations/Session/SessionManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index 31e574ba65..a6a5523ded 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -161,7 +161,7 @@ namespace Emby.Server.Implementations.Session } /// - /// Releases unmanaged and - optionally - managed resources. + /// Releases unmanaged and optionally managed resources. /// /// true to release both managed and unmanaged resources; false to release only unmanaged resources. protected virtual void Dispose(bool disposing) From 7060934792d463840a616499ab869d4285582608 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 6 Feb 2020 15:20:23 +0100 Subject: [PATCH 08/23] Fix some warnings in Emby.Server.Implementations --- .../EntryPoints/RecordingNotifier.cs | 29 ++++++------ .../EntryPoints/RefreshUsersMetadata.cs | 9 +--- .../EntryPoints/StartupWizard.cs | 15 ++---- .../EntryPoints/UdpServerEntryPoint.cs | 6 +-- .../EntryPoints/UserDataChangeNotifier.cs | 46 ++++++++++--------- .../HttpClientManager/HttpClientManager.cs | 2 +- .../HttpServer/HttpListenerHost.cs | 27 ++++++----- .../IO/ExtendedFileSystemInfo.cs | 2 + .../IO/FileRefresher.cs | 42 +++++++++-------- .../LiveTv/EmbyTV/DirectRecorder.cs | 3 ++ .../LiveTv/EmbyTV/EmbyTV.cs | 1 - .../LiveTv/EmbyTV/EncodedRecorder.cs | 3 ++ .../LiveTv/EmbyTV/EntryPoint.cs | 5 ++ .../LiveTv/EmbyTV/IRecorder.cs | 3 ++ .../LiveTv/EmbyTV/ItemDataProvider.cs | 3 ++ .../LiveTv/EmbyTV/RecordingHelper.cs | 18 ++++++-- .../LiveTv/EmbyTV/SeriesTimerManager.cs | 4 ++ .../LiveTv/EmbyTV/TimerManager.cs | 3 ++ .../LiveTv/Listings/SchedulesDirect.cs | 3 ++ .../LiveTv/Listings/XmlTvListingsProvider.cs | 7 ++- .../LiveTv/LiveTvConfigurationFactory.cs | 3 ++ .../LiveTv/LiveTvDtoService.cs | 3 ++ .../LiveTv/LiveTvManager.cs | 2 +- .../LiveTv/LiveTvMediaSourceProvider.cs | 46 ++++++++----------- .../LiveTv/TunerHosts/BaseTunerHost.cs | 3 ++ .../TunerHosts/HdHomerun/HdHomerunHost.cs | 3 ++ .../TunerHosts/HdHomerun/HdHomerunManager.cs | 3 ++ .../HdHomerun/HdHomerunUdpStream.cs | 3 ++ .../LiveTv/TunerHosts/LiveStream.cs | 3 ++ .../LiveTv/TunerHosts/M3UTunerHost.cs | 3 ++ .../LiveTv/TunerHosts/M3uParser.cs | 3 ++ .../LiveTv/TunerHosts/SharedHttpStream.cs | 3 ++ 32 files changed, 181 insertions(+), 128 deletions(-) diff --git a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs index e0aa18e895..eecc2c5297 100644 --- a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs @@ -13,7 +13,7 @@ using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.EntryPoints { - public class RecordingNotifier : IServerEntryPoint + public sealed class RecordingNotifier : IServerEntryPoint { private readonly ILiveTvManager _liveTvManager; private readonly ISessionManager _sessionManager; @@ -30,30 +30,30 @@ namespace Emby.Server.Implementations.EntryPoints public Task RunAsync() { - _liveTvManager.TimerCancelled += _liveTvManager_TimerCancelled; - _liveTvManager.SeriesTimerCancelled += _liveTvManager_SeriesTimerCancelled; - _liveTvManager.TimerCreated += _liveTvManager_TimerCreated; - _liveTvManager.SeriesTimerCreated += _liveTvManager_SeriesTimerCreated; + _liveTvManager.TimerCancelled += LiveTvManagerTimerCancelled; + _liveTvManager.SeriesTimerCancelled += LiveTvManagerSeriesTimerCancelled; + _liveTvManager.TimerCreated += OnLiveTvManagerTimerCreated; + _liveTvManager.SeriesTimerCreated += OnLiveTvManagerSeriesTimerCreated; return Task.CompletedTask; } - private void _liveTvManager_SeriesTimerCreated(object sender, MediaBrowser.Model.Events.GenericEventArgs e) + private void OnLiveTvManagerSeriesTimerCreated(object sender, MediaBrowser.Model.Events.GenericEventArgs e) { SendMessage("SeriesTimerCreated", e.Argument); } - private void _liveTvManager_TimerCreated(object sender, MediaBrowser.Model.Events.GenericEventArgs e) + private void OnLiveTvManagerTimerCreated(object sender, MediaBrowser.Model.Events.GenericEventArgs e) { SendMessage("TimerCreated", e.Argument); } - private void _liveTvManager_SeriesTimerCancelled(object sender, MediaBrowser.Model.Events.GenericEventArgs e) + private void LiveTvManagerSeriesTimerCancelled(object sender, MediaBrowser.Model.Events.GenericEventArgs e) { SendMessage("SeriesTimerCancelled", e.Argument); } - private void _liveTvManager_TimerCancelled(object sender, MediaBrowser.Model.Events.GenericEventArgs e) + private void LiveTvManagerTimerCancelled(object sender, MediaBrowser.Model.Events.GenericEventArgs e) { SendMessage("TimerCancelled", e.Argument); } @@ -64,7 +64,7 @@ namespace Emby.Server.Implementations.EntryPoints try { - await _sessionManager.SendMessageToUserSessions(users, name, info, CancellationToken.None); + await _sessionManager.SendMessageToUserSessions(users, name, info, CancellationToken.None).ConfigureAwait(false); } catch (ObjectDisposedException) { @@ -76,12 +76,13 @@ namespace Emby.Server.Implementations.EntryPoints } } + /// public void Dispose() { - _liveTvManager.TimerCancelled -= _liveTvManager_TimerCancelled; - _liveTvManager.SeriesTimerCancelled -= _liveTvManager_SeriesTimerCancelled; - _liveTvManager.TimerCreated -= _liveTvManager_TimerCreated; - _liveTvManager.SeriesTimerCreated -= _liveTvManager_SeriesTimerCreated; + _liveTvManager.TimerCancelled -= LiveTvManagerTimerCancelled; + _liveTvManager.SeriesTimerCancelled -= LiveTvManagerSeriesTimerCancelled; + _liveTvManager.TimerCreated -= OnLiveTvManagerTimerCreated; + _liveTvManager.SeriesTimerCreated -= OnLiveTvManagerSeriesTimerCreated; } } } diff --git a/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs b/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs index f00996b5fe..54f4b67e66 100644 --- a/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs +++ b/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs @@ -6,7 +6,6 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.IO; using MediaBrowser.Model.Tasks; -using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.EntryPoints { @@ -15,21 +14,17 @@ namespace Emby.Server.Implementations.EntryPoints /// public class RefreshUsersMetadata : IScheduledTask, IConfigurableScheduledTask { - private readonly ILogger _logger; - /// /// The user manager. /// private readonly IUserManager _userManager; - - private IFileSystem _fileSystem; + private readonly IFileSystem _fileSystem; /// /// Initializes a new instance of the class. /// - public RefreshUsersMetadata(ILogger logger, IUserManager userManager, IFileSystem fileSystem) + public RefreshUsersMetadata(IUserManager userManager, IFileSystem fileSystem) { - _logger = logger; _userManager = userManager; _fileSystem = fileSystem; } diff --git a/Emby.Server.Implementations/EntryPoints/StartupWizard.cs b/Emby.Server.Implementations/EntryPoints/StartupWizard.cs index 161788c636..5f2d629fea 100644 --- a/Emby.Server.Implementations/EntryPoints/StartupWizard.cs +++ b/Emby.Server.Implementations/EntryPoints/StartupWizard.cs @@ -3,37 +3,28 @@ using Emby.Server.Implementations.Browser; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Plugins; -using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.EntryPoints { /// /// Class StartupWizard. /// - public class StartupWizard : IServerEntryPoint + public sealed class StartupWizard : IServerEntryPoint { /// /// The app host. /// private readonly IServerApplicationHost _appHost; - - /// - /// The user manager. - /// - private readonly ILogger _logger; - - private IServerConfigurationManager _config; + private readonly IServerConfigurationManager _config; /// /// Initializes a new instance of the class. /// /// The application host. - /// The logger. /// The configuration manager. - public StartupWizard(IServerApplicationHost appHost, ILogger logger, IServerConfigurationManager config) + public StartupWizard(IServerApplicationHost appHost, IServerConfigurationManager config) { _appHost = appHost; - _logger = logger; _config = config; } diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index 529f835606..50ba0f8fac 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -3,8 +3,6 @@ using System.Threading.Tasks; using Emby.Server.Implementations.Udp; using MediaBrowser.Controller; using MediaBrowser.Controller.Plugins; -using MediaBrowser.Model.Net; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.EntryPoints @@ -23,9 +21,7 @@ namespace Emby.Server.Implementations.EntryPoints /// The logger. /// private readonly ILogger _logger; - private readonly ISocketFactory _socketFactory; private readonly IServerApplicationHost _appHost; - private readonly IJsonSerializer _json; /// /// The UDP server. @@ -64,7 +60,7 @@ namespace Emby.Server.Implementations.EntryPoints _cancellationTokenSource.Cancel(); _udpServer.Dispose(); - + _cancellationTokenSource.Dispose(); _cancellationTokenSource = null; _udpServer = null; diff --git a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs index 3e22080fc0..026b5dae97 100644 --- a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs @@ -13,39 +13,38 @@ using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Session; -using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.EntryPoints { - public class UserDataChangeNotifier : IServerEntryPoint + public sealed class UserDataChangeNotifier : IServerEntryPoint { + private const int UpdateDuration = 500; + private readonly ISessionManager _sessionManager; - private readonly ILogger _logger; private readonly IUserDataManager _userDataManager; private readonly IUserManager _userManager; - private readonly object _syncLock = new object(); - private Timer UpdateTimer { get; set; } - private const int UpdateDuration = 500; - private readonly Dictionary> _changedItems = new Dictionary>(); - public UserDataChangeNotifier(IUserDataManager userDataManager, ISessionManager sessionManager, ILogger logger, IUserManager userManager) + private readonly object _syncLock = new object(); + private Timer _updateTimer; + + + public UserDataChangeNotifier(IUserDataManager userDataManager, ISessionManager sessionManager, IUserManager userManager) { _userDataManager = userDataManager; _sessionManager = sessionManager; - _logger = logger; _userManager = userManager; } public Task RunAsync() { - _userDataManager.UserDataSaved += _userDataManager_UserDataSaved; + _userDataManager.UserDataSaved += OnUserDataManagerUserDataSaved; return Task.CompletedTask; } - void _userDataManager_UserDataSaved(object sender, UserDataSaveEventArgs e) + void OnUserDataManagerUserDataSaved(object sender, UserDataSaveEventArgs e) { if (e.SaveReason == UserDataSaveReason.PlaybackProgress) { @@ -54,14 +53,17 @@ namespace Emby.Server.Implementations.EntryPoints lock (_syncLock) { - if (UpdateTimer == null) + if (_updateTimer == null) { - UpdateTimer = new Timer(UpdateTimerCallback, null, UpdateDuration, - Timeout.Infinite); + _updateTimer = new Timer( + UpdateTimerCallback, + null, + UpdateDuration, + Timeout.Infinite); } else { - UpdateTimer.Change(UpdateDuration, Timeout.Infinite); + _updateTimer.Change(UpdateDuration, Timeout.Infinite); } if (!_changedItems.TryGetValue(e.UserId, out List keys)) @@ -97,10 +99,10 @@ namespace Emby.Server.Implementations.EntryPoints var task = SendNotifications(changes, CancellationToken.None); - if (UpdateTimer != null) + if (_updateTimer != null) { - UpdateTimer.Dispose(); - UpdateTimer = null; + _updateTimer.Dispose(); + _updateTimer = null; } } } @@ -145,13 +147,13 @@ namespace Emby.Server.Implementations.EntryPoints public void Dispose() { - if (UpdateTimer != null) + if (_updateTimer != null) { - UpdateTimer.Dispose(); - UpdateTimer = null; + _updateTimer.Dispose(); + _updateTimer = null; } - _userDataManager.UserDataSaved -= _userDataManager_UserDataSaved; + _userDataManager.UserDataSaved -= OnUserDataManagerUserDataSaved; } } } diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs index 8a2bc83fb0..45fa03cdd7 100644 --- a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs +++ b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs @@ -78,7 +78,7 @@ namespace Emby.Server.Implementations.HttpClientManager if (!string.IsNullOrWhiteSpace(userInfo)) { _logger.LogWarning("Found userInfo in url: {0} ... url: {1}", userInfo, url); - url = url.Replace(userInfo + '@', string.Empty); + url = url.Replace(userInfo + '@', string.Empty, StringComparison.Ordinal); } var request = new HttpRequestMessage(method, url); diff --git a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs index b0126f7fa5..85602a67f0 100644 --- a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -40,9 +40,9 @@ namespace Emby.Server.Implementations.HttpServer private readonly Func> _funcParseFn; private readonly string _defaultRedirectPath; private readonly string _baseUrlPrefix; - private readonly Dictionary ServiceOperationsMap = new Dictionary(); - private IWebSocketListener[] _webSocketListeners = Array.Empty(); + private readonly Dictionary _serviceOperationsMap = new Dictionary(); private readonly List _webSocketConnections = new List(); + private IWebSocketListener[] _webSocketListeners = Array.Empty(); private bool _disposed = false; public HttpListenerHost( @@ -72,6 +72,8 @@ namespace Emby.Server.Implementations.HttpServer ResponseFilters = Array.Empty>(); } + public event EventHandler> WebSocketConnected; + public Action[] ResponseFilters { get; set; } public static HttpListenerHost Instance { get; protected set; } @@ -82,8 +84,6 @@ namespace Emby.Server.Implementations.HttpServer public ServiceController ServiceController { get; private set; } - public event EventHandler> WebSocketConnected; - public object CreateInstance(Type type) { return _appHost.CreateInstance(type); @@ -91,7 +91,7 @@ namespace Emby.Server.Implementations.HttpServer private static string NormalizeUrlPath(string path) { - if (path.StartsWith("/")) + if (path.Length > 0 && path[0] == '/') { // If the path begins with a leading slash, just return it as-is return path; @@ -131,13 +131,13 @@ namespace Emby.Server.Implementations.HttpServer public Type GetServiceTypeByRequest(Type requestType) { - ServiceOperationsMap.TryGetValue(requestType, out var serviceType); + _serviceOperationsMap.TryGetValue(requestType, out var serviceType); return serviceType; } public void AddServiceInfo(Type serviceType, Type requestType) { - ServiceOperationsMap[requestType] = serviceType; + _serviceOperationsMap[requestType] = serviceType; } private List GetRequestFilterAttributes(Type requestDtoType) @@ -199,7 +199,7 @@ namespace Emby.Server.Implementations.HttpServer else { var inners = agg.InnerExceptions; - if (inners != null && inners.Count > 0) + if (inners.Count > 0) { return GetActualException(inners[0]); } @@ -362,7 +362,7 @@ namespace Emby.Server.Implementations.HttpServer return true; } - host = host ?? string.Empty; + host ??= string.Empty; if (_networkManager.IsInPrivateAddressSpace(host)) { @@ -433,7 +433,7 @@ namespace Emby.Server.Implementations.HttpServer } /// - /// Overridable method that can be used to implement a custom hnandler + /// Overridable method that can be used to implement a custom handler. /// public async Task RequestHandler(IHttpRequest httpReq, string urlString, string host, string localPath, CancellationToken cancellationToken) { @@ -492,7 +492,7 @@ namespace Emby.Server.Implementations.HttpServer || string.Equals(localPath, _baseUrlPrefix, StringComparison.OrdinalIgnoreCase) || string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase) || string.IsNullOrEmpty(localPath) - || !localPath.StartsWith(_baseUrlPrefix)) + || !localPath.StartsWith(_baseUrlPrefix, StringComparison.OrdinalIgnoreCase)) { // Always redirect back to the default path if the base prefix is invalid or missing _logger.LogDebug("Normalizing a URL at {0}", localPath); @@ -693,7 +693,10 @@ namespace Emby.Server.Implementations.HttpServer protected virtual void Dispose(bool disposing) { - if (_disposed) return; + if (_disposed) + { + return; + } if (disposing) { diff --git a/Emby.Server.Implementations/IO/ExtendedFileSystemInfo.cs b/Emby.Server.Implementations/IO/ExtendedFileSystemInfo.cs index 5be1444525..ec26324c39 100644 --- a/Emby.Server.Implementations/IO/ExtendedFileSystemInfo.cs +++ b/Emby.Server.Implementations/IO/ExtendedFileSystemInfo.cs @@ -6,7 +6,9 @@ namespace Emby.Server.Implementations.IO public class ExtendedFileSystemInfo { public bool IsHidden { get; set; } + public bool IsReadOnly { get; set; } + public bool Exists { get; set; } } } diff --git a/Emby.Server.Implementations/IO/FileRefresher.cs b/Emby.Server.Implementations/IO/FileRefresher.cs index cf92ddbcd7..f37a6af909 100644 --- a/Emby.Server.Implementations/IO/FileRefresher.cs +++ b/Emby.Server.Implementations/IO/FileRefresher.cs @@ -15,27 +15,29 @@ namespace Emby.Server.Implementations.IO { public class FileRefresher : IDisposable { - private ILogger Logger { get; set; } - private ILibraryManager LibraryManager { get; set; } - private IServerConfigurationManager ConfigurationManager { get; set; } - private readonly List _affectedPaths = new List(); - private Timer _timer; - private readonly object _timerLock = new object(); - public string Path { get; private set; } + private readonly ILogger _logger; + private readonly ILibraryManager _libraryManager; + private readonly IServerConfigurationManager _configurationManager; - public event EventHandler Completed; + private readonly List _affectedPaths = new List(); + private readonly object _timerLock = new object(); + private Timer _timer; public FileRefresher(string path, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, ILogger logger) { logger.LogDebug("New file refresher created for {0}", path); Path = path; - ConfigurationManager = configurationManager; - LibraryManager = libraryManager; - Logger = logger; + _configurationManager = configurationManager; + _libraryManager = libraryManager; + _logger = logger; AddPath(path); } + public event EventHandler Completed; + + public string Path { get; private set; } + private void AddAffectedPath(string path) { if (string.IsNullOrEmpty(path)) @@ -80,11 +82,11 @@ namespace Emby.Server.Implementations.IO if (_timer == null) { - _timer = new Timer(OnTimerCallback, null, TimeSpan.FromSeconds(ConfigurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1)); + _timer = new Timer(OnTimerCallback, null, TimeSpan.FromSeconds(_configurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1)); } else { - _timer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1)); + _timer.Change(TimeSpan.FromSeconds(_configurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1)); } } } @@ -93,7 +95,7 @@ namespace Emby.Server.Implementations.IO { lock (_timerLock) { - Logger.LogDebug("Resetting file refresher from {0} to {1}", Path, path); + _logger.LogDebug("Resetting file refresher from {0} to {1}", Path, path); Path = path; AddAffectedPath(path); @@ -116,7 +118,7 @@ namespace Emby.Server.Implementations.IO paths = _affectedPaths.ToList(); } - Logger.LogDebug("Timer stopped."); + _logger.LogDebug("Timer stopped."); DisposeTimer(); Completed?.Invoke(this, EventArgs.Empty); @@ -127,7 +129,7 @@ namespace Emby.Server.Implementations.IO } catch (Exception ex) { - Logger.LogError(ex, "Error processing directory changes"); + _logger.LogError(ex, "Error processing directory changes"); } } @@ -147,7 +149,7 @@ namespace Emby.Server.Implementations.IO continue; } - Logger.LogInformation("{name} ({path}) will be refreshed.", item.Name, item.Path); + _logger.LogInformation("{name} ({path}) will be refreshed.", item.Name, item.Path); try { @@ -158,11 +160,11 @@ namespace Emby.Server.Implementations.IO // For now swallow and log. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable) // Should we remove it from it's parent? - Logger.LogError(ex, "Error refreshing {name}", item.Name); + _logger.LogError(ex, "Error refreshing {name}", item.Name); } catch (Exception ex) { - Logger.LogError(ex, "Error refreshing {name}", item.Name); + _logger.LogError(ex, "Error refreshing {name}", item.Name); } } } @@ -178,7 +180,7 @@ namespace Emby.Server.Implementations.IO while (item == null && !string.IsNullOrEmpty(path)) { - item = LibraryManager.FindByPath(path, null); + item = _libraryManager.FindByPath(path, null); path = System.IO.Path.GetDirectoryName(path); } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs index 161cf60516..9c4f5fe3d8 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.IO; using System.Net.Http; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 4ac48e5378..49d4ddbaf5 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -30,7 +30,6 @@ using MediaBrowser.Model.Diagnostics; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Events; -using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; using MediaBrowser.Model.LiveTv; using MediaBrowser.Model.MediaInfo; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 6e4ac2fecc..8590c56dfd 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.Globalization; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EntryPoint.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EntryPoint.cs index 9c9ba09f5f..a716b6240f 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EntryPoint.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EntryPoint.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Threading.Tasks; using MediaBrowser.Controller.Plugins; @@ -5,11 +8,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { public class EntryPoint : IServerEntryPoint { + /// public Task RunAsync() { return EmbyTV.Current.Start(); } + /// public void Dispose() { } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs index 6eced30509..d6a1aee38b 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Threading; using System.Threading.Tasks; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs index 9055a70a67..6d42a58f42 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.IO; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs index ded3c7607d..4cb9f6fe88 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Globalization; using MediaBrowser.Controller.LiveTv; @@ -21,7 +24,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (info.SeasonNumber.HasValue && info.EpisodeNumber.HasValue) { - name += string.Format(" S{0}E{1}", info.SeasonNumber.Value.ToString("00", CultureInfo.InvariantCulture), info.EpisodeNumber.Value.ToString("00", CultureInfo.InvariantCulture)); + name += string.Format( + CultureInfo.InvariantCulture, + " S{0}E{1}", + info.SeasonNumber.Value.ToString("00", CultureInfo.InvariantCulture), + info.EpisodeNumber.Value.ToString("00", CultureInfo.InvariantCulture)); addHyphen = false; } else if (info.OriginalAirDate.HasValue) @@ -32,7 +39,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } else { - name += " " + info.OriginalAirDate.Value.ToLocalTime().ToString("yyyy-MM-dd"); + name += " " + info.OriginalAirDate.Value.ToLocalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); } } else @@ -67,14 +74,15 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { date = date.ToLocalTime(); - return string.Format("{0}_{1}_{2}_{3}_{4}_{5}", + return string.Format( + CultureInfo.InvariantCulture, + "{0}_{1}_{2}_{3}_{4}_{5}", date.Year.ToString("0000", CultureInfo.InvariantCulture), date.Month.ToString("00", CultureInfo.InvariantCulture), date.Day.ToString("00", CultureInfo.InvariantCulture), date.Hour.ToString("00", CultureInfo.InvariantCulture), date.Minute.ToString("00", CultureInfo.InvariantCulture), - date.Second.ToString("00", CultureInfo.InvariantCulture) - ); + date.Second.ToString("00", CultureInfo.InvariantCulture)); } } } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs index 520b444041..9cc53fddcd 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Serialization; @@ -12,6 +15,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { } + /// public override void Add(SeriesTimerInfo item) { if (string.IsNullOrEmpty(item.Id)) diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs index d09b281d4c..330e881ef5 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Concurrent; using System.Globalization; diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 1dd794da0d..906f42d2e9 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Concurrent; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs index 1f38de2d86..42daa98f5c 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.Globalization; @@ -91,12 +94,12 @@ namespace Emby.Server.Implementations.LiveTv.Listings { using (var gzStream = new GZipStream(stream, CompressionMode.Decompress)) { - await gzStream.CopyToAsync(fileStream).ConfigureAwait(false); + await gzStream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false); } } else { - await stream.CopyToAsync(fileStream).ConfigureAwait(false); + await stream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false); } } diff --git a/Emby.Server.Implementations/LiveTv/LiveTvConfigurationFactory.cs b/Emby.Server.Implementations/LiveTv/LiveTvConfigurationFactory.cs index f9b274acbd..222fed9d92 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvConfigurationFactory.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvConfigurationFactory.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Collections.Generic; using MediaBrowser.Common.Configuration; using MediaBrowser.Model.LiveTv; diff --git a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs index e584664c94..14b627f82e 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Globalization; using System.Linq; diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index e3f9df35a0..f20f6140e5 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -1,5 +1,5 @@ -#pragma warning disable SA1600 #pragma warning disable CS1591 +#pragma warning disable SA1600 using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs index 52d60c004a..7503c5d069 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs @@ -1,52 +1,48 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Common.Configuration; using MediaBrowser.Controller; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Dto; using MediaBrowser.Model.MediaInfo; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv { public class LiveTvMediaSourceProvider : IMediaSourceProvider { + // Do not use a pipe here because Roku http requests to the server will fail, without any explicit error message. + private const char StreamIdDelimeter = '_'; + private const string StreamIdDelimeterString = "_"; + private readonly ILiveTvManager _liveTvManager; - private readonly IJsonSerializer _jsonSerializer; private readonly ILogger _logger; private readonly IMediaSourceManager _mediaSourceManager; - private readonly IMediaEncoder _mediaEncoder; private readonly IServerApplicationHost _appHost; - private IApplicationPaths _appPaths; - public LiveTvMediaSourceProvider(ILiveTvManager liveTvManager, IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILoggerFactory loggerFactory, IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, IServerApplicationHost appHost) + public LiveTvMediaSourceProvider(ILiveTvManager liveTvManager, ILogger logger, IMediaSourceManager mediaSourceManager, IServerApplicationHost appHost) { _liveTvManager = liveTvManager; - _jsonSerializer = jsonSerializer; + _logger = logger; _mediaSourceManager = mediaSourceManager; - _mediaEncoder = mediaEncoder; _appHost = appHost; - _logger = loggerFactory.CreateLogger(GetType().Name); - _appPaths = appPaths; } public Task> GetMediaSources(BaseItem item, CancellationToken cancellationToken) { - var baseItem = (BaseItem)item; - - if (baseItem.SourceType == SourceType.LiveTV) + if (item.SourceType == SourceType.LiveTV) { var activeRecordingInfo = _liveTvManager.GetActiveRecordingInfo(item.Path); - if (string.IsNullOrEmpty(baseItem.Path) || activeRecordingInfo != null) + if (string.IsNullOrEmpty(item.Path) || activeRecordingInfo != null) { return GetMediaSourcesInternal(item, activeRecordingInfo, cancellationToken); } @@ -55,10 +51,6 @@ namespace Emby.Server.Implementations.LiveTv return Task.FromResult>(Array.Empty()); } - // Do not use a pipe here because Roku http requests to the server will fail, without any explicit error message. - private const char StreamIdDelimeter = '_'; - private const string StreamIdDelimeterString = "_"; - private async Task> GetMediaSourcesInternal(BaseItem item, ActiveRecordingInfo activeRecordingInfo, CancellationToken cancellationToken) { IEnumerable sources; @@ -91,7 +83,7 @@ namespace Emby.Server.Implementations.LiveTv foreach (var source in list) { source.Type = MediaSourceType.Default; - source.BufferMs = source.BufferMs ?? 1500; + source.BufferMs ??= 1500; if (source.RequiresOpening || forceRequireOpening) { @@ -100,11 +92,13 @@ namespace Emby.Server.Implementations.LiveTv if (source.RequiresOpening) { - var openKeys = new List(); - openKeys.Add(item.GetType().Name); - openKeys.Add(item.Id.ToString("N", CultureInfo.InvariantCulture)); - openKeys.Add(source.Id ?? string.Empty); - source.OpenToken = string.Join(StreamIdDelimeterString, openKeys.ToArray()); + var openKeys = new List + { + item.GetType().Name, + item.Id.ToString("N", CultureInfo.InvariantCulture), + source.Id ?? string.Empty + }; + source.OpenToken = string.Join(StreamIdDelimeterString, openKeys); } // Dummy this up so that direct play checks can still run @@ -114,7 +108,7 @@ namespace Emby.Server.Implementations.LiveTv } } - _logger.LogDebug("MediaSources: {0}", _jsonSerializer.SerializeToString(list)); + _logger.LogDebug("MediaSources: {@MediaSources}", list); return list; } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs index 715f600a17..419ec3635a 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Concurrent; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 06f27fa3ea..e5cb6c7b9c 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.Globalization; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs index 9702392b29..56864ab116 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Buffers; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index 649becbd3c..77669da39f 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.IO; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs index 862b9fdfed..5354489f9c 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.Globalization; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs index df054f1ebb..46c77e7b0e 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.Globalization; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs index 51f61bac76..511af150bb 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.Globalization; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs index 99244eb625..8615183871 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System; using System.Collections.Generic; using System.IO; From 867835a474d16bfe6ab6a27214de49478ed2a05b Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 8 Feb 2020 22:25:44 +0100 Subject: [PATCH 09/23] Fix build --- .../Api/NotificationsService.cs | 24 +++++++++---------- Emby.Notifications/NotificationEntryPoint.cs | 9 +++++-- Emby.Notifications/NotificationManager.cs | 2 +- .../Activity/ActivityLogEntryPoint.cs | 10 ++++---- .../ApplicationHost.cs | 5 +++- 5 files changed, 28 insertions(+), 22 deletions(-) diff --git a/Emby.Notifications/Api/NotificationsService.cs b/Emby.Notifications/Api/NotificationsService.cs index f9e923d10b..f2f3818381 100644 --- a/Emby.Notifications/Api/NotificationsService.cs +++ b/Emby.Notifications/Api/NotificationsService.cs @@ -22,7 +22,7 @@ namespace Emby.Notifications.Api public class GetNotifications : IReturn { [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] - public string UserId { get; set; } + public string UserId { get; set; } = string.Empty; [ApiMember(Name = "IsRead", Description = "An optional filter by IsRead", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")] public bool? IsRead { get; set; } @@ -36,26 +36,26 @@ namespace Emby.Notifications.Api public class Notification { - public string Id { get; set; } + public string Id { get; set; } = string.Empty; - public string UserId { get; set; } + public string UserId { get; set; } = string.Empty; public DateTime Date { get; set; } public bool IsRead { get; set; } - public string Name { get; set; } + public string Name { get; set; } = string.Empty; - public string Description { get; set; } + public string Description { get; set; } = string.Empty; - public string Url { get; set; } + public string Url { get; set; } = string.Empty; public NotificationLevel Level { get; set; } } public class NotificationResult { - public IReadOnlyList Notifications { get; set; } + public IReadOnlyList Notifications { get; set; } = Array.Empty(); public int TotalRecordCount { get; set; } } @@ -71,7 +71,7 @@ namespace Emby.Notifications.Api public class GetNotificationsSummary : IReturn { [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] - public string UserId { get; set; } + public string UserId { get; set; } = string.Empty; } [Route("/Notifications/Types", "GET", Summary = "Gets notification types")] @@ -107,20 +107,20 @@ namespace Emby.Notifications.Api public class MarkRead : IReturnVoid { [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] - public string UserId { get; set; } + public string UserId { get; set; } = string.Empty; [ApiMember(Name = "Ids", Description = "A list of notification ids, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)] - public string Ids { get; set; } + public string Ids { get; set; } = string.Empty; } [Route("/Notifications/{UserId}/Unread", "POST", Summary = "Marks notifications as unread")] public class MarkUnread : IReturnVoid { [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] - public string UserId { get; set; } + public string UserId { get; set; } = string.Empty; [ApiMember(Name = "Ids", Description = "A list of notification ids, comma delimited", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST", AllowMultiple = true)] - public string Ids { get; set; } + public string Ids { get; set; } = string.Empty; } [Authenticated] diff --git a/Emby.Notifications/NotificationEntryPoint.cs b/Emby.Notifications/NotificationEntryPoint.cs index ab92822fa2..befecc570b 100644 --- a/Emby.Notifications/NotificationEntryPoint.cs +++ b/Emby.Notifications/NotificationEntryPoint.cs @@ -227,7 +227,12 @@ namespace Emby.Notifications } } - private static string GetItemName(BaseItem item) + /// + /// Creates a human readable name for the item. + /// + /// The item. + /// A human readable name for the item. + public static string GetItemName(BaseItem item) { var name = item.Name; if (item is Episode episode) @@ -298,7 +303,7 @@ namespace Emby.Notifications } /// - /// Releases unmanaged and - optionally - managed resources. + /// Releases unmanaged and optionally managed resources. /// /// true to release both managed and unmanaged resources; false to release only unmanaged resources. protected virtual void Dispose(bool disposing) diff --git a/Emby.Notifications/NotificationManager.cs b/Emby.Notifications/NotificationManager.cs index 836aa3e729..639a5e1aad 100644 --- a/Emby.Notifications/NotificationManager.cs +++ b/Emby.Notifications/NotificationManager.cs @@ -32,7 +32,7 @@ namespace Emby.Notifications /// Initializes a new instance of the class. /// /// The logger. - /// the user manager. + /// The user manager. /// The server configuration manager. public NotificationManager( ILogger logger, diff --git a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs index ac8af66a20..4664eadd3a 100644 --- a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs +++ b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs @@ -29,7 +29,7 @@ using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Activity { - public class ActivityLogEntryPoint : IServerEntryPoint + public sealed class ActivityLogEntryPoint : IServerEntryPoint { private readonly ILogger _logger; private readonly IInstallationManager _installationManager; @@ -39,7 +39,6 @@ namespace Emby.Server.Implementations.Activity private readonly ILocalizationManager _localization; private readonly ISubtitleManager _subManager; private readonly IUserManager _userManager; - private readonly IServerApplicationHost _appHost; private readonly IDeviceManager _deviceManager; /// @@ -64,8 +63,7 @@ namespace Emby.Server.Implementations.Activity ILocalizationManager localization, IInstallationManager installationManager, ISubtitleManager subManager, - IUserManager userManager, - IServerApplicationHost appHost) + IUserManager userManager) { _logger = logger; _sessionManager = sessionManager; @@ -76,7 +74,6 @@ namespace Emby.Server.Implementations.Activity _installationManager = installationManager; _subManager = subManager; _userManager = userManager; - _appHost = appHost; } public Task RunAsync() @@ -141,7 +138,7 @@ namespace Emby.Server.Implementations.Activity CultureInfo.InvariantCulture, _localization.GetLocalizedString("SubtitleDownloadFailureFromForItem"), e.Provider, - Notifications.Notifications.GetItemName(e.Item)), + Emby.Notifications.NotificationEntryPoint.GetItemName(e.Item)), Type = "SubtitleDownloadFailure", ItemId = e.Item.Id.ToString("N", CultureInfo.InvariantCulture), ShortOverview = e.Exception.Message @@ -533,6 +530,7 @@ namespace Emby.Server.Implementations.Activity private void CreateLogEntry(ActivityLogEntry entry) => _activityManager.Create(entry); + /// public void Dispose() { _taskManager.TaskCompleted -= OnTaskCompleted; diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index e2df8877ab..91e635b467 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -825,7 +825,10 @@ namespace Emby.Server.Implementations UserViewManager = new UserViewManager(LibraryManager, LocalizationManager, UserManager, ChannelManager, LiveTvManager, ServerConfigurationManager); serviceCollection.AddSingleton(UserViewManager); - NotificationManager = new NotificationManager(LoggerFactory, UserManager, ServerConfigurationManager); + NotificationManager = new NotificationManager( + LoggerFactory.CreateLogger(), + UserManager, + ServerConfigurationManager); serviceCollection.AddSingleton(NotificationManager); serviceCollection.AddSingleton(new DeviceDiscovery(ServerConfigurationManager)); From 184ad29f3f5a579b38ce01d88bf22ad9dc229617 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 19 Feb 2020 21:04:28 +0100 Subject: [PATCH 10/23] Address comments --- .../EntryPoints/RecordingNotifier.cs | 17 +++++++---------- .../LiveTv/LiveTvMediaSourceProvider.cs | 2 ++ .../Library/IMediaSourceProvider.cs | 3 +++ 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs index eecc2c5297..9603d79761 100644 --- a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs @@ -28,10 +28,11 @@ namespace Emby.Server.Implementations.EntryPoints _liveTvManager = liveTvManager; } + /// public Task RunAsync() { - _liveTvManager.TimerCancelled += LiveTvManagerTimerCancelled; - _liveTvManager.SeriesTimerCancelled += LiveTvManagerSeriesTimerCancelled; + _liveTvManager.TimerCancelled += OnLiveTvManagerTimerCancelled; + _liveTvManager.SeriesTimerCancelled += OnLiveTvManagerSeriesTimerCancelled; _liveTvManager.TimerCreated += OnLiveTvManagerTimerCreated; _liveTvManager.SeriesTimerCreated += OnLiveTvManagerSeriesTimerCreated; @@ -48,12 +49,12 @@ namespace Emby.Server.Implementations.EntryPoints SendMessage("TimerCreated", e.Argument); } - private void LiveTvManagerSeriesTimerCancelled(object sender, MediaBrowser.Model.Events.GenericEventArgs e) + private void OnLiveTvManagerSeriesTimerCancelled(object sender, MediaBrowser.Model.Events.GenericEventArgs e) { SendMessage("SeriesTimerCancelled", e.Argument); } - private void LiveTvManagerTimerCancelled(object sender, MediaBrowser.Model.Events.GenericEventArgs e) + private void OnLiveTvManagerTimerCancelled(object sender, MediaBrowser.Model.Events.GenericEventArgs e) { SendMessage("TimerCancelled", e.Argument); } @@ -66,10 +67,6 @@ namespace Emby.Server.Implementations.EntryPoints { await _sessionManager.SendMessageToUserSessions(users, name, info, CancellationToken.None).ConfigureAwait(false); } - catch (ObjectDisposedException) - { - // TODO Log exception or Investigate and properly fix. - } catch (Exception ex) { _logger.LogError(ex, "Error sending message"); @@ -79,8 +76,8 @@ namespace Emby.Server.Implementations.EntryPoints /// public void Dispose() { - _liveTvManager.TimerCancelled -= LiveTvManagerTimerCancelled; - _liveTvManager.SeriesTimerCancelled -= LiveTvManagerSeriesTimerCancelled; + _liveTvManager.TimerCancelled -= OnLiveTvManagerTimerCancelled; + _liveTvManager.SeriesTimerCancelled -= OnLiveTvManagerSeriesTimerCancelled; _liveTvManager.TimerCreated -= OnLiveTvManagerTimerCreated; _liveTvManager.SeriesTimerCreated -= OnLiveTvManagerSeriesTimerCreated; } diff --git a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs index 7503c5d069..33887bbfd2 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs @@ -98,6 +98,7 @@ namespace Emby.Server.Implementations.LiveTv item.Id.ToString("N", CultureInfo.InvariantCulture), source.Id ?? string.Empty }; + source.OpenToken = string.Join(StreamIdDelimeterString, openKeys); } @@ -113,6 +114,7 @@ namespace Emby.Server.Implementations.LiveTv return list; } + /// public async Task OpenMediaSource(string openToken, List currentLiveStreams, CancellationToken cancellationToken) { var keys = openToken.Split(new[] { StreamIdDelimeter }, 3); diff --git a/MediaBrowser.Controller/Library/IMediaSourceProvider.cs b/MediaBrowser.Controller/Library/IMediaSourceProvider.cs index 9e74879fc3..ec7798551b 100644 --- a/MediaBrowser.Controller/Library/IMediaSourceProvider.cs +++ b/MediaBrowser.Controller/Library/IMediaSourceProvider.cs @@ -1,3 +1,6 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1600 + using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; From 620047ab9adeea5fc0d38f51990d456b1300b968 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 19 Feb 2020 22:35:40 +0100 Subject: [PATCH 11/23] Fix episode parsing --- Emby.Naming/Common/NamingOptions.cs | 2 +- .../TV/EpisodeNumberTests.cs | 19 ++++++++++++++++--- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 1554e61d83..b4f22ed696 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -277,7 +277,7 @@ namespace Emby.Naming.Common // This isn't a Kodi naming rule, but the expression below causes false positives, // so we make sure this one gets tested first. // "Foo Bar 889" - new EpisodeExpression(@".*[\\\/](?![Ee]pisode)(?[\w\s]+?)\s(?\d{1,3})(-(?\d{2,3}))*[^\\\/]*$") + new EpisodeExpression(@".*[\\\/](?![Ee]pisode)(?[\w\s]+?)\s(?\d{1,3})(-(?\d{2,3}))*[^\\\/x]*$") { IsNamed = true }, diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs index 93c59c9cab..fe6f1515c0 100644 --- a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs @@ -6,6 +6,21 @@ namespace Jellyfin.Naming.Tests.TV { public class EpisodeNumberTests { + private readonly NamingOptions _namingOptions = new NamingOptions(); + + [Theory] + [InlineData("Watchmen (2019)/Watchmen 1x03 [WEBDL-720p][EAC3 5.1][h264][-TBS] - She Was Killed by Space Junk.mkv", 3)] + [InlineData("The Daily Show/The Daily Show 25x22 - [WEBDL-720p][AAC 2.0][x264] Noah Baumbach-TBS.mkv", 22)] + [InlineData("Castle Rock 2x01 Que el rio siga su curso [WEB-DL HULU 1080p h264 Dual DD5.1 Subs].mkv", 1)] + [InlineData("'After Life 1x06 Episodio 6 [WEB-DL NF 1080p h264 Dual DD 5.1 Sub].mkv", 6)] + public void GetEpisodeNumberFromFileTest(string path, int? expected) + { + var result = new EpisodePathParser(_namingOptions) + .Parse(path, false); + + Assert.Equal(expected, result.EpisodeNumber); + } + [Fact] public void TestEpisodeNumber1() { @@ -382,9 +397,7 @@ namespace Jellyfin.Naming.Tests.TV private int? GetEpisodeNumberFromFile(string path) { - var options = new NamingOptions(); - - var result = new EpisodePathParser(options) + var result = new EpisodePathParser(_namingOptions) .Parse(path, false); return result.EpisodeNumber; From dfd74adc15a1f90f2e7ae6050a563bdbef581ee2 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 19 Feb 2020 22:51:30 +0100 Subject: [PATCH 12/23] Add test --- .../TV/SeasonNumberTests.cs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/tests/Jellyfin.Naming.Tests/TV/SeasonNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/SeasonNumberTests.cs index ba3c5ecac9..1df28c974c 100644 --- a/tests/Jellyfin.Naming.Tests/TV/SeasonNumberTests.cs +++ b/tests/Jellyfin.Naming.Tests/TV/SeasonNumberTests.cs @@ -6,11 +6,21 @@ namespace Jellyfin.Naming.Tests.TV { public class SeasonNumberTests { + private readonly NamingOptions _namingOptions = new NamingOptions(); + + [Theory] + [InlineData("The Daily Show/The Daily Show 25x22 - [WEBDL-720p][AAC 2.0][x264] Noah Baumbach-TBS.mkv", 25)] + public void GetSeasonNumberFromEpisodeFileTest(string path, int? expected) + { + var result = new EpisodeResolver(_namingOptions) + .Resolve(path, false); + + Assert.Equal(expected, result.SeasonNumber); + } + private int? GetSeasonNumberFromEpisodeFile(string path) { - var options = new NamingOptions(); - - var result = new EpisodeResolver(options) + var result = new EpisodeResolver(_namingOptions) .Resolve(path, false); return result.SeasonNumber; From adc9fc282cf94adbfb48b3680246105b55d24ff5 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 19 Feb 2020 21:56:35 +0100 Subject: [PATCH 13/23] Minor improvements --- Emby.Naming/Audio/AudioFileParser.cs | 13 +---- Emby.Naming/TV/SeasonPathParser.cs | 44 +++++++------- Emby.Naming/Video/ExtraResolver.cs | 2 +- Emby.Naming/Video/StackResolver.cs | 4 +- .../Data/SqliteItemRepository.cs | 49 ++++++++-------- .../Devices/DeviceManager.cs | 15 ++--- .../Library/LibraryManager.cs | 57 +++++++++---------- .../Library/Resolvers/Audio/AudioResolver.cs | 6 +- .../Resolvers/Audio/MusicAlbumResolver.cs | 12 ++-- .../Resolvers/Audio/MusicArtistResolver.cs | 7 ++- .../Library/Resolvers/BaseVideoResolver.cs | 3 +- .../Library/Resolvers/Movies/MovieResolver.cs | 14 ++--- .../Library/Resolvers/PhotoAlbumResolver.cs | 3 +- .../Library/Resolvers/PhotoResolver.cs | 12 ++-- .../Library/Resolvers/TV/SeriesResolver.cs | 18 +----- .../Library/ILibraryManager.cs | 6 +- MediaBrowser.Model/Querying/QueryResult.cs | 6 ++ 17 files changed, 122 insertions(+), 149 deletions(-) diff --git a/Emby.Naming/Audio/AudioFileParser.cs b/Emby.Naming/Audio/AudioFileParser.cs index 9f21e93dc4..748622102f 100644 --- a/Emby.Naming/Audio/AudioFileParser.cs +++ b/Emby.Naming/Audio/AudioFileParser.cs @@ -8,19 +8,12 @@ using Emby.Naming.Common; namespace Emby.Naming.Audio { - public class AudioFileParser + public static class AudioFileParser { - private readonly NamingOptions _options; - - public AudioFileParser(NamingOptions options) - { - _options = options; - } - - public bool IsAudioFile(string path) + public static bool IsAudioFile(string path, NamingOptions options) { var extension = Path.GetExtension(path) ?? string.Empty; - return _options.AudioFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase); + return options.AudioFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase); } } } diff --git a/Emby.Naming/TV/SeasonPathParser.cs b/Emby.Naming/TV/SeasonPathParser.cs index 7715a16a45..79fdae5734 100644 --- a/Emby.Naming/TV/SeasonPathParser.cs +++ b/Emby.Naming/TV/SeasonPathParser.cs @@ -4,7 +4,6 @@ using System; using System.Globalization; using System.IO; -using System.Linq; namespace Emby.Naming.TV { @@ -29,14 +28,14 @@ namespace Emby.Naming.TV { var result = new SeasonPathParserResult(); - var seasonNumberInfo = GetSeasonNumberFromPath(path, supportSpecialAliases, supportNumericSeasonFolders); + var (seasonNumber, isSeasonFolder) = GetSeasonNumberFromPath(path, supportSpecialAliases, supportNumericSeasonFolders); - result.SeasonNumber = seasonNumberInfo.seasonNumber; + result.SeasonNumber = seasonNumber; if (result.SeasonNumber.HasValue) { result.Success = true; - result.IsSeasonFolder = seasonNumberInfo.isSeasonFolder; + result.IsSeasonFolder = isSeasonFolder; } return result; @@ -90,12 +89,10 @@ namespace Emby.Naming.TV // Look for one of the season folder names foreach (var name in _seasonFolderNames) { - var index = filename.IndexOf(name, StringComparison.OrdinalIgnoreCase); - - if (index != -1) + if (filename.Contains(name, StringComparison.OrdinalIgnoreCase)) { var result = GetSeasonNumberFromPathSubstring(filename.Replace(name, " ", StringComparison.OrdinalIgnoreCase)); - if (result.Item1.HasValue) + if (result.seasonNumber.HasValue) { return result; } @@ -105,25 +102,32 @@ namespace Emby.Naming.TV } var parts = filename.Split(new[] { '.', '_', ' ', '-' }, StringSplitOptions.RemoveEmptyEntries); - var resultNumber = parts.Select(GetSeasonNumberFromPart).FirstOrDefault(i => i.HasValue); - return (resultNumber, true); + for (int i = 0; i < parts.Length; i++) + { + if (TryGetSeasonNumberFromPart(parts[i], out int seasonNumber)) + { + return (seasonNumber, true); + } + } + + return (null, true); } - private static int? GetSeasonNumberFromPart(string part) + private static bool TryGetSeasonNumberFromPart(ReadOnlySpan part, out int seasonNumber) { + seasonNumber = 0; if (part.Length < 2 || !part.StartsWith("s", StringComparison.OrdinalIgnoreCase)) { - return null; + return false; } - part = part.Substring(1); - - if (int.TryParse(part, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value)) + if (int.TryParse(part.Slice(1), NumberStyles.Integer, CultureInfo.InvariantCulture, out var value)) { - return value; + seasonNumber = value; + return true; } - return null; + return false; } /// @@ -131,7 +135,7 @@ namespace Emby.Naming.TV /// /// The path. /// System.Nullable{System.Int32}. - private static (int? seasonNumber, bool isSeasonFolder) GetSeasonNumberFromPathSubstring(string path) + private static (int? seasonNumber, bool isSeasonFolder) GetSeasonNumberFromPathSubstring(ReadOnlySpan path) { var numericStart = -1; var length = 0; @@ -142,7 +146,7 @@ namespace Emby.Naming.TV // Find out where the numbers start, and then keep going until they end for (var i = 0; i < path.Length; i++) { - if (char.IsNumber(path, i)) + if (char.IsNumber(path[i])) { if (!hasOpenParenth) { @@ -177,7 +181,7 @@ namespace Emby.Naming.TV return (null, isSeasonFolder); } - return (int.Parse(path.Substring(numericStart, length), CultureInfo.InvariantCulture), isSeasonFolder); + return (int.Parse(path.Slice(numericStart, length), provider: CultureInfo.InvariantCulture), isSeasonFolder); } } } diff --git a/Emby.Naming/Video/ExtraResolver.cs b/Emby.Naming/Video/ExtraResolver.cs index ea9a6d6c2a..3e5d473ecc 100644 --- a/Emby.Naming/Video/ExtraResolver.cs +++ b/Emby.Naming/Video/ExtraResolver.cs @@ -32,7 +32,7 @@ namespace Emby.Naming.Video if (rule.MediaType == MediaType.Audio) { - if (!new AudioFileParser(_options).IsAudioFile(path)) + if (!AudioFileParser.IsAudioFile(path, _options)) { return result; } diff --git a/Emby.Naming/Video/StackResolver.cs b/Emby.Naming/Video/StackResolver.cs index 8f210fa453..b9afe998b7 100644 --- a/Emby.Naming/Video/StackResolver.cs +++ b/Emby.Naming/Video/StackResolver.cs @@ -194,7 +194,7 @@ namespace Emby.Naming.Video } } - private string GetRegexInput(FileSystemMetadata file) + private static string GetRegexInput(FileSystemMetadata file) { // For directories, dummy up an extension otherwise the expressions will fail var input = !file.IsDirectory @@ -204,7 +204,7 @@ namespace Emby.Naming.Video return Path.GetFileName(input); } - private Match FindMatch(FileSystemMetadata input, Regex regex, int offset) + private static Match FindMatch(FileSystemMetadata input, Regex regex, int offset) { var regexInput = GetRegexInput(input); diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index c514846e58..44f38504ab 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -3521,20 +3521,6 @@ namespace Emby.Server.Implementations.Data } var includeTypes = query.IncludeItemTypes.SelectMany(MapIncludeItemTypes).ToArray(); - if (includeTypes.Length == 1) - { - whereClauses.Add("type=@type"); - if (statement != null) - { - statement.TryBind("@type", includeTypes[0]); - } - } - else if (includeTypes.Length > 1) - { - var inClause = string.Join(",", includeTypes.Select(i => "'" + i + "'")); - whereClauses.Add($"type in ({inClause})"); - } - // Only specify excluded types if no included types are specified if (includeTypes.Length == 0) { @@ -3553,6 +3539,19 @@ namespace Emby.Server.Implementations.Data whereClauses.Add($"type not in ({inClause})"); } } + else if (includeTypes.Length == 1) + { + whereClauses.Add("type=@type"); + if (statement != null) + { + statement.TryBind("@type", includeTypes[0]); + } + } + else if (includeTypes.Length > 1) + { + var inClause = string.Join(",", includeTypes.Select(i => "'" + i + "'")); + whereClauses.Add($"type in ({inClause})"); + } if (query.ChannelIds.Length == 1) { @@ -4927,7 +4926,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type // Not crazy about having this all the way down here, but at least it's in one place readonly Dictionary _types = GetTypeMapDictionary(); - private IEnumerable MapIncludeItemTypes(string value) + private string[] MapIncludeItemTypes(string value) { if (_types.TryGetValue(value, out string[] result)) { @@ -5611,32 +5610,32 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type return counts; } - private List> GetItemValuesToSave(BaseItem item, List inheritedTags) + private List<(int, string)> GetItemValuesToSave(BaseItem item, List inheritedTags) { - var list = new List>(); + var list = new List<(int, string)>(); if (item is IHasArtist hasArtist) { - list.AddRange(hasArtist.Artists.Select(i => new Tuple(0, i))); + list.AddRange(hasArtist.Artists.Select(i => (0, i))); } if (item is IHasAlbumArtist hasAlbumArtist) { - list.AddRange(hasAlbumArtist.AlbumArtists.Select(i => new Tuple(1, i))); + list.AddRange(hasAlbumArtist.AlbumArtists.Select(i => (1, i))); } - list.AddRange(item.Genres.Select(i => new Tuple(2, i))); - list.AddRange(item.Studios.Select(i => new Tuple(3, i))); - list.AddRange(item.Tags.Select(i => new Tuple(4, i))); + list.AddRange(item.Genres.Select(i => (2, i))); + list.AddRange(item.Studios.Select(i => (3, i))); + list.AddRange(item.Tags.Select(i => (4, i))); // keywords was 5 - list.AddRange(inheritedTags.Select(i => new Tuple(6, i))); + list.AddRange(inheritedTags.Select(i => (6, i))); return list; } - private void UpdateItemValues(Guid itemId, List> values, IDatabaseConnection db) + private void UpdateItemValues(Guid itemId, List<(int, string)> values, IDatabaseConnection db) { if (itemId.Equals(Guid.Empty)) { @@ -5658,7 +5657,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type InsertItemValues(guidBlob, values, db); } - private void InsertItemValues(byte[] idBlob, List> values, IDatabaseConnection db) + private void InsertItemValues(byte[] idBlob, List<(int, string)> values, IDatabaseConnection db) { var startIndex = 0; var limit = 100; diff --git a/Emby.Server.Implementations/Devices/DeviceManager.cs b/Emby.Server.Implementations/Devices/DeviceManager.cs index 2bd0b840a5..4f8f9f23b3 100644 --- a/Emby.Server.Implementations/Devices/DeviceManager.cs +++ b/Emby.Server.Implementations/Devices/DeviceManager.cs @@ -142,11 +142,10 @@ namespace Emby.Server.Implementations.Devices public QueryResult GetDevices(DeviceQuery query) { - var sessions = _authRepo.Get(new AuthenticationInfoQuery + IEnumerable sessions = _authRepo.Get(new AuthenticationInfoQuery { //UserId = query.UserId HasUser = true - }).Items; // TODO: DeviceQuery doesn't seem to be used from client. Not even Swagger. @@ -154,23 +153,19 @@ namespace Emby.Server.Implementations.Devices { var val = query.SupportsSync.Value; - sessions = sessions.Where(i => GetCapabilities(i.DeviceId).SupportsSync == val).ToArray(); + sessions = sessions.Where(i => GetCapabilities(i.DeviceId).SupportsSync == val); } if (!query.UserId.Equals(Guid.Empty)) { var user = _userManager.GetUserById(query.UserId); - sessions = sessions.Where(i => CanAccessDevice(user, i.DeviceId)).ToArray(); + sessions = sessions.Where(i => CanAccessDevice(user, i.DeviceId)); } var array = sessions.Select(ToDeviceInfo).ToArray(); - return new QueryResult - { - Items = array, - TotalRecordCount = array.Length - }; + return new QueryResult(array); } private DeviceInfo ToDeviceInfo(AuthenticationInfo authInfo) @@ -186,7 +181,7 @@ namespace Emby.Server.Implementations.Devices LastUserName = authInfo.UserName, Name = authInfo.DeviceName, DateLastActivity = authInfo.DateLastActivity, - IconUrl = caps == null ? null : caps.IconUrl + IconUrl = caps?.IconUrl }; } diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index d983c1dc63..8f3128245e 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -1169,7 +1169,6 @@ namespace Emby.Server.Implementations.Library return _fileSystem.GetDirectoryPaths(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath) .Select(dir => GetVirtualFolderInfo(dir, topLibraryFolders, refreshQueue)) - .OrderBy(i => i.Name) .ToList(); } @@ -1401,25 +1400,32 @@ namespace Emby.Server.Implementations.Library private void SetTopParentOrAncestorIds(InternalItemsQuery query) { - if (query.AncestorIds.Length == 0) + var ancestorIds = query.AncestorIds; + int len = ancestorIds.Length; + if (len == 0) { return; } - var parents = query.AncestorIds.Select(i => GetItemById(i)).ToList(); - - if (parents.All(i => i is ICollectionFolder || i is UserView)) + var parents = new BaseItem[len]; + for (int i = 0; i < len; i++) { - // Optimize by querying against top level views - query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray(); - query.AncestorIds = Array.Empty(); - - // Prevent searching in all libraries due to empty filter - if (query.TopParentIds.Length == 0) + parents[i] = GetItemById(ancestorIds[i]); + if (!(parents[i] is ICollectionFolder || parents[i] is UserView)) { - query.TopParentIds = new[] { Guid.NewGuid() }; + return; } } + + // Optimize by querying against top level views + query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray(); + query.AncestorIds = Array.Empty(); + + // Prevent searching in all libraries due to empty filter + if (query.TopParentIds.Length == 0) + { + query.TopParentIds = new[] { Guid.NewGuid() }; + } } public QueryResult<(BaseItem, ItemCounts)> GetAlbumArtists(InternalItemsQuery query) @@ -1580,7 +1586,7 @@ namespace Emby.Server.Implementations.Library public async Task> GetIntros(BaseItem item, User user) { var tasks = IntroProviders - .OrderBy(i => i.GetType().Name.IndexOf("Default", StringComparison.OrdinalIgnoreCase) == -1 ? 0 : 1) + .OrderBy(i => i.GetType().Name.Contains("Default", StringComparison.OrdinalIgnoreCase) ? 1 : 0) .Take(1) .Select(i => GetIntros(i, item, user)); @@ -2358,33 +2364,22 @@ namespace Emby.Server.Implementations.Library new SubtitleResolver(BaseItem.LocalizationManager, _fileSystem).AddExternalSubtitleStreams(streams, videoPath, streams.Count, files); } - public bool IsVideoFile(string path, LibraryOptions libraryOptions) + /// + public bool IsVideoFile(string path) { var resolver = new VideoResolver(GetNamingOptions()); return resolver.IsVideoFile(path); } - public bool IsVideoFile(string path) - { - return IsVideoFile(path, new LibraryOptions()); - } - - public bool IsAudioFile(string path, LibraryOptions libraryOptions) - { - var parser = new AudioFileParser(GetNamingOptions()); - return parser.IsAudioFile(path); - } - + /// public bool IsAudioFile(string path) - { - return IsAudioFile(path, new LibraryOptions()); - } + => AudioFileParser.IsAudioFile(path, GetNamingOptions()); + /// public int? GetSeasonNumberFromPath(string path) - { - return SeasonPathParser.Parse(path, true, true).SeasonNumber; - } + => SeasonPathParser.Parse(path, true, true).SeasonNumber; + /// public bool FillMissingEpisodeNumbersFromPath(Episode episode, bool forceRefresh) { var series = episode.Series; diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs index 7e3b27a123..524fb7c109 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs @@ -73,7 +73,6 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio { // Return audio if the path is a file and has a matching extension - var libraryOptions = args.GetLibraryOptions(); var collectionType = args.GetCollectionType(); var isBooksCollectionType = string.Equals(collectionType, CollectionType.Books, StringComparison.OrdinalIgnoreCase); @@ -92,7 +91,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio return FindAudio(args, args.Path, args.Parent, files, args.DirectoryService, collectionType, false); } - if (LibraryManager.IsAudioFile(args.Path, libraryOptions)) + if (LibraryManager.IsAudioFile(args.Path)) { var extension = Path.GetExtension(args.Path); @@ -105,7 +104,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio var isMixedCollectionType = string.IsNullOrEmpty(collectionType); // For conflicting extensions, give priority to videos - if (isMixedCollectionType && LibraryManager.IsVideoFile(args.Path, libraryOptions)) + if (isMixedCollectionType && LibraryManager.IsVideoFile(args.Path)) { return null; } @@ -121,7 +120,6 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio { item = new MediaBrowser.Controller.Entities.Audio.Audio(); } - else if (isBooksCollectionType) { item = new AudioBook(); diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs index 9f858f98dd..85b1b6e323 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs @@ -5,7 +5,6 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Resolvers; -using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using Microsoft.Extensions.Logging; @@ -78,9 +77,9 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio /// /// Determine if the supplied file data points to a music album. /// - public bool IsMusicAlbum(string path, IDirectoryService directoryService, LibraryOptions libraryOptions) + public bool IsMusicAlbum(string path, IDirectoryService directoryService) { - return ContainsMusic(directoryService.GetFileSystemEntries(path), true, directoryService, _logger, _fileSystem, libraryOptions, _libraryManager); + return ContainsMusic(directoryService.GetFileSystemEntries(path), true, directoryService, _logger, _fileSystem, _libraryManager); } /// @@ -94,7 +93,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio if (args.IsDirectory) { // if (args.Parent is MusicArtist) return true; //saves us from testing children twice - if (ContainsMusic(args.FileSystemChildren, true, args.DirectoryService, _logger, _fileSystem, args.GetLibraryOptions(), _libraryManager)) + if (ContainsMusic(args.FileSystemChildren, true, args.DirectoryService, _logger, _fileSystem, _libraryManager)) { return true; } @@ -112,7 +111,6 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio IDirectoryService directoryService, ILogger logger, IFileSystem fileSystem, - LibraryOptions libraryOptions, ILibraryManager libraryManager) { var discSubfolderCount = 0; @@ -132,7 +130,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio } var path = fileSystemInfo.FullName; - var hasMusic = ContainsMusic(directoryService.GetFileSystemEntries(path), false, directoryService, logger, fileSystem, libraryOptions, libraryManager); + var hasMusic = ContainsMusic(directoryService.GetFileSystemEntries(path), false, directoryService, logger, fileSystem, libraryManager); if (hasMusic) { @@ -153,7 +151,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio { var fullName = fileSystemInfo.FullName; - if (libraryManager.IsAudioFile(fullName, libraryOptions)) + if (libraryManager.IsAudioFile(fullName)) { return true; } diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs index ee7e849295..013fdbf138 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs @@ -80,14 +80,17 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio } // Avoid mis-identifying top folders - if (args.Parent.IsRoot) return null; + if (args.Parent.IsRoot) + { + return null; + } var directoryService = args.DirectoryService; var albumResolver = new MusicAlbumResolver(_logger, _fileSystem, _libraryManager); // If we contain an album assume we are an artist folder - return args.FileSystemChildren.Where(i => i.IsDirectory).Any(i => albumResolver.IsMusicAlbum(i.FullName, directoryService, args.GetLibraryOptions())) ? new MusicArtist() : null; + return args.FileSystemChildren.Where(i => i.IsDirectory).Any(i => albumResolver.IsMusicAlbum(i.FullName, directoryService)) ? new MusicArtist() : null; } } } diff --git a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs index 43302bb3fe..848cdb7bd3 100644 --- a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs @@ -80,6 +80,7 @@ namespace Emby.Server.Implementations.Library.Resolvers }; break; } + if (IsBluRayDirectory(child.FullName, filename, args.DirectoryService)) { videoInfo = parser.ResolveDirectory(args.Path); @@ -137,7 +138,7 @@ namespace Emby.Server.Implementations.Library.Resolvers return null; } - if (LibraryManager.IsVideoFile(args.Path, args.GetLibraryOptions()) || videoInfo.IsStub) + if (LibraryManager.IsVideoFile(args.Path) || videoInfo.IsStub) { var path = args.Path; diff --git a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs index 08db168bc3..cb67c8aa7c 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs @@ -436,7 +436,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies if (result.Items.Count == 1) { var videoPath = result.Items[0].Path; - var hasPhotos = photos.Any(i => !PhotoResolver.IsOwnedByResolvedMedia(LibraryManager, libraryOptions, videoPath, i.Name)); + var hasPhotos = photos.Any(i => !PhotoResolver.IsOwnedByResolvedMedia(LibraryManager, videoPath, i.Name)); if (!hasPhotos) { @@ -446,8 +446,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies return movie; } } - - if (result.Items.Count == 0 && multiDiscFolders.Count > 0) + else if (result.Items.Count == 0 && multiDiscFolders.Count > 0) { return GetMultiDiscMovie(multiDiscFolders, directoryService); } @@ -519,14 +518,15 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies return null; } + int additionalPartsLen = folderPaths.Count - 1; + var additionalParts = new string[additionalPartsLen]; + folderPaths.CopyTo(1, additionalParts, 0, additionalPartsLen); + var returnVideo = new T { Path = folderPaths[0], - - AdditionalParts = folderPaths.Skip(1).ToArray(), - + AdditionalParts = additionalParts, VideoType = videoTypes[0], - Name = result[0].Name }; diff --git a/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs index 4536b0aaa8..3ac837057a 100644 --- a/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs @@ -63,13 +63,12 @@ namespace Emby.Server.Implementations.Library.Resolvers { if (!file.IsDirectory && PhotoResolver.IsImageFile(file.FullName, _imageProcessor)) { - var libraryOptions = args.GetLibraryOptions(); var filename = file.Name; var ownedByMedia = false; foreach (var siblingFile in files) { - if (PhotoResolver.IsOwnedByMedia(_libraryManager, libraryOptions, siblingFile.FullName, filename)) + if (PhotoResolver.IsOwnedByMedia(_libraryManager, siblingFile.FullName, filename)) { ownedByMedia = true; break; diff --git a/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs index e1eb23652d..8ad546f8ee 100644 --- a/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs @@ -8,7 +8,6 @@ using System.Linq; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; namespace Emby.Server.Implementations.Library.Resolvers @@ -57,11 +56,10 @@ namespace Emby.Server.Implementations.Library.Resolvers // Make sure the image doesn't belong to a video file var files = args.DirectoryService.GetFiles(Path.GetDirectoryName(args.Path)); - var libraryOptions = args.GetLibraryOptions(); foreach (var file in files) { - if (IsOwnedByMedia(_libraryManager, libraryOptions, file.FullName, filename)) + if (IsOwnedByMedia(_libraryManager, file.FullName, filename)) { return null; } @@ -78,17 +76,17 @@ namespace Emby.Server.Implementations.Library.Resolvers return null; } - internal static bool IsOwnedByMedia(ILibraryManager libraryManager, LibraryOptions libraryOptions, string file, string imageFilename) + internal static bool IsOwnedByMedia(ILibraryManager libraryManager, string file, string imageFilename) { - if (libraryManager.IsVideoFile(file, libraryOptions)) + if (libraryManager.IsVideoFile(file)) { - return IsOwnedByResolvedMedia(libraryManager, libraryOptions, file, imageFilename); + return IsOwnedByResolvedMedia(libraryManager, file, imageFilename); } return false; } - internal static bool IsOwnedByResolvedMedia(ILibraryManager libraryManager, LibraryOptions libraryOptions, string file, string imageFilename) + internal static bool IsOwnedByResolvedMedia(ILibraryManager libraryManager, string file, string imageFilename) => imageFilename.StartsWith(Path.GetFileNameWithoutExtension(file), StringComparison.OrdinalIgnoreCase); internal static bool IsImageFile(string path, IImageProcessor imageProcessor) diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs index 4ee30b4758..b547fc8c91 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs @@ -102,7 +102,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV return null; } - if (IsSeriesFolder(args.Path, args.FileSystemChildren, args.DirectoryService, _fileSystem, _logger, _libraryManager, args.GetLibraryOptions(), false)) + if (IsSeriesFolder(args.Path, args.FileSystemChildren, args.DirectoryService, _fileSystem, _logger, _libraryManager, false)) { return new Series { @@ -123,24 +123,10 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV IFileSystem fileSystem, ILogger logger, ILibraryManager libraryManager, - LibraryOptions libraryOptions, bool isTvContentType) { foreach (var child in fileSystemChildren) { - //if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden) - //{ - // //logger.LogDebug("Igoring series file or folder marked hidden: {0}", child.FullName); - // continue; - //} - - // Can't enforce this because files saved by Bitcasa are always marked System - //if ((attributes & FileAttributes.System) == FileAttributes.System) - //{ - // logger.LogDebug("Igoring series subfolder marked system: {0}", child.FullName); - // continue; - //} - if (child.IsDirectory) { if (IsSeasonFolder(child.FullName, isTvContentType, libraryManager)) @@ -152,7 +138,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV else { string fullName = child.FullName; - if (libraryManager.IsVideoFile(fullName, libraryOptions)) + if (libraryManager.IsVideoFile(fullName)) { if (isTvContentType) { diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index 511356aa4e..2e1c97f674 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -157,7 +157,8 @@ namespace MediaBrowser.Controller.Library /// The intro providers. /// The item comparers. /// The postscan tasks. - void AddParts(IEnumerable rules, + void AddParts( + IEnumerable rules, IEnumerable resolvers, IEnumerable introProviders, IEnumerable itemComparers, @@ -349,9 +350,6 @@ namespace MediaBrowser.Controller.Library /// true if [is audio file] [the specified path]; otherwise, false. bool IsAudioFile(string path); - bool IsAudioFile(string path, LibraryOptions libraryOptions); - bool IsVideoFile(string path, LibraryOptions libraryOptions); - /// /// Gets the season number from path. /// diff --git a/MediaBrowser.Model/Querying/QueryResult.cs b/MediaBrowser.Model/Querying/QueryResult.cs index ad89ae38d5..5d4d6226be 100644 --- a/MediaBrowser.Model/Querying/QueryResult.cs +++ b/MediaBrowser.Model/Querying/QueryResult.cs @@ -30,5 +30,11 @@ namespace MediaBrowser.Model.Querying { Items = Array.Empty(); } + + public QueryResult(IReadOnlyList items) + { + Items = items; + TotalRecordCount = items.Count; + } } } From 7df6d4e7a09faf54fb7b907fd40fed2eb354f813 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Thu, 20 Feb 2020 12:02:45 +0100 Subject: [PATCH 14/23] Update EpisodeNumberTests.cs --- tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs index fe6f1515c0..5017fce4d9 100644 --- a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs @@ -12,7 +12,7 @@ namespace Jellyfin.Naming.Tests.TV [InlineData("Watchmen (2019)/Watchmen 1x03 [WEBDL-720p][EAC3 5.1][h264][-TBS] - She Was Killed by Space Junk.mkv", 3)] [InlineData("The Daily Show/The Daily Show 25x22 - [WEBDL-720p][AAC 2.0][x264] Noah Baumbach-TBS.mkv", 22)] [InlineData("Castle Rock 2x01 Que el rio siga su curso [WEB-DL HULU 1080p h264 Dual DD5.1 Subs].mkv", 1)] - [InlineData("'After Life 1x06 Episodio 6 [WEB-DL NF 1080p h264 Dual DD 5.1 Sub].mkv", 6)] + [InlineData("After Life 1x06 Episodio 6 [WEB-DL NF 1080p h264 Dual DD 5.1 Sub].mkv", 6)] public void GetEpisodeNumberFromFileTest(string path, int? expected) { var result = new EpisodePathParser(_namingOptions) From b02a3a29f52326bc278448266045eb4240cc07f2 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Thu, 20 Feb 2020 15:30:04 +0100 Subject: [PATCH 15/23] Fix photo serialization --- MediaBrowser.Controller/Entities/Photo.cs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/MediaBrowser.Controller/Entities/Photo.cs b/MediaBrowser.Controller/Entities/Photo.cs index 86d62add97..5ebc9f16ad 100644 --- a/MediaBrowser.Controller/Entities/Photo.cs +++ b/MediaBrowser.Controller/Entities/Photo.cs @@ -41,10 +41,10 @@ namespace MediaBrowser.Controller.Entities public override double GetDefaultPrimaryImageAspectRatio() { // REVIEW: @bond - if (Width.HasValue && Height.HasValue) + if (Width != 0 && Height != 0) { - double width = Width.Value; - double height = Height.Value; + double width = Width; + double height = Height; if (Orientation.HasValue) { @@ -67,8 +67,6 @@ namespace MediaBrowser.Controller.Entities return base.GetDefaultPrimaryImageAspectRatio(); } - public new int? Width { get; set; } - public new int? Height { get; set; } public string CameraMake { get; set; } public string CameraModel { get; set; } public string Software { get; set; } From 583f171f9eec05af22842d50aa5a7f3d30053325 Mon Sep 17 00:00:00 2001 From: R0flcopt3r Date: Fri, 21 Feb 2020 19:29:18 +0000 Subject: [PATCH 16/23] Added translation using Weblate (Norwegian Nynorsk) --- Emby.Server.Implementations/Localization/Core/nn.json | 1 + 1 file changed, 1 insertion(+) create mode 100644 Emby.Server.Implementations/Localization/Core/nn.json diff --git a/Emby.Server.Implementations/Localization/Core/nn.json b/Emby.Server.Implementations/Localization/Core/nn.json new file mode 100644 index 0000000000..0967ef424b --- /dev/null +++ b/Emby.Server.Implementations/Localization/Core/nn.json @@ -0,0 +1 @@ +{} From 804ca0543b1c746a751142edc6525d157da472c9 Mon Sep 17 00:00:00 2001 From: Saksol Date: Fri, 21 Feb 2020 03:39:27 +0000 Subject: [PATCH 17/23] Translated using Weblate (Icelandic) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/is/ --- .../Localization/Core/is.json | 36 ++++++++++++++----- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/is.json b/Emby.Server.Implementations/Localization/Core/is.json index c3b5211b84..3490a73022 100644 --- a/Emby.Server.Implementations/Localization/Core/is.json +++ b/Emby.Server.Implementations/Localization/Core/is.json @@ -3,7 +3,7 @@ "ItemRemovedWithName": "{0} var fjarlægt úr safninu", "ItemAddedWithName": "{0} var bætt í safnið", "Inherit": "Erfa", - "HomeVideos": "Myndbönd að heiman", + "HomeVideos": "Heimamyndbönd", "HeaderRecordingGroups": "Upptökuhópar", "HeaderNextUp": "Næst á dagskrá", "HeaderLiveTV": "Sjónvarp í beinni útsendingu", @@ -36,10 +36,10 @@ "NotificationOptionVideoPlaybackStopped": "Myndbandafspilun stöðvuð", "NotificationOptionVideoPlayback": "Myndbandafspilun hafin", "NotificationOptionUserLockedOut": "Notandi læstur úti", - "NotificationOptionServerRestartRequired": "Endurræsing miðlara nauðsynileg", + "NotificationOptionServerRestartRequired": "Endurræsing þjóns er nauðsynileg", "NotificationOptionPluginUpdateInstalled": "Viðbótar uppfærsla uppsett", "NotificationOptionPluginUninstalled": "Viðbót fjarlægð", - "NotificationOptionPluginInstalled": "Viðbót settur upp", + "NotificationOptionPluginInstalled": "Viðbót sett upp", "NotificationOptionPluginError": "Bilun í viðbót", "NotificationOptionInstallationFailed": "Uppsetning tókst ekki", "NotificationOptionCameraImageUploaded": "Myndavélarmynd hlaðið upp", @@ -50,15 +50,15 @@ "NameSeasonUnknown": "Sería óþekkt", "NameSeasonNumber": "Sería {0}", "MixedContent": "Blandað efni", - "MessageServerConfigurationUpdated": "Stillingar miðlarans hefur verið uppfærð", - "MessageApplicationUpdatedTo": "Jellyfin Server hefur verið uppfærður í {0}", - "MessageApplicationUpdated": "Jellyfin Server hefur verið uppfærður", + "MessageServerConfigurationUpdated": "Stillingar þjóns hafa verið uppfærðar", + "MessageApplicationUpdatedTo": "Jellyfin þjónn hefur verið uppfærður í {0}", + "MessageApplicationUpdated": "Jellyfin þjónn hefur verið uppfærður", "Latest": "Nýjasta", - "LabelRunningTimeValue": "Keyrslutími kerfis: {0}", + "LabelRunningTimeValue": "spilunartími: {0}", "User": "Notandi", "System": "Kerfi", "NotificationOptionNewLibraryContent": "Nýju efni bætt við", - "NewVersionIsAvailable": "Ný útgáfa af Jellyfin Server er fáanleg til niðurhals.", + "NewVersionIsAvailable": "Ný útgáfa af Jellyfin þjón er fáanleg til niðurhals.", "NameInstallFailed": "{0} uppsetning mistókst", "MusicVideos": "Tónlistarmyndbönd", "Music": "Tónlist", @@ -74,5 +74,23 @@ "PluginUpdatedWithName": "{0} var uppfært", "PluginUninstalledWithName": "{0} var fjarlægt", "PluginInstalledWithName": "{0} var sett upp", - "NotificationOptionTaskFailed": "Tímasett verkefni mistókst" + "NotificationOptionTaskFailed": "Tímasett verkefni mistókst", + "StartupEmbyServerIsLoading": "Jellyfin netþjónnin er að hlaðast. Vinsamlega prufaðu aftur fljótlega.", + "VersionNumber": "Útgáfa {0}", + "ValueHasBeenAddedToLibrary": "{0} hefur verið bætt við í gagnasafnið þitt", + "UserStoppedPlayingItemWithValues": "{0} hefur lokið spilunar af {1} á {2}", + "UserStartedPlayingItemWithValues": "{0} er að spila {1} á {2}", + "UserPolicyUpdatedWithName": "Notandaregla hefur verið uppfærð fyrir notanda {0}", + "UserPasswordChangedWithName": "Lykilorði fyrir notandann {0} hefur verið breytt", + "UserOnlineFromDevice": "{0} hefur verið virkur síðan {1}", + "UserOfflineFromDevice": "{0} hefur aftengst frá {1}", + "UserLockedOutWithName": "Notanda {0} hefur verið hindraður aðgangur", + "UserDownloadingItemWithValues": "{0} Hleður niður {1}", + "SubtitlesDownloadedForItem": "Skjátextum halað niður fyrir {0}", + "SubtitleDownloadFailureFromForItem": "Tókst ekki að hala niður skjátextum frá {0} til {1}", + "ProviderValue": "Veitandi: {0}", + "MessageNamedServerConfigurationUpdatedWithValue": "Stilling {0} hefur verið uppfærð á netþjón", + "ValueSpecialEpisodeName": "Sérstakt - {0}", + "Shows": "Þættir", + "Playlists": "Spilunarlisti" } From ffc9eb67f0422129af05dd2ea6ab2088e80f2550 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 23 Feb 2020 00:05:28 +0100 Subject: [PATCH 18/23] Switch remux and direct stream --- MediaBrowser.Api/Playback/BaseStreamingService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index 7837aa65b0..5029ce0bb7 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -250,11 +250,11 @@ namespace MediaBrowser.Api.Playback { if (string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase)) { - logFilePrefix = "ffmpeg-directstream"; + logFilePrefix = "ffmpeg-remux"; } else { - logFilePrefix = "ffmpeg-remux"; + logFilePrefix = "ffmpeg-directstream"; } } From 21f11c600a51ec15810ae052fa85abf6bafadabf Mon Sep 17 00:00:00 2001 From: Narfinger Date: Sun, 23 Feb 2020 12:12:48 +0900 Subject: [PATCH 19/23] converted tests to inlinedata --- .../TV/EpisodeNumberTests.cs | 434 +++--------------- 1 file changed, 60 insertions(+), 374 deletions(-) diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs index 5017fce4d9..c4dbf304ae 100644 --- a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs @@ -13,6 +13,66 @@ namespace Jellyfin.Naming.Tests.TV [InlineData("The Daily Show/The Daily Show 25x22 - [WEBDL-720p][AAC 2.0][x264] Noah Baumbach-TBS.mkv", 22)] [InlineData("Castle Rock 2x01 Que el rio siga su curso [WEB-DL HULU 1080p h264 Dual DD5.1 Subs].mkv", 1)] [InlineData("After Life 1x06 Episodio 6 [WEB-DL NF 1080p h264 Dual DD 5.1 Sub].mkv", 6)] + [InlineData("Season 02/S02E03 blah.avi", 3)] + [InlineData("Season 2/02x03 - 02x04 - 02x15 - Ep Name.mp4", 3)] + [InlineData("Season 02/02x03 - x04 - x15 - Ep Name.mp4", 3)] + [InlineData("Season 1/01x02 blah.avi", 2)] + [InlineData("Season 1/S01x02 blah.avi", 2)] + [InlineData("Season 1/S01E02 blah.avi", 2)] + [InlineData("Season 2/Elementary - 02x03-04-15 - Ep Name.mp4", 3)] + [InlineData("Season 1/S01xE02 blah.avi", 2)] + [InlineData("Season 1/seriesname S01E02 blah.avi", 2)] + /// This does not seem to be the correct value or is it? + [InlineData("Season 2/[HorribleSubs] Hunter X Hunter - 136 [720p].mkv", 36)] + [InlineData("Season 2/Episode - 16.avi", 16)] + [InlineData("Season 2/Episode 16.avi", 16)] + [InlineData("Season 2/Episode 16 - Some Title.avi", 16)] + [InlineData("Season 2/16 Some Title.avi", 16)] + [InlineData("Season 2/16 - 12 Some Title.avi", 16)] + [InlineData("Season 2/7 - 12 Angry Men.avi", 7)] + [InlineData("Season 2/16 12 Some Title.avi", 16)] + [InlineData("Season 2/7 12 Angry Men.avi", 7)] + [InlineData("Season 4/Uchuu.Senkan.Yamato.2199.E03.avi", 3)] + [InlineData("Running Man/Running Man S2017E368.mkv", 360)] + [InlineData("/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv/The.Legend.of.Condor.Heroes.2017.E07.V2.web-dl.1080p.h264.aac-hdctv.mkv", 7)] + [InlineData("Season 1/seriesname 01x02 blah.avi", 2)] + [InlineData("Season 25/The Simpsons.S25E09.Steal this episode.mp4", 9)] + [InlineData("Season 1/seriesname S01x02 blah.avi", 2)] + [InlineData("Season 2/Elementary - 02x03 - 02x04 - 02x15 - Ep Name.mp4", 3)] + [InlineData("Season 1/seriesname S01xE02 blah.avi", 2)] + [InlineData("Season 02/Elementary - 02x03 - x04 - x15 - Ep Name.mp4", 3)] + [InlineData("Season 02/02x03x04x15 - Ep Name.mp4", 2)] + [InlineData("Season 02/Elementary - 02x03x04x15 - Ep Name.mp4", 3)] + [InlineData("Season 2/02x03-04-15 - Ep Name.mp4", 3)] + [InlineData("Season 02/02x03-E15 - Ep Name.mp4", 3)] + [InlineData("Season 02/Elementary - 02x03-E15 - Ep Name.mp4", 3)] + [InlineData("Season 1/Elementary - S01E23-E24-E26 - The Woman.mp4", 23)] + [InlineData("Season 2009/S2009E23-E24-E26 - The Woman.mp4", 23)] + [InlineData("Season 2009/2009x02 blah.avi", 2)] + [InlineData("Season 2009/S2009x02 blah.avi", 2)] + [InlineData("Season 2009/S2009E02 blah.avi", 2)] + [InlineData("Season 2009/seriesname 2009x02 blah.avi", 2)] + [InlineData("Season 2009/Elementary - 2009x03x04x15 - Ep Name.mp4", 3)] + [InlineData("Season 2009/2009x03x04x15 - Ep Name.mp4", 3)] + [InlineData("Season 2009/Elementary - 2009x03-E15 - Ep Name.mp4", 3)] + [InlineData("Season 2009/S2009xE02 blah.avi", 2)] + [InlineData("Season 2009/Elementary - S2009E23-E24-E26 - The Woman.mp4", 23)] + [InlineData("Season 2009/seriesname S2009xE02 blah.avi", 2)] + [InlineData("Season 2009/2009x03-E15 - Ep Name.mp4", 3)] + [InlineData("Season 2009/seriesname S2009E02 blah.avi", 2)] + [InlineData("Season 2009/2009x03 - 2009x04 - 2009x15 - Ep Name.mp4", 3)] + [InlineData("Season 2009/2009x03 - x04 - x15 - Ep Name.mp4", 3)] + [InlineData("Season 2009/seriesname S2009x02 blah.avi", 2)] + [InlineData("Season 2009/Elementary - 2009x03 - 2009x04 - 2009x15 - Ep Name.mp4", 3)] + [InlineData("Season 2009/Elementary - 2009x03-04-15 - Ep Name.mp4", 3)] + [InlineData("Season 2009/2009x03-04-15 - Ep Name.mp4", 3)] + [InlineData("Season 2009/Elementary - 2009x03 - x04 - x15 - Ep Name.mp4", 3)] + [InlineData("Season 1/02 - blah-02 a.avi", 2)] + [InlineData("Season 1/02 - blah.avi", 2)] + [InlineData("Season 2/02 - blah 14 blah.avi", 2)] + [InlineData("Season 2/02.avi", 2)] + [InlineData("Season 2/2. Infestation.avi", 2)] + [InlineData("The Wonder Years/The.Wonder.Years.S04.PDTV.x264-JCH/The Wonder Years s04e07 Christmas Party NTSC PDTV.avi", 7)] public void GetEpisodeNumberFromFileTest(string path, int? expected) { var result = new EpisodePathParser(_namingOptions) @@ -21,380 +81,6 @@ namespace Jellyfin.Naming.Tests.TV Assert.Equal(expected, result.EpisodeNumber); } - [Fact] - public void TestEpisodeNumber1() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 02/S02E03 blah.avi")); - } - - [Fact] - public void TestEpisodeNumber40() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2/02x03 - 02x04 - 02x15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber41() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/01x02 blah.avi")); - } - - [Fact] - public void TestEpisodeNumber42() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/S01x02 blah.avi")); - } - - [Fact] - public void TestEpisodeNumber43() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/S01E02 blah.avi")); - } - - [Fact] - public void TestEpisodeNumber44() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2/Elementary - 02x03-04-15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber45() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/S01xE02 blah.avi")); - } - - [Fact] - public void TestEpisodeNumber46() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/seriesname S01E02 blah.avi")); - } - - [Fact] - public void TestEpisodeNumber47() - { - Assert.Equal(36, GetEpisodeNumberFromFile(@"Season 2/[HorribleSubs] Hunter X Hunter - 136 [720p].mkv")); - } - - [Fact] - public void TestEpisodeNumber52() - { - Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Episode - 16.avi")); - } - - [Fact] - public void TestEpisodeNumber53() - { - Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Episode 16.avi")); - } - - [Fact] - public void TestEpisodeNumber54() - { - Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/Episode 16 - Some Title.avi")); - } - - [Fact] - public void TestEpisodeNumber57() - { - Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/16 Some Title.avi")); - } - - [Fact] - public void TestEpisodeNumber58() - { - Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/16 - 12 Some Title.avi")); - } - - [Fact] - public void TestEpisodeNumber59() - { - Assert.Equal(7, GetEpisodeNumberFromFile(@"Season 2/7 - 12 Angry Men.avi")); - } - - // FIXME - // [Fact] - public void TestEpisodeNumber60() - { - Assert.Equal(16, GetEpisodeNumberFromFile(@"Season 2/16 12 Some Title.avi")); - } - - // FIXME - // [Fact] - public void TestEpisodeNumber61() - { - Assert.Equal(7, GetEpisodeNumberFromFile(@"Season 2/7 12 Angry Men.avi")); - } - - // FIXME - // [Fact] - public void TestEpisodeNumber62() - { - // This is not supported. Expected to fail, although it would be a good one to add support for. - Assert.Equal(3, GetEpisodeNumberFromFile(@"Season 4/Uchuu.Senkan.Yamato.2199.E03.avi")); - } - - [Fact] - public void TestEpisodeNumber63() - { - Assert.Equal(3, GetEpisodeNumberFromFile(@"Season 4/Uchuu.Senkan.Yamato.2199.S04E03.avi")); - } - - [Fact] - public void TestEpisodeNumber64() - { - Assert.Equal(368, GetEpisodeNumberFromFile(@"Running Man/Running Man S2017E368.mkv")); - } - - // FIXME - // [Fact] - public void TestEpisodeNumber65() - { - // Not supported yet - Assert.Equal(7, GetEpisodeNumberFromFile(@"/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv/The.Legend.of.Condor.Heroes.2017.E07.V2.web-dl.1080p.h264.aac-hdctv.mkv")); - } - - [Fact] - public void TestEpisodeNumber30() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2/02x03 - 02x04 - 02x15 - Ep Name.mp4")); - } - - // FIXME - // [Fact] - public void TestEpisodeNumber31() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/seriesname 01x02 blah.avi")); - } - - [Fact] - public void TestEpisodeNumber32() - { - Assert.Equal(9, GetEpisodeNumberFromFile(@"Season 25/The Simpsons.S25E09.Steal this episode.mp4")); - } - - [Fact] - public void TestEpisodeNumber33() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/seriesname S01x02 blah.avi")); - } - - [Fact] - public void TestEpisodeNumber34() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2/Elementary - 02x03 - 02x04 - 02x15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber35() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/seriesname S01xE02 blah.avi")); - } - - [Fact] - public void TestEpisodeNumber36() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 02/02x03 - x04 - x15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber37() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 02/Elementary - 02x03 - x04 - x15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber38() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 02/02x03x04x15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber39() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 02/Elementary - 02x03x04x15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber20() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2/02x03-04-15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber21() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 02/02x03-E15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber22() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 02/Elementary - 02x03-E15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber23() - { - Assert.Equal(23, GetEpisodeNumberFromFile(@"Season 1/Elementary - S01E23-E24-E26 - The Woman.mp4")); - } - - [Fact] - public void TestEpisodeNumber24() - { - Assert.Equal(23, GetEpisodeNumberFromFile(@"Season 2009/S2009E23-E24-E26 - The Woman.mp4")); - } - - [Fact] - public void TestEpisodeNumber25() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2009/2009x02 blah.avi")); - } - - [Fact] - public void TestEpisodeNumber26() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2009/S2009x02 blah.avi")); - } - - [Fact] - public void TestEpisodeNumber27() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2009/S2009E02 blah.avi")); - } - - // FIXME - // [Fact] - public void TestEpisodeNumber28() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2009/seriesname 2009x02 blah.avi")); - } - - [Fact] - public void TestEpisodeNumber29() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/Elementary - 2009x03x04x15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber11() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/2009x03x04x15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber12() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/Elementary - 2009x03-E15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber13() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2009/S2009xE02 blah.avi")); - } - - [Fact] - public void TestEpisodeNumber14() - { - Assert.Equal(23, GetEpisodeNumberFromFile(@"Season 2009/Elementary - S2009E23-E24-E26 - The Woman.mp4")); - } - - [Fact] - public void TestEpisodeNumber15() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2009/seriesname S2009xE02 blah.avi")); - } - - [Fact] - public void TestEpisodeNumber16() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/2009x03-E15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber17() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2009/seriesname S2009E02 blah.avi")); - } - - [Fact] - public void TestEpisodeNumber18() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/2009x03 - 2009x04 - 2009x15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber19() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/2009x03 - x04 - x15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber2() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2009/seriesname S2009x02 blah.avi")); - } - - [Fact] - public void TestEpisodeNumber3() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/Elementary - 2009x03 - 2009x04 - 2009x15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber4() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/Elementary - 2009x03-04-15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber5() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/2009x03-04-15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber6() - { - Assert.Equal(03, GetEpisodeNumberFromFile(@"Season 2009/Elementary - 2009x03 - x04 - x15 - Ep Name.mp4")); - } - - [Fact] - public void TestEpisodeNumber7() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/02 - blah-02 a.avi")); - } - - [Fact] - public void TestEpisodeNumber8() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 1/02 - blah.avi")); - } - - [Fact] - public void TestEpisodeNumber9() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2/02 - blah 14 blah.avi")); - } - - [Fact] - public void TestEpisodeNumber10() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2/02.avi")); - } - - [Fact] - public void TestEpisodeNumber48() - { - Assert.Equal(02, GetEpisodeNumberFromFile(@"Season 2/2. Infestation.avi")); - } - - [Fact] - public void TestEpisodeNumber49() - { - Assert.Equal(7, GetEpisodeNumberFromFile(@"The Wonder Years/The.Wonder.Years.S04.PDTV.x264-JCH/The Wonder Years s04e07 Christmas Party NTSC PDTV.avi")); - } - private int? GetEpisodeNumberFromFile(string path) { var result = new EpisodePathParser(_namingOptions) From c2fe628c796e7c2525629b39d7eaceaaf4d07ae9 Mon Sep 17 00:00:00 2001 From: Narfinger Date: Sun, 23 Feb 2020 18:19:19 +0900 Subject: [PATCH 20/23] removed failing tests --- .../Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs index c4dbf304ae..4895431ebc 100644 --- a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs @@ -23,25 +23,19 @@ namespace Jellyfin.Naming.Tests.TV [InlineData("Season 1/S01xE02 blah.avi", 2)] [InlineData("Season 1/seriesname S01E02 blah.avi", 2)] /// This does not seem to be the correct value or is it? - [InlineData("Season 2/[HorribleSubs] Hunter X Hunter - 136 [720p].mkv", 36)] + g [InlineData("Season 2/Episode - 16.avi", 16)] [InlineData("Season 2/Episode 16.avi", 16)] [InlineData("Season 2/Episode 16 - Some Title.avi", 16)] [InlineData("Season 2/16 Some Title.avi", 16)] [InlineData("Season 2/16 - 12 Some Title.avi", 16)] [InlineData("Season 2/7 - 12 Angry Men.avi", 7)] - [InlineData("Season 2/16 12 Some Title.avi", 16)] - [InlineData("Season 2/7 12 Angry Men.avi", 7)] - [InlineData("Season 4/Uchuu.Senkan.Yamato.2199.E03.avi", 3)] - [InlineData("Running Man/Running Man S2017E368.mkv", 360)] - [InlineData("/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv/The.Legend.of.Condor.Heroes.2017.E07.V2.web-dl.1080p.h264.aac-hdctv.mkv", 7)] [InlineData("Season 1/seriesname 01x02 blah.avi", 2)] [InlineData("Season 25/The Simpsons.S25E09.Steal this episode.mp4", 9)] [InlineData("Season 1/seriesname S01x02 blah.avi", 2)] [InlineData("Season 2/Elementary - 02x03 - 02x04 - 02x15 - Ep Name.mp4", 3)] [InlineData("Season 1/seriesname S01xE02 blah.avi", 2)] [InlineData("Season 02/Elementary - 02x03 - x04 - x15 - Ep Name.mp4", 3)] - [InlineData("Season 02/02x03x04x15 - Ep Name.mp4", 2)] [InlineData("Season 02/Elementary - 02x03x04x15 - Ep Name.mp4", 3)] [InlineData("Season 2/02x03-04-15 - Ep Name.mp4", 3)] [InlineData("Season 02/02x03-E15 - Ep Name.mp4", 3)] @@ -73,6 +67,12 @@ namespace Jellyfin.Naming.Tests.TV [InlineData("Season 2/02.avi", 2)] [InlineData("Season 2/2. Infestation.avi", 2)] [InlineData("The Wonder Years/The.Wonder.Years.S04.PDTV.x264-JCH/The Wonder Years s04e07 Christmas Party NTSC PDTV.avi", 7)] + //[InlineData("Season 2/16 12 Some Title.avi", 16)] + //[InlineData("Running Man/Running Man S2017E368.mkv", 360)] + //[InlineData("/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv/The.Legend.of.Condor.Heroes.2017.E07.V2.web-dl.1080p.h264.aac-hdctv.mkv", 7)] + //[InlineData("Season 4/Uchuu.Senkan.Yamato.2199.E03.avi", 3)] + //[InlineData("Season 2/7 12 Angry Men.avi", 7)] + //[InlineData("Season 02/02x03x04x15 - Ep Name.mp4", 2)] public void GetEpisodeNumberFromFileTest(string path, int? expected) { var result = new EpisodePathParser(_namingOptions) From 4dabc50f09425fe8011288ee356509cb3095ed59 Mon Sep 17 00:00:00 2001 From: Narfinger Date: Sun, 23 Feb 2020 18:31:23 +0900 Subject: [PATCH 21/23] fixes last tests and cleanup --- tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs index 4895431ebc..a9e6d63432 100644 --- a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs @@ -22,8 +22,6 @@ namespace Jellyfin.Naming.Tests.TV [InlineData("Season 2/Elementary - 02x03-04-15 - Ep Name.mp4", 3)] [InlineData("Season 1/S01xE02 blah.avi", 2)] [InlineData("Season 1/seriesname S01E02 blah.avi", 2)] - /// This does not seem to be the correct value or is it? - g [InlineData("Season 2/Episode - 16.avi", 16)] [InlineData("Season 2/Episode 16.avi", 16)] [InlineData("Season 2/Episode 16 - Some Title.avi", 16)] @@ -73,6 +71,7 @@ namespace Jellyfin.Naming.Tests.TV //[InlineData("Season 4/Uchuu.Senkan.Yamato.2199.E03.avi", 3)] //[InlineData("Season 2/7 12 Angry Men.avi", 7)] //[InlineData("Season 02/02x03x04x15 - Ep Name.mp4", 2)] + //[InlineData("Season 2/[HorribleSubs] Hunter X Hunter - 136 [720p].mkv", 136)] public void GetEpisodeNumberFromFileTest(string path, int? expected) { var result = new EpisodePathParser(_namingOptions) @@ -80,13 +79,5 @@ namespace Jellyfin.Naming.Tests.TV Assert.Equal(expected, result.EpisodeNumber); } - - private int? GetEpisodeNumberFromFile(string path) - { - var result = new EpisodePathParser(_namingOptions) - .Parse(path, false); - - return result.EpisodeNumber; - } } } From b306b8b8815cb4b3e9f6c8f7987b281a31fc0455 Mon Sep 17 00:00:00 2001 From: Narfinger Date: Sun, 23 Feb 2020 18:46:10 +0900 Subject: [PATCH 22/23] add todos and fixes some todo tests --- .../Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs index a9e6d63432..d74afe38bc 100644 --- a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs @@ -65,13 +65,13 @@ namespace Jellyfin.Naming.Tests.TV [InlineData("Season 2/02.avi", 2)] [InlineData("Season 2/2. Infestation.avi", 2)] [InlineData("The Wonder Years/The.Wonder.Years.S04.PDTV.x264-JCH/The Wonder Years s04e07 Christmas Party NTSC PDTV.avi", 7)] - //[InlineData("Season 2/16 12 Some Title.avi", 16)] - //[InlineData("Running Man/Running Man S2017E368.mkv", 360)] - //[InlineData("/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv/The.Legend.of.Condor.Heroes.2017.E07.V2.web-dl.1080p.h264.aac-hdctv.mkv", 7)] - //[InlineData("Season 4/Uchuu.Senkan.Yamato.2199.E03.avi", 3)] - //[InlineData("Season 2/7 12 Angry Men.avi", 7)] - //[InlineData("Season 02/02x03x04x15 - Ep Name.mp4", 2)] - //[InlineData("Season 2/[HorribleSubs] Hunter X Hunter - 136 [720p].mkv", 136)] + //TODO: [InlineData("Season 2/16 12 Some Title.avi", 16)] + //TODO: [InlineData("Running Man/Running Man S2017E368.mkv", 368)] + //TODO: [InlineData("/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv/The.Legend.of.Condor.Heroes.2017.E07.V2.web-dl.1080p.h264.aac-hdctv.mkv", 7)] + //TODO: [InlineData("Season 4/Uchuu.Senkan.Yamato.2199.E03.avi", 3)] + //TODO: [InlineData("Season 2/7 12 Angry Men.avi", 7)] + //TODO: [InlineData("Season 02/02x03x04x15 - Ep Name.mp4", 2)] + //TODO: [InlineData("Season 2/[HorribleSubs] Hunter X Hunter - 136 [720p].mkv", 136)] public void GetEpisodeNumberFromFileTest(string path, int? expected) { var result = new EpisodePathParser(_namingOptions) From fd5f0c54a645d024d1decca7bf4b7da302882d67 Mon Sep 17 00:00:00 2001 From: Narfinger Date: Sun, 23 Feb 2020 18:50:33 +0900 Subject: [PATCH 23/23] fixes formatting and enabling another test --- .../Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs index d74afe38bc..5e023bdb06 100644 --- a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs @@ -65,13 +65,13 @@ namespace Jellyfin.Naming.Tests.TV [InlineData("Season 2/02.avi", 2)] [InlineData("Season 2/2. Infestation.avi", 2)] [InlineData("The Wonder Years/The.Wonder.Years.S04.PDTV.x264-JCH/The Wonder Years s04e07 Christmas Party NTSC PDTV.avi", 7)] - //TODO: [InlineData("Season 2/16 12 Some Title.avi", 16)] - //TODO: [InlineData("Running Man/Running Man S2017E368.mkv", 368)] - //TODO: [InlineData("/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv/The.Legend.of.Condor.Heroes.2017.E07.V2.web-dl.1080p.h264.aac-hdctv.mkv", 7)] - //TODO: [InlineData("Season 4/Uchuu.Senkan.Yamato.2199.E03.avi", 3)] - //TODO: [InlineData("Season 2/7 12 Angry Men.avi", 7)] - //TODO: [InlineData("Season 02/02x03x04x15 - Ep Name.mp4", 2)] - //TODO: [InlineData("Season 2/[HorribleSubs] Hunter X Hunter - 136 [720p].mkv", 136)] + [InlineData("Running Man/Running Man S2017E368.mkv", 368)] + // TODO: [InlineData("Season 2/16 12 Some Title.avi", 16)] + // TODO: [InlineData("/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv/The.Legend.of.Condor.Heroes.2017.E07.V2.web-dl.1080p.h264.aac-hdctv.mkv", 7)] + // TODO: [InlineData("Season 4/Uchuu.Senkan.Yamato.2199.E03.avi", 3)] + // TODO: [InlineData("Season 2/7 12 Angry Men.avi", 7)] + // TODO: [InlineData("Season 02/02x03x04x15 - Ep Name.mp4", 2)] + // TODO: [InlineData("Season 2/[HorribleSubs] Hunter X Hunter - 136 [720p].mkv", 136)] public void GetEpisodeNumberFromFileTest(string path, int? expected) { var result = new EpisodePathParser(_namingOptions)