BaseItem.cs 56 KB

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