BaseItem.cs 58 KB

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