BaseItem.cs 50 KB

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