2
0

BaseItem.cs 58 KB

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