BaseItem.cs 51 KB

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