jellyfin/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs

1032 lines
35 KiB
C#
Raw Normal View History

#pragma warning disable CS1591
using System;
2014-07-08 01:41:03 +00:00
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
2017-07-19 19:53:47 +00:00
using System.Text.RegularExpressions;
2014-07-09 00:46:11 +00:00
using System.Threading;
2014-07-08 01:41:03 +00:00
using System.Xml;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
2016-10-25 19:02:04 +00:00
using MediaBrowser.Model.IO;
using MediaBrowser.XbmcMetadata.Configuration;
using Microsoft.Extensions.Logging;
namespace MediaBrowser.XbmcMetadata.Savers
{
2014-07-09 00:46:11 +00:00
public abstract class BaseNfoSaver : IMetadataFileSaver
{
public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss";
public const string YouTubeWatchUrl = "https://www.youtube.com/watch?v=";
// filters control characters but allows only properly-formed surrogate sequences
private const string _invalidXMLCharsRegex = @"(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\uFEFF\uFFFE\uFFFF]";
private static readonly HashSet<string> _commonTags = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"plot",
"customrating",
"lockdata",
"dateadded",
"title",
"rating",
"year",
"sorttitle",
"mpaa",
"aspectratio",
"collectionnumber",
"tmdbid",
"rottentomatoesid",
"language",
"tvcomid",
"tagline",
"studio",
"genre",
"tag",
"runtime",
"actor",
"criticrating",
"fileinfo",
"director",
"writer",
"trailer",
"premiered",
"releasedate",
"outline",
"id",
"credits",
"originaltitle",
"watched",
"playcount",
"lastplayed",
"art",
"resume",
"biography",
"formed",
"review",
"style",
"imdbid",
"imdb_id",
"country",
"audiodbalbumid",
"audiodbartistid",
"enddate",
"lockedfields",
"zap2itid",
"tvrageid",
"musicbrainzartistid",
"musicbrainzalbumartistid",
"musicbrainzalbumid",
"musicbrainzreleasegroupid",
"tvdbid",
"collectionitem",
"isuserfavorite",
"userrating",
"countrycode"
};
protected BaseNfoSaver(
IFileSystem fileSystem,
IServerConfigurationManager configurationManager,
ILibraryManager libraryManager,
IUserManager userManager,
IUserDataManager userDataManager,
2020-06-06 00:15:56 +00:00
ILogger<BaseNfoSaver> logger)
2014-07-09 00:46:11 +00:00
{
2014-07-12 02:31:08 +00:00
Logger = logger;
2014-07-09 00:46:11 +00:00
UserDataManager = userDataManager;
UserManager = userManager;
LibraryManager = libraryManager;
ConfigurationManager = configurationManager;
FileSystem = fileSystem;
}
protected IFileSystem FileSystem { get; }
protected IServerConfigurationManager ConfigurationManager { get; }
protected ILibraryManager LibraryManager { get; }
protected IUserManager UserManager { get; }
protected IUserDataManager UserDataManager { get; }
2020-06-06 00:15:56 +00:00
protected ILogger<BaseNfoSaver> Logger { get; }
2014-07-09 00:46:11 +00:00
protected ItemUpdateType MinimumUpdateType
{
get
{
if (ConfigurationManager.GetNfoConfiguration().SaveImagePathsInNfo)
{
return ItemUpdateType.ImageUpdate;
}
return ItemUpdateType.MetadataDownload;
}
}
2019-09-01 15:24:42 +00:00
/// <inheritdoc />
public string Name => SaverName;
public static string SaverName => "Nfo";
2014-07-09 00:46:11 +00:00
/// <inheritdoc />
2018-09-12 17:26:21 +00:00
public string GetSavePath(BaseItem item)
=> GetLocalSavePath(item);
2015-03-31 19:33:38 +00:00
2014-07-09 00:46:11 +00:00
/// <summary>
/// Gets the save path.
/// </summary>
/// <param name="item">The item.</param>
/// <returns><see cref="string" />.</returns>
2018-09-12 17:26:21 +00:00
protected abstract string GetLocalSavePath(BaseItem item);
2014-07-09 00:46:11 +00:00
/// <summary>
/// Gets the name of the root element.
/// </summary>
/// <param name="item">The item.</param>
/// <returns><see cref="string" />.</returns>
2018-09-12 17:26:21 +00:00
protected abstract string GetRootElementName(BaseItem item);
2014-07-09 00:46:11 +00:00
2019-09-01 15:24:42 +00:00
/// <inheritdoc />
2018-09-12 17:26:21 +00:00
public abstract bool IsEnabledFor(BaseItem item, ItemUpdateType updateType);
2014-07-09 00:46:11 +00:00
2018-09-12 17:26:21 +00:00
protected virtual List<string> GetTagsUsed(BaseItem item)
2014-07-09 00:46:11 +00:00
{
var list = new List<string>();
foreach (var providerKey in item.ProviderIds.Keys)
{
var providerIdTagName = GetTagForProviderKey(providerKey);
if (!_commonTags.Contains(providerIdTagName))
{
list.Add(providerIdTagName);
}
}
return list;
2014-07-09 00:46:11 +00:00
}
2019-09-01 15:24:42 +00:00
/// <inheritdoc />
2018-09-12 17:26:21 +00:00
public void Save(BaseItem item, CancellationToken cancellationToken)
{
2014-07-09 00:46:11 +00:00
var path = GetSavePath(item);
2015-03-31 19:33:38 +00:00
2014-07-09 00:46:11 +00:00
using (var memoryStream = new MemoryStream())
{
2014-07-09 00:46:11 +00:00
Save(item, memoryStream, path);
2014-07-09 00:46:11 +00:00
memoryStream.Position = 0;
2014-07-09 00:46:11 +00:00
cancellationToken.ThrowIfCancellationRequested();
2014-07-09 00:46:11 +00:00
SaveToFile(memoryStream, path);
}
}
2014-07-09 00:46:11 +00:00
private void SaveToFile(Stream stream, string path)
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
2019-09-01 15:24:42 +00:00
2018-09-12 17:26:21 +00:00
// On Windows, savint the file will fail if the file is hidden or readonly
FileSystem.SetAttributes(path, false, false);
using (var filestream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
{
2014-07-09 00:46:11 +00:00
stream.CopyTo(filestream);
}
2018-09-12 17:26:21 +00:00
if (ConfigurationManager.Configuration.SaveMetadataHidden)
{
2017-11-15 21:33:04 +00:00
SetHidden(path, true);
}
}
private void SetHidden(string path, bool hidden)
{
try
{
FileSystem.SetHidden(path, hidden);
}
2019-09-01 15:24:42 +00:00
catch (IOException ex)
2017-11-15 21:33:04 +00:00
{
2019-09-01 15:24:42 +00:00
Logger.LogError(ex, "Error setting hidden attribute on {Path}", path);
}
}
2018-09-12 17:26:21 +00:00
private void Save(BaseItem item, Stream stream, string xmlPath)
{
2014-07-09 00:46:11 +00:00
var settings = new XmlWriterSettings
{
2014-07-09 00:46:11 +00:00
Indent = true,
Encoding = Encoding.UTF8,
CloseOutput = false
};
2019-01-13 20:37:13 +00:00
using (var writer = XmlWriter.Create(stream, settings))
{
2014-07-09 00:46:11 +00:00
var root = GetRootElementName(item);
writer.WriteStartDocument(true);
writer.WriteStartElement(root);
2018-09-12 17:26:21 +00:00
var baseItem = item;
2014-07-09 00:46:11 +00:00
if (baseItem != null)
{
AddCommonNodes(baseItem, writer, LibraryManager, UserManager, UserDataManager, ConfigurationManager);
2014-07-09 00:46:11 +00:00
}
2014-07-09 00:46:11 +00:00
WriteCustomElements(item, writer);
if (baseItem is IHasMediaSources hasMediaSources)
2014-07-09 00:46:11 +00:00
{
AddMediaInfo(hasMediaSources, writer);
}
var tagsUsed = GetTagsUsed(item);
2014-07-09 00:46:11 +00:00
try
{
2019-09-01 15:24:42 +00:00
AddCustomTags(xmlPath, tagsUsed, writer, Logger);
2014-07-09 00:46:11 +00:00
}
catch (FileNotFoundException)
{
}
2016-10-26 02:53:47 +00:00
catch (IOException)
2014-12-23 03:58:14 +00:00
{
}
2015-03-31 19:33:38 +00:00
catch (XmlException ex)
{
2018-12-20 12:11:26 +00:00
Logger.LogError(ex, "Error reading existing nfo");
2015-03-31 19:33:38 +00:00
}
2014-07-09 00:46:11 +00:00
writer.WriteEndElement();
writer.WriteEndDocument();
}
}
2018-09-12 17:26:21 +00:00
protected abstract void WriteCustomElements(BaseItem item, XmlWriter writer);
2014-07-09 00:46:11 +00:00
public static void AddMediaInfo<T>(T item, XmlWriter writer)
2019-09-01 15:24:42 +00:00
where T : IHasMediaSources
{
2014-07-09 00:46:11 +00:00
writer.WriteStartElement("fileinfo");
writer.WriteStartElement("streamdetails");
2017-08-05 19:02:33 +00:00
var mediaStreams = item.GetMediaStreams();
2014-07-09 00:46:11 +00:00
2017-08-05 19:02:33 +00:00
foreach (var stream in mediaStreams)
{
2019-01-27 11:03:43 +00:00
writer.WriteStartElement(stream.Type.ToString().ToLowerInvariant());
if (!string.IsNullOrEmpty(stream.Codec))
{
2016-01-14 17:17:21 +00:00
var codec = stream.Codec;
if ((stream.CodecTag ?? string.Empty).IndexOf("xvid", StringComparison.OrdinalIgnoreCase) != -1)
{
2017-01-12 19:50:52 +00:00
codec = "xvid";
2016-01-14 17:17:21 +00:00
}
else if ((stream.CodecTag ?? string.Empty).IndexOf("divx", StringComparison.OrdinalIgnoreCase) != -1)
{
2017-01-12 19:50:52 +00:00
codec = "divx";
2016-01-14 17:17:21 +00:00
}
writer.WriteElementString("codec", codec);
writer.WriteElementString("micodec", codec);
}
if (stream.BitRate.HasValue)
{
2019-09-01 15:24:42 +00:00
writer.WriteElementString("bitrate", stream.BitRate.Value.ToString(CultureInfo.InvariantCulture));
}
if (stream.Width.HasValue)
{
2019-09-01 15:24:42 +00:00
writer.WriteElementString("width", stream.Width.Value.ToString(CultureInfo.InvariantCulture));
}
if (stream.Height.HasValue)
{
2019-09-01 15:24:42 +00:00
writer.WriteElementString("height", stream.Height.Value.ToString(CultureInfo.InvariantCulture));
}
if (!string.IsNullOrEmpty(stream.AspectRatio))
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("aspect", stream.AspectRatio);
writer.WriteElementString("aspectratio", stream.AspectRatio);
}
var framerate = stream.AverageFrameRate ?? stream.RealFrameRate;
if (framerate.HasValue)
{
2019-09-01 15:24:42 +00:00
writer.WriteElementString("framerate", framerate.Value.ToString(CultureInfo.InvariantCulture));
}
if (!string.IsNullOrEmpty(stream.Language))
{
// http://web.archive.org/web/20181230211547/https://emby.media/community/index.php?/topic/49071-nfo-not-generated-on-actualize-or-rescan-or-identify
// Web Archive version of link since it's not really explained in the thread.
writer.WriteElementString("language", Regex.Replace(stream.Language, _invalidXMLCharsRegex, string.Empty));
}
var scanType = stream.IsInterlaced ? "interlaced" : "progressive";
if (!string.IsNullOrEmpty(scanType))
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("scantype", scanType);
}
if (stream.Channels.HasValue)
{
2019-09-01 15:24:42 +00:00
writer.WriteElementString("channels", stream.Channels.Value.ToString(CultureInfo.InvariantCulture));
}
if (stream.SampleRate.HasValue)
{
2019-09-01 15:24:42 +00:00
writer.WriteElementString("samplingrate", stream.SampleRate.Value.ToString(CultureInfo.InvariantCulture));
}
writer.WriteElementString("default", stream.IsDefault.ToString(CultureInfo.InvariantCulture));
writer.WriteElementString("forced", stream.IsForced.ToString(CultureInfo.InvariantCulture));
if (stream.Type == MediaStreamType.Video)
{
2018-09-12 17:26:21 +00:00
var runtimeTicks = item.RunTimeTicks;
2017-08-05 19:02:33 +00:00
if (runtimeTicks.HasValue)
{
2017-08-05 19:02:33 +00:00
var timespan = TimeSpan.FromTicks(runtimeTicks.Value);
2019-09-01 15:24:42 +00:00
writer.WriteElementString(
"duration",
Math.Floor(timespan.TotalMinutes).ToString(CultureInfo.InvariantCulture));
writer.WriteElementString(
"durationinseconds",
Math.Floor(timespan.TotalSeconds).ToString(CultureInfo.InvariantCulture));
}
if (item is Video video)
{
// AddChapters(video, builder, itemRepository);
if (video.Video3DFormat.HasValue)
{
switch (video.Video3DFormat.Value)
{
case Video3DFormat.FullSideBySide:
2014-07-09 00:46:11 +00:00
writer.WriteElementString("format3d", "FSBS");
break;
case Video3DFormat.FullTopAndBottom:
2014-07-09 00:46:11 +00:00
writer.WriteElementString("format3d", "FTAB");
break;
case Video3DFormat.HalfSideBySide:
2014-07-09 00:46:11 +00:00
writer.WriteElementString("format3d", "HSBS");
break;
case Video3DFormat.HalfTopAndBottom:
2014-07-09 00:46:11 +00:00
writer.WriteElementString("format3d", "HTAB");
break;
2016-02-11 19:11:28 +00:00
case Video3DFormat.MVC:
writer.WriteElementString("format3d", "MVC");
break;
}
}
}
}
2014-07-09 00:46:11 +00:00
writer.WriteEndElement();
}
2014-07-09 00:46:11 +00:00
writer.WriteEndElement();
writer.WriteEndElement();
}
/// <summary>
/// Adds the common nodes.
/// </summary>
2019-09-01 15:24:42 +00:00
private void AddCommonNodes(
BaseItem item,
XmlWriter writer,
ILibraryManager libraryManager,
IUserManager userManager,
IUserDataManager userDataRepo,
IServerConfigurationManager config)
{
2016-10-26 02:53:47 +00:00
var writtenProviderIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var overview = (item.Overview ?? string.Empty)
.StripHtml()
.Replace("&quot;", "'", StringComparison.Ordinal);
var options = config.GetNfoConfiguration();
if (item is MusicArtist)
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("biography", overview);
}
else if (item is MusicAlbum)
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("review", overview);
}
else
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("plot", overview);
}
2016-10-17 16:18:12 +00:00
if (item is Video)
{
2017-01-29 20:00:29 +00:00
var outline = (item.Tagline ?? string.Empty)
.StripHtml()
.Replace("&quot;", "'", StringComparison.Ordinal);
2014-07-09 00:46:11 +00:00
writer.WriteElementString("outline", outline);
}
else
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("outline", overview);
}
if (!string.IsNullOrWhiteSpace(item.CustomRating))
{
writer.WriteElementString("customrating", item.CustomRating);
}
2019-01-27 11:03:43 +00:00
writer.WriteElementString("lockdata", item.IsLocked.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
if (item.LockedFields.Length > 0)
{
writer.WriteElementString("lockedfields", string.Join("|", item.LockedFields));
}
2014-07-09 00:46:11 +00:00
writer.WriteElementString("dateadded", item.DateCreated.ToLocalTime().ToString(DateAddedFormat, CultureInfo.InvariantCulture));
2014-07-09 00:46:11 +00:00
writer.WriteElementString("title", item.Name ?? string.Empty);
2016-10-31 04:28:23 +00:00
if (!string.IsNullOrWhiteSpace(item.OriginalTitle))
2015-03-10 01:30:20 +00:00
{
2016-10-31 04:28:23 +00:00
writer.WriteElementString("originaltitle", item.OriginalTitle);
2015-03-31 19:33:38 +00:00
}
2015-06-21 03:35:22 +00:00
var people = libraryManager.GetPeople(item);
var directors = people
.Where(i => IsPersonType(i, PersonType.Director))
.Select(i => i.Name)
.ToList();
foreach (var person in directors)
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("director", person);
}
2015-06-21 03:35:22 +00:00
var writers = people
2014-06-30 13:28:38 +00:00
.Where(i => IsPersonType(i, PersonType.Writer))
.Select(i => i.Name)
2014-06-30 13:28:38 +00:00
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
foreach (var person in writers)
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("writer", person);
}
2014-07-08 01:41:03 +00:00
foreach (var person in writers)
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("credits", person);
}
2018-09-12 17:26:21 +00:00
foreach (var trailer in item.RemoteTrailers)
{
2018-09-12 17:26:21 +00:00
writer.WriteElementString("trailer", GetOutputTrailerUrl(trailer.Url));
}
if (item.CommunityRating.HasValue)
{
2019-09-01 15:24:42 +00:00
writer.WriteElementString("rating", item.CommunityRating.Value.ToString(CultureInfo.InvariantCulture));
}
if (item.ProductionYear.HasValue)
{
2019-09-01 15:24:42 +00:00
writer.WriteElementString("year", item.ProductionYear.Value.ToString(CultureInfo.InvariantCulture));
}
2017-05-19 16:36:43 +00:00
var forcedSortName = item.ForcedSortName;
if (!string.IsNullOrEmpty(forcedSortName))
{
2017-05-19 16:36:43 +00:00
writer.WriteElementString("sorttitle", forcedSortName);
}
if (!string.IsNullOrEmpty(item.OfficialRating))
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("mpaa", item.OfficialRating);
}
2019-09-01 15:24:42 +00:00
if (item is IHasAspectRatio hasAspectRatio
&& !string.IsNullOrEmpty(hasAspectRatio.AspectRatio))
{
2019-09-01 15:24:42 +00:00
writer.WriteElementString("aspectratio", hasAspectRatio.AspectRatio);
}
2020-06-06 19:17:49 +00:00
var tmdbCollection = item.GetProviderId(MetadataProvider.TmdbCollection);
if (!string.IsNullOrEmpty(tmdbCollection))
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("collectionnumber", tmdbCollection);
2020-06-06 19:17:49 +00:00
writtenProviderIds.Add(MetadataProvider.TmdbCollection.ToString());
}
2020-06-06 19:17:49 +00:00
var imdb = item.GetProviderId(MetadataProvider.Imdb);
if (!string.IsNullOrEmpty(imdb))
{
if (item is Series)
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("imdb_id", imdb);
}
else
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("imdbid", imdb);
}
2019-09-01 15:24:42 +00:00
2020-06-06 19:17:49 +00:00
writtenProviderIds.Add(MetadataProvider.Imdb.ToString());
}
// Series xml saver already saves this
if (!(item is Series))
{
2020-06-06 19:17:49 +00:00
var tvdb = item.GetProviderId(MetadataProvider.Tvdb);
if (!string.IsNullOrEmpty(tvdb))
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("tvdbid", tvdb);
2020-06-06 19:17:49 +00:00
writtenProviderIds.Add(MetadataProvider.Tvdb.ToString());
}
}
2020-06-06 19:17:49 +00:00
var tmdb = item.GetProviderId(MetadataProvider.Tmdb);
if (!string.IsNullOrEmpty(tmdb))
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("tmdbid", tmdb);
2020-06-06 19:17:49 +00:00
writtenProviderIds.Add(MetadataProvider.Tmdb.ToString());
}
2015-09-29 17:35:23 +00:00
if (!string.IsNullOrEmpty(item.PreferredMetadataLanguage))
{
2015-09-29 17:35:23 +00:00
writer.WriteElementString("language", item.PreferredMetadataLanguage);
}
2015-09-29 17:35:23 +00:00
if (!string.IsNullOrEmpty(item.PreferredMetadataCountryCode))
{
writer.WriteElementString("countrycode", item.PreferredMetadataCountryCode);
}
if (item.PremiereDate.HasValue && !(item is Episode))
{
var formatString = options.ReleaseDateFormat;
if (item is MusicArtist)
{
2019-09-01 15:24:42 +00:00
writer.WriteElementString(
"formed",
item.PremiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture));
}
else
{
2019-09-01 15:24:42 +00:00
writer.WriteElementString(
"premiered",
item.PremiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture));
2019-09-01 15:24:42 +00:00
writer.WriteElementString(
"releasedate",
item.PremiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture));
}
}
if (item.EndDate.HasValue)
{
if (!(item is Episode))
{
var formatString = options.ReleaseDateFormat;
2019-09-01 15:24:42 +00:00
writer.WriteElementString(
"enddate",
item.EndDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture));
}
}
2016-10-17 16:18:12 +00:00
if (item.CriticRating.HasValue)
{
2019-09-01 15:24:42 +00:00
writer.WriteElementString(
"criticrating",
item.CriticRating.Value.ToString(CultureInfo.InvariantCulture));
2016-10-17 16:18:12 +00:00
}
if (item is IHasDisplayOrder hasDisplayOrder)
{
if (!string.IsNullOrEmpty(hasDisplayOrder.DisplayOrder))
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("displayorder", hasDisplayOrder.DisplayOrder);
}
}
// Use original runtime here, actual file runtime later in MediaInfo
var runTimeTicks = item.RunTimeTicks;
if (runTimeTicks.HasValue)
{
var timespan = TimeSpan.FromTicks(runTimeTicks.Value);
2019-09-01 15:24:42 +00:00
writer.WriteElementString(
"runtime",
Convert.ToInt64(timespan.TotalMinutes).ToString(CultureInfo.InvariantCulture));
}
2016-10-08 05:57:38 +00:00
if (!string.IsNullOrWhiteSpace(item.Tagline))
{
2016-10-08 05:57:38 +00:00
writer.WriteElementString("tagline", item.Tagline);
}
2016-10-09 07:18:43 +00:00
foreach (var country in item.ProductionLocations)
{
writer.WriteElementString("country", country);
}
foreach (var genre in item.Genres)
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("genre", genre);
}
foreach (var studio in item.Studios)
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("studio", studio);
}
2016-06-02 17:43:29 +00:00
foreach (var tag in item.Tags)
{
2016-06-02 17:43:29 +00:00
if (item is MusicAlbum || item is MusicArtist)
{
2016-06-02 17:43:29 +00:00
writer.WriteElementString("style", tag);
}
else
{
writer.WriteElementString("tag", tag);
}
}
2020-06-06 19:17:49 +00:00
var externalId = item.GetProviderId(MetadataProvider.AudioDbArtist);
if (!string.IsNullOrEmpty(externalId))
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("audiodbartistid", externalId);
2020-06-06 19:17:49 +00:00
writtenProviderIds.Add(MetadataProvider.AudioDbArtist.ToString());
}
2020-06-06 19:17:49 +00:00
externalId = item.GetProviderId(MetadataProvider.AudioDbAlbum);
if (!string.IsNullOrEmpty(externalId))
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("audiodbalbumid", externalId);
2020-06-06 19:17:49 +00:00
writtenProviderIds.Add(MetadataProvider.AudioDbAlbum.ToString());
}
2020-06-06 19:17:49 +00:00
externalId = item.GetProviderId(MetadataProvider.Zap2It);
if (!string.IsNullOrEmpty(externalId))
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("zap2itid", externalId);
2020-06-06 19:17:49 +00:00
writtenProviderIds.Add(MetadataProvider.Zap2It.ToString());
}
2020-06-06 19:17:49 +00:00
externalId = item.GetProviderId(MetadataProvider.MusicBrainzAlbum);
if (!string.IsNullOrEmpty(externalId))
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("musicbrainzalbumid", externalId);
2020-06-06 19:17:49 +00:00
writtenProviderIds.Add(MetadataProvider.MusicBrainzAlbum.ToString());
}
2020-06-06 19:17:49 +00:00
externalId = item.GetProviderId(MetadataProvider.MusicBrainzAlbumArtist);
if (!string.IsNullOrEmpty(externalId))
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("musicbrainzalbumartistid", externalId);
2020-06-06 19:17:49 +00:00
writtenProviderIds.Add(MetadataProvider.MusicBrainzAlbumArtist.ToString());
}
2020-06-06 19:17:49 +00:00
externalId = item.GetProviderId(MetadataProvider.MusicBrainzArtist);
if (!string.IsNullOrEmpty(externalId))
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("musicbrainzartistid", externalId);
2020-06-06 19:17:49 +00:00
writtenProviderIds.Add(MetadataProvider.MusicBrainzArtist.ToString());
}
2020-06-06 19:17:49 +00:00
externalId = item.GetProviderId(MetadataProvider.MusicBrainzReleaseGroup);
if (!string.IsNullOrEmpty(externalId))
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("musicbrainzreleasegroupid", externalId);
2020-06-06 19:17:49 +00:00
writtenProviderIds.Add(MetadataProvider.MusicBrainzReleaseGroup.ToString());
}
2020-06-06 19:17:49 +00:00
externalId = item.GetProviderId(MetadataProvider.TvRage);
if (!string.IsNullOrEmpty(externalId))
{
2014-07-09 00:46:11 +00:00
writer.WriteElementString("tvrageid", externalId);
2020-06-06 19:17:49 +00:00
writtenProviderIds.Add(MetadataProvider.TvRage.ToString());
}
if (item.ProviderIds != null)
{
foreach (var providerKey in item.ProviderIds.Keys)
{
var providerId = item.ProviderIds[providerKey];
if (!string.IsNullOrEmpty(providerId) && !writtenProviderIds.Contains(providerKey))
{
2018-09-12 17:26:21 +00:00
try
{
var tagName = GetTagForProviderKey(providerKey);
2019-09-01 15:24:42 +00:00
Logger.LogDebug("Verifying custom provider tagname {0}", tagName);
2018-09-12 17:26:21 +00:00
XmlConvert.VerifyName(tagName);
2019-09-01 15:24:42 +00:00
Logger.LogDebug("Saving custom provider tagname {0}", tagName);
2018-09-12 17:26:21 +00:00
writer.WriteElementString(GetTagForProviderKey(providerKey), providerId);
}
catch (ArgumentException)
{
// catch invalid names without failing the entire operation
}
catch (XmlException)
{
// catch invalid names without failing the entire operation
}
}
}
}
if (options.SaveImagePathsInNfo)
{
AddImages(item, writer, libraryManager);
}
2014-07-09 00:46:11 +00:00
AddUserData(item, writer, userManager, userDataRepo, options);
AddActors(people, writer, libraryManager, options.SaveImagePathsInNfo);
if (item is BoxSet folder)
{
2014-07-09 00:46:11 +00:00
AddCollectionItems(folder, writer);
}
}
2018-09-12 17:26:21 +00:00
private void AddCollectionItems(Folder item, XmlWriter writer)
{
var items = item.LinkedChildren
2015-03-05 02:49:08 +00:00
.Where(i => i.Type == LinkedChildType.Manual)
.ToList();
foreach (var link in items)
{
2014-07-09 00:46:11 +00:00
writer.WriteStartElement("collectionitem");
2015-03-05 02:49:08 +00:00
if (!string.IsNullOrWhiteSpace(link.Path))
{
2015-03-05 02:49:08 +00:00
writer.WriteElementString("path", link.Path);
}
2018-09-12 17:26:21 +00:00
if (!string.IsNullOrWhiteSpace(link.LibraryItemId))
{
writer.WriteElementString("ItemId", link.LibraryItemId);
}
2014-07-09 00:46:11 +00:00
writer.WriteEndElement();
}
}
/// <summary>
/// Gets the output trailer URL.
/// </summary>
/// <param name="url">The URL.</param>
/// <returns>System.String.</returns>
2018-09-12 17:26:21 +00:00
private string GetOutputTrailerUrl(string url)
{
// This is what xbmc expects
2018-09-12 17:26:21 +00:00
return url.Replace(YouTubeWatchUrl, "plugin://plugin.video.youtube/?action=play_video&videoid=", StringComparison.OrdinalIgnoreCase);
}
private void AddImages(BaseItem item, XmlWriter writer, ILibraryManager libraryManager)
{
2014-07-09 00:46:11 +00:00
writer.WriteStartElement("art");
2015-10-16 17:06:31 +00:00
var image = item.GetImageInfo(ImageType.Primary, 0);
2016-11-27 19:36:56 +00:00
if (image != null)
{
writer.WriteElementString("poster", GetImagePathToSave(image, libraryManager));
}
foreach (var backdrop in item.GetImages(ImageType.Backdrop))
{
writer.WriteElementString("fanart", GetImagePathToSave(backdrop, libraryManager));
}
2014-07-09 00:46:11 +00:00
writer.WriteEndElement();
}
2018-09-12 17:26:21 +00:00
private void AddUserData(BaseItem item, XmlWriter writer, IUserManager userManager, IUserDataManager userDataRepo, XbmcMetadataOptions options)
{
var userId = options.UserId;
if (string.IsNullOrWhiteSpace(userId))
{
return;
}
var user = userManager.GetUserById(Guid.Parse(userId));
if (user == null)
{
return;
}
if (item.IsFolder)
{
return;
}
2016-04-30 22:05:13 +00:00
var userdata = userDataRepo.GetUserData(user, item);
2019-09-01 15:24:42 +00:00
writer.WriteElementString(
"isuserfavorite",
userdata.IsFavorite.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
if (userdata.Rating.HasValue)
{
2019-09-01 15:24:42 +00:00
writer.WriteElementString(
"userrating",
userdata.Rating.Value.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
}
if (!item.IsFolder)
{
2019-09-01 15:24:42 +00:00
writer.WriteElementString(
"playcount",
userdata.PlayCount.ToString(CultureInfo.InvariantCulture));
writer.WriteElementString(
"watched",
userdata.Played.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
if (userdata.LastPlayedDate.HasValue)
{
2019-09-01 15:24:42 +00:00
writer.WriteElementString(
"lastplayed",
userdata.LastPlayedDate.Value.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture).ToLowerInvariant());
}
writer.WriteStartElement("resume");
var runTimeTicks = item.RunTimeTicks ?? 0;
2019-09-01 15:24:42 +00:00
writer.WriteElementString(
"position",
TimeSpan.FromTicks(userdata.PlaybackPositionTicks).TotalSeconds.ToString(CultureInfo.InvariantCulture));
writer.WriteElementString(
"total",
TimeSpan.FromTicks(runTimeTicks).TotalSeconds.ToString(CultureInfo.InvariantCulture));
}
2014-07-09 00:46:11 +00:00
writer.WriteEndElement();
}
private void AddActors(List<PersonInfo> people, XmlWriter writer, ILibraryManager libraryManager, bool saveImagePath)
{
2019-01-27 11:03:43 +00:00
foreach (var person in people)
{
2019-01-27 11:03:43 +00:00
if (IsPersonType(person, PersonType.Director) || IsPersonType(person, PersonType.Writer))
{
continue;
}
2014-07-09 00:46:11 +00:00
writer.WriteStartElement("actor");
if (!string.IsNullOrWhiteSpace(person.Name))
{
writer.WriteElementString("name", person.Name);
}
if (!string.IsNullOrWhiteSpace(person.Role))
{
writer.WriteElementString("role", person.Role);
}
2014-07-09 00:46:11 +00:00
if (!string.IsNullOrWhiteSpace(person.Type))
{
writer.WriteElementString("type", person.Type);
}
2015-03-31 19:33:38 +00:00
2014-06-30 13:28:38 +00:00
if (person.SortOrder.HasValue)
{
2019-09-01 15:24:42 +00:00
writer.WriteElementString(
"sortorder",
person.SortOrder.Value.ToString(CultureInfo.InvariantCulture));
2014-06-30 13:28:38 +00:00
}
2017-01-10 20:17:01 +00:00
if (saveImagePath)
{
var personEntity = libraryManager.GetPerson(person.Name);
var image = personEntity.GetImageInfo(ImageType.Primary, 0);
if (image != null)
{
2019-09-01 15:24:42 +00:00
writer.WriteElementString(
"thumb",
GetImagePathToSave(image, libraryManager));
}
}
2014-07-09 00:46:11 +00:00
writer.WriteEndElement();
}
}
private string GetImagePathToSave(ItemImageInfo image, ILibraryManager libraryManager)
{
2016-11-27 19:36:56 +00:00
if (!image.IsLocalFile)
{
return image.Path;
}
return libraryManager.GetPathAfterNetworkSubstitution(image.Path);
}
2018-09-12 17:26:21 +00:00
private bool IsPersonType(PersonInfo person, string type)
2019-09-01 15:24:42 +00:00
=> string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase)
|| string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase);
2014-07-09 00:46:11 +00:00
2020-06-06 00:15:56 +00:00
private void AddCustomTags(string path, List<string> xmlTagsUsed, XmlWriter writer, ILogger<BaseNfoSaver> logger)
{
var settings = new XmlReaderSettings()
{
ValidationType = ValidationType.None,
CheckCharacters = false,
IgnoreProcessingInstructions = true,
IgnoreComments = true
};
2016-10-26 02:53:47 +00:00
2019-01-26 21:31:59 +00:00
using (var fileStream = File.OpenRead(path))
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
using (var reader = XmlReader.Create(streamReader, settings))
{
try
{
reader.MoveToContent();
}
catch (Exception ex)
2014-07-09 00:46:11 +00:00
{
2019-09-01 15:24:42 +00:00
logger.LogError(ex, "Error reading existing xml tags from {Path}.", path);
return;
}
reader.Read();
// Loop through each element
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
{
if (reader.NodeType == XmlNodeType.Element)
2014-07-12 02:31:08 +00:00
{
var name = reader.Name;
2019-09-01 15:24:42 +00:00
if (!_commonTags.Contains(name)
&& !xmlTagsUsed.Contains(name, StringComparer.OrdinalIgnoreCase))
2014-07-09 00:46:11 +00:00
{
writer.WriteNode(reader, false);
2016-10-26 02:53:47 +00:00
}
else
2016-10-26 02:53:47 +00:00
{
reader.Skip();
2016-10-26 02:53:47 +00:00
}
}
else
{
2016-11-02 17:08:20 +00:00
reader.Read();
2014-07-09 00:46:11 +00:00
}
}
}
}
2018-09-12 17:26:21 +00:00
private string GetTagForProviderKey(string providerKey)
=> providerKey.ToLowerInvariant() + "id";
}
}