BaseItem.cs 56 KB

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