BaseItem.cs 54 KB

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