BaseItem.cs 55 KB

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