2
0

BaseItem.cs 49 KB

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