2
0

BaseItem.cs 52 KB

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