BaseItem.cs 50 KB

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