BaseItem.cs 49 KB

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