BaseItem.cs 58 KB

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