BaseItem.cs 49 KB

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