BaseXmlSaver.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. using System;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using System.Xml;
  9. using MediaBrowser.Controller.Configuration;
  10. using MediaBrowser.Controller.Entities;
  11. using MediaBrowser.Controller.Entities.Movies;
  12. using MediaBrowser.Controller.Entities.TV;
  13. using MediaBrowser.Controller.Library;
  14. using MediaBrowser.Controller.Playlists;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.IO;
  17. using Microsoft.Extensions.Logging;
  18. namespace MediaBrowser.LocalMetadata.Savers
  19. {
  20. /// <inheritdoc />
  21. public abstract class BaseXmlSaver : IMetadataFileSaver
  22. {
  23. /// <summary>
  24. /// Initializes a new instance of the <see cref="BaseXmlSaver"/> class.
  25. /// </summary>
  26. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  27. /// <param name="configurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
  28. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  29. /// <param name="logger">Instance of the <see cref="ILogger{BaseXmlSaver}"/> interface.</param>
  30. protected BaseXmlSaver(IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, ILogger<BaseXmlSaver> logger)
  31. {
  32. FileSystem = fileSystem;
  33. ConfigurationManager = configurationManager;
  34. LibraryManager = libraryManager;
  35. Logger = logger;
  36. }
  37. /// <summary>
  38. /// Gets the file system.
  39. /// </summary>
  40. protected IFileSystem FileSystem { get; private set; }
  41. /// <summary>
  42. /// Gets the configuration manager.
  43. /// </summary>
  44. protected IServerConfigurationManager ConfigurationManager { get; private set; }
  45. /// <summary>
  46. /// Gets the library manager.
  47. /// </summary>
  48. protected ILibraryManager LibraryManager { get; private set; }
  49. /// <summary>
  50. /// Gets the logger.
  51. /// </summary>
  52. protected ILogger<BaseXmlSaver> Logger { get; private set; }
  53. /// <inheritdoc />
  54. public string Name => XmlProviderUtils.Name;
  55. /// <inheritdoc />
  56. public string GetSavePath(BaseItem item)
  57. {
  58. return GetLocalSavePath(item);
  59. }
  60. /// <summary>
  61. /// Gets the save path.
  62. /// </summary>
  63. /// <param name="item">The item.</param>
  64. /// <returns>System.String.</returns>
  65. protected abstract string GetLocalSavePath(BaseItem item);
  66. /// <summary>
  67. /// Gets the name of the root element.
  68. /// </summary>
  69. /// <param name="item">The item.</param>
  70. /// <returns>System.String.</returns>
  71. protected virtual string GetRootElementName(BaseItem item)
  72. => "Item";
  73. /// <summary>
  74. /// Determines whether [is enabled for] [the specified item].
  75. /// </summary>
  76. /// <param name="item">The item.</param>
  77. /// <param name="updateType">Type of the update.</param>
  78. /// <returns><c>true</c> if [is enabled for] [the specified item]; otherwise, <c>false</c>.</returns>
  79. public abstract bool IsEnabledFor(BaseItem item, ItemUpdateType updateType);
  80. /// <inheritdoc />
  81. public async Task SaveAsync(BaseItem item, CancellationToken cancellationToken)
  82. {
  83. var path = GetSavePath(item);
  84. var directory = Path.GetDirectoryName(path) ?? throw new InvalidDataException($"Provided path ({path}) is not valid.");
  85. Directory.CreateDirectory(directory);
  86. // On Windows, savint the file will fail if the file is hidden or readonly
  87. FileSystem.SetAttributes(path, false, false);
  88. var fileStreamOptions = new FileStreamOptions()
  89. {
  90. Mode = FileMode.Create,
  91. Access = FileAccess.Write,
  92. Share = FileShare.None
  93. };
  94. var filestream = new FileStream(path, fileStreamOptions);
  95. await using (filestream.ConfigureAwait(false))
  96. {
  97. var settings = new XmlWriterSettings
  98. {
  99. Indent = true,
  100. Encoding = Encoding.UTF8,
  101. Async = true
  102. };
  103. var writer = XmlWriter.Create(filestream, settings);
  104. await using (writer.ConfigureAwait(false))
  105. {
  106. var root = GetRootElementName(item);
  107. await writer.WriteStartDocumentAsync(true).ConfigureAwait(false);
  108. await writer.WriteStartElementAsync(null, root, null).ConfigureAwait(false);
  109. var baseItem = item;
  110. if (baseItem != null)
  111. {
  112. await AddCommonNodesAsync(baseItem, writer).ConfigureAwait(false);
  113. }
  114. await WriteCustomElementsAsync(item, writer).ConfigureAwait(false);
  115. await writer.WriteEndElementAsync().ConfigureAwait(false);
  116. await writer.WriteEndDocumentAsync().ConfigureAwait(false);
  117. }
  118. }
  119. if (ConfigurationManager.Configuration.SaveMetadataHidden)
  120. {
  121. SetHidden(path, true);
  122. }
  123. }
  124. private void SetHidden(string path, bool hidden)
  125. {
  126. try
  127. {
  128. FileSystem.SetHidden(path, hidden);
  129. }
  130. catch (Exception ex)
  131. {
  132. Logger.LogError(ex, "Error setting hidden attribute on {Path}", path);
  133. }
  134. }
  135. /// <summary>
  136. /// Write custom elements.
  137. /// </summary>
  138. /// <param name="item">The item.</param>
  139. /// <param name="writer">The xml writer.</param>
  140. /// <returns>The task object representing the asynchronous operation.</returns>
  141. protected abstract Task WriteCustomElementsAsync(BaseItem item, XmlWriter writer);
  142. /// <summary>
  143. /// Adds the common nodes.
  144. /// </summary>
  145. /// <param name="item">The item.</param>
  146. /// <param name="writer">The xml writer.</param>
  147. /// <returns>The task object representing the asynchronous operation.</returns>
  148. private async Task AddCommonNodesAsync(BaseItem item, XmlWriter writer)
  149. {
  150. if (!string.IsNullOrEmpty(item.OfficialRating))
  151. {
  152. await writer.WriteElementStringAsync(null, "ContentRating", null, item.OfficialRating).ConfigureAwait(false);
  153. }
  154. await writer.WriteElementStringAsync(null, "Added", null, item.DateCreated.ToLocalTime().ToString("G", CultureInfo.InvariantCulture)).ConfigureAwait(false);
  155. await writer.WriteElementStringAsync(null, "LockData", null, item.IsLocked.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()).ConfigureAwait(false);
  156. if (item.LockedFields.Length > 0)
  157. {
  158. await writer.WriteElementStringAsync(null, "LockedFields", null, string.Join('|', item.LockedFields)).ConfigureAwait(false);
  159. }
  160. if (item.CriticRating.HasValue)
  161. {
  162. await writer.WriteElementStringAsync(null, "CriticRating", null, item.CriticRating.Value.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
  163. }
  164. if (!string.IsNullOrEmpty(item.Overview))
  165. {
  166. await writer.WriteElementStringAsync(null, "Overview", null, item.Overview).ConfigureAwait(false);
  167. }
  168. if (!string.IsNullOrEmpty(item.OriginalTitle))
  169. {
  170. await writer.WriteElementStringAsync(null, "OriginalTitle", null, item.OriginalTitle).ConfigureAwait(false);
  171. }
  172. if (!string.IsNullOrEmpty(item.CustomRating))
  173. {
  174. await writer.WriteElementStringAsync(null, "CustomRating", null, item.CustomRating).ConfigureAwait(false);
  175. }
  176. if (!string.IsNullOrEmpty(item.Name) && item is not Episode)
  177. {
  178. await writer.WriteElementStringAsync(null, "LocalTitle", null, item.Name).ConfigureAwait(false);
  179. }
  180. var forcedSortName = item.ForcedSortName;
  181. if (!string.IsNullOrEmpty(forcedSortName))
  182. {
  183. await writer.WriteElementStringAsync(null, "SortTitle", null, forcedSortName).ConfigureAwait(false);
  184. }
  185. if (item.PremiereDate.HasValue)
  186. {
  187. if (item is Person)
  188. {
  189. await writer.WriteElementStringAsync(null, "BirthDate", null, item.PremiereDate.Value.ToLocalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)).ConfigureAwait(false);
  190. }
  191. else if (item is not Episode)
  192. {
  193. await writer.WriteElementStringAsync(null, "PremiereDate", null, item.PremiereDate.Value.ToLocalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)).ConfigureAwait(false);
  194. }
  195. }
  196. if (item.EndDate.HasValue)
  197. {
  198. if (item is Person)
  199. {
  200. await writer.WriteElementStringAsync(null, "DeathDate", null, item.EndDate.Value.ToLocalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)).ConfigureAwait(false);
  201. }
  202. else if (item is not Episode)
  203. {
  204. await writer.WriteElementStringAsync(null, "EndDate", null, item.EndDate.Value.ToLocalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)).ConfigureAwait(false);
  205. }
  206. }
  207. if (item.RemoteTrailers.Count > 0)
  208. {
  209. await writer.WriteStartElementAsync(null, "Trailers", null).ConfigureAwait(false);
  210. foreach (var trailer in item.RemoteTrailers)
  211. {
  212. await writer.WriteElementStringAsync(null, "Trailer", null, trailer.Url).ConfigureAwait(false);
  213. }
  214. await writer.WriteEndElementAsync().ConfigureAwait(false);
  215. }
  216. if (item.ProductionLocations.Length > 0)
  217. {
  218. await writer.WriteStartElementAsync(null, "Countries", null).ConfigureAwait(false);
  219. foreach (var name in item.ProductionLocations)
  220. {
  221. await writer.WriteElementStringAsync(null, "Country", null, name).ConfigureAwait(false);
  222. }
  223. await writer.WriteEndElementAsync().ConfigureAwait(false);
  224. }
  225. if (item is IHasDisplayOrder hasDisplayOrder && !string.IsNullOrEmpty(hasDisplayOrder.DisplayOrder))
  226. {
  227. await writer.WriteElementStringAsync(null, "DisplayOrder", null, hasDisplayOrder.DisplayOrder).ConfigureAwait(false);
  228. }
  229. if (item.CommunityRating.HasValue)
  230. {
  231. await writer.WriteElementStringAsync(null, "Rating", null, item.CommunityRating.Value.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
  232. }
  233. if (item.ProductionYear.HasValue && item is not Person)
  234. {
  235. await writer.WriteElementStringAsync(null, "ProductionYear", null, item.ProductionYear.Value.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
  236. }
  237. if (item is IHasAspectRatio hasAspectRatio)
  238. {
  239. if (!string.IsNullOrEmpty(hasAspectRatio.AspectRatio))
  240. {
  241. await writer.WriteElementStringAsync(null, "AspectRatio", null, hasAspectRatio.AspectRatio).ConfigureAwait(false);
  242. }
  243. }
  244. if (!string.IsNullOrEmpty(item.PreferredMetadataLanguage))
  245. {
  246. await writer.WriteElementStringAsync(null, "Language", null, item.PreferredMetadataLanguage).ConfigureAwait(false);
  247. }
  248. if (!string.IsNullOrEmpty(item.PreferredMetadataCountryCode))
  249. {
  250. await writer.WriteElementStringAsync(null, "CountryCode", null, item.PreferredMetadataCountryCode).ConfigureAwait(false);
  251. }
  252. // Use original runtime here, actual file runtime later in MediaInfo
  253. var runTimeTicks = item.RunTimeTicks;
  254. if (runTimeTicks.HasValue)
  255. {
  256. var timespan = TimeSpan.FromTicks(runTimeTicks.Value);
  257. await writer.WriteElementStringAsync(null, "RunningTime", null, Math.Floor(timespan.TotalMinutes).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
  258. }
  259. if (item.ProviderIds != null)
  260. {
  261. foreach (var providerKey in item.ProviderIds.Keys)
  262. {
  263. var providerId = item.ProviderIds[providerKey];
  264. if (!string.IsNullOrEmpty(providerId))
  265. {
  266. await writer.WriteElementStringAsync(null, providerKey + "Id", null, providerId).ConfigureAwait(false);
  267. }
  268. }
  269. }
  270. if (!string.IsNullOrWhiteSpace(item.Tagline))
  271. {
  272. await writer.WriteStartElementAsync(null, "Taglines", null).ConfigureAwait(false);
  273. await writer.WriteElementStringAsync(null, "Tagline", null, item.Tagline).ConfigureAwait(false);
  274. await writer.WriteEndElementAsync().ConfigureAwait(false);
  275. }
  276. if (item.Genres.Length > 0)
  277. {
  278. await writer.WriteStartElementAsync(null, "Genres", null).ConfigureAwait(false);
  279. foreach (var genre in item.Genres)
  280. {
  281. await writer.WriteElementStringAsync(null, "Genre", null, genre).ConfigureAwait(false);
  282. }
  283. await writer.WriteEndElementAsync().ConfigureAwait(false);
  284. }
  285. if (item.Studios.Length > 0)
  286. {
  287. await writer.WriteStartElementAsync(null, "Studios", null).ConfigureAwait(false);
  288. foreach (var studio in item.Studios)
  289. {
  290. await writer.WriteElementStringAsync(null, "Studio", null, studio).ConfigureAwait(false);
  291. }
  292. await writer.WriteEndElementAsync().ConfigureAwait(false);
  293. }
  294. if (item.Tags.Length > 0)
  295. {
  296. await writer.WriteStartElementAsync(null, "Tags", null).ConfigureAwait(false);
  297. foreach (var tag in item.Tags)
  298. {
  299. await writer.WriteElementStringAsync(null, "Tag", null, tag).ConfigureAwait(false);
  300. }
  301. await writer.WriteEndElementAsync().ConfigureAwait(false);
  302. }
  303. var people = LibraryManager.GetPeople(item);
  304. if (people.Count > 0)
  305. {
  306. await writer.WriteStartElementAsync(null, "Persons", null).ConfigureAwait(false);
  307. foreach (var person in people)
  308. {
  309. await writer.WriteStartElementAsync(null, "Person", null).ConfigureAwait(false);
  310. await writer.WriteElementStringAsync(null, "Name", null, person.Name).ConfigureAwait(false);
  311. await writer.WriteElementStringAsync(null, "Type", null, person.Type).ConfigureAwait(false);
  312. await writer.WriteElementStringAsync(null, "Role", null, person.Role).ConfigureAwait(false);
  313. if (person.SortOrder.HasValue)
  314. {
  315. await writer.WriteElementStringAsync(null, "SortOrder", null, person.SortOrder.Value.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
  316. }
  317. await writer.WriteEndElementAsync().ConfigureAwait(false);
  318. }
  319. await writer.WriteEndElementAsync().ConfigureAwait(false);
  320. }
  321. if (item is BoxSet boxset)
  322. {
  323. await AddLinkedChildren(boxset, writer, "CollectionItems", "CollectionItem").ConfigureAwait(false);
  324. }
  325. if (item is Playlist playlist && !Playlist.IsPlaylistFile(playlist.Path))
  326. {
  327. await AddLinkedChildren(playlist, writer, "PlaylistItems", "PlaylistItem").ConfigureAwait(false);
  328. }
  329. if (item is IHasShares hasShares)
  330. {
  331. await AddSharesAsync(hasShares, writer).ConfigureAwait(false);
  332. }
  333. await AddMediaInfo(item, writer).ConfigureAwait(false);
  334. }
  335. /// <summary>
  336. /// Add shares.
  337. /// </summary>
  338. /// <param name="item">The item.</param>
  339. /// <param name="writer">The xml writer.</param>
  340. /// <returns>The task object representing the asynchronous operation.</returns>
  341. private static async Task AddSharesAsync(IHasShares item, XmlWriter writer)
  342. {
  343. await writer.WriteStartElementAsync(null, "Shares", null).ConfigureAwait(false);
  344. foreach (var share in item.Shares)
  345. {
  346. await writer.WriteStartElementAsync(null, "Share", null).ConfigureAwait(false);
  347. await writer.WriteElementStringAsync(null, "UserId", null, share.UserId).ConfigureAwait(false);
  348. await writer.WriteElementStringAsync(
  349. null,
  350. "CanEdit",
  351. null,
  352. share.CanEdit.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()).ConfigureAwait(false);
  353. await writer.WriteEndElementAsync().ConfigureAwait(false);
  354. }
  355. await writer.WriteEndElementAsync().ConfigureAwait(false);
  356. }
  357. /// <summary>
  358. /// Appends the media info.
  359. /// </summary>
  360. /// <param name="item">The item.</param>
  361. /// <param name="writer">The xml writer.</param>
  362. /// <typeparam name="T">Type of item.</typeparam>
  363. /// <returns>The task object representing the asynchronous operation.</returns>
  364. private static Task AddMediaInfo<T>(T item, XmlWriter writer)
  365. where T : BaseItem
  366. {
  367. if (item is Video video && video.Video3DFormat.HasValue)
  368. {
  369. return video.Video3DFormat switch
  370. {
  371. Video3DFormat.FullSideBySide =>
  372. writer.WriteElementStringAsync(null, "Format3D", null, "FSBS"),
  373. Video3DFormat.FullTopAndBottom =>
  374. writer.WriteElementStringAsync(null, "Format3D", null, "FTAB"),
  375. Video3DFormat.HalfSideBySide =>
  376. writer.WriteElementStringAsync(null, "Format3D", null, "HSBS"),
  377. Video3DFormat.HalfTopAndBottom =>
  378. writer.WriteElementStringAsync(null, "Format3D", null, "HTAB"),
  379. Video3DFormat.MVC =>
  380. writer.WriteElementStringAsync(null, "Format3D", null, "MVC"),
  381. _ => Task.CompletedTask
  382. };
  383. }
  384. return Task.CompletedTask;
  385. }
  386. /// <summary>
  387. /// ADd linked children.
  388. /// </summary>
  389. /// <param name="item">The item.</param>
  390. /// <param name="writer">The xml writer.</param>
  391. /// <param name="pluralNodeName">The plural node name.</param>
  392. /// <param name="singularNodeName">The singular node name.</param>
  393. /// <returns>The task object representing the asynchronous operation.</returns>
  394. private static async Task AddLinkedChildren(Folder item, XmlWriter writer, string pluralNodeName, string singularNodeName)
  395. {
  396. var items = item.LinkedChildren
  397. .Where(i => i.Type == LinkedChildType.Manual)
  398. .ToList();
  399. if (items.Count == 0)
  400. {
  401. return;
  402. }
  403. await writer.WriteStartElementAsync(null, pluralNodeName, null).ConfigureAwait(false);
  404. foreach (var link in items)
  405. {
  406. if (!string.IsNullOrWhiteSpace(link.Path) || !string.IsNullOrWhiteSpace(link.LibraryItemId))
  407. {
  408. await writer.WriteStartElementAsync(null, singularNodeName, null).ConfigureAwait(false);
  409. if (!string.IsNullOrWhiteSpace(link.Path))
  410. {
  411. await writer.WriteElementStringAsync(null, "Path", null, link.Path).ConfigureAwait(false);
  412. }
  413. if (!string.IsNullOrWhiteSpace(link.LibraryItemId))
  414. {
  415. await writer.WriteElementStringAsync(null, "ItemId", null, link.LibraryItemId).ConfigureAwait(false);
  416. }
  417. await writer.WriteEndElementAsync().ConfigureAwait(false);
  418. }
  419. }
  420. await writer.WriteEndElementAsync().ConfigureAwait(false);
  421. }
  422. }
  423. }