BaseItem.cs 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  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 official rating description.
  411. /// </summary>
  412. /// <value>The official rating description.</value>
  413. public string OfficialRatingDescription { get; set; }
  414. /// <summary>
  415. /// Gets or sets the custom rating.
  416. /// </summary>
  417. /// <value>The custom rating.</value>
  418. public virtual string CustomRating { get; set; }
  419. /// <summary>
  420. /// Gets or sets the language.
  421. /// </summary>
  422. /// <value>The language.</value>
  423. public string Language { get; set; }
  424. /// <summary>
  425. /// Gets or sets the overview.
  426. /// </summary>
  427. /// <value>The overview.</value>
  428. public string Overview { get; set; }
  429. /// <summary>
  430. /// Gets or sets the taglines.
  431. /// </summary>
  432. /// <value>The taglines.</value>
  433. public List<string> Taglines { get; set; }
  434. /// <summary>
  435. /// Gets or sets the people.
  436. /// </summary>
  437. /// <value>The people.</value>
  438. public List<PersonInfo> People { get; set; }
  439. /// <summary>
  440. /// Gets or sets the tags.
  441. /// </summary>
  442. /// <value>The tags.</value>
  443. public List<string> Tags { get; set; }
  444. /// <summary>
  445. /// Override this if you need to combine/collapse person information
  446. /// </summary>
  447. /// <value>All people.</value>
  448. [IgnoreDataMember]
  449. public virtual IEnumerable<PersonInfo> AllPeople
  450. {
  451. get { return People; }
  452. }
  453. /// <summary>
  454. /// Gets or sets the studios.
  455. /// </summary>
  456. /// <value>The studios.</value>
  457. public virtual List<string> Studios { get; set; }
  458. /// <summary>
  459. /// Gets or sets the genres.
  460. /// </summary>
  461. /// <value>The genres.</value>
  462. public virtual List<string> Genres { get; set; }
  463. /// <summary>
  464. /// Gets or sets the home page URL.
  465. /// </summary>
  466. /// <value>The home page URL.</value>
  467. public string HomePageUrl { get; set; }
  468. /// <summary>
  469. /// Gets or sets the budget.
  470. /// </summary>
  471. /// <value>The budget.</value>
  472. public double? Budget { get; set; }
  473. /// <summary>
  474. /// Gets or sets the revenue.
  475. /// </summary>
  476. /// <value>The revenue.</value>
  477. public double? Revenue { get; set; }
  478. /// <summary>
  479. /// Gets or sets the production locations.
  480. /// </summary>
  481. /// <value>The production locations.</value>
  482. public List<string> ProductionLocations { get; set; }
  483. /// <summary>
  484. /// Gets or sets the critic rating.
  485. /// </summary>
  486. /// <value>The critic rating.</value>
  487. public float? CriticRating { get; set; }
  488. /// <summary>
  489. /// Gets or sets the critic rating summary.
  490. /// </summary>
  491. /// <value>The critic rating summary.</value>
  492. public string CriticRatingSummary { get; set; }
  493. /// <summary>
  494. /// Gets or sets the community rating.
  495. /// </summary>
  496. /// <value>The community rating.</value>
  497. public float? CommunityRating { get; set; }
  498. /// <summary>
  499. /// Gets or sets the run time ticks.
  500. /// </summary>
  501. /// <value>The run time ticks.</value>
  502. public long? RunTimeTicks { get; set; }
  503. /// <summary>
  504. /// Gets or sets the original run time ticks.
  505. /// </summary>
  506. /// <value>The original run time ticks.</value>
  507. public long? OriginalRunTimeTicks { get; set; }
  508. /// <summary>
  509. /// Gets or sets the aspect ratio.
  510. /// </summary>
  511. /// <value>The aspect ratio.</value>
  512. public string AspectRatio { get; set; }
  513. /// <summary>
  514. /// Gets or sets the production year.
  515. /// </summary>
  516. /// <value>The production year.</value>
  517. public virtual int? ProductionYear { get; set; }
  518. /// <summary>
  519. /// If the item is part of a series, this is it's number in the series.
  520. /// This could be episode number, album track number, etc.
  521. /// </summary>
  522. /// <value>The index number.</value>
  523. public int? IndexNumber { get; set; }
  524. /// <summary>
  525. /// For an episode this could be the season number, or for a song this could be the disc number.
  526. /// </summary>
  527. /// <value>The parent index number.</value>
  528. public int? ParentIndexNumber { get; set; }
  529. public List<Guid> ThemeSongIds { get; set; }
  530. public List<Guid> ThemeVideoIds { get; set; }
  531. public List<Guid> LocalTrailerIds { get; set; }
  532. /// <summary>
  533. /// Loads local trailers from the file system
  534. /// </summary>
  535. /// <returns>List{Video}.</returns>
  536. private IEnumerable<Trailer> LoadLocalTrailers()
  537. {
  538. ItemResolveArgs resolveArgs;
  539. try
  540. {
  541. resolveArgs = ResolveArgs;
  542. }
  543. catch (IOException ex)
  544. {
  545. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  546. return new List<Trailer>();
  547. }
  548. if (!resolveArgs.IsDirectory)
  549. {
  550. return new List<Trailer>();
  551. }
  552. var files = new List<FileSystemInfo>();
  553. var folder = resolveArgs.GetFileSystemEntryByName(TrailerFolderName);
  554. // Path doesn't exist. No biggie
  555. if (folder != null)
  556. {
  557. try
  558. {
  559. files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  560. }
  561. catch (IOException ex)
  562. {
  563. Logger.ErrorException("Error loading trailers for {0}", ex, Name);
  564. }
  565. }
  566. // Support xbmc trailers (-trailer suffix on video file names)
  567. files.AddRange(resolveArgs.FileSystemChildren.Where(i =>
  568. {
  569. if ((i.Attributes & FileAttributes.Directory) != FileAttributes.Directory)
  570. {
  571. if (System.IO.Path.GetFileNameWithoutExtension(i.Name).EndsWith(XbmcTrailerFileSuffix, StringComparison.OrdinalIgnoreCase) && !string.Equals(Path, i.FullName, StringComparison.OrdinalIgnoreCase))
  572. {
  573. return true;
  574. }
  575. }
  576. return false;
  577. }));
  578. return LibraryManager.ResolvePaths<Trailer>(files, null).Select(video =>
  579. {
  580. // Try to retrieve it from the db. If we don't find it, use the resolved version
  581. var dbItem = LibraryManager.RetrieveItem(video.Id, typeof(Trailer)) as Trailer;
  582. if (dbItem != null)
  583. {
  584. dbItem.ResolveArgs = video.ResolveArgs;
  585. video = dbItem;
  586. }
  587. return video;
  588. }).ToList();
  589. }
  590. /// <summary>
  591. /// Loads the theme songs.
  592. /// </summary>
  593. /// <returns>List{Audio.Audio}.</returns>
  594. private IEnumerable<Audio.Audio> LoadThemeSongs()
  595. {
  596. ItemResolveArgs resolveArgs;
  597. try
  598. {
  599. resolveArgs = ResolveArgs;
  600. }
  601. catch (IOException ex)
  602. {
  603. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  604. return new List<Audio.Audio>();
  605. }
  606. if (!resolveArgs.IsDirectory)
  607. {
  608. return new List<Audio.Audio>();
  609. }
  610. var files = new List<FileSystemInfo>();
  611. var folder = resolveArgs.GetFileSystemEntryByName(ThemeSongsFolderName);
  612. // Path doesn't exist. No biggie
  613. if (folder != null)
  614. {
  615. try
  616. {
  617. files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  618. }
  619. catch (IOException ex)
  620. {
  621. Logger.ErrorException("Error loading theme songs for {0}", ex, Name);
  622. }
  623. }
  624. // Support plex/xbmc convention
  625. files.AddRange(resolveArgs.FileSystemChildren
  626. .Where(i => string.Equals(System.IO.Path.GetFileNameWithoutExtension(i.Name), ThemeSongFilename, StringComparison.OrdinalIgnoreCase) && EntityResolutionHelper.IsAudioFile(i.Name))
  627. );
  628. return LibraryManager.ResolvePaths<Audio.Audio>(files, null).Select(audio =>
  629. {
  630. // Try to retrieve it from the db. If we don't find it, use the resolved version
  631. var dbItem = LibraryManager.RetrieveItem(audio.Id, typeof(Audio.Audio)) as Audio.Audio;
  632. if (dbItem != null)
  633. {
  634. dbItem.ResolveArgs = audio.ResolveArgs;
  635. audio = dbItem;
  636. }
  637. return audio;
  638. }).ToList();
  639. }
  640. /// <summary>
  641. /// Loads the video backdrops.
  642. /// </summary>
  643. /// <returns>List{Video}.</returns>
  644. private IEnumerable<Video> LoadThemeVideos()
  645. {
  646. ItemResolveArgs resolveArgs;
  647. try
  648. {
  649. resolveArgs = ResolveArgs;
  650. }
  651. catch (IOException ex)
  652. {
  653. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  654. return new List<Video>();
  655. }
  656. if (!resolveArgs.IsDirectory)
  657. {
  658. return new List<Video>();
  659. }
  660. var folder = resolveArgs.GetFileSystemEntryByName(ThemeVideosFolderName);
  661. // Path doesn't exist. No biggie
  662. if (folder == null)
  663. {
  664. return new List<Video>();
  665. }
  666. IEnumerable<FileSystemInfo> files;
  667. try
  668. {
  669. files = new DirectoryInfo(folder.FullName).EnumerateFiles();
  670. }
  671. catch (IOException ex)
  672. {
  673. Logger.ErrorException("Error loading video backdrops for {0}", ex, Name);
  674. return new List<Video>();
  675. }
  676. return LibraryManager.ResolvePaths<Video>(files, null).Select(item =>
  677. {
  678. // Try to retrieve it from the db. If we don't find it, use the resolved version
  679. var dbItem = LibraryManager.RetrieveItem(item.Id, typeof(Video)) as Video;
  680. if (dbItem != null)
  681. {
  682. dbItem.ResolveArgs = item.ResolveArgs;
  683. item = dbItem;
  684. }
  685. return item;
  686. }).ToList();
  687. }
  688. /// <summary>
  689. /// Overrides the base implementation to refresh metadata for local trailers
  690. /// </summary>
  691. /// <param name="cancellationToken">The cancellation token.</param>
  692. /// <param name="forceSave">if set to <c>true</c> [is new item].</param>
  693. /// <param name="forceRefresh">if set to <c>true</c> [force].</param>
  694. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  695. /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param>
  696. /// <returns>true if a provider reports we changed</returns>
  697. public virtual async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  698. {
  699. if (resetResolveArgs)
  700. {
  701. // Reload this
  702. ResolveArgs = null;
  703. }
  704. // Refresh for the item
  705. var itemRefreshTask = ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh, allowSlowProviders);
  706. cancellationToken.ThrowIfCancellationRequested();
  707. var themeSongsChanged = false;
  708. var themeVideosChanged = false;
  709. var localTrailersChanged = false;
  710. if (LocationType == LocationType.FileSystem && Parent != null)
  711. {
  712. themeSongsChanged = await RefreshThemeSongs(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  713. themeVideosChanged = await RefreshThemeVideos(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  714. localTrailersChanged = await RefreshLocalTrailers(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  715. }
  716. cancellationToken.ThrowIfCancellationRequested();
  717. // Get the result from the item task
  718. var changed = await itemRefreshTask.ConfigureAwait(false);
  719. if (changed || forceSave || themeSongsChanged || themeVideosChanged || localTrailersChanged)
  720. {
  721. cancellationToken.ThrowIfCancellationRequested();
  722. await LibraryManager.UpdateItem(this, cancellationToken).ConfigureAwait(false);
  723. }
  724. return changed;
  725. }
  726. private async Task<bool> RefreshLocalTrailers(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  727. {
  728. var newItems = LoadLocalTrailers().ToList();
  729. var newItemIds = newItems.Select(i => i.Id).ToList();
  730. var itemsChanged = !LocalTrailerIds.SequenceEqual(newItemIds);
  731. var tasks = newItems.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  732. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  733. LocalTrailerIds = newItemIds;
  734. return itemsChanged || results.Contains(true);
  735. }
  736. private async Task<bool> RefreshThemeVideos(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  737. {
  738. var newThemeVideos = LoadThemeVideos().ToList();
  739. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  740. var themeVideosChanged = !ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  741. var tasks = newThemeVideos.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  742. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  743. ThemeVideoIds = newThemeVideoIds;
  744. return themeVideosChanged || results.Contains(true);
  745. }
  746. /// <summary>
  747. /// Refreshes the theme songs.
  748. /// </summary>
  749. private async Task<bool> RefreshThemeSongs(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  750. {
  751. var newThemeSongs = LoadThemeSongs().ToList();
  752. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  753. var themeSongsChanged = !ThemeSongIds.SequenceEqual(newThemeSongIds);
  754. var tasks = newThemeSongs.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  755. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  756. ThemeSongIds = newThemeSongIds;
  757. return themeSongsChanged || results.Contains(true);
  758. }
  759. /// <summary>
  760. /// Gets or sets the trailer URL.
  761. /// </summary>
  762. /// <value>The trailer URL.</value>
  763. public List<string> TrailerUrls { get; set; }
  764. /// <summary>
  765. /// Gets or sets the provider ids.
  766. /// </summary>
  767. /// <value>The provider ids.</value>
  768. public Dictionary<string, string> ProviderIds { get; set; }
  769. /// <summary>
  770. /// Override this to false if class should be ignored for indexing purposes
  771. /// </summary>
  772. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  773. [IgnoreDataMember]
  774. public virtual bool IncludeInIndex
  775. {
  776. get { return true; }
  777. }
  778. /// <summary>
  779. /// Override this to true if class should be grouped under a container in indicies
  780. /// The container class should be defined via IndexContainer
  781. /// </summary>
  782. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  783. [IgnoreDataMember]
  784. public virtual bool GroupInIndex
  785. {
  786. get { return false; }
  787. }
  788. /// <summary>
  789. /// Override this to return the folder that should be used to construct a container
  790. /// for this item in an index. GroupInIndex should be true as well.
  791. /// </summary>
  792. /// <value>The index container.</value>
  793. [IgnoreDataMember]
  794. public virtual Folder IndexContainer
  795. {
  796. get { return null; }
  797. }
  798. /// <summary>
  799. /// Gets the user data key.
  800. /// </summary>
  801. /// <returns>System.String.</returns>
  802. public virtual string GetUserDataKey()
  803. {
  804. return Id.ToString();
  805. }
  806. /// <summary>
  807. /// Determines if a given user has access to this item
  808. /// </summary>
  809. /// <param name="user">The user.</param>
  810. /// <param name="localizationManager">The localization manager.</param>
  811. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  812. /// <exception cref="System.ArgumentNullException">user</exception>
  813. public bool IsParentalAllowed(User user, ILocalizationManager localizationManager)
  814. {
  815. if (user == null)
  816. {
  817. throw new ArgumentNullException("user");
  818. }
  819. if (user.Configuration.MaxParentalRating == null)
  820. {
  821. return true;
  822. }
  823. var rating = CustomRating ?? OfficialRating;
  824. if (string.IsNullOrEmpty(rating))
  825. {
  826. return !user.Configuration.BlockNotRated;
  827. }
  828. var value = localizationManager.GetRatingLevel(rating);
  829. // Could not determine the integer value
  830. if (!value.HasValue)
  831. {
  832. return true;
  833. }
  834. return value.Value <= user.Configuration.MaxParentalRating.Value;
  835. }
  836. /// <summary>
  837. /// Determines if this folder should be visible to a given user.
  838. /// Default is just parental allowed. Can be overridden for more functionality.
  839. /// </summary>
  840. /// <param name="user">The user.</param>
  841. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  842. /// <exception cref="System.ArgumentNullException">user</exception>
  843. public virtual bool IsVisible(User user)
  844. {
  845. if (user == null)
  846. {
  847. throw new ArgumentNullException("user");
  848. }
  849. return IsParentalAllowed(user, LocalizationManager);
  850. }
  851. /// <summary>
  852. /// Finds the particular item by searching through our parents and, if not found there, loading from repo
  853. /// </summary>
  854. /// <param name="id">The id.</param>
  855. /// <returns>BaseItem.</returns>
  856. /// <exception cref="System.ArgumentException"></exception>
  857. protected BaseItem FindParentItem(Guid id)
  858. {
  859. if (id == Guid.Empty)
  860. {
  861. throw new ArgumentException();
  862. }
  863. var parent = Parent;
  864. while (parent != null && !parent.IsRoot)
  865. {
  866. if (parent.Id == id) return parent;
  867. parent = parent.Parent;
  868. }
  869. return null;
  870. }
  871. /// <summary>
  872. /// Gets a value indicating whether this instance is folder.
  873. /// </summary>
  874. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  875. [IgnoreDataMember]
  876. public virtual bool IsFolder
  877. {
  878. get
  879. {
  880. return false;
  881. }
  882. }
  883. /// <summary>
  884. /// Determine if we have changed vs the passed in copy
  885. /// </summary>
  886. /// <param name="copy">The copy.</param>
  887. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  888. /// <exception cref="System.ArgumentNullException"></exception>
  889. public virtual bool HasChanged(BaseItem copy)
  890. {
  891. if (copy == null)
  892. {
  893. throw new ArgumentNullException();
  894. }
  895. var changed = copy.DateModified != DateModified;
  896. if (changed)
  897. {
  898. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  899. }
  900. return changed;
  901. }
  902. /// <summary>
  903. /// Determines if the item is considered new based on user settings
  904. /// </summary>
  905. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  906. /// <exception cref="System.ArgumentNullException"></exception>
  907. public bool IsRecentlyAdded()
  908. {
  909. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  910. }
  911. /// <summary>
  912. /// Adds a person to the item
  913. /// </summary>
  914. /// <param name="person">The person.</param>
  915. /// <exception cref="System.ArgumentNullException"></exception>
  916. public void AddPerson(PersonInfo person)
  917. {
  918. if (person == null)
  919. {
  920. throw new ArgumentNullException("person");
  921. }
  922. if (string.IsNullOrWhiteSpace(person.Name))
  923. {
  924. throw new ArgumentNullException();
  925. }
  926. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  927. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  928. {
  929. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  930. if (existing != null)
  931. {
  932. existing.Type = PersonType.GuestStar;
  933. return;
  934. }
  935. }
  936. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  937. {
  938. // If the actor already exists without a role and we have one, fill it in
  939. 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)));
  940. if (existing == null)
  941. {
  942. // Wasn't there - add it
  943. People.Add(person);
  944. }
  945. else
  946. {
  947. // Was there, if no role and we have one - fill it in
  948. if (string.IsNullOrWhiteSpace(existing.Role) && !string.IsNullOrWhiteSpace(person.Role)) existing.Role = person.Role;
  949. }
  950. }
  951. else
  952. {
  953. // Check for dupes based on the combination of Name and Type
  954. if (!People.Any(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(person.Type, StringComparison.OrdinalIgnoreCase)))
  955. {
  956. People.Add(person);
  957. }
  958. }
  959. }
  960. /// <summary>
  961. /// Adds a studio to the item
  962. /// </summary>
  963. /// <param name="name">The name.</param>
  964. /// <exception cref="System.ArgumentNullException"></exception>
  965. public void AddStudio(string name)
  966. {
  967. if (string.IsNullOrWhiteSpace(name))
  968. {
  969. throw new ArgumentNullException("name");
  970. }
  971. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  972. {
  973. Studios.Add(name);
  974. }
  975. }
  976. /// <summary>
  977. /// Adds a tagline to the item
  978. /// </summary>
  979. /// <param name="name">The name.</param>
  980. /// <exception cref="System.ArgumentNullException"></exception>
  981. public void AddTagline(string name)
  982. {
  983. if (string.IsNullOrWhiteSpace(name))
  984. {
  985. throw new ArgumentNullException("name");
  986. }
  987. if (!Taglines.Contains(name, StringComparer.OrdinalIgnoreCase))
  988. {
  989. Taglines.Add(name);
  990. }
  991. }
  992. /// <summary>
  993. /// Adds a TrailerUrl to the item
  994. /// </summary>
  995. /// <param name="url">The URL.</param>
  996. /// <exception cref="System.ArgumentNullException"></exception>
  997. public void AddTrailerUrl(string url)
  998. {
  999. if (string.IsNullOrWhiteSpace(url))
  1000. {
  1001. throw new ArgumentNullException("url");
  1002. }
  1003. if (TrailerUrls == null)
  1004. {
  1005. TrailerUrls = new List<string>();
  1006. }
  1007. if (!TrailerUrls.Contains(url, StringComparer.OrdinalIgnoreCase))
  1008. {
  1009. TrailerUrls.Add(url);
  1010. }
  1011. }
  1012. /// <summary>
  1013. /// Adds a genre to the item
  1014. /// </summary>
  1015. /// <param name="name">The name.</param>
  1016. /// <exception cref="System.ArgumentNullException"></exception>
  1017. public void AddGenre(string name)
  1018. {
  1019. if (string.IsNullOrWhiteSpace(name))
  1020. {
  1021. throw new ArgumentNullException("name");
  1022. }
  1023. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1024. {
  1025. Genres.Add(name);
  1026. }
  1027. }
  1028. /// <summary>
  1029. /// Adds the production location.
  1030. /// </summary>
  1031. /// <param name="location">The location.</param>
  1032. /// <exception cref="System.ArgumentNullException">location</exception>
  1033. public void AddProductionLocation(string location)
  1034. {
  1035. if (string.IsNullOrWhiteSpace(location))
  1036. {
  1037. throw new ArgumentNullException("location");
  1038. }
  1039. if (ProductionLocations == null)
  1040. {
  1041. ProductionLocations = new List<string>();
  1042. }
  1043. if (!ProductionLocations.Contains(location, StringComparer.OrdinalIgnoreCase))
  1044. {
  1045. ProductionLocations.Add(location);
  1046. }
  1047. }
  1048. /// <summary>
  1049. /// Marks the item as either played or unplayed
  1050. /// </summary>
  1051. /// <param name="user">The user.</param>
  1052. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  1053. /// <param name="userManager">The user manager.</param>
  1054. /// <returns>Task.</returns>
  1055. /// <exception cref="System.ArgumentNullException"></exception>
  1056. public virtual async Task SetPlayedStatus(User user, bool wasPlayed, IUserDataRepository userManager)
  1057. {
  1058. if (user == null)
  1059. {
  1060. throw new ArgumentNullException();
  1061. }
  1062. var key = GetUserDataKey();
  1063. var data = userManager.GetUserData(user.Id, key);
  1064. if (wasPlayed)
  1065. {
  1066. data.PlayCount = Math.Max(data.PlayCount, 1);
  1067. if (!data.LastPlayedDate.HasValue)
  1068. {
  1069. data.LastPlayedDate = DateTime.UtcNow;
  1070. }
  1071. }
  1072. else
  1073. {
  1074. //I think it is okay to do this here.
  1075. // if this is only called when a user is manually forcing something to un-played
  1076. // then it probably is what we want to do...
  1077. data.PlayCount = 0;
  1078. data.PlaybackPositionTicks = 0;
  1079. data.LastPlayedDate = null;
  1080. }
  1081. data.Played = wasPlayed;
  1082. await userManager.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  1083. }
  1084. /// <summary>
  1085. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1086. /// </summary>
  1087. /// <returns>Task.</returns>
  1088. public virtual Task ChangedExternally()
  1089. {
  1090. return RefreshMetadata(CancellationToken.None);
  1091. }
  1092. /// <summary>
  1093. /// Finds a parent of a given type
  1094. /// </summary>
  1095. /// <typeparam name="T"></typeparam>
  1096. /// <returns>``0.</returns>
  1097. public T FindParent<T>()
  1098. where T : Folder
  1099. {
  1100. var parent = Parent;
  1101. while (parent != null)
  1102. {
  1103. var result = parent as T;
  1104. if (result != null)
  1105. {
  1106. return result;
  1107. }
  1108. parent = parent.Parent;
  1109. }
  1110. return null;
  1111. }
  1112. /// <summary>
  1113. /// Gets an image
  1114. /// </summary>
  1115. /// <param name="type">The type.</param>
  1116. /// <returns>System.String.</returns>
  1117. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1118. public string GetImage(ImageType type)
  1119. {
  1120. if (type == ImageType.Backdrop)
  1121. {
  1122. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1123. }
  1124. if (type == ImageType.Screenshot)
  1125. {
  1126. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1127. }
  1128. string val;
  1129. Images.TryGetValue(type, out val);
  1130. return val;
  1131. }
  1132. /// <summary>
  1133. /// Gets an image
  1134. /// </summary>
  1135. /// <param name="type">The type.</param>
  1136. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1137. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1138. public bool HasImage(ImageType type)
  1139. {
  1140. if (type == ImageType.Backdrop)
  1141. {
  1142. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1143. }
  1144. if (type == ImageType.Screenshot)
  1145. {
  1146. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1147. }
  1148. return !string.IsNullOrEmpty(GetImage(type));
  1149. }
  1150. /// <summary>
  1151. /// Sets an image
  1152. /// </summary>
  1153. /// <param name="type">The type.</param>
  1154. /// <param name="path">The path.</param>
  1155. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1156. public void SetImage(ImageType type, string path)
  1157. {
  1158. if (type == ImageType.Backdrop)
  1159. {
  1160. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1161. }
  1162. if (type == ImageType.Screenshot)
  1163. {
  1164. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1165. }
  1166. var typeKey = type;
  1167. // If it's null remove the key from the dictionary
  1168. if (string.IsNullOrEmpty(path))
  1169. {
  1170. if (Images.ContainsKey(typeKey))
  1171. {
  1172. Images.Remove(typeKey);
  1173. }
  1174. }
  1175. else
  1176. {
  1177. Images[typeKey] = path;
  1178. }
  1179. }
  1180. /// <summary>
  1181. /// Deletes the image.
  1182. /// </summary>
  1183. /// <param name="type">The type.</param>
  1184. /// <param name="index">The index.</param>
  1185. /// <returns>Task.</returns>
  1186. public Task DeleteImage(ImageType type, int? index)
  1187. {
  1188. if (type == ImageType.Backdrop)
  1189. {
  1190. if (!index.HasValue)
  1191. {
  1192. throw new ArgumentException("Please specify a backdrop image index to delete.");
  1193. }
  1194. var file = BackdropImagePaths[index.Value];
  1195. BackdropImagePaths.Remove(file);
  1196. // Delete the source file
  1197. File.Delete(file);
  1198. }
  1199. else if (type == ImageType.Screenshot)
  1200. {
  1201. if (!index.HasValue)
  1202. {
  1203. throw new ArgumentException("Please specify a screenshot image index to delete.");
  1204. }
  1205. var file = ScreenshotImagePaths[index.Value];
  1206. ScreenshotImagePaths.Remove(file);
  1207. // Delete the source file
  1208. File.Delete(file);
  1209. }
  1210. else
  1211. {
  1212. // Delete the source file
  1213. File.Delete(GetImage(type));
  1214. // Remove it from the item
  1215. SetImage(type, null);
  1216. }
  1217. // Refresh metadata
  1218. return RefreshMetadata(CancellationToken.None, forceSave: true);
  1219. }
  1220. }
  1221. }