BaseItem.cs 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485
  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 virtual string CustomRatingForComparison
  390. {
  391. get { return CustomRating; }
  392. }
  393. /// <summary>
  394. /// Loads local trailers from the file system
  395. /// </summary>
  396. /// <returns>List{Video}.</returns>
  397. private IEnumerable<Trailer> LoadLocalTrailers(List<FileSystemInfo> fileSystemChildren)
  398. {
  399. return new List<Trailer>();
  400. //ItemResolveArgs resolveArgs;
  401. //try
  402. //{
  403. // resolveArgs = ResolveArgs;
  404. // if (!resolveArgs.IsDirectory)
  405. // {
  406. // return new List<Trailer>();
  407. // }
  408. //}
  409. //catch (IOException ex)
  410. //{
  411. // Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  412. // return new List<Trailer>();
  413. //}
  414. //var files = new List<FileSystemInfo>();
  415. //var folder = resolveArgs.GetFileSystemEntryByName(TrailerFolderName);
  416. //// Path doesn't exist. No biggie
  417. //if (folder != null)
  418. //{
  419. // try
  420. // {
  421. // files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  422. // }
  423. // catch (IOException ex)
  424. // {
  425. // Logger.ErrorException("Error loading trailers for {0}", ex, Name);
  426. // }
  427. //}
  428. //// Support xbmc trailers (-trailer suffix on video file names)
  429. //files.AddRange(resolveArgs.FileSystemChildren.Where(i =>
  430. //{
  431. // try
  432. // {
  433. // if ((i.Attributes & FileAttributes.Directory) != FileAttributes.Directory)
  434. // {
  435. // if (System.IO.Path.GetFileNameWithoutExtension(i.Name).EndsWith(XbmcTrailerFileSuffix, StringComparison.OrdinalIgnoreCase) && !string.Equals(Path, i.FullName, StringComparison.OrdinalIgnoreCase))
  436. // {
  437. // return true;
  438. // }
  439. // }
  440. // }
  441. // catch (IOException ex)
  442. // {
  443. // Logger.ErrorException("Error accessing path {0}", ex, i.FullName);
  444. // }
  445. // return false;
  446. //}));
  447. //return LibraryManager.ResolvePaths<Trailer>(files, null).Select(video =>
  448. //{
  449. // // Try to retrieve it from the db. If we don't find it, use the resolved version
  450. // var dbItem = LibraryManager.GetItemById(video.Id) as Trailer;
  451. // if (dbItem != null)
  452. // {
  453. // video = dbItem;
  454. // }
  455. // return video;
  456. //}).ToList();
  457. }
  458. /// <summary>
  459. /// Loads the theme songs.
  460. /// </summary>
  461. /// <returns>List{Audio.Audio}.</returns>
  462. private IEnumerable<Audio.Audio> LoadThemeSongs(List<FileSystemInfo> fileSystemChildren)
  463. {
  464. var files = fileSystemChildren.OfType<DirectoryInfo>()
  465. .Where(i => string.Equals(i.Name, ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase))
  466. .SelectMany(i => i.EnumerateFiles("*", SearchOption.TopDirectoryOnly))
  467. .ToList();
  468. // Support plex/xbmc convention
  469. files.AddRange(fileSystemChildren.OfType<FileInfo>()
  470. .Where(i => string.Equals(System.IO.Path.GetFileNameWithoutExtension(i.Name), ThemeSongFilename, StringComparison.OrdinalIgnoreCase))
  471. );
  472. return LibraryManager.ResolvePaths<Audio.Audio>(files, null).Select(audio =>
  473. {
  474. // Try to retrieve it from the db. If we don't find it, use the resolved version
  475. var dbItem = LibraryManager.GetItemById(audio.Id) as Audio.Audio;
  476. if (dbItem != null)
  477. {
  478. audio = dbItem;
  479. }
  480. return audio;
  481. }).ToList();
  482. }
  483. /// <summary>
  484. /// Loads the video backdrops.
  485. /// </summary>
  486. /// <returns>List{Video}.</returns>
  487. private IEnumerable<Video> LoadThemeVideos(IEnumerable<FileSystemInfo> fileSystemChildren)
  488. {
  489. var files = fileSystemChildren.OfType<DirectoryInfo>()
  490. .Where(i => string.Equals(i.Name, ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase))
  491. .SelectMany(i => i.EnumerateFiles("*", SearchOption.TopDirectoryOnly));
  492. return LibraryManager.ResolvePaths<Video>(files, null).Select(item =>
  493. {
  494. // Try to retrieve it from the db. If we don't find it, use the resolved version
  495. var dbItem = LibraryManager.GetItemById(item.Id) as Video;
  496. if (dbItem != null)
  497. {
  498. item = dbItem;
  499. }
  500. return item;
  501. }).ToList();
  502. }
  503. public Task RefreshMetadata(CancellationToken cancellationToken)
  504. {
  505. return RefreshMetadata(new MetadataRefreshOptions(), cancellationToken);
  506. }
  507. /// <summary>
  508. /// Overrides the base implementation to refresh metadata for local trailers
  509. /// </summary>
  510. /// <param name="options">The options.</param>
  511. /// <param name="cancellationToken">The cancellation token.</param>
  512. /// <returns>true if a provider reports we changed</returns>
  513. public async Task RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
  514. {
  515. var locationType = LocationType;
  516. if (IsFolder || Parent != null)
  517. {
  518. var files = locationType == LocationType.FileSystem || locationType == LocationType.Offline ?
  519. GetFileSystemChildren().ToList() :
  520. new List<FileSystemInfo>();
  521. await BeforeRefreshMetadata(options, files, cancellationToken).ConfigureAwait(false);
  522. }
  523. await ProviderManager.RefreshMetadata(this, options, cancellationToken).ConfigureAwait(false);
  524. }
  525. protected virtual async Task BeforeRefreshMetadata(MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  526. {
  527. var themeSongsChanged = false;
  528. var themeVideosChanged = false;
  529. var localTrailersChanged = false;
  530. if (LocationType == LocationType.FileSystem && Parent != null)
  531. {
  532. var hasThemeMedia = this as IHasThemeMedia;
  533. if (hasThemeMedia != null)
  534. {
  535. if (!IsInMixedFolder)
  536. {
  537. themeSongsChanged = await RefreshThemeSongs(hasThemeMedia, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  538. themeVideosChanged = await RefreshThemeVideos(hasThemeMedia, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  539. }
  540. }
  541. var hasTrailers = this as IHasTrailers;
  542. if (hasTrailers != null)
  543. {
  544. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  545. }
  546. }
  547. if (themeSongsChanged || themeVideosChanged || localTrailersChanged)
  548. {
  549. options.ForceSave = true;
  550. }
  551. }
  552. protected virtual IEnumerable<FileSystemInfo> GetFileSystemChildren()
  553. {
  554. var path = ContainingFolderPath;
  555. return new DirectoryInfo(path).EnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly);
  556. }
  557. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  558. {
  559. var newItems = LoadLocalTrailers(fileSystemChildren).ToList();
  560. var newItemIds = newItems.Select(i => i.Id).ToList();
  561. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  562. var tasks = newItems.Select(i => i.RefreshMetadata(options, cancellationToken));
  563. await Task.WhenAll(tasks).ConfigureAwait(false);
  564. item.LocalTrailerIds = newItemIds;
  565. return itemsChanged;
  566. }
  567. private async Task<bool> RefreshThemeVideos(IHasThemeMedia item, MetadataRefreshOptions options, IEnumerable<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  568. {
  569. var newThemeVideos = LoadThemeVideos(fileSystemChildren).ToList();
  570. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  571. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  572. var tasks = newThemeVideos.Select(i => i.RefreshMetadata(options, cancellationToken));
  573. await Task.WhenAll(tasks).ConfigureAwait(false);
  574. item.ThemeVideoIds = newThemeVideoIds;
  575. return themeVideosChanged;
  576. }
  577. /// <summary>
  578. /// Refreshes the theme songs.
  579. /// </summary>
  580. private async Task<bool> RefreshThemeSongs(IHasThemeMedia item, MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  581. {
  582. var newThemeSongs = LoadThemeSongs(fileSystemChildren).ToList();
  583. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  584. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  585. var tasks = newThemeSongs.Select(i => i.RefreshMetadata(options, cancellationToken));
  586. await Task.WhenAll(tasks).ConfigureAwait(false);
  587. item.ThemeSongIds = newThemeSongIds;
  588. return themeSongsChanged;
  589. }
  590. /// <summary>
  591. /// Gets or sets the provider ids.
  592. /// </summary>
  593. /// <value>The provider ids.</value>
  594. public Dictionary<string, string> ProviderIds { get; set; }
  595. /// <summary>
  596. /// Override this to false if class should be ignored for indexing purposes
  597. /// </summary>
  598. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  599. [IgnoreDataMember]
  600. public virtual bool IncludeInIndex
  601. {
  602. get { return true; }
  603. }
  604. /// <summary>
  605. /// Override this to true if class should be grouped under a container in indicies
  606. /// The container class should be defined via IndexContainer
  607. /// </summary>
  608. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  609. [IgnoreDataMember]
  610. public virtual bool GroupInIndex
  611. {
  612. get { return false; }
  613. }
  614. /// <summary>
  615. /// Override this to return the folder that should be used to construct a container
  616. /// for this item in an index. GroupInIndex should be true as well.
  617. /// </summary>
  618. /// <value>The index container.</value>
  619. [IgnoreDataMember]
  620. public virtual Folder IndexContainer
  621. {
  622. get { return null; }
  623. }
  624. /// <summary>
  625. /// Gets the user data key.
  626. /// </summary>
  627. /// <returns>System.String.</returns>
  628. public virtual string GetUserDataKey()
  629. {
  630. return Id.ToString();
  631. }
  632. /// <summary>
  633. /// Gets the preferred metadata language.
  634. /// </summary>
  635. /// <returns>System.String.</returns>
  636. public string GetPreferredMetadataLanguage()
  637. {
  638. string lang = null;
  639. var hasLang = this as IHasPreferredMetadataLanguage;
  640. if (hasLang != null)
  641. {
  642. lang = hasLang.PreferredMetadataLanguage;
  643. }
  644. if (string.IsNullOrEmpty(lang))
  645. {
  646. lang = Parents.OfType<IHasPreferredMetadataLanguage>()
  647. .Select(i => i.PreferredMetadataLanguage)
  648. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  649. }
  650. if (string.IsNullOrEmpty(lang))
  651. {
  652. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  653. }
  654. return lang;
  655. }
  656. /// <summary>
  657. /// Gets the preferred metadata language.
  658. /// </summary>
  659. /// <returns>System.String.</returns>
  660. public string GetPreferredMetadataCountryCode()
  661. {
  662. string lang = null;
  663. var hasLang = this as IHasPreferredMetadataLanguage;
  664. if (hasLang != null)
  665. {
  666. lang = hasLang.PreferredMetadataCountryCode;
  667. }
  668. if (string.IsNullOrEmpty(lang))
  669. {
  670. lang = Parents.OfType<IHasPreferredMetadataLanguage>()
  671. .Select(i => i.PreferredMetadataCountryCode)
  672. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  673. }
  674. if (string.IsNullOrEmpty(lang))
  675. {
  676. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  677. }
  678. return lang;
  679. }
  680. public virtual bool IsSaveLocalMetadataEnabled()
  681. {
  682. return ConfigurationManager.Configuration.SaveLocalMeta;
  683. }
  684. /// <summary>
  685. /// Determines if a given user has access to this item
  686. /// </summary>
  687. /// <param name="user">The user.</param>
  688. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  689. /// <exception cref="System.ArgumentNullException">user</exception>
  690. public bool IsParentalAllowed(User user)
  691. {
  692. if (user == null)
  693. {
  694. throw new ArgumentNullException("user");
  695. }
  696. var maxAllowedRating = user.Configuration.MaxParentalRating;
  697. if (maxAllowedRating == null)
  698. {
  699. return true;
  700. }
  701. var rating = CustomRatingForComparison;
  702. if (string.IsNullOrEmpty(rating))
  703. {
  704. rating = OfficialRatingForComparison;
  705. }
  706. if (string.IsNullOrEmpty(rating))
  707. {
  708. return !GetBlockUnratedValue(user.Configuration);
  709. }
  710. var value = LocalizationManager.GetRatingLevel(rating);
  711. // Could not determine the integer value
  712. if (!value.HasValue)
  713. {
  714. return true;
  715. }
  716. return value.Value <= maxAllowedRating.Value;
  717. }
  718. /// <summary>
  719. /// Gets the block unrated value.
  720. /// </summary>
  721. /// <param name="config">The configuration.</param>
  722. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  723. protected virtual bool GetBlockUnratedValue(UserConfiguration config)
  724. {
  725. return config.BlockNotRated;
  726. }
  727. /// <summary>
  728. /// Determines if this folder should be visible to a given user.
  729. /// Default is just parental allowed. Can be overridden for more functionality.
  730. /// </summary>
  731. /// <param name="user">The user.</param>
  732. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  733. /// <exception cref="System.ArgumentNullException">user</exception>
  734. public virtual bool IsVisible(User user)
  735. {
  736. if (user == null)
  737. {
  738. throw new ArgumentNullException("user");
  739. }
  740. return IsParentalAllowed(user);
  741. }
  742. /// <summary>
  743. /// Finds the particular item by searching through our parents and, if not found there, loading from repo
  744. /// </summary>
  745. /// <param name="id">The id.</param>
  746. /// <returns>BaseItem.</returns>
  747. /// <exception cref="System.ArgumentException"></exception>
  748. protected BaseItem FindParentItem(Guid id)
  749. {
  750. if (id == Guid.Empty)
  751. {
  752. throw new ArgumentException();
  753. }
  754. var parent = Parent;
  755. while (parent != null && !parent.IsRoot)
  756. {
  757. if (parent.Id == id) return parent;
  758. parent = parent.Parent;
  759. }
  760. return null;
  761. }
  762. /// <summary>
  763. /// Gets a value indicating whether this instance is folder.
  764. /// </summary>
  765. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  766. [IgnoreDataMember]
  767. public virtual bool IsFolder
  768. {
  769. get
  770. {
  771. return false;
  772. }
  773. }
  774. /// <summary>
  775. /// Determine if we have changed vs the passed in copy
  776. /// </summary>
  777. /// <param name="copy">The copy.</param>
  778. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  779. /// <exception cref="System.ArgumentNullException"></exception>
  780. public virtual bool HasChanged(BaseItem copy)
  781. {
  782. if (copy == null)
  783. {
  784. throw new ArgumentNullException();
  785. }
  786. if (IsInMixedFolder != copy.IsInMixedFolder)
  787. {
  788. Logger.Debug(Name + " changed due to different value for IsInMixedFolder.");
  789. return true;
  790. }
  791. var changed = copy.DateModified != DateModified;
  792. if (changed)
  793. {
  794. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  795. }
  796. return changed;
  797. }
  798. public virtual string GetClientTypeName()
  799. {
  800. return GetType().Name;
  801. }
  802. /// <summary>
  803. /// Determines if the item is considered new based on user settings
  804. /// </summary>
  805. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  806. /// <exception cref="System.ArgumentNullException"></exception>
  807. public bool IsRecentlyAdded()
  808. {
  809. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  810. }
  811. /// <summary>
  812. /// Adds a person to the item
  813. /// </summary>
  814. /// <param name="person">The person.</param>
  815. /// <exception cref="System.ArgumentNullException"></exception>
  816. public void AddPerson(PersonInfo person)
  817. {
  818. if (person == null)
  819. {
  820. throw new ArgumentNullException("person");
  821. }
  822. if (string.IsNullOrWhiteSpace(person.Name))
  823. {
  824. throw new ArgumentNullException();
  825. }
  826. // Normalize
  827. if (string.Equals(person.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  828. {
  829. person.Type = PersonType.GuestStar;
  830. }
  831. else if (string.Equals(person.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
  832. {
  833. person.Type = PersonType.Director;
  834. }
  835. else if (string.Equals(person.Role, PersonType.Producer, StringComparison.OrdinalIgnoreCase))
  836. {
  837. person.Type = PersonType.Producer;
  838. }
  839. else if (string.Equals(person.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
  840. {
  841. person.Type = PersonType.Writer;
  842. }
  843. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  844. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  845. {
  846. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  847. if (existing != null)
  848. {
  849. existing.Type = PersonType.GuestStar;
  850. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  851. return;
  852. }
  853. }
  854. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  855. {
  856. // If the actor already exists without a role and we have one, fill it in
  857. 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)));
  858. if (existing == null)
  859. {
  860. // Wasn't there - add it
  861. People.Add(person);
  862. }
  863. else
  864. {
  865. // Was there, if no role and we have one - fill it in
  866. if (string.IsNullOrWhiteSpace(existing.Role) && !string.IsNullOrWhiteSpace(person.Role))
  867. {
  868. existing.Role = person.Role;
  869. }
  870. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  871. }
  872. }
  873. else
  874. {
  875. var existing = People.FirstOrDefault(p =>
  876. string.Equals(p.Name, person.Name, StringComparison.OrdinalIgnoreCase) &&
  877. string.Equals(p.Type, person.Type, StringComparison.OrdinalIgnoreCase));
  878. // Check for dupes based on the combination of Name and Type
  879. if (existing == null)
  880. {
  881. People.Add(person);
  882. }
  883. else
  884. {
  885. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  886. }
  887. }
  888. }
  889. /// <summary>
  890. /// Adds a studio to the item
  891. /// </summary>
  892. /// <param name="name">The name.</param>
  893. /// <exception cref="System.ArgumentNullException"></exception>
  894. public void AddStudio(string name)
  895. {
  896. if (string.IsNullOrWhiteSpace(name))
  897. {
  898. throw new ArgumentNullException("name");
  899. }
  900. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  901. {
  902. Studios.Add(name);
  903. }
  904. }
  905. /// <summary>
  906. /// Adds a genre to the item
  907. /// </summary>
  908. /// <param name="name">The name.</param>
  909. /// <exception cref="System.ArgumentNullException"></exception>
  910. public void AddGenre(string name)
  911. {
  912. if (string.IsNullOrWhiteSpace(name))
  913. {
  914. throw new ArgumentNullException("name");
  915. }
  916. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  917. {
  918. Genres.Add(name);
  919. }
  920. }
  921. /// <summary>
  922. /// Marks the played.
  923. /// </summary>
  924. /// <param name="user">The user.</param>
  925. /// <param name="datePlayed">The date played.</param>
  926. /// <param name="userManager">The user manager.</param>
  927. /// <returns>Task.</returns>
  928. /// <exception cref="System.ArgumentNullException"></exception>
  929. public virtual async Task MarkPlayed(User user, DateTime? datePlayed, IUserDataManager userManager)
  930. {
  931. if (user == null)
  932. {
  933. throw new ArgumentNullException();
  934. }
  935. var key = GetUserDataKey();
  936. var data = userManager.GetUserData(user.Id, key);
  937. if (datePlayed.HasValue)
  938. {
  939. // Incremenet
  940. data.PlayCount++;
  941. }
  942. // Ensure it's at least one
  943. data.PlayCount = Math.Max(data.PlayCount, 1);
  944. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate;
  945. data.Played = true;
  946. await userManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  947. }
  948. /// <summary>
  949. /// Marks the unplayed.
  950. /// </summary>
  951. /// <param name="user">The user.</param>
  952. /// <param name="userManager">The user manager.</param>
  953. /// <returns>Task.</returns>
  954. /// <exception cref="System.ArgumentNullException"></exception>
  955. public virtual async Task MarkUnplayed(User user, IUserDataManager userManager)
  956. {
  957. if (user == null)
  958. {
  959. throw new ArgumentNullException();
  960. }
  961. var key = GetUserDataKey();
  962. var data = userManager.GetUserData(user.Id, key);
  963. //I think it is okay to do this here.
  964. // if this is only called when a user is manually forcing something to un-played
  965. // then it probably is what we want to do...
  966. data.PlayCount = 0;
  967. data.PlaybackPositionTicks = 0;
  968. data.LastPlayedDate = null;
  969. data.Played = false;
  970. await userManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  971. }
  972. /// <summary>
  973. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  974. /// </summary>
  975. /// <returns>Task.</returns>
  976. public virtual Task ChangedExternally()
  977. {
  978. return RefreshMetadata(CancellationToken.None);
  979. }
  980. /// <summary>
  981. /// Finds a parent of a given type
  982. /// </summary>
  983. /// <typeparam name="T"></typeparam>
  984. /// <returns>``0.</returns>
  985. public T FindParent<T>()
  986. where T : Folder
  987. {
  988. var parent = Parent;
  989. while (parent != null)
  990. {
  991. var result = parent as T;
  992. if (result != null)
  993. {
  994. return result;
  995. }
  996. parent = parent.Parent;
  997. }
  998. return null;
  999. }
  1000. /// <summary>
  1001. /// Gets an image
  1002. /// </summary>
  1003. /// <param name="type">The type.</param>
  1004. /// <param name="imageIndex">Index of the image.</param>
  1005. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1006. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1007. public bool HasImage(ImageType type, int imageIndex)
  1008. {
  1009. if (type == ImageType.Backdrop)
  1010. {
  1011. return BackdropImagePaths.Count > imageIndex;
  1012. }
  1013. if (type == ImageType.Screenshot)
  1014. {
  1015. var hasScreenshots = this as IHasScreenshots;
  1016. return hasScreenshots != null && hasScreenshots.ScreenshotImagePaths.Count > imageIndex;
  1017. }
  1018. return !string.IsNullOrEmpty(this.GetImagePath(type));
  1019. }
  1020. public void SetImagePath(ImageType type, int index, string path)
  1021. {
  1022. if (type == ImageType.Backdrop)
  1023. {
  1024. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1025. }
  1026. if (type == ImageType.Screenshot)
  1027. {
  1028. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1029. }
  1030. var typeKey = type;
  1031. // If it's null remove the key from the dictionary
  1032. if (string.IsNullOrEmpty(path))
  1033. {
  1034. if (Images.ContainsKey(typeKey))
  1035. {
  1036. Images.Remove(typeKey);
  1037. }
  1038. }
  1039. else
  1040. {
  1041. Images[typeKey] = path;
  1042. }
  1043. }
  1044. /// <summary>
  1045. /// Deletes the image.
  1046. /// </summary>
  1047. /// <param name="type">The type.</param>
  1048. /// <param name="index">The index.</param>
  1049. /// <returns>Task.</returns>
  1050. public Task DeleteImage(ImageType type, int? index)
  1051. {
  1052. if (type == ImageType.Backdrop)
  1053. {
  1054. if (!index.HasValue)
  1055. {
  1056. throw new ArgumentException("Please specify a backdrop image index to delete.");
  1057. }
  1058. var file = BackdropImagePaths[index.Value];
  1059. BackdropImagePaths.Remove(file);
  1060. // Delete the source file
  1061. DeleteImagePath(file);
  1062. }
  1063. else if (type == ImageType.Screenshot)
  1064. {
  1065. if (!index.HasValue)
  1066. {
  1067. throw new ArgumentException("Please specify a screenshot image index to delete.");
  1068. }
  1069. var hasScreenshots = (IHasScreenshots)this;
  1070. var file = hasScreenshots.ScreenshotImagePaths[index.Value];
  1071. hasScreenshots.ScreenshotImagePaths.Remove(file);
  1072. // Delete the source file
  1073. DeleteImagePath(file);
  1074. }
  1075. else
  1076. {
  1077. // Delete the source file
  1078. DeleteImagePath(this.GetImagePath(type));
  1079. // Remove it from the item
  1080. this.SetImagePath(type, null);
  1081. }
  1082. // Refresh metadata
  1083. // Need to disable slow providers or the image might get re-downloaded
  1084. return RefreshMetadata(new MetadataRefreshOptions
  1085. {
  1086. ForceSave = true,
  1087. ImageRefreshMode = ImageRefreshMode.ValidationOnly,
  1088. MetadataRefreshMode = MetadataRefreshMode.None
  1089. }, CancellationToken.None);
  1090. }
  1091. /// <summary>
  1092. /// Deletes the image path.
  1093. /// </summary>
  1094. /// <param name="path">The path.</param>
  1095. private void DeleteImagePath(string path)
  1096. {
  1097. var currentFile = new FileInfo(path);
  1098. // This will fail if the file is hidden
  1099. if (currentFile.Exists)
  1100. {
  1101. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  1102. {
  1103. currentFile.Attributes &= ~FileAttributes.Hidden;
  1104. }
  1105. currentFile.Delete();
  1106. }
  1107. }
  1108. /// <summary>
  1109. /// Validates that images within the item are still on the file system
  1110. /// </summary>
  1111. public bool ValidateImages()
  1112. {
  1113. var changed = false;
  1114. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1115. var deletedKeys = Images
  1116. .Where(image => !File.Exists(image.Value))
  1117. .Select(i => i.Key)
  1118. .ToList();
  1119. // Now remove them from the dictionary
  1120. foreach (var key in deletedKeys)
  1121. {
  1122. Images.Remove(key);
  1123. changed = true;
  1124. }
  1125. if (ValidateBackdrops())
  1126. {
  1127. changed = true;
  1128. }
  1129. if (ValidateScreenshots())
  1130. {
  1131. changed = true;
  1132. }
  1133. return changed;
  1134. }
  1135. /// <summary>
  1136. /// Validates that backdrops within the item are still on the file system
  1137. /// </summary>
  1138. private bool ValidateBackdrops()
  1139. {
  1140. var changed = false;
  1141. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1142. var deletedImages = BackdropImagePaths
  1143. .Where(path => !File.Exists(path))
  1144. .ToList();
  1145. // Now remove them from the dictionary
  1146. foreach (var path in deletedImages)
  1147. {
  1148. BackdropImagePaths.Remove(path);
  1149. changed = true;
  1150. }
  1151. return changed;
  1152. }
  1153. /// <summary>
  1154. /// Validates the screenshots.
  1155. /// </summary>
  1156. private bool ValidateScreenshots()
  1157. {
  1158. var changed = false;
  1159. var hasScreenshots = this as IHasScreenshots;
  1160. if (hasScreenshots == null)
  1161. {
  1162. return changed;
  1163. }
  1164. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1165. var deletedImages = hasScreenshots.ScreenshotImagePaths
  1166. .Where(path => !File.Exists(path))
  1167. .ToList();
  1168. // Now remove them from the dictionary
  1169. foreach (var path in deletedImages)
  1170. {
  1171. hasScreenshots.ScreenshotImagePaths.Remove(path);
  1172. changed = true;
  1173. }
  1174. return changed;
  1175. }
  1176. /// <summary>
  1177. /// Gets the image path.
  1178. /// </summary>
  1179. /// <param name="imageType">Type of the image.</param>
  1180. /// <param name="imageIndex">Index of the image.</param>
  1181. /// <returns>System.String.</returns>
  1182. /// <exception cref="System.InvalidOperationException">
  1183. /// </exception>
  1184. /// <exception cref="System.ArgumentNullException">item</exception>
  1185. public string GetImagePath(ImageType imageType, int imageIndex)
  1186. {
  1187. if (imageType == ImageType.Backdrop)
  1188. {
  1189. return BackdropImagePaths.Count > imageIndex ? BackdropImagePaths[imageIndex] : null;
  1190. }
  1191. if (imageType == ImageType.Screenshot)
  1192. {
  1193. var hasScreenshots = (IHasScreenshots)this;
  1194. return hasScreenshots.ScreenshotImagePaths.Count > imageIndex ? hasScreenshots.ScreenshotImagePaths[imageIndex] : null;
  1195. }
  1196. if (imageType == ImageType.Chapter)
  1197. {
  1198. return ItemRepository.GetChapter(Id, imageIndex).ImagePath;
  1199. }
  1200. string val;
  1201. Images.TryGetValue(imageType, out val);
  1202. return val;
  1203. }
  1204. /// <summary>
  1205. /// Gets the image date modified.
  1206. /// </summary>
  1207. /// <param name="imagePath">The image path.</param>
  1208. /// <returns>DateTime.</returns>
  1209. /// <exception cref="System.ArgumentNullException">item</exception>
  1210. public DateTime GetImageDateModified(string imagePath)
  1211. {
  1212. if (string.IsNullOrEmpty(imagePath))
  1213. {
  1214. throw new ArgumentNullException("imagePath");
  1215. }
  1216. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1217. return FileSystem.GetLastWriteTimeUtc(imagePath);
  1218. }
  1219. /// <summary>
  1220. /// Gets the file system path to delete when the item is to be deleted
  1221. /// </summary>
  1222. /// <returns></returns>
  1223. public virtual IEnumerable<string> GetDeletePaths()
  1224. {
  1225. return new[] { Path };
  1226. }
  1227. public Task SwapImages(ImageType type, int index1, int index2)
  1228. {
  1229. if (type != ImageType.Screenshot && type != ImageType.Backdrop)
  1230. {
  1231. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  1232. }
  1233. var file1 = GetImagePath(type, index1);
  1234. var file2 = GetImagePath(type, index2);
  1235. FileSystem.SwapFiles(file1, file2);
  1236. // Directory watchers should repeat this, but do a quick refresh first
  1237. return RefreshMetadata(new MetadataRefreshOptions
  1238. {
  1239. ForceSave = true,
  1240. MetadataRefreshMode = MetadataRefreshMode.None
  1241. }, CancellationToken.None);
  1242. }
  1243. public virtual bool IsPlayed(User user)
  1244. {
  1245. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1246. return userdata != null && userdata.Played;
  1247. }
  1248. public virtual bool IsUnplayed(User user)
  1249. {
  1250. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1251. return userdata == null || !userdata.Played;
  1252. }
  1253. }
  1254. }