jellyfin/MediaBrowser.Providers/Manager/ImageSaver.cs

640 lines
24 KiB
C#
Raw Normal View History

using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.IO;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Logging;
2015-01-27 15:45:59 -07:00
using MediaBrowser.Model.Net;
using System;
using System.Collections.Generic;
2013-09-17 19:43:34 -07:00
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
2016-10-25 12:02:04 -07:00
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
namespace MediaBrowser.Providers.Manager
{
/// <summary>
/// Class ImageSaver
/// </summary>
public class ImageSaver
{
private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
/// <summary>
/// The _config
/// </summary>
private readonly IServerConfigurationManager _config;
/// <summary>
/// The _directory watchers
/// </summary>
private readonly ILibraryMonitor _libraryMonitor;
private readonly IFileSystem _fileSystem;
2013-11-08 08:35:11 -07:00
private readonly ILogger _logger;
2016-11-08 11:44:23 -07:00
private readonly IMemoryStreamFactory _memoryStreamProvider;
/// <summary>
2014-02-08 13:02:35 -07:00
/// Initializes a new instance of the <see cref="ImageSaver" /> class.
/// </summary>
/// <param name="config">The config.</param>
/// <param name="libraryMonitor">The directory watchers.</param>
2014-02-08 13:02:35 -07:00
/// <param name="fileSystem">The file system.</param>
/// <param name="logger">The logger.</param>
2016-11-08 11:44:23 -07:00
public ImageSaver(IServerConfigurationManager config, ILibraryMonitor libraryMonitor, IFileSystem fileSystem, ILogger logger, IMemoryStreamFactory memoryStreamProvider)
{
_config = config;
_libraryMonitor = libraryMonitor;
_fileSystem = fileSystem;
2013-11-08 08:35:11 -07:00
_logger = logger;
2016-10-06 11:55:01 -07:00
_memoryStreamProvider = memoryStreamProvider;
}
/// <summary>
/// Saves the image.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="source">The source.</param>
/// <param name="mimeType">Type of the MIME.</param>
/// <param name="type">The type.</param>
/// <param name="imageIndex">Index of the image.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException">mimeType</exception>
2014-10-19 20:04:45 -07:00
public Task SaveImage(IHasImages item, Stream source, string mimeType, ImageType type, int? imageIndex, CancellationToken cancellationToken)
{
return SaveImage(item, source, mimeType, type, imageIndex, null, cancellationToken);
}
2016-10-17 09:35:29 -07:00
public async Task SaveImage(IHasImages item, Stream source, string mimeType, ImageType type, int? imageIndex, bool? saveLocallyWithMedia, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(mimeType))
{
throw new ArgumentNullException("mimeType");
}
2014-02-15 15:42:06 -07:00
var saveLocally = item.SupportsLocalMetadata && item.IsSaveLocalMetadataEnabled() && !item.IsOwnedItem && !(item is Audio);
2014-04-13 10:27:13 -07:00
if (item is User)
{
saveLocally = true;
}
2013-10-25 13:58:31 -07:00
if (type != ImageType.Primary && item is Episode)
{
2013-10-25 13:58:31 -07:00
saveLocally = false;
}
2013-10-25 13:58:31 -07:00
var locationType = item.LocationType;
if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
{
saveLocally = false;
var season = item as Season;
// If season is virtual under a physical series, save locally if using compatible convention
if (season != null && _config.Configuration.ImageSavingConvention == ImageSavingConvention.Compatible)
{
var series = season.Series;
2014-02-15 15:42:06 -07:00
if (series != null && series.SupportsLocalMetadata && series.IsSaveLocalMetadataEnabled())
{
2014-02-10 13:11:46 -07:00
saveLocally = true;
}
}
}
2016-10-17 09:35:29 -07:00
if (saveLocallyWithMedia.HasValue && !saveLocallyWithMedia.Value)
2014-10-19 20:04:45 -07:00
{
2016-10-17 09:35:29 -07:00
saveLocally = saveLocallyWithMedia.Value;
2014-10-19 20:04:45 -07:00
}
2014-02-07 13:30:41 -07:00
if (!imageIndex.HasValue && item.AllowsMultipleImages(type))
{
2014-02-07 13:30:41 -07:00
imageIndex = item.GetImages(type).Count();
}
2013-12-19 14:51:32 -07:00
var index = imageIndex ?? 0;
2015-10-30 09:45:22 -07:00
var paths = GetSavePaths(item, type, imageIndex, mimeType, saveLocally);
2015-10-30 09:45:22 -07:00
var retryPaths = GetSavePaths(item, type, imageIndex, mimeType, false);
// If there are more than one output paths, the stream will need to be seekable
2016-10-06 11:55:01 -07:00
var memoryStream = _memoryStreamProvider.CreateNew();
using (source)
{
await source.CopyToAsync(memoryStream).ConfigureAwait(false);
}
source = memoryStream;
2015-10-16 10:06:31 -07:00
var currentImage = GetCurrentImage(item, type, index);
var currentImageIsLocalFile = currentImage != null && currentImage.IsLocalFile;
var currentImagePath = currentImage == null ? null : currentImage.Path;
2016-01-16 20:23:59 -07:00
var savedPaths = new List<string>();
using (source)
{
var currentPathIndex = 0;
foreach (var path in paths)
{
source.Position = 0;
2015-10-10 17:39:30 -07:00
string retryPath = null;
if (paths.Length == retryPaths.Length)
{
retryPath = retryPaths[currentPathIndex];
}
2016-01-16 20:23:59 -07:00
var savedPath = await SaveImageToLocation(source, path, retryPath, cancellationToken).ConfigureAwait(false);
savedPaths.Add(savedPath);
currentPathIndex++;
}
}
2013-12-19 14:51:32 -07:00
// Set the path into the item
2016-01-16 20:23:59 -07:00
SetImagePath(item, type, imageIndex, savedPaths[0]);
// Delete the current path
if (currentImageIsLocalFile && !savedPaths.Contains(currentImagePath, StringComparer.OrdinalIgnoreCase))
{
var currentPath = currentImagePath;
2015-10-16 10:06:31 -07:00
2016-06-26 21:19:10 -07:00
_logger.Debug("Deleting previous image {0}", currentPath);
_libraryMonitor.ReportFileSystemChangeBeginning(currentPath);
try
{
var currentFile = _fileSystem.GetFileInfo(currentPath);
// This will fail if the file is hidden
if (currentFile.Exists)
{
if (currentFile.IsHidden)
{
_fileSystem.SetHidden(currentFile.FullName, false);
}
_fileSystem.DeleteFile(currentFile.FullName);
}
}
finally
{
_libraryMonitor.ReportFileSystemChangeComplete(currentPath, false);
}
}
}
2016-01-16 20:23:59 -07:00
private async Task<string> SaveImageToLocation(Stream source, string path, string retryPath, CancellationToken cancellationToken)
{
try
{
await SaveImageToLocation(source, path, cancellationToken).ConfigureAwait(false);
2016-01-16 20:23:59 -07:00
return path;
}
catch (UnauthorizedAccessException)
{
2015-10-30 09:45:22 -07:00
var retry = !string.IsNullOrWhiteSpace(retryPath) &&
2015-10-10 17:39:30 -07:00
!string.Equals(path, retryPath, StringComparison.OrdinalIgnoreCase);
if (retry)
{
_logger.Error("UnauthorizedAccessException - Access to path {0} is denied. Will retry saving to {1}", path, retryPath);
}
else
{
throw;
}
}
2016-10-02 23:28:45 -07:00
catch (IOException ex)
{
var retry = !string.IsNullOrWhiteSpace(retryPath) &&
!string.Equals(path, retryPath, StringComparison.OrdinalIgnoreCase);
if (retry)
{
_logger.Error("IOException saving to {0}. {2}. Will retry saving to {1}", path, retryPath, ex.Message);
}
else
{
throw;
}
}
source.Position = 0;
await SaveImageToLocation(source, retryPath, cancellationToken).ConfigureAwait(false);
2016-01-16 20:23:59 -07:00
return retryPath;
}
/// <summary>
/// Saves the image to location.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="path">The path.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
private async Task SaveImageToLocation(Stream source, string path, CancellationToken cancellationToken)
{
2013-11-08 08:35:11 -07:00
_logger.Debug("Saving image to {0}", path);
var parentFolder = Path.GetDirectoryName(path);
_libraryMonitor.ReportFileSystemChangeBeginning(path);
_libraryMonitor.ReportFileSystemChangeBeginning(parentFolder);
try
{
_fileSystem.CreateDirectory(Path.GetDirectoryName(path));
// If the file is currently hidden we'll have to remove that or the save will fail
var file = _fileSystem.GetFileInfo(path);
// This will fail if the file is hidden
if (file.Exists)
{
if (file.IsHidden)
{
_fileSystem.SetHidden(file.FullName, false);
}
2016-11-09 10:24:57 -07:00
if (file.IsReadOnly)
{
_fileSystem.SetReadOnly(path, false);
}
}
2016-10-25 12:02:04 -07:00
using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
{
2015-01-12 22:40:27 -07:00
await source.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, cancellationToken)
.ConfigureAwait(false);
}
if (_config.Configuration.SaveMetadataHidden)
{
_fileSystem.SetHidden(file.FullName, true);
}
}
finally
{
_libraryMonitor.ReportFileSystemChangeComplete(path, false);
_libraryMonitor.ReportFileSystemChangeComplete(parentFolder, false);
}
}
/// <summary>
/// Gets the save paths.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="type">The type.</param>
/// <param name="imageIndex">Index of the image.</param>
/// <param name="mimeType">Type of the MIME.</param>
/// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
/// <returns>IEnumerable{System.String}.</returns>
2014-02-15 15:42:06 -07:00
private string[] GetSavePaths(IHasImages item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
{
2016-06-27 21:47:30 -07:00
if (!saveLocally || (_config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy))
{
2013-10-17 08:35:39 -07:00
return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, saveLocally) };
}
return GetCompatibleSavePaths(item, type, imageIndex, mimeType);
}
/// <summary>
/// Gets the current image path.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="type">The type.</param>
/// <param name="imageIndex">Index of the image.</param>
/// <returns>System.String.</returns>
/// <exception cref="System.ArgumentNullException">
/// imageIndex
/// or
/// imageIndex
/// </exception>
2015-10-16 10:06:31 -07:00
private ItemImageInfo GetCurrentImage(IHasImages item, ImageType type, int imageIndex)
{
2015-10-16 10:06:31 -07:00
return item.GetImageInfo(type, imageIndex);
}
/// <summary>
/// Sets the image path.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="type">The type.</param>
/// <param name="imageIndex">Index of the image.</param>
/// <param name="path">The path.</param>
/// <exception cref="System.ArgumentNullException">imageIndex
/// or
/// imageIndex</exception>
2014-02-15 15:42:06 -07:00
private void SetImagePath(IHasImages item, ImageType type, int? imageIndex, string path)
{
2015-10-03 20:38:46 -07:00
item.SetImagePath(type, imageIndex ?? 0, _fileSystem.GetFileInfo(path));
}
/// <summary>
/// Gets the save path.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="type">The type.</param>
/// <param name="imageIndex">Index of the image.</param>
/// <param name="mimeType">Type of the MIME.</param>
/// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
/// <returns>System.String.</returns>
/// <exception cref="System.ArgumentNullException">
/// imageIndex
/// or
/// imageIndex
/// </exception>
2014-02-15 15:42:06 -07:00
private string GetStandardSavePath(IHasImages item, ImageType type, int? imageIndex, string mimeType, bool saveLocally)
{
2016-01-21 19:59:07 -07:00
var season = item as Season;
var extension = MimeTypes.ToExtension(mimeType);
2016-10-18 23:29:00 -07:00
if (string.IsNullOrWhiteSpace(extension))
{
throw new ArgumentException(string.Format("Unable to determine image file extension from mime type {0}", mimeType));
}
2016-01-21 19:59:07 -07:00
if (type == ImageType.Thumb && saveLocally)
{
if (season != null && season.IndexNumber.HasValue)
{
var seriesFolder = season.SeriesPath;
var seasonMarker = season.IndexNumber.Value == 0
? "-specials"
: season.IndexNumber.Value.ToString("00", UsCulture);
var imageFilename = "season" + seasonMarker + "-landscape" + extension;
return Path.Combine(seriesFolder, imageFilename);
}
2016-10-07 08:08:13 -07:00
if (item.DetectIsInMixedFolder())
2016-01-21 19:59:07 -07:00
{
return GetSavePathForItemInMixedFolder(item, type, "landscape", extension);
}
return Path.Combine(item.ContainingFolderPath, "landscape" + extension);
}
if (type == ImageType.Banner && saveLocally)
{
if (season != null && season.IndexNumber.HasValue)
{
var seriesFolder = season.SeriesPath;
var seasonMarker = season.IndexNumber.Value == 0
? "-specials"
: season.IndexNumber.Value.ToString("00", UsCulture);
var imageFilename = "season" + seasonMarker + "-banner" + extension;
return Path.Combine(seriesFolder, imageFilename);
}
}
string filename;
2016-06-26 21:19:10 -07:00
var folderName = item is MusicAlbum ||
item is MusicArtist ||
item is PhotoAlbum ||
(saveLocally && _config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy) ?
"folder" :
2016-02-05 19:13:36 -07:00
"poster";
2014-10-19 20:04:45 -07:00
switch (type)
{
case ImageType.Art:
filename = "clearart";
break;
2014-01-28 18:47:47 -07:00
case ImageType.BoxRear:
filename = "back";
break;
2016-01-21 19:59:07 -07:00
case ImageType.Thumb:
filename = "landscape";
break;
2013-11-19 09:44:53 -07:00
case ImageType.Disc:
filename = item is MusicAlbum ? "cdart" : "disc";
break;
case ImageType.Primary:
2016-01-21 19:59:07 -07:00
filename = item is Episode ? _fileSystem.GetFileNameWithoutExtension(item.Path) : folderName;
break;
case ImageType.Backdrop:
2014-02-07 13:30:41 -07:00
filename = GetBackdropSaveFilename(item.GetImages(type), "backdrop", "backdrop", imageIndex);
break;
case ImageType.Screenshot:
2014-02-07 13:30:41 -07:00
filename = GetBackdropSaveFilename(item.GetImages(type), "screenshot", "screenshot", imageIndex);
break;
default:
filename = type.ToString().ToLower();
break;
}
2016-01-23 10:12:11 -07:00
if (string.Equals(extension, ".jpeg", StringComparison.OrdinalIgnoreCase))
{
2016-01-23 10:12:11 -07:00
extension = ".jpg";
}
2016-01-23 10:12:11 -07:00
extension = extension.ToLower();
string path = null;
if (saveLocally)
{
2016-03-21 13:15:18 -07:00
if (type == ImageType.Primary && item is Episode)
{
path = Path.Combine(Path.GetDirectoryName(item.Path), "metadata", filename + extension);
}
2016-10-07 08:08:13 -07:00
else if (item.DetectIsInMixedFolder())
{
path = GetSavePathForItemInMixedFolder(item, type, filename, extension);
}
2013-10-25 13:58:31 -07:00
if (string.IsNullOrEmpty(path))
{
path = Path.Combine(item.ContainingFolderPath, filename + extension);
}
}
// None of the save local conditions passed, so store it in our internal folders
if (string.IsNullOrEmpty(path))
{
2014-02-08 21:52:52 -07:00
if (string.IsNullOrEmpty(filename))
{
2016-01-21 19:59:07 -07:00
filename = folderName;
2014-02-08 21:52:52 -07:00
}
2014-09-28 08:27:26 -07:00
path = Path.Combine(item.GetInternalMetadataPath(), filename + extension);
}
return path;
}
2014-02-07 13:30:41 -07:00
private string GetBackdropSaveFilename(IEnumerable<ItemImageInfo> images, string zeroIndexFilename, string numberedIndexPrefix, int? index)
{
2014-02-07 13:30:41 -07:00
if (index.HasValue && index.Value == 0)
{
return zeroIndexFilename;
}
2014-07-26 10:30:15 -07:00
var filenames = images.Select(i => _fileSystem.GetFileNameWithoutExtension(i.Path)).ToList();
2013-11-02 18:58:56 -07:00
2014-02-07 13:30:41 -07:00
var current = 1;
2013-11-02 18:58:56 -07:00
while (filenames.Contains(numberedIndexPrefix + current.ToString(UsCulture), StringComparer.OrdinalIgnoreCase))
{
current++;
}
return numberedIndexPrefix + current.ToString(UsCulture);
}
/// <summary>
/// Gets the compatible save paths.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="type">The type.</param>
/// <param name="imageIndex">Index of the image.</param>
/// <param name="mimeType">Type of the MIME.</param>
/// <returns>IEnumerable{System.String}.</returns>
/// <exception cref="System.ArgumentNullException">imageIndex</exception>
2014-02-15 15:42:06 -07:00
private string[] GetCompatibleSavePaths(IHasImages item, ImageType type, int? imageIndex, string mimeType)
{
var season = item as Season;
2014-10-19 20:04:45 -07:00
var extension = MimeTypes.ToExtension(mimeType);
// Backdrop paths
if (type == ImageType.Backdrop)
{
if (!imageIndex.HasValue)
{
throw new ArgumentNullException("imageIndex");
}
if (imageIndex.Value == 0)
{
2016-10-07 08:08:13 -07:00
if (item.DetectIsInMixedFolder())
2013-12-11 16:30:41 -07:00
{
return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart", extension) };
}
2014-02-15 15:42:06 -07:00
if (season != null && season.IndexNumber.HasValue)
2013-10-15 18:44:23 -07:00
{
var seriesFolder = season.SeriesPath;
2013-10-15 18:44:23 -07:00
2014-02-15 15:42:06 -07:00
var seasonMarker = season.IndexNumber.Value == 0
2013-10-15 18:44:23 -07:00
? "-specials"
2014-02-15 15:42:06 -07:00
: season.IndexNumber.Value.ToString("00", UsCulture);
2013-10-15 18:44:23 -07:00
var imageFilename = "season" + seasonMarker + "-fanart" + extension;
return new[] { Path.Combine(seriesFolder, imageFilename) };
}
return new[]
{
Path.Combine(item.ContainingFolderPath, "fanart" + extension)
};
}
var outputIndex = imageIndex.Value;
2016-10-07 08:08:13 -07:00
if (item.DetectIsInMixedFolder())
2013-12-11 16:30:41 -07:00
{
return new[] { GetSavePathForItemInMixedFolder(item, type, "fanart" + outputIndex.ToString(UsCulture), extension) };
}
2014-02-07 13:30:41 -07:00
var extraFanartFilename = GetBackdropSaveFilename(item.GetImages(ImageType.Backdrop), "fanart", "fanart", outputIndex);
2013-11-02 18:58:56 -07:00
var list = new List<string>
{
Path.Combine(item.ContainingFolderPath, "extrafanart", extraFanartFilename + extension)
};
if (EnableExtraThumbsDuplication)
{
list.Add(Path.Combine(item.ContainingFolderPath, "extrathumbs", "thumb" + outputIndex.ToString(UsCulture) + extension));
}
return list.ToArray();
}
if (type == ImageType.Primary)
{
2014-02-15 15:42:06 -07:00
if (season != null && season.IndexNumber.HasValue)
{
var seriesFolder = season.SeriesPath;
2014-02-15 15:42:06 -07:00
var seasonMarker = season.IndexNumber.Value == 0
? "-specials"
2014-02-15 15:42:06 -07:00
: season.IndexNumber.Value.ToString("00", UsCulture);
var imageFilename = "season" + seasonMarker + "-poster" + extension;
return new[] { Path.Combine(seriesFolder, imageFilename) };
}
if (item is Episode)
{
var seasonFolder = Path.GetDirectoryName(item.Path);
2014-07-26 10:30:15 -07:00
var imageFilename = _fileSystem.GetFileNameWithoutExtension(item.Path) + "-thumb" + extension;
return new[] { Path.Combine(seasonFolder, imageFilename) };
}
2016-10-07 08:08:13 -07:00
if (item.DetectIsInMixedFolder() || item is MusicVideo)
{
return new[] { GetSavePathForItemInMixedFolder(item, type, string.Empty, extension) };
}
2013-11-21 13:48:26 -07:00
if (item is MusicAlbum || item is MusicArtist)
{
return new[] { Path.Combine(item.ContainingFolderPath, "folder" + extension) };
}
return new[] { Path.Combine(item.ContainingFolderPath, "poster" + extension) };
}
// All other paths are the same
2013-10-17 08:35:39 -07:00
return new[] { GetStandardSavePath(item, type, imageIndex, mimeType, true) };
}
private bool EnableExtraThumbsDuplication
{
get
{
var config = _config.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata");
return config.EnableExtraThumbsDuplication;
}
}
/// <summary>
/// Gets the save path for item in mixed folder.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="type">The type.</param>
/// <param name="imageFilename">The image filename.</param>
/// <param name="extension">The extension.</param>
/// <returns>System.String.</returns>
2013-12-19 14:51:32 -07:00
private string GetSavePathForItemInMixedFolder(IHasImages item, ImageType type, string imageFilename, string extension)
{
if (type == ImageType.Primary)
{
imageFilename = "poster";
}
var folder = Path.GetDirectoryName(item.Path);
2014-07-26 10:30:15 -07:00
return Path.Combine(folder, _fileSystem.GetFileNameWithoutExtension(item.Path) + "-" + imageFilename + extension);
}
}
}