From ed8159117519209418d04e293e116ad4b6711492 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 27 Aug 2017 20:33:05 -0400 Subject: update dto methods --- Emby.Server.Implementations/Dto/DtoService.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'Emby.Server.Implementations/Dto') diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index 0282572708..22793e6529 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -87,17 +87,17 @@ namespace Emby.Server.Implementations.Dto return GetBaseItemDto(item, options, user, owner); } - public Task GetBaseItemDtos(List items, DtoOptions options, User user = null, BaseItem owner = null) + public BaseItemDto[] GetBaseItemDtos(List items, DtoOptions options, User user = null, BaseItem owner = null) { return GetBaseItemDtos(items, items.Count, options, user, owner); } - public Task GetBaseItemDtos(BaseItem[] items, DtoOptions options, User user = null, BaseItem owner = null) + public BaseItemDto[] GetBaseItemDtos(BaseItem[] items, DtoOptions options, User user = null, BaseItem owner = null) { return GetBaseItemDtos(items, items.Length, options, user, owner); } - public async Task GetBaseItemDtos(IEnumerable items, int itemCount, DtoOptions options, User user = null, BaseItem owner = null) + public BaseItemDto[] GetBaseItemDtos(IEnumerable items, int itemCount, DtoOptions options, User user = null, BaseItem owner = null) { if (items == null) { @@ -157,12 +157,13 @@ namespace Emby.Server.Implementations.Dto if (programTuples.Count > 0) { - await _livetvManager().AddInfoToProgramDto(programTuples, options.Fields, user).ConfigureAwait(false); + var task = _livetvManager().AddInfoToProgramDto(programTuples, options.Fields, user); + Task.WaitAll(task); } if (channelTuples.Count > 0) { - await _livetvManager().AddChannelInfo(channelTuples, options, user).ConfigureAwait(false); + _livetvManager().AddChannelInfo(channelTuples, options, user); } return returnItems; @@ -177,8 +178,7 @@ namespace Emby.Server.Implementations.Dto if (tvChannel != null) { var list = new List> { new Tuple(dto, tvChannel) }; - var task = _livetvManager().AddChannelInfo(list, options, user); - Task.WaitAll(task); + _livetvManager().AddChannelInfo(list, options, user); } else if (item is LiveTvProgram) { -- cgit v1.2.3 From 8de80d43ba496535aac89d9ec260d8dc2550169b Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 30 Aug 2017 14:06:54 -0400 Subject: update ResolutionNormalizer --- Emby.Server.Implementations/Dto/DtoService.cs | 2 + .../HttpServer/HttpResultFactory.cs | 81 +++++----------------- MediaBrowser.Api/EnvironmentService.cs | 2 +- MediaBrowser.Model/Dlna/ResolutionNormalizer.cs | 6 +- 4 files changed, 25 insertions(+), 66 deletions(-) (limited to 'Emby.Server.Implementations/Dto') diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index 22793e6529..a0bbd171f8 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -418,6 +418,8 @@ namespace Emby.Server.Implementations.Dto { dto.Type = "Recording"; dto.CanDownload = false; + dto.RunTimeTicks = null; + if (!string.IsNullOrWhiteSpace(dto.SeriesName)) { dto.EpisodeTitle = dto.Name; diff --git a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs index 7bd8fe2bf9..d030068465 100644 --- a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs +++ b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs @@ -487,69 +487,8 @@ namespace Emby.Server.Implementations.HttpServer return result; } - var compress = ShouldCompressResponse(requestContext, contentType); - var hasHeaders = await GetStaticResult(requestContext, options, compress).ConfigureAwait(false); - AddResponseHeaders(hasHeaders, options.ResponseHeaders); - - return hasHeaders; - } - - /// - /// Shoulds the compress response. - /// - /// The request context. - /// Type of the content. - /// true if XXXX, false otherwise - private bool ShouldCompressResponse(IRequest requestContext, string contentType) - { - // It will take some work to support compression with byte range requests - if (!string.IsNullOrWhiteSpace(requestContext.Headers.Get("Range"))) - { - return false; - } - - // Don't compress media - if (contentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase)) - { - return false; - } - - // Don't compress images - if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase)) - { - return false; - } - - if (contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase)) - { - return false; - } - if (contentType.StartsWith("application/", StringComparison.OrdinalIgnoreCase)) - { - if (string.Equals(contentType, "application/x-javascript", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - if (string.Equals(contentType, "application/xml", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - return false; - } - - return true; - } - - /// - /// The us culture - /// - private static readonly CultureInfo UsCulture = new CultureInfo("en-US"); - - private async Task GetStaticResult(IRequest requestContext, StaticResultOptions options, bool compress) - { var isHeadRequest = options.IsHeadRequest; var factoryFn = options.ContentFactory; - var contentType = options.ContentType; var responseHeaders = options.ResponseHeaders; //var requestedCompressionType = GetCompressionType(requestContext); @@ -558,22 +497,28 @@ namespace Emby.Server.Implementations.HttpServer if (!isHeadRequest && !string.IsNullOrWhiteSpace(options.Path)) { - return new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem) + var hasHeaders = new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem) { OnComplete = options.OnComplete, OnError = options.OnError, FileShare = options.FileShare }; + + AddResponseHeaders(hasHeaders, options.ResponseHeaders); + return hasHeaders; } if (!string.IsNullOrWhiteSpace(rangeHeader)) { var stream = await factoryFn().ConfigureAwait(false); - return new RangeRequestWriter(rangeHeader, stream, contentType, isHeadRequest, _logger) + var hasHeaders = new RangeRequestWriter(rangeHeader, stream, contentType, isHeadRequest, _logger) { OnComplete = options.OnComplete }; + + AddResponseHeaders(hasHeaders, options.ResponseHeaders); + return hasHeaders; } else { @@ -588,14 +533,22 @@ namespace Emby.Server.Implementations.HttpServer return GetHttpResult(new byte[] { }, contentType, true); } - return new StreamWriter(stream, contentType, _logger) + var hasHeaders = new StreamWriter(stream, contentType, _logger) { OnComplete = options.OnComplete, OnError = options.OnError }; + + AddResponseHeaders(hasHeaders, options.ResponseHeaders); + return hasHeaders; } } + /// + /// The us culture + /// + private static readonly CultureInfo UsCulture = new CultureInfo("en-US"); + /// /// Adds the caching responseHeaders. /// diff --git a/MediaBrowser.Api/EnvironmentService.cs b/MediaBrowser.Api/EnvironmentService.cs index bc6101d6cd..400169ac55 100644 --- a/MediaBrowser.Api/EnvironmentService.cs +++ b/MediaBrowser.Api/EnvironmentService.cs @@ -298,7 +298,7 @@ namespace MediaBrowser.Api /// IEnumerable{FileSystemEntryInfo}. private IEnumerable GetFileSystemEntries(GetDirectoryContents request) { - var entries = _fileSystem.GetFileSystemEntries(request.Path).Where(i => + var entries = _fileSystem.GetFileSystemEntries(request.Path).OrderBy(i => i.FullName).Where(i => { if (!request.IncludeHidden && i.IsHidden) { diff --git a/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs b/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs index ae74e255b0..de832314c9 100644 --- a/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs +++ b/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs @@ -58,12 +58,16 @@ namespace MediaBrowser.Model.Dlna private static ResolutionConfiguration GetResolutionConfiguration(int outputBitrate) { + ResolutionConfiguration previousOption = null; + foreach (var config in Configurations) { if (outputBitrate <= config.MaxBitrate) { - return config; + return previousOption ?? config; } + + previousOption = config; } return null; -- cgit v1.2.3 From eb63e0d264d563b100a353c12859f226e9303910 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 7 Sep 2017 14:17:18 -0400 Subject: update image processor --- Emby.Drawing/ImageProcessor.cs | 94 +++++++---- Emby.Server.Implementations/ApplicationHost.cs | 4 +- .../Data/SqliteItemRepository.cs | 2 +- .../Data/SqliteUserDataRepository.cs | 2 +- Emby.Server.Implementations/Dto/DtoService.cs | 3 +- .../Emby.Server.Implementations.csproj | 1 + .../Services/SwaggerService.cs | 183 +++++++++++++++++++++ MediaBrowser.Api/Images/ImageService.cs | 47 +----- MediaBrowser.Api/UserLibrary/ItemsService.cs | 14 ++ MediaBrowser.Controller/Drawing/IImageProcessor.cs | 2 + .../Drawing/ImageProcessingOptions.cs | 8 +- MediaBrowser.Controller/Entities/Movies/BoxSet.cs | 28 ++++ .../Providers/IImageEnhancer.cs | 7 + MediaBrowser.Model/Dlna/StreamBuilder.cs | 122 ++++++++++++-- 14 files changed, 428 insertions(+), 89 deletions(-) create mode 100644 Emby.Server.Implementations/Services/SwaggerService.cs (limited to 'Emby.Server.Implementations/Dto') diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs index 1d3f4a8e39..9e941b38c7 100644 --- a/Emby.Drawing/ImageProcessor.cs +++ b/Emby.Drawing/ImageProcessor.cs @@ -203,10 +203,9 @@ namespace Emby.Drawing } private static readonly string[] TransparentImageTypes = new string[] { ".png", ".webp" }; - private bool SupportsTransparency(string path) + public bool SupportsTransparency(string path) { return TransparentImageTypes.Contains(Path.GetExtension(path) ?? string.Empty); - ; } public async Task> ProcessImage(ImageProcessingOptions options) @@ -239,6 +238,7 @@ namespace Emby.Drawing var supportedImageInfo = await GetSupportedImage(originalImagePath, dateModified).ConfigureAwait(false); originalImagePath = supportedImageInfo.Item1; dateModified = supportedImageInfo.Item2; + var requiresTransparency = TransparentImageTypes.Contains(Path.GetExtension(originalImagePath) ?? string.Empty); if (options.Enhancers.Count > 0) { @@ -253,10 +253,11 @@ namespace Emby.Drawing Type = originalImage.Type, Path = originalImagePath - }, item, options.ImageIndex, options.Enhancers).ConfigureAwait(false); + }, requiresTransparency, item, options.ImageIndex, options.Enhancers).ConfigureAwait(false); originalImagePath = tuple.Item1; dateModified = tuple.Item2; + requiresTransparency = tuple.Item3; } var photo = item as Photo; @@ -268,7 +269,7 @@ namespace Emby.Drawing orientation = photo.Orientation; } - if (options.HasDefaultOptions(originalImagePath) && !autoOrient) + if (options.HasDefaultOptions(originalImagePath) && (!autoOrient || !options.RequiresAutoOrientation)) { // Just spit out the original file if all the options are default return new Tuple(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); @@ -285,7 +286,7 @@ namespace Emby.Drawing var newSize = ImageHelper.GetNewImageSize(options, originalImageSize); var quality = options.Quality; - var outputFormat = GetOutputFormat(options.SupportedOutputFormats[0]); + var outputFormat = GetOutputFormat(options.SupportedOutputFormats, requiresTransparency); var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.Blur, options.BackgroundColor, options.ForegroundLayer); try @@ -336,6 +337,34 @@ namespace Emby.Drawing } } + private ImageFormat GetOutputFormat(ImageFormat[] clientSupportedFormats, bool requiresTransparency) + { + var serverFormats = GetSupportedImageOutputFormats(); + + // Client doesn't care about format, so start with webp if supported + if (serverFormats.Contains(ImageFormat.Webp) && clientSupportedFormats.Contains(ImageFormat.Webp)) + { + return ImageFormat.Webp; + } + + // If transparency is needed and webp isn't supported, than png is the only option + if (requiresTransparency) + { + return ImageFormat.Png; + } + + foreach (var format in clientSupportedFormats) + { + if (serverFormats.Contains(format)) + { + return format; + } + } + + // We should never actually get here + return ImageFormat.Jpg; + } + private void CopyFile(string src, string destination) { try @@ -389,21 +418,6 @@ namespace Emby.Drawing return MimeTypes.GetMimeType(path); } - private ImageFormat GetOutputFormat(ImageFormat requestedFormat) - { - if (requestedFormat == ImageFormat.Webp && !_imageEncoder.SupportedOutputFormats.Contains(ImageFormat.Webp)) - { - return ImageFormat.Png; - } - - return requestedFormat; - } - - private Tuple GetResult(string path) - { - return new Tuple(path, _fileSystem.GetLastWriteTimeUtc(path)); - } - /// /// Increment this when there's a change requiring caches to be invalidated /// @@ -753,12 +767,15 @@ namespace Emby.Drawing var imageInfo = item.GetImageInfo(imageType, imageIndex); - var result = await GetEnhancedImage(imageInfo, item, imageIndex, enhancers); + var inputImageSupportsTransparency = SupportsTransparency(imageInfo.Path); + + var result = await GetEnhancedImage(imageInfo, inputImageSupportsTransparency, item, imageIndex, enhancers); return result.Item1; } - private async Task> GetEnhancedImage(ItemImageInfo image, + private async Task> GetEnhancedImage(ItemImageInfo image, + bool inputImageSupportsTransparency, IHasMetadata item, int imageIndex, List enhancers) @@ -772,12 +789,16 @@ namespace Emby.Drawing var cacheGuid = GetImageCacheTag(item, image, enhancers); // Enhance if we have enhancers - var ehnancedImagePath = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid).ConfigureAwait(false); + var ehnancedImageInfo = await GetEnhancedImageInternal(originalImagePath, item, imageType, imageIndex, enhancers, cacheGuid).ConfigureAwait(false); + + var ehnancedImagePath = ehnancedImageInfo.Item1; // If the path changed update dateModified if (!string.Equals(ehnancedImagePath, originalImagePath, StringComparison.OrdinalIgnoreCase)) { - return GetResult(ehnancedImagePath); + var treatmentRequiresTransparency = ehnancedImageInfo.Item2; + + return new Tuple(ehnancedImagePath, _fileSystem.GetLastWriteTimeUtc(ehnancedImagePath), treatmentRequiresTransparency); } } catch (Exception ex) @@ -785,7 +806,7 @@ namespace Emby.Drawing _logger.Error("Error enhancing image", ex); } - return new Tuple(originalImagePath, dateModified); + return new Tuple(originalImagePath, dateModified, inputImageSupportsTransparency); } /// @@ -803,11 +824,11 @@ namespace Emby.Drawing /// or /// item /// - private async Task GetEnhancedImageInternal(string originalImagePath, + private async Task> GetEnhancedImageInternal(string originalImagePath, IHasMetadata item, ImageType imageType, int imageIndex, - IEnumerable supportedEnhancers, + List supportedEnhancers, string cacheGuid) { if (string.IsNullOrEmpty(originalImagePath)) @@ -820,13 +841,26 @@ namespace Emby.Drawing throw new ArgumentNullException("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 - var enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + ".png"); + var cacheExtension = _imageEncoder.SupportedOutputFormats.Contains(ImageFormat.Webp) ? + ".webp" : + (treatmentRequiresTransparency ? ".png" : ".jpg"); + + var enhancedImagePath = GetCachePath(EnhancedImageCachePath, cacheGuid + cacheExtension); // Check again in case of contention if (_fileSystem.FileExists(enhancedImagePath)) { - return enhancedImagePath; + return new Tuple(enhancedImagePath, treatmentRequiresTransparency); } _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(enhancedImagePath)); @@ -845,7 +879,7 @@ namespace Emby.Drawing } - return tmpPath; + return new Tuple(tmpPath, treatmentRequiresTransparency); } /// diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index b3268b156b..673798294c 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1861,7 +1861,9 @@ namespace Emby.Server.Implementations { "mbplus.dll", "mbintros.dll", - "embytv.dll" + "embytv.dll", + "Messenger.dll", + "MediaBrowser.Plugins.TvMazeProvider.dll" }; return !exclude.Contains(filename ?? string.Empty, StringComparer.OrdinalIgnoreCase); diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 165d17a570..a07b79e109 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -114,7 +114,7 @@ namespace Emby.Server.Implementations.Data { get { - return true; + return false; } } diff --git a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs index ef1d7ba445..d078a31c9b 100644 --- a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs @@ -94,7 +94,7 @@ namespace Emby.Server.Implementations.Data { get { - return true; + return false; } } diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index a0bbd171f8..b57662e311 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -275,8 +275,7 @@ namespace Emby.Server.Implementations.Dto { var hasFullSyncInfo = options.Fields.Contains(ItemFields.SyncInfo); - if (!options.Fields.Contains(ItemFields.BasicSyncInfo) && - !hasFullSyncInfo) + if (!hasFullSyncInfo && !options.Fields.Contains(ItemFields.BasicSyncInfo)) { return; } diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 75a9d85886..719510fc39 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -496,6 +496,7 @@ + diff --git a/Emby.Server.Implementations/Services/SwaggerService.cs b/Emby.Server.Implementations/Services/SwaggerService.cs new file mode 100644 index 0000000000..4590369fab --- /dev/null +++ b/Emby.Server.Implementations/Services/SwaggerService.cs @@ -0,0 +1,183 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using MediaBrowser.Model.Services; + +namespace Emby.Server.Implementations.Services +{ + [Route("/swagger", "GET", Summary = "Gets the swagger specifications")] + [Route("/swagger.json", "GET", Summary = "Gets the swagger specifications")] + public class GetSwaggerSpec : IReturn + { + } + + public class SwaggerSpec + { + public string swagger { get; set; } + public string[] schemes { get; set; } + public SwaggerInfo info { get; set; } + public string host { get; set; } + public string basePath { get; set; } + public SwaggerTag[] tags { get; set; } + public Dictionary> paths { get; set; } + public Dictionary definitions { get; set; } + } + + public class SwaggerInfo + { + public string description { get; set; } + public string version { get; set; } + public string title { get; set; } + + public SwaggerConcactInfo contact { get; set; } + } + + public class SwaggerConcactInfo + { + public string email { get; set; } + } + + public class SwaggerTag + { + public string description { get; set; } + public string name { get; set; } + } + + public class SwaggerMethod + { + public string summary { get; set; } + public string description { get; set; } + public string[] tags { get; set; } + public string operationId { get; set; } + public string[] consumes { get; set; } + public string[] produces { get; set; } + public SwaggerParam[] parameters { get; set; } + public Dictionary responses { get; set; } + } + + public class SwaggerParam + { + public string @in { get; set; } + public string name { get; set; } + public string description { get; set; } + public bool required { get; set; } + public string type { get; set; } + public string collectionFormat { get; set; } + } + + public class SwaggerResponse + { + public string description { get; set; } + + // ex. "$ref":"#/definitions/Pet" + public Dictionary schema { get; set; } + } + + public class SwaggerDefinition + { + public string type { get; set; } + public Dictionary properties { get; set; } + } + + public class SwaggerProperty + { + public string type { get; set; } + public string format { get; set; } + public string description { get; set; } + public string[] @enum { get; set; } + public string @default { get; set; } + } + + public class SwaggerService : IService + { + private SwaggerSpec _spec; + + public object Get(GetSwaggerSpec request) + { + return _spec ?? (_spec = GetSpec()); + } + + private SwaggerSpec GetSpec() + { + var spec = new SwaggerSpec + { + schemes = new[] { "http" }, + tags = GetTags(), + swagger = "2.0", + info = new SwaggerInfo + { + title = "Emby Server API", + version = "1", + description = "Explore the Emby Server API", + contact = new SwaggerConcactInfo + { + email = "api@emby.media" + } + }, + paths = GetPaths(), + definitions = GetDefinitions() + }; + + return spec; + } + + + private SwaggerTag[] GetTags() + { + return new SwaggerTag[] { }; + } + + private Dictionary GetDefinitions() + { + return new Dictionary(); + } + + private Dictionary> GetPaths() + { + var paths = new Dictionary>(); + + var all = ServiceController.Instance.RestPathMap.ToList(); + + foreach (var current in all) + { + foreach (var info in current.Value) + { + paths[info.Path] = GetPathInfo(info); + } + } + + return paths; + } + + private Dictionary GetPathInfo(RestPath info) + { + var result = new Dictionary(); + + foreach (var verb in info.Verbs) + { + result[verb] = new SwaggerMethod + { + summary = info.Summary, + produces = new[] + { + "application/json", + "application/xml" + }, + consumes = new[] + { + "application/json", + "application/xml" + }, + operationId = info.RequestType.Name, + tags = new string[] { }, + + parameters = new SwaggerParam[] { } + }; + } + + return result; + } + } +} diff --git a/MediaBrowser.Api/Images/ImageService.cs b/MediaBrowser.Api/Images/ImageService.cs index 69d4a4ab45..f8481517db 100644 --- a/MediaBrowser.Api/Images/ImageService.cs +++ b/MediaBrowser.Api/Images/ImageService.cs @@ -567,7 +567,7 @@ namespace MediaBrowser.Api.Images cropwhitespace = request.CropWhitespace.Value; } - var outputFormats = GetOutputFormats(request, imageInfo, cropwhitespace, supportedImageEnhancers); + var outputFormats = GetOutputFormats(request); TimeSpan? cacheDuration = null; @@ -597,7 +597,7 @@ namespace MediaBrowser.Api.Images ImageRequest request, ItemImageInfo image, bool cropwhitespace, - List supportedFormats, + ImageFormat[] supportedFormats, List enhancers, TimeSpan? cacheDuration, IDictionary headers, @@ -644,55 +644,18 @@ namespace MediaBrowser.Api.Images }).ConfigureAwait(false); } - private List GetOutputFormats(ImageRequest request, ItemImageInfo image, bool cropwhitespace, List enhancers) + private ImageFormat[] GetOutputFormats(ImageRequest request) { if (!string.IsNullOrWhiteSpace(request.Format)) { ImageFormat format; if (Enum.TryParse(request.Format, true, out format)) { - return new List { format }; + return new ImageFormat[] { format }; } } - var extension = Path.GetExtension(image.Path); - ImageFormat? inputFormat = null; - - if (string.Equals(extension, ".jpg", StringComparison.OrdinalIgnoreCase) || - string.Equals(extension, ".jpeg", StringComparison.OrdinalIgnoreCase)) - { - inputFormat = ImageFormat.Jpg; - } - else if (string.Equals(extension, ".png", StringComparison.OrdinalIgnoreCase)) - { - inputFormat = ImageFormat.Png; - } - - var clientSupportedFormats = GetClientSupportedFormats(); - - var serverFormats = _imageProcessor.GetSupportedImageOutputFormats(); - var outputFormats = new List(); - - // Client doesn't care about format, so start with webp if supported - if (serverFormats.Contains(ImageFormat.Webp) && clientSupportedFormats.Contains(ImageFormat.Webp)) - { - outputFormats.Add(ImageFormat.Webp); - } - - if (enhancers.Count > 0) - { - outputFormats.Add(ImageFormat.Png); - } - - if (inputFormat.HasValue && inputFormat.Value == ImageFormat.Jpg) - { - outputFormats.Add(ImageFormat.Jpg); - } - - // We can't predict if there will be transparency or not, so play it safe - outputFormats.Add(ImageFormat.Png); - - return outputFormats; + return GetClientSupportedFormats(); } private ImageFormat[] GetClientSupportedFormats() diff --git a/MediaBrowser.Api/UserLibrary/ItemsService.cs b/MediaBrowser.Api/UserLibrary/ItemsService.cs index fb48f65e4b..5919c50d48 100644 --- a/MediaBrowser.Api/UserLibrary/ItemsService.cs +++ b/MediaBrowser.Api/UserLibrary/ItemsService.cs @@ -408,6 +408,20 @@ namespace MediaBrowser.Api.UserLibrary }).Where(i => i != null).Select(i => i.Id.ToString("N")).ToArray(); } + // Apply default sorting if none requested + if (query.OrderBy.Length == 0) + { + // Albums by artist + if (query.ArtistIds.Length > 0 && query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], "MusicAlbum", StringComparison.OrdinalIgnoreCase)) + { + query.OrderBy = new Tuple[] + { + new Tuple(ItemSortBy.ProductionYear, SortOrder.Descending), + new Tuple(ItemSortBy.SortName, SortOrder.Ascending) + }; + } + } + return query; } } diff --git a/MediaBrowser.Controller/Drawing/IImageProcessor.cs b/MediaBrowser.Controller/Drawing/IImageProcessor.cs index 113f823f5f..d7b68d1e7e 100644 --- a/MediaBrowser.Controller/Drawing/IImageProcessor.cs +++ b/MediaBrowser.Controller/Drawing/IImageProcessor.cs @@ -118,5 +118,7 @@ namespace MediaBrowser.Controller.Drawing IImageEncoder ImageEncoder { get; set; } void SaveImageSize(string path, DateTime imageDateModified, ImageSize size); + + bool SupportsTransparency(string path); } } diff --git a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs index fac21c7445..26283b5eae 100644 --- a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs +++ b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs @@ -10,6 +10,11 @@ namespace MediaBrowser.Controller.Drawing { public class ImageProcessingOptions { + public ImageProcessingOptions() + { + RequiresAutoOrientation = true; + } + public string ItemId { get; set; } public string ItemType { get; set; } public IHasMetadata Item { get; set; } @@ -32,7 +37,7 @@ namespace MediaBrowser.Controller.Drawing public List Enhancers { get; set; } - public List SupportedOutputFormats { get; set; } + public ImageFormat[] SupportedOutputFormats { get; set; } public bool AddPlayedIndicator { get; set; } @@ -43,6 +48,7 @@ namespace MediaBrowser.Controller.Drawing public string BackgroundColor { get; set; } public string ForegroundLayer { get; set; } + public bool RequiresAutoOrientation { get; set; } public bool HasDefaultOptions(string originalImagePath) { diff --git a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs index 900e8a6646..bd8d9024d4 100644 --- a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs +++ b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs @@ -80,15 +80,43 @@ namespace MediaBrowser.Controller.Entities.Movies protected override IEnumerable GetNonCachedChildren(IDirectoryService directoryService) { + if (IsLegacyBoxSet) + { + return base.GetNonCachedChildren(directoryService); + } return new List(); } protected override List LoadChildren() { + if (IsLegacyBoxSet) + { + return base.LoadChildren(); + } + // Save a trip to the database return new List(); } + [IgnoreDataMember] + private bool IsLegacyBoxSet + { + get + { + if (string.IsNullOrWhiteSpace(Path)) + { + return false; + } + + if (LinkedChildren.Length > 0) + { + return false; + } + + return !FileSystem.ContainsSubPath(ConfigurationManager.ApplicationPaths.DataPath, Path); + } + } + [IgnoreDataMember] public override bool IsPreSorted { diff --git a/MediaBrowser.Controller/Providers/IImageEnhancer.cs b/MediaBrowser.Controller/Providers/IImageEnhancer.cs index a993f536d9..90f7296c65 100644 --- a/MediaBrowser.Controller/Providers/IImageEnhancer.cs +++ b/MediaBrowser.Controller/Providers/IImageEnhancer.cs @@ -39,6 +39,8 @@ namespace MediaBrowser.Controller.Providers /// ImageSize. ImageSize GetEnhancedImageSize(IHasMetadata item, ImageType imageType, int imageIndex, ImageSize originalImageSize); + EnhancedImageInfo GetEnhancedImageInfo(IHasMetadata item, string inputFile, ImageType imageType, int imageIndex); + /// /// Enhances the image async. /// @@ -51,4 +53,9 @@ namespace MediaBrowser.Controller.Providers /// Task EnhanceImageAsync(IHasMetadata item, string inputFile, string outputFile, ImageType imageType, int imageIndex); } + + public class EnhancedImageInfo + { + public bool RequiresTransparency { get; set; } + } } \ No newline at end of file diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 10c6a05c0f..a5ec0f26c9 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -849,8 +849,6 @@ namespace MediaBrowser.Model.Dlna } } } - ApplyTranscodingConditions(playlistItem, audioTranscodingConditions); - // Honor requested max channels if (options.MaxAudioChannels.HasValue) { @@ -878,6 +876,9 @@ namespace MediaBrowser.Model.Dlna var longBitrate = Math.Max(Math.Min(videoBitrate, currentValue), 64000); playlistItem.VideoBitrate = longBitrate > int.MaxValue ? int.MaxValue : Convert.ToInt32(longBitrate); } + + // Do this after initial values are set to account for greater than/less than conditions + ApplyTranscodingConditions(playlistItem, audioTranscodingConditions); } playlistItem.TranscodeReasons = transcodeReasons; @@ -1430,7 +1431,18 @@ namespace MediaBrowser.Model.Dlna int num; if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num)) { - item.AudioBitrate = num; + if (condition.Condition == ProfileConditionType.Equals) + { + item.AudioBitrate = num; + } + else if (condition.Condition == ProfileConditionType.LessThanEqual) + { + item.AudioBitrate = Math.Min(num, item.AudioBitrate ?? num); + } + else if (condition.Condition == ProfileConditionType.GreaterThanEqual) + { + item.AudioBitrate = Math.Max(num, item.AudioBitrate ?? num); + } } break; } @@ -1439,7 +1451,18 @@ namespace MediaBrowser.Model.Dlna int num; if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num)) { - item.MaxAudioChannels = num; + if (condition.Condition == ProfileConditionType.Equals) + { + item.MaxAudioChannels = num; + } + else if (condition.Condition == ProfileConditionType.LessThanEqual) + { + item.MaxAudioChannels = Math.Min(num, item.MaxAudioChannels ?? num); + } + else if (condition.Condition == ProfileConditionType.GreaterThanEqual) + { + item.MaxAudioChannels = Math.Max(num, item.MaxAudioChannels ?? num); + } } break; } @@ -1507,7 +1530,18 @@ namespace MediaBrowser.Model.Dlna int num; if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num)) { - item.MaxRefFrames = num; + if (condition.Condition == ProfileConditionType.Equals) + { + item.MaxRefFrames = num; + } + else if (condition.Condition == ProfileConditionType.LessThanEqual) + { + item.MaxRefFrames = Math.Min(num, item.MaxRefFrames ?? num); + } + else if (condition.Condition == ProfileConditionType.GreaterThanEqual) + { + item.MaxRefFrames = Math.Max(num, item.MaxRefFrames ?? num); + } } break; } @@ -1516,7 +1550,18 @@ namespace MediaBrowser.Model.Dlna int num; if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num)) { - item.MaxVideoBitDepth = num; + if (condition.Condition == ProfileConditionType.Equals) + { + item.MaxVideoBitDepth = num; + } + else if (condition.Condition == ProfileConditionType.LessThanEqual) + { + item.MaxVideoBitDepth = Math.Min(num, item.MaxVideoBitDepth ?? num); + } + else if (condition.Condition == ProfileConditionType.GreaterThanEqual) + { + item.MaxVideoBitDepth = Math.Max(num, item.MaxVideoBitDepth ?? num); + } } break; } @@ -1530,7 +1575,18 @@ namespace MediaBrowser.Model.Dlna int num; if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num)) { - item.MaxHeight = num; + if (condition.Condition == ProfileConditionType.Equals) + { + item.MaxHeight = num; + } + else if (condition.Condition == ProfileConditionType.LessThanEqual) + { + item.MaxHeight = Math.Min(num, item.MaxHeight ?? num); + } + else if (condition.Condition == ProfileConditionType.GreaterThanEqual) + { + item.MaxHeight = Math.Max(num, item.MaxHeight ?? num); + } } break; } @@ -1539,7 +1595,18 @@ namespace MediaBrowser.Model.Dlna int num; if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num)) { - item.VideoBitrate = num; + if (condition.Condition == ProfileConditionType.Equals) + { + item.VideoBitrate = num; + } + else if (condition.Condition == ProfileConditionType.LessThanEqual) + { + item.VideoBitrate = Math.Min(num, item.VideoBitrate ?? num); + } + else if (condition.Condition == ProfileConditionType.GreaterThanEqual) + { + item.VideoBitrate = Math.Max(num, item.VideoBitrate ?? num); + } } break; } @@ -1548,7 +1615,18 @@ namespace MediaBrowser.Model.Dlna float num; if (float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num)) { - item.MaxFramerate = num; + if (condition.Condition == ProfileConditionType.Equals) + { + item.MaxFramerate = num; + } + else if (condition.Condition == ProfileConditionType.LessThanEqual) + { + item.MaxFramerate = Math.Min(num, item.MaxFramerate ?? num); + } + else if (condition.Condition == ProfileConditionType.GreaterThanEqual) + { + item.MaxFramerate = Math.Max(num, item.MaxFramerate ?? num); + } } break; } @@ -1557,7 +1635,18 @@ namespace MediaBrowser.Model.Dlna int num; if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num)) { - item.VideoLevel = num; + if (condition.Condition == ProfileConditionType.Equals) + { + item.VideoLevel = num; + } + else if (condition.Condition == ProfileConditionType.LessThanEqual) + { + item.VideoLevel = Math.Min(num, item.VideoLevel ?? num); + } + else if (condition.Condition == ProfileConditionType.GreaterThanEqual) + { + item.VideoLevel = Math.Max(num, item.VideoLevel ?? num); + } } break; } @@ -1566,7 +1655,18 @@ namespace MediaBrowser.Model.Dlna int num; if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num)) { - item.MaxWidth = num; + if (condition.Condition == ProfileConditionType.Equals) + { + item.MaxWidth = num; + } + else if (condition.Condition == ProfileConditionType.LessThanEqual) + { + item.MaxWidth = Math.Min(num, item.MaxWidth ?? num); + } + else if (condition.Condition == ProfileConditionType.GreaterThanEqual) + { + item.MaxWidth = Math.Max(num, item.MaxWidth ?? num); + } } break; } -- cgit v1.2.3 From cdd79ec7e2fcea806be7a9b50764b1ad473d5970 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 18 Sep 2017 12:52:22 -0400 Subject: update owned items --- .../Collections/CollectionImageProvider.cs | 2 +- .../Data/SqliteItemRepository.cs | 50 +++++++--- Emby.Server.Implementations/Dto/DtoService.cs | 2 +- .../EntryPoints/LibraryChangedNotifier.cs | 10 +- .../EntryPoints/RefreshUsersMetadata.cs | 59 ++++++++--- .../EntryPoints/UserDataChangeNotifier.cs | 2 +- Emby.Server.Implementations/IO/FileRefresher.cs | 2 +- .../Library/LibraryManager.cs | 36 ++++--- Emby.Server.Implementations/Library/UserManager.cs | 9 +- .../LiveTv/EmbyTV/DirectRecorder.cs | 4 + .../LiveTv/EmbyTV/EmbyTV.cs | 54 +++++------ .../LiveTv/LiveTvManager.cs | 6 +- .../TunerHosts/HdHomerun/HdHomerunHttpStream.cs | 2 +- .../Playlists/PlaylistImageProvider.cs | 2 +- .../Entities/AggregateFolder.cs | 2 +- MediaBrowser.Controller/Entities/BaseItem.cs | 108 ++++++++++++++++----- .../Entities/CollectionFolder.cs | 2 +- MediaBrowser.Controller/Entities/Folder.cs | 103 +++++++++++++------- MediaBrowser.Controller/Entities/IHasTrailers.cs | 2 +- MediaBrowser.Controller/Entities/ItemImageInfo.cs | 6 -- MediaBrowser.Controller/Entities/Movies/Movie.cs | 15 ++- MediaBrowser.Controller/Entities/TV/Series.cs | 10 +- MediaBrowser.Controller/Entities/User.cs | 3 + .../Providers/MetadataRefreshOptions.cs | 28 +++++- MediaBrowser.Model/LiveTv/LiveTvOptions.cs | 1 - .../Manager/GenericPriorityQueue.cs | 15 +-- .../Manager/ItemImageProvider.cs | 5 +- MediaBrowser.Providers/Manager/MetadataService.cs | 3 +- .../MediaInfo/FFProbeProvider.cs | 5 + .../MediaInfo/VideoImageProvider.cs | 2 +- 30 files changed, 373 insertions(+), 177 deletions(-) (limited to 'Emby.Server.Implementations/Dto') diff --git a/Emby.Server.Implementations/Collections/CollectionImageProvider.cs b/Emby.Server.Implementations/Collections/CollectionImageProvider.cs index c7378956dd..f47e2d10a7 100644 --- a/Emby.Server.Implementations/Collections/CollectionImageProvider.cs +++ b/Emby.Server.Implementations/Collections/CollectionImageProvider.cs @@ -57,7 +57,7 @@ namespace Emby.Server.Implementations.Collections return subItem; } - var parent = subItem.GetParent(); + var parent = subItem.IsOwnedItem ? subItem.GetOwner() : subItem.GetParent(); if (parent != null && parent.HasImage(ImageType.Primary)) { diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 6811e42ec0..2186982d3e 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -253,6 +253,7 @@ namespace Emby.Server.Implementations.Data AddColumn(db, "TypedBaseItems", "ExternalId", "Text", existingColumnNames); AddColumn(db, "TypedBaseItems", "SeriesPresentationUniqueKey", "Text", existingColumnNames); AddColumn(db, "TypedBaseItems", "ShowId", "Text", existingColumnNames); + AddColumn(db, "TypedBaseItems", "OwnerId", "Text", existingColumnNames); existingColumnNames = GetColumnNames(db, "ItemValues"); AddColumn(db, "ItemValues", "CleanValue", "Text", existingColumnNames); @@ -459,7 +460,8 @@ namespace Emby.Server.Implementations.Data "AlbumArtists", "ExternalId", "SeriesPresentationUniqueKey", - "ShowId" + "ShowId", + "OwnerId" }; private readonly string[] _mediaStreamSaveColumns = @@ -580,7 +582,8 @@ namespace Emby.Server.Implementations.Data "AlbumArtists", "ExternalId", "SeriesPresentationUniqueKey", - "ShowId" + "ShowId", + "OwnerId" }; var saveItemCommandCommandText = "replace into TypedBaseItems (" + string.Join(",", saveColumns.ToArray()) + ") values ("; @@ -784,13 +787,14 @@ namespace Emby.Server.Implementations.Data saveItemStatement.TryBind("@PremiereDate", item.PremiereDate); saveItemStatement.TryBind("@ProductionYear", item.ProductionYear); - if (item.ParentId == Guid.Empty) + var parentId = item.ParentId; + if (parentId == Guid.Empty) { saveItemStatement.TryBindNull("@ParentId"); } else { - saveItemStatement.TryBind("@ParentId", item.ParentId); + saveItemStatement.TryBind("@ParentId", parentId); } if (item.Genres.Count > 0) @@ -1057,6 +1061,16 @@ namespace Emby.Server.Implementations.Data saveItemStatement.TryBindNull("@ShowId"); } + var ownerId = item.OwnerId; + if (ownerId != Guid.Empty) + { + saveItemStatement.TryBind("@OwnerId", ownerId); + } + else + { + saveItemStatement.TryBindNull("@OwnerId"); + } + saveItemStatement.MoveNext(); } @@ -1156,16 +1170,14 @@ namespace Emby.Server.Implementations.Data delimeter + image.DateModified.Ticks.ToString(CultureInfo.InvariantCulture) + delimeter + - image.Type + - delimeter + - image.IsPlaceholder; + image.Type; } public ItemImageInfo ItemImageInfoFromValueString(string value) { var parts = value.Split(new[] { '*' }, StringSplitOptions.None); - if (parts.Length != 4) + if (parts.Length < 3) { return null; } @@ -1173,9 +1185,18 @@ namespace Emby.Server.Implementations.Data var image = new ItemImageInfo(); image.Path = parts[0]; - image.DateModified = new DateTime(long.Parse(parts[1], CultureInfo.InvariantCulture), DateTimeKind.Utc); - image.Type = (ImageType)Enum.Parse(typeof(ImageType), parts[2], true); - image.IsPlaceholder = string.Equals(parts[3], true.ToString(), StringComparison.OrdinalIgnoreCase); + + long ticks; + if (long.TryParse(parts[1], NumberStyles.Any, CultureInfo.InvariantCulture, out ticks)) + { + image.DateModified = new DateTime(ticks, DateTimeKind.Utc); + } + + ImageType type; + if (Enum.TryParse(parts[2], true, out type)) + { + image.Type = type; + } return image; } @@ -1965,6 +1986,12 @@ namespace Emby.Server.Implementations.Data } } + if (!reader.IsDBNull(index)) + { + item.OwnerId = reader.GetGuid(index); + } + index++; + return item; } @@ -4467,7 +4494,6 @@ namespace Emby.Server.Implementations.Data } } - var includedItemByNameTypes = GetItemByNameTypesInQuery(query).SelectMany(MapIncludeItemTypes).ToList(); var enableItemsByName = (query.IncludeItemsByName ?? false) && includedItemByNameTypes.Count > 0; diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index b57662e311..1854829a24 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -1487,7 +1487,7 @@ namespace Emby.Server.Implementations.Dto } } - var parent = currentItem.DisplayParent ?? currentItem.GetParent(); + var parent = currentItem.DisplayParent ?? (currentItem.IsOwnedItem ? currentItem.GetOwner() : currentItem.GetParent()); if (parent == null && !(originalItem is UserRootFolder) && !(originalItem is UserView) && !(originalItem is AggregateFolder) && !(originalItem is ICollectionFolder) && !(originalItem is Channel)) { diff --git a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs index 796d8cf482..299da07445 100644 --- a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs @@ -198,9 +198,10 @@ namespace Emby.Server.Implementations.EntryPoints LibraryUpdateTimer.Change(LibraryUpdateDuration, Timeout.Infinite); } - if (e.Item.Parent != null) + var parent = e.Item.GetParent() as Folder; + if (parent != null) { - _foldersAddedTo.Add(e.Item.Parent); + _foldersAddedTo.Add(parent); } _itemsAdded.Add(e.Item); @@ -259,9 +260,10 @@ namespace Emby.Server.Implementations.EntryPoints LibraryUpdateTimer.Change(LibraryUpdateDuration, Timeout.Infinite); } - if (e.Item.Parent != null) + var parent = e.Item.GetParent() as Folder; + if (parent != null) { - _foldersRemovedFrom.Add(e.Item.Parent); + _foldersRemovedFrom.Add(parent); } _itemsRemoved.Add(e.Item); diff --git a/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs b/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs index 13e14be36f..4c16b1d39e 100644 --- a/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs +++ b/Emby.Server.Implementations/EntryPoints/RefreshUsersMetadata.cs @@ -1,43 +1,74 @@ using System; using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Plugins; using System.Threading; +using MediaBrowser.Model.Tasks; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.IO; namespace Emby.Server.Implementations.EntryPoints { /// /// Class RefreshUsersMetadata /// - public class RefreshUsersMetadata : IServerEntryPoint + public class RefreshUsersMetadata : IScheduledTask, IConfigurableScheduledTask { /// /// The _user manager /// private readonly IUserManager _userManager; + private IFileSystem _fileSystem; + + public string Name => "Refresh Users"; + + public string Key => "RefreshUsers"; + + public string Description => "Refresh user infos"; + + public string Category + { + get { return "Library"; } + } + + public bool IsHidden => true; + + public bool IsEnabled => true; + + public bool IsLogged => true; /// /// Initializes a new instance of the class. /// - /// The user manager. - public RefreshUsersMetadata(IUserManager userManager) + public RefreshUsersMetadata(IUserManager userManager, IFileSystem fileSystem) { _userManager = userManager; + _fileSystem = fileSystem; } - /// - /// Runs this instance. - /// - public async void Run() + public async Task Execute(CancellationToken cancellationToken, IProgress progress) { - await _userManager.RefreshUsersMetadata(CancellationToken.None).ConfigureAwait(false); + var users = _userManager.Users.ToList(); + + foreach (var user in users) + { + cancellationToken.ThrowIfCancellationRequested(); + + await user.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken).ConfigureAwait(false); + } } - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() + public IEnumerable GetDefaultTriggers() { - GC.SuppressFinalize(this); + return new List + { + new TaskTriggerInfo + { + IntervalTicks = TimeSpan.FromDays(1).Ticks, + Type = TaskTriggerInfo.TriggerInterval + } + }; } } } diff --git a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs index 4a7182a43c..13c72bf3c7 100644 --- a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs @@ -77,7 +77,7 @@ namespace Emby.Server.Implementations.EntryPoints // Go up one level for indicators if (baseItem != null) { - var parent = baseItem.GetParent(); + var parent = baseItem.IsOwnedItem ? baseItem.GetOwner() : baseItem.GetParent(); if (parent != null) { diff --git a/Emby.Server.Implementations/IO/FileRefresher.cs b/Emby.Server.Implementations/IO/FileRefresher.cs index 20de8a5180..315bee103e 100644 --- a/Emby.Server.Implementations/IO/FileRefresher.cs +++ b/Emby.Server.Implementations/IO/FileRefresher.cs @@ -209,7 +209,7 @@ namespace Emby.Server.Implementations.IO // If the item has been deleted find the first valid parent that still exists while (!_fileSystem.DirectoryExists(item.Path) && !_fileSystem.FileExists(item.Path)) { - item = item.GetParent(); + item = item.IsOwnedItem ? item.GetOwner() : item.GetParent(); if (item == null) { diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 139435faa7..eab52e5e81 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -386,7 +386,7 @@ namespace Emby.Server.Implementations.Library item.Id); } - var parent = item.Parent; + var parent = item.IsOwnedItem ? item.GetOwner() : item.GetParent(); var locationType = item.LocationType; @@ -453,12 +453,28 @@ namespace Emby.Server.Implementations.Library if (parent != null) { - await parent.ValidateChildren(new SimpleProgress(), CancellationToken.None, new MetadataRefreshOptions(_fileSystem), false).ConfigureAwait(false); + var parentFolder = parent as Folder; + if (parentFolder != null) + { + await parentFolder.ValidateChildren(new SimpleProgress(), CancellationToken.None, new MetadataRefreshOptions(_fileSystem), false).ConfigureAwait(false); + } + else + { + await parent.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), CancellationToken.None).ConfigureAwait(false); + } } } else if (parent != null) { - parent.RemoveChild(item); + var parentFolder = parent as Folder; + if (parentFolder != null) + { + parentFolder.RemoveChild(item); + } + else + { + await parent.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), CancellationToken.None).ConfigureAwait(false); + } } ItemRepository.DeleteItem(item.Id, CancellationToken.None); @@ -2604,8 +2620,11 @@ namespace Emby.Server.Implementations.Library { video = dbItem; } - - video.ExtraType = ExtraType.Trailer; + else + { + // item is new + video.ExtraType = ExtraType.Trailer; + } video.TrailerTypes = new List { TrailerType.LocalTrailer }; return video; @@ -2846,13 +2865,6 @@ namespace Emby.Server.Implementations.Library await _providerManagerFactory().SaveImage(item, url, image.Type, imageIndex, CancellationToken.None).ConfigureAwait(false); - var newImage = item.GetImageInfo(image.Type, imageIndex); - - if (newImage != null) - { - newImage.IsPlaceholder = image.IsPlaceholder; - } - await item.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false); return item.GetImageInfo(image.Type, imageIndex); diff --git a/Emby.Server.Implementations/Library/UserManager.cs b/Emby.Server.Implementations/Library/UserManager.cs index c9de3c01b1..0f48ff46b8 100644 --- a/Emby.Server.Implementations/Library/UserManager.cs +++ b/Emby.Server.Implementations/Library/UserManager.cs @@ -518,11 +518,12 @@ namespace Emby.Server.Implementations.Library /// /// The cancellation token. /// Task. - public Task RefreshUsersMetadata(CancellationToken cancellationToken) + public async Task RefreshUsersMetadata(CancellationToken cancellationToken) { - var tasks = Users.Select(user => user.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken)).ToList(); - - return Task.WhenAll(tasks); + foreach (var user in Users) + { + await user.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken).ConfigureAwait(false); + } } /// diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs index 2a2e1886f6..f0578d9efb 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs @@ -42,6 +42,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private async Task RecordFromDirectStreamProvider(IDirectStreamProvider directStreamProvider, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken) { + _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(targetFile)); + using (var output = _fileSystem.GetFileStream(targetFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) { onStarted(); @@ -76,6 +78,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { _logger.Info("Opened recording stream from tuner provider"); + _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(targetFile)); + using (var output = _fileSystem.GetFileStream(targetFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read)) { onStarted(); diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index bd9754f26c..1975a6b019 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -1429,14 +1429,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV string liveStreamId = null; - OnRecordingStatusChanged(); - try { var recorder = await GetRecorder().ConfigureAwait(false); var allMediaSources = await GetChannelStreamMediaSources(timer.ChannelId, CancellationToken.None).ConfigureAwait(false); + _logger.Info("Opening recording stream from tuner provider"); var liveStreamInfo = await GetChannelStreamInternal(timer.ChannelId, allMediaSources[0].Id, CancellationToken.None) .ConfigureAwait(false); @@ -1450,23 +1449,20 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV recordPath = EnsureFileUnique(recordPath, timer.Id); _libraryMonitor.ReportFileSystemChangeBeginning(recordPath); - _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(recordPath)); activeRecordingInfo.Path = recordPath; var duration = recordingEndDate - DateTime.UtcNow; - _logger.Info("Beginning recording. Will record for {0} minutes.", - duration.TotalMinutes.ToString(CultureInfo.InvariantCulture)); + _logger.Info("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture)); _logger.Info("Writing file to path: " + recordPath); - _logger.Info("Opening recording stream from tuner provider"); - Action onStarted = () => + Action onStarted = async () => { timer.Status = RecordingStatus.InProgress; _timerProvider.AddOrUpdate(timer, false); - SaveRecordingMetadata(timer, recordPath, seriesPath); + await SaveRecordingMetadata(timer, recordPath, seriesPath).ConfigureAwait(false); TriggerRefresh(recordPath); EnforceKeepUpTo(timer, seriesPath); }; @@ -1500,7 +1496,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } TriggerRefresh(recordPath); - _libraryMonitor.ReportFileSystemChangeComplete(recordPath, true); + _libraryMonitor.ReportFileSystemChangeComplete(recordPath, false); ActiveRecordingInfo removed; _activeRecordings.TryRemove(timer.Id, out removed); @@ -1526,17 +1522,29 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { _timerProvider.Delete(timer); } - - OnRecordingStatusChanged(); } private void TriggerRefresh(string path) { + _logger.Debug("Triggering refresh on {0}", path); + var item = GetAffectedBaseItem(_fileSystem.GetDirectoryName(path)); if (item != null) { - item.ChangedExternally(); + _logger.Debug("Refreshing recording parent {0}", item.Path); + + _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem) + { + ValidateChildren = true, + RefreshPaths = new List + { + path, + _fileSystem.GetDirectoryName(path), + _fileSystem.GetDirectoryName(_fileSystem.GetDirectoryName(path)) + } + + }, RefreshPriority.High); } } @@ -1544,6 +1552,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { BaseItem item = null; + var parentPath = _fileSystem.GetDirectoryName(path); + while (item == null && !string.IsNullOrEmpty(path)) { item = _libraryManager.FindByPath(path, null); @@ -1553,14 +1563,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV if (item != null) { - // If the item has been deleted find the first valid parent that still exists - while (!_fileSystem.DirectoryExists(item.Path) && !_fileSystem.FileExists(item.Path)) + if (item.GetType() == typeof(Folder) && string.Equals(item.Path, parentPath, StringComparison.OrdinalIgnoreCase)) { - item = item.GetParent(); - - if (item == null) + var parentItem = item.GetParent(); + if (parentItem != null && !(parentItem is AggregateFolder)) { - break; + item = parentItem; } } } @@ -1568,14 +1576,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return item; } - private void OnRecordingStatusChanged() - { - EventHelper.FireEventIfNotNull(RecordingStatusChanged, this, new RecordingStatusChangedEventArgs - { - - }, _logger); - } - private async void EnforceKeepUpTo(TimerInfo timer, string seriesPath) { if (string.IsNullOrWhiteSpace(timer.SeriesTimerId)) @@ -1960,7 +1960,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } } - private async void SaveRecordingMetadata(TimerInfo timer, string recordingPath, string seriesPath) + private async Task SaveRecordingMetadata(TimerInfo timer, string recordingPath, string seriesPath) { try { diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index 870a3b4937..38d2fd3c64 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -843,8 +843,7 @@ namespace Emby.Server.Implementations.LiveTv item.SetImage(new ItemImageInfo { Path = info.ImagePath, - Type = ImageType.Primary, - IsPlaceholder = true + Type = ImageType.Primary }, 0); } else if (!string.IsNullOrWhiteSpace(info.ImageUrl)) @@ -852,8 +851,7 @@ namespace Emby.Server.Implementations.LiveTv item.SetImage(new ItemImageInfo { Path = info.ImageUrl, - Type = ImageType.Primary, - IsPlaceholder = true + Type = ImageType.Primary }, 0); } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHttpStream.cs index 4dcbc4b54c..af064755d0 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHttpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHttpStream.cs @@ -134,7 +134,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun } _liveStreamTaskCompletionSource.TrySetResult(true); - //await DeleteTempFile(_tempFilePath).ConfigureAwait(false); + await DeleteTempFile(_tempFilePath).ConfigureAwait(false); }); } diff --git a/Emby.Server.Implementations/Playlists/PlaylistImageProvider.cs b/Emby.Server.Implementations/Playlists/PlaylistImageProvider.cs index 525df03504..36e8b4dd89 100644 --- a/Emby.Server.Implementations/Playlists/PlaylistImageProvider.cs +++ b/Emby.Server.Implementations/Playlists/PlaylistImageProvider.cs @@ -53,7 +53,7 @@ namespace Emby.Server.Implementations.Playlists return subItem; } - var parent = subItem.GetParent(); + var parent = subItem.IsOwnedItem ? subItem.GetOwner() : subItem.GetParent(); if (parent != null && parent.HasImage(ImageType.Primary)) { diff --git a/MediaBrowser.Controller/Entities/AggregateFolder.cs b/MediaBrowser.Controller/Entities/AggregateFolder.cs index 2105ef9079..00fac1eabd 100644 --- a/MediaBrowser.Controller/Entities/AggregateFolder.cs +++ b/MediaBrowser.Controller/Entities/AggregateFolder.cs @@ -137,7 +137,7 @@ namespace MediaBrowser.Controller.Entities { FileInfo = FileSystem.GetDirectoryInfo(path), Path = path, - Parent = Parent + Parent = GetParent() as Folder }; // Gather child folder and files diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 4416c5e916..502ba6c60e 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -97,7 +97,7 @@ namespace MediaBrowser.Controller.Entities public string Tagline { get; set; } [IgnoreDataMember] - public ItemImageInfo[] ImageInfos { get; set; } + public virtual ItemImageInfo[] ImageInfos { get; set; } [IgnoreDataMember] public bool IsVirtualItem { get; set; } @@ -216,6 +216,9 @@ namespace MediaBrowser.Controller.Entities [IgnoreDataMember] public Guid Id { get; set; } + [IgnoreDataMember] + public Guid OwnerId { get; set; } + /// /// Gets or sets a value indicating whether this instance is hd. /// @@ -321,12 +324,31 @@ namespace MediaBrowser.Controller.Entities { get { + if (OwnerId != Guid.Empty) + { + return true; + } + + // legacy + // Local trailer, special feature, theme video, etc. // An item that belongs to another item but is not part of the Parent-Child tree - return !IsFolder && ParentId == Guid.Empty && LocationType == LocationType.FileSystem; + // This is a hack for now relying on ExtraType. Eventually we may need to persist this + if (ParentId == Guid.Empty && !IsFolder && LocationType == LocationType.FileSystem) + { + return true; + } + + return false; } } + public BaseItem GetOwner() + { + var ownerId = OwnerId; + return ownerId == Guid.Empty ? null : LibraryManager.GetItemById(ownerId); + } + /// /// Gets or sets the type of the location. /// @@ -727,17 +749,12 @@ namespace MediaBrowser.Controller.Entities ParentId = parent == null ? Guid.Empty : parent.Id; } - [IgnoreDataMember] - public IEnumerable Parents - { - get { return GetParents().OfType(); } - } - public BaseItem GetParent() { - if (ParentId != Guid.Empty) + var parentId = ParentId; + if (parentId != Guid.Empty) { - return LibraryManager.GetItemById(ParentId); + return LibraryManager.GetItemById(parentId); } return null; @@ -779,11 +796,13 @@ namespace MediaBrowser.Controller.Entities { get { - if (ParentId == Guid.Empty) + var parentId = ParentId; + + if (parentId == Guid.Empty) { return null; } - return ParentId; + return parentId; } } @@ -1002,8 +1021,11 @@ namespace MediaBrowser.Controller.Entities { audio = dbItem; } - - audio.ExtraType = MediaBrowser.Model.Entities.ExtraType.ThemeSong; + else + { + // item is new + audio.ExtraType = MediaBrowser.Model.Entities.ExtraType.ThemeSong; + } return audio; @@ -1032,8 +1054,11 @@ namespace MediaBrowser.Controller.Entities { item = dbItem; } - - item.ExtraType = MediaBrowser.Model.Entities.ExtraType.ThemeVideo; + else + { + // item is new + item.ExtraType = MediaBrowser.Model.Entities.ExtraType.ThemeVideo; + } return item; @@ -1178,8 +1203,25 @@ namespace MediaBrowser.Controller.Entities var newItemIds = newItems.Select(i => i.Id).ToArray(); var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds); + var ownerId = item.Id; - var tasks = newItems.Select(i => RefreshMetadataForOwnedItem(i, true, options, cancellationToken)); + var tasks = newItems.Select(i => + { + var subOptions = new MetadataRefreshOptions(options); + + if (!i.ExtraType.HasValue || + i.ExtraType.Value != Model.Entities.ExtraType.Trailer || + i.OwnerId != ownerId || + i.ParentId != Guid.Empty) + { + i.ExtraType = Model.Entities.ExtraType.Trailer; + i.OwnerId = ownerId; + i.ParentId = Guid.Empty; + subOptions.ForceSave = true; + } + + return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken); + }); await Task.WhenAll(tasks).ConfigureAwait(false); @@ -1196,13 +1238,20 @@ namespace MediaBrowser.Controller.Entities var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds); + var ownerId = item.Id; + var tasks = newThemeVideos.Select(i => { var subOptions = new MetadataRefreshOptions(options); - if (!i.IsThemeMedia) + if (!i.ExtraType.HasValue || + i.ExtraType.Value != Model.Entities.ExtraType.ThemeVideo || + i.OwnerId != ownerId || + i.ParentId != Guid.Empty) { - i.ExtraType = MediaBrowser.Model.Entities.ExtraType.ThemeVideo; + i.ExtraType = Model.Entities.ExtraType.ThemeVideo; + i.OwnerId = ownerId; + i.ParentId = Guid.Empty; subOptions.ForceSave = true; } @@ -1226,13 +1275,20 @@ namespace MediaBrowser.Controller.Entities var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds); + var ownerId = item.Id; + var tasks = newThemeSongs.Select(i => { var subOptions = new MetadataRefreshOptions(options); - if (!i.IsThemeMedia) + if (!i.ExtraType.HasValue || + i.ExtraType.Value != Model.Entities.ExtraType.ThemeSong || + i.OwnerId != ownerId || + i.ParentId != Guid.Empty) { - i.ExtraType = MediaBrowser.Model.Entities.ExtraType.ThemeSong; + i.ExtraType = Model.Entities.ExtraType.ThemeSong; + i.OwnerId = ownerId; + i.ParentId = Guid.Empty; subOptions.ForceSave = true; } @@ -1868,7 +1924,6 @@ namespace MediaBrowser.Controller.Entities { existingImage.Path = image.Path; existingImage.DateModified = image.DateModified; - existingImage.IsPlaceholder = image.IsPlaceholder; } else @@ -1902,7 +1957,6 @@ namespace MediaBrowser.Controller.Entities image.Path = file.FullName; image.DateModified = imageInfo.DateModified; - image.IsPlaceholder = false; } } @@ -2359,6 +2413,14 @@ namespace MediaBrowser.Controller.Entities newOptions.ForceSave = true; } + //var parentId = Id; + //if (!video.IsOwnedItem || video.ParentId != parentId) + //{ + // video.IsOwnedItem = true; + // video.ParentId = parentId; + // newOptions.ForceSave = true; + //} + if (video == null) { return Task.FromResult(true); diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs index 537beb26b6..a83e084db5 100644 --- a/MediaBrowser.Controller/Entities/CollectionFolder.cs +++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs @@ -280,7 +280,7 @@ namespace MediaBrowser.Controller.Entities { FileInfo = FileSystem.GetDirectoryInfo(path), Path = path, - Parent = Parent, + Parent = GetParent() as Folder, CollectionType = CollectionType }; diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 2e741a8c44..6d88f70152 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -378,6 +378,7 @@ namespace MediaBrowser.Controller.Entities cancellationToken.ThrowIfCancellationRequested(); var validChildren = new List(); + var validChildrenNeedGeneration = false; var allLibraryPaths = LibraryManager .GetVirtualFolders() @@ -474,11 +475,7 @@ namespace MediaBrowser.Controller.Entities } else { - if (recursive || refreshChildMetadata) - { - // used below - validChildren = Children.ToList(); - } + validChildrenNeedGeneration = true; } progress.Report(10); @@ -502,6 +499,12 @@ namespace MediaBrowser.Controller.Entities ProviderManager.OnRefreshProgress(folder, newPct); }); + if (validChildrenNeedGeneration) + { + validChildren = Children.ToList(); + validChildrenNeedGeneration = false; + } + await ValidateSubFolders(validChildren.OfType().ToList(), directoryService, innerProgress, cancellationToken).ConfigureAwait(false); } } @@ -536,6 +539,12 @@ namespace MediaBrowser.Controller.Entities } else { + if (validChildrenNeedGeneration) + { + validChildren = Children.ToList(); + validChildrenNeedGeneration = false; + } + await RefreshMetadataRecursive(validChildren, refreshOptions, recursive, innerProgress, cancellationToken); } } @@ -565,7 +574,7 @@ namespace MediaBrowser.Controller.Entities }); await RefreshChildMetadata(child, refreshOptions, recursive && child.IsFolder, innerProgress, cancellationToken) - .ConfigureAwait(false); + .ConfigureAwait(false); } numComplete++; @@ -588,7 +597,10 @@ namespace MediaBrowser.Controller.Entities } else { - await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false); + if (refreshOptions.RefreshItem(child)) + { + await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false); + } if (recursive) { @@ -1196,11 +1208,21 @@ namespace MediaBrowser.Controller.Entities /// Gets the linked children. /// /// IEnumerable{BaseItem}. - public IEnumerable GetLinkedChildren() + public List GetLinkedChildren() { - return LinkedChildren - .Select(GetLinkedChild) - .Where(i => i != null); + var linkedChildren = LinkedChildren; + var list = new List(linkedChildren.Length); + + foreach (var i in linkedChildren) + { + var child = GetLinkedChild(i); + + if (child != null) + { + list.Add(child); + } + } + return list; } protected virtual bool FilterLinkedChildrenPerUser @@ -1211,16 +1233,19 @@ namespace MediaBrowser.Controller.Entities } } - public IEnumerable GetLinkedChildren(User user) + public List GetLinkedChildren(User user) { if (!FilterLinkedChildrenPerUser || user == null) { return GetLinkedChildren(); } - if (LinkedChildren.Length == 0) + var linkedChildren = LinkedChildren; + var list = new List(linkedChildren.Length); + + if (linkedChildren.Length == 0) { - return new List(); + return list; } var allUserRootChildren = user.RootFolder.Children.OfType().ToList(); @@ -1231,37 +1256,43 @@ namespace MediaBrowser.Controller.Entities .Select(i => i.Id) .ToList(); - return LinkedChildren - .Select(i => + foreach (var i in linkedChildren) + { + var child = GetLinkedChild(i); + + if (child == null) { - var child = GetLinkedChild(i); + continue; + } + + var childOwner = child.IsOwnedItem ? (child.GetOwner() ?? child) : child; - if (child != null) + if (childOwner != null) + { + var childLocationType = childOwner.LocationType; + if (childLocationType == LocationType.Remote || childLocationType == LocationType.Virtual) { - var childLocationType = child.LocationType; - if (childLocationType == LocationType.Remote || childLocationType == LocationType.Virtual) + if (!childOwner.IsVisibleStandalone(user)) { - if (!child.IsVisibleStandalone(user)) - { - return null; - } + continue; } - else if (childLocationType == LocationType.FileSystem) - { - var itemCollectionFolderIds = - LibraryManager.GetCollectionFolders(child, allUserRootChildren) - .Select(f => f.Id).ToList(); + } + else if (childLocationType == LocationType.FileSystem) + { + var itemCollectionFolderIds = + LibraryManager.GetCollectionFolders(childOwner, allUserRootChildren).Select(f => f.Id); - if (!itemCollectionFolderIds.Any(collectionFolderIds.Contains)) - { - return null; - } + if (!itemCollectionFolderIds.Any(collectionFolderIds.Contains)) + { + continue; } } + } + + list.Add(child); + } - return child; - }) - .Where(i => i != null); + return list; } /// diff --git a/MediaBrowser.Controller/Entities/IHasTrailers.cs b/MediaBrowser.Controller/Entities/IHasTrailers.cs index 8686c802ab..07dde37894 100644 --- a/MediaBrowser.Controller/Entities/IHasTrailers.cs +++ b/MediaBrowser.Controller/Entities/IHasTrailers.cs @@ -5,7 +5,7 @@ using System.Linq; namespace MediaBrowser.Controller.Entities { - public interface IHasTrailers : IHasProviderIds + public interface IHasTrailers : IHasMetadata { /// /// Gets or sets the remote trailers. diff --git a/MediaBrowser.Controller/Entities/ItemImageInfo.cs b/MediaBrowser.Controller/Entities/ItemImageInfo.cs index 672595db84..6b2d2392dc 100644 --- a/MediaBrowser.Controller/Entities/ItemImageInfo.cs +++ b/MediaBrowser.Controller/Entities/ItemImageInfo.cs @@ -24,12 +24,6 @@ namespace MediaBrowser.Controller.Entities /// The date modified. public DateTime DateModified { get; set; } - /// - /// Gets or sets a value indicating whether this instance is placeholder. - /// - /// true if this instance is placeholder; otherwise, false. - public bool IsPlaceholder { get; set; } - [IgnoreDataMember] public bool IsLocalFile { diff --git a/MediaBrowser.Controller/Entities/Movies/Movie.cs b/MediaBrowser.Controller/Entities/Movies/Movie.cs index 3a41709fed..2e0e019443 100644 --- a/MediaBrowser.Controller/Entities/Movies/Movie.cs +++ b/MediaBrowser.Controller/Entities/Movies/Movie.cs @@ -81,7 +81,20 @@ namespace MediaBrowser.Controller.Entities.Movies var itemsChanged = !SpecialFeatureIds.SequenceEqual(newItemIds); - var tasks = newItems.Select(i => RefreshMetadataForOwnedItem(i, false, options, cancellationToken)); + var ownerId = Id; + + var tasks = newItems.Select(i => + { + var subOptions = new MetadataRefreshOptions(options); + + if (i.OwnerId != ownerId) + { + i.OwnerId = ownerId; + subOptions.ForceSave = true; + } + + return RefreshMetadataForOwnedItem(i, false, subOptions, cancellationToken); + }); await Task.WhenAll(tasks).ConfigureAwait(false); diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs index 60d2624fa9..5931c32e1b 100644 --- a/MediaBrowser.Controller/Entities/TV/Series.cs +++ b/MediaBrowser.Controller/Entities/TV/Series.cs @@ -347,7 +347,10 @@ namespace MediaBrowser.Controller.Entities.TV cancellationToken.ThrowIfCancellationRequested(); - await item.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false); + if (refreshOptions.RefreshItem(item)) + { + await item.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false); + } numComplete++; double percent = numComplete; @@ -382,7 +385,10 @@ namespace MediaBrowser.Controller.Entities.TV if (!skipItem) { - await item.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false); + if (refreshOptions.RefreshItem(item)) + { + await item.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false); + } } numComplete++; diff --git a/MediaBrowser.Controller/Entities/User.cs b/MediaBrowser.Controller/Entities/User.cs index cca3091c15..4aa1311e1f 100644 --- a/MediaBrowser.Controller/Entities/User.cs +++ b/MediaBrowser.Controller/Entities/User.cs @@ -37,6 +37,9 @@ namespace MediaBrowser.Controller.Entities public UserLinkType? ConnectLinkType { get; set; } public string ConnectAccessKey { get; set; } + // Strictly to remove IgnoreDataMember + public override ItemImageInfo[] ImageInfos { get => base.ImageInfos; set => base.ImageInfos = value; } + /// /// Gets or sets the path. /// diff --git a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs index 86cef628e0..0df2370bd3 100644 --- a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs +++ b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs @@ -1,5 +1,7 @@ -using System.Linq; - +using System; +using System.Collections.Generic; +using System.Linq; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.IO; using MediaBrowser.Model.IO; using MediaBrowser.Model.Logging; @@ -20,6 +22,8 @@ namespace MediaBrowser.Controller.Providers public MetadataRefreshMode MetadataRefreshMode { get; set; } public RemoteSearchResult SearchResult { get; set; } + public List RefreshPaths { get; set; } + public bool ForceSave { get; set; } public MetadataRefreshOptions(IFileSystem fileSystem) @@ -44,6 +48,26 @@ namespace MediaBrowser.Controller.Providers ReplaceAllImages = copy.ReplaceAllImages; ReplaceImages = copy.ReplaceImages.ToList(); SearchResult = copy.SearchResult; + + if (copy.RefreshPaths != null && copy.RefreshPaths.Count > 0) + { + if (RefreshPaths == null) + { + RefreshPaths = new List(); + } + + RefreshPaths.AddRange(copy.RefreshPaths); + } + } + + public bool RefreshItem(BaseItem item) + { + if (RefreshPaths != null && RefreshPaths.Count > 0) + { + return RefreshPaths.Contains(item.Path ?? string.Empty, StringComparer.OrdinalIgnoreCase); + } + + return true; } } } diff --git a/MediaBrowser.Model/LiveTv/LiveTvOptions.cs b/MediaBrowser.Model/LiveTv/LiveTvOptions.cs index 2c2f22e867..a70a1066d7 100644 --- a/MediaBrowser.Model/LiveTv/LiveTvOptions.cs +++ b/MediaBrowser.Model/LiveTv/LiveTvOptions.cs @@ -33,7 +33,6 @@ namespace MediaBrowser.Model.LiveTv MediaLocationsCreated = new string[] { }; RecordingEncodingFormat = "mkv"; RecordingPostProcessorArguments = "\"{path}\""; - EnableRecordingEncoding = true; } } diff --git a/MediaBrowser.Providers/Manager/GenericPriorityQueue.cs b/MediaBrowser.Providers/Manager/GenericPriorityQueue.cs index e245476146..0e6c073577 100644 --- a/MediaBrowser.Providers/Manager/GenericPriorityQueue.cs +++ b/MediaBrowser.Providers/Manager/GenericPriorityQueue.cs @@ -1,6 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; @@ -66,9 +67,7 @@ namespace Priority_Queue /// Removes every node from the queue. /// O(n) (So, don't do this often!) /// -#if NET_VERSION_4_5 [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif public void Clear() { Array.Clear(_nodes, 1, _numNodes); @@ -78,9 +77,7 @@ namespace Priority_Queue /// /// Returns (in O(1)!) whether the given node is in the queue. O(1) /// -#if NET_VERSION_4_5 [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif public bool Contains(TItem node) { #if DEBUG @@ -103,9 +100,7 @@ namespace Priority_Queue /// If the node is already enqueued, the result is undefined. /// O(log n) /// -#if NET_VERSION_4_5 [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif public void Enqueue(TItem node, TPriority priority) { #if DEBUG @@ -131,9 +126,7 @@ namespace Priority_Queue CascadeUp(_nodes[_numNodes]); } -#if NET_VERSION_4_5 [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif private void Swap(TItem node1, TItem node2) { //Swap the nodes @@ -164,9 +157,7 @@ namespace Priority_Queue } } -#if NET_VERSION_4_5 [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif private void CascadeDown(TItem node) { //aka Heapify-down @@ -228,9 +219,7 @@ namespace Priority_Queue /// Returns true if 'higher' has higher priority than 'lower', false otherwise. /// Note that calling HasHigherPriority(node, node) (ie. both arguments the same node) will return false /// -#if NET_VERSION_4_5 [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif private bool HasHigherPriority(TItem higher, TItem lower) { var cmp = higher.Priority.CompareTo(lower.Priority); @@ -319,9 +308,7 @@ namespace Priority_Queue /// Calling this method on a node not in the queue results in undefined behavior /// O(log n) /// -#if NET_VERSION_4_5 [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif public void UpdatePriority(TItem node, TPriority priority) { #if DEBUG diff --git a/MediaBrowser.Providers/Manager/ItemImageProvider.cs b/MediaBrowser.Providers/Manager/ItemImageProvider.cs index e62ce0225d..a6d4d4c334 100644 --- a/MediaBrowser.Providers/Manager/ItemImageProvider.cs +++ b/MediaBrowser.Providers/Manager/ItemImageProvider.cs @@ -206,8 +206,7 @@ namespace MediaBrowser.Providers.Manager { var image = item.GetImageInfo(type, 0); - // if it's a placeholder image then pretend like it's not there so that we can replace it - return image != null && !image.IsPlaceholder; + return image != null; } /// @@ -547,7 +546,7 @@ namespace MediaBrowser.Providers.Manager switch (type) { case ImageType.Primary: - return !(item is Movie || item is Series || item is Game); + return true; default: return true; } diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index ae029cc594..b93f783418 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -262,8 +262,7 @@ namespace MediaBrowser.Providers.Manager personEntity.SetImage(new ItemImageInfo { Path = imageUrl, - Type = ImageType.Primary, - IsPlaceholder = true + Type = ImageType.Primary }, 0); } diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs b/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs index 333f3d5932..a9aa71bfa4 100644 --- a/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs @@ -146,6 +146,11 @@ namespace MediaBrowser.Providers.MediaInfo return _cachedTask; } + if (!item.IsCompleteMedia) + { + return _cachedTask; + } + if (item.IsShortcut) { FetchShortcutInfo(item); diff --git a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs index f666d8b7ff..9b0d29cf04 100644 --- a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs @@ -133,7 +133,7 @@ namespace MediaBrowser.Providers.MediaInfo { var video = item as Video; - if (item.LocationType == LocationType.FileSystem && video != null && !video.IsPlaceHolder && !video.IsShortcut) + if (item.LocationType == LocationType.FileSystem && video != null && !video.IsPlaceHolder && !video.IsShortcut && video.IsCompleteMedia) { return true; } -- cgit v1.2.3