BaseItem.cs 52 KB

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