BaseItem.cs 50 KB

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