BaseItem.cs 50 KB

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