BaseItem.cs 58 KB

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