BaseItem.cs 60 KB

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