BaseItem.cs 59 KB

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