BaseItem.cs 61 KB

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