BaseItem.cs 51 KB

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