BaseItem.cs 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440
  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. public void AddTag(string name)
  977. {
  978. if (string.IsNullOrWhiteSpace(name))
  979. {
  980. throw new ArgumentNullException("name");
  981. }
  982. if (!Tags.Contains(name, StringComparer.OrdinalIgnoreCase))
  983. {
  984. Tags.Add(name);
  985. }
  986. }
  987. /// <summary>
  988. /// Adds a tagline to the item
  989. /// </summary>
  990. /// <param name="name">The name.</param>
  991. /// <exception cref="System.ArgumentNullException"></exception>
  992. public void AddTagline(string name)
  993. {
  994. if (string.IsNullOrWhiteSpace(name))
  995. {
  996. throw new ArgumentNullException("name");
  997. }
  998. if (!Taglines.Contains(name, StringComparer.OrdinalIgnoreCase))
  999. {
  1000. Taglines.Add(name);
  1001. }
  1002. }
  1003. /// <summary>
  1004. /// Adds a TrailerUrl to the item
  1005. /// </summary>
  1006. /// <param name="url">The URL.</param>
  1007. /// <exception cref="System.ArgumentNullException"></exception>
  1008. public void AddTrailerUrl(string url)
  1009. {
  1010. if (string.IsNullOrWhiteSpace(url))
  1011. {
  1012. throw new ArgumentNullException("url");
  1013. }
  1014. if (TrailerUrls == null)
  1015. {
  1016. TrailerUrls = new List<string>();
  1017. }
  1018. if (!TrailerUrls.Contains(url, StringComparer.OrdinalIgnoreCase))
  1019. {
  1020. TrailerUrls.Add(url);
  1021. }
  1022. }
  1023. /// <summary>
  1024. /// Adds a genre to the item
  1025. /// </summary>
  1026. /// <param name="name">The name.</param>
  1027. /// <exception cref="System.ArgumentNullException"></exception>
  1028. public void AddGenre(string name)
  1029. {
  1030. if (string.IsNullOrWhiteSpace(name))
  1031. {
  1032. throw new ArgumentNullException("name");
  1033. }
  1034. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1035. {
  1036. Genres.Add(name);
  1037. }
  1038. }
  1039. /// <summary>
  1040. /// Adds the production location.
  1041. /// </summary>
  1042. /// <param name="location">The location.</param>
  1043. /// <exception cref="System.ArgumentNullException">location</exception>
  1044. public void AddProductionLocation(string location)
  1045. {
  1046. if (string.IsNullOrWhiteSpace(location))
  1047. {
  1048. throw new ArgumentNullException("location");
  1049. }
  1050. if (ProductionLocations == null)
  1051. {
  1052. ProductionLocations = new List<string>();
  1053. }
  1054. if (!ProductionLocations.Contains(location, StringComparer.OrdinalIgnoreCase))
  1055. {
  1056. ProductionLocations.Add(location);
  1057. }
  1058. }
  1059. /// <summary>
  1060. /// Marks the item as either played or unplayed
  1061. /// </summary>
  1062. /// <param name="user">The user.</param>
  1063. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  1064. /// <param name="userManager">The user manager.</param>
  1065. /// <returns>Task.</returns>
  1066. /// <exception cref="System.ArgumentNullException"></exception>
  1067. public virtual async Task SetPlayedStatus(User user, bool wasPlayed, IUserDataRepository userManager)
  1068. {
  1069. if (user == null)
  1070. {
  1071. throw new ArgumentNullException();
  1072. }
  1073. var key = GetUserDataKey();
  1074. var data = userManager.GetUserData(user.Id, key);
  1075. if (wasPlayed)
  1076. {
  1077. data.PlayCount = Math.Max(data.PlayCount, 1);
  1078. if (!data.LastPlayedDate.HasValue)
  1079. {
  1080. data.LastPlayedDate = DateTime.UtcNow;
  1081. }
  1082. }
  1083. else
  1084. {
  1085. //I think it is okay to do this here.
  1086. // if this is only called when a user is manually forcing something to un-played
  1087. // then it probably is what we want to do...
  1088. data.PlayCount = 0;
  1089. data.PlaybackPositionTicks = 0;
  1090. data.LastPlayedDate = null;
  1091. }
  1092. data.Played = wasPlayed;
  1093. await userManager.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  1094. }
  1095. /// <summary>
  1096. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1097. /// </summary>
  1098. /// <returns>Task.</returns>
  1099. public virtual Task ChangedExternally()
  1100. {
  1101. return RefreshMetadata(CancellationToken.None);
  1102. }
  1103. /// <summary>
  1104. /// Finds a parent of a given type
  1105. /// </summary>
  1106. /// <typeparam name="T"></typeparam>
  1107. /// <returns>``0.</returns>
  1108. public T FindParent<T>()
  1109. where T : Folder
  1110. {
  1111. var parent = Parent;
  1112. while (parent != null)
  1113. {
  1114. var result = parent as T;
  1115. if (result != null)
  1116. {
  1117. return result;
  1118. }
  1119. parent = parent.Parent;
  1120. }
  1121. return null;
  1122. }
  1123. /// <summary>
  1124. /// Gets an image
  1125. /// </summary>
  1126. /// <param name="type">The type.</param>
  1127. /// <returns>System.String.</returns>
  1128. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1129. public string GetImage(ImageType type)
  1130. {
  1131. if (type == ImageType.Backdrop)
  1132. {
  1133. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1134. }
  1135. if (type == ImageType.Screenshot)
  1136. {
  1137. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1138. }
  1139. string val;
  1140. Images.TryGetValue(type, out val);
  1141. return val;
  1142. }
  1143. /// <summary>
  1144. /// Gets an image
  1145. /// </summary>
  1146. /// <param name="type">The type.</param>
  1147. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1148. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1149. public bool HasImage(ImageType type)
  1150. {
  1151. if (type == ImageType.Backdrop)
  1152. {
  1153. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1154. }
  1155. if (type == ImageType.Screenshot)
  1156. {
  1157. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1158. }
  1159. return !string.IsNullOrEmpty(GetImage(type));
  1160. }
  1161. /// <summary>
  1162. /// Sets an image
  1163. /// </summary>
  1164. /// <param name="type">The type.</param>
  1165. /// <param name="path">The path.</param>
  1166. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1167. public void SetImage(ImageType type, string path)
  1168. {
  1169. if (type == ImageType.Backdrop)
  1170. {
  1171. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1172. }
  1173. if (type == ImageType.Screenshot)
  1174. {
  1175. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1176. }
  1177. var typeKey = type;
  1178. // If it's null remove the key from the dictionary
  1179. if (string.IsNullOrEmpty(path))
  1180. {
  1181. if (Images.ContainsKey(typeKey))
  1182. {
  1183. Images.Remove(typeKey);
  1184. }
  1185. }
  1186. else
  1187. {
  1188. Images[typeKey] = path;
  1189. }
  1190. }
  1191. /// <summary>
  1192. /// Deletes the image.
  1193. /// </summary>
  1194. /// <param name="type">The type.</param>
  1195. /// <param name="index">The index.</param>
  1196. /// <returns>Task.</returns>
  1197. public Task DeleteImage(ImageType type, int? index)
  1198. {
  1199. if (type == ImageType.Backdrop)
  1200. {
  1201. if (!index.HasValue)
  1202. {
  1203. throw new ArgumentException("Please specify a backdrop image index to delete.");
  1204. }
  1205. var file = BackdropImagePaths[index.Value];
  1206. BackdropImagePaths.Remove(file);
  1207. // Delete the source file
  1208. File.Delete(file);
  1209. }
  1210. else if (type == ImageType.Screenshot)
  1211. {
  1212. if (!index.HasValue)
  1213. {
  1214. throw new ArgumentException("Please specify a screenshot image index to delete.");
  1215. }
  1216. var file = ScreenshotImagePaths[index.Value];
  1217. ScreenshotImagePaths.Remove(file);
  1218. // Delete the source file
  1219. File.Delete(file);
  1220. }
  1221. else
  1222. {
  1223. // Delete the source file
  1224. File.Delete(GetImage(type));
  1225. // Remove it from the item
  1226. SetImage(type, null);
  1227. }
  1228. // Refresh metadata
  1229. return RefreshMetadata(CancellationToken.None, forceSave: true);
  1230. }
  1231. }
  1232. }