using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.Entities;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security;
using System.Text;
using System.Xml;
namespace MediaBrowser.Providers.Savers
{
///
/// Class XmlHelpers
///
public static class XmlSaverHelpers
{
private static readonly Dictionary CommonTags = new[] {
"Added",
"AspectRatio",
"BirthDate",
"Budget",
"certification",
"Chapters",
"ContentRating",
"CustomRating",
"CriticRating",
"CriticRatingSummary",
"DeathDate",
"EndDate",
"Genres",
"Genre",
"GamesDbId",
"IMDB_ID",
"IMDB",
"IMDbId",
"Language",
"LocalTitle",
"LockData",
"LockedFields",
"MediaInfo",
"MPAARating",
"MusicbrainzId",
"MusicBrainzReleaseGroupId",
"Overview",
"Persons",
"PremiereDate",
"ProductionYear",
"Rating",
"Revenue",
"RottenTomatoesId",
"RunningTime",
"Runtime",
"SortTitle",
"Studios",
"Tags",
"TagLine",
"Taglines",
"TMDbCollectionId",
"TMDbId",
"Trailer",
"Trailers",
"TVcomId",
"TvDbId",
"Type",
"VoteCount",
"Website",
"Zap2ItId"
}.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
///
/// The us culture
///
private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
///
/// Saves the specified XML.
///
/// The XML.
/// The path.
/// The XML tags used.
public static void Save(StringBuilder xml, string path, List xmlTagsUsed)
{
if (File.Exists(path))
{
var position = xml.ToString().LastIndexOf("", StringComparison.OrdinalIgnoreCase);
xml.Insert(position, GetCustomTags(path, xmlTagsUsed));
}
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml.ToString());
//Add the new node to the document.
xmlDocument.InsertBefore(xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", "yes"), xmlDocument.DocumentElement);
var parentPath = Path.GetDirectoryName(path);
Directory.CreateDirectory(parentPath);
var wasHidden = false;
var file = new FileInfo(path);
// This will fail if the file is hidden
if (file.Exists)
{
if ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
{
file.Attributes &= ~FileAttributes.Hidden;
wasHidden = true;
}
}
using (var filestream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
{
using (var streamWriter = new StreamWriter(filestream, Encoding.UTF8))
{
xmlDocument.Save(streamWriter);
}
}
if (wasHidden)
{
file.Refresh();
// Add back the attribute
file.Attributes |= FileAttributes.Hidden;
}
}
///
/// Gets the custom tags.
///
/// The path.
/// The XML tags used.
/// System.String.
private static string GetCustomTags(string path, List xmlTagsUsed)
{
var settings = new XmlReaderSettings
{
CheckCharacters = false,
IgnoreProcessingInstructions = true,
IgnoreComments = true,
ValidationType = ValidationType.None
};
var builder = new StringBuilder();
using (var streamReader = new StreamReader(path, Encoding.UTF8))
{
// Use XmlReader for best performance
using (var reader = XmlReader.Create(streamReader, settings))
{
reader.MoveToContent();
// Loop through each element
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
var name = reader.Name;
if (!CommonTags.ContainsKey(name) && !xmlTagsUsed.Contains(name, StringComparer.OrdinalIgnoreCase))
{
builder.AppendLine(reader.ReadOuterXml());
}
else
{
reader.Skip();
}
}
}
}
}
return builder.ToString();
}
///
/// Adds the common nodes.
///
/// The item.
/// The builder.
public static void AddCommonNodes(BaseItem item, StringBuilder builder)
{
if (!string.IsNullOrEmpty(item.OfficialRating))
{
builder.Append("" + SecurityElement.Escape(item.OfficialRating) + "");
builder.Append("" + SecurityElement.Escape(item.OfficialRating) + "");
builder.Append("" + SecurityElement.Escape(item.OfficialRating) + "");
}
builder.Append("" + SecurityElement.Escape(item.DateCreated.ToLocalTime().ToString("G")) + "");
builder.Append("" + item.DontFetchMeta.ToString().ToLower() + "");
if (item.LockedFields.Count > 0)
{
builder.Append("" + string.Join("|", item.LockedFields.Select(i => i.ToString()).ToArray()) + "");
}
if (!string.IsNullOrEmpty(item.DisplayMediaType))
{
builder.Append("" + SecurityElement.Escape(item.DisplayMediaType) + "");
}
var hasCriticRating = item as IHasCriticRating;
if (hasCriticRating != null)
{
if (hasCriticRating.CriticRating.HasValue)
{
builder.Append("" + SecurityElement.Escape(hasCriticRating.CriticRating.Value.ToString(UsCulture)) + "");
}
if (!string.IsNullOrEmpty(hasCriticRating.CriticRatingSummary))
{
builder.Append("");
}
}
if (!string.IsNullOrEmpty(item.Overview))
{
builder.Append("");
}
if (!string.IsNullOrEmpty(item.CustomRating))
{
builder.Append("" + SecurityElement.Escape(item.CustomRating) + "");
}
if (!string.IsNullOrEmpty(item.Name) && !(item is Episode))
{
builder.Append("" + SecurityElement.Escape(item.Name) + "");
}
if (!string.IsNullOrEmpty(item.ForcedSortName))
{
builder.Append("" + SecurityElement.Escape(item.ForcedSortName) + "");
}
if (item.PremiereDate.HasValue)
{
if (item is Person)
{
builder.Append("" + SecurityElement.Escape(item.PremiereDate.Value.ToString("yyyy-MM-dd")) + "");
}
else if (!(item is Episode))
{
builder.Append("" + SecurityElement.Escape(item.PremiereDate.Value.ToString("yyyy-MM-dd")) + "");
}
}
if (item.EndDate.HasValue)
{
if (item is Person)
{
builder.Append("" + SecurityElement.Escape(item.EndDate.Value.ToString("yyyy-MM-dd")) + "");
}
else if (!(item is Episode))
{
builder.Append("" + SecurityElement.Escape(item.EndDate.Value.ToString("yyyy-MM-dd")) + "");
}
}
var hasTrailers = item as IHasTrailers;
if (hasTrailers != null)
{
if (hasTrailers.RemoteTrailers.Count > 0)
{
builder.Append("");
foreach (var trailer in hasTrailers.RemoteTrailers)
{
builder.Append("" + SecurityElement.Escape(trailer.Url) + "");
}
builder.Append("");
}
}
var hasBudget = item as IHasBudget;
if (hasBudget != null)
{
if (hasBudget.Budget.HasValue)
{
builder.Append("" + SecurityElement.Escape(hasBudget.Budget.Value.ToString(UsCulture)) + "");
}
if (hasBudget.Revenue.HasValue)
{
builder.Append("" + SecurityElement.Escape(hasBudget.Revenue.Value.ToString(UsCulture)) + "");
}
}
if (item.CommunityRating.HasValue)
{
builder.Append("" + SecurityElement.Escape(item.CommunityRating.Value.ToString(UsCulture)) + "");
}
if (item.VoteCount.HasValue)
{
builder.Append("" + SecurityElement.Escape(item.VoteCount.Value.ToString(UsCulture)) + "");
}
if (item.ProductionYear.HasValue && !(item is Person))
{
builder.Append("" + SecurityElement.Escape(item.ProductionYear.Value.ToString(UsCulture)) + "");
}
if (!string.IsNullOrEmpty(item.HomePageUrl))
{
builder.Append("" + SecurityElement.Escape(item.HomePageUrl) + "");
}
var hasAspectRatio = item as IHasAspectRatio;
if (hasAspectRatio != null)
{
if (!string.IsNullOrEmpty(hasAspectRatio.AspectRatio))
{
builder.Append("" + SecurityElement.Escape(hasAspectRatio.AspectRatio) + "");
}
}
var hasLanguage = item as IHasLanguage;
if (hasLanguage != null)
{
if (!string.IsNullOrEmpty(hasLanguage.Language))
{
builder.Append("" + SecurityElement.Escape(hasLanguage.Language) + "");
}
}
// Use original runtime here, actual file runtime later in MediaInfo
var runTimeTicks = item.OriginalRunTimeTicks ?? item.RunTimeTicks;
if (runTimeTicks.HasValue)
{
var timespan = TimeSpan.FromTicks(runTimeTicks.Value);
builder.Append("" + Convert.ToInt32(timespan.TotalMinutes).ToString(UsCulture) + "");
builder.Append("" + Convert.ToInt32(timespan.TotalMinutes).ToString(UsCulture) + "");
}
var imdb = item.GetProviderId(MetadataProviders.Imdb);
if (!string.IsNullOrEmpty(imdb))
{
builder.Append("" + SecurityElement.Escape(imdb) + "");
builder.Append("" + SecurityElement.Escape(imdb) + "");
builder.Append("" + SecurityElement.Escape(imdb) + "");
}
var tmdb = item.GetProviderId(MetadataProviders.Tmdb);
if (!string.IsNullOrEmpty(tmdb))
{
builder.Append("" + SecurityElement.Escape(tmdb) + "");
}
if (!(item is Series))
{
var tvdb = item.GetProviderId(MetadataProviders.Tvdb);
if (!string.IsNullOrEmpty(tvdb))
{
builder.Append("" + SecurityElement.Escape(tvdb) + "");
}
}
var tvcom = item.GetProviderId(MetadataProviders.Tvcom);
if (!string.IsNullOrEmpty(tvcom))
{
builder.Append("" + SecurityElement.Escape(tvcom) + "");
}
var rt = item.GetProviderId(MetadataProviders.RottenTomatoes);
if (!string.IsNullOrEmpty(rt))
{
builder.Append("" + SecurityElement.Escape(rt) + "");
}
var zap2It = item.GetProviderId(MetadataProviders.Zap2It);
if (!string.IsNullOrEmpty(zap2It))
{
builder.Append("" + SecurityElement.Escape(zap2It) + "");
}
var mbz = item.GetProviderId(MetadataProviders.Musicbrainz);
if (!string.IsNullOrEmpty(mbz))
{
builder.Append("" + SecurityElement.Escape(mbz) + "");
}
mbz = item.GetProviderId(MetadataProviders.MusicBrainzReleaseGroup);
if (!string.IsNullOrEmpty(mbz))
{
builder.Append("" + SecurityElement.Escape(mbz) + "");
}
var gamesdb = item.GetProviderId(MetadataProviders.Gamesdb);
if (!string.IsNullOrEmpty(gamesdb))
{
builder.Append("" + SecurityElement.Escape(gamesdb) + "");
}
var tmdbCollection = item.GetProviderId(MetadataProviders.TmdbCollection);
if (!string.IsNullOrEmpty(tmdbCollection))
{
builder.Append("" + SecurityElement.Escape(tmdbCollection) + "");
}
var hasTagline = item as IHasTaglines;
if (hasTagline != null)
{
if (hasTagline.Taglines.Count > 0)
{
builder.Append("" + SecurityElement.Escape(hasTagline.Taglines[0]) + "");
builder.Append("");
foreach (var tagline in hasTagline.Taglines)
{
builder.Append("" + SecurityElement.Escape(tagline) + "");
}
builder.Append("");
}
}
if (item.Genres.Count > 0)
{
builder.Append("");
foreach (var genre in item.Genres)
{
builder.Append("" + SecurityElement.Escape(genre) + "");
}
builder.Append("");
builder.Append("" + SecurityElement.Escape(string.Join("|", item.Genres.ToArray())) + "");
}
if (item.Studios.Count > 0)
{
builder.Append("");
foreach (var studio in item.Studios)
{
builder.Append("" + SecurityElement.Escape(studio) + "");
}
builder.Append("");
}
var hasTags = item as IHasTags;
if (hasTags != null)
{
if (hasTags.Tags.Count > 0)
{
builder.Append("");
foreach (var tag in hasTags.Tags)
{
builder.Append("" + SecurityElement.Escape(tag) + "");
}
builder.Append("");
}
}
if (item.People.Count > 0)
{
builder.Append("");
foreach (var person in item.People)
{
builder.Append("");
builder.Append("" + SecurityElement.Escape(person.Name) + "");
builder.Append("" + SecurityElement.Escape(person.Type) + "");
builder.Append("" + SecurityElement.Escape(person.Role) + "");
if (person.SortOrder.HasValue)
{
builder.Append("" + SecurityElement.Escape(person.SortOrder.Value.ToString(UsCulture)) + "");
}
builder.Append("");
}
builder.Append("");
}
}
public static void AddChapters(Video item, StringBuilder builder, IItemRepository repository)
{
var chapters = repository.GetChapters(item.Id);
builder.Append("");
foreach (var chapter in chapters)
{
builder.Append("");
builder.Append("" + SecurityElement.Escape(chapter.Name) + "");
var time = TimeSpan.FromTicks(chapter.StartPositionTicks);
var ms = Convert.ToInt64(time.TotalMilliseconds);
builder.Append("" + SecurityElement.Escape(ms.ToString(UsCulture)) + "");
builder.Append("");
}
builder.Append("");
}
///
/// Appends the media info.
///
///
public static void AddMediaInfo(T item, StringBuilder builder, IItemRepository itemRepository)
where T : BaseItem, IHasMediaStreams
{
var video = item as Video;
builder.Append("");
builder.Append("");
builder.Append("");
}
}
}