BaseItem.cs 49 KB

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