BaseItem.cs 50 KB

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