BaseItem.cs 49 KB

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