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