BaseItem.cs 49 KB

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