BaseItem.cs 50 KB

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