BaseItem.cs 53 KB

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