BaseItem.cs 52 KB

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