BaseItem.cs 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769
  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. return current.IsInMixedFolder == newItem.IsInMixedFolder;
  755. }
  756. /// <summary>
  757. /// Gets the preferred metadata language.
  758. /// </summary>
  759. /// <returns>System.String.</returns>
  760. public string GetPreferredMetadataLanguage()
  761. {
  762. string lang = null;
  763. var hasLang = this as IHasPreferredMetadataLanguage;
  764. if (hasLang != null)
  765. {
  766. lang = hasLang.PreferredMetadataLanguage;
  767. }
  768. if (string.IsNullOrEmpty(lang))
  769. {
  770. lang = Parents.OfType<IHasPreferredMetadataLanguage>()
  771. .Select(i => i.PreferredMetadataLanguage)
  772. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  773. }
  774. if (string.IsNullOrEmpty(lang))
  775. {
  776. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  777. }
  778. return lang;
  779. }
  780. /// <summary>
  781. /// Gets the preferred metadata language.
  782. /// </summary>
  783. /// <returns>System.String.</returns>
  784. public string GetPreferredMetadataCountryCode()
  785. {
  786. string lang = null;
  787. var hasLang = this as IHasPreferredMetadataLanguage;
  788. if (hasLang != null)
  789. {
  790. lang = hasLang.PreferredMetadataCountryCode;
  791. }
  792. if (string.IsNullOrEmpty(lang))
  793. {
  794. lang = Parents.OfType<IHasPreferredMetadataLanguage>()
  795. .Select(i => i.PreferredMetadataCountryCode)
  796. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  797. }
  798. if (string.IsNullOrEmpty(lang))
  799. {
  800. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  801. }
  802. return lang;
  803. }
  804. public virtual bool IsSaveLocalMetadataEnabled()
  805. {
  806. return ConfigurationManager.Configuration.SaveLocalMeta;
  807. }
  808. /// <summary>
  809. /// Determines if a given user has access to this item
  810. /// </summary>
  811. /// <param name="user">The user.</param>
  812. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  813. /// <exception cref="System.ArgumentNullException">user</exception>
  814. public bool IsParentalAllowed(User user)
  815. {
  816. if (user == null)
  817. {
  818. throw new ArgumentNullException("user");
  819. }
  820. if (!IsVisibleViaTags(user))
  821. {
  822. return false;
  823. }
  824. var maxAllowedRating = user.Configuration.MaxParentalRating;
  825. if (maxAllowedRating == null)
  826. {
  827. return true;
  828. }
  829. var rating = CustomRatingForComparison;
  830. if (string.IsNullOrWhiteSpace(rating))
  831. {
  832. rating = OfficialRatingForComparison;
  833. }
  834. if (string.IsNullOrWhiteSpace(rating))
  835. {
  836. return !GetBlockUnratedValue(user.Configuration);
  837. }
  838. var value = LocalizationManager.GetRatingLevel(rating);
  839. // Could not determine the integer value
  840. if (!value.HasValue)
  841. {
  842. return true;
  843. }
  844. return value.Value <= maxAllowedRating.Value;
  845. }
  846. private bool IsVisibleViaTags(User user)
  847. {
  848. var hasTags = this as IHasTags;
  849. if (hasTags != null)
  850. {
  851. if (user.Configuration.BlockedTags.Any(i => hasTags.Tags.Contains(i, StringComparer.OrdinalIgnoreCase)))
  852. {
  853. return false;
  854. }
  855. }
  856. return true;
  857. }
  858. /// <summary>
  859. /// Gets the block unrated value.
  860. /// </summary>
  861. /// <param name="config">The configuration.</param>
  862. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  863. protected virtual bool GetBlockUnratedValue(UserConfiguration config)
  864. {
  865. return config.BlockUnratedItems.Contains(UnratedItem.Other);
  866. }
  867. /// <summary>
  868. /// Determines if this folder should be visible to a given user.
  869. /// Default is just parental allowed. Can be overridden for more functionality.
  870. /// </summary>
  871. /// <param name="user">The user.</param>
  872. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  873. /// <exception cref="System.ArgumentNullException">user</exception>
  874. public virtual bool IsVisible(User user)
  875. {
  876. if (user == null)
  877. {
  878. throw new ArgumentNullException("user");
  879. }
  880. return IsParentalAllowed(user);
  881. }
  882. /// <summary>
  883. /// Gets a value indicating whether this instance is folder.
  884. /// </summary>
  885. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  886. [IgnoreDataMember]
  887. public virtual bool IsFolder
  888. {
  889. get
  890. {
  891. return false;
  892. }
  893. }
  894. public virtual string GetClientTypeName()
  895. {
  896. return GetType().Name;
  897. }
  898. /// <summary>
  899. /// Gets the linked child.
  900. /// </summary>
  901. /// <param name="info">The info.</param>
  902. /// <returns>BaseItem.</returns>
  903. protected BaseItem GetLinkedChild(LinkedChild info)
  904. {
  905. // First get using the cached Id
  906. if (info.ItemId.HasValue)
  907. {
  908. if (info.ItemId.Value == Guid.Empty)
  909. {
  910. return null;
  911. }
  912. var itemById = LibraryManager.GetItemById(info.ItemId.Value);
  913. if (itemById != null)
  914. {
  915. return itemById;
  916. }
  917. }
  918. var item = FindLinkedChild(info);
  919. // If still null, log
  920. if (item == null)
  921. {
  922. // Don't keep searching over and over
  923. info.ItemId = Guid.Empty;
  924. }
  925. else
  926. {
  927. // Cache the id for next time
  928. info.ItemId = item.Id;
  929. }
  930. return item;
  931. }
  932. private BaseItem FindLinkedChild(LinkedChild info)
  933. {
  934. if (!string.IsNullOrWhiteSpace(info.ItemName))
  935. {
  936. if (string.Equals(info.ItemType, "musicgenre", StringComparison.OrdinalIgnoreCase))
  937. {
  938. return LibraryManager.GetMusicGenre(info.ItemName);
  939. }
  940. if (string.Equals(info.ItemType, "musicartist", StringComparison.OrdinalIgnoreCase))
  941. {
  942. return LibraryManager.GetArtist(info.ItemName);
  943. }
  944. }
  945. if (!string.IsNullOrEmpty(info.Path))
  946. {
  947. var itemByPath = LibraryManager.RootFolder.FindByPath(info.Path);
  948. if (itemByPath == null)
  949. {
  950. Logger.Warn("Unable to find linked item at path {0}", info.Path);
  951. }
  952. return itemByPath;
  953. }
  954. if (!string.IsNullOrWhiteSpace(info.ItemName) && !string.IsNullOrWhiteSpace(info.ItemType))
  955. {
  956. return LibraryManager.RootFolder.RecursiveChildren.FirstOrDefault(i =>
  957. {
  958. if (string.Equals(i.Name, info.ItemName, StringComparison.OrdinalIgnoreCase))
  959. {
  960. if (string.Equals(i.GetType().Name, info.ItemType, StringComparison.OrdinalIgnoreCase))
  961. {
  962. if (info.ItemYear.HasValue)
  963. {
  964. if (info.ItemYear.Value != (i.ProductionYear ?? -1))
  965. {
  966. return false;
  967. }
  968. }
  969. return true;
  970. }
  971. }
  972. return false;
  973. });
  974. }
  975. return null;
  976. }
  977. /// <summary>
  978. /// Adds a person to the item
  979. /// </summary>
  980. /// <param name="person">The person.</param>
  981. /// <exception cref="System.ArgumentNullException"></exception>
  982. public void AddPerson(PersonInfo person)
  983. {
  984. if (person == null)
  985. {
  986. throw new ArgumentNullException("person");
  987. }
  988. if (string.IsNullOrWhiteSpace(person.Name))
  989. {
  990. throw new ArgumentNullException();
  991. }
  992. // Normalize
  993. if (string.Equals(person.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  994. {
  995. person.Type = PersonType.GuestStar;
  996. }
  997. else if (string.Equals(person.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
  998. {
  999. person.Type = PersonType.Director;
  1000. }
  1001. else if (string.Equals(person.Role, PersonType.Producer, StringComparison.OrdinalIgnoreCase))
  1002. {
  1003. person.Type = PersonType.Producer;
  1004. }
  1005. else if (string.Equals(person.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
  1006. {
  1007. person.Type = PersonType.Writer;
  1008. }
  1009. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  1010. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  1011. {
  1012. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  1013. if (existing != null)
  1014. {
  1015. existing.Type = PersonType.GuestStar;
  1016. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  1017. return;
  1018. }
  1019. }
  1020. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  1021. {
  1022. // If the actor already exists without a role and we have one, fill it in
  1023. 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)));
  1024. if (existing == null)
  1025. {
  1026. // Wasn't there - add it
  1027. People.Add(person);
  1028. }
  1029. else
  1030. {
  1031. // Was there, if no role and we have one - fill it in
  1032. if (string.IsNullOrWhiteSpace(existing.Role) && !string.IsNullOrWhiteSpace(person.Role))
  1033. {
  1034. existing.Role = person.Role;
  1035. }
  1036. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  1037. }
  1038. }
  1039. else
  1040. {
  1041. var existing = People.FirstOrDefault(p =>
  1042. string.Equals(p.Name, person.Name, StringComparison.OrdinalIgnoreCase) &&
  1043. string.Equals(p.Type, person.Type, StringComparison.OrdinalIgnoreCase));
  1044. // Check for dupes based on the combination of Name and Type
  1045. if (existing == null)
  1046. {
  1047. People.Add(person);
  1048. }
  1049. else
  1050. {
  1051. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  1052. }
  1053. }
  1054. }
  1055. /// <summary>
  1056. /// Adds a studio to the item
  1057. /// </summary>
  1058. /// <param name="name">The name.</param>
  1059. /// <exception cref="System.ArgumentNullException"></exception>
  1060. public void AddStudio(string name)
  1061. {
  1062. if (string.IsNullOrWhiteSpace(name))
  1063. {
  1064. throw new ArgumentNullException("name");
  1065. }
  1066. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1067. {
  1068. Studios.Add(name);
  1069. }
  1070. }
  1071. /// <summary>
  1072. /// Adds a genre to the item
  1073. /// </summary>
  1074. /// <param name="name">The name.</param>
  1075. /// <exception cref="System.ArgumentNullException"></exception>
  1076. public void AddGenre(string name)
  1077. {
  1078. if (string.IsNullOrWhiteSpace(name))
  1079. {
  1080. throw new ArgumentNullException("name");
  1081. }
  1082. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1083. {
  1084. Genres.Add(name);
  1085. }
  1086. }
  1087. /// <summary>
  1088. /// Marks the played.
  1089. /// </summary>
  1090. /// <param name="user">The user.</param>
  1091. /// <param name="datePlayed">The date played.</param>
  1092. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1093. /// <returns>Task.</returns>
  1094. /// <exception cref="System.ArgumentNullException"></exception>
  1095. public virtual async Task MarkPlayed(User user,
  1096. DateTime? datePlayed,
  1097. bool resetPosition)
  1098. {
  1099. if (user == null)
  1100. {
  1101. throw new ArgumentNullException();
  1102. }
  1103. var key = GetUserDataKey();
  1104. var data = UserDataManager.GetUserData(user.Id, key);
  1105. if (datePlayed.HasValue)
  1106. {
  1107. // Incremenet
  1108. data.PlayCount++;
  1109. }
  1110. // Ensure it's at least one
  1111. data.PlayCount = Math.Max(data.PlayCount, 1);
  1112. if (resetPosition)
  1113. {
  1114. data.PlaybackPositionTicks = 0;
  1115. }
  1116. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate;
  1117. data.Played = true;
  1118. await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1119. }
  1120. /// <summary>
  1121. /// Marks the unplayed.
  1122. /// </summary>
  1123. /// <param name="user">The user.</param>
  1124. /// <returns>Task.</returns>
  1125. /// <exception cref="System.ArgumentNullException"></exception>
  1126. public virtual async Task MarkUnplayed(User user)
  1127. {
  1128. if (user == null)
  1129. {
  1130. throw new ArgumentNullException();
  1131. }
  1132. var key = GetUserDataKey();
  1133. var data = UserDataManager.GetUserData(user.Id, key);
  1134. //I think it is okay to do this here.
  1135. // if this is only called when a user is manually forcing something to un-played
  1136. // then it probably is what we want to do...
  1137. data.PlayCount = 0;
  1138. data.PlaybackPositionTicks = 0;
  1139. data.LastPlayedDate = null;
  1140. data.Played = false;
  1141. await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1142. }
  1143. /// <summary>
  1144. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1145. /// </summary>
  1146. /// <returns>Task.</returns>
  1147. public virtual Task ChangedExternally()
  1148. {
  1149. return RefreshMetadata(CancellationToken.None);
  1150. }
  1151. /// <summary>
  1152. /// Finds a parent of a given type
  1153. /// </summary>
  1154. /// <typeparam name="T"></typeparam>
  1155. /// <returns>``0.</returns>
  1156. public T FindParent<T>()
  1157. where T : Folder
  1158. {
  1159. var parent = Parent;
  1160. while (parent != null)
  1161. {
  1162. var result = parent as T;
  1163. if (result != null)
  1164. {
  1165. return result;
  1166. }
  1167. parent = parent.Parent;
  1168. }
  1169. return null;
  1170. }
  1171. /// <summary>
  1172. /// Gets an image
  1173. /// </summary>
  1174. /// <param name="type">The type.</param>
  1175. /// <param name="imageIndex">Index of the image.</param>
  1176. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1177. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1178. public bool HasImage(ImageType type, int imageIndex)
  1179. {
  1180. return GetImageInfo(type, imageIndex) != null;
  1181. }
  1182. public void SetImagePath(ImageType type, int index, FileSystemInfo file)
  1183. {
  1184. if (type == ImageType.Chapter)
  1185. {
  1186. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1187. }
  1188. var image = GetImageInfo(type, index);
  1189. if (image == null)
  1190. {
  1191. ImageInfos.Add(GetImageInfo(file, type));
  1192. }
  1193. else
  1194. {
  1195. var imageInfo = GetImageInfo(file, type);
  1196. image.Path = file.FullName;
  1197. image.DateModified = imageInfo.DateModified;
  1198. }
  1199. }
  1200. /// <summary>
  1201. /// Deletes the image.
  1202. /// </summary>
  1203. /// <param name="type">The type.</param>
  1204. /// <param name="index">The index.</param>
  1205. /// <returns>Task.</returns>
  1206. public Task DeleteImage(ImageType type, int index)
  1207. {
  1208. var info = GetImageInfo(type, index);
  1209. if (info == null)
  1210. {
  1211. // Nothing to do
  1212. return Task.FromResult(true);
  1213. }
  1214. // Remove it from the item
  1215. ImageInfos.Remove(info);
  1216. // Delete the source file
  1217. var currentFile = new FileInfo(info.Path);
  1218. // Deletion will fail if the file is hidden so remove the attribute first
  1219. if (currentFile.Exists)
  1220. {
  1221. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  1222. {
  1223. currentFile.Attributes &= ~FileAttributes.Hidden;
  1224. }
  1225. currentFile.Delete();
  1226. }
  1227. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1228. }
  1229. public virtual Task UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1230. {
  1231. return LibraryManager.UpdateItem(this, updateReason, cancellationToken);
  1232. }
  1233. /// <summary>
  1234. /// Validates that images within the item are still on the file system
  1235. /// </summary>
  1236. public bool ValidateImages(IDirectoryService directoryService)
  1237. {
  1238. var allDirectories = ImageInfos.Select(i => System.IO.Path.GetDirectoryName(i.Path)).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  1239. var allFiles = allDirectories.SelectMany(directoryService.GetFiles).Select(i => i.FullName).ToList();
  1240. var deletedImages = ImageInfos
  1241. .Where(image => !allFiles.Contains(image.Path, StringComparer.OrdinalIgnoreCase))
  1242. .ToList();
  1243. if (deletedImages.Count > 0)
  1244. {
  1245. ImageInfos = ImageInfos.Except(deletedImages).ToList();
  1246. }
  1247. return deletedImages.Count > 0;
  1248. }
  1249. /// <summary>
  1250. /// Gets the image path.
  1251. /// </summary>
  1252. /// <param name="imageType">Type of the image.</param>
  1253. /// <param name="imageIndex">Index of the image.</param>
  1254. /// <returns>System.String.</returns>
  1255. /// <exception cref="System.InvalidOperationException">
  1256. /// </exception>
  1257. /// <exception cref="System.ArgumentNullException">item</exception>
  1258. public string GetImagePath(ImageType imageType, int imageIndex)
  1259. {
  1260. var info = GetImageInfo(imageType, imageIndex);
  1261. return info == null ? null : info.Path;
  1262. }
  1263. /// <summary>
  1264. /// Gets the image information.
  1265. /// </summary>
  1266. /// <param name="imageType">Type of the image.</param>
  1267. /// <param name="imageIndex">Index of the image.</param>
  1268. /// <returns>ItemImageInfo.</returns>
  1269. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1270. {
  1271. if (imageType == ImageType.Chapter)
  1272. {
  1273. var chapter = ItemRepository.GetChapter(Id, imageIndex);
  1274. if (chapter == null)
  1275. {
  1276. return null;
  1277. }
  1278. var path = chapter.ImagePath;
  1279. if (string.IsNullOrWhiteSpace(path))
  1280. {
  1281. return null;
  1282. }
  1283. return new ItemImageInfo
  1284. {
  1285. Path = path,
  1286. DateModified = FileSystem.GetLastWriteTimeUtc(path),
  1287. Type = imageType
  1288. };
  1289. }
  1290. return GetImages(imageType)
  1291. .ElementAtOrDefault(imageIndex);
  1292. }
  1293. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1294. {
  1295. if (imageType == ImageType.Chapter)
  1296. {
  1297. throw new ArgumentException("No image info for chapter images");
  1298. }
  1299. return ImageInfos.Where(i => i.Type == imageType);
  1300. }
  1301. public bool AddImages(ImageType imageType, IEnumerable<FileInfo> images)
  1302. {
  1303. return AddImages(imageType, images.Cast<FileSystemInfo>());
  1304. }
  1305. /// <summary>
  1306. /// Adds the images.
  1307. /// </summary>
  1308. /// <param name="imageType">Type of the image.</param>
  1309. /// <param name="images">The images.</param>
  1310. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1311. /// <exception cref="System.ArgumentException">Cannot call AddImages with chapter images</exception>
  1312. public bool AddImages(ImageType imageType, IEnumerable<FileSystemInfo> images)
  1313. {
  1314. if (imageType == ImageType.Chapter)
  1315. {
  1316. throw new ArgumentException("Cannot call AddImages with chapter images");
  1317. }
  1318. var existingImages = GetImages(imageType)
  1319. .ToList();
  1320. var newImageList = new List<FileSystemInfo>();
  1321. foreach (var newImage in images)
  1322. {
  1323. var existing = existingImages
  1324. .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  1325. if (existing == null)
  1326. {
  1327. newImageList.Add(newImage);
  1328. }
  1329. else
  1330. {
  1331. existing.DateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  1332. }
  1333. }
  1334. ImageInfos.AddRange(newImageList.Select(i => GetImageInfo(i, imageType)));
  1335. return newImageList.Count > 0;
  1336. }
  1337. private ItemImageInfo GetImageInfo(FileSystemInfo file, ImageType type)
  1338. {
  1339. return new ItemImageInfo
  1340. {
  1341. Path = file.FullName,
  1342. Type = type,
  1343. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  1344. };
  1345. }
  1346. /// <summary>
  1347. /// Gets the file system path to delete when the item is to be deleted
  1348. /// </summary>
  1349. /// <returns></returns>
  1350. public virtual IEnumerable<string> GetDeletePaths()
  1351. {
  1352. return new[] { Path };
  1353. }
  1354. public bool AllowsMultipleImages(ImageType type)
  1355. {
  1356. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  1357. }
  1358. public Task SwapImages(ImageType type, int index1, int index2)
  1359. {
  1360. if (!AllowsMultipleImages(type))
  1361. {
  1362. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  1363. }
  1364. var info1 = GetImageInfo(type, index1);
  1365. var info2 = GetImageInfo(type, index2);
  1366. if (info1 == null || info2 == null)
  1367. {
  1368. // Nothing to do
  1369. return Task.FromResult(true);
  1370. }
  1371. var path1 = info1.Path;
  1372. var path2 = info2.Path;
  1373. FileSystem.SwapFiles(path1, path2);
  1374. // Refresh these values
  1375. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  1376. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  1377. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1378. }
  1379. public virtual bool IsPlayed(User user)
  1380. {
  1381. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1382. return userdata != null && userdata.Played;
  1383. }
  1384. public bool IsFavoriteOrLiked(User user)
  1385. {
  1386. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1387. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  1388. }
  1389. public virtual bool IsUnplayed(User user)
  1390. {
  1391. if (user == null)
  1392. {
  1393. throw new ArgumentNullException("user");
  1394. }
  1395. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1396. return userdata == null || !userdata.Played;
  1397. }
  1398. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  1399. {
  1400. return GetItemLookupInfo<ItemLookupInfo>();
  1401. }
  1402. protected T GetItemLookupInfo<T>()
  1403. where T : ItemLookupInfo, new()
  1404. {
  1405. return new T
  1406. {
  1407. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  1408. MetadataLanguage = GetPreferredMetadataLanguage(),
  1409. Name = Name,
  1410. ProviderIds = ProviderIds,
  1411. IndexNumber = IndexNumber,
  1412. ParentIndexNumber = ParentIndexNumber,
  1413. Year = ProductionYear
  1414. };
  1415. }
  1416. /// <summary>
  1417. /// This is called before any metadata refresh and returns true or false indicating if changes were made
  1418. /// </summary>
  1419. public virtual bool BeforeMetadataRefresh()
  1420. {
  1421. var hasChanges = false;
  1422. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  1423. {
  1424. Name = FileSystem.GetFileNameWithoutExtension(Path);
  1425. hasChanges = true;
  1426. }
  1427. return hasChanges;
  1428. }
  1429. protected static string GetMappedPath(string path, LocationType locationType)
  1430. {
  1431. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1432. {
  1433. foreach (var map in ConfigurationManager.Configuration.PathSubstitutions)
  1434. {
  1435. path = FileSystem.SubstitutePath(path, map.From, map.To);
  1436. }
  1437. }
  1438. return path;
  1439. }
  1440. public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, User user)
  1441. {
  1442. if (RunTimeTicks.HasValue)
  1443. {
  1444. double pct = RunTimeTicks.Value;
  1445. if (pct > 0)
  1446. {
  1447. pct = userData.PlaybackPositionTicks / pct;
  1448. if (pct > 0)
  1449. {
  1450. dto.PlayedPercentage = 100 * pct;
  1451. }
  1452. }
  1453. }
  1454. }
  1455. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, string path, CancellationToken cancellationToken)
  1456. {
  1457. var newOptions = new MetadataRefreshOptions(options.DirectoryService)
  1458. {
  1459. ImageRefreshMode = options.ImageRefreshMode,
  1460. MetadataRefreshMode = options.MetadataRefreshMode,
  1461. ReplaceAllMetadata = options.ReplaceAllMetadata
  1462. };
  1463. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  1464. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1465. var video = LibraryManager.GetItemById(id) as Video;
  1466. if (video == null)
  1467. {
  1468. video = LibraryManager.ResolvePath(new FileInfo(path)) as Video;
  1469. newOptions.ForceSave = true;
  1470. }
  1471. if (video == null)
  1472. {
  1473. return Task.FromResult(true);
  1474. }
  1475. return video.RefreshMetadata(newOptions, cancellationToken);
  1476. }
  1477. }
  1478. }