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. /// <summary>
  191. /// This is just a helper for convenience
  192. /// </summary>
  193. /// <value>The primary image path.</value>
  194. [IgnoreDataMember]
  195. public string PrimaryImagePath
  196. {
  197. get { return this.GetImagePath(ImageType.Primary); }
  198. }
  199. /// <summary>
  200. /// Gets or sets the date created.
  201. /// </summary>
  202. /// <value>The date created.</value>
  203. public DateTime DateCreated { get; set; }
  204. /// <summary>
  205. /// Gets or sets the date modified.
  206. /// </summary>
  207. /// <value>The date modified.</value>
  208. public DateTime DateModified { get; set; }
  209. public DateTime DateLastSaved { get; set; }
  210. /// <summary>
  211. /// The logger
  212. /// </summary>
  213. public static ILogger Logger { get; set; }
  214. public static ILibraryManager LibraryManager { get; set; }
  215. public static IServerConfigurationManager ConfigurationManager { get; set; }
  216. public static IProviderManager ProviderManager { get; set; }
  217. public static ILocalizationManager LocalizationManager { get; set; }
  218. public static IItemRepository ItemRepository { get; set; }
  219. public static IFileSystem FileSystem { get; set; }
  220. public static IUserDataManager UserDataManager { get; set; }
  221. public static ILiveTvManager LiveTvManager { get; set; }
  222. public static IChannelManager ChannelManager { get; set; }
  223. public static ICollectionManager CollectionManager { get; set; }
  224. public static IImageProcessor ImageProcessor { get; set; }
  225. /// <summary>
  226. /// Returns a <see cref="System.String" /> that represents this instance.
  227. /// </summary>
  228. /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
  229. public override string ToString()
  230. {
  231. return Name;
  232. }
  233. /// <summary>
  234. /// Returns true if this item should not attempt to fetch metadata
  235. /// </summary>
  236. /// <value><c>true</c> if [dont fetch meta]; otherwise, <c>false</c>.</value>
  237. [Obsolete("Please use IsLocked instead of DontFetchMeta")]
  238. public bool DontFetchMeta { get; set; }
  239. [IgnoreDataMember]
  240. public bool IsLocked
  241. {
  242. get
  243. {
  244. return DontFetchMeta;
  245. }
  246. set
  247. {
  248. DontFetchMeta = value;
  249. }
  250. }
  251. public bool IsUnidentified { get; set; }
  252. [IgnoreDataMember]
  253. public List<IItemIdentity> Identities { get; set; }
  254. /// <summary>
  255. /// Gets or sets the locked fields.
  256. /// </summary>
  257. /// <value>The locked fields.</value>
  258. public List<MetadataFields> LockedFields { get; set; }
  259. /// <summary>
  260. /// Gets the type of the media.
  261. /// </summary>
  262. /// <value>The type of the media.</value>
  263. [IgnoreDataMember]
  264. public virtual string MediaType
  265. {
  266. get
  267. {
  268. return null;
  269. }
  270. }
  271. [IgnoreDataMember]
  272. public virtual IEnumerable<string> PhysicalLocations
  273. {
  274. get
  275. {
  276. var locationType = LocationType;
  277. if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
  278. {
  279. return new string[] { };
  280. }
  281. return new[] { Path };
  282. }
  283. }
  284. private string _forcedSortName;
  285. /// <summary>
  286. /// Gets or sets the name of the forced sort.
  287. /// </summary>
  288. /// <value>The name of the forced sort.</value>
  289. public string ForcedSortName
  290. {
  291. get { return _forcedSortName; }
  292. set { _forcedSortName = value; _sortName = null; }
  293. }
  294. private string _sortName;
  295. /// <summary>
  296. /// Gets the name of the sort.
  297. /// </summary>
  298. /// <value>The name of the sort.</value>
  299. [IgnoreDataMember]
  300. public string SortName
  301. {
  302. get
  303. {
  304. if (!string.IsNullOrEmpty(ForcedSortName))
  305. {
  306. return ForcedSortName;
  307. }
  308. return _sortName ?? (_sortName = CreateSortName());
  309. }
  310. }
  311. public bool ContainsPerson(string name)
  312. {
  313. if (string.IsNullOrWhiteSpace(name))
  314. {
  315. throw new ArgumentNullException("name");
  316. }
  317. return People.Any(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
  318. }
  319. public string GetInternalMetadataPath()
  320. {
  321. return GetInternalMetadataPath(ConfigurationManager.ApplicationPaths.InternalMetadataPath);
  322. }
  323. protected virtual string GetInternalMetadataPath(string basePath)
  324. {
  325. var idString = Id.ToString("N");
  326. return System.IO.Path.Combine(basePath, idString.Substring(0, 2), idString);
  327. }
  328. public static string GetInternalMetadataPathForId(Guid id)
  329. {
  330. var idString = id.ToString("N");
  331. var basePath = ConfigurationManager.ApplicationPaths.InternalMetadataPath;
  332. return System.IO.Path.Combine(basePath, idString.Substring(0, 2), idString);
  333. }
  334. /// <summary>
  335. /// Creates the name of the sort.
  336. /// </summary>
  337. /// <returns>System.String.</returns>
  338. protected virtual string CreateSortName()
  339. {
  340. if (Name == null) return null; //some items may not have name filled in properly
  341. var sortable = Name.Trim().ToLower();
  342. sortable = ConfigurationManager.Configuration.SortRemoveCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), string.Empty));
  343. sortable = ConfigurationManager.Configuration.SortReplaceCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), " "));
  344. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  345. {
  346. var searchLower = search.ToLower();
  347. // Remove from beginning if a space follows
  348. if (sortable.StartsWith(searchLower + " "))
  349. {
  350. sortable = sortable.Remove(0, searchLower.Length + 1);
  351. }
  352. // Remove from middle if surrounded by spaces
  353. sortable = sortable.Replace(" " + searchLower + " ", " ");
  354. // Remove from end if followed by a space
  355. if (sortable.EndsWith(" " + searchLower))
  356. {
  357. sortable = sortable.Remove(sortable.Length - (searchLower.Length + 1));
  358. }
  359. }
  360. return sortable;
  361. }
  362. /// <summary>
  363. /// Gets or sets the parent.
  364. /// </summary>
  365. /// <value>The parent.</value>
  366. [IgnoreDataMember]
  367. public Folder Parent { get; set; }
  368. [IgnoreDataMember]
  369. public IEnumerable<Folder> Parents
  370. {
  371. get
  372. {
  373. var parent = Parent;
  374. while (parent != null)
  375. {
  376. yield return parent;
  377. parent = parent.Parent;
  378. }
  379. }
  380. }
  381. [IgnoreDataMember]
  382. public virtual BaseItem DisplayParent
  383. {
  384. get { return Parent; }
  385. }
  386. /// <summary>
  387. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  388. /// </summary>
  389. /// <value>The premiere date.</value>
  390. public DateTime? PremiereDate { get; set; }
  391. /// <summary>
  392. /// Gets or sets the end date.
  393. /// </summary>
  394. /// <value>The end date.</value>
  395. public DateTime? EndDate { get; set; }
  396. /// <summary>
  397. /// Gets or sets the display type of the media.
  398. /// </summary>
  399. /// <value>The display type of the media.</value>
  400. public string DisplayMediaType { get; set; }
  401. /// <summary>
  402. /// Gets or sets the official rating.
  403. /// </summary>
  404. /// <value>The official rating.</value>
  405. public string OfficialRating { get; set; }
  406. /// <summary>
  407. /// Gets or sets the official rating description.
  408. /// </summary>
  409. /// <value>The official rating description.</value>
  410. public string OfficialRatingDescription { get; set; }
  411. /// <summary>
  412. /// Gets or sets the custom rating.
  413. /// </summary>
  414. /// <value>The custom rating.</value>
  415. public string CustomRating { get; set; }
  416. /// <summary>
  417. /// Gets or sets the overview.
  418. /// </summary>
  419. /// <value>The overview.</value>
  420. public string Overview { get; set; }
  421. /// <summary>
  422. /// Gets or sets the people.
  423. /// </summary>
  424. /// <value>The people.</value>
  425. public List<PersonInfo> People { get; set; }
  426. /// <summary>
  427. /// Gets or sets the studios.
  428. /// </summary>
  429. /// <value>The studios.</value>
  430. public List<string> Studios { get; set; }
  431. /// <summary>
  432. /// Gets or sets the genres.
  433. /// </summary>
  434. /// <value>The genres.</value>
  435. public List<string> Genres { get; set; }
  436. /// <summary>
  437. /// Gets or sets the home page URL.
  438. /// </summary>
  439. /// <value>The home page URL.</value>
  440. public string HomePageUrl { get; set; }
  441. /// <summary>
  442. /// Gets or sets the community rating.
  443. /// </summary>
  444. /// <value>The community rating.</value>
  445. public float? CommunityRating { get; set; }
  446. /// <summary>
  447. /// Gets or sets the community rating vote count.
  448. /// </summary>
  449. /// <value>The community rating vote count.</value>
  450. public int? VoteCount { get; set; }
  451. /// <summary>
  452. /// Gets or sets the run time ticks.
  453. /// </summary>
  454. /// <value>The run time ticks.</value>
  455. public long? RunTimeTicks { get; set; }
  456. /// <summary>
  457. /// Gets or sets the production year.
  458. /// </summary>
  459. /// <value>The production year.</value>
  460. public int? ProductionYear { get; set; }
  461. /// <summary>
  462. /// If the item is part of a series, this is it's number in the series.
  463. /// This could be episode number, album track number, etc.
  464. /// </summary>
  465. /// <value>The index number.</value>
  466. public int? IndexNumber { get; set; }
  467. /// <summary>
  468. /// For an episode this could be the season number, or for a song this could be the disc number.
  469. /// </summary>
  470. /// <value>The parent index number.</value>
  471. public int? ParentIndexNumber { get; set; }
  472. [IgnoreDataMember]
  473. public virtual string OfficialRatingForComparison
  474. {
  475. get { return OfficialRating; }
  476. }
  477. [IgnoreDataMember]
  478. public string CustomRatingForComparison
  479. {
  480. get
  481. {
  482. if (!string.IsNullOrEmpty(CustomRating))
  483. {
  484. return CustomRating;
  485. }
  486. var parent = DisplayParent;
  487. if (parent != null)
  488. {
  489. return parent.CustomRatingForComparison;
  490. }
  491. return null;
  492. }
  493. }
  494. /// <summary>
  495. /// Gets the play access.
  496. /// </summary>
  497. /// <param name="user">The user.</param>
  498. /// <returns>PlayAccess.</returns>
  499. public PlayAccess GetPlayAccess(User user)
  500. {
  501. if (!user.Configuration.EnableMediaPlayback)
  502. {
  503. return PlayAccess.None;
  504. }
  505. //if (!user.IsParentalScheduleAllowed())
  506. //{
  507. // return PlayAccess.None;
  508. //}
  509. return PlayAccess.Full;
  510. }
  511. /// <summary>
  512. /// Loads the theme songs.
  513. /// </summary>
  514. /// <returns>List{Audio.Audio}.</returns>
  515. private IEnumerable<Audio.Audio> LoadThemeSongs(List<FileSystemInfo> fileSystemChildren, IDirectoryService directoryService)
  516. {
  517. var files = fileSystemChildren.OfType<DirectoryInfo>()
  518. .Where(i => string.Equals(i.Name, ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase))
  519. .SelectMany(i => i.EnumerateFiles("*", SearchOption.TopDirectoryOnly))
  520. .ToList();
  521. // Support plex/xbmc convention
  522. files.AddRange(fileSystemChildren.OfType<FileInfo>()
  523. .Where(i => string.Equals(FileSystem.GetFileNameWithoutExtension(i), ThemeSongFilename, StringComparison.OrdinalIgnoreCase))
  524. );
  525. return LibraryManager.ResolvePaths(files, directoryService, null)
  526. .OfType<Audio.Audio>()
  527. .Select(audio =>
  528. {
  529. // Try to retrieve it from the db. If we don't find it, use the resolved version
  530. var dbItem = LibraryManager.GetItemById(audio.Id) as Audio.Audio;
  531. if (dbItem != null)
  532. {
  533. audio = dbItem;
  534. }
  535. audio.ExtraType = ExtraType.ThemeSong;
  536. return audio;
  537. // Sort them so that the list can be easily compared for changes
  538. }).OrderBy(i => i.Path).ToList();
  539. }
  540. /// <summary>
  541. /// Loads the video backdrops.
  542. /// </summary>
  543. /// <returns>List{Video}.</returns>
  544. private IEnumerable<Video> LoadThemeVideos(IEnumerable<FileSystemInfo> fileSystemChildren, IDirectoryService directoryService)
  545. {
  546. var files = fileSystemChildren.OfType<DirectoryInfo>()
  547. .Where(i => string.Equals(i.Name, ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase))
  548. .SelectMany(i => i.EnumerateFiles("*", SearchOption.TopDirectoryOnly));
  549. return LibraryManager.ResolvePaths(files, directoryService, null)
  550. .OfType<Video>()
  551. .Select(item =>
  552. {
  553. // Try to retrieve it from the db. If we don't find it, use the resolved version
  554. var dbItem = LibraryManager.GetItemById(item.Id) as Video;
  555. if (dbItem != null)
  556. {
  557. item = dbItem;
  558. }
  559. item.ExtraType = ExtraType.ThemeVideo;
  560. return item;
  561. // Sort them so that the list can be easily compared for changes
  562. }).OrderBy(i => i.Path).ToList();
  563. }
  564. public Task RefreshMetadata(CancellationToken cancellationToken)
  565. {
  566. return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService()), cancellationToken);
  567. }
  568. /// <summary>
  569. /// Overrides the base implementation to refresh metadata for local trailers
  570. /// </summary>
  571. /// <param name="options">The options.</param>
  572. /// <param name="cancellationToken">The cancellation token.</param>
  573. /// <returns>true if a provider reports we changed</returns>
  574. public async Task RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
  575. {
  576. var locationType = LocationType;
  577. var requiresSave = false;
  578. if (IsFolder || Parent != null)
  579. {
  580. try
  581. {
  582. var files = locationType != LocationType.Remote && locationType != LocationType.Virtual ?
  583. GetFileSystemChildren(options.DirectoryService).ToList() :
  584. new List<FileSystemInfo>();
  585. var ownedItemsChanged = await RefreshedOwnedItems(options, files, cancellationToken).ConfigureAwait(false);
  586. if (ownedItemsChanged)
  587. {
  588. requiresSave = true;
  589. }
  590. }
  591. catch (Exception ex)
  592. {
  593. Logger.ErrorException("Error refreshing owned items for {0}", ex, Path ?? Name);
  594. }
  595. }
  596. var dateLastSaved = DateLastSaved;
  597. await ProviderManager.RefreshMetadata(this, options, cancellationToken).ConfigureAwait(false);
  598. // If it wasn't saved by the provider process, save now
  599. if (requiresSave && dateLastSaved == DateLastSaved)
  600. {
  601. await UpdateToRepository(ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  602. }
  603. }
  604. /// <summary>
  605. /// Refreshes owned items such as trailers, theme videos, special features, etc.
  606. /// Returns true or false indicating if changes were found.
  607. /// </summary>
  608. /// <param name="options"></param>
  609. /// <param name="fileSystemChildren"></param>
  610. /// <param name="cancellationToken"></param>
  611. /// <returns></returns>
  612. protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  613. {
  614. var themeSongsChanged = false;
  615. var themeVideosChanged = false;
  616. var localTrailersChanged = false;
  617. if (LocationType == LocationType.FileSystem && Parent != null)
  618. {
  619. var hasThemeMedia = this as IHasThemeMedia;
  620. if (hasThemeMedia != null)
  621. {
  622. if (!IsInMixedFolder)
  623. {
  624. themeSongsChanged = await RefreshThemeSongs(hasThemeMedia, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  625. themeVideosChanged = await RefreshThemeVideos(hasThemeMedia, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  626. }
  627. }
  628. var hasTrailers = this as IHasTrailers;
  629. if (hasTrailers != null)
  630. {
  631. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  632. }
  633. }
  634. return themeSongsChanged || themeVideosChanged || localTrailersChanged;
  635. }
  636. protected virtual IEnumerable<FileSystemInfo> GetFileSystemChildren(IDirectoryService directoryService)
  637. {
  638. var path = ContainingFolderPath;
  639. return directoryService.GetFileSystemEntries(path);
  640. }
  641. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  642. {
  643. var newItems = LibraryManager.FindTrailers(this, fileSystemChildren, options.DirectoryService).ToList();
  644. var newItemIds = newItems.Select(i => i.Id).ToList();
  645. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  646. var tasks = newItems.Select(i => i.RefreshMetadata(options, cancellationToken));
  647. await Task.WhenAll(tasks).ConfigureAwait(false);
  648. item.LocalTrailerIds = newItemIds;
  649. return itemsChanged;
  650. }
  651. private async Task<bool> RefreshThemeVideos(IHasThemeMedia item, MetadataRefreshOptions options, IEnumerable<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  652. {
  653. var newThemeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService).ToList();
  654. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  655. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  656. var tasks = newThemeVideos.Select(i =>
  657. {
  658. var subOptions = new MetadataRefreshOptions(options);
  659. if (!i.IsThemeMedia)
  660. {
  661. i.IsThemeMedia = true;
  662. subOptions.ForceSave = true;
  663. }
  664. return i.RefreshMetadata(subOptions, cancellationToken);
  665. });
  666. await Task.WhenAll(tasks).ConfigureAwait(false);
  667. item.ThemeVideoIds = newThemeVideoIds;
  668. return themeVideosChanged;
  669. }
  670. /// <summary>
  671. /// Refreshes the theme songs.
  672. /// </summary>
  673. private async Task<bool> RefreshThemeSongs(IHasThemeMedia item, MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  674. {
  675. var newThemeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService).ToList();
  676. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  677. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  678. var tasks = newThemeSongs.Select(i =>
  679. {
  680. var subOptions = new MetadataRefreshOptions(options);
  681. if (!i.IsThemeMedia)
  682. {
  683. i.IsThemeMedia = true;
  684. subOptions.ForceSave = true;
  685. }
  686. return i.RefreshMetadata(subOptions, cancellationToken);
  687. });
  688. await Task.WhenAll(tasks).ConfigureAwait(false);
  689. item.ThemeSongIds = newThemeSongIds;
  690. return themeSongsChanged;
  691. }
  692. /// <summary>
  693. /// Gets or sets the provider ids.
  694. /// </summary>
  695. /// <value>The provider ids.</value>
  696. public Dictionary<string, string> ProviderIds { get; set; }
  697. /// <summary>
  698. /// Override this to false if class should be ignored for indexing purposes
  699. /// </summary>
  700. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  701. [IgnoreDataMember]
  702. public virtual bool IncludeInIndex
  703. {
  704. get { return true; }
  705. }
  706. /// <summary>
  707. /// Override this to true if class should be grouped under a container in indicies
  708. /// The container class should be defined via IndexContainer
  709. /// </summary>
  710. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  711. [IgnoreDataMember]
  712. public virtual bool GroupInIndex
  713. {
  714. get { return false; }
  715. }
  716. /// <summary>
  717. /// Override this to return the folder that should be used to construct a container
  718. /// for this item in an index. GroupInIndex should be true as well.
  719. /// </summary>
  720. /// <value>The index container.</value>
  721. [IgnoreDataMember]
  722. public virtual Folder IndexContainer
  723. {
  724. get { return null; }
  725. }
  726. [IgnoreDataMember]
  727. public virtual Folder LatestItemsIndexContainer
  728. {
  729. get { return null; }
  730. }
  731. /// <summary>
  732. /// Gets the user data key.
  733. /// </summary>
  734. /// <returns>System.String.</returns>
  735. public virtual string GetUserDataKey()
  736. {
  737. return Id.ToString();
  738. }
  739. internal virtual bool IsValidFromResolver(BaseItem newItem)
  740. {
  741. var current = this;
  742. var currentAsPlaceHolder = current as ISupportsPlaceHolders;
  743. if (currentAsPlaceHolder != null)
  744. {
  745. var newHasPlaceHolder = newItem as ISupportsPlaceHolders;
  746. if (newHasPlaceHolder != null)
  747. {
  748. if (currentAsPlaceHolder.IsPlaceHolder != newHasPlaceHolder.IsPlaceHolder)
  749. {
  750. return false;
  751. }
  752. }
  753. }
  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. };
  1414. }
  1415. /// <summary>
  1416. /// This is called before any metadata refresh and returns true or false indicating if changes were made
  1417. /// </summary>
  1418. public virtual bool BeforeMetadataRefresh()
  1419. {
  1420. var hasChanges = false;
  1421. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  1422. {
  1423. Name = FileSystem.GetFileNameWithoutExtension(Path);
  1424. hasChanges = true;
  1425. }
  1426. return hasChanges;
  1427. }
  1428. protected static string GetMappedPath(string path, LocationType locationType)
  1429. {
  1430. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1431. {
  1432. foreach (var map in ConfigurationManager.Configuration.PathSubstitutions)
  1433. {
  1434. path = FileSystem.SubstitutePath(path, map.From, map.To);
  1435. }
  1436. }
  1437. return path;
  1438. }
  1439. public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, User user)
  1440. {
  1441. if (RunTimeTicks.HasValue)
  1442. {
  1443. double pct = RunTimeTicks.Value;
  1444. if (pct > 0)
  1445. {
  1446. pct = userData.PlaybackPositionTicks / pct;
  1447. if (pct > 0)
  1448. {
  1449. dto.PlayedPercentage = 100 * pct;
  1450. }
  1451. }
  1452. }
  1453. }
  1454. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, string path, CancellationToken cancellationToken)
  1455. {
  1456. var newOptions = new MetadataRefreshOptions(options.DirectoryService)
  1457. {
  1458. ImageRefreshMode = options.ImageRefreshMode,
  1459. MetadataRefreshMode = options.MetadataRefreshMode,
  1460. ReplaceAllMetadata = options.ReplaceAllMetadata
  1461. };
  1462. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  1463. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1464. var video = LibraryManager.GetItemById(id) as Video;
  1465. if (video == null)
  1466. {
  1467. video = LibraryManager.ResolvePath(new FileInfo(path)) as Video;
  1468. newOptions.ForceSave = true;
  1469. }
  1470. if (video == null)
  1471. {
  1472. return Task.FromResult(true);
  1473. }
  1474. return video.RefreshMetadata(newOptions, cancellationToken);
  1475. }
  1476. }
  1477. }