BaseItem.cs 51 KB

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