BaseItem.cs 50 KB

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