BaseItem.cs 52 KB

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