XmlSaverHelpers.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. using MediaBrowser.Controller.Entities;
  2. using MediaBrowser.Controller.Entities.TV;
  3. using MediaBrowser.Controller.Persistence;
  4. using MediaBrowser.Model.Entities;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Globalization;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Security;
  11. using System.Text;
  12. using System.Xml;
  13. namespace MediaBrowser.Providers.Savers
  14. {
  15. /// <summary>
  16. /// Class XmlHelpers
  17. /// </summary>
  18. public static class XmlSaverHelpers
  19. {
  20. private static readonly Dictionary<string, string> CommonTags = new[] {
  21. "Added",
  22. "AspectRatio",
  23. "BirthDate",
  24. "Budget",
  25. "certification",
  26. "Chapters",
  27. "ContentRating",
  28. "CustomRating",
  29. "CriticRating",
  30. "CriticRatingSummary",
  31. "DeathDate",
  32. "EndDate",
  33. "Genres",
  34. "Genre",
  35. "GamesDbId",
  36. "IMDB_ID",
  37. "IMDB",
  38. "IMDbId",
  39. "Language",
  40. "LocalTitle",
  41. "LockData",
  42. "LockedFields",
  43. "MediaInfo",
  44. "MPAARating",
  45. "MusicbrainzId",
  46. "MusicBrainzReleaseGroupId",
  47. "Overview",
  48. "Persons",
  49. "PremiereDate",
  50. "ProductionYear",
  51. "Rating",
  52. "Revenue",
  53. "RottenTomatoesId",
  54. "RunningTime",
  55. "Runtime",
  56. "SortTitle",
  57. "Studios",
  58. "Tags",
  59. "TagLine",
  60. "Taglines",
  61. "TMDbCollectionId",
  62. "TMDbId",
  63. "Trailer",
  64. "TVcomId",
  65. "TvDbId",
  66. "Type",
  67. "Website",
  68. "Zap2ItId"
  69. }.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
  70. /// <summary>
  71. /// The us culture
  72. /// </summary>
  73. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  74. /// <summary>
  75. /// Saves the specified XML.
  76. /// </summary>
  77. /// <param name="xml">The XML.</param>
  78. /// <param name="path">The path.</param>
  79. /// <param name="xmlTagsUsed">The XML tags used.</param>
  80. public static void Save(StringBuilder xml, string path, List<string> xmlTagsUsed)
  81. {
  82. if (File.Exists(path))
  83. {
  84. var position = xml.ToString().LastIndexOf("</", StringComparison.OrdinalIgnoreCase);
  85. xml.Insert(position, GetCustomTags(path, xmlTagsUsed));
  86. }
  87. var xmlDocument = new XmlDocument();
  88. xmlDocument.LoadXml(xml.ToString());
  89. //Add the new node to the document.
  90. xmlDocument.InsertBefore(xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", "yes"), xmlDocument.DocumentElement);
  91. var parentPath = Path.GetDirectoryName(path);
  92. Directory.CreateDirectory(parentPath);
  93. var wasHidden = false;
  94. var file = new FileInfo(path);
  95. // This will fail if the file is hidden
  96. if (file.Exists)
  97. {
  98. if ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  99. {
  100. file.Attributes &= ~FileAttributes.Hidden;
  101. wasHidden = true;
  102. }
  103. }
  104. using (var filestream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
  105. {
  106. using (var streamWriter = new StreamWriter(filestream, Encoding.UTF8))
  107. {
  108. xmlDocument.Save(streamWriter);
  109. }
  110. }
  111. if (wasHidden)
  112. {
  113. file.Refresh();
  114. // Add back the attribute
  115. file.Attributes |= FileAttributes.Hidden;
  116. }
  117. }
  118. /// <summary>
  119. /// Gets the custom tags.
  120. /// </summary>
  121. /// <param name="path">The path.</param>
  122. /// <param name="xmlTagsUsed">The XML tags used.</param>
  123. /// <returns>System.String.</returns>
  124. private static string GetCustomTags(string path, List<string> xmlTagsUsed)
  125. {
  126. var settings = new XmlReaderSettings
  127. {
  128. CheckCharacters = false,
  129. IgnoreProcessingInstructions = true,
  130. IgnoreComments = true,
  131. ValidationType = ValidationType.None
  132. };
  133. var builder = new StringBuilder();
  134. using (var streamReader = new StreamReader(path, Encoding.UTF8))
  135. {
  136. // Use XmlReader for best performance
  137. using (var reader = XmlReader.Create(streamReader, settings))
  138. {
  139. reader.MoveToContent();
  140. // Loop through each element
  141. while (reader.Read())
  142. {
  143. if (reader.NodeType == XmlNodeType.Element)
  144. {
  145. var name = reader.Name;
  146. if (!CommonTags.ContainsKey(name) && !xmlTagsUsed.Contains(name, StringComparer.OrdinalIgnoreCase))
  147. {
  148. builder.AppendLine(reader.ReadOuterXml());
  149. }
  150. else
  151. {
  152. reader.Skip();
  153. }
  154. }
  155. }
  156. }
  157. }
  158. return builder.ToString();
  159. }
  160. /// <summary>
  161. /// Adds the common nodes.
  162. /// </summary>
  163. /// <param name="item">The item.</param>
  164. /// <param name="builder">The builder.</param>
  165. public static void AddCommonNodes(BaseItem item, StringBuilder builder)
  166. {
  167. if (!string.IsNullOrEmpty(item.OfficialRating))
  168. {
  169. builder.Append("<ContentRating>" + SecurityElement.Escape(item.OfficialRating) + "</ContentRating>");
  170. builder.Append("<MPAARating>" + SecurityElement.Escape(item.OfficialRating) + "</MPAARating>");
  171. builder.Append("<certification>" + SecurityElement.Escape(item.OfficialRating) + "</certification>");
  172. }
  173. builder.Append("<Added>" + SecurityElement.Escape(item.DateCreated.ToLocalTime().ToString("G")) + "</Added>");
  174. builder.Append("<LockData>" + item.DontFetchMeta.ToString().ToLower() + "</LockData>");
  175. if (item.LockedFields.Count > 0)
  176. {
  177. builder.Append("<LockedFields>" + string.Join("|", item.LockedFields.Select(i => i.ToString()).ToArray()) + "</LockedFields>");
  178. }
  179. if (!string.IsNullOrEmpty(item.DisplayMediaType))
  180. {
  181. builder.Append("<Type>" + SecurityElement.Escape(item.DisplayMediaType) + "</Type>");
  182. }
  183. if (item.CriticRating.HasValue)
  184. {
  185. builder.Append("<CriticRating>" + SecurityElement.Escape(item.CriticRating.Value.ToString(UsCulture)) + "</CriticRating>");
  186. }
  187. if (!string.IsNullOrEmpty(item.CriticRatingSummary))
  188. {
  189. builder.Append("<CriticRatingSummary><![CDATA[" + item.CriticRatingSummary + "]]></CriticRatingSummary>");
  190. }
  191. if (!string.IsNullOrEmpty(item.Overview))
  192. {
  193. builder.Append("<Overview><![CDATA[" + item.Overview + "]]></Overview>");
  194. }
  195. if (!string.IsNullOrEmpty(item.CustomRating))
  196. {
  197. builder.Append("<CustomRating>" + SecurityElement.Escape(item.CustomRating) + "</CustomRating>");
  198. }
  199. if (!string.IsNullOrEmpty(item.Name) && !(item is Episode))
  200. {
  201. builder.Append("<LocalTitle>" + SecurityElement.Escape(item.Name) + "</LocalTitle>");
  202. }
  203. if (!string.IsNullOrEmpty(item.ForcedSortName))
  204. {
  205. builder.Append("<SortTitle>" + SecurityElement.Escape(item.ForcedSortName) + "</SortTitle>");
  206. }
  207. if (item.PremiereDate.HasValue)
  208. {
  209. if (item is Person)
  210. {
  211. builder.Append("<BirthDate>" + SecurityElement.Escape(item.PremiereDate.Value.ToString("yyyy-MM-dd")) + "</BirthDate>");
  212. }
  213. else if (!(item is Episode))
  214. {
  215. builder.Append("<PremiereDate>" + SecurityElement.Escape(item.PremiereDate.Value.ToString("yyyy-MM-dd")) + "</PremiereDate>");
  216. }
  217. }
  218. if (item.EndDate.HasValue)
  219. {
  220. if (item is Person)
  221. {
  222. builder.Append("<DeathDate>" + SecurityElement.Escape(item.EndDate.Value.ToString("yyyy-MM-dd")) + "</DeathDate>");
  223. }
  224. else if (!(item is Episode))
  225. {
  226. builder.Append("<EndDate>" + SecurityElement.Escape(item.EndDate.Value.ToString("yyyy-MM-dd")) + "</EndDate>");
  227. }
  228. }
  229. if (item.RemoteTrailers.Count > 0)
  230. {
  231. builder.Append("<Trailer>" + SecurityElement.Escape(item.RemoteTrailers[0].Url) + "</Trailer>");
  232. }
  233. if (item.Budget.HasValue)
  234. {
  235. builder.Append("<Budget>" + SecurityElement.Escape(item.Budget.Value.ToString(UsCulture)) + "</Budget>");
  236. }
  237. if (item.Revenue.HasValue)
  238. {
  239. builder.Append("<Revenue>" + SecurityElement.Escape(item.Revenue.Value.ToString(UsCulture)) + "</Revenue>");
  240. }
  241. if (item.CommunityRating.HasValue)
  242. {
  243. builder.Append("<Rating>" + SecurityElement.Escape(item.CommunityRating.Value.ToString(UsCulture)) + "</Rating>");
  244. }
  245. if (item.ProductionYear.HasValue && !(item is Person))
  246. {
  247. builder.Append("<ProductionYear>" + SecurityElement.Escape(item.ProductionYear.Value.ToString(UsCulture)) + "</ProductionYear>");
  248. }
  249. if (!string.IsNullOrEmpty(item.HomePageUrl))
  250. {
  251. builder.Append("<Website>" + SecurityElement.Escape(item.HomePageUrl) + "</Website>");
  252. }
  253. if (!string.IsNullOrEmpty(item.AspectRatio))
  254. {
  255. builder.Append("<AspectRatio>" + SecurityElement.Escape(item.AspectRatio) + "</AspectRatio>");
  256. }
  257. if (!string.IsNullOrEmpty(item.Language))
  258. {
  259. builder.Append("<Language>" + SecurityElement.Escape(item.Language) + "</Language>");
  260. }
  261. // Use original runtime here, actual file runtime later in MediaInfo
  262. var runTimeTicks = item.OriginalRunTimeTicks ?? item.RunTimeTicks;
  263. if (runTimeTicks.HasValue)
  264. {
  265. var timespan = TimeSpan.FromTicks(runTimeTicks.Value);
  266. builder.Append("<RunningTime>" + Convert.ToInt32(timespan.TotalMinutes).ToString(UsCulture) + "</RunningTime>");
  267. builder.Append("<Runtime>" + Convert.ToInt32(timespan.TotalMinutes).ToString(UsCulture) + "</Runtime>");
  268. }
  269. var imdb = item.GetProviderId(MetadataProviders.Imdb);
  270. if (!string.IsNullOrEmpty(imdb))
  271. {
  272. builder.Append("<IMDB_ID>" + SecurityElement.Escape(imdb) + "</IMDB_ID>");
  273. builder.Append("<IMDB>" + SecurityElement.Escape(imdb) + "</IMDB>");
  274. builder.Append("<IMDbId>" + SecurityElement.Escape(imdb) + "</IMDbId>");
  275. }
  276. var tmdb = item.GetProviderId(MetadataProviders.Tmdb);
  277. if (!string.IsNullOrEmpty(tmdb))
  278. {
  279. builder.Append("<TMDbId>" + SecurityElement.Escape(tmdb) + "</TMDbId>");
  280. }
  281. if (!(item is Series))
  282. {
  283. var tvdb = item.GetProviderId(MetadataProviders.Tvdb);
  284. if (!string.IsNullOrEmpty(tvdb))
  285. {
  286. builder.Append("<TvDbId>" + SecurityElement.Escape(tvdb) + "</TvDbId>");
  287. }
  288. }
  289. var tvcom = item.GetProviderId(MetadataProviders.Tvcom);
  290. if (!string.IsNullOrEmpty(tvcom))
  291. {
  292. builder.Append("<TVcomId>" + SecurityElement.Escape(tvcom) + "</TVcomId>");
  293. }
  294. var rt = item.GetProviderId(MetadataProviders.RottenTomatoes);
  295. if (!string.IsNullOrEmpty(rt))
  296. {
  297. builder.Append("<RottenTomatoesId>" + SecurityElement.Escape(rt) + "</RottenTomatoesId>");
  298. }
  299. var zap2It = item.GetProviderId(MetadataProviders.Zap2It);
  300. if (!string.IsNullOrEmpty(zap2It))
  301. {
  302. builder.Append("<Zap2ItId>" + SecurityElement.Escape(zap2It) + "</Zap2ItId>");
  303. }
  304. var mbz = item.GetProviderId(MetadataProviders.Musicbrainz);
  305. if (!string.IsNullOrEmpty(mbz))
  306. {
  307. builder.Append("<MusicbrainzId>" + SecurityElement.Escape(mbz) + "</MusicbrainzId>");
  308. }
  309. mbz = item.GetProviderId(MetadataProviders.MusicBrainzReleaseGroup);
  310. if (!string.IsNullOrEmpty(mbz))
  311. {
  312. builder.Append("<MusicBrainzReleaseGroupId>" + SecurityElement.Escape(mbz) + "</MusicBrainzReleaseGroupId>");
  313. }
  314. var gamesdb = item.GetProviderId(MetadataProviders.Gamesdb);
  315. if (!string.IsNullOrEmpty(gamesdb))
  316. {
  317. builder.Append("<GamesDbId>" + SecurityElement.Escape(gamesdb) + "</GamesDbId>");
  318. }
  319. var tmdbCollection = item.GetProviderId(MetadataProviders.TmdbCollection);
  320. if (!string.IsNullOrEmpty(tmdbCollection))
  321. {
  322. builder.Append("<TMDbCollectionId>" + SecurityElement.Escape(tmdbCollection) + "</TMDbCollectionId>");
  323. }
  324. if (item.Taglines.Count > 0)
  325. {
  326. builder.Append("<TagLine>" + SecurityElement.Escape(item.Taglines[0]) + "</TagLine>");
  327. builder.Append("<Taglines>");
  328. foreach (var tagline in item.Taglines)
  329. {
  330. builder.Append("<Tagline>" + SecurityElement.Escape(tagline) + "</Tagline>");
  331. }
  332. builder.Append("</Taglines>");
  333. }
  334. if (item.Genres.Count > 0)
  335. {
  336. builder.Append("<Genres>");
  337. foreach (var genre in item.Genres)
  338. {
  339. builder.Append("<Genre>" + SecurityElement.Escape(genre) + "</Genre>");
  340. }
  341. builder.Append("</Genres>");
  342. builder.Append("<Genre>" + SecurityElement.Escape(string.Join("|", item.Genres.ToArray())) + "</Genre>");
  343. }
  344. if (item.Studios.Count > 0)
  345. {
  346. builder.Append("<Studios>");
  347. foreach (var studio in item.Studios)
  348. {
  349. builder.Append("<Studio>" + SecurityElement.Escape(studio) + "</Studio>");
  350. }
  351. builder.Append("</Studios>");
  352. }
  353. if (item.Tags.Count > 0)
  354. {
  355. builder.Append("<Tags>");
  356. foreach (var tag in item.Tags)
  357. {
  358. builder.Append("<Tag>" + SecurityElement.Escape(tag) + "</Tag>");
  359. }
  360. builder.Append("</Tags>");
  361. }
  362. if (item.People.Count > 0)
  363. {
  364. builder.Append("<Persons>");
  365. foreach (var person in item.People)
  366. {
  367. builder.Append("<Person>");
  368. builder.Append("<Name>" + SecurityElement.Escape(person.Name) + "</Name>");
  369. builder.Append("<Type>" + SecurityElement.Escape(person.Type) + "</Type>");
  370. builder.Append("<Role>" + SecurityElement.Escape(person.Role) + "</Role>");
  371. builder.Append("</Person>");
  372. }
  373. builder.Append("</Persons>");
  374. }
  375. }
  376. public static void AddChapters(Video item, StringBuilder builder, IItemRepository repository)
  377. {
  378. var chapters = repository.GetChapters(item.Id);
  379. builder.Append("<Chapters>");
  380. foreach (var chapter in chapters)
  381. {
  382. builder.Append("<Chapter>");
  383. builder.Append("<Name>" + SecurityElement.Escape(chapter.Name) + "</Name>");
  384. var time = TimeSpan.FromTicks(chapter.StartPositionTicks);
  385. var ms = Convert.ToInt64(time.TotalMilliseconds);
  386. builder.Append("<StartPositionMs>" + SecurityElement.Escape(ms.ToString(UsCulture)) + "</StartPositionMs>");
  387. builder.Append("</Chapter>");
  388. }
  389. builder.Append("</Chapters>");
  390. }
  391. /// <summary>
  392. /// Appends the media info.
  393. /// </summary>
  394. /// <typeparam name="T"></typeparam>
  395. /// <param name="item">The item.</param>
  396. /// <param name="builder">The builder.</param>
  397. public static void AddMediaInfo<T>(T item, StringBuilder builder, IItemRepository itemRepository)
  398. where T : BaseItem, IHasMediaStreams
  399. {
  400. var video = item as Video;
  401. builder.Append("<MediaInfo>");
  402. foreach (var stream in item.MediaStreams)
  403. {
  404. builder.Append("<" + stream.Type + ">");
  405. if (!string.IsNullOrEmpty(stream.Codec))
  406. {
  407. builder.Append("<Codec>" + SecurityElement.Escape(stream.Codec) + "</Codec>");
  408. builder.Append("<FFCodec>" + SecurityElement.Escape(stream.Codec) + "</FFCodec>");
  409. }
  410. if (stream.BitRate.HasValue)
  411. {
  412. builder.Append("<BitRate>" + stream.BitRate.Value.ToString(UsCulture) + "</BitRate>");
  413. }
  414. if (stream.Width.HasValue)
  415. {
  416. builder.Append("<Width>" + stream.Width.Value.ToString(UsCulture) + "</Width>");
  417. }
  418. if (stream.Height.HasValue)
  419. {
  420. builder.Append("<Height>" + stream.Height.Value.ToString(UsCulture) + "</Height>");
  421. }
  422. if (!string.IsNullOrEmpty(stream.AspectRatio))
  423. {
  424. builder.Append("<AspectRatio>" + SecurityElement.Escape(stream.AspectRatio) + "</AspectRatio>");
  425. }
  426. var framerate = stream.AverageFrameRate ?? stream.RealFrameRate;
  427. if (framerate.HasValue)
  428. {
  429. builder.Append("<FrameRate>" + framerate.Value.ToString(UsCulture) + "</FrameRate>");
  430. }
  431. if (!string.IsNullOrEmpty(stream.Language))
  432. {
  433. builder.Append("<Language>" + SecurityElement.Escape(stream.Language) + "</Language>");
  434. }
  435. if (!string.IsNullOrEmpty(stream.ScanType))
  436. {
  437. builder.Append("<ScanType>" + SecurityElement.Escape(stream.ScanType) + "</ScanType>");
  438. }
  439. if (stream.Channels.HasValue)
  440. {
  441. builder.Append("<Channels>" + stream.Channels.Value.ToString(UsCulture) + "</Channels>");
  442. }
  443. if (stream.SampleRate.HasValue)
  444. {
  445. builder.Append("<SamplingRate>" + stream.SampleRate.Value.ToString(UsCulture) + "</SamplingRate>");
  446. }
  447. builder.Append("<Default>" + SecurityElement.Escape(stream.IsDefault.ToString()) + "</Default>");
  448. builder.Append("<Forced>" + SecurityElement.Escape(stream.IsForced.ToString()) + "</Forced>");
  449. if (stream.Type == MediaStreamType.Video)
  450. {
  451. if (item.RunTimeTicks.HasValue)
  452. {
  453. var timespan = TimeSpan.FromTicks(item.RunTimeTicks.Value);
  454. builder.Append("<Duration>" + Convert.ToInt32(timespan.TotalMinutes).ToString(UsCulture) + "</Duration>");
  455. builder.Append("<DurationSeconds>" + Convert.ToInt32(timespan.TotalSeconds).ToString(UsCulture) + "</DurationSeconds>");
  456. }
  457. if (video != null && video.Video3DFormat.HasValue)
  458. {
  459. switch (video.Video3DFormat.Value)
  460. {
  461. case Video3DFormat.FullSideBySide:
  462. builder.Append("<Format3D>FSBS</Format3D>");
  463. break;
  464. case Video3DFormat.FullTopAndBottom:
  465. builder.Append("<Format3D>FTAB</Format3D>");
  466. break;
  467. case Video3DFormat.HalfSideBySide:
  468. builder.Append("<Format3D>HSBS</Format3D>");
  469. break;
  470. case Video3DFormat.HalfTopAndBottom:
  471. builder.Append("<Format3D>HTAB</Format3D>");
  472. break;
  473. }
  474. }
  475. }
  476. builder.Append("</" + stream.Type + ">");
  477. }
  478. builder.Append("</MediaInfo>");
  479. if (video != null)
  480. {
  481. //AddChapters(video, builder, itemRepository);
  482. }
  483. }
  484. }
  485. }