BaseItem.cs 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777
  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.IsNullOrEmpty(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. return GetInternalMetadataPath(ConfigurationManager.ApplicationPaths.InternalMetadataPath);
  336. }
  337. protected virtual string GetInternalMetadataPath(string basePath)
  338. {
  339. var idString = Id.ToString("N");
  340. return System.IO.Path.Combine(basePath, idString.Substring(0, 2), idString);
  341. }
  342. public static string GetInternalMetadataPathForId(Guid id)
  343. {
  344. var idString = id.ToString("N");
  345. var basePath = ConfigurationManager.ApplicationPaths.InternalMetadataPath;
  346. return System.IO.Path.Combine(basePath, idString.Substring(0, 2), idString);
  347. }
  348. /// <summary>
  349. /// Creates the name of the sort.
  350. /// </summary>
  351. /// <returns>System.String.</returns>
  352. protected virtual string CreateSortName()
  353. {
  354. if (Name == null) return null; //some items may not have name filled in properly
  355. var sortable = Name.Trim().ToLower();
  356. sortable = ConfigurationManager.Configuration.SortRemoveCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), string.Empty));
  357. sortable = ConfigurationManager.Configuration.SortReplaceCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), " "));
  358. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  359. {
  360. var searchLower = search.ToLower();
  361. // Remove from beginning if a space follows
  362. if (sortable.StartsWith(searchLower + " "))
  363. {
  364. sortable = sortable.Remove(0, searchLower.Length + 1);
  365. }
  366. // Remove from middle if surrounded by spaces
  367. sortable = sortable.Replace(" " + searchLower + " ", " ");
  368. // Remove from end if followed by a space
  369. if (sortable.EndsWith(" " + searchLower))
  370. {
  371. sortable = sortable.Remove(sortable.Length - (searchLower.Length + 1));
  372. }
  373. }
  374. return sortable;
  375. }
  376. /// <summary>
  377. /// Gets or sets the parent.
  378. /// </summary>
  379. /// <value>The parent.</value>
  380. [IgnoreDataMember]
  381. public Folder Parent { get; set; }
  382. [IgnoreDataMember]
  383. public IEnumerable<Folder> Parents
  384. {
  385. get
  386. {
  387. var parent = Parent;
  388. while (parent != null)
  389. {
  390. yield return parent;
  391. parent = parent.Parent;
  392. }
  393. }
  394. }
  395. [IgnoreDataMember]
  396. public virtual BaseItem DisplayParent
  397. {
  398. get { return Parent; }
  399. }
  400. /// <summary>
  401. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  402. /// </summary>
  403. /// <value>The premiere date.</value>
  404. public DateTime? PremiereDate { get; set; }
  405. /// <summary>
  406. /// Gets or sets the end date.
  407. /// </summary>
  408. /// <value>The end date.</value>
  409. public DateTime? EndDate { get; set; }
  410. /// <summary>
  411. /// Gets or sets the display type of the media.
  412. /// </summary>
  413. /// <value>The display type of the media.</value>
  414. public string DisplayMediaType { get; set; }
  415. /// <summary>
  416. /// Gets or sets the official rating.
  417. /// </summary>
  418. /// <value>The official rating.</value>
  419. public string OfficialRating { get; set; }
  420. /// <summary>
  421. /// Gets or sets the official rating description.
  422. /// </summary>
  423. /// <value>The official rating description.</value>
  424. public string OfficialRatingDescription { get; set; }
  425. /// <summary>
  426. /// Gets or sets the custom rating.
  427. /// </summary>
  428. /// <value>The custom rating.</value>
  429. public string CustomRating { get; set; }
  430. /// <summary>
  431. /// Gets or sets the overview.
  432. /// </summary>
  433. /// <value>The overview.</value>
  434. public string Overview { get; set; }
  435. /// <summary>
  436. /// Gets or sets the people.
  437. /// </summary>
  438. /// <value>The people.</value>
  439. public List<PersonInfo> People { get; set; }
  440. /// <summary>
  441. /// Gets or sets the studios.
  442. /// </summary>
  443. /// <value>The studios.</value>
  444. public List<string> Studios { get; set; }
  445. /// <summary>
  446. /// Gets or sets the genres.
  447. /// </summary>
  448. /// <value>The genres.</value>
  449. public List<string> Genres { get; set; }
  450. /// <summary>
  451. /// Gets or sets the home page URL.
  452. /// </summary>
  453. /// <value>The home page URL.</value>
  454. public string HomePageUrl { get; set; }
  455. /// <summary>
  456. /// Gets or sets the community rating.
  457. /// </summary>
  458. /// <value>The community rating.</value>
  459. public float? CommunityRating { get; set; }
  460. /// <summary>
  461. /// Gets or sets the community rating vote count.
  462. /// </summary>
  463. /// <value>The community rating vote count.</value>
  464. public int? VoteCount { get; set; }
  465. /// <summary>
  466. /// Gets or sets the run time ticks.
  467. /// </summary>
  468. /// <value>The run time ticks.</value>
  469. public long? RunTimeTicks { get; set; }
  470. /// <summary>
  471. /// Gets or sets the production year.
  472. /// </summary>
  473. /// <value>The production year.</value>
  474. public int? ProductionYear { get; set; }
  475. /// <summary>
  476. /// If the item is part of a series, this is it's number in the series.
  477. /// This could be episode number, album track number, etc.
  478. /// </summary>
  479. /// <value>The index number.</value>
  480. public int? IndexNumber { get; set; }
  481. /// <summary>
  482. /// For an episode this could be the season number, or for a song this could be the disc number.
  483. /// </summary>
  484. /// <value>The parent index number.</value>
  485. public int? ParentIndexNumber { get; set; }
  486. [IgnoreDataMember]
  487. public virtual string OfficialRatingForComparison
  488. {
  489. get { return OfficialRating; }
  490. }
  491. [IgnoreDataMember]
  492. public string CustomRatingForComparison
  493. {
  494. get
  495. {
  496. if (!string.IsNullOrEmpty(CustomRating))
  497. {
  498. return CustomRating;
  499. }
  500. var parent = DisplayParent;
  501. if (parent != null)
  502. {
  503. return parent.CustomRatingForComparison;
  504. }
  505. return null;
  506. }
  507. }
  508. /// <summary>
  509. /// Gets the play access.
  510. /// </summary>
  511. /// <param name="user">The user.</param>
  512. /// <returns>PlayAccess.</returns>
  513. public PlayAccess GetPlayAccess(User user)
  514. {
  515. if (!user.Policy.EnableMediaPlayback)
  516. {
  517. return PlayAccess.None;
  518. }
  519. //if (!user.IsParentalScheduleAllowed())
  520. //{
  521. // return PlayAccess.None;
  522. //}
  523. return PlayAccess.Full;
  524. }
  525. /// <summary>
  526. /// Loads the theme songs.
  527. /// </summary>
  528. /// <returns>List{Audio.Audio}.</returns>
  529. private IEnumerable<Audio.Audio> LoadThemeSongs(List<FileSystemInfo> fileSystemChildren, IDirectoryService directoryService)
  530. {
  531. var files = fileSystemChildren.OfType<DirectoryInfo>()
  532. .Where(i => string.Equals(i.Name, ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase))
  533. .SelectMany(i => i.EnumerateFiles("*", SearchOption.TopDirectoryOnly))
  534. .ToList();
  535. // Support plex/xbmc convention
  536. files.AddRange(fileSystemChildren.OfType<FileInfo>()
  537. .Where(i => string.Equals(FileSystem.GetFileNameWithoutExtension(i), ThemeSongFilename, StringComparison.OrdinalIgnoreCase))
  538. );
  539. return LibraryManager.ResolvePaths(files, directoryService, null)
  540. .OfType<Audio.Audio>()
  541. .Select(audio =>
  542. {
  543. // Try to retrieve it from the db. If we don't find it, use the resolved version
  544. var dbItem = LibraryManager.GetItemById(audio.Id) as Audio.Audio;
  545. if (dbItem != null)
  546. {
  547. audio = dbItem;
  548. }
  549. audio.ExtraType = ExtraType.ThemeSong;
  550. return audio;
  551. // Sort them so that the list can be easily compared for changes
  552. }).OrderBy(i => i.Path).ToList();
  553. }
  554. /// <summary>
  555. /// Loads the video backdrops.
  556. /// </summary>
  557. /// <returns>List{Video}.</returns>
  558. private IEnumerable<Video> LoadThemeVideos(IEnumerable<FileSystemInfo> fileSystemChildren, IDirectoryService directoryService)
  559. {
  560. var files = fileSystemChildren.OfType<DirectoryInfo>()
  561. .Where(i => string.Equals(i.Name, ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase))
  562. .SelectMany(i => i.EnumerateFiles("*", SearchOption.TopDirectoryOnly));
  563. return LibraryManager.ResolvePaths(files, directoryService, null)
  564. .OfType<Video>()
  565. .Select(item =>
  566. {
  567. // Try to retrieve it from the db. If we don't find it, use the resolved version
  568. var dbItem = LibraryManager.GetItemById(item.Id) as Video;
  569. if (dbItem != null)
  570. {
  571. item = dbItem;
  572. }
  573. item.ExtraType = ExtraType.ThemeVideo;
  574. return item;
  575. // Sort them so that the list can be easily compared for changes
  576. }).OrderBy(i => i.Path).ToList();
  577. }
  578. public Task RefreshMetadata(CancellationToken cancellationToken)
  579. {
  580. return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService()), cancellationToken);
  581. }
  582. /// <summary>
  583. /// Overrides the base implementation to refresh metadata for local trailers
  584. /// </summary>
  585. /// <param name="options">The options.</param>
  586. /// <param name="cancellationToken">The cancellation token.</param>
  587. /// <returns>true if a provider reports we changed</returns>
  588. public async Task RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
  589. {
  590. var locationType = LocationType;
  591. var requiresSave = false;
  592. if (IsFolder || Parent != null)
  593. {
  594. try
  595. {
  596. var files = locationType != LocationType.Remote && locationType != LocationType.Virtual ?
  597. GetFileSystemChildren(options.DirectoryService).ToList() :
  598. new List<FileSystemInfo>();
  599. var ownedItemsChanged = await RefreshedOwnedItems(options, files, cancellationToken).ConfigureAwait(false);
  600. if (ownedItemsChanged)
  601. {
  602. requiresSave = true;
  603. }
  604. }
  605. catch (Exception ex)
  606. {
  607. Logger.ErrorException("Error refreshing owned items for {0}", ex, Path ?? Name);
  608. }
  609. }
  610. var dateLastSaved = DateLastSaved;
  611. await ProviderManager.RefreshMetadata(this, options, cancellationToken).ConfigureAwait(false);
  612. // If it wasn't saved by the provider process, save now
  613. if (requiresSave && dateLastSaved == DateLastSaved)
  614. {
  615. await UpdateToRepository(ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  616. }
  617. }
  618. /// <summary>
  619. /// Refreshes owned items such as trailers, theme videos, special features, etc.
  620. /// Returns true or false indicating if changes were found.
  621. /// </summary>
  622. /// <param name="options"></param>
  623. /// <param name="fileSystemChildren"></param>
  624. /// <param name="cancellationToken"></param>
  625. /// <returns></returns>
  626. protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  627. {
  628. var themeSongsChanged = false;
  629. var themeVideosChanged = false;
  630. var localTrailersChanged = false;
  631. if (LocationType == LocationType.FileSystem && Parent != null)
  632. {
  633. var hasThemeMedia = this as IHasThemeMedia;
  634. if (hasThemeMedia != null)
  635. {
  636. if (!IsInMixedFolder)
  637. {
  638. themeSongsChanged = await RefreshThemeSongs(hasThemeMedia, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  639. themeVideosChanged = await RefreshThemeVideos(hasThemeMedia, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  640. }
  641. }
  642. var hasTrailers = this as IHasTrailers;
  643. if (hasTrailers != null)
  644. {
  645. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  646. }
  647. }
  648. return themeSongsChanged || themeVideosChanged || localTrailersChanged;
  649. }
  650. protected virtual IEnumerable<FileSystemInfo> GetFileSystemChildren(IDirectoryService directoryService)
  651. {
  652. var path = ContainingFolderPath;
  653. return directoryService.GetFileSystemEntries(path);
  654. }
  655. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  656. {
  657. var newItems = LibraryManager.FindTrailers(this, fileSystemChildren, options.DirectoryService).ToList();
  658. var newItemIds = newItems.Select(i => i.Id).ToList();
  659. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  660. var tasks = newItems.Select(i => i.RefreshMetadata(options, cancellationToken));
  661. await Task.WhenAll(tasks).ConfigureAwait(false);
  662. item.LocalTrailerIds = newItemIds;
  663. return itemsChanged;
  664. }
  665. private async Task<bool> RefreshThemeVideos(IHasThemeMedia item, MetadataRefreshOptions options, IEnumerable<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  666. {
  667. var newThemeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService).ToList();
  668. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  669. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  670. var tasks = newThemeVideos.Select(i =>
  671. {
  672. var subOptions = new MetadataRefreshOptions(options);
  673. if (!i.IsThemeMedia)
  674. {
  675. i.IsThemeMedia = true;
  676. subOptions.ForceSave = true;
  677. }
  678. return i.RefreshMetadata(subOptions, cancellationToken);
  679. });
  680. await Task.WhenAll(tasks).ConfigureAwait(false);
  681. item.ThemeVideoIds = newThemeVideoIds;
  682. return themeVideosChanged;
  683. }
  684. /// <summary>
  685. /// Refreshes the theme songs.
  686. /// </summary>
  687. private async Task<bool> RefreshThemeSongs(IHasThemeMedia item, MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  688. {
  689. var newThemeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService).ToList();
  690. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  691. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  692. var tasks = newThemeSongs.Select(i =>
  693. {
  694. var subOptions = new MetadataRefreshOptions(options);
  695. if (!i.IsThemeMedia)
  696. {
  697. i.IsThemeMedia = true;
  698. subOptions.ForceSave = true;
  699. }
  700. return i.RefreshMetadata(subOptions, cancellationToken);
  701. });
  702. await Task.WhenAll(tasks).ConfigureAwait(false);
  703. item.ThemeSongIds = newThemeSongIds;
  704. return themeSongsChanged;
  705. }
  706. /// <summary>
  707. /// Gets or sets the provider ids.
  708. /// </summary>
  709. /// <value>The provider ids.</value>
  710. public Dictionary<string, string> ProviderIds { get; set; }
  711. /// <summary>
  712. /// Override this to false if class should be ignored for indexing purposes
  713. /// </summary>
  714. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  715. [IgnoreDataMember]
  716. public virtual bool IncludeInIndex
  717. {
  718. get { return true; }
  719. }
  720. /// <summary>
  721. /// Override this to true if class should be grouped under a container in indicies
  722. /// The container class should be defined via IndexContainer
  723. /// </summary>
  724. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  725. [IgnoreDataMember]
  726. public virtual bool GroupInIndex
  727. {
  728. get { return false; }
  729. }
  730. /// <summary>
  731. /// Override this to return the folder that should be used to construct a container
  732. /// for this item in an index. GroupInIndex should be true as well.
  733. /// </summary>
  734. /// <value>The index container.</value>
  735. [IgnoreDataMember]
  736. public virtual Folder IndexContainer
  737. {
  738. get { return null; }
  739. }
  740. [IgnoreDataMember]
  741. public virtual Folder LatestItemsIndexContainer
  742. {
  743. get { return null; }
  744. }
  745. /// <summary>
  746. /// Gets the user data key.
  747. /// </summary>
  748. /// <returns>System.String.</returns>
  749. public virtual string GetUserDataKey()
  750. {
  751. return Id.ToString();
  752. }
  753. internal virtual bool IsValidFromResolver(BaseItem newItem)
  754. {
  755. var current = this;
  756. return current.IsInMixedFolder == newItem.IsInMixedFolder;
  757. }
  758. /// <summary>
  759. /// Gets the preferred metadata language.
  760. /// </summary>
  761. /// <returns>System.String.</returns>
  762. public string GetPreferredMetadataLanguage()
  763. {
  764. string lang = null;
  765. var hasLang = this as IHasPreferredMetadataLanguage;
  766. if (hasLang != null)
  767. {
  768. lang = hasLang.PreferredMetadataLanguage;
  769. }
  770. if (string.IsNullOrEmpty(lang))
  771. {
  772. lang = Parents.OfType<IHasPreferredMetadataLanguage>()
  773. .Select(i => i.PreferredMetadataLanguage)
  774. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  775. }
  776. if (string.IsNullOrEmpty(lang))
  777. {
  778. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  779. }
  780. return lang;
  781. }
  782. /// <summary>
  783. /// Gets the preferred metadata language.
  784. /// </summary>
  785. /// <returns>System.String.</returns>
  786. public string GetPreferredMetadataCountryCode()
  787. {
  788. string lang = null;
  789. var hasLang = this as IHasPreferredMetadataLanguage;
  790. if (hasLang != null)
  791. {
  792. lang = hasLang.PreferredMetadataCountryCode;
  793. }
  794. if (string.IsNullOrEmpty(lang))
  795. {
  796. lang = Parents.OfType<IHasPreferredMetadataLanguage>()
  797. .Select(i => i.PreferredMetadataCountryCode)
  798. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  799. }
  800. if (string.IsNullOrEmpty(lang))
  801. {
  802. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  803. }
  804. return lang;
  805. }
  806. public virtual bool IsSaveLocalMetadataEnabled()
  807. {
  808. return ConfigurationManager.Configuration.SaveLocalMeta;
  809. }
  810. /// <summary>
  811. /// Determines if a given user has access to this item
  812. /// </summary>
  813. /// <param name="user">The user.</param>
  814. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  815. /// <exception cref="System.ArgumentNullException">user</exception>
  816. public bool IsParentalAllowed(User user)
  817. {
  818. if (user == null)
  819. {
  820. throw new ArgumentNullException("user");
  821. }
  822. if (!IsVisibleViaTags(user))
  823. {
  824. return false;
  825. }
  826. var maxAllowedRating = user.Policy.MaxParentalRating;
  827. if (maxAllowedRating == null)
  828. {
  829. return true;
  830. }
  831. var rating = CustomRatingForComparison;
  832. if (string.IsNullOrWhiteSpace(rating))
  833. {
  834. rating = OfficialRatingForComparison;
  835. }
  836. if (string.IsNullOrWhiteSpace(rating))
  837. {
  838. return !GetBlockUnratedValue(user.Policy);
  839. }
  840. var value = LocalizationManager.GetRatingLevel(rating);
  841. // Could not determine the integer value
  842. if (!value.HasValue)
  843. {
  844. return true;
  845. }
  846. return value.Value <= maxAllowedRating.Value;
  847. }
  848. private bool IsVisibleViaTags(User user)
  849. {
  850. var hasTags = this as IHasTags;
  851. if (hasTags != null)
  852. {
  853. if (user.Policy.BlockedTags.Any(i => hasTags.Tags.Contains(i, StringComparer.OrdinalIgnoreCase)))
  854. {
  855. return false;
  856. }
  857. }
  858. return true;
  859. }
  860. /// <summary>
  861. /// Gets the block unrated value.
  862. /// </summary>
  863. /// <param name="config">The configuration.</param>
  864. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  865. protected virtual bool GetBlockUnratedValue(UserPolicy config)
  866. {
  867. return config.BlockUnratedItems.Contains(UnratedItem.Other);
  868. }
  869. /// <summary>
  870. /// Determines if this folder should be visible to a given user.
  871. /// Default is just parental allowed. Can be overridden for more functionality.
  872. /// </summary>
  873. /// <param name="user">The user.</param>
  874. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  875. /// <exception cref="System.ArgumentNullException">user</exception>
  876. public virtual bool IsVisible(User user)
  877. {
  878. if (user == null)
  879. {
  880. throw new ArgumentNullException("user");
  881. }
  882. return IsParentalAllowed(user);
  883. }
  884. /// <summary>
  885. /// Gets a value indicating whether this instance is folder.
  886. /// </summary>
  887. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  888. [IgnoreDataMember]
  889. public virtual bool IsFolder
  890. {
  891. get
  892. {
  893. return false;
  894. }
  895. }
  896. public virtual string GetClientTypeName()
  897. {
  898. return GetType().Name;
  899. }
  900. /// <summary>
  901. /// Gets the linked child.
  902. /// </summary>
  903. /// <param name="info">The info.</param>
  904. /// <returns>BaseItem.</returns>
  905. protected BaseItem GetLinkedChild(LinkedChild info)
  906. {
  907. // First get using the cached Id
  908. if (info.ItemId.HasValue)
  909. {
  910. if (info.ItemId.Value == Guid.Empty)
  911. {
  912. return null;
  913. }
  914. var itemById = LibraryManager.GetItemById(info.ItemId.Value);
  915. if (itemById != null)
  916. {
  917. return itemById;
  918. }
  919. }
  920. var item = FindLinkedChild(info);
  921. // If still null, log
  922. if (item == null)
  923. {
  924. // Don't keep searching over and over
  925. info.ItemId = Guid.Empty;
  926. }
  927. else
  928. {
  929. // Cache the id for next time
  930. info.ItemId = item.Id;
  931. }
  932. return item;
  933. }
  934. private BaseItem FindLinkedChild(LinkedChild info)
  935. {
  936. if (!string.IsNullOrWhiteSpace(info.ItemName))
  937. {
  938. if (string.Equals(info.ItemType, "musicgenre", StringComparison.OrdinalIgnoreCase))
  939. {
  940. return LibraryManager.GetMusicGenre(info.ItemName);
  941. }
  942. if (string.Equals(info.ItemType, "musicartist", StringComparison.OrdinalIgnoreCase))
  943. {
  944. return LibraryManager.GetArtist(info.ItemName);
  945. }
  946. }
  947. if (!string.IsNullOrEmpty(info.Path))
  948. {
  949. var itemByPath = LibraryManager.RootFolder.FindByPath(info.Path);
  950. if (itemByPath == null)
  951. {
  952. Logger.Warn("Unable to find linked item at path {0}", info.Path);
  953. }
  954. return itemByPath;
  955. }
  956. if (!string.IsNullOrWhiteSpace(info.ItemName) && !string.IsNullOrWhiteSpace(info.ItemType))
  957. {
  958. return LibraryManager.RootFolder.RecursiveChildren.FirstOrDefault(i =>
  959. {
  960. if (string.Equals(i.Name, info.ItemName, StringComparison.OrdinalIgnoreCase))
  961. {
  962. if (string.Equals(i.GetType().Name, info.ItemType, StringComparison.OrdinalIgnoreCase))
  963. {
  964. if (info.ItemYear.HasValue)
  965. {
  966. if (info.ItemYear.Value != (i.ProductionYear ?? -1))
  967. {
  968. return false;
  969. }
  970. }
  971. return true;
  972. }
  973. }
  974. return false;
  975. });
  976. }
  977. return null;
  978. }
  979. /// <summary>
  980. /// Adds a person to the item
  981. /// </summary>
  982. /// <param name="person">The person.</param>
  983. /// <exception cref="System.ArgumentNullException"></exception>
  984. public void AddPerson(PersonInfo person)
  985. {
  986. if (person == null)
  987. {
  988. throw new ArgumentNullException("person");
  989. }
  990. if (string.IsNullOrWhiteSpace(person.Name))
  991. {
  992. throw new ArgumentNullException();
  993. }
  994. // Normalize
  995. if (string.Equals(person.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  996. {
  997. person.Type = PersonType.GuestStar;
  998. }
  999. else if (string.Equals(person.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
  1000. {
  1001. person.Type = PersonType.Director;
  1002. }
  1003. else if (string.Equals(person.Role, PersonType.Producer, StringComparison.OrdinalIgnoreCase))
  1004. {
  1005. person.Type = PersonType.Producer;
  1006. }
  1007. else if (string.Equals(person.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
  1008. {
  1009. person.Type = PersonType.Writer;
  1010. }
  1011. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  1012. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  1013. {
  1014. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  1015. if (existing != null)
  1016. {
  1017. existing.Type = PersonType.GuestStar;
  1018. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  1019. return;
  1020. }
  1021. }
  1022. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  1023. {
  1024. // If the actor already exists without a role and we have one, fill it in
  1025. 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)));
  1026. if (existing == null)
  1027. {
  1028. // Wasn't there - add it
  1029. People.Add(person);
  1030. }
  1031. else
  1032. {
  1033. // Was there, if no role and we have one - fill it in
  1034. if (string.IsNullOrWhiteSpace(existing.Role) && !string.IsNullOrWhiteSpace(person.Role))
  1035. {
  1036. existing.Role = person.Role;
  1037. }
  1038. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  1039. }
  1040. }
  1041. else
  1042. {
  1043. var existing = People.FirstOrDefault(p =>
  1044. string.Equals(p.Name, person.Name, StringComparison.OrdinalIgnoreCase) &&
  1045. string.Equals(p.Type, person.Type, StringComparison.OrdinalIgnoreCase));
  1046. // Check for dupes based on the combination of Name and Type
  1047. if (existing == null)
  1048. {
  1049. People.Add(person);
  1050. }
  1051. else
  1052. {
  1053. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  1054. }
  1055. }
  1056. }
  1057. /// <summary>
  1058. /// Adds a studio to the item
  1059. /// </summary>
  1060. /// <param name="name">The name.</param>
  1061. /// <exception cref="System.ArgumentNullException"></exception>
  1062. public void AddStudio(string name)
  1063. {
  1064. if (string.IsNullOrWhiteSpace(name))
  1065. {
  1066. throw new ArgumentNullException("name");
  1067. }
  1068. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1069. {
  1070. Studios.Add(name);
  1071. }
  1072. }
  1073. /// <summary>
  1074. /// Adds a genre to the item
  1075. /// </summary>
  1076. /// <param name="name">The name.</param>
  1077. /// <exception cref="System.ArgumentNullException"></exception>
  1078. public void AddGenre(string name)
  1079. {
  1080. if (string.IsNullOrWhiteSpace(name))
  1081. {
  1082. throw new ArgumentNullException("name");
  1083. }
  1084. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1085. {
  1086. Genres.Add(name);
  1087. }
  1088. }
  1089. /// <summary>
  1090. /// Marks the played.
  1091. /// </summary>
  1092. /// <param name="user">The user.</param>
  1093. /// <param name="datePlayed">The date played.</param>
  1094. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1095. /// <returns>Task.</returns>
  1096. /// <exception cref="System.ArgumentNullException"></exception>
  1097. public virtual async Task MarkPlayed(User user,
  1098. DateTime? datePlayed,
  1099. bool resetPosition)
  1100. {
  1101. if (user == null)
  1102. {
  1103. throw new ArgumentNullException();
  1104. }
  1105. var key = GetUserDataKey();
  1106. var data = UserDataManager.GetUserData(user.Id, key);
  1107. if (datePlayed.HasValue)
  1108. {
  1109. // Incremenet
  1110. data.PlayCount++;
  1111. }
  1112. // Ensure it's at least one
  1113. data.PlayCount = Math.Max(data.PlayCount, 1);
  1114. if (resetPosition)
  1115. {
  1116. data.PlaybackPositionTicks = 0;
  1117. }
  1118. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate;
  1119. data.Played = true;
  1120. await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1121. }
  1122. /// <summary>
  1123. /// Marks the unplayed.
  1124. /// </summary>
  1125. /// <param name="user">The user.</param>
  1126. /// <returns>Task.</returns>
  1127. /// <exception cref="System.ArgumentNullException"></exception>
  1128. public virtual async Task MarkUnplayed(User user)
  1129. {
  1130. if (user == null)
  1131. {
  1132. throw new ArgumentNullException();
  1133. }
  1134. var key = GetUserDataKey();
  1135. var data = UserDataManager.GetUserData(user.Id, key);
  1136. //I think it is okay to do this here.
  1137. // if this is only called when a user is manually forcing something to un-played
  1138. // then it probably is what we want to do...
  1139. data.PlayCount = 0;
  1140. data.PlaybackPositionTicks = 0;
  1141. data.LastPlayedDate = null;
  1142. data.Played = false;
  1143. await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1144. }
  1145. /// <summary>
  1146. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1147. /// </summary>
  1148. /// <returns>Task.</returns>
  1149. public virtual Task ChangedExternally()
  1150. {
  1151. return RefreshMetadata(CancellationToken.None);
  1152. }
  1153. /// <summary>
  1154. /// Finds a parent of a given type
  1155. /// </summary>
  1156. /// <typeparam name="T"></typeparam>
  1157. /// <returns>``0.</returns>
  1158. public T FindParent<T>()
  1159. where T : Folder
  1160. {
  1161. var parent = Parent;
  1162. while (parent != null)
  1163. {
  1164. var result = parent as T;
  1165. if (result != null)
  1166. {
  1167. return result;
  1168. }
  1169. parent = parent.Parent;
  1170. }
  1171. return null;
  1172. }
  1173. /// <summary>
  1174. /// Gets an image
  1175. /// </summary>
  1176. /// <param name="type">The type.</param>
  1177. /// <param name="imageIndex">Index of the image.</param>
  1178. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1179. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1180. public bool HasImage(ImageType type, int imageIndex)
  1181. {
  1182. return GetImageInfo(type, imageIndex) != null;
  1183. }
  1184. public void SetImagePath(ImageType type, int index, FileSystemInfo file)
  1185. {
  1186. if (type == ImageType.Chapter)
  1187. {
  1188. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1189. }
  1190. var image = GetImageInfo(type, index);
  1191. if (image == null)
  1192. {
  1193. ImageInfos.Add(GetImageInfo(file, type));
  1194. }
  1195. else
  1196. {
  1197. var imageInfo = GetImageInfo(file, type);
  1198. image.Path = file.FullName;
  1199. image.DateModified = imageInfo.DateModified;
  1200. }
  1201. }
  1202. /// <summary>
  1203. /// Deletes the image.
  1204. /// </summary>
  1205. /// <param name="type">The type.</param>
  1206. /// <param name="index">The index.</param>
  1207. /// <returns>Task.</returns>
  1208. public Task DeleteImage(ImageType type, int index)
  1209. {
  1210. var info = GetImageInfo(type, index);
  1211. if (info == null)
  1212. {
  1213. // Nothing to do
  1214. return Task.FromResult(true);
  1215. }
  1216. // Remove it from the item
  1217. ImageInfos.Remove(info);
  1218. // Delete the source file
  1219. var currentFile = new FileInfo(info.Path);
  1220. // Deletion will fail if the file is hidden so remove the attribute first
  1221. if (currentFile.Exists)
  1222. {
  1223. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  1224. {
  1225. currentFile.Attributes &= ~FileAttributes.Hidden;
  1226. }
  1227. currentFile.Delete();
  1228. }
  1229. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1230. }
  1231. public virtual Task UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1232. {
  1233. return LibraryManager.UpdateItem(this, updateReason, cancellationToken);
  1234. }
  1235. /// <summary>
  1236. /// Validates that images within the item are still on the file system
  1237. /// </summary>
  1238. public bool ValidateImages(IDirectoryService directoryService)
  1239. {
  1240. var allDirectories = ImageInfos.Select(i => System.IO.Path.GetDirectoryName(i.Path)).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  1241. var allFiles = allDirectories.SelectMany(directoryService.GetFiles).Select(i => i.FullName).ToList();
  1242. var deletedImages = ImageInfos
  1243. .Where(image => !allFiles.Contains(image.Path, StringComparer.OrdinalIgnoreCase))
  1244. .ToList();
  1245. if (deletedImages.Count > 0)
  1246. {
  1247. ImageInfos = ImageInfos.Except(deletedImages).ToList();
  1248. }
  1249. return deletedImages.Count > 0;
  1250. }
  1251. /// <summary>
  1252. /// Gets the image path.
  1253. /// </summary>
  1254. /// <param name="imageType">Type of the image.</param>
  1255. /// <param name="imageIndex">Index of the image.</param>
  1256. /// <returns>System.String.</returns>
  1257. /// <exception cref="System.InvalidOperationException">
  1258. /// </exception>
  1259. /// <exception cref="System.ArgumentNullException">item</exception>
  1260. public string GetImagePath(ImageType imageType, int imageIndex)
  1261. {
  1262. var info = GetImageInfo(imageType, imageIndex);
  1263. return info == null ? null : info.Path;
  1264. }
  1265. /// <summary>
  1266. /// Gets the image information.
  1267. /// </summary>
  1268. /// <param name="imageType">Type of the image.</param>
  1269. /// <param name="imageIndex">Index of the image.</param>
  1270. /// <returns>ItemImageInfo.</returns>
  1271. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1272. {
  1273. if (imageType == ImageType.Chapter)
  1274. {
  1275. var chapter = ItemRepository.GetChapter(Id, imageIndex);
  1276. if (chapter == null)
  1277. {
  1278. return null;
  1279. }
  1280. var path = chapter.ImagePath;
  1281. if (string.IsNullOrWhiteSpace(path))
  1282. {
  1283. return null;
  1284. }
  1285. return new ItemImageInfo
  1286. {
  1287. Path = path,
  1288. DateModified = FileSystem.GetLastWriteTimeUtc(path),
  1289. Type = imageType
  1290. };
  1291. }
  1292. return GetImages(imageType)
  1293. .ElementAtOrDefault(imageIndex);
  1294. }
  1295. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1296. {
  1297. if (imageType == ImageType.Chapter)
  1298. {
  1299. throw new ArgumentException("No image info for chapter images");
  1300. }
  1301. return ImageInfos.Where(i => i.Type == imageType);
  1302. }
  1303. public bool AddImages(ImageType imageType, IEnumerable<FileInfo> images)
  1304. {
  1305. return AddImages(imageType, images.Cast<FileSystemInfo>());
  1306. }
  1307. /// <summary>
  1308. /// Adds the images.
  1309. /// </summary>
  1310. /// <param name="imageType">Type of the image.</param>
  1311. /// <param name="images">The images.</param>
  1312. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1313. /// <exception cref="System.ArgumentException">Cannot call AddImages with chapter images</exception>
  1314. public bool AddImages(ImageType imageType, IEnumerable<FileSystemInfo> images)
  1315. {
  1316. if (imageType == ImageType.Chapter)
  1317. {
  1318. throw new ArgumentException("Cannot call AddImages with chapter images");
  1319. }
  1320. var existingImages = GetImages(imageType)
  1321. .ToList();
  1322. var newImageList = new List<FileSystemInfo>();
  1323. foreach (var newImage in images)
  1324. {
  1325. if (newImage == null)
  1326. {
  1327. throw new ArgumentException("null image found in list");
  1328. }
  1329. var existing = existingImages
  1330. .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  1331. if (existing == null)
  1332. {
  1333. newImageList.Add(newImage);
  1334. }
  1335. else
  1336. {
  1337. existing.DateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  1338. }
  1339. }
  1340. ImageInfos.AddRange(newImageList.Select(i => GetImageInfo(i, imageType)));
  1341. return newImageList.Count > 0;
  1342. }
  1343. private ItemImageInfo GetImageInfo(FileSystemInfo file, ImageType type)
  1344. {
  1345. return new ItemImageInfo
  1346. {
  1347. Path = file.FullName,
  1348. Type = type,
  1349. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  1350. };
  1351. }
  1352. /// <summary>
  1353. /// Gets the file system path to delete when the item is to be deleted
  1354. /// </summary>
  1355. /// <returns></returns>
  1356. public virtual IEnumerable<string> GetDeletePaths()
  1357. {
  1358. return new[] { Path };
  1359. }
  1360. public bool AllowsMultipleImages(ImageType type)
  1361. {
  1362. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  1363. }
  1364. public Task SwapImages(ImageType type, int index1, int index2)
  1365. {
  1366. if (!AllowsMultipleImages(type))
  1367. {
  1368. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  1369. }
  1370. var info1 = GetImageInfo(type, index1);
  1371. var info2 = GetImageInfo(type, index2);
  1372. if (info1 == null || info2 == null)
  1373. {
  1374. // Nothing to do
  1375. return Task.FromResult(true);
  1376. }
  1377. var path1 = info1.Path;
  1378. var path2 = info2.Path;
  1379. FileSystem.SwapFiles(path1, path2);
  1380. // Refresh these values
  1381. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  1382. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  1383. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1384. }
  1385. public virtual bool IsPlayed(User user)
  1386. {
  1387. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1388. return userdata != null && userdata.Played;
  1389. }
  1390. public bool IsFavoriteOrLiked(User user)
  1391. {
  1392. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1393. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  1394. }
  1395. public virtual bool IsUnplayed(User user)
  1396. {
  1397. if (user == null)
  1398. {
  1399. throw new ArgumentNullException("user");
  1400. }
  1401. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1402. return userdata == null || !userdata.Played;
  1403. }
  1404. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  1405. {
  1406. return GetItemLookupInfo<ItemLookupInfo>();
  1407. }
  1408. protected T GetItemLookupInfo<T>()
  1409. where T : ItemLookupInfo, new()
  1410. {
  1411. return new T
  1412. {
  1413. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  1414. MetadataLanguage = GetPreferredMetadataLanguage(),
  1415. Name = Name,
  1416. ProviderIds = ProviderIds,
  1417. IndexNumber = IndexNumber,
  1418. ParentIndexNumber = ParentIndexNumber,
  1419. Year = ProductionYear
  1420. };
  1421. }
  1422. /// <summary>
  1423. /// This is called before any metadata refresh and returns true or false indicating if changes were made
  1424. /// </summary>
  1425. public virtual bool BeforeMetadataRefresh()
  1426. {
  1427. var hasChanges = false;
  1428. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  1429. {
  1430. Name = FileSystem.GetFileNameWithoutExtension(Path);
  1431. hasChanges = true;
  1432. }
  1433. return hasChanges;
  1434. }
  1435. protected static string GetMappedPath(string path, LocationType locationType)
  1436. {
  1437. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1438. {
  1439. foreach (var map in ConfigurationManager.Configuration.PathSubstitutions)
  1440. {
  1441. path = FileSystem.SubstitutePath(path, map.From, map.To);
  1442. }
  1443. }
  1444. return path;
  1445. }
  1446. public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, User user)
  1447. {
  1448. if (RunTimeTicks.HasValue)
  1449. {
  1450. double pct = RunTimeTicks.Value;
  1451. if (pct > 0)
  1452. {
  1453. pct = userData.PlaybackPositionTicks / pct;
  1454. if (pct > 0)
  1455. {
  1456. dto.PlayedPercentage = 100 * pct;
  1457. }
  1458. }
  1459. }
  1460. }
  1461. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, string path, CancellationToken cancellationToken)
  1462. {
  1463. var newOptions = new MetadataRefreshOptions(options.DirectoryService)
  1464. {
  1465. ImageRefreshMode = options.ImageRefreshMode,
  1466. MetadataRefreshMode = options.MetadataRefreshMode,
  1467. ReplaceAllMetadata = options.ReplaceAllMetadata
  1468. };
  1469. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  1470. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1471. var video = LibraryManager.GetItemById(id) as Video;
  1472. if (video == null)
  1473. {
  1474. video = LibraryManager.ResolvePath(new FileInfo(path)) as Video;
  1475. newOptions.ForceSave = true;
  1476. }
  1477. if (video == null)
  1478. {
  1479. return Task.FromResult(true);
  1480. }
  1481. return video.RefreshMetadata(newOptions, cancellationToken);
  1482. }
  1483. }
  1484. }