BaseItem.cs 49 KB

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