BaseItem.cs 59 KB

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