BaseItem.cs 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512
  1. using MediaBrowser.Controller.Configuration;
  2. using MediaBrowser.Controller.IO;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Controller.Localization;
  5. using MediaBrowser.Controller.Persistence;
  6. using MediaBrowser.Controller.Providers;
  7. using MediaBrowser.Controller.Resolvers;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Runtime.Serialization;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. namespace MediaBrowser.Controller.Entities
  18. {
  19. /// <summary>
  20. /// Class BaseItem
  21. /// </summary>
  22. public abstract class BaseItem : IHasProviderIds
  23. {
  24. protected BaseItem()
  25. {
  26. Genres = new List<string>();
  27. RemoteTrailers = new List<MediaUrl>();
  28. Studios = new List<string>();
  29. People = new List<PersonInfo>();
  30. Taglines = new List<string>();
  31. ScreenshotImagePaths = new List<string>();
  32. BackdropImagePaths = new List<string>();
  33. ProductionLocations = new List<string>();
  34. Images = new Dictionary<ImageType, string>();
  35. ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  36. Tags = new List<string>();
  37. ThemeSongIds = new List<Guid>();
  38. ThemeVideoIds = new List<Guid>();
  39. LocalTrailerIds = new List<Guid>();
  40. LockedFields = new List<MetadataFields>();
  41. }
  42. /// <summary>
  43. /// The supported image extensions
  44. /// </summary>
  45. public static readonly string[] SupportedImageExtensions = new[] { ".png", ".jpg", ".jpeg" };
  46. /// <summary>
  47. /// The trailer folder name
  48. /// </summary>
  49. public const string TrailerFolderName = "trailers";
  50. public const string ThemeSongsFolderName = "theme-music";
  51. public const string ThemeSongFilename = "theme";
  52. public const string ThemeVideosFolderName = "backdrops";
  53. public const string XbmcTrailerFileSuffix = "-trailer";
  54. private string _name;
  55. /// <summary>
  56. /// Gets or sets the name.
  57. /// </summary>
  58. /// <value>The name.</value>
  59. public virtual string Name
  60. {
  61. get
  62. {
  63. return _name;
  64. }
  65. set
  66. {
  67. _name = value;
  68. // lazy load this again
  69. _sortName = null;
  70. }
  71. }
  72. /// <summary>
  73. /// Gets or sets the id.
  74. /// </summary>
  75. /// <value>The id.</value>
  76. public Guid Id { get; set; }
  77. /// <summary>
  78. /// Gets or sets the path.
  79. /// </summary>
  80. /// <value>The path.</value>
  81. public virtual string Path { get; set; }
  82. [IgnoreDataMember]
  83. protected internal bool IsOffline { get; set; }
  84. /// <summary>
  85. /// Gets or sets the type of the location.
  86. /// </summary>
  87. /// <value>The type of the location.</value>
  88. public virtual LocationType LocationType
  89. {
  90. get
  91. {
  92. if (IsOffline)
  93. {
  94. return LocationType.Offline;
  95. }
  96. if (string.IsNullOrEmpty(Path))
  97. {
  98. return LocationType.Virtual;
  99. }
  100. return System.IO.Path.IsPathRooted(Path) ? LocationType.FileSystem : LocationType.Remote;
  101. }
  102. }
  103. /// <summary>
  104. /// This is just a helper for convenience
  105. /// </summary>
  106. /// <value>The primary image path.</value>
  107. [IgnoreDataMember]
  108. public string PrimaryImagePath
  109. {
  110. get { return GetImage(ImageType.Primary); }
  111. set { SetImage(ImageType.Primary, value); }
  112. }
  113. /// <summary>
  114. /// Gets or sets the images.
  115. /// </summary>
  116. /// <value>The images.</value>
  117. public virtual Dictionary<ImageType, string> Images { get; set; }
  118. /// <summary>
  119. /// Gets or sets the date created.
  120. /// </summary>
  121. /// <value>The date created.</value>
  122. public DateTime DateCreated { get; set; }
  123. /// <summary>
  124. /// Gets or sets the date modified.
  125. /// </summary>
  126. /// <value>The date modified.</value>
  127. public DateTime DateModified { get; set; }
  128. /// <summary>
  129. /// The logger
  130. /// </summary>
  131. public static ILogger Logger { get; set; }
  132. public static ILibraryManager LibraryManager { get; set; }
  133. public static IServerConfigurationManager ConfigurationManager { get; set; }
  134. public static IProviderManager ProviderManager { get; set; }
  135. public static ILocalizationManager LocalizationManager { get; set; }
  136. public static IItemRepository ItemRepository { get; set; }
  137. /// <summary>
  138. /// Returns a <see cref="System.String" /> that represents this instance.
  139. /// </summary>
  140. /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
  141. public override string ToString()
  142. {
  143. return Name;
  144. }
  145. /// <summary>
  146. /// Returns true if this item should not attempt to fetch metadata
  147. /// </summary>
  148. /// <value><c>true</c> if [dont fetch meta]; otherwise, <c>false</c>.</value>
  149. public bool DontFetchMeta { get; set; }
  150. /// <summary>
  151. /// Gets or sets the locked fields.
  152. /// </summary>
  153. /// <value>The locked fields.</value>
  154. public List<MetadataFields> LockedFields { get; set; }
  155. /// <summary>
  156. /// Determines whether the item has a saved local image of the specified name (jpg or png).
  157. /// </summary>
  158. /// <param name="name">The name.</param>
  159. /// <returns><c>true</c> if [has local image] [the specified item]; otherwise, <c>false</c>.</returns>
  160. /// <exception cref="System.ArgumentNullException">name</exception>
  161. public bool HasLocalImage(string name)
  162. {
  163. if (string.IsNullOrEmpty(name))
  164. {
  165. throw new ArgumentNullException("name");
  166. }
  167. return ResolveArgs.ContainsMetaFileByName(name + ".jpg") ||
  168. ResolveArgs.ContainsMetaFileByName(name + ".png");
  169. }
  170. /// <summary>
  171. /// Should be overridden to return the proper folder where metadata lives
  172. /// </summary>
  173. /// <value>The meta location.</value>
  174. [IgnoreDataMember]
  175. public virtual string MetaLocation
  176. {
  177. get
  178. {
  179. return Path ?? "";
  180. }
  181. }
  182. /// <summary>
  183. /// The _provider data
  184. /// </summary>
  185. private Dictionary<Guid, BaseProviderInfo> _providerData;
  186. /// <summary>
  187. /// Holds persistent data for providers like last refresh date.
  188. /// Providers can use this to determine if they need to refresh.
  189. /// The BaseProviderInfo class can be extended to hold anything a provider may need.
  190. /// Keyed by a unique provider ID.
  191. /// </summary>
  192. /// <value>The provider data.</value>
  193. public Dictionary<Guid, BaseProviderInfo> ProviderData
  194. {
  195. get
  196. {
  197. return _providerData ?? (_providerData = new Dictionary<Guid, BaseProviderInfo>());
  198. }
  199. set
  200. {
  201. _providerData = value;
  202. }
  203. }
  204. /// <summary>
  205. /// Gets the type of the media.
  206. /// </summary>
  207. /// <value>The type of the media.</value>
  208. [IgnoreDataMember]
  209. public virtual string MediaType
  210. {
  211. get
  212. {
  213. return null;
  214. }
  215. }
  216. /// <summary>
  217. /// The _resolve args
  218. /// </summary>
  219. private ItemResolveArgs _resolveArgs;
  220. /// <summary>
  221. /// The _resolve args initialized
  222. /// </summary>
  223. private bool _resolveArgsInitialized;
  224. /// <summary>
  225. /// The _resolve args sync lock
  226. /// </summary>
  227. private object _resolveArgsSyncLock = new object();
  228. /// <summary>
  229. /// We attach these to the item so that we only ever have to hit the file system once
  230. /// (this includes the children of the containing folder)
  231. /// </summary>
  232. /// <value>The resolve args.</value>
  233. [IgnoreDataMember]
  234. public ItemResolveArgs ResolveArgs
  235. {
  236. get
  237. {
  238. try
  239. {
  240. LazyInitializer.EnsureInitialized(ref _resolveArgs, ref _resolveArgsInitialized, ref _resolveArgsSyncLock, () => CreateResolveArgs());
  241. }
  242. catch (IOException ex)
  243. {
  244. Logger.ErrorException("Error creating resolve args for {0}", ex, Path);
  245. IsOffline = true;
  246. throw;
  247. }
  248. return _resolveArgs;
  249. }
  250. set
  251. {
  252. _resolveArgs = value;
  253. _resolveArgsInitialized = value != null;
  254. }
  255. }
  256. /// <summary>
  257. /// Resets the resolve args.
  258. /// </summary>
  259. /// <param name="pathInfo">The path info.</param>
  260. public void ResetResolveArgs(FileSystemInfo pathInfo)
  261. {
  262. ResolveArgs = CreateResolveArgs(pathInfo);
  263. }
  264. /// <summary>
  265. /// Creates ResolveArgs on demand
  266. /// </summary>
  267. /// <param name="pathInfo">The path info.</param>
  268. /// <returns>ItemResolveArgs.</returns>
  269. /// <exception cref="System.IO.IOException">Unable to retrieve file system info for + path</exception>
  270. protected internal virtual ItemResolveArgs CreateResolveArgs(FileSystemInfo pathInfo = null)
  271. {
  272. var path = Path;
  273. if (LocationType == LocationType.Remote || LocationType == LocationType.Virtual)
  274. {
  275. return new ItemResolveArgs(ConfigurationManager.ApplicationPaths);
  276. }
  277. var isDirectory = false;
  278. if (UseParentPathToCreateResolveArgs)
  279. {
  280. path = System.IO.Path.GetDirectoryName(path);
  281. isDirectory = true;
  282. }
  283. pathInfo = pathInfo ?? (isDirectory ? new DirectoryInfo(path) : FileSystem.GetFileSystemInfo(path));
  284. if (pathInfo == null || !pathInfo.Exists)
  285. {
  286. throw new IOException("Unable to retrieve file system info for " + path);
  287. }
  288. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths)
  289. {
  290. FileInfo = pathInfo,
  291. Path = path,
  292. Parent = Parent
  293. };
  294. // Gather child folder and files
  295. if (args.IsDirectory)
  296. {
  297. var isPhysicalRoot = args.IsPhysicalRoot;
  298. // When resolving the root, we need it's grandchildren (children of user views)
  299. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  300. args.FileSystemDictionary = FileData.GetFilteredFileSystemEntries(args.Path, Logger, args, flattenFolderDepth: flattenFolderDepth, resolveShortcuts: isPhysicalRoot || args.IsVf);
  301. // Need to remove subpaths that may have been resolved from shortcuts
  302. // Example: if \\server\movies exists, then strip out \\server\movies\action
  303. if (isPhysicalRoot)
  304. {
  305. var paths = args.FileSystemDictionary.Keys.ToList();
  306. foreach (var subPath in paths
  307. .Where(subPath => !subPath.EndsWith(":\\", StringComparison.OrdinalIgnoreCase) && paths.Any(i => subPath.StartsWith(i.TrimEnd(System.IO.Path.DirectorySeparatorChar) + System.IO.Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))))
  308. {
  309. Logger.Info("Ignoring duplicate path: {0}", subPath);
  310. args.FileSystemDictionary.Remove(subPath);
  311. }
  312. }
  313. }
  314. //update our dates
  315. EntityResolutionHelper.EnsureDates(this, args);
  316. IsOffline = false;
  317. return args;
  318. }
  319. /// <summary>
  320. /// Some subclasses will stop resolving at a directory and point their Path to a file within. This will help ensure the on-demand resolve args are identical to the
  321. /// original ones.
  322. /// </summary>
  323. /// <value><c>true</c> if [use parent path to create resolve args]; otherwise, <c>false</c>.</value>
  324. [IgnoreDataMember]
  325. protected virtual bool UseParentPathToCreateResolveArgs
  326. {
  327. get
  328. {
  329. return false;
  330. }
  331. }
  332. /// <summary>
  333. /// Gets or sets the name of the forced sort.
  334. /// </summary>
  335. /// <value>The name of the forced sort.</value>
  336. public string ForcedSortName { get; set; }
  337. private string _sortName;
  338. /// <summary>
  339. /// Gets or sets the name of the sort.
  340. /// </summary>
  341. /// <value>The name of the sort.</value>
  342. [IgnoreDataMember]
  343. public string SortName
  344. {
  345. get
  346. {
  347. return ForcedSortName ?? _sortName ?? (_sortName = CreateSortName());
  348. }
  349. }
  350. /// <summary>
  351. /// Creates the name of the sort.
  352. /// </summary>
  353. /// <returns>System.String.</returns>
  354. protected virtual string CreateSortName()
  355. {
  356. if (Name == null) return null; //some items may not have name filled in properly
  357. var sortable = Name.Trim().ToLower();
  358. sortable = ConfigurationManager.Configuration.SortRemoveCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), string.Empty));
  359. sortable = ConfigurationManager.Configuration.SortReplaceCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), " "));
  360. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  361. {
  362. var searchLower = search.ToLower();
  363. // Remove from beginning if a space follows
  364. if (sortable.StartsWith(searchLower + " "))
  365. {
  366. sortable = sortable.Remove(0, searchLower.Length + 1);
  367. }
  368. // Remove from middle if surrounded by spaces
  369. sortable = sortable.Replace(" " + searchLower + " ", " ");
  370. // Remove from end if followed by a space
  371. if (sortable.EndsWith(" " + searchLower))
  372. {
  373. sortable = sortable.Remove(sortable.Length - (searchLower.Length + 1));
  374. }
  375. }
  376. return sortable;
  377. }
  378. /// <summary>
  379. /// Gets or sets the parent.
  380. /// </summary>
  381. /// <value>The parent.</value>
  382. [IgnoreDataMember]
  383. public Folder Parent { get; set; }
  384. /// <summary>
  385. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  386. /// </summary>
  387. /// <value>The premiere date.</value>
  388. public DateTime? PremiereDate { get; set; }
  389. /// <summary>
  390. /// Gets or sets the end date.
  391. /// </summary>
  392. /// <value>The end date.</value>
  393. public DateTime? EndDate { get; set; }
  394. /// <summary>
  395. /// Gets or sets the display type of the media.
  396. /// </summary>
  397. /// <value>The display type of the media.</value>
  398. public string DisplayMediaType { get; set; }
  399. /// <summary>
  400. /// Gets or sets the backdrop image paths.
  401. /// </summary>
  402. /// <value>The backdrop image paths.</value>
  403. public List<string> BackdropImagePaths { get; set; }
  404. /// <summary>
  405. /// Gets or sets the screenshot image paths.
  406. /// </summary>
  407. /// <value>The screenshot image paths.</value>
  408. public List<string> ScreenshotImagePaths { get; set; }
  409. /// <summary>
  410. /// Gets or sets the official rating.
  411. /// </summary>
  412. /// <value>The official rating.</value>
  413. public string OfficialRating { get; set; }
  414. /// <summary>
  415. /// Gets or sets the official rating description.
  416. /// </summary>
  417. /// <value>The official rating description.</value>
  418. public string OfficialRatingDescription { get; set; }
  419. /// <summary>
  420. /// Gets or sets the custom rating.
  421. /// </summary>
  422. /// <value>The custom rating.</value>
  423. public string CustomRating { get; set; }
  424. /// <summary>
  425. /// Gets or sets the language.
  426. /// </summary>
  427. /// <value>The language.</value>
  428. public string Language { get; set; }
  429. /// <summary>
  430. /// Gets or sets the overview.
  431. /// </summary>
  432. /// <value>The overview.</value>
  433. public string Overview { get; set; }
  434. /// <summary>
  435. /// Gets or sets the taglines.
  436. /// </summary>
  437. /// <value>The taglines.</value>
  438. public List<string> Taglines { get; set; }
  439. /// <summary>
  440. /// Gets or sets the people.
  441. /// </summary>
  442. /// <value>The people.</value>
  443. public List<PersonInfo> People { get; set; }
  444. /// <summary>
  445. /// Gets or sets the tags.
  446. /// </summary>
  447. /// <value>The tags.</value>
  448. public List<string> Tags { get; set; }
  449. /// <summary>
  450. /// Override this if you need to combine/collapse person information
  451. /// </summary>
  452. /// <value>All people.</value>
  453. [IgnoreDataMember]
  454. public virtual IEnumerable<PersonInfo> AllPeople
  455. {
  456. get { return People; }
  457. }
  458. [IgnoreDataMember]
  459. public virtual IEnumerable<string> AllStudios
  460. {
  461. get { return Studios; }
  462. }
  463. [IgnoreDataMember]
  464. public virtual IEnumerable<string> AllGenres
  465. {
  466. get { return Genres; }
  467. }
  468. /// <summary>
  469. /// Gets or sets the studios.
  470. /// </summary>
  471. /// <value>The studios.</value>
  472. public List<string> Studios { get; set; }
  473. /// <summary>
  474. /// Gets or sets the genres.
  475. /// </summary>
  476. /// <value>The genres.</value>
  477. public virtual List<string> Genres { get; set; }
  478. /// <summary>
  479. /// Gets or sets the home page URL.
  480. /// </summary>
  481. /// <value>The home page URL.</value>
  482. public string HomePageUrl { get; set; }
  483. /// <summary>
  484. /// Gets or sets the budget.
  485. /// </summary>
  486. /// <value>The budget.</value>
  487. public double? Budget { get; set; }
  488. /// <summary>
  489. /// Gets or sets the revenue.
  490. /// </summary>
  491. /// <value>The revenue.</value>
  492. public double? Revenue { get; set; }
  493. /// <summary>
  494. /// Gets or sets the production locations.
  495. /// </summary>
  496. /// <value>The production locations.</value>
  497. public List<string> ProductionLocations { get; set; }
  498. /// <summary>
  499. /// Gets or sets the critic rating.
  500. /// </summary>
  501. /// <value>The critic rating.</value>
  502. public float? CriticRating { get; set; }
  503. /// <summary>
  504. /// Gets or sets the critic rating summary.
  505. /// </summary>
  506. /// <value>The critic rating summary.</value>
  507. public string CriticRatingSummary { get; set; }
  508. /// <summary>
  509. /// Gets or sets the community rating.
  510. /// </summary>
  511. /// <value>The community rating.</value>
  512. public float? CommunityRating { get; set; }
  513. /// <summary>
  514. /// Gets or sets the community rating vote count.
  515. /// </summary>
  516. /// <value>The community rating vote count.</value>
  517. public int? VoteCount { get; set; }
  518. /// <summary>
  519. /// Gets or sets the run time ticks.
  520. /// </summary>
  521. /// <value>The run time ticks.</value>
  522. public long? RunTimeTicks { get; set; }
  523. /// <summary>
  524. /// Gets or sets the original run time ticks.
  525. /// </summary>
  526. /// <value>The original run time ticks.</value>
  527. public long? OriginalRunTimeTicks { get; set; }
  528. /// <summary>
  529. /// Gets or sets the aspect ratio.
  530. /// </summary>
  531. /// <value>The aspect ratio.</value>
  532. public string AspectRatio { get; set; }
  533. /// <summary>
  534. /// Gets or sets the production year.
  535. /// </summary>
  536. /// <value>The production year.</value>
  537. public int? ProductionYear { get; set; }
  538. /// <summary>
  539. /// If the item is part of a series, this is it's number in the series.
  540. /// This could be episode number, album track number, etc.
  541. /// </summary>
  542. /// <value>The index number.</value>
  543. public int? IndexNumber { get; set; }
  544. /// <summary>
  545. /// For an episode this could be the season number, or for a song this could be the disc number.
  546. /// </summary>
  547. /// <value>The parent index number.</value>
  548. public int? ParentIndexNumber { get; set; }
  549. public List<Guid> ThemeSongIds { get; set; }
  550. public List<Guid> ThemeVideoIds { get; set; }
  551. public List<Guid> LocalTrailerIds { get; set; }
  552. [IgnoreDataMember]
  553. public virtual string OfficialRatingForComparison
  554. {
  555. get { return OfficialRating; }
  556. }
  557. [IgnoreDataMember]
  558. public virtual string CustomRatingForComparison
  559. {
  560. get { return CustomRating; }
  561. }
  562. /// <summary>
  563. /// Loads local trailers from the file system
  564. /// </summary>
  565. /// <returns>List{Video}.</returns>
  566. private IEnumerable<Trailer> LoadLocalTrailers()
  567. {
  568. ItemResolveArgs resolveArgs;
  569. try
  570. {
  571. resolveArgs = ResolveArgs;
  572. if (!resolveArgs.IsDirectory)
  573. {
  574. return new List<Trailer>();
  575. }
  576. }
  577. catch (IOException ex)
  578. {
  579. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  580. return new List<Trailer>();
  581. }
  582. var files = new List<FileSystemInfo>();
  583. var folder = resolveArgs.GetFileSystemEntryByName(TrailerFolderName);
  584. // Path doesn't exist. No biggie
  585. if (folder != null)
  586. {
  587. try
  588. {
  589. files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  590. }
  591. catch (IOException ex)
  592. {
  593. Logger.ErrorException("Error loading trailers for {0}", ex, Name);
  594. }
  595. }
  596. // Support xbmc trailers (-trailer suffix on video file names)
  597. files.AddRange(resolveArgs.FileSystemChildren.Where(i =>
  598. {
  599. try
  600. {
  601. if ((i.Attributes & FileAttributes.Directory) != FileAttributes.Directory)
  602. {
  603. if (System.IO.Path.GetFileNameWithoutExtension(i.Name).EndsWith(XbmcTrailerFileSuffix, StringComparison.OrdinalIgnoreCase) && !string.Equals(Path, i.FullName, StringComparison.OrdinalIgnoreCase))
  604. {
  605. return true;
  606. }
  607. }
  608. }
  609. catch (IOException ex)
  610. {
  611. Logger.ErrorException("Error accessing path {0}", ex, i.FullName);
  612. }
  613. return false;
  614. }));
  615. return LibraryManager.ResolvePaths<Trailer>(files, null).Select(video =>
  616. {
  617. // Try to retrieve it from the db. If we don't find it, use the resolved version
  618. var dbItem = LibraryManager.RetrieveItem(video.Id) as Trailer;
  619. if (dbItem != null)
  620. {
  621. dbItem.ResolveArgs = video.ResolveArgs;
  622. video = dbItem;
  623. }
  624. return video;
  625. }).ToList();
  626. }
  627. /// <summary>
  628. /// Loads the theme songs.
  629. /// </summary>
  630. /// <returns>List{Audio.Audio}.</returns>
  631. private IEnumerable<Audio.Audio> LoadThemeSongs()
  632. {
  633. ItemResolveArgs resolveArgs;
  634. try
  635. {
  636. resolveArgs = ResolveArgs;
  637. if (!resolveArgs.IsDirectory)
  638. {
  639. return new List<Audio.Audio>();
  640. }
  641. }
  642. catch (IOException ex)
  643. {
  644. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  645. return new List<Audio.Audio>();
  646. }
  647. var files = new List<FileSystemInfo>();
  648. var folder = resolveArgs.GetFileSystemEntryByName(ThemeSongsFolderName);
  649. // Path doesn't exist. No biggie
  650. if (folder != null)
  651. {
  652. try
  653. {
  654. files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  655. }
  656. catch (IOException ex)
  657. {
  658. Logger.ErrorException("Error loading theme songs for {0}", ex, Name);
  659. }
  660. }
  661. // Support plex/xbmc convention
  662. files.AddRange(resolveArgs.FileSystemChildren
  663. .Where(i => string.Equals(System.IO.Path.GetFileNameWithoutExtension(i.Name), ThemeSongFilename, StringComparison.OrdinalIgnoreCase) && EntityResolutionHelper.IsAudioFile(i.Name))
  664. );
  665. return LibraryManager.ResolvePaths<Audio.Audio>(files, null).Select(audio =>
  666. {
  667. // Try to retrieve it from the db. If we don't find it, use the resolved version
  668. var dbItem = LibraryManager.RetrieveItem(audio.Id) as Audio.Audio;
  669. if (dbItem != null)
  670. {
  671. dbItem.ResolveArgs = audio.ResolveArgs;
  672. audio = dbItem;
  673. }
  674. return audio;
  675. }).ToList();
  676. }
  677. /// <summary>
  678. /// Loads the video backdrops.
  679. /// </summary>
  680. /// <returns>List{Video}.</returns>
  681. private IEnumerable<Video> LoadThemeVideos()
  682. {
  683. ItemResolveArgs resolveArgs;
  684. try
  685. {
  686. resolveArgs = ResolveArgs;
  687. if (!resolveArgs.IsDirectory)
  688. {
  689. return new List<Video>();
  690. }
  691. }
  692. catch (IOException ex)
  693. {
  694. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  695. return new List<Video>();
  696. }
  697. var folder = resolveArgs.GetFileSystemEntryByName(ThemeVideosFolderName);
  698. // Path doesn't exist. No biggie
  699. if (folder == null)
  700. {
  701. return new List<Video>();
  702. }
  703. IEnumerable<FileSystemInfo> files;
  704. try
  705. {
  706. files = new DirectoryInfo(folder.FullName).EnumerateFiles();
  707. }
  708. catch (IOException ex)
  709. {
  710. Logger.ErrorException("Error loading video backdrops for {0}", ex, Name);
  711. return new List<Video>();
  712. }
  713. return LibraryManager.ResolvePaths<Video>(files, null).Select(item =>
  714. {
  715. // Try to retrieve it from the db. If we don't find it, use the resolved version
  716. var dbItem = LibraryManager.RetrieveItem(item.Id) as Video;
  717. if (dbItem != null)
  718. {
  719. dbItem.ResolveArgs = item.ResolveArgs;
  720. item = dbItem;
  721. }
  722. return item;
  723. }).ToList();
  724. }
  725. /// <summary>
  726. /// Overrides the base implementation to refresh metadata for local trailers
  727. /// </summary>
  728. /// <param name="cancellationToken">The cancellation token.</param>
  729. /// <param name="forceSave">if set to <c>true</c> [is new item].</param>
  730. /// <param name="forceRefresh">if set to <c>true</c> [force].</param>
  731. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  732. /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param>
  733. /// <returns>true if a provider reports we changed</returns>
  734. public virtual async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  735. {
  736. if (resetResolveArgs)
  737. {
  738. // Reload this
  739. ResolveArgs = null;
  740. }
  741. // Refresh for the item
  742. var itemRefreshTask = ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh, allowSlowProviders);
  743. cancellationToken.ThrowIfCancellationRequested();
  744. var themeSongsChanged = false;
  745. var themeVideosChanged = false;
  746. var localTrailersChanged = false;
  747. if (LocationType == LocationType.FileSystem && Parent != null)
  748. {
  749. themeSongsChanged = await RefreshThemeSongs(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  750. themeVideosChanged = await RefreshThemeVideos(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  751. localTrailersChanged = await RefreshLocalTrailers(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  752. }
  753. cancellationToken.ThrowIfCancellationRequested();
  754. // Get the result from the item task
  755. var updateReason = await itemRefreshTask.ConfigureAwait(false);
  756. var changed = updateReason.HasValue;
  757. if (changed || forceSave || themeSongsChanged || themeVideosChanged || localTrailersChanged)
  758. {
  759. cancellationToken.ThrowIfCancellationRequested();
  760. await LibraryManager.UpdateItem(this, updateReason ?? ItemUpdateType.Unspecified, cancellationToken).ConfigureAwait(false);
  761. }
  762. return changed;
  763. }
  764. private async Task<bool> RefreshLocalTrailers(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  765. {
  766. var newItems = LoadLocalTrailers().ToList();
  767. var newItemIds = newItems.Select(i => i.Id).ToList();
  768. var itemsChanged = !LocalTrailerIds.SequenceEqual(newItemIds);
  769. var tasks = newItems.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  770. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  771. LocalTrailerIds = newItemIds;
  772. return itemsChanged || results.Contains(true);
  773. }
  774. private async Task<bool> RefreshThemeVideos(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  775. {
  776. var newThemeVideos = LoadThemeVideos().ToList();
  777. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  778. var themeVideosChanged = !ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  779. var tasks = newThemeVideos.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  780. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  781. ThemeVideoIds = newThemeVideoIds;
  782. return themeVideosChanged || results.Contains(true);
  783. }
  784. /// <summary>
  785. /// Refreshes the theme songs.
  786. /// </summary>
  787. private async Task<bool> RefreshThemeSongs(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  788. {
  789. var newThemeSongs = LoadThemeSongs().ToList();
  790. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  791. var themeSongsChanged = !ThemeSongIds.SequenceEqual(newThemeSongIds);
  792. var tasks = newThemeSongs.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  793. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  794. ThemeSongIds = newThemeSongIds;
  795. return themeSongsChanged || results.Contains(true);
  796. }
  797. /// <summary>
  798. /// Gets or sets the trailer URL.
  799. /// </summary>
  800. /// <value>The trailer URL.</value>
  801. public List<MediaUrl> RemoteTrailers { get; set; }
  802. /// <summary>
  803. /// Gets or sets the provider ids.
  804. /// </summary>
  805. /// <value>The provider ids.</value>
  806. public Dictionary<string, string> ProviderIds { get; set; }
  807. /// <summary>
  808. /// Override this to false if class should be ignored for indexing purposes
  809. /// </summary>
  810. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  811. [IgnoreDataMember]
  812. public virtual bool IncludeInIndex
  813. {
  814. get { return true; }
  815. }
  816. /// <summary>
  817. /// Override this to true if class should be grouped under a container in indicies
  818. /// The container class should be defined via IndexContainer
  819. /// </summary>
  820. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  821. [IgnoreDataMember]
  822. public virtual bool GroupInIndex
  823. {
  824. get { return false; }
  825. }
  826. /// <summary>
  827. /// Override this to return the folder that should be used to construct a container
  828. /// for this item in an index. GroupInIndex should be true as well.
  829. /// </summary>
  830. /// <value>The index container.</value>
  831. [IgnoreDataMember]
  832. public virtual Folder IndexContainer
  833. {
  834. get { return null; }
  835. }
  836. /// <summary>
  837. /// Gets the user data key.
  838. /// </summary>
  839. /// <returns>System.String.</returns>
  840. public virtual string GetUserDataKey()
  841. {
  842. return Id.ToString();
  843. }
  844. /// <summary>
  845. /// Determines if a given user has access to this item
  846. /// </summary>
  847. /// <param name="user">The user.</param>
  848. /// <param name="localizationManager">The localization manager.</param>
  849. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  850. /// <exception cref="System.ArgumentNullException">user</exception>
  851. public bool IsParentalAllowed(User user, ILocalizationManager localizationManager)
  852. {
  853. if (user == null)
  854. {
  855. throw new ArgumentNullException("user");
  856. }
  857. if (user.Configuration.MaxParentalRating == null)
  858. {
  859. return true;
  860. }
  861. var rating = CustomRatingForComparison;
  862. if (string.IsNullOrEmpty(rating))
  863. {
  864. rating = OfficialRatingForComparison;
  865. }
  866. if (string.IsNullOrEmpty(rating))
  867. {
  868. return !user.Configuration.BlockNotRated;
  869. }
  870. var value = localizationManager.GetRatingLevel(rating);
  871. // Could not determine the integer value
  872. if (!value.HasValue)
  873. {
  874. return true;
  875. }
  876. return value.Value <= user.Configuration.MaxParentalRating.Value;
  877. }
  878. /// <summary>
  879. /// Determines if this folder should be visible to a given user.
  880. /// Default is just parental allowed. Can be overridden for more functionality.
  881. /// </summary>
  882. /// <param name="user">The user.</param>
  883. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  884. /// <exception cref="System.ArgumentNullException">user</exception>
  885. public virtual bool IsVisible(User user)
  886. {
  887. if (user == null)
  888. {
  889. throw new ArgumentNullException("user");
  890. }
  891. return IsParentalAllowed(user, LocalizationManager);
  892. }
  893. /// <summary>
  894. /// Finds the particular item by searching through our parents and, if not found there, loading from repo
  895. /// </summary>
  896. /// <param name="id">The id.</param>
  897. /// <returns>BaseItem.</returns>
  898. /// <exception cref="System.ArgumentException"></exception>
  899. protected BaseItem FindParentItem(Guid id)
  900. {
  901. if (id == Guid.Empty)
  902. {
  903. throw new ArgumentException();
  904. }
  905. var parent = Parent;
  906. while (parent != null && !parent.IsRoot)
  907. {
  908. if (parent.Id == id) return parent;
  909. parent = parent.Parent;
  910. }
  911. return null;
  912. }
  913. /// <summary>
  914. /// Gets a value indicating whether this instance is folder.
  915. /// </summary>
  916. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  917. [IgnoreDataMember]
  918. public virtual bool IsFolder
  919. {
  920. get
  921. {
  922. return false;
  923. }
  924. }
  925. /// <summary>
  926. /// Determine if we have changed vs the passed in copy
  927. /// </summary>
  928. /// <param name="copy">The copy.</param>
  929. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  930. /// <exception cref="System.ArgumentNullException"></exception>
  931. public virtual bool HasChanged(BaseItem copy)
  932. {
  933. if (copy == null)
  934. {
  935. throw new ArgumentNullException();
  936. }
  937. var changed = copy.DateModified != DateModified;
  938. if (changed)
  939. {
  940. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  941. }
  942. return changed;
  943. }
  944. /// <summary>
  945. /// Determines if the item is considered new based on user settings
  946. /// </summary>
  947. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  948. /// <exception cref="System.ArgumentNullException"></exception>
  949. public bool IsRecentlyAdded()
  950. {
  951. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  952. }
  953. /// <summary>
  954. /// Adds a person to the item
  955. /// </summary>
  956. /// <param name="person">The person.</param>
  957. /// <exception cref="System.ArgumentNullException"></exception>
  958. public void AddPerson(PersonInfo person)
  959. {
  960. if (person == null)
  961. {
  962. throw new ArgumentNullException("person");
  963. }
  964. if (string.IsNullOrWhiteSpace(person.Name))
  965. {
  966. throw new ArgumentNullException();
  967. }
  968. // Normalize
  969. if (string.Equals(person.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  970. {
  971. person.Type = PersonType.GuestStar;
  972. }
  973. else if (string.Equals(person.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
  974. {
  975. person.Type = PersonType.Director;
  976. }
  977. else if (string.Equals(person.Role, PersonType.Producer, StringComparison.OrdinalIgnoreCase))
  978. {
  979. person.Type = PersonType.Producer;
  980. }
  981. else if (string.Equals(person.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
  982. {
  983. person.Type = PersonType.Writer;
  984. }
  985. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  986. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  987. {
  988. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  989. if (existing != null)
  990. {
  991. existing.Type = PersonType.GuestStar;
  992. return;
  993. }
  994. }
  995. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  996. {
  997. // If the actor already exists without a role and we have one, fill it in
  998. 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)));
  999. if (existing == null)
  1000. {
  1001. // Wasn't there - add it
  1002. People.Add(person);
  1003. }
  1004. else
  1005. {
  1006. // Was there, if no role and we have one - fill it in
  1007. if (string.IsNullOrWhiteSpace(existing.Role) && !string.IsNullOrWhiteSpace(person.Role)) existing.Role = person.Role;
  1008. }
  1009. }
  1010. else
  1011. {
  1012. // Check for dupes based on the combination of Name and Type
  1013. if (!People.Any(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(person.Type, StringComparison.OrdinalIgnoreCase)))
  1014. {
  1015. People.Add(person);
  1016. }
  1017. }
  1018. }
  1019. /// <summary>
  1020. /// Adds a studio to the item
  1021. /// </summary>
  1022. /// <param name="name">The name.</param>
  1023. /// <exception cref="System.ArgumentNullException"></exception>
  1024. public void AddStudio(string name)
  1025. {
  1026. if (string.IsNullOrWhiteSpace(name))
  1027. {
  1028. throw new ArgumentNullException("name");
  1029. }
  1030. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1031. {
  1032. Studios.Add(name);
  1033. }
  1034. }
  1035. public void AddTag(string name)
  1036. {
  1037. if (string.IsNullOrWhiteSpace(name))
  1038. {
  1039. throw new ArgumentNullException("name");
  1040. }
  1041. if (!Tags.Contains(name, StringComparer.OrdinalIgnoreCase))
  1042. {
  1043. Tags.Add(name);
  1044. }
  1045. }
  1046. /// <summary>
  1047. /// Adds a tagline to the item
  1048. /// </summary>
  1049. /// <param name="name">The name.</param>
  1050. /// <exception cref="System.ArgumentNullException"></exception>
  1051. public void AddTagline(string name)
  1052. {
  1053. if (string.IsNullOrWhiteSpace(name))
  1054. {
  1055. throw new ArgumentNullException("name");
  1056. }
  1057. if (!Taglines.Contains(name, StringComparer.OrdinalIgnoreCase))
  1058. {
  1059. Taglines.Add(name);
  1060. }
  1061. }
  1062. /// <summary>
  1063. /// Adds a TrailerUrl to the item
  1064. /// </summary>
  1065. /// <param name="url">The URL.</param>
  1066. /// <param name="isDirectLink">if set to <c>true</c> [is direct link].</param>
  1067. /// <exception cref="System.ArgumentNullException">url</exception>
  1068. public void AddTrailerUrl(string url, bool isDirectLink)
  1069. {
  1070. if (string.IsNullOrWhiteSpace(url))
  1071. {
  1072. throw new ArgumentNullException("url");
  1073. }
  1074. var current = RemoteTrailers.FirstOrDefault(i => string.Equals(i.Url, url, StringComparison.OrdinalIgnoreCase));
  1075. if (current != null)
  1076. {
  1077. current.IsDirectLink = isDirectLink;
  1078. }
  1079. else
  1080. {
  1081. RemoteTrailers.Add(new MediaUrl
  1082. {
  1083. Url = url,
  1084. IsDirectLink = isDirectLink
  1085. });
  1086. }
  1087. }
  1088. /// <summary>
  1089. /// Adds a genre to the item
  1090. /// </summary>
  1091. /// <param name="name">The name.</param>
  1092. /// <exception cref="System.ArgumentNullException"></exception>
  1093. public void AddGenre(string name)
  1094. {
  1095. if (string.IsNullOrWhiteSpace(name))
  1096. {
  1097. throw new ArgumentNullException("name");
  1098. }
  1099. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1100. {
  1101. Genres.Add(name);
  1102. }
  1103. }
  1104. /// <summary>
  1105. /// Adds the production location.
  1106. /// </summary>
  1107. /// <param name="location">The location.</param>
  1108. /// <exception cref="System.ArgumentNullException">location</exception>
  1109. public void AddProductionLocation(string location)
  1110. {
  1111. if (string.IsNullOrWhiteSpace(location))
  1112. {
  1113. throw new ArgumentNullException("location");
  1114. }
  1115. if (!ProductionLocations.Contains(location, StringComparer.OrdinalIgnoreCase))
  1116. {
  1117. ProductionLocations.Add(location);
  1118. }
  1119. }
  1120. /// <summary>
  1121. /// Marks the item as either played or unplayed
  1122. /// </summary>
  1123. /// <param name="user">The user.</param>
  1124. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  1125. /// <param name="userManager">The user manager.</param>
  1126. /// <returns>Task.</returns>
  1127. /// <exception cref="System.ArgumentNullException"></exception>
  1128. public virtual async Task SetPlayedStatus(User user, bool wasPlayed, IUserDataRepository userManager)
  1129. {
  1130. if (user == null)
  1131. {
  1132. throw new ArgumentNullException();
  1133. }
  1134. var key = GetUserDataKey();
  1135. var data = userManager.GetUserData(user.Id, key);
  1136. if (wasPlayed)
  1137. {
  1138. data.PlayCount = Math.Max(data.PlayCount, 1);
  1139. if (!data.LastPlayedDate.HasValue)
  1140. {
  1141. data.LastPlayedDate = DateTime.UtcNow;
  1142. }
  1143. }
  1144. else
  1145. {
  1146. //I think it is okay to do this here.
  1147. // if this is only called when a user is manually forcing something to un-played
  1148. // then it probably is what we want to do...
  1149. data.PlayCount = 0;
  1150. data.PlaybackPositionTicks = 0;
  1151. data.LastPlayedDate = null;
  1152. }
  1153. data.Played = wasPlayed;
  1154. await userManager.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  1155. }
  1156. /// <summary>
  1157. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1158. /// </summary>
  1159. /// <returns>Task.</returns>
  1160. public virtual Task ChangedExternally()
  1161. {
  1162. return RefreshMetadata(CancellationToken.None);
  1163. }
  1164. /// <summary>
  1165. /// Finds a parent of a given type
  1166. /// </summary>
  1167. /// <typeparam name="T"></typeparam>
  1168. /// <returns>``0.</returns>
  1169. public T FindParent<T>()
  1170. where T : Folder
  1171. {
  1172. var parent = Parent;
  1173. while (parent != null)
  1174. {
  1175. var result = parent as T;
  1176. if (result != null)
  1177. {
  1178. return result;
  1179. }
  1180. parent = parent.Parent;
  1181. }
  1182. return null;
  1183. }
  1184. /// <summary>
  1185. /// Gets an image
  1186. /// </summary>
  1187. /// <param name="type">The type.</param>
  1188. /// <returns>System.String.</returns>
  1189. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1190. public string GetImage(ImageType type)
  1191. {
  1192. if (type == ImageType.Backdrop)
  1193. {
  1194. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1195. }
  1196. if (type == ImageType.Screenshot)
  1197. {
  1198. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1199. }
  1200. string val;
  1201. Images.TryGetValue(type, out val);
  1202. return val;
  1203. }
  1204. /// <summary>
  1205. /// Gets an image
  1206. /// </summary>
  1207. /// <param name="type">The type.</param>
  1208. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1209. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1210. public bool HasImage(ImageType type)
  1211. {
  1212. if (type == ImageType.Backdrop)
  1213. {
  1214. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1215. }
  1216. if (type == ImageType.Screenshot)
  1217. {
  1218. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1219. }
  1220. return !string.IsNullOrEmpty(GetImage(type));
  1221. }
  1222. /// <summary>
  1223. /// Sets an image
  1224. /// </summary>
  1225. /// <param name="type">The type.</param>
  1226. /// <param name="path">The path.</param>
  1227. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1228. public void SetImage(ImageType type, string path)
  1229. {
  1230. if (type == ImageType.Backdrop)
  1231. {
  1232. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1233. }
  1234. if (type == ImageType.Screenshot)
  1235. {
  1236. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1237. }
  1238. var typeKey = type;
  1239. // If it's null remove the key from the dictionary
  1240. if (string.IsNullOrEmpty(path))
  1241. {
  1242. if (Images.ContainsKey(typeKey))
  1243. {
  1244. Images.Remove(typeKey);
  1245. }
  1246. }
  1247. else
  1248. {
  1249. Images[typeKey] = path;
  1250. }
  1251. }
  1252. /// <summary>
  1253. /// Deletes the image.
  1254. /// </summary>
  1255. /// <param name="type">The type.</param>
  1256. /// <param name="index">The index.</param>
  1257. /// <returns>Task.</returns>
  1258. public Task DeleteImage(ImageType type, int? index)
  1259. {
  1260. if (type == ImageType.Backdrop)
  1261. {
  1262. if (!index.HasValue)
  1263. {
  1264. throw new ArgumentException("Please specify a backdrop image index to delete.");
  1265. }
  1266. var file = BackdropImagePaths[index.Value];
  1267. BackdropImagePaths.Remove(file);
  1268. // Delete the source file
  1269. File.Delete(file);
  1270. }
  1271. else if (type == ImageType.Screenshot)
  1272. {
  1273. if (!index.HasValue)
  1274. {
  1275. throw new ArgumentException("Please specify a screenshot image index to delete.");
  1276. }
  1277. var file = ScreenshotImagePaths[index.Value];
  1278. ScreenshotImagePaths.Remove(file);
  1279. // Delete the source file
  1280. File.Delete(file);
  1281. }
  1282. else
  1283. {
  1284. // Delete the source file
  1285. File.Delete(GetImage(type));
  1286. // Remove it from the item
  1287. SetImage(type, null);
  1288. }
  1289. // Refresh metadata
  1290. return RefreshMetadata(CancellationToken.None, forceSave: true);
  1291. }
  1292. }
  1293. }