BaseItem.cs 60 KB

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