BaseItem.cs 57 KB

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