BaseItem.cs 60 KB

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