BaseXmlSaver.cs 21 KB

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