BaseItem.cs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475
  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 VideoBackdropsFolderName = "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> _videoBackdrops;
  618. private bool _videoBackdropsInitialized;
  619. private object _videoBackdropsSyncLock = new object();
  620. [IgnoreDataMember]
  621. public List<Video> VideoBackdrops
  622. {
  623. get
  624. {
  625. LazyInitializer.EnsureInitialized(ref _videoBackdrops, ref _videoBackdropsInitialized, ref _videoBackdropsSyncLock, LoadVideoBackdrops);
  626. return _videoBackdrops;
  627. }
  628. private set
  629. {
  630. _videoBackdrops = value;
  631. if (value == null)
  632. {
  633. _videoBackdropsInitialized = 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> LoadVideoBackdrops()
  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(VideoBackdropsFolderName);
  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. VideoBackdrops = 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 = VideoBackdrops.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. // Only add actors if there isn't an existing one of type Actor or GuestStar
  1015. if (!People.Any(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && (p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase) || p.Type.Equals(PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))))
  1016. {
  1017. People.Add(person);
  1018. }
  1019. }
  1020. else
  1021. {
  1022. // Check for dupes based on the combination of Name and Type
  1023. if (!People.Any(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(person.Type, StringComparison.OrdinalIgnoreCase)))
  1024. {
  1025. People.Add(person);
  1026. }
  1027. }
  1028. }
  1029. /// <summary>
  1030. /// Adds a studio to the item
  1031. /// </summary>
  1032. /// <param name="name">The name.</param>
  1033. /// <exception cref="System.ArgumentNullException"></exception>
  1034. public void AddStudio(string name)
  1035. {
  1036. if (string.IsNullOrWhiteSpace(name))
  1037. {
  1038. throw new ArgumentNullException("name");
  1039. }
  1040. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1041. {
  1042. Studios.Add(name);
  1043. }
  1044. }
  1045. /// <summary>
  1046. /// Adds a tagline to the item
  1047. /// </summary>
  1048. /// <param name="name">The name.</param>
  1049. /// <exception cref="System.ArgumentNullException"></exception>
  1050. public void AddTagline(string name)
  1051. {
  1052. if (string.IsNullOrWhiteSpace(name))
  1053. {
  1054. throw new ArgumentNullException("name");
  1055. }
  1056. if (!Taglines.Contains(name, StringComparer.OrdinalIgnoreCase))
  1057. {
  1058. Taglines.Add(name);
  1059. }
  1060. }
  1061. /// <summary>
  1062. /// Adds a TrailerUrl to the item
  1063. /// </summary>
  1064. /// <param name="url">The URL.</param>
  1065. /// <exception cref="System.ArgumentNullException"></exception>
  1066. public void AddTrailerUrl(string url)
  1067. {
  1068. if (string.IsNullOrWhiteSpace(url))
  1069. {
  1070. throw new ArgumentNullException("url");
  1071. }
  1072. if (TrailerUrls == null)
  1073. {
  1074. TrailerUrls = new List<string>();
  1075. }
  1076. if (!TrailerUrls.Contains(url, StringComparer.OrdinalIgnoreCase))
  1077. {
  1078. TrailerUrls.Add(url);
  1079. }
  1080. }
  1081. /// <summary>
  1082. /// Adds a genre to the item
  1083. /// </summary>
  1084. /// <param name="name">The name.</param>
  1085. /// <exception cref="System.ArgumentNullException"></exception>
  1086. public void AddGenre(string name)
  1087. {
  1088. if (string.IsNullOrWhiteSpace(name))
  1089. {
  1090. throw new ArgumentNullException("name");
  1091. }
  1092. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1093. {
  1094. Genres.Add(name);
  1095. }
  1096. }
  1097. /// <summary>
  1098. /// Adds the production location.
  1099. /// </summary>
  1100. /// <param name="location">The location.</param>
  1101. /// <exception cref="System.ArgumentNullException">location</exception>
  1102. public void AddProductionLocation(string location)
  1103. {
  1104. if (string.IsNullOrWhiteSpace(location))
  1105. {
  1106. throw new ArgumentNullException("location");
  1107. }
  1108. if (ProductionLocations == null)
  1109. {
  1110. ProductionLocations = new List<string>();
  1111. }
  1112. if (!ProductionLocations.Contains(location, StringComparer.OrdinalIgnoreCase))
  1113. {
  1114. ProductionLocations.Add(location);
  1115. }
  1116. }
  1117. /// <summary>
  1118. /// Marks the item as either played or unplayed
  1119. /// </summary>
  1120. /// <param name="user">The user.</param>
  1121. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  1122. /// <param name="userManager">The user manager.</param>
  1123. /// <returns>Task.</returns>
  1124. /// <exception cref="System.ArgumentNullException"></exception>
  1125. public virtual async Task SetPlayedStatus(User user, bool wasPlayed, IUserDataRepository userManager)
  1126. {
  1127. if (user == null)
  1128. {
  1129. throw new ArgumentNullException();
  1130. }
  1131. var key = GetUserDataKey();
  1132. var data = await userManager.GetUserData(user.Id, key).ConfigureAwait(false);
  1133. if (wasPlayed)
  1134. {
  1135. data.PlayCount = Math.Max(data.PlayCount, 1);
  1136. if (!data.LastPlayedDate.HasValue)
  1137. {
  1138. data.LastPlayedDate = DateTime.UtcNow;
  1139. }
  1140. }
  1141. else
  1142. {
  1143. //I think it is okay to do this here.
  1144. // if this is only called when a user is manually forcing something to un-played
  1145. // then it probably is what we want to do...
  1146. data.PlayCount = 0;
  1147. data.PlaybackPositionTicks = 0;
  1148. data.LastPlayedDate = null;
  1149. }
  1150. data.Played = wasPlayed;
  1151. await userManager.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  1152. }
  1153. /// <summary>
  1154. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1155. /// </summary>
  1156. /// <returns>Task.</returns>
  1157. public virtual Task ChangedExternally()
  1158. {
  1159. return RefreshMetadata(CancellationToken.None);
  1160. }
  1161. /// <summary>
  1162. /// Finds a parent of a given type
  1163. /// </summary>
  1164. /// <typeparam name="T"></typeparam>
  1165. /// <returns>``0.</returns>
  1166. public T FindParent<T>()
  1167. where T : Folder
  1168. {
  1169. var parent = Parent;
  1170. while (parent != null)
  1171. {
  1172. var result = parent as T;
  1173. if (result != null)
  1174. {
  1175. return result;
  1176. }
  1177. parent = parent.Parent;
  1178. }
  1179. return null;
  1180. }
  1181. /// <summary>
  1182. /// Gets an image
  1183. /// </summary>
  1184. /// <param name="type">The type.</param>
  1185. /// <returns>System.String.</returns>
  1186. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1187. public string GetImage(ImageType type)
  1188. {
  1189. if (type == ImageType.Backdrop)
  1190. {
  1191. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1192. }
  1193. if (type == ImageType.Screenshot)
  1194. {
  1195. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1196. }
  1197. if (Images == null)
  1198. {
  1199. return null;
  1200. }
  1201. string val;
  1202. Images.TryGetValue(type, out val);
  1203. return val;
  1204. }
  1205. /// <summary>
  1206. /// Gets an image
  1207. /// </summary>
  1208. /// <param name="type">The type.</param>
  1209. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1210. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1211. public bool HasImage(ImageType type)
  1212. {
  1213. if (type == ImageType.Backdrop)
  1214. {
  1215. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1216. }
  1217. if (type == ImageType.Screenshot)
  1218. {
  1219. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1220. }
  1221. return !string.IsNullOrEmpty(GetImage(type));
  1222. }
  1223. /// <summary>
  1224. /// Sets an image
  1225. /// </summary>
  1226. /// <param name="type">The type.</param>
  1227. /// <param name="path">The path.</param>
  1228. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1229. public void SetImage(ImageType type, string path)
  1230. {
  1231. if (type == ImageType.Backdrop)
  1232. {
  1233. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1234. }
  1235. if (type == ImageType.Screenshot)
  1236. {
  1237. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1238. }
  1239. var typeKey = type;
  1240. // If it's null remove the key from the dictionary
  1241. if (string.IsNullOrEmpty(path))
  1242. {
  1243. if (Images != null)
  1244. {
  1245. if (Images.ContainsKey(typeKey))
  1246. {
  1247. Images.Remove(typeKey);
  1248. }
  1249. }
  1250. }
  1251. else
  1252. {
  1253. // Ensure it exists
  1254. if (Images == null)
  1255. {
  1256. Images = new Dictionary<ImageType, string>();
  1257. }
  1258. Images[typeKey] = path;
  1259. }
  1260. }
  1261. /// <summary>
  1262. /// Deletes the image.
  1263. /// </summary>
  1264. /// <param name="type">The type.</param>
  1265. /// <returns>Task.</returns>
  1266. public async Task DeleteImage(ImageType type)
  1267. {
  1268. if (!HasImage(type))
  1269. {
  1270. return;
  1271. }
  1272. // Delete the source file
  1273. File.Delete(GetImage(type));
  1274. // Remove it from the item
  1275. SetImage(type, null);
  1276. // Refresh metadata
  1277. await RefreshMetadata(CancellationToken.None).ConfigureAwait(false);
  1278. }
  1279. }
  1280. }