BaseItem.cs 51 KB

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