BaseItem.cs 49 KB

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