BaseItem.cs 49 KB

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