BaseItem.cs 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798
  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 (IsFolder || Parent != null)
  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. /// <summary>
  618. /// Refreshes owned items such as trailers, theme videos, special features, etc.
  619. /// Returns true or false indicating if changes were found.
  620. /// </summary>
  621. /// <param name="options"></param>
  622. /// <param name="fileSystemChildren"></param>
  623. /// <param name="cancellationToken"></param>
  624. /// <returns></returns>
  625. protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  626. {
  627. var themeSongsChanged = false;
  628. var themeVideosChanged = false;
  629. var localTrailersChanged = false;
  630. if (LocationType == LocationType.FileSystem && Parent != null)
  631. {
  632. var hasThemeMedia = this as IHasThemeMedia;
  633. if (hasThemeMedia != null)
  634. {
  635. if (!IsInMixedFolder)
  636. {
  637. themeSongsChanged = await RefreshThemeSongs(hasThemeMedia, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  638. themeVideosChanged = await RefreshThemeVideos(hasThemeMedia, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  639. }
  640. }
  641. var hasTrailers = this as IHasTrailers;
  642. if (hasTrailers != null)
  643. {
  644. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  645. }
  646. }
  647. return themeSongsChanged || themeVideosChanged || localTrailersChanged;
  648. }
  649. protected virtual IEnumerable<FileSystemInfo> GetFileSystemChildren(IDirectoryService directoryService)
  650. {
  651. var path = ContainingFolderPath;
  652. return directoryService.GetFileSystemEntries(path);
  653. }
  654. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  655. {
  656. var newItems = LibraryManager.FindTrailers(this, fileSystemChildren, options.DirectoryService).ToList();
  657. var newItemIds = newItems.Select(i => i.Id).ToList();
  658. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  659. var tasks = newItems.Select(i => i.RefreshMetadata(options, cancellationToken));
  660. await Task.WhenAll(tasks).ConfigureAwait(false);
  661. item.LocalTrailerIds = newItemIds;
  662. return itemsChanged;
  663. }
  664. private async Task<bool> RefreshThemeVideos(IHasThemeMedia item, MetadataRefreshOptions options, IEnumerable<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  665. {
  666. var newThemeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService).ToList();
  667. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  668. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  669. var tasks = newThemeVideos.Select(i =>
  670. {
  671. var subOptions = new MetadataRefreshOptions(options);
  672. if (!i.IsThemeMedia)
  673. {
  674. i.IsThemeMedia = true;
  675. subOptions.ForceSave = true;
  676. }
  677. return i.RefreshMetadata(subOptions, cancellationToken);
  678. });
  679. await Task.WhenAll(tasks).ConfigureAwait(false);
  680. item.ThemeVideoIds = newThemeVideoIds;
  681. return themeVideosChanged;
  682. }
  683. /// <summary>
  684. /// Refreshes the theme songs.
  685. /// </summary>
  686. private async Task<bool> RefreshThemeSongs(IHasThemeMedia item, MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  687. {
  688. var newThemeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService).ToList();
  689. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  690. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  691. var tasks = newThemeSongs.Select(i =>
  692. {
  693. var subOptions = new MetadataRefreshOptions(options);
  694. if (!i.IsThemeMedia)
  695. {
  696. i.IsThemeMedia = true;
  697. subOptions.ForceSave = true;
  698. }
  699. return i.RefreshMetadata(subOptions, cancellationToken);
  700. });
  701. await Task.WhenAll(tasks).ConfigureAwait(false);
  702. item.ThemeSongIds = newThemeSongIds;
  703. return themeSongsChanged;
  704. }
  705. /// <summary>
  706. /// Gets or sets the provider ids.
  707. /// </summary>
  708. /// <value>The provider ids.</value>
  709. public Dictionary<string, string> ProviderIds { get; set; }
  710. /// <summary>
  711. /// Override this to false if class should be ignored for indexing purposes
  712. /// </summary>
  713. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  714. [IgnoreDataMember]
  715. public virtual bool IncludeInIndex
  716. {
  717. get { return true; }
  718. }
  719. /// <summary>
  720. /// Override this to true if class should be grouped under a container in indicies
  721. /// The container class should be defined via IndexContainer
  722. /// </summary>
  723. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  724. [IgnoreDataMember]
  725. public virtual bool GroupInIndex
  726. {
  727. get { return false; }
  728. }
  729. /// <summary>
  730. /// Override this to return the folder that should be used to construct a container
  731. /// for this item in an index. GroupInIndex should be true as well.
  732. /// </summary>
  733. /// <value>The index container.</value>
  734. [IgnoreDataMember]
  735. public virtual Folder IndexContainer
  736. {
  737. get { return null; }
  738. }
  739. [IgnoreDataMember]
  740. public virtual Folder LatestItemsIndexContainer
  741. {
  742. get { return null; }
  743. }
  744. private string _userDataKey;
  745. /// <summary>
  746. /// Gets the user data key.
  747. /// </summary>
  748. /// <returns>System.String.</returns>
  749. public string GetUserDataKey()
  750. {
  751. if (string.IsNullOrWhiteSpace(_userDataKey))
  752. {
  753. var key = CreateUserDataKey();
  754. _userDataKey = key;
  755. return key;
  756. }
  757. return _userDataKey;
  758. }
  759. protected virtual string CreateUserDataKey()
  760. {
  761. return Id.ToString();
  762. }
  763. internal virtual bool IsValidFromResolver(BaseItem newItem)
  764. {
  765. var current = this;
  766. return current.IsInMixedFolder == newItem.IsInMixedFolder;
  767. }
  768. public void AfterMetadataRefresh()
  769. {
  770. _sortName = null;
  771. _userDataKey = null;
  772. }
  773. /// <summary>
  774. /// Gets the preferred metadata language.
  775. /// </summary>
  776. /// <returns>System.String.</returns>
  777. public string GetPreferredMetadataLanguage()
  778. {
  779. string lang = null;
  780. var hasLang = this as IHasPreferredMetadataLanguage;
  781. if (hasLang != null)
  782. {
  783. lang = hasLang.PreferredMetadataLanguage;
  784. }
  785. if (string.IsNullOrEmpty(lang))
  786. {
  787. lang = Parents.OfType<IHasPreferredMetadataLanguage>()
  788. .Select(i => i.PreferredMetadataLanguage)
  789. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  790. }
  791. if (string.IsNullOrEmpty(lang))
  792. {
  793. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  794. }
  795. return lang;
  796. }
  797. /// <summary>
  798. /// Gets the preferred metadata language.
  799. /// </summary>
  800. /// <returns>System.String.</returns>
  801. public string GetPreferredMetadataCountryCode()
  802. {
  803. string lang = null;
  804. var hasLang = this as IHasPreferredMetadataLanguage;
  805. if (hasLang != null)
  806. {
  807. lang = hasLang.PreferredMetadataCountryCode;
  808. }
  809. if (string.IsNullOrEmpty(lang))
  810. {
  811. lang = Parents.OfType<IHasPreferredMetadataLanguage>()
  812. .Select(i => i.PreferredMetadataCountryCode)
  813. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  814. }
  815. if (string.IsNullOrEmpty(lang))
  816. {
  817. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  818. }
  819. return lang;
  820. }
  821. public virtual bool IsSaveLocalMetadataEnabled()
  822. {
  823. return ConfigurationManager.Configuration.SaveLocalMeta;
  824. }
  825. /// <summary>
  826. /// Determines if a given user has access to this item
  827. /// </summary>
  828. /// <param name="user">The user.</param>
  829. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  830. /// <exception cref="System.ArgumentNullException">user</exception>
  831. public bool IsParentalAllowed(User user)
  832. {
  833. if (user == null)
  834. {
  835. throw new ArgumentNullException("user");
  836. }
  837. if (!IsVisibleViaTags(user))
  838. {
  839. return false;
  840. }
  841. var maxAllowedRating = user.Policy.MaxParentalRating;
  842. if (maxAllowedRating == null)
  843. {
  844. return true;
  845. }
  846. var rating = CustomRatingForComparison;
  847. if (string.IsNullOrWhiteSpace(rating))
  848. {
  849. rating = OfficialRatingForComparison;
  850. }
  851. if (string.IsNullOrWhiteSpace(rating))
  852. {
  853. return !GetBlockUnratedValue(user.Policy);
  854. }
  855. var value = LocalizationManager.GetRatingLevel(rating);
  856. // Could not determine the integer value
  857. if (!value.HasValue)
  858. {
  859. return true;
  860. }
  861. return value.Value <= maxAllowedRating.Value;
  862. }
  863. private bool IsVisibleViaTags(User user)
  864. {
  865. var hasTags = this as IHasTags;
  866. if (hasTags != null)
  867. {
  868. if (user.Policy.BlockedTags.Any(i => hasTags.Tags.Contains(i, StringComparer.OrdinalIgnoreCase)))
  869. {
  870. return false;
  871. }
  872. }
  873. return true;
  874. }
  875. /// <summary>
  876. /// Gets the block unrated value.
  877. /// </summary>
  878. /// <param name="config">The configuration.</param>
  879. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  880. protected virtual bool GetBlockUnratedValue(UserPolicy config)
  881. {
  882. return config.BlockUnratedItems.Contains(UnratedItem.Other);
  883. }
  884. /// <summary>
  885. /// Determines if this folder should be visible to a given user.
  886. /// Default is just parental allowed. Can be overridden for more functionality.
  887. /// </summary>
  888. /// <param name="user">The user.</param>
  889. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  890. /// <exception cref="System.ArgumentNullException">user</exception>
  891. public virtual bool IsVisible(User user)
  892. {
  893. if (user == null)
  894. {
  895. throw new ArgumentNullException("user");
  896. }
  897. return IsParentalAllowed(user);
  898. }
  899. /// <summary>
  900. /// Gets a value indicating whether this instance is folder.
  901. /// </summary>
  902. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  903. [IgnoreDataMember]
  904. public virtual bool IsFolder
  905. {
  906. get
  907. {
  908. return false;
  909. }
  910. }
  911. public virtual string GetClientTypeName()
  912. {
  913. return GetType().Name;
  914. }
  915. /// <summary>
  916. /// Gets the linked child.
  917. /// </summary>
  918. /// <param name="info">The info.</param>
  919. /// <returns>BaseItem.</returns>
  920. protected BaseItem GetLinkedChild(LinkedChild info)
  921. {
  922. // First get using the cached Id
  923. if (info.ItemId.HasValue)
  924. {
  925. if (info.ItemId.Value == Guid.Empty)
  926. {
  927. return null;
  928. }
  929. var itemById = LibraryManager.GetItemById(info.ItemId.Value);
  930. if (itemById != null)
  931. {
  932. return itemById;
  933. }
  934. }
  935. var item = FindLinkedChild(info);
  936. // If still null, log
  937. if (item == null)
  938. {
  939. // Don't keep searching over and over
  940. info.ItemId = Guid.Empty;
  941. }
  942. else
  943. {
  944. // Cache the id for next time
  945. info.ItemId = item.Id;
  946. }
  947. return item;
  948. }
  949. private BaseItem FindLinkedChild(LinkedChild info)
  950. {
  951. if (!string.IsNullOrWhiteSpace(info.ItemName))
  952. {
  953. if (string.Equals(info.ItemType, "musicgenre", StringComparison.OrdinalIgnoreCase))
  954. {
  955. return LibraryManager.GetMusicGenre(info.ItemName);
  956. }
  957. if (string.Equals(info.ItemType, "musicartist", StringComparison.OrdinalIgnoreCase))
  958. {
  959. return LibraryManager.GetArtist(info.ItemName);
  960. }
  961. }
  962. if (!string.IsNullOrEmpty(info.Path))
  963. {
  964. var itemByPath = LibraryManager.RootFolder.FindByPath(info.Path);
  965. if (itemByPath == null)
  966. {
  967. Logger.Warn("Unable to find linked item at path {0}", info.Path);
  968. }
  969. return itemByPath;
  970. }
  971. if (!string.IsNullOrWhiteSpace(info.ItemName) && !string.IsNullOrWhiteSpace(info.ItemType))
  972. {
  973. return LibraryManager.RootFolder.GetRecursiveChildren(i =>
  974. {
  975. if (string.Equals(i.Name, info.ItemName, StringComparison.OrdinalIgnoreCase))
  976. {
  977. if (string.Equals(i.GetType().Name, info.ItemType, StringComparison.OrdinalIgnoreCase))
  978. {
  979. if (info.ItemYear.HasValue)
  980. {
  981. if (info.ItemYear.Value != (i.ProductionYear ?? -1))
  982. {
  983. return false;
  984. }
  985. }
  986. return true;
  987. }
  988. }
  989. return false;
  990. }).FirstOrDefault();
  991. }
  992. return null;
  993. }
  994. /// <summary>
  995. /// Adds a person to the item
  996. /// </summary>
  997. /// <param name="person">The person.</param>
  998. /// <exception cref="System.ArgumentNullException"></exception>
  999. public void AddPerson(PersonInfo person)
  1000. {
  1001. if (person == null)
  1002. {
  1003. throw new ArgumentNullException("person");
  1004. }
  1005. if (string.IsNullOrWhiteSpace(person.Name))
  1006. {
  1007. throw new ArgumentNullException();
  1008. }
  1009. // Normalize
  1010. if (string.Equals(person.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  1011. {
  1012. person.Type = PersonType.GuestStar;
  1013. }
  1014. else if (string.Equals(person.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
  1015. {
  1016. person.Type = PersonType.Director;
  1017. }
  1018. else if (string.Equals(person.Role, PersonType.Producer, StringComparison.OrdinalIgnoreCase))
  1019. {
  1020. person.Type = PersonType.Producer;
  1021. }
  1022. else if (string.Equals(person.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
  1023. {
  1024. person.Type = PersonType.Writer;
  1025. }
  1026. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  1027. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  1028. {
  1029. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  1030. if (existing != null)
  1031. {
  1032. existing.Type = PersonType.GuestStar;
  1033. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  1034. return;
  1035. }
  1036. }
  1037. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  1038. {
  1039. // If the actor already exists without a role and we have one, fill it in
  1040. 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)));
  1041. if (existing == null)
  1042. {
  1043. // Wasn't there - add it
  1044. People.Add(person);
  1045. }
  1046. else
  1047. {
  1048. // Was there, if no role and we have one - fill it in
  1049. if (string.IsNullOrWhiteSpace(existing.Role) && !string.IsNullOrWhiteSpace(person.Role))
  1050. {
  1051. existing.Role = person.Role;
  1052. }
  1053. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  1054. }
  1055. }
  1056. else
  1057. {
  1058. var existing = People.FirstOrDefault(p =>
  1059. string.Equals(p.Name, person.Name, StringComparison.OrdinalIgnoreCase) &&
  1060. string.Equals(p.Type, person.Type, StringComparison.OrdinalIgnoreCase));
  1061. // Check for dupes based on the combination of Name and Type
  1062. if (existing == null)
  1063. {
  1064. People.Add(person);
  1065. }
  1066. else
  1067. {
  1068. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  1069. }
  1070. }
  1071. }
  1072. /// <summary>
  1073. /// Adds a studio to the item
  1074. /// </summary>
  1075. /// <param name="name">The name.</param>
  1076. /// <exception cref="System.ArgumentNullException"></exception>
  1077. public void AddStudio(string name)
  1078. {
  1079. if (string.IsNullOrWhiteSpace(name))
  1080. {
  1081. throw new ArgumentNullException("name");
  1082. }
  1083. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1084. {
  1085. Studios.Add(name);
  1086. }
  1087. }
  1088. /// <summary>
  1089. /// Adds a genre to the item
  1090. /// </summary>
  1091. /// <param name="name">The name.</param>
  1092. /// <exception cref="System.ArgumentNullException"></exception>
  1093. public void AddGenre(string name)
  1094. {
  1095. if (string.IsNullOrWhiteSpace(name))
  1096. {
  1097. throw new ArgumentNullException("name");
  1098. }
  1099. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1100. {
  1101. Genres.Add(name);
  1102. }
  1103. }
  1104. /// <summary>
  1105. /// Marks the played.
  1106. /// </summary>
  1107. /// <param name="user">The user.</param>
  1108. /// <param name="datePlayed">The date played.</param>
  1109. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1110. /// <returns>Task.</returns>
  1111. /// <exception cref="System.ArgumentNullException"></exception>
  1112. public virtual async Task MarkPlayed(User user,
  1113. DateTime? datePlayed,
  1114. bool resetPosition)
  1115. {
  1116. if (user == null)
  1117. {
  1118. throw new ArgumentNullException();
  1119. }
  1120. var key = GetUserDataKey();
  1121. var data = UserDataManager.GetUserData(user.Id, key);
  1122. if (datePlayed.HasValue)
  1123. {
  1124. // Incremenet
  1125. data.PlayCount++;
  1126. }
  1127. // Ensure it's at least one
  1128. data.PlayCount = Math.Max(data.PlayCount, 1);
  1129. if (resetPosition)
  1130. {
  1131. data.PlaybackPositionTicks = 0;
  1132. }
  1133. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate;
  1134. data.Played = true;
  1135. await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1136. }
  1137. /// <summary>
  1138. /// Marks the unplayed.
  1139. /// </summary>
  1140. /// <param name="user">The user.</param>
  1141. /// <returns>Task.</returns>
  1142. /// <exception cref="System.ArgumentNullException"></exception>
  1143. public virtual async Task MarkUnplayed(User user)
  1144. {
  1145. if (user == null)
  1146. {
  1147. throw new ArgumentNullException();
  1148. }
  1149. var key = GetUserDataKey();
  1150. var data = UserDataManager.GetUserData(user.Id, key);
  1151. //I think it is okay to do this here.
  1152. // if this is only called when a user is manually forcing something to un-played
  1153. // then it probably is what we want to do...
  1154. data.PlayCount = 0;
  1155. data.PlaybackPositionTicks = 0;
  1156. data.LastPlayedDate = null;
  1157. data.Played = false;
  1158. await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1159. }
  1160. /// <summary>
  1161. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1162. /// </summary>
  1163. /// <returns>Task.</returns>
  1164. public virtual Task ChangedExternally()
  1165. {
  1166. return RefreshMetadata(CancellationToken.None);
  1167. }
  1168. /// <summary>
  1169. /// Finds a parent of a given type
  1170. /// </summary>
  1171. /// <typeparam name="T"></typeparam>
  1172. /// <returns>``0.</returns>
  1173. public T FindParent<T>()
  1174. where T : Folder
  1175. {
  1176. var parent = Parent;
  1177. while (parent != null)
  1178. {
  1179. var result = parent as T;
  1180. if (result != null)
  1181. {
  1182. return result;
  1183. }
  1184. parent = parent.Parent;
  1185. }
  1186. return null;
  1187. }
  1188. /// <summary>
  1189. /// Gets an image
  1190. /// </summary>
  1191. /// <param name="type">The type.</param>
  1192. /// <param name="imageIndex">Index of the image.</param>
  1193. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1194. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1195. public bool HasImage(ImageType type, int imageIndex)
  1196. {
  1197. return GetImageInfo(type, imageIndex) != null;
  1198. }
  1199. public void SetImagePath(ImageType type, int index, FileSystemInfo file)
  1200. {
  1201. if (type == ImageType.Chapter)
  1202. {
  1203. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1204. }
  1205. var image = GetImageInfo(type, index);
  1206. if (image == null)
  1207. {
  1208. ImageInfos.Add(GetImageInfo(file, type));
  1209. }
  1210. else
  1211. {
  1212. var imageInfo = GetImageInfo(file, type);
  1213. image.Path = file.FullName;
  1214. image.DateModified = imageInfo.DateModified;
  1215. }
  1216. }
  1217. /// <summary>
  1218. /// Deletes the image.
  1219. /// </summary>
  1220. /// <param name="type">The type.</param>
  1221. /// <param name="index">The index.</param>
  1222. /// <returns>Task.</returns>
  1223. public Task DeleteImage(ImageType type, int index)
  1224. {
  1225. var info = GetImageInfo(type, index);
  1226. if (info == null)
  1227. {
  1228. // Nothing to do
  1229. return Task.FromResult(true);
  1230. }
  1231. // Remove it from the item
  1232. ImageInfos.Remove(info);
  1233. // Delete the source file
  1234. var currentFile = new FileInfo(info.Path);
  1235. // Deletion will fail if the file is hidden so remove the attribute first
  1236. if (currentFile.Exists)
  1237. {
  1238. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  1239. {
  1240. currentFile.Attributes &= ~FileAttributes.Hidden;
  1241. }
  1242. FileSystem.DeleteFile(currentFile.FullName);
  1243. }
  1244. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1245. }
  1246. public virtual Task UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1247. {
  1248. return LibraryManager.UpdateItem(this, updateReason, cancellationToken);
  1249. }
  1250. /// <summary>
  1251. /// Validates that images within the item are still on the file system
  1252. /// </summary>
  1253. public bool ValidateImages(IDirectoryService directoryService)
  1254. {
  1255. var allDirectories = ImageInfos.Select(i => System.IO.Path.GetDirectoryName(i.Path)).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  1256. var allFiles = allDirectories.SelectMany(directoryService.GetFiles).Select(i => i.FullName).ToList();
  1257. var deletedImages = ImageInfos
  1258. .Where(image => !allFiles.Contains(image.Path, StringComparer.OrdinalIgnoreCase))
  1259. .ToList();
  1260. if (deletedImages.Count > 0)
  1261. {
  1262. ImageInfos = ImageInfos.Except(deletedImages).ToList();
  1263. }
  1264. return deletedImages.Count > 0;
  1265. }
  1266. /// <summary>
  1267. /// Gets the image path.
  1268. /// </summary>
  1269. /// <param name="imageType">Type of the image.</param>
  1270. /// <param name="imageIndex">Index of the image.</param>
  1271. /// <returns>System.String.</returns>
  1272. /// <exception cref="System.InvalidOperationException">
  1273. /// </exception>
  1274. /// <exception cref="System.ArgumentNullException">item</exception>
  1275. public string GetImagePath(ImageType imageType, int imageIndex)
  1276. {
  1277. var info = GetImageInfo(imageType, imageIndex);
  1278. return info == null ? null : info.Path;
  1279. }
  1280. /// <summary>
  1281. /// Gets the image information.
  1282. /// </summary>
  1283. /// <param name="imageType">Type of the image.</param>
  1284. /// <param name="imageIndex">Index of the image.</param>
  1285. /// <returns>ItemImageInfo.</returns>
  1286. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1287. {
  1288. if (imageType == ImageType.Chapter)
  1289. {
  1290. var chapter = ItemRepository.GetChapter(Id, imageIndex);
  1291. if (chapter == null)
  1292. {
  1293. return null;
  1294. }
  1295. var path = chapter.ImagePath;
  1296. if (string.IsNullOrWhiteSpace(path))
  1297. {
  1298. return null;
  1299. }
  1300. return new ItemImageInfo
  1301. {
  1302. Path = path,
  1303. DateModified = FileSystem.GetLastWriteTimeUtc(path),
  1304. Type = imageType
  1305. };
  1306. }
  1307. return GetImages(imageType)
  1308. .ElementAtOrDefault(imageIndex);
  1309. }
  1310. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1311. {
  1312. if (imageType == ImageType.Chapter)
  1313. {
  1314. throw new ArgumentException("No image info for chapter images");
  1315. }
  1316. return ImageInfos.Where(i => i.Type == imageType);
  1317. }
  1318. public bool AddImages(ImageType imageType, IEnumerable<FileInfo> images)
  1319. {
  1320. return AddImages(imageType, images.Cast<FileSystemInfo>());
  1321. }
  1322. /// <summary>
  1323. /// Adds the images.
  1324. /// </summary>
  1325. /// <param name="imageType">Type of the image.</param>
  1326. /// <param name="images">The images.</param>
  1327. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1328. /// <exception cref="System.ArgumentException">Cannot call AddImages with chapter images</exception>
  1329. public bool AddImages(ImageType imageType, IEnumerable<FileSystemInfo> images)
  1330. {
  1331. if (imageType == ImageType.Chapter)
  1332. {
  1333. throw new ArgumentException("Cannot call AddImages with chapter images");
  1334. }
  1335. var existingImages = GetImages(imageType)
  1336. .ToList();
  1337. var newImageList = new List<FileSystemInfo>();
  1338. foreach (var newImage in images)
  1339. {
  1340. if (newImage == null)
  1341. {
  1342. throw new ArgumentException("null image found in list");
  1343. }
  1344. var existing = existingImages
  1345. .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  1346. if (existing == null)
  1347. {
  1348. newImageList.Add(newImage);
  1349. }
  1350. else
  1351. {
  1352. existing.DateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  1353. }
  1354. }
  1355. ImageInfos.AddRange(newImageList.Select(i => GetImageInfo(i, imageType)));
  1356. return newImageList.Count > 0;
  1357. }
  1358. private ItemImageInfo GetImageInfo(FileSystemInfo file, ImageType type)
  1359. {
  1360. return new ItemImageInfo
  1361. {
  1362. Path = file.FullName,
  1363. Type = type,
  1364. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  1365. };
  1366. }
  1367. /// <summary>
  1368. /// Gets the file system path to delete when the item is to be deleted
  1369. /// </summary>
  1370. /// <returns></returns>
  1371. public virtual IEnumerable<string> GetDeletePaths()
  1372. {
  1373. return new[] { Path };
  1374. }
  1375. public bool AllowsMultipleImages(ImageType type)
  1376. {
  1377. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  1378. }
  1379. public Task SwapImages(ImageType type, int index1, int index2)
  1380. {
  1381. if (!AllowsMultipleImages(type))
  1382. {
  1383. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  1384. }
  1385. var info1 = GetImageInfo(type, index1);
  1386. var info2 = GetImageInfo(type, index2);
  1387. if (info1 == null || info2 == null)
  1388. {
  1389. // Nothing to do
  1390. return Task.FromResult(true);
  1391. }
  1392. var path1 = info1.Path;
  1393. var path2 = info2.Path;
  1394. FileSystem.SwapFiles(path1, path2);
  1395. // Refresh these values
  1396. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  1397. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  1398. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1399. }
  1400. public virtual bool IsPlayed(User user)
  1401. {
  1402. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1403. return userdata != null && userdata.Played;
  1404. }
  1405. public bool IsFavoriteOrLiked(User user)
  1406. {
  1407. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1408. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  1409. }
  1410. public virtual bool IsUnplayed(User user)
  1411. {
  1412. if (user == null)
  1413. {
  1414. throw new ArgumentNullException("user");
  1415. }
  1416. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1417. return userdata == null || !userdata.Played;
  1418. }
  1419. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  1420. {
  1421. return GetItemLookupInfo<ItemLookupInfo>();
  1422. }
  1423. protected T GetItemLookupInfo<T>()
  1424. where T : ItemLookupInfo, new()
  1425. {
  1426. return new T
  1427. {
  1428. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  1429. MetadataLanguage = GetPreferredMetadataLanguage(),
  1430. Name = Name,
  1431. ProviderIds = ProviderIds,
  1432. IndexNumber = IndexNumber,
  1433. ParentIndexNumber = ParentIndexNumber,
  1434. Year = ProductionYear
  1435. };
  1436. }
  1437. /// <summary>
  1438. /// This is called before any metadata refresh and returns true or false indicating if changes were made
  1439. /// </summary>
  1440. public virtual bool BeforeMetadataRefresh()
  1441. {
  1442. _userDataKey = null;
  1443. _sortName = null;
  1444. var hasChanges = false;
  1445. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  1446. {
  1447. Name = FileSystem.GetFileNameWithoutExtension(Path);
  1448. hasChanges = true;
  1449. }
  1450. return hasChanges;
  1451. }
  1452. protected static string GetMappedPath(string path, LocationType locationType)
  1453. {
  1454. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1455. {
  1456. foreach (var map in ConfigurationManager.Configuration.PathSubstitutions)
  1457. {
  1458. path = FileSystem.SubstitutePath(path, map.From, map.To);
  1459. }
  1460. }
  1461. return path;
  1462. }
  1463. public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, User user)
  1464. {
  1465. if (RunTimeTicks.HasValue)
  1466. {
  1467. double pct = RunTimeTicks.Value;
  1468. if (pct > 0)
  1469. {
  1470. pct = userData.PlaybackPositionTicks / pct;
  1471. if (pct > 0)
  1472. {
  1473. dto.PlayedPercentage = 100 * pct;
  1474. }
  1475. }
  1476. }
  1477. }
  1478. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, string path, CancellationToken cancellationToken)
  1479. {
  1480. var newOptions = new MetadataRefreshOptions(options.DirectoryService)
  1481. {
  1482. ImageRefreshMode = options.ImageRefreshMode,
  1483. MetadataRefreshMode = options.MetadataRefreshMode,
  1484. ReplaceAllMetadata = options.ReplaceAllMetadata
  1485. };
  1486. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  1487. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1488. var video = LibraryManager.GetItemById(id) as Video;
  1489. if (video == null)
  1490. {
  1491. video = LibraryManager.ResolvePath(new FileInfo(path)) as Video;
  1492. newOptions.ForceSave = true;
  1493. }
  1494. if (video == null)
  1495. {
  1496. return Task.FromResult(true);
  1497. }
  1498. return video.RefreshMetadata(newOptions, cancellationToken);
  1499. }
  1500. }
  1501. }