BaseXmlSaver.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Security;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Xml;
  10. using MediaBrowser.Common.Extensions;
  11. using MediaBrowser.Controller.Configuration;
  12. using MediaBrowser.Controller.Entities;
  13. using MediaBrowser.Controller.Entities.Audio;
  14. using MediaBrowser.Controller.Entities.Movies;
  15. using MediaBrowser.Controller.Entities.TV;
  16. using MediaBrowser.Controller.Library;
  17. using MediaBrowser.Controller.Persistence;
  18. using MediaBrowser.Controller.Playlists;
  19. using MediaBrowser.Model.Configuration;
  20. using MediaBrowser.Model.Entities;
  21. using MediaBrowser.Model.Extensions;
  22. using MediaBrowser.Model.IO;
  23. using MediaBrowser.Model.Logging;
  24. using MediaBrowser.Model.Xml;
  25. namespace MediaBrowser.LocalMetadata.Savers
  26. {
  27. public abstract class BaseXmlSaver : IMetadataFileSaver
  28. {
  29. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  30. private static readonly Dictionary<string, string> CommonTags = new[] {
  31. "Added",
  32. "AspectRatio",
  33. "AudioDbAlbumId",
  34. "AudioDbArtistId",
  35. "AwardSummary",
  36. "BirthDate",
  37. // Deprecated. No longer saving in this field.
  38. "certification",
  39. "Chapters",
  40. "ContentRating",
  41. "Countries",
  42. "CustomRating",
  43. "CriticRating",
  44. "DeathDate",
  45. "DisplayOrder",
  46. "EndDate",
  47. "Genres",
  48. "Genre",
  49. "GamesDbId",
  50. // Deprecated. No longer saving in this field.
  51. "IMDB_ID",
  52. "IMDB",
  53. // Deprecated. No longer saving in this field.
  54. "IMDbId",
  55. "Language",
  56. "LocalTitle",
  57. "OriginalTitle",
  58. "LockData",
  59. "LockedFields",
  60. "Format3D",
  61. // Deprecated. No longer saving in this field.
  62. "MPAARating",
  63. "MusicBrainzArtistId",
  64. "MusicBrainzAlbumArtistId",
  65. "MusicBrainzAlbumId",
  66. "MusicBrainzReleaseGroupId",
  67. // Deprecated. No longer saving in this field.
  68. "MusicbrainzId",
  69. "Overview",
  70. "Persons",
  71. "PlotKeywords",
  72. "PremiereDate",
  73. "ProductionYear",
  74. "Rating",
  75. "RottenTomatoesId",
  76. "RunningTime",
  77. // Deprecated. No longer saving in this field.
  78. "Runtime",
  79. "SortTitle",
  80. "Studios",
  81. "Tags",
  82. // Deprecated. No longer saving in this field.
  83. "TagLine",
  84. "Taglines",
  85. "TMDbCollectionId",
  86. "TMDbId",
  87. // Deprecated. No longer saving in this field.
  88. "Trailer",
  89. "Trailers",
  90. "TVcomId",
  91. "TvDbId",
  92. "Type",
  93. "TVRageId",
  94. "VoteCount",
  95. "Website",
  96. "Zap2ItId",
  97. "CollectionItems",
  98. "PlaylistItems",
  99. "Shares"
  100. }.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
  101. public BaseXmlSaver(IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataManager, ILogger logger, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
  102. {
  103. FileSystem = fileSystem;
  104. ConfigurationManager = configurationManager;
  105. LibraryManager = libraryManager;
  106. UserManager = userManager;
  107. UserDataManager = userDataManager;
  108. Logger = logger;
  109. XmlReaderSettingsFactory = xmlReaderSettingsFactory;
  110. }
  111. protected IFileSystem FileSystem { get; private set; }
  112. protected IServerConfigurationManager ConfigurationManager { get; private set; }
  113. protected ILibraryManager LibraryManager { get; private set; }
  114. protected IUserManager UserManager { get; private set; }
  115. protected IUserDataManager UserDataManager { get; private set; }
  116. protected ILogger Logger { get; private set; }
  117. protected IXmlReaderSettingsFactory XmlReaderSettingsFactory { get; private set; }
  118. protected ItemUpdateType MinimumUpdateType
  119. {
  120. get
  121. {
  122. return ItemUpdateType.MetadataDownload;
  123. }
  124. }
  125. public string Name
  126. {
  127. get
  128. {
  129. return XmlProviderUtils.Name;
  130. }
  131. }
  132. public string GetSavePath(IHasMetadata item)
  133. {
  134. return GetLocalSavePath(item);
  135. }
  136. /// <summary>
  137. /// Gets the save path.
  138. /// </summary>
  139. /// <param name="item">The item.</param>
  140. /// <returns>System.String.</returns>
  141. protected abstract string GetLocalSavePath(IHasMetadata item);
  142. /// <summary>
  143. /// Gets the name of the root element.
  144. /// </summary>
  145. /// <param name="item">The item.</param>
  146. /// <returns>System.String.</returns>
  147. protected virtual string GetRootElementName(IHasMetadata item)
  148. {
  149. return "Item";
  150. }
  151. /// <summary>
  152. /// Determines whether [is enabled for] [the specified item].
  153. /// </summary>
  154. /// <param name="item">The item.</param>
  155. /// <param name="updateType">Type of the update.</param>
  156. /// <returns><c>true</c> if [is enabled for] [the specified item]; otherwise, <c>false</c>.</returns>
  157. public abstract bool IsEnabledFor(IHasMetadata item, ItemUpdateType updateType);
  158. protected virtual List<string> GetTagsUsed()
  159. {
  160. return new List<string>();
  161. }
  162. public void Save(IHasMetadata item, CancellationToken cancellationToken)
  163. {
  164. var path = GetSavePath(item);
  165. using (var memoryStream = new MemoryStream())
  166. {
  167. Save(item, memoryStream, path);
  168. memoryStream.Position = 0;
  169. cancellationToken.ThrowIfCancellationRequested();
  170. SaveToFile(memoryStream, path);
  171. }
  172. }
  173. private void SaveToFile(Stream stream, string path)
  174. {
  175. FileSystem.CreateDirectory(FileSystem.GetDirectoryName(path));
  176. var file = FileSystem.GetFileInfo(path);
  177. var wasHidden = false;
  178. // This will fail if the file is hidden
  179. if (file.Exists)
  180. {
  181. if (file.IsHidden)
  182. {
  183. wasHidden = true;
  184. }
  185. FileSystem.SetAttributes(path, false, false);
  186. }
  187. using (var filestream = FileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  188. {
  189. stream.CopyTo(filestream);
  190. }
  191. if (wasHidden || ConfigurationManager.Configuration.SaveMetadataHidden)
  192. {
  193. FileSystem.SetHidden(path, true);
  194. }
  195. }
  196. private void Save(IHasMetadata item, Stream stream, string xmlPath)
  197. {
  198. var settings = new XmlWriterSettings
  199. {
  200. Indent = true,
  201. Encoding = Encoding.UTF8,
  202. CloseOutput = false
  203. };
  204. using (XmlWriter writer = XmlWriter.Create(stream, settings))
  205. {
  206. var root = GetRootElementName(item);
  207. writer.WriteStartDocument(true);
  208. writer.WriteStartElement(root);
  209. var baseItem = item as BaseItem;
  210. if (baseItem != null)
  211. {
  212. AddCommonNodes(baseItem, writer, LibraryManager, UserManager, UserDataManager, FileSystem, ConfigurationManager);
  213. }
  214. WriteCustomElements(item, writer);
  215. var tagsUsed = GetTagsUsed();
  216. try
  217. {
  218. AddCustomTags(xmlPath, tagsUsed, writer, Logger, FileSystem);
  219. }
  220. catch (FileNotFoundException)
  221. {
  222. }
  223. catch (IOException)
  224. {
  225. }
  226. catch (XmlException ex)
  227. {
  228. Logger.ErrorException("Error reading existng xml", ex);
  229. }
  230. writer.WriteEndElement();
  231. writer.WriteEndDocument();
  232. }
  233. }
  234. protected abstract void WriteCustomElements(IHasMetadata item, XmlWriter writer);
  235. public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss";
  236. /// <summary>
  237. /// Adds the common nodes.
  238. /// </summary>
  239. /// <returns>Task.</returns>
  240. public static void AddCommonNodes(BaseItem item, XmlWriter writer, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataRepo, IFileSystem fileSystem, IServerConfigurationManager config)
  241. {
  242. var writtenProviderIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
  243. if (!string.IsNullOrEmpty(item.OfficialRating))
  244. {
  245. writer.WriteElementString("ContentRating", item.OfficialRating);
  246. }
  247. writer.WriteElementString("Added", item.DateCreated.ToLocalTime().ToString("G"));
  248. writer.WriteElementString("LockData", item.IsLocked.ToString().ToLower());
  249. if (item.LockedFields.Count > 0)
  250. {
  251. writer.WriteElementString("LockedFields", string.Join("|", item.LockedFields.Select(i => i.ToString()).ToArray()));
  252. }
  253. if (!string.IsNullOrEmpty(item.DisplayMediaType))
  254. {
  255. writer.WriteElementString("Type", item.DisplayMediaType);
  256. }
  257. if (item.CriticRating.HasValue)
  258. {
  259. writer.WriteElementString("CriticRating", item.CriticRating.Value.ToString(UsCulture));
  260. }
  261. if (!string.IsNullOrEmpty(item.Overview))
  262. {
  263. writer.WriteElementString("Overview", item.Overview);
  264. }
  265. if (!string.IsNullOrEmpty(item.OriginalTitle))
  266. {
  267. writer.WriteElementString("OriginalTitle", item.OriginalTitle);
  268. }
  269. if (!string.IsNullOrEmpty(item.CustomRating))
  270. {
  271. writer.WriteElementString("CustomRating", item.CustomRating);
  272. }
  273. if (!string.IsNullOrEmpty(item.Name) && !(item is Episode))
  274. {
  275. writer.WriteElementString("LocalTitle", item.Name);
  276. }
  277. if (!string.IsNullOrEmpty(item.ForcedSortName))
  278. {
  279. writer.WriteElementString("SortTitle", item.ForcedSortName);
  280. }
  281. if (item.PremiereDate.HasValue)
  282. {
  283. if (item is Person)
  284. {
  285. writer.WriteElementString("BirthDate", item.PremiereDate.Value.ToLocalTime().ToString("yyyy-MM-dd"));
  286. }
  287. else if (!(item is Episode))
  288. {
  289. writer.WriteElementString("PremiereDate", item.PremiereDate.Value.ToLocalTime().ToString("yyyy-MM-dd"));
  290. }
  291. }
  292. if (item.EndDate.HasValue)
  293. {
  294. if (item is Person)
  295. {
  296. writer.WriteElementString("DeathDate", item.EndDate.Value.ToLocalTime().ToString("yyyy-MM-dd"));
  297. }
  298. else if (!(item is Episode))
  299. {
  300. writer.WriteElementString("EndDate", item.EndDate.Value.ToLocalTime().ToString("yyyy-MM-dd"));
  301. }
  302. }
  303. var hasTrailers = item as IHasTrailers;
  304. if (hasTrailers != null)
  305. {
  306. if (hasTrailers.RemoteTrailers.Count > 0)
  307. {
  308. writer.WriteStartElement("Trailers");
  309. foreach (var trailer in hasTrailers.RemoteTrailers)
  310. {
  311. writer.WriteElementString("Trailer", trailer.Url);
  312. }
  313. writer.WriteEndElement();
  314. }
  315. }
  316. if (item.ProductionLocations.Count > 0)
  317. {
  318. writer.WriteStartElement("Countries");
  319. foreach (var name in item.ProductionLocations)
  320. {
  321. writer.WriteElementString("Country", name);
  322. }
  323. writer.WriteEndElement();
  324. }
  325. var hasDisplayOrder = item as IHasDisplayOrder;
  326. if (hasDisplayOrder != null && !string.IsNullOrEmpty(hasDisplayOrder.DisplayOrder))
  327. {
  328. writer.WriteElementString("DisplayOrder", hasDisplayOrder.DisplayOrder);
  329. }
  330. var hasAwards = item as IHasAwards;
  331. if (hasAwards != null && !string.IsNullOrEmpty(hasAwards.AwardSummary))
  332. {
  333. writer.WriteElementString("AwardSummary", hasAwards.AwardSummary);
  334. }
  335. if (item.CommunityRating.HasValue)
  336. {
  337. writer.WriteElementString("Rating", item.CommunityRating.Value.ToString(UsCulture));
  338. }
  339. if (item.VoteCount.HasValue)
  340. {
  341. writer.WriteElementString("VoteCount", item.VoteCount.Value.ToString(UsCulture));
  342. }
  343. if (item.ProductionYear.HasValue && !(item is Person))
  344. {
  345. writer.WriteElementString("ProductionYear", item.ProductionYear.Value.ToString(UsCulture));
  346. }
  347. if (!string.IsNullOrEmpty(item.HomePageUrl))
  348. {
  349. writer.WriteElementString("Website", item.HomePageUrl);
  350. }
  351. var hasAspectRatio = item as IHasAspectRatio;
  352. if (hasAspectRatio != null)
  353. {
  354. if (!string.IsNullOrEmpty(hasAspectRatio.AspectRatio))
  355. {
  356. writer.WriteElementString("AspectRatio", hasAspectRatio.AspectRatio);
  357. }
  358. }
  359. if (!string.IsNullOrEmpty(item.PreferredMetadataLanguage))
  360. {
  361. writer.WriteElementString("Language", item.PreferredMetadataLanguage);
  362. }
  363. if (!string.IsNullOrEmpty(item.PreferredMetadataCountryCode))
  364. {
  365. writer.WriteElementString("CountryCode", item.PreferredMetadataCountryCode);
  366. }
  367. // Use original runtime here, actual file runtime later in MediaInfo
  368. var runTimeTicks = item.RunTimeTicks;
  369. if (runTimeTicks.HasValue)
  370. {
  371. var timespan = TimeSpan.FromTicks(runTimeTicks.Value);
  372. writer.WriteElementString("RunningTime", Convert.ToInt32(timespan.TotalMinutes).ToString(UsCulture));
  373. }
  374. if (item.ProviderIds != null)
  375. {
  376. foreach (var providerKey in item.ProviderIds.Keys)
  377. {
  378. var providerId = item.ProviderIds[providerKey];
  379. if (!string.IsNullOrEmpty(providerId))
  380. {
  381. writer.WriteElementString(providerKey + "Id", providerId);
  382. }
  383. }
  384. }
  385. if (!string.IsNullOrWhiteSpace(item.Tagline))
  386. {
  387. writer.WriteStartElement("Taglines");
  388. writer.WriteElementString("Tagline", item.Tagline);
  389. writer.WriteEndElement();
  390. }
  391. if (item.Genres.Count > 0)
  392. {
  393. writer.WriteStartElement("Genres");
  394. foreach (var genre in item.Genres)
  395. {
  396. writer.WriteElementString("Genre", genre);
  397. }
  398. writer.WriteEndElement();
  399. }
  400. if (item.Studios.Count > 0)
  401. {
  402. writer.WriteStartElement("Studios");
  403. foreach (var studio in item.Studios)
  404. {
  405. writer.WriteElementString("Studio", studio);
  406. }
  407. writer.WriteEndElement();
  408. }
  409. if (item.Tags.Count > 0)
  410. {
  411. writer.WriteStartElement("Tags");
  412. foreach (var tag in item.Tags)
  413. {
  414. writer.WriteElementString("Tag", tag);
  415. }
  416. writer.WriteEndElement();
  417. }
  418. if (item.Keywords.Count > 0)
  419. {
  420. writer.WriteStartElement("PlotKeywords");
  421. foreach (var tag in item.Keywords)
  422. {
  423. writer.WriteElementString("PlotKeyword", tag);
  424. }
  425. writer.WriteEndElement();
  426. }
  427. var people = libraryManager.GetPeople(item);
  428. if (people.Count > 0)
  429. {
  430. writer.WriteStartElement("Persons");
  431. foreach (var person in people)
  432. {
  433. writer.WriteStartElement("Person");
  434. writer.WriteElementString("Name", person.Name);
  435. writer.WriteElementString("Type", person.Type);
  436. writer.WriteElementString("Role", person.Role);
  437. if (person.SortOrder.HasValue)
  438. {
  439. writer.WriteElementString("SortOrder", person.SortOrder.Value.ToString(UsCulture));
  440. }
  441. writer.WriteEndElement();
  442. }
  443. writer.WriteEndElement();
  444. }
  445. var boxset = item as BoxSet;
  446. if (boxset != null)
  447. {
  448. AddLinkedChildren(boxset, writer, "CollectionItems", "CollectionItem");
  449. }
  450. var playlist = item as Playlist;
  451. if (playlist != null)
  452. {
  453. AddLinkedChildren(playlist, writer, "PlaylistItems", "PlaylistItem");
  454. }
  455. var hasShares = item as IHasShares;
  456. if (hasShares != null)
  457. {
  458. AddShares(hasShares, writer);
  459. }
  460. AddMediaInfo(item, writer);
  461. }
  462. public static void AddShares(IHasShares item, XmlWriter writer)
  463. {
  464. writer.WriteStartElement("Shares");
  465. foreach (var share in item.Shares)
  466. {
  467. writer.WriteStartElement("Share");
  468. writer.WriteElementString("UserId", share.UserId);
  469. writer.WriteElementString("CanEdit", share.CanEdit.ToString().ToLower());
  470. writer.WriteEndElement();
  471. }
  472. writer.WriteEndElement();
  473. }
  474. /// <summary>
  475. /// Appends the media info.
  476. /// </summary>
  477. /// <typeparam name="T"></typeparam>
  478. public static void AddMediaInfo<T>(T item, XmlWriter writer)
  479. where T : BaseItem
  480. {
  481. var video = item as Video;
  482. if (video != null)
  483. {
  484. if (video.Video3DFormat.HasValue)
  485. {
  486. switch (video.Video3DFormat.Value)
  487. {
  488. case Video3DFormat.FullSideBySide:
  489. writer.WriteElementString("Format3D", "FSBS");
  490. break;
  491. case Video3DFormat.FullTopAndBottom:
  492. writer.WriteElementString("Format3D", "FTAB");
  493. break;
  494. case Video3DFormat.HalfSideBySide:
  495. writer.WriteElementString("Format3D", "HSBS");
  496. break;
  497. case Video3DFormat.HalfTopAndBottom:
  498. writer.WriteElementString("Format3D", "HTAB");
  499. break;
  500. case Video3DFormat.MVC:
  501. writer.WriteElementString("Format3D", "MVC");
  502. break;
  503. }
  504. }
  505. }
  506. }
  507. public static void AddLinkedChildren(Folder item, XmlWriter writer, string pluralNodeName, string singularNodeName)
  508. {
  509. var items = item.LinkedChildren
  510. .Where(i => i.Type == LinkedChildType.Manual)
  511. .ToList();
  512. if (items.Count == 0)
  513. {
  514. return;
  515. }
  516. writer.WriteStartElement(pluralNodeName);
  517. foreach (var link in items)
  518. {
  519. if (!string.IsNullOrWhiteSpace(link.Path))
  520. {
  521. writer.WriteStartElement(singularNodeName);
  522. writer.WriteElementString("Path", link.Path);
  523. writer.WriteEndElement();
  524. }
  525. }
  526. writer.WriteEndElement();
  527. }
  528. private static bool IsPersonType(PersonInfo person, string type)
  529. {
  530. return string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase) || string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase);
  531. }
  532. private void AddCustomTags(string path, List<string> xmlTagsUsed, XmlWriter writer, ILogger logger, IFileSystem fileSystem)
  533. {
  534. var settings = XmlReaderSettingsFactory.Create(false);
  535. settings.CheckCharacters = false;
  536. settings.IgnoreProcessingInstructions = true;
  537. settings.IgnoreComments = true;
  538. using (var fileStream = fileSystem.OpenRead(path))
  539. {
  540. using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
  541. {
  542. // Use XmlReader for best performance
  543. using (var reader = XmlReader.Create(streamReader, settings))
  544. {
  545. try
  546. {
  547. reader.MoveToContent();
  548. }
  549. catch (Exception ex)
  550. {
  551. logger.ErrorException("Error reading existing xml tags from {0}.", ex, path);
  552. return;
  553. }
  554. reader.Read();
  555. // Loop through each element
  556. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  557. {
  558. if (reader.NodeType == XmlNodeType.Element)
  559. {
  560. var name = reader.Name;
  561. if (!CommonTags.ContainsKey(name) && !xmlTagsUsed.Contains(name, StringComparer.OrdinalIgnoreCase))
  562. {
  563. writer.WriteNode(reader, false);
  564. }
  565. else
  566. {
  567. reader.Skip();
  568. }
  569. }
  570. else
  571. {
  572. reader.Read();
  573. }
  574. }
  575. }
  576. }
  577. }
  578. }
  579. }
  580. }