BaseItem.cs 49 KB

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