BaseItem.cs 54 KB

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