BaseItem.cs 55 KB

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