BaseItem.cs 50 KB

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