BaseItem.cs 50 KB

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