BaseItem.cs 51 KB

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