BaseItem.cs 53 KB

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