BaseItem.cs 53 KB

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