diff options
31 files changed, 460 insertions, 312 deletions
diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs index 81c4d3d16..440f96b3f 100644 --- a/Emby.Dlna/Didl/DidlBuilder.cs +++ b/Emby.Dlna/Didl/DidlBuilder.cs @@ -1088,8 +1088,8 @@ namespace Emby.Dlna.Didl //{ // var size = _imageProcessor.GetImageSize(imageInfo); - // width = Convert.ToInt32(size.Width); - // height = Convert.ToInt32(size.Height); + // width = size.Width; + // height = size.Height; //} //catch //{ @@ -1162,8 +1162,7 @@ namespace Emby.Dlna.Didl info.ImageTag, format, maxWidth.ToString(CultureInfo.InvariantCulture), - maxHeight.ToString(CultureInfo.InvariantCulture) - ); + maxHeight.ToString(CultureInfo.InvariantCulture)); var width = info.Width; var height = info.Height; @@ -1172,15 +1171,11 @@ namespace Emby.Dlna.Didl if (width.HasValue && height.HasValue) { - var newSize = DrawingUtils.Resize(new ImageSize - { - Height = height.Value, - Width = width.Value - - }, 0, 0, maxWidth, maxHeight); + var newSize = DrawingUtils.Resize( + new ImageDimensions(width.Value, height.Value), 0, 0, maxWidth, maxHeight); - width = Convert.ToInt32(newSize.Width); - height = Convert.ToInt32(newSize.Height); + width = newSize.Width; + height = newSize.Height; var normalizedFormat = format .Replace("jpeg", "jpg", StringComparison.OrdinalIgnoreCase); diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs index c750b60e2..8ac2b9b27 100644 --- a/Emby.Drawing/ImageProcessor.cs +++ b/Emby.Drawing/ImageProcessor.cs @@ -18,7 +18,6 @@ using MediaBrowser.Model.Extensions; using MediaBrowser.Model.IO; using MediaBrowser.Model.Net; using Microsoft.Extensions.Logging; -using SkiaSharp; namespace Emby.Drawing { @@ -66,7 +65,7 @@ namespace Emby.Drawing _appPaths = appPaths; ImageEnhancers = Array.Empty<IImageEnhancer>(); - + ImageHelper.ImageProcessor = this; } @@ -168,10 +167,10 @@ namespace Emby.Drawing string originalImagePath = originalImage.Path; DateTime dateModified = originalImage.DateModified; - ImageSize? originalImageSize = null; + ImageDimensions? originalImageSize = null; if (originalImage.Width > 0 && originalImage.Height > 0) { - originalImageSize = new ImageSize(originalImage.Width, originalImage.Height); + originalImageSize = new ImageDimensions(originalImage.Width, originalImage.Height); } if (!_imageEncoder.SupportsImageEncoding) @@ -231,7 +230,7 @@ namespace Emby.Drawing return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); } - ImageSize newSize = ImageHelper.GetNewImageSize(options, null); + ImageDimensions newSize = ImageHelper.GetNewImageSize(options, null); int quality = options.Quality; ImageFormat outputFormat = GetOutputFormat(options.SupportedOutputFormats, requiresTransparency); @@ -334,7 +333,7 @@ namespace Emby.Drawing /// <summary> /// Gets the cache file path based on a set of parameters /// </summary> - private string GetCacheFilePath(string originalPath, ImageSize outputSize, int quality, DateTime dateModified, ImageFormat format, bool addPlayedIndicator, double percentPlayed, int? unwatchedCount, int? blur, string backgroundColor, string foregroundLayer) + 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) { var filename = originalPath + "width=" + outputSize.Width @@ -378,26 +377,25 @@ namespace Emby.Drawing return GetCachePath(ResizedImageCachePath, filename, "." + format.ToString().ToLower()); } - public ImageSize GetImageSize(BaseItem item, ItemImageInfo info) + public ImageDimensions GetImageSize(BaseItem item, ItemImageInfo info) => GetImageSize(item, info, true); - public ImageSize GetImageSize(BaseItem item, ItemImageInfo info, bool updateItem) + public ImageDimensions GetImageSize(BaseItem item, ItemImageInfo info, bool updateItem) { int width = info.Width; int height = info.Height; if (height > 0 && width > 0) { - return new ImageSize(width, height); + return new ImageDimensions(width, height); } string path = info.Path; _logger.LogInformation("Getting image size for item {ItemType} {Path}", item.GetType().Name, path); - var size = GetImageSize(path); - - info.Height = Convert.ToInt32(size.Height); - info.Width = Convert.ToInt32(size.Width); + ImageDimensions size = GetImageSize(path); + info.Width = size.Width; + info.Height = size.Height; if (updateItem) { @@ -410,20 +408,8 @@ namespace Emby.Drawing /// <summary> /// Gets the size of the image. /// </summary> - public ImageSize GetImageSize(string path) - { - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentNullException(nameof(path)); - } - - using (var s = new SKFileStream(path)) - using (var codec = SKCodec.Create(s)) - { - var info = codec.Info; - return new ImageSize(info.Width, info.Height); - } - } + public ImageDimensions GetImageSize(string path) + => _imageEncoder.GetImageSize(path); /// <summary> /// Gets the image cache tag. diff --git a/Emby.Drawing/NullImageEncoder.cs b/Emby.Drawing/NullImageEncoder.cs index e6f205a1f..14f0424ac 100644 --- a/Emby.Drawing/NullImageEncoder.cs +++ b/Emby.Drawing/NullImageEncoder.cs @@ -37,7 +37,7 @@ namespace Emby.Drawing public bool SupportsImageEncoding => false; - public ImageSize GetImageSize(string path) + public ImageDimensions GetImageSize(string path) { throw new NotImplementedException(); } diff --git a/Emby.Drawing/PercentPlayedDrawer.cs b/Emby.Drawing/PercentPlayedDrawer.cs index 52b4329e1..3ce46bc12 100644 --- a/Emby.Drawing/PercentPlayedDrawer.cs +++ b/Emby.Drawing/PercentPlayedDrawer.cs @@ -8,7 +8,7 @@ namespace Emby.Drawing { private const int IndicatorHeight = 8; - public static void Process(SKCanvas canvas, ImageSize imageSize, double percent) + public static void Process(SKCanvas canvas, ImageDimensions imageSize, double percent) { using (var paint = new SKPaint()) { @@ -24,7 +24,7 @@ namespace Emby.Drawing foregroundWidth /= 100; paint.Color = SKColor.Parse("#FF52B54B"); - canvas.DrawRect(SKRect.Create(0, (float)endY - IndicatorHeight, Convert.ToInt32(Math.Round(foregroundWidth)), (float)endY), paint); + canvas.DrawRect(SKRect.Create(0, (float)endY - IndicatorHeight, Convert.ToInt32(foregroundWidth), (float)endY), paint); } } } diff --git a/Emby.Drawing/PlayedIndicatorDrawer.cs b/Emby.Drawing/PlayedIndicatorDrawer.cs index a82398fa5..38b5edc92 100644 --- a/Emby.Drawing/PlayedIndicatorDrawer.cs +++ b/Emby.Drawing/PlayedIndicatorDrawer.cs @@ -7,7 +7,7 @@ namespace Emby.Drawing { private const int OffsetFromTopRightCorner = 38; - public static void DrawPlayedIndicator(SKCanvas canvas, ImageSize imageSize) + public static void DrawPlayedIndicator(SKCanvas canvas, ImageDimensions imageSize) { var x = imageSize.Width - OffsetFromTopRightCorner; diff --git a/Emby.Drawing/SkiaEncoder.cs b/Emby.Drawing/SkiaEncoder.cs index 9883b3cca..aae10f6cc 100644 --- a/Emby.Drawing/SkiaEncoder.cs +++ b/Emby.Drawing/SkiaEncoder.cs @@ -168,18 +168,14 @@ namespace Emby.Drawing } } - public ImageSize GetImageSize(string path) + public ImageDimensions GetImageSize(string path) { using (var s = new SKFileStream(path)) using (var codec = SKCodec.Create(s)) { var info = codec.Info; - return new ImageSize - { - Width = info.Width, - Height = info.Height - }; + return new ImageDimensions(info.Width, info.Height); } } @@ -513,7 +509,7 @@ namespace Emby.Drawing //_logger.LogInformation("Color type {0}", bitmap.Info.ColorType); - var originalImageSize = new ImageSize(bitmap.Width, bitmap.Height); + var originalImageSize = new ImageDimensions(bitmap.Width, bitmap.Height); if (!options.CropWhiteSpace && options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient) { @@ -523,8 +519,8 @@ namespace Emby.Drawing var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize); - var width = Convert.ToInt32(Math.Round(newImageSize.Width)); - var height = Convert.ToInt32(Math.Round(newImageSize.Height)); + var width = newImageSize.Width; + var height = newImageSize.Height; using (var resizedBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType)) { @@ -626,7 +622,7 @@ namespace Emby.Drawing { try { - var currentImageSize = new ImageSize(imageWidth, imageHeight); + var currentImageSize = new ImageDimensions(imageWidth, imageHeight); if (options.AddPlayedIndicator) { diff --git a/Emby.Drawing/UnplayedCountIndicator.cs b/Emby.Drawing/UnplayedCountIndicator.cs index 16c084a21..4d0cc9d40 100644 --- a/Emby.Drawing/UnplayedCountIndicator.cs +++ b/Emby.Drawing/UnplayedCountIndicator.cs @@ -8,7 +8,7 @@ namespace Emby.Drawing { private const int OffsetFromTopRightCorner = 38; - public static void DrawUnplayedCountIndicator(SKCanvas canvas, ImageSize imageSize, int count) + public static void DrawUnplayedCountIndicator(SKCanvas canvas, ImageDimensions imageSize, int count) { var x = imageSize.Width - OffsetFromTopRightCorner; var text = count.ToString(CultureInfo.InvariantCulture); diff --git a/Emby.Photos/PhotoProvider.cs b/Emby.Photos/PhotoProvider.cs index 4e483ad5b..aaebe1a21 100644 --- a/Emby.Photos/PhotoProvider.cs +++ b/Emby.Photos/PhotoProvider.cs @@ -185,8 +185,8 @@ namespace Emby.Photos if (size.Width > 0 && size.Height > 0) { - item.Width = Convert.ToInt32(size.Width); - item.Height = Convert.ToInt32(size.Height); + item.Width = size.Width; + item.Height = size.Height; } } catch (ArgumentException) diff --git a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs index aef72c697..a8e8f815a 100644 --- a/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs +++ b/Emby.Server.Implementations/Activity/ActivityLogEntryPoint.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; -using System.Threading.Tasks; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Updates; @@ -93,18 +92,18 @@ namespace Emby.Server.Implementations.Activity _appHost.ApplicationUpdated += _appHost_ApplicationUpdated; } - async void _deviceManager_CameraImageUploaded(object sender, GenericEventArgs<CameraImageUploadInfo> e) + void _deviceManager_CameraImageUploaded(object sender, GenericEventArgs<CameraImageUploadInfo> e) { - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("CameraImageUploadedFrom"), e.Argument.Device.Name), Type = NotificationType.CameraImageUploaded.ToString() }); } - async void _userManager_UserLockedOut(object sender, GenericEventArgs<User> e) + void _userManager_UserLockedOut(object sender, GenericEventArgs<User> e) { - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("UserLockedOutWithName"), e.Argument.Name), Type = NotificationType.UserLockedOut.ToString(), @@ -112,9 +111,9 @@ namespace Emby.Server.Implementations.Activity }); } - async void _subManager_SubtitleDownloadFailure(object sender, SubtitleDownloadFailureEventArgs e) + void _subManager_SubtitleDownloadFailure(object sender, SubtitleDownloadFailureEventArgs e) { - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("SubtitleDownloadFailureFromForItem"), e.Provider, Notifications.Notifications.GetItemName(e.Item)), Type = "SubtitleDownloadFailure", @@ -123,7 +122,7 @@ namespace Emby.Server.Implementations.Activity }); } - async void _sessionManager_PlaybackStopped(object sender, PlaybackStopEventArgs e) + void _sessionManager_PlaybackStopped(object sender, PlaybackStopEventArgs e) { var item = e.MediaInfo; @@ -146,7 +145,7 @@ namespace Emby.Server.Implementations.Activity var user = e.Users.First(); - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("UserStoppedPlayingItemWithValues"), user.Name, GetItemName(item), e.DeviceName), Type = GetPlaybackStoppedNotificationType(item.MediaType), @@ -154,7 +153,7 @@ namespace Emby.Server.Implementations.Activity }); } - async void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e) + void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e) { var item = e.MediaInfo; @@ -177,7 +176,7 @@ namespace Emby.Server.Implementations.Activity var user = e.Users.First(); - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("UserStartedPlayingItemWithValues"), user.Name, GetItemName(item), e.DeviceName), Type = GetPlaybackNotificationType(item.MediaType), @@ -238,7 +237,7 @@ namespace Emby.Server.Implementations.Activity return null; } - async void _sessionManager_SessionEnded(object sender, SessionEventArgs e) + void _sessionManager_SessionEnded(object sender, SessionEventArgs e) { string name; var session = e.SessionInfo; @@ -255,7 +254,7 @@ namespace Emby.Server.Implementations.Activity name = string.Format(_localization.GetLocalizedString("UserOfflineFromDevice"), session.UserName, session.DeviceName); } - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = name, Type = "SessionEnded", @@ -264,11 +263,11 @@ namespace Emby.Server.Implementations.Activity }); } - async void _sessionManager_AuthenticationSucceeded(object sender, GenericEventArgs<AuthenticationResult> e) + void _sessionManager_AuthenticationSucceeded(object sender, GenericEventArgs<AuthenticationResult> e) { var user = e.Argument.User; - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("AuthenticationSucceededWithUserName"), user.Name), Type = "AuthenticationSucceeded", @@ -277,9 +276,9 @@ namespace Emby.Server.Implementations.Activity }); } - async void _sessionManager_AuthenticationFailed(object sender, GenericEventArgs<AuthenticationRequest> e) + void _sessionManager_AuthenticationFailed(object sender, GenericEventArgs<AuthenticationRequest> e) { - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("FailedLoginAttemptWithUserName"), e.Argument.Username), Type = "AuthenticationFailed", @@ -288,9 +287,9 @@ namespace Emby.Server.Implementations.Activity }); } - async void _appHost_ApplicationUpdated(object sender, GenericEventArgs<PackageVersionInfo> e) + void _appHost_ApplicationUpdated(object sender, GenericEventArgs<PackageVersionInfo> e) { - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("MessageApplicationUpdatedTo"), e.Argument.versionStr), Type = NotificationType.ApplicationUpdateInstalled.ToString(), @@ -298,27 +297,27 @@ namespace Emby.Server.Implementations.Activity }); } - async void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e) + void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e) { - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("MessageNamedServerConfigurationUpdatedWithValue"), e.Key), Type = "NamedConfigurationUpdated" }); } - async void _config_ConfigurationUpdated(object sender, EventArgs e) + void _config_ConfigurationUpdated(object sender, EventArgs e) { - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = _localization.GetLocalizedString("MessageServerConfigurationUpdated"), Type = "ServerConfigurationUpdated" }); } - async void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e) + void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e) { - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("UserPolicyUpdatedWithName"), e.Argument.Name), Type = "UserPolicyUpdated", @@ -326,18 +325,18 @@ namespace Emby.Server.Implementations.Activity }); } - async void _userManager_UserDeleted(object sender, GenericEventArgs<User> e) + void _userManager_UserDeleted(object sender, GenericEventArgs<User> e) { - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("UserDeletedWithName"), e.Argument.Name), Type = "UserDeleted" }); } - async void _userManager_UserPasswordChanged(object sender, GenericEventArgs<User> e) + void _userManager_UserPasswordChanged(object sender, GenericEventArgs<User> e) { - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("UserPasswordChangedWithName"), e.Argument.Name), Type = "UserPasswordChanged", @@ -345,9 +344,9 @@ namespace Emby.Server.Implementations.Activity }); } - async void _userManager_UserCreated(object sender, GenericEventArgs<User> e) + void _userManager_UserCreated(object sender, GenericEventArgs<User> e) { - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("UserCreatedWithName"), e.Argument.Name), Type = "UserCreated", @@ -355,9 +354,9 @@ namespace Emby.Server.Implementations.Activity }); } - async void _subManager_SubtitlesDownloaded(object sender, SubtitleDownloadEventArgs e) + void _subManager_SubtitlesDownloaded(object sender, SubtitleDownloadEventArgs e) { - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("SubtitlesDownloadedForItem"), Notifications.Notifications.GetItemName(e.Item)), Type = "SubtitlesDownloaded", @@ -366,7 +365,7 @@ namespace Emby.Server.Implementations.Activity }); } - async void _sessionManager_SessionStarted(object sender, SessionEventArgs e) + void _sessionManager_SessionStarted(object sender, SessionEventArgs e) { string name; var session = e.SessionInfo; @@ -383,7 +382,7 @@ namespace Emby.Server.Implementations.Activity name = string.Format(_localization.GetLocalizedString("UserOnlineFromDevice"), session.UserName, session.DeviceName); } - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = name, Type = "SessionStarted", @@ -392,9 +391,9 @@ namespace Emby.Server.Implementations.Activity }); } - async void _installationManager_PluginUpdated(object sender, GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> e) + void _installationManager_PluginUpdated(object sender, GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> e) { - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("PluginUpdatedWithName"), e.Argument.Item1.Name), Type = NotificationType.PluginUpdateInstalled.ToString(), @@ -403,18 +402,18 @@ namespace Emby.Server.Implementations.Activity }); } - async void _installationManager_PluginUninstalled(object sender, GenericEventArgs<IPlugin> e) + void _installationManager_PluginUninstalled(object sender, GenericEventArgs<IPlugin> e) { - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("PluginUninstalledWithName"), e.Argument.Name), Type = NotificationType.PluginUninstalled.ToString() }); } - async void _installationManager_PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> e) + void _installationManager_PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> e) { - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("PluginInstalledWithName"), e.Argument.name), Type = NotificationType.PluginInstalled.ToString(), @@ -422,11 +421,11 @@ namespace Emby.Server.Implementations.Activity }); } - async void _installationManager_PackageInstallationFailed(object sender, InstallationFailedEventArgs e) + void _installationManager_PackageInstallationFailed(object sender, InstallationFailedEventArgs e) { var installationInfo = e.InstallationInfo; - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("NameInstallFailed"), installationInfo.Name), Type = NotificationType.InstallationFailed.ToString(), @@ -435,7 +434,7 @@ namespace Emby.Server.Implementations.Activity }); } - async void _taskManager_TaskCompleted(object sender, TaskCompletionEventArgs e) + void _taskManager_TaskCompleted(object sender, TaskCompletionEventArgs e) { var result = e.Result; var task = e.Task; @@ -462,7 +461,7 @@ namespace Emby.Server.Implementations.Activity vals.Add(e.Result.LongErrorMessage); } - await CreateLogEntry(new ActivityLogEntry + CreateLogEntry(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("ScheduledTaskFailedWithName"), task.Name), Type = NotificationType.TaskFailed.ToString(), @@ -473,11 +472,11 @@ namespace Emby.Server.Implementations.Activity } } - private async Task CreateLogEntry(ActivityLogEntry entry) + private void CreateLogEntry(ActivityLogEntry entry) { try { - await _activityManager.CreateAsync(entry); + _activityManager.Create(entry); } catch { diff --git a/Emby.Server.Implementations/Activity/ActivityManager.cs b/Emby.Server.Implementations/Activity/ActivityManager.cs index 8fcacb002..6febcc2f7 100644 --- a/Emby.Server.Implementations/Activity/ActivityManager.cs +++ b/Emby.Server.Implementations/Activity/ActivityManager.cs @@ -1,10 +1,9 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Activity; using MediaBrowser.Model.Events; +using MediaBrowser.Model.Querying; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Activity @@ -27,38 +26,20 @@ namespace Emby.Server.Implementations.Activity _userManager = userManager; } - public async Task CreateAsync(ActivityLogEntry entry) + public void Create(ActivityLogEntry entry) { entry.Date = DateTime.UtcNow; - await _repo.CreateAsync(entry); + _repo.Create(entry); EntryCreated?.Invoke(this, new GenericEventArgs<ActivityLogEntry>(entry)); } - public IEnumerable<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, bool? hasUserId, int? startIndex, int? limit) + public QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, bool? hasUserId, int? startIndex, int? limit) { - var result = _repo.GetActivityLogEntries(); + var result = _repo.GetActivityLogEntries(minDate, hasUserId, startIndex, limit); - if (minDate.HasValue) - { - result = result.Where(x => x.Date >= minDate.Value); - } - if (hasUserId.HasValue) - { - result = result.Where(x => x.UserId != null && x.UserId != Guid.Empty); - } - if (startIndex.HasValue) - { - result = result.Where(x => x.Id >= startIndex.Value); - } - if (limit.HasValue) - { - result = result.Take(limit.Value); - } - - // Add images for each user - foreach (var item in result) + foreach (var item in result.Items.Where(i => !i.UserId.Equals(Guid.Empty))) { var user = _userManager.GetUserById(item.UserId); @@ -69,7 +50,12 @@ namespace Emby.Server.Implementations.Activity } } - return result.AsEnumerable(); + return result; + } + + public QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, int? startIndex, int? limit) + { + return GetActivityLogEntries(minDate, null, startIndex, limit); } } } diff --git a/Emby.Server.Implementations/Activity/ActivityRepository.cs b/Emby.Server.Implementations/Activity/ActivityRepository.cs index af0b20d92..aeed8b6f1 100644 --- a/Emby.Server.Implementations/Activity/ActivityRepository.cs +++ b/Emby.Server.Implementations/Activity/ActivityRepository.cs @@ -1,37 +1,310 @@ +using System; +using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; -using System.Threading.Tasks; +using Emby.Server.Implementations.Data; +using MediaBrowser.Controller; using MediaBrowser.Model.Activity; -using Microsoft.EntityFrameworkCore; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.Querying; +using Microsoft.Extensions.Logging; +using SQLitePCL.pretty; namespace Emby.Server.Implementations.Activity { - public class ActivityRepository : DbContext, IActivityRepository + public class ActivityRepository : BaseSqliteRepository, IActivityRepository { - protected string _dataDirPath; + private readonly CultureInfo _usCulture = new CultureInfo("en-US"); + protected IFileSystem FileSystem { get; private set; } - public DbSet<ActivityLogEntry> ActivityLogs { get; set; } + public ActivityRepository(ILoggerFactory loggerFactory, IServerApplicationPaths appPaths, IFileSystem fileSystem) + : base(loggerFactory.CreateLogger(nameof(ActivityRepository))) + { + DbFilePath = Path.Combine(appPaths.DataPath, "activitylog.db"); + FileSystem = fileSystem; + } - public ActivityRepository(string dataDirPath) + public void Initialize() { - _dataDirPath = dataDirPath; + try + { + InitializeInternal(); + } + catch (Exception ex) + { + Logger.LogError(ex, "Error loading database file. Will reset and retry."); + + FileSystem.DeleteFile(DbFilePath); + + InitializeInternal(); + } } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + private void InitializeInternal() { - // Ensure the dir exists - Directory.CreateDirectory(_dataDirPath); + using (var connection = CreateConnection()) + { + RunDefaultInitialization(connection); + + connection.RunQueries(new[] + { + "create table if not exists ActivityLog (Id INTEGER PRIMARY KEY, Name TEXT NOT NULL, Overview TEXT, ShortOverview TEXT, Type TEXT NOT NULL, ItemId TEXT, UserId TEXT, DateCreated DATETIME NOT NULL, LogSeverity TEXT NOT NULL)", + "drop index if exists idx_ActivityLogEntries" + }); + + TryMigrate(connection); + } + } - optionsBuilder.UseSqlite($"Filename={Path.Combine(_dataDirPath, "activitylog.sqlite.db")}"); + private void TryMigrate(ManagedConnection connection) + { + try + { + if (TableExists(connection, "ActivityLogEntries")) + { + connection.RunQueries(new[] + { + "INSERT INTO ActivityLog (Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity) SELECT Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity FROM ActivityLogEntries", + "drop table if exists ActivityLogEntries" + }); + } + } + catch (Exception ex) + { + Logger.LogError(ex, "Error migrating activity log database"); + } } - public async Task CreateAsync(ActivityLogEntry entry) + private const string BaseActivitySelectText = "select Id, Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity from ActivityLog"; + + public void Create(ActivityLogEntry entry) { - await ActivityLogs.AddAsync(entry); - await SaveChangesAsync(); + if (entry == null) + { + throw new ArgumentNullException(nameof(entry)); + } + + using (WriteLock.Write()) + using (var connection = CreateConnection()) + { + connection.RunInTransaction(db => + { + using (var statement = db.PrepareStatement("insert into ActivityLog (Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity) values (@Name, @Overview, @ShortOverview, @Type, @ItemId, @UserId, @DateCreated, @LogSeverity)")) + { + statement.TryBind("@Name", entry.Name); + + statement.TryBind("@Overview", entry.Overview); + statement.TryBind("@ShortOverview", entry.ShortOverview); + statement.TryBind("@Type", entry.Type); + statement.TryBind("@ItemId", entry.ItemId); + + if (entry.UserId.Equals(Guid.Empty)) + { + statement.TryBindNull("@UserId"); + } + else + { + statement.TryBind("@UserId", entry.UserId.ToString("N")); + } + + statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue()); + statement.TryBind("@LogSeverity", entry.Severity.ToString()); + + statement.MoveNext(); + } + }, TransactionMode); + } + } + + public void Update(ActivityLogEntry entry) + { + if (entry == null) + { + throw new ArgumentNullException(nameof(entry)); + } + + using (WriteLock.Write()) + using (var connection = CreateConnection()) + { + connection.RunInTransaction(db => + { + using (var statement = db.PrepareStatement("Update ActivityLog set Name=@Name,Overview=@Overview,ShortOverview=@ShortOverview,Type=@Type,ItemId=@ItemId,UserId=@UserId,DateCreated=@DateCreated,LogSeverity=@LogSeverity where Id=@Id")) + { + statement.TryBind("@Id", entry.Id); + + statement.TryBind("@Name", entry.Name); + statement.TryBind("@Overview", entry.Overview); + statement.TryBind("@ShortOverview", entry.ShortOverview); + statement.TryBind("@Type", entry.Type); + statement.TryBind("@ItemId", entry.ItemId); + + if (entry.UserId.Equals(Guid.Empty)) + { + statement.TryBindNull("@UserId"); + } + else + { + statement.TryBind("@UserId", entry.UserId.ToString("N")); + } + + statement.TryBind("@DateCreated", entry.Date.ToDateTimeParamValue()); + statement.TryBind("@LogSeverity", entry.Severity.ToString()); + + statement.MoveNext(); + } + }, TransactionMode); + } + } + + public QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, bool? hasUserId, int? startIndex, int? limit) + { + using (WriteLock.Read()) + using (var connection = CreateConnection(true)) + { + var commandText = BaseActivitySelectText; + var whereClauses = new List<string>(); + + if (minDate.HasValue) + { + whereClauses.Add("DateCreated>=@DateCreated"); + } + if (hasUserId.HasValue) + { + if (hasUserId.Value) + { + whereClauses.Add("UserId not null"); + } + else + { + whereClauses.Add("UserId is null"); + } + } + + var whereTextWithoutPaging = whereClauses.Count == 0 ? + string.Empty : + " where " + string.Join(" AND ", whereClauses.ToArray()); + + if (startIndex.HasValue && startIndex.Value > 0) + { + var pagingWhereText = whereClauses.Count == 0 ? + string.Empty : + " where " + string.Join(" AND ", whereClauses.ToArray()); + + whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM ActivityLog {0} ORDER BY DateCreated DESC LIMIT {1})", + pagingWhereText, + startIndex.Value.ToString(_usCulture))); + } + + var whereText = whereClauses.Count == 0 ? + string.Empty : + " where " + string.Join(" AND ", whereClauses.ToArray()); + + commandText += whereText; + + commandText += " ORDER BY DateCreated DESC"; + + if (limit.HasValue) + { + commandText += " LIMIT " + limit.Value.ToString(_usCulture); + } + + var statementTexts = new List<string>(); + statementTexts.Add(commandText); + statementTexts.Add("select count (Id) from ActivityLog" + whereTextWithoutPaging); + + return connection.RunInTransaction(db => + { + var list = new List<ActivityLogEntry>(); + var result = new QueryResult<ActivityLogEntry>(); + + var statements = PrepareAllSafe(db, statementTexts).ToList(); + + using (var statement = statements[0]) + { + if (minDate.HasValue) + { + statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue()); + } + + foreach (var row in statement.ExecuteQuery()) + { + list.Add(GetEntry(row)); + } + } + + using (var statement = statements[1]) + { + if (minDate.HasValue) + { + statement.TryBind("@DateCreated", minDate.Value.ToDateTimeParamValue()); + } + + result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First(); + } + + result.Items = list.ToArray(); + return result; + + }, ReadTransactionMode); + } } - public IQueryable<ActivityLogEntry> GetActivityLogEntries() - => ActivityLogs; + private static ActivityLogEntry GetEntry(IReadOnlyList<IResultSetValue> reader) + { + var index = 0; + + var info = new ActivityLogEntry + { + Id = reader[index].ToInt64() + }; + + index++; + if (reader[index].SQLiteType != SQLiteType.Null) + { + info.Name = reader[index].ToString(); + } + + index++; + if (reader[index].SQLiteType != SQLiteType.Null) + { + info.Overview = reader[index].ToString(); + } + + index++; + if (reader[index].SQLiteType != SQLiteType.Null) + { + info.ShortOverview = reader[index].ToString(); + } + + index++; + if (reader[index].SQLiteType != SQLiteType.Null) + { + info.Type = reader[index].ToString(); + } + + index++; + if (reader[index].SQLiteType != SQLiteType.Null) + { + info.ItemId = reader[index].ToString(); + } + + index++; + if (reader[index].SQLiteType != SQLiteType.Null) + { + info.UserId = new Guid(reader[index].ToString()); + } + + index++; + info.Date = reader[index].ReadDateTime(); + + index++; + if (reader[index].SQLiteType != SQLiteType.Null) + { + info.Severity = (LogLevel)Enum.Parse(typeof(LogLevel), reader[index].ToString(), true); + } + + return info; + } } } diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index fb4e41550..e0088ab19 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -705,7 +705,7 @@ namespace Emby.Server.Implementations } } - public async Task InitAsync() + public void Init() { HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber; HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber; @@ -735,7 +735,7 @@ namespace Emby.Server.Implementations SetHttpLimit(); - await RegisterResourcesAsync(); + RegisterResources(); FindParts(); } @@ -750,7 +750,7 @@ namespace Emby.Server.Implementations /// <summary> /// Registers resources that classes will depend on /// </summary> - protected async Task RegisterResourcesAsync() + protected void RegisterResources() { RegisterSingleInstance(ConfigurationManager); RegisterSingleInstance<IApplicationHost>(this); @@ -926,7 +926,7 @@ namespace Emby.Server.Implementations EncodingManager = new MediaEncoder.EncodingManager(FileSystemManager, LoggerFactory, MediaEncoder, ChapterManager, LibraryManager); RegisterSingleInstance(EncodingManager); - var activityLogRepo = await GetActivityLogRepositoryAsync(); + var activityLogRepo = GetActivityLogRepository(); RegisterSingleInstance(activityLogRepo); RegisterSingleInstance<IActivityManager>(new ActivityManager(LoggerFactory, activityLogRepo, UserManager)); @@ -1141,11 +1141,11 @@ namespace Emby.Server.Implementations return repo; } - private async Task<IActivityRepository> GetActivityLogRepositoryAsync() + private IActivityRepository GetActivityLogRepository() { - var repo = new ActivityRepository(ServerConfigurationManager.ApplicationPaths.DataPath); + var repo = new ActivityRepository(LoggerFactory, ServerConfigurationManager.ApplicationPaths, FileSystemManager); - await repo.Database.EnsureCreatedAsync(); + repo.Initialize(); return repo; } diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index 13febc214..d0a7de11d 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -1428,7 +1428,7 @@ namespace Emby.Server.Implementations.Dto var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary); - ImageSize size; + ImageDimensions size; var defaultAspectRatio = item.GetDefaultPrimaryImageAspectRatio(); @@ -1439,9 +1439,9 @@ namespace Emby.Server.Implementations.Dto return defaultAspectRatio; } - double dummyWidth = 200; - double dummyHeight = dummyWidth / defaultAspectRatio; - size = new ImageSize(dummyWidth, dummyHeight); + int dummyWidth = 200; + int dummyHeight = Convert.ToInt32(dummyWidth / defaultAspectRatio); + size = new ImageDimensions(dummyWidth, dummyHeight); } else { @@ -1481,7 +1481,7 @@ namespace Emby.Server.Implementations.Dto var width = size.Width; var height = size.Height; - if (width.Equals(0) || height.Equals(0)) + if (width <= 0 || height <= 0) { return null; } diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index f2a5b2e38..3aa617b02 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -22,7 +22,6 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.2.0" /> <PackageReference Include="ServiceStack.Text.Core" Version="5.4.0" /> <PackageReference Include="sharpcompress" Version="0.22.0" /> <PackageReference Include="SimpleInjector" Version="4.4.2" /> diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index ecd31e625..f64f50cd7 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -98,7 +98,7 @@ namespace Jellyfin.Server new NullImageEncoder(), new NetworkManager(_loggerFactory, environmentInfo))) { - await appHost.InitAsync(); + appHost.Init(); appHost.ImageProcessor.ImageEncoder = GetImageEncoder(fileSystem, appPaths, appHost.LocalizationManager); @@ -107,6 +107,7 @@ namespace Jellyfin.Server await appHost.RunStartupTasks(); // TODO: read input for a stop command + try { // Block main thread until shutdown @@ -165,6 +166,7 @@ namespace Jellyfin.Server { Directory.CreateDirectory(programDataPath); } + string configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR"); if (string.IsNullOrEmpty(configDir)) { diff --git a/MediaBrowser.Api/Images/ImageService.cs b/MediaBrowser.Api/Images/ImageService.cs index 26ac8d40e..149e54f01 100644 --- a/MediaBrowser.Api/Images/ImageService.cs +++ b/MediaBrowser.Api/Images/ImageService.cs @@ -328,10 +328,9 @@ namespace MediaBrowser.Api.Images var fileInfo = _fileSystem.GetFileInfo(info.Path); length = fileInfo.Length; - var size = _imageProcessor.GetImageSize(item, info, true); - - width = Convert.ToInt32(size.Width); - height = Convert.ToInt32(size.Height); + ImageDimensions size = _imageProcessor.GetImageSize(item, info, true); + width = size.Width; + height = size.Height; if (width <= 0 || height <= 0) { diff --git a/MediaBrowser.Api/Library/LibraryService.cs b/MediaBrowser.Api/Library/LibraryService.cs index d3009295f..12d807a7e 100644 --- a/MediaBrowser.Api/Library/LibraryService.cs +++ b/MediaBrowser.Api/Library/LibraryService.cs @@ -839,7 +839,7 @@ namespace MediaBrowser.Api.Library { try { - _activityManager.CreateAsync(new ActivityLogEntry + _activityManager.Create(new ActivityLogEntry { Name = string.Format(_localization.GetLocalizedString("UserDownloadingItemWithValues"), user.Name, item.Name), Type = "UserDownloadingContent", diff --git a/MediaBrowser.Common/IApplicationHost.cs b/MediaBrowser.Common/IApplicationHost.cs index 9dc625e35..385127c54 100644 --- a/MediaBrowser.Common/IApplicationHost.cs +++ b/MediaBrowser.Common/IApplicationHost.cs @@ -131,7 +131,7 @@ namespace MediaBrowser.Common /// <summary> /// Inits this instance. /// </summary> - Task InitAsync(); + void Init(); /// <summary> /// Creates the instance. diff --git a/MediaBrowser.Controller/Drawing/IImageEncoder.cs b/MediaBrowser.Controller/Drawing/IImageEncoder.cs index 6e2d5781a..5b8c9da6f 100644 --- a/MediaBrowser.Controller/Drawing/IImageEncoder.cs +++ b/MediaBrowser.Controller/Drawing/IImageEncoder.cs @@ -44,6 +44,6 @@ namespace MediaBrowser.Controller.Drawing /// <value><c>true</c> if [supports image encoding]; otherwise, <c>false</c>.</value> bool SupportsImageEncoding { get; } - ImageSize GetImageSize(string path); + ImageDimensions GetImageSize(string path); } } diff --git a/MediaBrowser.Controller/Drawing/IImageProcessor.cs b/MediaBrowser.Controller/Drawing/IImageProcessor.cs index 7e6e0127f..783182730 100644 --- a/MediaBrowser.Controller/Drawing/IImageProcessor.cs +++ b/MediaBrowser.Controller/Drawing/IImageProcessor.cs @@ -26,16 +26,16 @@ namespace MediaBrowser.Controller.Drawing /// <value>The image enhancers.</value> IImageEnhancer[] ImageEnhancers { get; } - ImageSize GetImageSize(string path); + ImageDimensions GetImageSize(string path); /// <summary> /// Gets the size of the image. /// </summary> /// <param name="info">The information.</param> /// <returns>ImageSize.</returns> - ImageSize GetImageSize(BaseItem item, ItemImageInfo info); + ImageDimensions GetImageSize(BaseItem item, ItemImageInfo info); - ImageSize GetImageSize(BaseItem item, ItemImageInfo info, bool updateItem); + ImageDimensions GetImageSize(BaseItem item, ItemImageInfo info, bool updateItem); /// <summary> /// Adds the parts. diff --git a/MediaBrowser.Controller/Drawing/ImageHelper.cs b/MediaBrowser.Controller/Drawing/ImageHelper.cs index 2680c60bd..f88a63223 100644 --- a/MediaBrowser.Controller/Drawing/ImageHelper.cs +++ b/MediaBrowser.Controller/Drawing/ImageHelper.cs @@ -1,3 +1,4 @@ +using System; using MediaBrowser.Controller.Entities; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Entities; @@ -6,7 +7,7 @@ namespace MediaBrowser.Controller.Drawing { public static class ImageHelper { - public static ImageSize GetNewImageSize(ImageProcessingOptions options, ImageSize? originalImageSize) + public static ImageDimensions GetNewImageSize(ImageProcessingOptions options, ImageDimensions? originalImageSize) { if (originalImageSize.HasValue) { @@ -20,26 +21,26 @@ namespace MediaBrowser.Controller.Drawing public static IImageProcessor ImageProcessor { get; set; } - private static ImageSize GetSizeEstimate(ImageProcessingOptions options) + private static ImageDimensions GetSizeEstimate(ImageProcessingOptions options) { if (options.Width.HasValue && options.Height.HasValue) { - return new ImageSize(options.Width.Value, options.Height.Value); + return new ImageDimensions(options.Width.Value, options.Height.Value); } - var aspect = GetEstimatedAspectRatio(options.Image.Type, options.Item); + double aspect = GetEstimatedAspectRatio(options.Image.Type, options.Item); - var width = options.Width ?? options.MaxWidth; + int? width = options.Width ?? options.MaxWidth; if (width.HasValue) { - var heightValue = width.Value / aspect; - return new ImageSize(width.Value, heightValue); + int heightValue = Convert.ToInt32((double)width.Value / aspect); + return new ImageDimensions(width.Value, heightValue); } var height = options.Height ?? options.MaxHeight ?? 200; - var widthValue = aspect * height; - return new ImageSize(widthValue, height); + int widthValue = Convert.ToInt32(aspect * height); + return new ImageDimensions(widthValue, height); } private static double GetEstimatedAspectRatio(ImageType type, BaseItem item) diff --git a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs index 00d93930f..db432f500 100644 --- a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs +++ b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs @@ -57,7 +57,7 @@ namespace MediaBrowser.Controller.Drawing !MaxHeight.HasValue; } - public bool HasDefaultOptions(string originalImagePath, ImageSize? size) + public bool HasDefaultOptions(string originalImagePath, ImageDimensions? size) { if (!size.HasValue) { diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 5534576f1..0d1a0ce86 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -2235,11 +2235,7 @@ namespace MediaBrowser.Controller.Entities /// </exception> /// <exception cref="ArgumentNullException">item</exception> public string GetImagePath(ImageType imageType, int imageIndex) - { - var info = GetImageInfo(imageType, imageIndex); - - return info == null ? null : info.Path; - } + => GetImageInfo(imageType, imageIndex)?.Path; /// <summary> /// Gets the image information. diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index e086f9d33..d8d0a1aa3 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -424,11 +424,9 @@ namespace MediaBrowser.Controller.MediaEncoding if (state.VideoStream != null && state.VideoStream.Width.HasValue) { // This is hacky but not sure how to get the exact subtitle resolution - double height = state.VideoStream.Width.Value; - height /= 16; - height *= 9; + int height = Convert.ToInt32((double)state.VideoStream.Width.Value / 16.0 * 9.0); - arg += string.Format(" -canvas_size {0}:{1}", state.VideoStream.Width.Value.ToString(CultureInfo.InvariantCulture), Convert.ToInt32(height).ToString(CultureInfo.InvariantCulture)); + arg += string.Format(" -canvas_size {0}:{1}", state.VideoStream.Width.Value.ToString(CultureInfo.InvariantCulture), height.ToString(CultureInfo.InvariantCulture)); } var subtitlePath = state.SubtitleStream.Path; diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs index 6651a6d70..1fe8856cc 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs @@ -319,7 +319,7 @@ namespace MediaBrowser.Controller.MediaEncoding { if (VideoStream != null && VideoStream.Width.HasValue && VideoStream.Height.HasValue) { - var size = new ImageSize + var size = new ImageDimensions { Width = VideoStream.Width.Value, Height = VideoStream.Height.Value @@ -331,7 +331,7 @@ namespace MediaBrowser.Controller.MediaEncoding BaseRequest.MaxWidth ?? 0, BaseRequest.MaxHeight ?? 0); - return Convert.ToInt32(newSize.Width); + return newSize.Width; } if (!IsVideoRequest) @@ -349,7 +349,7 @@ namespace MediaBrowser.Controller.MediaEncoding { if (VideoStream != null && VideoStream.Width.HasValue && VideoStream.Height.HasValue) { - var size = new ImageSize + var size = new ImageDimensions { Width = VideoStream.Width.Value, Height = VideoStream.Height.Value @@ -361,7 +361,7 @@ namespace MediaBrowser.Controller.MediaEncoding BaseRequest.MaxWidth ?? 0, BaseRequest.MaxHeight ?? 0); - return Convert.ToInt32(newSize.Height); + return newSize.Height; } if (!IsVideoRequest) diff --git a/MediaBrowser.Controller/Providers/IImageEnhancer.cs b/MediaBrowser.Controller/Providers/IImageEnhancer.cs index 2de657854..c27c00ca2 100644 --- a/MediaBrowser.Controller/Providers/IImageEnhancer.cs +++ b/MediaBrowser.Controller/Providers/IImageEnhancer.cs @@ -37,7 +37,7 @@ namespace MediaBrowser.Controller.Providers /// <param name="imageIndex">Index of the image.</param> /// <param name="originalImageSize">Size of the original image.</param> /// <returns>ImageSize.</returns> - ImageSize GetEnhancedImageSize(BaseItem item, ImageType imageType, int imageIndex, ImageSize originalImageSize); + ImageDimensions GetEnhancedImageSize(BaseItem item, ImageType imageType, int imageIndex, ImageDimensions originalImageSize); EnhancedImageInfo GetEnhancedImageInfo(BaseItem item, string inputFile, ImageType imageType, int imageIndex); diff --git a/MediaBrowser.Model/Activity/IActivityManager.cs b/MediaBrowser.Model/Activity/IActivityManager.cs index bbd7b6f2d..897d93d79 100644 --- a/MediaBrowser.Model/Activity/IActivityManager.cs +++ b/MediaBrowser.Model/Activity/IActivityManager.cs @@ -1,7 +1,6 @@ using System; -using System.Collections.Generic; -using System.Threading.Tasks; using MediaBrowser.Model.Events; +using MediaBrowser.Model.Querying; namespace MediaBrowser.Model.Activity { @@ -9,8 +8,10 @@ namespace MediaBrowser.Model.Activity { event EventHandler<GenericEventArgs<ActivityLogEntry>> EntryCreated; - Task CreateAsync(ActivityLogEntry entry); + void Create(ActivityLogEntry entry); - IEnumerable<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, bool? hasUserId, int? x, int? y); + QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, int? startIndex, int? limit); + + QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, bool? hasUserId, int? x, int? y); } } diff --git a/MediaBrowser.Model/Activity/IActivityRepository.cs b/MediaBrowser.Model/Activity/IActivityRepository.cs index 3ed6175ce..f0e3b902c 100644 --- a/MediaBrowser.Model/Activity/IActivityRepository.cs +++ b/MediaBrowser.Model/Activity/IActivityRepository.cs @@ -1,12 +1,12 @@ -using System.Linq; -using System.Threading.Tasks; +using System; +using MediaBrowser.Model.Querying; namespace MediaBrowser.Model.Activity { public interface IActivityRepository { - Task CreateAsync(ActivityLogEntry entry); + void Create(ActivityLogEntry entry); - IQueryable<ActivityLogEntry> GetActivityLogEntries(); + QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, bool? z, int? startIndex, int? limit); } } diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs index 522c10980..6d03a03b0 100644 --- a/MediaBrowser.Model/Dlna/StreamInfo.cs +++ b/MediaBrowser.Model/Dlna/StreamInfo.cs @@ -953,22 +953,11 @@ namespace MediaBrowser.Model.Dlna if (videoStream != null && videoStream.Width.HasValue && videoStream.Height.HasValue) { - var size = new ImageSize - { - Width = videoStream.Width.Value, - Height = videoStream.Height.Value - }; - - double? maxWidth = MaxWidth.HasValue ? (double)MaxWidth.Value : (double?)null; - double? maxHeight = MaxHeight.HasValue ? (double)MaxHeight.Value : (double?)null; + ImageDimensions size = new ImageDimensions(videoStream.Width.Value, videoStream.Height.Value); - var newSize = DrawingUtils.Resize(size, - 0, - 0, - maxWidth ?? 0, - maxHeight ?? 0); + size = DrawingUtils.Resize(size, 0, 0, MaxWidth ?? 0, MaxHeight ?? 0); - return Convert.ToInt32(newSize.Width); + return size.Width; } return MaxWidth; @@ -983,22 +972,11 @@ namespace MediaBrowser.Model.Dlna if (videoStream != null && videoStream.Width.HasValue && videoStream.Height.HasValue) { - var size = new ImageSize - { - Width = videoStream.Width.Value, - Height = videoStream.Height.Value - }; - - double? maxWidth = MaxWidth.HasValue ? (double)MaxWidth.Value : (double?)null; - double? maxHeight = MaxHeight.HasValue ? (double)MaxHeight.Value : (double?)null; + ImageDimensions size = new ImageDimensions(videoStream.Width.Value, videoStream.Height.Value); - var newSize = DrawingUtils.Resize(size, - 0, - 0, - maxWidth ?? 0, - maxHeight ?? 0); + size = DrawingUtils.Resize(size, 0, 0, MaxWidth ?? 0, MaxHeight ?? 0); - return Convert.ToInt32(newSize.Height); + return size.Height; } return MaxHeight; diff --git a/MediaBrowser.Model/Drawing/DrawingUtils.cs b/MediaBrowser.Model/Drawing/DrawingUtils.cs index fbd074218..9fe85512f 100644 --- a/MediaBrowser.Model/Drawing/DrawingUtils.cs +++ b/MediaBrowser.Model/Drawing/DrawingUtils.cs @@ -1,3 +1,5 @@ +using System; + namespace MediaBrowser.Model.Drawing { /// <summary> @@ -14,27 +16,25 @@ namespace MediaBrowser.Model.Drawing /// <param name="maxWidth">A max fixed width, if desired</param> /// <param name="maxHeight">A max fixed height, if desired</param> /// <returns>A new size object</returns> - public static ImageSize Resize(ImageSize size, - double width, - double height, - double maxWidth, - double maxHeight) + public static ImageDimensions Resize(ImageDimensions size, + int width, + int height, + int maxWidth, + int maxHeight) { - double newWidth = size.Width; - double newHeight = size.Height; + int newWidth = size.Width; + int newHeight = size.Height; if (width > 0 && height > 0) { newWidth = width; newHeight = height; } - else if (height > 0) { newWidth = GetNewWidth(newHeight, newWidth, height); newHeight = height; } - else if (width > 0) { newHeight = GetNewHeight(newHeight, newWidth, width); @@ -53,7 +53,7 @@ namespace MediaBrowser.Model.Drawing newWidth = maxWidth; } - return new ImageSize { Width = newWidth, Height = newHeight }; + return new ImageDimensions(newWidth, newHeight); } /// <summary> @@ -62,15 +62,9 @@ namespace MediaBrowser.Model.Drawing /// <param name="currentHeight">Height of the current.</param> /// <param name="currentWidth">Width of the current.</param> /// <param name="newHeight">The new height.</param> - /// <returns>System.Double.</returns> - private static double GetNewWidth(double currentHeight, double currentWidth, double newHeight) - { - double scaleFactor = newHeight; - scaleFactor /= currentHeight; - scaleFactor *= currentWidth; - - return scaleFactor; - } + /// <returns>the new width</returns> + private static int GetNewWidth(int currentHeight, int currentWidth, int newHeight) + => Convert.ToInt32((double)newHeight / currentHeight * currentWidth); /// <summary> /// Gets the new height. @@ -79,13 +73,7 @@ namespace MediaBrowser.Model.Drawing /// <param name="currentWidth">Width of the current.</param> /// <param name="newWidth">The new width.</param> /// <returns>System.Double.</returns> - private static double GetNewHeight(double currentHeight, double currentWidth, double newWidth) - { - double scaleFactor = newWidth; - scaleFactor /= currentWidth; - scaleFactor *= currentHeight; - - return scaleFactor; - } + private static int GetNewHeight(int currentHeight, int currentWidth, int newWidth) + => Convert.ToInt32((double)newWidth / currentWidth * currentHeight); } } diff --git a/MediaBrowser.Model/Drawing/ImageSize.cs b/MediaBrowser.Model/Drawing/ImageSize.cs index 87764bbf4..75591d83d 100644 --- a/MediaBrowser.Model/Drawing/ImageSize.cs +++ b/MediaBrowser.Model/Drawing/ImageSize.cs @@ -1,36 +1,23 @@ -using System.Globalization; - namespace MediaBrowser.Model.Drawing { /// <summary> /// Struct ImageSize /// </summary> - public struct ImageSize + public struct ImageDimensions { - private double _height; - private double _width; - /// <summary> /// Gets or sets the height. /// </summary> /// <value>The height.</value> - public double Height - { - get => _height; - set => _height = value; - } + public int Height { get; set; } /// <summary> /// Gets or sets the width. /// </summary> /// <value>The width.</value> - public double Width - { - get => _width; - set => _width = value; - } + public int Width { get; set; } - public bool Equals(ImageSize size) + public bool Equals(ImageDimensions size) { return Width.Equals(size.Width) && Height.Equals(size.Height); } @@ -40,46 +27,10 @@ namespace MediaBrowser.Model.Drawing return string.Format("{0}-{1}", Width, Height); } - public ImageSize(string value) + public ImageDimensions(int width, int height) { - _width = 0; - - _height = 0; - - ParseValue(value); - } - - public ImageSize(int width, int height) - { - _width = width; - _height = height; - } - - public ImageSize(double width, double height) - { - _width = width; - _height = height; - } - - private void ParseValue(string value) - { - if (!string.IsNullOrEmpty(value)) - { - string[] parts = value.Split('-'); - - if (parts.Length == 2) - { - if (double.TryParse(parts[0], NumberStyles.Any, CultureInfo.InvariantCulture, out var val)) - { - _width = val; - } - - if (double.TryParse(parts[1], NumberStyles.Any, CultureInfo.InvariantCulture, out val)) - { - _height = val; - } - } - } + Width = width; + Height = height; } } } |
