BaseItem.cs 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.IO;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.Localization;
  6. using MediaBrowser.Controller.Persistence;
  7. using MediaBrowser.Controller.Providers;
  8. using MediaBrowser.Controller.Resolvers;
  9. using MediaBrowser.Model.Entities;
  10. using MediaBrowser.Model.Logging;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Runtime.Serialization;
  16. using System.Text;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Controller.Entities
  20. {
  21. /// <summary>
  22. /// Class BaseItem
  23. /// </summary>
  24. public abstract class BaseItem : IHasProviderIds
  25. {
  26. protected BaseItem()
  27. {
  28. Genres = new List<string>();
  29. TrailerUrls = new List<string>();
  30. Studios = new List<string>();
  31. People = new List<PersonInfo>();
  32. CriticReviews = new List<ItemReview>();
  33. Taglines = new List<string>();
  34. }
  35. /// <summary>
  36. /// The trailer folder name
  37. /// </summary>
  38. public const string TrailerFolderName = "trailers";
  39. public const string ThemeSongsFolderName = "theme-music";
  40. public const string ThemeVideosFolderName = "backdrops";
  41. /// <summary>
  42. /// Gets or sets the name.
  43. /// </summary>
  44. /// <value>The name.</value>
  45. public virtual string Name { get; set; }
  46. /// <summary>
  47. /// Gets or sets the id.
  48. /// </summary>
  49. /// <value>The id.</value>
  50. public virtual Guid Id { get; set; }
  51. /// <summary>
  52. /// Gets or sets the path.
  53. /// </summary>
  54. /// <value>The path.</value>
  55. public virtual string Path { get; set; }
  56. /// <summary>
  57. /// Gets or sets the type of the location.
  58. /// </summary>
  59. /// <value>The type of the location.</value>
  60. public virtual LocationType LocationType
  61. {
  62. get
  63. {
  64. if (string.IsNullOrEmpty(Path))
  65. {
  66. return LocationType.Virtual;
  67. }
  68. return System.IO.Path.IsPathRooted(Path) ? LocationType.FileSystem : LocationType.Remote;
  69. }
  70. }
  71. /// <summary>
  72. /// This is just a helper for convenience
  73. /// </summary>
  74. /// <value>The primary image path.</value>
  75. [IgnoreDataMember]
  76. public string PrimaryImagePath
  77. {
  78. get { return GetImage(ImageType.Primary); }
  79. set { SetImage(ImageType.Primary, value); }
  80. }
  81. /// <summary>
  82. /// Gets or sets the images.
  83. /// </summary>
  84. /// <value>The images.</value>
  85. public virtual Dictionary<ImageType, string> Images { get; set; }
  86. /// <summary>
  87. /// Gets or sets the date created.
  88. /// </summary>
  89. /// <value>The date created.</value>
  90. public DateTime DateCreated { get; set; }
  91. /// <summary>
  92. /// Gets or sets the date modified.
  93. /// </summary>
  94. /// <value>The date modified.</value>
  95. public DateTime DateModified { get; set; }
  96. /// <summary>
  97. /// The logger
  98. /// </summary>
  99. public static ILogger Logger { get; set; }
  100. public static ILibraryManager LibraryManager { get; set; }
  101. public static IServerConfigurationManager ConfigurationManager { get; set; }
  102. public static IProviderManager ProviderManager { get; set; }
  103. /// <summary>
  104. /// Returns a <see cref="System.String" /> that represents this instance.
  105. /// </summary>
  106. /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
  107. public override string ToString()
  108. {
  109. return Name;
  110. }
  111. /// <summary>
  112. /// Returns true if this item should not attempt to fetch metadata
  113. /// </summary>
  114. /// <value><c>true</c> if [dont fetch meta]; otherwise, <c>false</c>.</value>
  115. [IgnoreDataMember]
  116. public virtual bool DontFetchMeta
  117. {
  118. get
  119. {
  120. if (Path != null)
  121. {
  122. return Path.IndexOf("[dontfetchmeta]", StringComparison.OrdinalIgnoreCase) != -1;
  123. }
  124. return false;
  125. }
  126. }
  127. /// <summary>
  128. /// Determines whether the item has a saved local image of the specified name (jpg or png).
  129. /// </summary>
  130. /// <param name="name">The name.</param>
  131. /// <returns><c>true</c> if [has local image] [the specified item]; otherwise, <c>false</c>.</returns>
  132. /// <exception cref="System.ArgumentNullException">name</exception>
  133. public bool HasLocalImage(string name)
  134. {
  135. if (string.IsNullOrEmpty(name))
  136. {
  137. throw new ArgumentNullException("name");
  138. }
  139. return ResolveArgs.ContainsMetaFileByName(name + ".jpg") ||
  140. ResolveArgs.ContainsMetaFileByName(name + ".png");
  141. }
  142. /// <summary>
  143. /// Should be overridden to return the proper folder where metadata lives
  144. /// </summary>
  145. /// <value>The meta location.</value>
  146. [IgnoreDataMember]
  147. public virtual string MetaLocation
  148. {
  149. get
  150. {
  151. return Path ?? "";
  152. }
  153. }
  154. /// <summary>
  155. /// The _provider data
  156. /// </summary>
  157. private Dictionary<Guid, BaseProviderInfo> _providerData;
  158. /// <summary>
  159. /// Holds persistent data for providers like last refresh date.
  160. /// Providers can use this to determine if they need to refresh.
  161. /// The BaseProviderInfo class can be extended to hold anything a provider may need.
  162. /// Keyed by a unique provider ID.
  163. /// </summary>
  164. /// <value>The provider data.</value>
  165. public Dictionary<Guid, BaseProviderInfo> ProviderData
  166. {
  167. get
  168. {
  169. return _providerData ?? (_providerData = new Dictionary<Guid, BaseProviderInfo>());
  170. }
  171. set
  172. {
  173. _providerData = value;
  174. }
  175. }
  176. /// <summary>
  177. /// The _file system stamp
  178. /// </summary>
  179. private Guid? _fileSystemStamp;
  180. /// <summary>
  181. /// Gets a directory stamp, in the form of a string, that can be used for
  182. /// comparison purposes to determine if the file system entries for this item have changed.
  183. /// </summary>
  184. /// <value>The file system stamp.</value>
  185. [IgnoreDataMember]
  186. public Guid FileSystemStamp
  187. {
  188. get
  189. {
  190. if (!_fileSystemStamp.HasValue)
  191. {
  192. _fileSystemStamp = GetFileSystemStamp();
  193. }
  194. return _fileSystemStamp.Value;
  195. }
  196. }
  197. /// <summary>
  198. /// Gets the type of the media.
  199. /// </summary>
  200. /// <value>The type of the media.</value>
  201. [IgnoreDataMember]
  202. public virtual string MediaType
  203. {
  204. get
  205. {
  206. return null;
  207. }
  208. }
  209. /// <summary>
  210. /// Gets a directory stamp, in the form of a string, that can be used for
  211. /// comparison purposes to determine if the file system entries for this item have changed.
  212. /// </summary>
  213. /// <returns>Guid.</returns>
  214. private Guid GetFileSystemStamp()
  215. {
  216. // If there's no path or the item is a file, there's nothing to do
  217. if (LocationType != LocationType.FileSystem || !ResolveArgs.IsDirectory)
  218. {
  219. return Guid.Empty;
  220. }
  221. var sb = new StringBuilder();
  222. // Record the name of each file
  223. // Need to sort these because accoring to msdn docs, our i/o methods are not guaranteed in any order
  224. foreach (var file in ResolveArgs.FileSystemChildren.OrderBy(f => f.Name))
  225. {
  226. sb.Append(file.Name);
  227. }
  228. foreach (var file in ResolveArgs.MetadataFiles.OrderBy(f => f.Name))
  229. {
  230. sb.Append(file.Name);
  231. }
  232. return sb.ToString().GetMD5();
  233. }
  234. /// <summary>
  235. /// The _resolve args
  236. /// </summary>
  237. private ItemResolveArgs _resolveArgs;
  238. /// <summary>
  239. /// The _resolve args initialized
  240. /// </summary>
  241. private bool _resolveArgsInitialized;
  242. /// <summary>
  243. /// The _resolve args sync lock
  244. /// </summary>
  245. private object _resolveArgsSyncLock = new object();
  246. /// <summary>
  247. /// We attach these to the item so that we only ever have to hit the file system once
  248. /// (this includes the children of the containing folder)
  249. /// Use ResolveArgs.FileSystemDictionary to check for the existence of files instead of File.Exists
  250. /// </summary>
  251. /// <value>The resolve args.</value>
  252. [IgnoreDataMember]
  253. public ItemResolveArgs ResolveArgs
  254. {
  255. get
  256. {
  257. try
  258. {
  259. LazyInitializer.EnsureInitialized(ref _resolveArgs, ref _resolveArgsInitialized, ref _resolveArgsSyncLock, () => CreateResolveArgs());
  260. }
  261. catch (IOException ex)
  262. {
  263. Logger.ErrorException("Error creating resolve args for ", ex, Path);
  264. throw;
  265. }
  266. return _resolveArgs;
  267. }
  268. set
  269. {
  270. _resolveArgs = value;
  271. _resolveArgsInitialized = value != null;
  272. // Null this out so that it can be lazy loaded again
  273. _fileSystemStamp = null;
  274. }
  275. }
  276. /// <summary>
  277. /// Resets the resolve args.
  278. /// </summary>
  279. /// <param name="pathInfo">The path info.</param>
  280. public void ResetResolveArgs(FileSystemInfo pathInfo)
  281. {
  282. ResolveArgs = CreateResolveArgs(pathInfo);
  283. }
  284. /// <summary>
  285. /// Creates ResolveArgs on demand
  286. /// </summary>
  287. /// <param name="pathInfo">The path info.</param>
  288. /// <returns>ItemResolveArgs.</returns>
  289. /// <exception cref="System.IO.IOException">Unable to retrieve file system info for + path</exception>
  290. protected internal virtual ItemResolveArgs CreateResolveArgs(FileSystemInfo pathInfo = null)
  291. {
  292. var path = Path;
  293. // non file-system entries will not have a path
  294. if (LocationType != LocationType.FileSystem || string.IsNullOrEmpty(path))
  295. {
  296. return new ItemResolveArgs(ConfigurationManager.ApplicationPaths);
  297. }
  298. if (UseParentPathToCreateResolveArgs)
  299. {
  300. path = System.IO.Path.GetDirectoryName(path);
  301. }
  302. pathInfo = pathInfo ?? FileSystem.GetFileSystemInfo(path);
  303. if (pathInfo == null || !pathInfo.Exists)
  304. {
  305. throw new IOException("Unable to retrieve file system info for " + path);
  306. }
  307. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths)
  308. {
  309. FileInfo = pathInfo,
  310. Path = path,
  311. Parent = Parent
  312. };
  313. // Gather child folder and files
  314. if (args.IsDirectory)
  315. {
  316. var isPhysicalRoot = args.IsPhysicalRoot;
  317. // When resolving the root, we need it's grandchildren (children of user views)
  318. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  319. args.FileSystemDictionary = FileData.GetFilteredFileSystemEntries(args.Path, Logger, flattenFolderDepth: flattenFolderDepth, args: args, resolveShortcuts: isPhysicalRoot || args.IsVf);
  320. }
  321. //update our dates
  322. EntityResolutionHelper.EnsureDates(this, args);
  323. return args;
  324. }
  325. /// <summary>
  326. /// Some subclasses will stop resolving at a directory and point their Path to a file within. This will help ensure the on-demand resolve args are identical to the
  327. /// original ones.
  328. /// </summary>
  329. /// <value><c>true</c> if [use parent path to create resolve args]; otherwise, <c>false</c>.</value>
  330. [IgnoreDataMember]
  331. protected virtual bool UseParentPathToCreateResolveArgs
  332. {
  333. get
  334. {
  335. return false;
  336. }
  337. }
  338. /// <summary>
  339. /// Gets or sets the name of the forced sort.
  340. /// </summary>
  341. /// <value>The name of the forced sort.</value>
  342. public string ForcedSortName { get; set; }
  343. private string _sortName;
  344. /// <summary>
  345. /// Gets or sets the name of the sort.
  346. /// </summary>
  347. /// <value>The name of the sort.</value>
  348. [IgnoreDataMember]
  349. public string SortName
  350. {
  351. get
  352. {
  353. return ForcedSortName ?? _sortName ?? (_sortName = CreateSortName());
  354. }
  355. }
  356. /// <summary>
  357. /// Creates the name of the sort.
  358. /// </summary>
  359. /// <returns>System.String.</returns>
  360. protected virtual string CreateSortName()
  361. {
  362. if (Name == null) return null; //some items may not have name filled in properly
  363. var sortable = Name.Trim().ToLower();
  364. sortable = ConfigurationManager.Configuration.SortRemoveCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), string.Empty));
  365. sortable = ConfigurationManager.Configuration.SortReplaceCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), " "));
  366. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  367. {
  368. var searchLower = search.ToLower();
  369. // Remove from beginning if a space follows
  370. if (sortable.StartsWith(searchLower + " "))
  371. {
  372. sortable = sortable.Remove(0, searchLower.Length + 1);
  373. }
  374. // Remove from middle if surrounded by spaces
  375. sortable = sortable.Replace(" " + searchLower + " ", " ");
  376. // Remove from end if followed by a space
  377. if (sortable.EndsWith(" " + searchLower))
  378. {
  379. sortable = sortable.Remove(sortable.Length - (searchLower.Length + 1));
  380. }
  381. }
  382. return sortable;
  383. }
  384. /// <summary>
  385. /// Gets or sets the parent.
  386. /// </summary>
  387. /// <value>The parent.</value>
  388. [IgnoreDataMember]
  389. public Folder Parent { get; set; }
  390. /// <summary>
  391. /// Gets the collection folder parent.
  392. /// </summary>
  393. /// <value>The collection folder parent.</value>
  394. [IgnoreDataMember]
  395. public Folder CollectionFolder
  396. {
  397. get
  398. {
  399. if (this is AggregateFolder)
  400. {
  401. return null;
  402. }
  403. if (IsFolder)
  404. {
  405. var iCollectionFolder = this as ICollectionFolder;
  406. if (iCollectionFolder != null)
  407. {
  408. return (Folder)this;
  409. }
  410. }
  411. var parent = Parent;
  412. while (parent != null)
  413. {
  414. var iCollectionFolder = parent as ICollectionFolder;
  415. if (iCollectionFolder != null)
  416. {
  417. return parent;
  418. }
  419. parent = parent.Parent;
  420. }
  421. return null;
  422. }
  423. }
  424. /// <summary>
  425. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  426. /// </summary>
  427. /// <value>The premiere date.</value>
  428. public DateTime? PremiereDate { get; set; }
  429. /// <summary>
  430. /// Gets or sets the end date.
  431. /// </summary>
  432. /// <value>The end date.</value>
  433. public DateTime? EndDate { get; set; }
  434. /// <summary>
  435. /// Gets or sets the display type of the media.
  436. /// </summary>
  437. /// <value>The display type of the media.</value>
  438. public virtual string DisplayMediaType { get; set; }
  439. /// <summary>
  440. /// Gets or sets the backdrop image paths.
  441. /// </summary>
  442. /// <value>The backdrop image paths.</value>
  443. public List<string> BackdropImagePaths { get; set; }
  444. /// <summary>
  445. /// Gets or sets the screenshot image paths.
  446. /// </summary>
  447. /// <value>The screenshot image paths.</value>
  448. public List<string> ScreenshotImagePaths { get; set; }
  449. /// <summary>
  450. /// Gets or sets the official rating.
  451. /// </summary>
  452. /// <value>The official rating.</value>
  453. public virtual string OfficialRating { get; set; }
  454. /// <summary>
  455. /// Gets or sets the custom rating.
  456. /// </summary>
  457. /// <value>The custom rating.</value>
  458. public virtual string CustomRating { get; set; }
  459. /// <summary>
  460. /// Gets or sets the language.
  461. /// </summary>
  462. /// <value>The language.</value>
  463. public string Language { get; set; }
  464. /// <summary>
  465. /// Gets or sets the overview.
  466. /// </summary>
  467. /// <value>The overview.</value>
  468. public string Overview { get; set; }
  469. /// <summary>
  470. /// Gets or sets the taglines.
  471. /// </summary>
  472. /// <value>The taglines.</value>
  473. public List<string> Taglines { get; set; }
  474. /// <summary>
  475. /// Gets or sets the people.
  476. /// </summary>
  477. /// <value>The people.</value>
  478. public List<PersonInfo> People { get; set; }
  479. /// <summary>
  480. /// Override this if you need to combine/collapse person information
  481. /// </summary>
  482. /// <value>All people.</value>
  483. [IgnoreDataMember]
  484. public virtual IEnumerable<PersonInfo> AllPeople
  485. {
  486. get { return People; }
  487. }
  488. /// <summary>
  489. /// Gets or sets the studios.
  490. /// </summary>
  491. /// <value>The studios.</value>
  492. public virtual List<string> Studios { get; set; }
  493. /// <summary>
  494. /// Gets or sets the genres.
  495. /// </summary>
  496. /// <value>The genres.</value>
  497. public virtual List<string> Genres { get; set; }
  498. /// <summary>
  499. /// Gets or sets the home page URL.
  500. /// </summary>
  501. /// <value>The home page URL.</value>
  502. public string HomePageUrl { get; set; }
  503. /// <summary>
  504. /// Gets or sets the budget.
  505. /// </summary>
  506. /// <value>The budget.</value>
  507. public double? Budget { get; set; }
  508. /// <summary>
  509. /// Gets or sets the revenue.
  510. /// </summary>
  511. /// <value>The revenue.</value>
  512. public double? Revenue { get; set; }
  513. /// <summary>
  514. /// Gets or sets the production locations.
  515. /// </summary>
  516. /// <value>The production locations.</value>
  517. public List<string> ProductionLocations { get; set; }
  518. /// <summary>
  519. /// Gets or sets the critic rating.
  520. /// </summary>
  521. /// <value>The critic rating.</value>
  522. public float? CriticRating { get; set; }
  523. /// <summary>
  524. /// Gets or sets the critic rating summary.
  525. /// </summary>
  526. /// <value>The critic rating summary.</value>
  527. public string CriticRatingSummary { get; set; }
  528. /// <summary>
  529. /// Gets or sets the community rating.
  530. /// </summary>
  531. /// <value>The community rating.</value>
  532. public float? CommunityRating { get; set; }
  533. /// <summary>
  534. /// Gets or sets the run time ticks.
  535. /// </summary>
  536. /// <value>The run time ticks.</value>
  537. public long? RunTimeTicks { get; set; }
  538. /// <summary>
  539. /// Gets or sets the aspect ratio.
  540. /// </summary>
  541. /// <value>The aspect ratio.</value>
  542. public string AspectRatio { get; set; }
  543. /// <summary>
  544. /// Gets or sets the production year.
  545. /// </summary>
  546. /// <value>The production year.</value>
  547. public virtual int? ProductionYear { get; set; }
  548. /// <summary>
  549. /// If the item is part of a series, this is it's number in the series.
  550. /// This could be episode number, album track number, etc.
  551. /// </summary>
  552. /// <value>The index number.</value>
  553. public int? IndexNumber { get; set; }
  554. /// <summary>
  555. /// For an episode this could be the season number, or for a song this could be the disc number.
  556. /// </summary>
  557. /// <value>The parent index number.</value>
  558. public int? ParentIndexNumber { get; set; }
  559. /// <summary>
  560. /// Gets or sets the critic reviews.
  561. /// </summary>
  562. /// <value>The critic reviews.</value>
  563. public List<ItemReview> CriticReviews { get; set; }
  564. /// <summary>
  565. /// The _local trailers
  566. /// </summary>
  567. private List<Trailer> _localTrailers;
  568. /// <summary>
  569. /// The _local trailers initialized
  570. /// </summary>
  571. private bool _localTrailersInitialized;
  572. /// <summary>
  573. /// The _local trailers sync lock
  574. /// </summary>
  575. private object _localTrailersSyncLock = new object();
  576. /// <summary>
  577. /// Gets the local trailers.
  578. /// </summary>
  579. /// <value>The local trailers.</value>
  580. [IgnoreDataMember]
  581. public List<Trailer> LocalTrailers
  582. {
  583. get
  584. {
  585. LazyInitializer.EnsureInitialized(ref _localTrailers, ref _localTrailersInitialized, ref _localTrailersSyncLock, LoadLocalTrailers);
  586. return _localTrailers;
  587. }
  588. private set
  589. {
  590. _localTrailers = value;
  591. if (value == null)
  592. {
  593. _localTrailersInitialized = false;
  594. }
  595. }
  596. }
  597. private List<Audio.Audio> _themeSongs;
  598. private bool _themeSongsInitialized;
  599. private object _themeSongsSyncLock = new object();
  600. [IgnoreDataMember]
  601. public List<Audio.Audio> ThemeSongs
  602. {
  603. get
  604. {
  605. LazyInitializer.EnsureInitialized(ref _themeSongs, ref _themeSongsInitialized, ref _themeSongsSyncLock, LoadThemeSongs);
  606. return _themeSongs;
  607. }
  608. private set
  609. {
  610. _themeSongs = value;
  611. if (value == null)
  612. {
  613. _themeSongsInitialized = false;
  614. }
  615. }
  616. }
  617. private List<Video> _themeVideos;
  618. private bool _themeVideosInitialized;
  619. private object _themeVideosSyncLock = new object();
  620. [IgnoreDataMember]
  621. public List<Video> ThemeVideos
  622. {
  623. get
  624. {
  625. LazyInitializer.EnsureInitialized(ref _themeVideos, ref _themeVideosInitialized, ref _themeVideosSyncLock, LoadThemeVideos);
  626. return _themeVideos;
  627. }
  628. private set
  629. {
  630. _themeVideos = value;
  631. if (value == null)
  632. {
  633. _themeVideosInitialized = false;
  634. }
  635. }
  636. }
  637. /// <summary>
  638. /// Loads local trailers from the file system
  639. /// </summary>
  640. /// <returns>List{Video}.</returns>
  641. private List<Trailer> LoadLocalTrailers()
  642. {
  643. ItemResolveArgs resolveArgs;
  644. try
  645. {
  646. resolveArgs = ResolveArgs;
  647. }
  648. catch (IOException ex)
  649. {
  650. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  651. return new List<Trailer>();
  652. }
  653. if (!resolveArgs.IsDirectory)
  654. {
  655. return new List<Trailer>();
  656. }
  657. var folder = resolveArgs.GetFileSystemEntryByName(TrailerFolderName);
  658. // Path doesn't exist. No biggie
  659. if (folder == null)
  660. {
  661. return new List<Trailer>();
  662. }
  663. IEnumerable<FileSystemInfo> files;
  664. try
  665. {
  666. files = new DirectoryInfo(folder.FullName).EnumerateFiles();
  667. }
  668. catch (IOException ex)
  669. {
  670. Logger.ErrorException("Error loading trailers for {0}", ex, Name);
  671. return new List<Trailer>();
  672. }
  673. return LibraryManager.ResolvePaths<Trailer>(files, null).Select(video =>
  674. {
  675. // Try to retrieve it from the db. If we don't find it, use the resolved version
  676. var dbItem = LibraryManager.RetrieveItem(video.Id) as Trailer;
  677. if (dbItem != null)
  678. {
  679. dbItem.ResolveArgs = video.ResolveArgs;
  680. video = dbItem;
  681. }
  682. return video;
  683. }).ToList();
  684. }
  685. /// <summary>
  686. /// Loads the theme songs.
  687. /// </summary>
  688. /// <returns>List{Audio.Audio}.</returns>
  689. private List<Audio.Audio> LoadThemeSongs()
  690. {
  691. ItemResolveArgs resolveArgs;
  692. try
  693. {
  694. resolveArgs = ResolveArgs;
  695. }
  696. catch (IOException ex)
  697. {
  698. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  699. return new List<Audio.Audio>();
  700. }
  701. if (!resolveArgs.IsDirectory)
  702. {
  703. return new List<Audio.Audio>();
  704. }
  705. var folder = resolveArgs.GetFileSystemEntryByName(ThemeSongsFolderName);
  706. // Path doesn't exist. No biggie
  707. if (folder == null)
  708. {
  709. return new List<Audio.Audio>();
  710. }
  711. IEnumerable<FileSystemInfo> files;
  712. try
  713. {
  714. files = new DirectoryInfo(folder.FullName).EnumerateFiles();
  715. }
  716. catch (IOException ex)
  717. {
  718. Logger.ErrorException("Error loading theme songs for {0}", ex, Name);
  719. return new List<Audio.Audio>();
  720. }
  721. return LibraryManager.ResolvePaths<Audio.Audio>(files, null).Select(audio =>
  722. {
  723. // Try to retrieve it from the db. If we don't find it, use the resolved version
  724. var dbItem = LibraryManager.RetrieveItem(audio.Id) as Audio.Audio;
  725. if (dbItem != null)
  726. {
  727. dbItem.ResolveArgs = audio.ResolveArgs;
  728. audio = dbItem;
  729. }
  730. return audio;
  731. }).ToList();
  732. }
  733. /// <summary>
  734. /// Loads the video backdrops.
  735. /// </summary>
  736. /// <returns>List{Video}.</returns>
  737. private List<Video> LoadThemeVideos()
  738. {
  739. ItemResolveArgs resolveArgs;
  740. try
  741. {
  742. resolveArgs = ResolveArgs;
  743. }
  744. catch (IOException ex)
  745. {
  746. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  747. return new List<Video>();
  748. }
  749. if (!resolveArgs.IsDirectory)
  750. {
  751. return new List<Video>();
  752. }
  753. var folder = resolveArgs.GetFileSystemEntryByName(ThemeVideosFolderName);
  754. // Path doesn't exist. No biggie
  755. if (folder == null)
  756. {
  757. return new List<Video>();
  758. }
  759. IEnumerable<FileSystemInfo> files;
  760. try
  761. {
  762. files = new DirectoryInfo(folder.FullName).EnumerateFiles();
  763. }
  764. catch (IOException ex)
  765. {
  766. Logger.ErrorException("Error loading video backdrops for {0}", ex, Name);
  767. return new List<Video>();
  768. }
  769. return LibraryManager.ResolvePaths<Video>(files, null).Select(item =>
  770. {
  771. // Try to retrieve it from the db. If we don't find it, use the resolved version
  772. var dbItem = LibraryManager.RetrieveItem(item.Id) as Video;
  773. if (dbItem != null)
  774. {
  775. dbItem.ResolveArgs = item.ResolveArgs;
  776. item = dbItem;
  777. }
  778. return item;
  779. }).ToList();
  780. }
  781. /// <summary>
  782. /// Overrides the base implementation to refresh metadata for local trailers
  783. /// </summary>
  784. /// <param name="cancellationToken">The cancellation token.</param>
  785. /// <param name="forceSave">if set to <c>true</c> [is new item].</param>
  786. /// <param name="forceRefresh">if set to <c>true</c> [force].</param>
  787. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  788. /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param>
  789. /// <returns>true if a provider reports we changed</returns>
  790. public virtual async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  791. {
  792. if (resetResolveArgs)
  793. {
  794. ResolveArgs = null;
  795. }
  796. // Lazy load these again
  797. LocalTrailers = null;
  798. ThemeSongs = null;
  799. ThemeVideos = null;
  800. // Refresh for the item
  801. var itemRefreshTask = ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh, allowSlowProviders);
  802. cancellationToken.ThrowIfCancellationRequested();
  803. // Refresh metadata for local trailers
  804. var trailerTasks = LocalTrailers.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  805. var themeSongTasks = ThemeSongs.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  806. var videoBackdropTasks = ThemeVideos.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  807. cancellationToken.ThrowIfCancellationRequested();
  808. // Await the trailer tasks
  809. await Task.WhenAll(trailerTasks).ConfigureAwait(false);
  810. await Task.WhenAll(themeSongTasks).ConfigureAwait(false);
  811. await Task.WhenAll(videoBackdropTasks).ConfigureAwait(false);
  812. cancellationToken.ThrowIfCancellationRequested();
  813. // Get the result from the item task
  814. var changed = await itemRefreshTask.ConfigureAwait(false);
  815. if (changed || forceSave)
  816. {
  817. cancellationToken.ThrowIfCancellationRequested();
  818. await LibraryManager.SaveItem(this, cancellationToken).ConfigureAwait(false);
  819. }
  820. return changed;
  821. }
  822. /// <summary>
  823. /// Clear out all metadata properties. Extend for sub-classes.
  824. /// </summary>
  825. public virtual void ClearMetaValues()
  826. {
  827. Images = null;
  828. ForcedSortName = null;
  829. PremiereDate = null;
  830. BackdropImagePaths = null;
  831. OfficialRating = null;
  832. CustomRating = null;
  833. Overview = null;
  834. Taglines.Clear();
  835. Language = null;
  836. Studios.Clear();
  837. Genres.Clear();
  838. CommunityRating = null;
  839. RunTimeTicks = null;
  840. AspectRatio = null;
  841. ProductionYear = null;
  842. ProviderIds = null;
  843. DisplayMediaType = GetType().Name;
  844. ResolveArgs = null;
  845. }
  846. /// <summary>
  847. /// Gets or sets the trailer URL.
  848. /// </summary>
  849. /// <value>The trailer URL.</value>
  850. public List<string> TrailerUrls { get; set; }
  851. /// <summary>
  852. /// Gets or sets the provider ids.
  853. /// </summary>
  854. /// <value>The provider ids.</value>
  855. public Dictionary<string, string> ProviderIds { get; set; }
  856. /// <summary>
  857. /// Override this to false if class should be ignored for indexing purposes
  858. /// </summary>
  859. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  860. [IgnoreDataMember]
  861. public virtual bool IncludeInIndex
  862. {
  863. get { return true; }
  864. }
  865. /// <summary>
  866. /// Override this to true if class should be grouped under a container in indicies
  867. /// The container class should be defined via IndexContainer
  868. /// </summary>
  869. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  870. [IgnoreDataMember]
  871. public virtual bool GroupInIndex
  872. {
  873. get { return false; }
  874. }
  875. /// <summary>
  876. /// Override this to return the folder that should be used to construct a container
  877. /// for this item in an index. GroupInIndex should be true as well.
  878. /// </summary>
  879. /// <value>The index container.</value>
  880. [IgnoreDataMember]
  881. public virtual Folder IndexContainer
  882. {
  883. get { return null; }
  884. }
  885. /// <summary>
  886. /// Gets the user data key.
  887. /// </summary>
  888. /// <returns>System.String.</returns>
  889. public virtual string GetUserDataKey()
  890. {
  891. return Id.ToString();
  892. }
  893. /// <summary>
  894. /// Determines if a given user has access to this item
  895. /// </summary>
  896. /// <param name="user">The user.</param>
  897. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  898. /// <exception cref="System.ArgumentNullException"></exception>
  899. public bool IsParentalAllowed(User user)
  900. {
  901. if (user == null)
  902. {
  903. throw new ArgumentNullException("user");
  904. }
  905. if (user.Configuration.MaxParentalRating == null)
  906. {
  907. return true;
  908. }
  909. return Ratings.Level(CustomRating ?? OfficialRating) <= user.Configuration.MaxParentalRating.Value;
  910. }
  911. /// <summary>
  912. /// Determines if this folder should be visible to a given user.
  913. /// Default is just parental allowed. Can be overridden for more functionality.
  914. /// </summary>
  915. /// <param name="user">The user.</param>
  916. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  917. /// <exception cref="System.ArgumentNullException">user</exception>
  918. public virtual bool IsVisible(User user)
  919. {
  920. if (user == null)
  921. {
  922. throw new ArgumentNullException("user");
  923. }
  924. return IsParentalAllowed(user);
  925. }
  926. /// <summary>
  927. /// Finds the particular item by searching through our parents and, if not found there, loading from repo
  928. /// </summary>
  929. /// <param name="id">The id.</param>
  930. /// <returns>BaseItem.</returns>
  931. /// <exception cref="System.ArgumentException"></exception>
  932. protected BaseItem FindParentItem(Guid id)
  933. {
  934. if (id == Guid.Empty)
  935. {
  936. throw new ArgumentException();
  937. }
  938. var parent = Parent;
  939. while (parent != null && !parent.IsRoot)
  940. {
  941. if (parent.Id == id) return parent;
  942. parent = parent.Parent;
  943. }
  944. //not found - load from repo
  945. return LibraryManager.RetrieveItem(id);
  946. }
  947. /// <summary>
  948. /// Gets a value indicating whether this instance is folder.
  949. /// </summary>
  950. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  951. [IgnoreDataMember]
  952. public virtual bool IsFolder
  953. {
  954. get
  955. {
  956. return false;
  957. }
  958. }
  959. /// <summary>
  960. /// Determine if we have changed vs the passed in copy
  961. /// </summary>
  962. /// <param name="copy">The copy.</param>
  963. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  964. /// <exception cref="System.ArgumentNullException"></exception>
  965. public virtual bool HasChanged(BaseItem copy)
  966. {
  967. if (copy == null)
  968. {
  969. throw new ArgumentNullException();
  970. }
  971. var changed = copy.DateModified != DateModified;
  972. if (changed)
  973. {
  974. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  975. }
  976. return changed;
  977. }
  978. /// <summary>
  979. /// Determines if the item is considered new based on user settings
  980. /// </summary>
  981. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  982. /// <exception cref="System.ArgumentNullException"></exception>
  983. public bool IsRecentlyAdded()
  984. {
  985. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  986. }
  987. /// <summary>
  988. /// Adds a person to the item
  989. /// </summary>
  990. /// <param name="person">The person.</param>
  991. /// <exception cref="System.ArgumentNullException"></exception>
  992. public void AddPerson(PersonInfo person)
  993. {
  994. if (person == null)
  995. {
  996. throw new ArgumentNullException("person");
  997. }
  998. if (string.IsNullOrWhiteSpace(person.Name))
  999. {
  1000. throw new ArgumentNullException();
  1001. }
  1002. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  1003. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  1004. {
  1005. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  1006. if (existing != null)
  1007. {
  1008. existing.Type = PersonType.GuestStar;
  1009. return;
  1010. }
  1011. }
  1012. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  1013. {
  1014. // If the actor already exists without a role and we have one, fill it in
  1015. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && (p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase) || p.Type.Equals(PersonType.GuestStar, StringComparison.OrdinalIgnoreCase)));
  1016. if (existing == null)
  1017. {
  1018. // Wasn't there - add it
  1019. People.Add(person);
  1020. }
  1021. else
  1022. {
  1023. // Was there, if no role and we have one - fill it in
  1024. if (string.IsNullOrWhiteSpace(existing.Role) && !string.IsNullOrWhiteSpace(person.Role)) existing.Role = person.Role;
  1025. }
  1026. }
  1027. else
  1028. {
  1029. // Check for dupes based on the combination of Name and Type
  1030. if (!People.Any(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(person.Type, StringComparison.OrdinalIgnoreCase)))
  1031. {
  1032. People.Add(person);
  1033. }
  1034. }
  1035. }
  1036. /// <summary>
  1037. /// Adds a studio to the item
  1038. /// </summary>
  1039. /// <param name="name">The name.</param>
  1040. /// <exception cref="System.ArgumentNullException"></exception>
  1041. public void AddStudio(string name)
  1042. {
  1043. if (string.IsNullOrWhiteSpace(name))
  1044. {
  1045. throw new ArgumentNullException("name");
  1046. }
  1047. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1048. {
  1049. Studios.Add(name);
  1050. }
  1051. }
  1052. /// <summary>
  1053. /// Adds a tagline to the item
  1054. /// </summary>
  1055. /// <param name="name">The name.</param>
  1056. /// <exception cref="System.ArgumentNullException"></exception>
  1057. public void AddTagline(string name)
  1058. {
  1059. if (string.IsNullOrWhiteSpace(name))
  1060. {
  1061. throw new ArgumentNullException("name");
  1062. }
  1063. if (!Taglines.Contains(name, StringComparer.OrdinalIgnoreCase))
  1064. {
  1065. Taglines.Add(name);
  1066. }
  1067. }
  1068. /// <summary>
  1069. /// Adds a TrailerUrl to the item
  1070. /// </summary>
  1071. /// <param name="url">The URL.</param>
  1072. /// <exception cref="System.ArgumentNullException"></exception>
  1073. public void AddTrailerUrl(string url)
  1074. {
  1075. if (string.IsNullOrWhiteSpace(url))
  1076. {
  1077. throw new ArgumentNullException("url");
  1078. }
  1079. if (TrailerUrls == null)
  1080. {
  1081. TrailerUrls = new List<string>();
  1082. }
  1083. if (!TrailerUrls.Contains(url, StringComparer.OrdinalIgnoreCase))
  1084. {
  1085. TrailerUrls.Add(url);
  1086. }
  1087. }
  1088. /// <summary>
  1089. /// Adds a genre to the item
  1090. /// </summary>
  1091. /// <param name="name">The name.</param>
  1092. /// <exception cref="System.ArgumentNullException"></exception>
  1093. public void AddGenre(string name)
  1094. {
  1095. if (string.IsNullOrWhiteSpace(name))
  1096. {
  1097. throw new ArgumentNullException("name");
  1098. }
  1099. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1100. {
  1101. Genres.Add(name);
  1102. }
  1103. }
  1104. /// <summary>
  1105. /// Adds the production location.
  1106. /// </summary>
  1107. /// <param name="location">The location.</param>
  1108. /// <exception cref="System.ArgumentNullException">location</exception>
  1109. public void AddProductionLocation(string location)
  1110. {
  1111. if (string.IsNullOrWhiteSpace(location))
  1112. {
  1113. throw new ArgumentNullException("location");
  1114. }
  1115. if (ProductionLocations == null)
  1116. {
  1117. ProductionLocations = new List<string>();
  1118. }
  1119. if (!ProductionLocations.Contains(location, StringComparer.OrdinalIgnoreCase))
  1120. {
  1121. ProductionLocations.Add(location);
  1122. }
  1123. }
  1124. /// <summary>
  1125. /// Marks the item as either played or unplayed
  1126. /// </summary>
  1127. /// <param name="user">The user.</param>
  1128. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  1129. /// <param name="userManager">The user manager.</param>
  1130. /// <returns>Task.</returns>
  1131. /// <exception cref="System.ArgumentNullException"></exception>
  1132. public virtual async Task SetPlayedStatus(User user, bool wasPlayed, IUserDataRepository userManager)
  1133. {
  1134. if (user == null)
  1135. {
  1136. throw new ArgumentNullException();
  1137. }
  1138. var key = GetUserDataKey();
  1139. var data = await userManager.GetUserData(user.Id, key).ConfigureAwait(false);
  1140. if (wasPlayed)
  1141. {
  1142. data.PlayCount = Math.Max(data.PlayCount, 1);
  1143. if (!data.LastPlayedDate.HasValue)
  1144. {
  1145. data.LastPlayedDate = DateTime.UtcNow;
  1146. }
  1147. }
  1148. else
  1149. {
  1150. //I think it is okay to do this here.
  1151. // if this is only called when a user is manually forcing something to un-played
  1152. // then it probably is what we want to do...
  1153. data.PlayCount = 0;
  1154. data.PlaybackPositionTicks = 0;
  1155. data.LastPlayedDate = null;
  1156. }
  1157. data.Played = wasPlayed;
  1158. await userManager.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  1159. }
  1160. /// <summary>
  1161. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1162. /// </summary>
  1163. /// <returns>Task.</returns>
  1164. public virtual Task ChangedExternally()
  1165. {
  1166. return RefreshMetadata(CancellationToken.None);
  1167. }
  1168. /// <summary>
  1169. /// Finds a parent of a given type
  1170. /// </summary>
  1171. /// <typeparam name="T"></typeparam>
  1172. /// <returns>``0.</returns>
  1173. public T FindParent<T>()
  1174. where T : Folder
  1175. {
  1176. var parent = Parent;
  1177. while (parent != null)
  1178. {
  1179. var result = parent as T;
  1180. if (result != null)
  1181. {
  1182. return result;
  1183. }
  1184. parent = parent.Parent;
  1185. }
  1186. return null;
  1187. }
  1188. /// <summary>
  1189. /// Gets an image
  1190. /// </summary>
  1191. /// <param name="type">The type.</param>
  1192. /// <returns>System.String.</returns>
  1193. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1194. public string GetImage(ImageType type)
  1195. {
  1196. if (type == ImageType.Backdrop)
  1197. {
  1198. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1199. }
  1200. if (type == ImageType.Screenshot)
  1201. {
  1202. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1203. }
  1204. if (Images == null)
  1205. {
  1206. return null;
  1207. }
  1208. string val;
  1209. Images.TryGetValue(type, out val);
  1210. return val;
  1211. }
  1212. /// <summary>
  1213. /// Gets an image
  1214. /// </summary>
  1215. /// <param name="type">The type.</param>
  1216. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1217. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1218. public bool HasImage(ImageType type)
  1219. {
  1220. if (type == ImageType.Backdrop)
  1221. {
  1222. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1223. }
  1224. if (type == ImageType.Screenshot)
  1225. {
  1226. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1227. }
  1228. return !string.IsNullOrEmpty(GetImage(type));
  1229. }
  1230. /// <summary>
  1231. /// Sets an image
  1232. /// </summary>
  1233. /// <param name="type">The type.</param>
  1234. /// <param name="path">The path.</param>
  1235. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1236. public void SetImage(ImageType type, string path)
  1237. {
  1238. if (type == ImageType.Backdrop)
  1239. {
  1240. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1241. }
  1242. if (type == ImageType.Screenshot)
  1243. {
  1244. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1245. }
  1246. var typeKey = type;
  1247. // If it's null remove the key from the dictionary
  1248. if (string.IsNullOrEmpty(path))
  1249. {
  1250. if (Images != null)
  1251. {
  1252. if (Images.ContainsKey(typeKey))
  1253. {
  1254. Images.Remove(typeKey);
  1255. }
  1256. }
  1257. }
  1258. else
  1259. {
  1260. // Ensure it exists
  1261. if (Images == null)
  1262. {
  1263. Images = new Dictionary<ImageType, string>();
  1264. }
  1265. Images[typeKey] = path;
  1266. }
  1267. }
  1268. /// <summary>
  1269. /// Deletes the image.
  1270. /// </summary>
  1271. /// <param name="type">The type.</param>
  1272. /// <returns>Task.</returns>
  1273. public async Task DeleteImage(ImageType type)
  1274. {
  1275. if (!HasImage(type))
  1276. {
  1277. return;
  1278. }
  1279. // Delete the source file
  1280. File.Delete(GetImage(type));
  1281. // Remove it from the item
  1282. SetImage(type, null);
  1283. // Refresh metadata
  1284. await RefreshMetadata(CancellationToken.None).ConfigureAwait(false);
  1285. }
  1286. }
  1287. }