BaseItem.cs 50 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.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, IDirectoryService directoryService)
  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, directoryService, 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, IDirectoryService directoryService)
  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, directoryService, 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, IDirectoryService directoryService)
  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, directoryService, 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. try
  497. {
  498. var files = locationType == LocationType.FileSystem || locationType == LocationType.Offline ?
  499. GetFileSystemChildren(options.DirectoryService).ToList() :
  500. new List<FileSystemInfo>();
  501. var ownedItemsChanged = await RefreshedOwnedItems(options, files, cancellationToken).ConfigureAwait(false);
  502. if (ownedItemsChanged)
  503. {
  504. requiresSave = true;
  505. }
  506. }
  507. catch (Exception ex)
  508. {
  509. Logger.ErrorException("Error refreshing owned items for {0}", ex, Path ?? Name);
  510. }
  511. }
  512. var dateLastSaved = DateLastSaved;
  513. await ProviderManager.RefreshMetadata(this, options, cancellationToken).ConfigureAwait(false);
  514. // If it wasn't saved by the provider process, save now
  515. if (requiresSave && dateLastSaved == DateLastSaved)
  516. {
  517. await UpdateToRepository(ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  518. }
  519. }
  520. /// <summary>
  521. /// Refreshes owned items such as trailers, theme videos, special features, etc.
  522. /// Returns true or false indicating if changes were found.
  523. /// </summary>
  524. /// <param name="options"></param>
  525. /// <param name="fileSystemChildren"></param>
  526. /// <param name="cancellationToken"></param>
  527. /// <returns></returns>
  528. protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  529. {
  530. var themeSongsChanged = false;
  531. var themeVideosChanged = false;
  532. var localTrailersChanged = false;
  533. if (LocationType == LocationType.FileSystem && Parent != null)
  534. {
  535. var hasThemeMedia = this as IHasThemeMedia;
  536. if (hasThemeMedia != null)
  537. {
  538. if (!IsInMixedFolder)
  539. {
  540. themeSongsChanged = await RefreshThemeSongs(hasThemeMedia, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  541. themeVideosChanged = await RefreshThemeVideos(hasThemeMedia, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  542. }
  543. }
  544. var hasTrailers = this as IHasTrailers;
  545. if (hasTrailers != null)
  546. {
  547. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  548. }
  549. }
  550. return themeSongsChanged || themeVideosChanged || localTrailersChanged;
  551. }
  552. protected virtual IEnumerable<FileSystemInfo> GetFileSystemChildren(IDirectoryService directoryService)
  553. {
  554. var path = ContainingFolderPath;
  555. return directoryService.GetFileSystemEntries(path);
  556. }
  557. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  558. {
  559. var newItems = LoadLocalTrailers(fileSystemChildren, options.DirectoryService).ToList();
  560. var newItemIds = newItems.Select(i => i.Id).ToList();
  561. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  562. var tasks = newItems.Select(i => i.RefreshMetadata(options, cancellationToken));
  563. await Task.WhenAll(tasks).ConfigureAwait(false);
  564. item.LocalTrailerIds = newItemIds;
  565. return itemsChanged;
  566. }
  567. private async Task<bool> RefreshThemeVideos(IHasThemeMedia item, MetadataRefreshOptions options, IEnumerable<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  568. {
  569. var newThemeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService).ToList();
  570. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  571. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  572. var tasks = newThemeVideos.Select(i => i.RefreshMetadata(options, cancellationToken));
  573. await Task.WhenAll(tasks).ConfigureAwait(false);
  574. item.ThemeVideoIds = newThemeVideoIds;
  575. return themeVideosChanged;
  576. }
  577. /// <summary>
  578. /// Refreshes the theme songs.
  579. /// </summary>
  580. private async Task<bool> RefreshThemeSongs(IHasThemeMedia item, MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  581. {
  582. var newThemeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService).ToList();
  583. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  584. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  585. var tasks = newThemeSongs.Select(i => i.RefreshMetadata(options, cancellationToken));
  586. await Task.WhenAll(tasks).ConfigureAwait(false);
  587. item.ThemeSongIds = newThemeSongIds;
  588. return themeSongsChanged;
  589. }
  590. /// <summary>
  591. /// Gets or sets the provider ids.
  592. /// </summary>
  593. /// <value>The provider ids.</value>
  594. public Dictionary<string, string> ProviderIds { get; set; }
  595. /// <summary>
  596. /// Override this to false if class should be ignored for indexing purposes
  597. /// </summary>
  598. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  599. [IgnoreDataMember]
  600. public virtual bool IncludeInIndex
  601. {
  602. get { return true; }
  603. }
  604. /// <summary>
  605. /// Override this to true if class should be grouped under a container in indicies
  606. /// The container class should be defined via IndexContainer
  607. /// </summary>
  608. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  609. [IgnoreDataMember]
  610. public virtual bool GroupInIndex
  611. {
  612. get { return false; }
  613. }
  614. /// <summary>
  615. /// Override this to return the folder that should be used to construct a container
  616. /// for this item in an index. GroupInIndex should be true as well.
  617. /// </summary>
  618. /// <value>The index container.</value>
  619. [IgnoreDataMember]
  620. public virtual Folder IndexContainer
  621. {
  622. get { return null; }
  623. }
  624. /// <summary>
  625. /// Gets the user data key.
  626. /// </summary>
  627. /// <returns>System.String.</returns>
  628. public virtual string GetUserDataKey()
  629. {
  630. return Id.ToString();
  631. }
  632. /// <summary>
  633. /// Gets the preferred metadata language.
  634. /// </summary>
  635. /// <returns>System.String.</returns>
  636. public string GetPreferredMetadataLanguage()
  637. {
  638. string lang = null;
  639. var hasLang = this as IHasPreferredMetadataLanguage;
  640. if (hasLang != null)
  641. {
  642. lang = hasLang.PreferredMetadataLanguage;
  643. }
  644. if (string.IsNullOrEmpty(lang))
  645. {
  646. lang = Parents.OfType<IHasPreferredMetadataLanguage>()
  647. .Select(i => i.PreferredMetadataLanguage)
  648. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  649. }
  650. if (string.IsNullOrEmpty(lang))
  651. {
  652. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  653. }
  654. return lang;
  655. }
  656. /// <summary>
  657. /// Gets the preferred metadata language.
  658. /// </summary>
  659. /// <returns>System.String.</returns>
  660. public string GetPreferredMetadataCountryCode()
  661. {
  662. string lang = null;
  663. var hasLang = this as IHasPreferredMetadataLanguage;
  664. if (hasLang != null)
  665. {
  666. lang = hasLang.PreferredMetadataCountryCode;
  667. }
  668. if (string.IsNullOrEmpty(lang))
  669. {
  670. lang = Parents.OfType<IHasPreferredMetadataLanguage>()
  671. .Select(i => i.PreferredMetadataCountryCode)
  672. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  673. }
  674. if (string.IsNullOrEmpty(lang))
  675. {
  676. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  677. }
  678. return lang;
  679. }
  680. public virtual bool IsSaveLocalMetadataEnabled()
  681. {
  682. return ConfigurationManager.Configuration.SaveLocalMeta;
  683. }
  684. /// <summary>
  685. /// Determines if a given user has access to this item
  686. /// </summary>
  687. /// <param name="user">The user.</param>
  688. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  689. /// <exception cref="System.ArgumentNullException">user</exception>
  690. public bool IsParentalAllowed(User user)
  691. {
  692. if (user == null)
  693. {
  694. throw new ArgumentNullException("user");
  695. }
  696. var maxAllowedRating = user.Configuration.MaxParentalRating;
  697. if (maxAllowedRating == null)
  698. {
  699. return true;
  700. }
  701. var rating = CustomRatingForComparison;
  702. if (string.IsNullOrEmpty(rating))
  703. {
  704. rating = OfficialRatingForComparison;
  705. }
  706. if (string.IsNullOrEmpty(rating))
  707. {
  708. return !GetBlockUnratedValue(user.Configuration);
  709. }
  710. var value = LocalizationManager.GetRatingLevel(rating);
  711. // Could not determine the integer value
  712. if (!value.HasValue)
  713. {
  714. return true;
  715. }
  716. return value.Value <= maxAllowedRating.Value;
  717. }
  718. /// <summary>
  719. /// Gets the block unrated value.
  720. /// </summary>
  721. /// <param name="config">The configuration.</param>
  722. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  723. protected virtual bool GetBlockUnratedValue(UserConfiguration config)
  724. {
  725. return config.BlockNotRated;
  726. }
  727. /// <summary>
  728. /// Determines if this folder should be visible to a given user.
  729. /// Default is just parental allowed. Can be overridden for more functionality.
  730. /// </summary>
  731. /// <param name="user">The user.</param>
  732. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  733. /// <exception cref="System.ArgumentNullException">user</exception>
  734. public virtual bool IsVisible(User user)
  735. {
  736. if (user == null)
  737. {
  738. throw new ArgumentNullException("user");
  739. }
  740. return IsParentalAllowed(user);
  741. }
  742. /// <summary>
  743. /// Gets a value indicating whether this instance is folder.
  744. /// </summary>
  745. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  746. [IgnoreDataMember]
  747. public virtual bool IsFolder
  748. {
  749. get
  750. {
  751. return false;
  752. }
  753. }
  754. /// <summary>
  755. /// Determine if we have changed vs the passed in copy
  756. /// </summary>
  757. /// <param name="copy">The copy.</param>
  758. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  759. /// <exception cref="System.ArgumentNullException"></exception>
  760. public virtual bool HasChanged(BaseItem copy)
  761. {
  762. if (copy == null)
  763. {
  764. throw new ArgumentNullException();
  765. }
  766. if (IsInMixedFolder != copy.IsInMixedFolder)
  767. {
  768. Logger.Debug(Name + " changed due to different value for IsInMixedFolder.");
  769. return true;
  770. }
  771. var changed = copy.DateModified != DateModified;
  772. if (changed)
  773. {
  774. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  775. }
  776. return changed;
  777. }
  778. public virtual string GetClientTypeName()
  779. {
  780. return GetType().Name;
  781. }
  782. /// <summary>
  783. /// Determines if the item is considered new based on user settings
  784. /// </summary>
  785. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  786. /// <exception cref="System.ArgumentNullException"></exception>
  787. public bool IsRecentlyAdded()
  788. {
  789. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  790. }
  791. /// <summary>
  792. /// Adds a person to the item
  793. /// </summary>
  794. /// <param name="person">The person.</param>
  795. /// <exception cref="System.ArgumentNullException"></exception>
  796. public void AddPerson(PersonInfo person)
  797. {
  798. if (person == null)
  799. {
  800. throw new ArgumentNullException("person");
  801. }
  802. if (string.IsNullOrWhiteSpace(person.Name))
  803. {
  804. throw new ArgumentNullException();
  805. }
  806. // Normalize
  807. if (string.Equals(person.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  808. {
  809. person.Type = PersonType.GuestStar;
  810. }
  811. else if (string.Equals(person.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
  812. {
  813. person.Type = PersonType.Director;
  814. }
  815. else if (string.Equals(person.Role, PersonType.Producer, StringComparison.OrdinalIgnoreCase))
  816. {
  817. person.Type = PersonType.Producer;
  818. }
  819. else if (string.Equals(person.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
  820. {
  821. person.Type = PersonType.Writer;
  822. }
  823. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  824. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  825. {
  826. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  827. if (existing != null)
  828. {
  829. existing.Type = PersonType.GuestStar;
  830. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  831. return;
  832. }
  833. }
  834. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  835. {
  836. // If the actor already exists without a role and we have one, fill it in
  837. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && (p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase) || p.Type.Equals(PersonType.GuestStar, StringComparison.OrdinalIgnoreCase)));
  838. if (existing == null)
  839. {
  840. // Wasn't there - add it
  841. People.Add(person);
  842. }
  843. else
  844. {
  845. // Was there, if no role and we have one - fill it in
  846. if (string.IsNullOrWhiteSpace(existing.Role) && !string.IsNullOrWhiteSpace(person.Role))
  847. {
  848. existing.Role = person.Role;
  849. }
  850. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  851. }
  852. }
  853. else
  854. {
  855. var existing = People.FirstOrDefault(p =>
  856. string.Equals(p.Name, person.Name, StringComparison.OrdinalIgnoreCase) &&
  857. string.Equals(p.Type, person.Type, StringComparison.OrdinalIgnoreCase));
  858. // Check for dupes based on the combination of Name and Type
  859. if (existing == null)
  860. {
  861. People.Add(person);
  862. }
  863. else
  864. {
  865. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  866. }
  867. }
  868. }
  869. /// <summary>
  870. /// Adds a studio to the item
  871. /// </summary>
  872. /// <param name="name">The name.</param>
  873. /// <exception cref="System.ArgumentNullException"></exception>
  874. public void AddStudio(string name)
  875. {
  876. if (string.IsNullOrWhiteSpace(name))
  877. {
  878. throw new ArgumentNullException("name");
  879. }
  880. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  881. {
  882. Studios.Add(name);
  883. }
  884. }
  885. /// <summary>
  886. /// Adds a genre to the item
  887. /// </summary>
  888. /// <param name="name">The name.</param>
  889. /// <exception cref="System.ArgumentNullException"></exception>
  890. public void AddGenre(string name)
  891. {
  892. if (string.IsNullOrWhiteSpace(name))
  893. {
  894. throw new ArgumentNullException("name");
  895. }
  896. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  897. {
  898. Genres.Add(name);
  899. }
  900. }
  901. /// <summary>
  902. /// Marks the played.
  903. /// </summary>
  904. /// <param name="user">The user.</param>
  905. /// <param name="datePlayed">The date played.</param>
  906. /// <param name="userManager">The user manager.</param>
  907. /// <returns>Task.</returns>
  908. /// <exception cref="System.ArgumentNullException"></exception>
  909. public virtual async Task MarkPlayed(User user, DateTime? datePlayed, IUserDataManager userManager)
  910. {
  911. if (user == null)
  912. {
  913. throw new ArgumentNullException();
  914. }
  915. var key = GetUserDataKey();
  916. var data = userManager.GetUserData(user.Id, key);
  917. if (datePlayed.HasValue)
  918. {
  919. // Incremenet
  920. data.PlayCount++;
  921. }
  922. // Ensure it's at least one
  923. data.PlayCount = Math.Max(data.PlayCount, 1);
  924. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate;
  925. data.Played = true;
  926. await userManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  927. }
  928. /// <summary>
  929. /// Marks the unplayed.
  930. /// </summary>
  931. /// <param name="user">The user.</param>
  932. /// <param name="userManager">The user manager.</param>
  933. /// <returns>Task.</returns>
  934. /// <exception cref="System.ArgumentNullException"></exception>
  935. public virtual async Task MarkUnplayed(User user, IUserDataManager userManager)
  936. {
  937. if (user == null)
  938. {
  939. throw new ArgumentNullException();
  940. }
  941. var key = GetUserDataKey();
  942. var data = userManager.GetUserData(user.Id, key);
  943. //I think it is okay to do this here.
  944. // if this is only called when a user is manually forcing something to un-played
  945. // then it probably is what we want to do...
  946. data.PlayCount = 0;
  947. data.PlaybackPositionTicks = 0;
  948. data.LastPlayedDate = null;
  949. data.Played = false;
  950. await userManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  951. }
  952. /// <summary>
  953. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  954. /// </summary>
  955. /// <returns>Task.</returns>
  956. public virtual Task ChangedExternally()
  957. {
  958. return RefreshMetadata(CancellationToken.None);
  959. }
  960. /// <summary>
  961. /// Finds a parent of a given type
  962. /// </summary>
  963. /// <typeparam name="T"></typeparam>
  964. /// <returns>``0.</returns>
  965. public T FindParent<T>()
  966. where T : Folder
  967. {
  968. var parent = Parent;
  969. while (parent != null)
  970. {
  971. var result = parent as T;
  972. if (result != null)
  973. {
  974. return result;
  975. }
  976. parent = parent.Parent;
  977. }
  978. return null;
  979. }
  980. /// <summary>
  981. /// Gets an image
  982. /// </summary>
  983. /// <param name="type">The type.</param>
  984. /// <param name="imageIndex">Index of the image.</param>
  985. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  986. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  987. public bool HasImage(ImageType type, int imageIndex)
  988. {
  989. return GetImageInfo(type, imageIndex) != null;
  990. }
  991. public void SetImagePath(ImageType type, int index, FileInfo file)
  992. {
  993. if (type == ImageType.Chapter)
  994. {
  995. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  996. }
  997. var image = GetImageInfo(type, index);
  998. if (image == null)
  999. {
  1000. ImageInfos.Add(new ItemImageInfo
  1001. {
  1002. Path = file.FullName,
  1003. Type = type,
  1004. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  1005. });
  1006. }
  1007. else
  1008. {
  1009. image.Path = file.FullName;
  1010. image.DateModified = FileSystem.GetLastWriteTimeUtc(file);
  1011. }
  1012. }
  1013. /// <summary>
  1014. /// Deletes the image.
  1015. /// </summary>
  1016. /// <param name="type">The type.</param>
  1017. /// <param name="index">The index.</param>
  1018. /// <returns>Task.</returns>
  1019. public Task DeleteImage(ImageType type, int index)
  1020. {
  1021. var info = GetImageInfo(type, index);
  1022. if (info == null)
  1023. {
  1024. // Nothing to do
  1025. return Task.FromResult(true);
  1026. }
  1027. // Remove it from the item
  1028. ImageInfos.Remove(info);
  1029. // Delete the source file
  1030. var currentFile = new FileInfo(info.Path);
  1031. // Deletion will fail if the file is hidden so remove the attribute first
  1032. if (currentFile.Exists)
  1033. {
  1034. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  1035. {
  1036. currentFile.Attributes &= ~FileAttributes.Hidden;
  1037. }
  1038. currentFile.Delete();
  1039. }
  1040. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1041. }
  1042. public virtual Task UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1043. {
  1044. return LibraryManager.UpdateItem(this, updateReason, cancellationToken);
  1045. }
  1046. /// <summary>
  1047. /// Validates that images within the item are still on the file system
  1048. /// </summary>
  1049. public bool ValidateImages(IDirectoryService directoryService)
  1050. {
  1051. var allDirectories = ImageInfos.Select(i => System.IO.Path.GetDirectoryName(i.Path)).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  1052. var allFiles = allDirectories.SelectMany(directoryService.GetFiles).Select(i => i.FullName).ToList();
  1053. var deletedImages = ImageInfos
  1054. .Where(image => !allFiles.Contains(image.Path, StringComparer.OrdinalIgnoreCase))
  1055. .ToList();
  1056. if (deletedImages.Count > 0)
  1057. {
  1058. ImageInfos = ImageInfos.Except(deletedImages).ToList();
  1059. }
  1060. return deletedImages.Count > 0;
  1061. }
  1062. /// <summary>
  1063. /// Gets the image path.
  1064. /// </summary>
  1065. /// <param name="imageType">Type of the image.</param>
  1066. /// <param name="imageIndex">Index of the image.</param>
  1067. /// <returns>System.String.</returns>
  1068. /// <exception cref="System.InvalidOperationException">
  1069. /// </exception>
  1070. /// <exception cref="System.ArgumentNullException">item</exception>
  1071. public string GetImagePath(ImageType imageType, int imageIndex)
  1072. {
  1073. var info = GetImageInfo(imageType, imageIndex);
  1074. return info == null ? null : info.Path;
  1075. }
  1076. /// <summary>
  1077. /// Gets the image information.
  1078. /// </summary>
  1079. /// <param name="imageType">Type of the image.</param>
  1080. /// <param name="imageIndex">Index of the image.</param>
  1081. /// <returns>ItemImageInfo.</returns>
  1082. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1083. {
  1084. if (imageType == ImageType.Chapter)
  1085. {
  1086. var chapter = ItemRepository.GetChapter(Id, imageIndex);
  1087. if (chapter == null)
  1088. {
  1089. return null;
  1090. }
  1091. var path = chapter.ImagePath;
  1092. if (string.IsNullOrWhiteSpace(path))
  1093. {
  1094. return null;
  1095. }
  1096. return new ItemImageInfo
  1097. {
  1098. Path = path,
  1099. DateModified = FileSystem.GetLastWriteTimeUtc(path),
  1100. Type = imageType
  1101. };
  1102. }
  1103. return GetImages(imageType)
  1104. .ElementAtOrDefault(imageIndex);
  1105. }
  1106. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1107. {
  1108. if (imageType == ImageType.Chapter)
  1109. {
  1110. throw new ArgumentException("No image info for chapter images");
  1111. }
  1112. return ImageInfos.Where(i => i.Type == imageType);
  1113. }
  1114. /// <summary>
  1115. /// Adds the images.
  1116. /// </summary>
  1117. /// <param name="imageType">Type of the image.</param>
  1118. /// <param name="images">The images.</param>
  1119. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1120. /// <exception cref="System.ArgumentException">Cannot call AddImages with chapter images</exception>
  1121. public bool AddImages(ImageType imageType, IEnumerable<FileInfo> images)
  1122. {
  1123. if (imageType == ImageType.Chapter)
  1124. {
  1125. throw new ArgumentException("Cannot call AddImages with chapter images");
  1126. }
  1127. var existingImagePaths = GetImages(imageType)
  1128. .Select(i => i.Path)
  1129. .ToList();
  1130. var newImages = images
  1131. .Where(i => !existingImagePaths.Contains(i.FullName, StringComparer.OrdinalIgnoreCase))
  1132. .ToList();
  1133. ImageInfos.AddRange(newImages.Select(i => new ItemImageInfo
  1134. {
  1135. Path = i.FullName,
  1136. Type = imageType,
  1137. DateModified = FileSystem.GetLastWriteTimeUtc(i)
  1138. }));
  1139. return newImages.Count > 0;
  1140. }
  1141. /// <summary>
  1142. /// Gets the file system path to delete when the item is to be deleted
  1143. /// </summary>
  1144. /// <returns></returns>
  1145. public virtual IEnumerable<string> GetDeletePaths()
  1146. {
  1147. return new[] { Path };
  1148. }
  1149. public bool AllowsMultipleImages(ImageType type)
  1150. {
  1151. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  1152. }
  1153. public Task SwapImages(ImageType type, int index1, int index2)
  1154. {
  1155. if (!AllowsMultipleImages(type))
  1156. {
  1157. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  1158. }
  1159. var info1 = GetImageInfo(type, index1);
  1160. var info2 = GetImageInfo(type, index2);
  1161. if (info1 == null || info2 == null)
  1162. {
  1163. // Nothing to do
  1164. return Task.FromResult(true);
  1165. }
  1166. var path1 = info1.Path;
  1167. var path2 = info2.Path;
  1168. FileSystem.SwapFiles(path1, path2);
  1169. // Refresh these values
  1170. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  1171. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  1172. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1173. }
  1174. public virtual bool IsPlayed(User user)
  1175. {
  1176. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1177. return userdata != null && userdata.Played;
  1178. }
  1179. public virtual bool IsUnplayed(User user)
  1180. {
  1181. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1182. return userdata == null || !userdata.Played;
  1183. }
  1184. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  1185. {
  1186. return GetItemLookupInfo<ItemLookupInfo>();
  1187. }
  1188. protected T GetItemLookupInfo<T>()
  1189. where T : ItemLookupInfo, new()
  1190. {
  1191. return new T
  1192. {
  1193. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  1194. MetadataLanguage = GetPreferredMetadataLanguage(),
  1195. Name = Name,
  1196. ProviderIds = ProviderIds,
  1197. IndexNumber = IndexNumber,
  1198. ParentIndexNumber = ParentIndexNumber
  1199. };
  1200. }
  1201. /// <summary>
  1202. /// This is called before any metadata refresh and returns true or false indicating if changes were made
  1203. /// </summary>
  1204. public virtual bool BeforeMetadataRefresh()
  1205. {
  1206. var hasChanges = false;
  1207. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  1208. {
  1209. Name = System.IO.Path.GetFileNameWithoutExtension(Path);
  1210. hasChanges = true;
  1211. }
  1212. return hasChanges;
  1213. }
  1214. }
  1215. }