BaseItem.cs 53 KB

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