BaseItem.cs 50 KB

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