BaseItem.cs 57 KB

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