BaseItem.cs 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493
  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 virtual 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 virtual 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. /// <summary>
  459. /// Gets or sets the studios.
  460. /// </summary>
  461. /// <value>The studios.</value>
  462. public virtual List<string> Studios { get; set; }
  463. /// <summary>
  464. /// Gets or sets the genres.
  465. /// </summary>
  466. /// <value>The genres.</value>
  467. public virtual List<string> Genres { get; set; }
  468. /// <summary>
  469. /// Gets or sets the home page URL.
  470. /// </summary>
  471. /// <value>The home page URL.</value>
  472. public string HomePageUrl { get; set; }
  473. /// <summary>
  474. /// Gets or sets the budget.
  475. /// </summary>
  476. /// <value>The budget.</value>
  477. public double? Budget { get; set; }
  478. /// <summary>
  479. /// Gets or sets the revenue.
  480. /// </summary>
  481. /// <value>The revenue.</value>
  482. public double? Revenue { get; set; }
  483. /// <summary>
  484. /// Gets or sets the production locations.
  485. /// </summary>
  486. /// <value>The production locations.</value>
  487. public List<string> ProductionLocations { get; set; }
  488. /// <summary>
  489. /// Gets or sets the critic rating.
  490. /// </summary>
  491. /// <value>The critic rating.</value>
  492. public float? CriticRating { get; set; }
  493. /// <summary>
  494. /// Gets or sets the critic rating summary.
  495. /// </summary>
  496. /// <value>The critic rating summary.</value>
  497. public string CriticRatingSummary { get; set; }
  498. /// <summary>
  499. /// Gets or sets the community rating.
  500. /// </summary>
  501. /// <value>The community rating.</value>
  502. public float? CommunityRating { get; set; }
  503. /// <summary>
  504. /// Gets or sets the community rating vote count.
  505. /// </summary>
  506. /// <value>The community rating vote count.</value>
  507. public int? VoteCount { get; set; }
  508. /// <summary>
  509. /// Gets or sets the run time ticks.
  510. /// </summary>
  511. /// <value>The run time ticks.</value>
  512. public long? RunTimeTicks { get; set; }
  513. /// <summary>
  514. /// Gets or sets the original run time ticks.
  515. /// </summary>
  516. /// <value>The original run time ticks.</value>
  517. public long? OriginalRunTimeTicks { get; set; }
  518. /// <summary>
  519. /// Gets or sets the aspect ratio.
  520. /// </summary>
  521. /// <value>The aspect ratio.</value>
  522. public string AspectRatio { get; set; }
  523. /// <summary>
  524. /// Gets or sets the production year.
  525. /// </summary>
  526. /// <value>The production year.</value>
  527. public virtual int? ProductionYear { get; set; }
  528. /// <summary>
  529. /// If the item is part of a series, this is it's number in the series.
  530. /// This could be episode number, album track number, etc.
  531. /// </summary>
  532. /// <value>The index number.</value>
  533. public int? IndexNumber { get; set; }
  534. /// <summary>
  535. /// For an episode this could be the season number, or for a song this could be the disc number.
  536. /// </summary>
  537. /// <value>The parent index number.</value>
  538. public int? ParentIndexNumber { get; set; }
  539. public List<Guid> ThemeSongIds { get; set; }
  540. public List<Guid> ThemeVideoIds { get; set; }
  541. public List<Guid> LocalTrailerIds { get; set; }
  542. /// <summary>
  543. /// Loads local trailers from the file system
  544. /// </summary>
  545. /// <returns>List{Video}.</returns>
  546. private IEnumerable<Trailer> LoadLocalTrailers()
  547. {
  548. ItemResolveArgs resolveArgs;
  549. try
  550. {
  551. resolveArgs = ResolveArgs;
  552. if (!resolveArgs.IsDirectory)
  553. {
  554. return new List<Trailer>();
  555. }
  556. }
  557. catch (IOException ex)
  558. {
  559. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  560. return new List<Trailer>();
  561. }
  562. var files = new List<FileSystemInfo>();
  563. var folder = resolveArgs.GetFileSystemEntryByName(TrailerFolderName);
  564. // Path doesn't exist. No biggie
  565. if (folder != null)
  566. {
  567. try
  568. {
  569. files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  570. }
  571. catch (IOException ex)
  572. {
  573. Logger.ErrorException("Error loading trailers for {0}", ex, Name);
  574. }
  575. }
  576. // Support xbmc trailers (-trailer suffix on video file names)
  577. files.AddRange(resolveArgs.FileSystemChildren.Where(i =>
  578. {
  579. try
  580. {
  581. if ((i.Attributes & FileAttributes.Directory) != FileAttributes.Directory)
  582. {
  583. if (System.IO.Path.GetFileNameWithoutExtension(i.Name).EndsWith(XbmcTrailerFileSuffix, StringComparison.OrdinalIgnoreCase) && !string.Equals(Path, i.FullName, StringComparison.OrdinalIgnoreCase))
  584. {
  585. return true;
  586. }
  587. }
  588. }
  589. catch (IOException ex)
  590. {
  591. Logger.ErrorException("Error accessing path {0}", ex, i.FullName);
  592. }
  593. return false;
  594. }));
  595. return LibraryManager.ResolvePaths<Trailer>(files, null).Select(video =>
  596. {
  597. // Try to retrieve it from the db. If we don't find it, use the resolved version
  598. var dbItem = LibraryManager.RetrieveItem(video.Id) as Trailer;
  599. if (dbItem != null)
  600. {
  601. dbItem.ResolveArgs = video.ResolveArgs;
  602. video = dbItem;
  603. }
  604. return video;
  605. }).ToList();
  606. }
  607. /// <summary>
  608. /// Loads the theme songs.
  609. /// </summary>
  610. /// <returns>List{Audio.Audio}.</returns>
  611. private IEnumerable<Audio.Audio> LoadThemeSongs()
  612. {
  613. ItemResolveArgs resolveArgs;
  614. try
  615. {
  616. resolveArgs = ResolveArgs;
  617. if (!resolveArgs.IsDirectory)
  618. {
  619. return new List<Audio.Audio>();
  620. }
  621. }
  622. catch (IOException ex)
  623. {
  624. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  625. return new List<Audio.Audio>();
  626. }
  627. var files = new List<FileSystemInfo>();
  628. var folder = resolveArgs.GetFileSystemEntryByName(ThemeSongsFolderName);
  629. // Path doesn't exist. No biggie
  630. if (folder != null)
  631. {
  632. try
  633. {
  634. files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  635. }
  636. catch (IOException ex)
  637. {
  638. Logger.ErrorException("Error loading theme songs for {0}", ex, Name);
  639. }
  640. }
  641. // Support plex/xbmc convention
  642. files.AddRange(resolveArgs.FileSystemChildren
  643. .Where(i => string.Equals(System.IO.Path.GetFileNameWithoutExtension(i.Name), ThemeSongFilename, StringComparison.OrdinalIgnoreCase) && EntityResolutionHelper.IsAudioFile(i.Name))
  644. );
  645. return LibraryManager.ResolvePaths<Audio.Audio>(files, null).Select(audio =>
  646. {
  647. // Try to retrieve it from the db. If we don't find it, use the resolved version
  648. var dbItem = LibraryManager.RetrieveItem(audio.Id) as Audio.Audio;
  649. if (dbItem != null)
  650. {
  651. dbItem.ResolveArgs = audio.ResolveArgs;
  652. audio = dbItem;
  653. }
  654. return audio;
  655. }).ToList();
  656. }
  657. /// <summary>
  658. /// Loads the video backdrops.
  659. /// </summary>
  660. /// <returns>List{Video}.</returns>
  661. private IEnumerable<Video> LoadThemeVideos()
  662. {
  663. ItemResolveArgs resolveArgs;
  664. try
  665. {
  666. resolveArgs = ResolveArgs;
  667. if (!resolveArgs.IsDirectory)
  668. {
  669. return new List<Video>();
  670. }
  671. }
  672. catch (IOException ex)
  673. {
  674. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  675. return new List<Video>();
  676. }
  677. var folder = resolveArgs.GetFileSystemEntryByName(ThemeVideosFolderName);
  678. // Path doesn't exist. No biggie
  679. if (folder == null)
  680. {
  681. return new List<Video>();
  682. }
  683. IEnumerable<FileSystemInfo> files;
  684. try
  685. {
  686. files = new DirectoryInfo(folder.FullName).EnumerateFiles();
  687. }
  688. catch (IOException ex)
  689. {
  690. Logger.ErrorException("Error loading video backdrops for {0}", ex, Name);
  691. return new List<Video>();
  692. }
  693. return LibraryManager.ResolvePaths<Video>(files, null).Select(item =>
  694. {
  695. // Try to retrieve it from the db. If we don't find it, use the resolved version
  696. var dbItem = LibraryManager.RetrieveItem(item.Id) as Video;
  697. if (dbItem != null)
  698. {
  699. dbItem.ResolveArgs = item.ResolveArgs;
  700. item = dbItem;
  701. }
  702. return item;
  703. }).ToList();
  704. }
  705. /// <summary>
  706. /// Overrides the base implementation to refresh metadata for local trailers
  707. /// </summary>
  708. /// <param name="cancellationToken">The cancellation token.</param>
  709. /// <param name="forceSave">if set to <c>true</c> [is new item].</param>
  710. /// <param name="forceRefresh">if set to <c>true</c> [force].</param>
  711. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  712. /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param>
  713. /// <returns>true if a provider reports we changed</returns>
  714. public virtual async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  715. {
  716. if (resetResolveArgs)
  717. {
  718. // Reload this
  719. ResolveArgs = null;
  720. }
  721. // Refresh for the item
  722. var itemRefreshTask = ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh, allowSlowProviders);
  723. cancellationToken.ThrowIfCancellationRequested();
  724. var themeSongsChanged = false;
  725. var themeVideosChanged = false;
  726. var localTrailersChanged = false;
  727. if (LocationType == LocationType.FileSystem && Parent != null)
  728. {
  729. themeSongsChanged = await RefreshThemeSongs(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  730. themeVideosChanged = await RefreshThemeVideos(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  731. localTrailersChanged = await RefreshLocalTrailers(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  732. }
  733. cancellationToken.ThrowIfCancellationRequested();
  734. // Get the result from the item task
  735. var updateReason = await itemRefreshTask.ConfigureAwait(false);
  736. var changed = updateReason.HasValue;
  737. if (changed || forceSave || themeSongsChanged || themeVideosChanged || localTrailersChanged)
  738. {
  739. cancellationToken.ThrowIfCancellationRequested();
  740. await LibraryManager.UpdateItem(this, updateReason ?? ItemUpdateType.Unspecified, cancellationToken).ConfigureAwait(false);
  741. }
  742. return changed;
  743. }
  744. private async Task<bool> RefreshLocalTrailers(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  745. {
  746. var newItems = LoadLocalTrailers().ToList();
  747. var newItemIds = newItems.Select(i => i.Id).ToList();
  748. var itemsChanged = !LocalTrailerIds.SequenceEqual(newItemIds);
  749. var tasks = newItems.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  750. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  751. LocalTrailerIds = newItemIds;
  752. return itemsChanged || results.Contains(true);
  753. }
  754. private async Task<bool> RefreshThemeVideos(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  755. {
  756. var newThemeVideos = LoadThemeVideos().ToList();
  757. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  758. var themeVideosChanged = !ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  759. var tasks = newThemeVideos.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  760. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  761. ThemeVideoIds = newThemeVideoIds;
  762. return themeVideosChanged || results.Contains(true);
  763. }
  764. /// <summary>
  765. /// Refreshes the theme songs.
  766. /// </summary>
  767. private async Task<bool> RefreshThemeSongs(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  768. {
  769. var newThemeSongs = LoadThemeSongs().ToList();
  770. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  771. var themeSongsChanged = !ThemeSongIds.SequenceEqual(newThemeSongIds);
  772. var tasks = newThemeSongs.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  773. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  774. ThemeSongIds = newThemeSongIds;
  775. return themeSongsChanged || results.Contains(true);
  776. }
  777. /// <summary>
  778. /// Gets or sets the trailer URL.
  779. /// </summary>
  780. /// <value>The trailer URL.</value>
  781. public List<MediaUrl> RemoteTrailers { get; set; }
  782. /// <summary>
  783. /// Gets or sets the provider ids.
  784. /// </summary>
  785. /// <value>The provider ids.</value>
  786. public Dictionary<string, string> ProviderIds { get; set; }
  787. /// <summary>
  788. /// Override this to false if class should be ignored for indexing purposes
  789. /// </summary>
  790. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  791. [IgnoreDataMember]
  792. public virtual bool IncludeInIndex
  793. {
  794. get { return true; }
  795. }
  796. /// <summary>
  797. /// Override this to true if class should be grouped under a container in indicies
  798. /// The container class should be defined via IndexContainer
  799. /// </summary>
  800. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  801. [IgnoreDataMember]
  802. public virtual bool GroupInIndex
  803. {
  804. get { return false; }
  805. }
  806. /// <summary>
  807. /// Override this to return the folder that should be used to construct a container
  808. /// for this item in an index. GroupInIndex should be true as well.
  809. /// </summary>
  810. /// <value>The index container.</value>
  811. [IgnoreDataMember]
  812. public virtual Folder IndexContainer
  813. {
  814. get { return null; }
  815. }
  816. /// <summary>
  817. /// Gets the user data key.
  818. /// </summary>
  819. /// <returns>System.String.</returns>
  820. public virtual string GetUserDataKey()
  821. {
  822. return Id.ToString();
  823. }
  824. /// <summary>
  825. /// Determines if a given user has access to this item
  826. /// </summary>
  827. /// <param name="user">The user.</param>
  828. /// <param name="localizationManager">The localization manager.</param>
  829. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  830. /// <exception cref="System.ArgumentNullException">user</exception>
  831. public bool IsParentalAllowed(User user, ILocalizationManager localizationManager)
  832. {
  833. if (user == null)
  834. {
  835. throw new ArgumentNullException("user");
  836. }
  837. if (user.Configuration.MaxParentalRating == null)
  838. {
  839. return true;
  840. }
  841. var rating = CustomRating;
  842. if (string.IsNullOrEmpty(rating))
  843. {
  844. rating = OfficialRating;
  845. }
  846. if (string.IsNullOrEmpty(rating))
  847. {
  848. return !user.Configuration.BlockNotRated;
  849. }
  850. var value = localizationManager.GetRatingLevel(rating);
  851. // Could not determine the integer value
  852. if (!value.HasValue)
  853. {
  854. return true;
  855. }
  856. return value.Value <= user.Configuration.MaxParentalRating.Value;
  857. }
  858. /// <summary>
  859. /// Determines if this folder should be visible to a given user.
  860. /// Default is just parental allowed. Can be overridden for more functionality.
  861. /// </summary>
  862. /// <param name="user">The user.</param>
  863. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  864. /// <exception cref="System.ArgumentNullException">user</exception>
  865. public virtual bool IsVisible(User user)
  866. {
  867. if (user == null)
  868. {
  869. throw new ArgumentNullException("user");
  870. }
  871. return IsParentalAllowed(user, LocalizationManager);
  872. }
  873. /// <summary>
  874. /// Finds the particular item by searching through our parents and, if not found there, loading from repo
  875. /// </summary>
  876. /// <param name="id">The id.</param>
  877. /// <returns>BaseItem.</returns>
  878. /// <exception cref="System.ArgumentException"></exception>
  879. protected BaseItem FindParentItem(Guid id)
  880. {
  881. if (id == Guid.Empty)
  882. {
  883. throw new ArgumentException();
  884. }
  885. var parent = Parent;
  886. while (parent != null && !parent.IsRoot)
  887. {
  888. if (parent.Id == id) return parent;
  889. parent = parent.Parent;
  890. }
  891. return null;
  892. }
  893. /// <summary>
  894. /// Gets a value indicating whether this instance is folder.
  895. /// </summary>
  896. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  897. [IgnoreDataMember]
  898. public virtual bool IsFolder
  899. {
  900. get
  901. {
  902. return false;
  903. }
  904. }
  905. /// <summary>
  906. /// Determine if we have changed vs the passed in copy
  907. /// </summary>
  908. /// <param name="copy">The copy.</param>
  909. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  910. /// <exception cref="System.ArgumentNullException"></exception>
  911. public virtual bool HasChanged(BaseItem copy)
  912. {
  913. if (copy == null)
  914. {
  915. throw new ArgumentNullException();
  916. }
  917. var changed = copy.DateModified != DateModified;
  918. if (changed)
  919. {
  920. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  921. }
  922. return changed;
  923. }
  924. /// <summary>
  925. /// Determines if the item is considered new based on user settings
  926. /// </summary>
  927. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  928. /// <exception cref="System.ArgumentNullException"></exception>
  929. public bool IsRecentlyAdded()
  930. {
  931. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  932. }
  933. /// <summary>
  934. /// Adds a person to the item
  935. /// </summary>
  936. /// <param name="person">The person.</param>
  937. /// <exception cref="System.ArgumentNullException"></exception>
  938. public void AddPerson(PersonInfo person)
  939. {
  940. if (person == null)
  941. {
  942. throw new ArgumentNullException("person");
  943. }
  944. if (string.IsNullOrWhiteSpace(person.Name))
  945. {
  946. throw new ArgumentNullException();
  947. }
  948. // Normalize
  949. if (string.Equals(person.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  950. {
  951. person.Type = PersonType.GuestStar;
  952. }
  953. else if (string.Equals(person.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
  954. {
  955. person.Type = PersonType.Director;
  956. }
  957. else if (string.Equals(person.Role, PersonType.Producer, StringComparison.OrdinalIgnoreCase))
  958. {
  959. person.Type = PersonType.Producer;
  960. }
  961. else if (string.Equals(person.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
  962. {
  963. person.Type = PersonType.Writer;
  964. }
  965. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  966. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  967. {
  968. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  969. if (existing != null)
  970. {
  971. existing.Type = PersonType.GuestStar;
  972. return;
  973. }
  974. }
  975. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  976. {
  977. // If the actor already exists without a role and we have one, fill it in
  978. 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)));
  979. if (existing == null)
  980. {
  981. // Wasn't there - add it
  982. People.Add(person);
  983. }
  984. else
  985. {
  986. // Was there, if no role and we have one - fill it in
  987. if (string.IsNullOrWhiteSpace(existing.Role) && !string.IsNullOrWhiteSpace(person.Role)) existing.Role = person.Role;
  988. }
  989. }
  990. else
  991. {
  992. // Check for dupes based on the combination of Name and Type
  993. if (!People.Any(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(person.Type, StringComparison.OrdinalIgnoreCase)))
  994. {
  995. People.Add(person);
  996. }
  997. }
  998. }
  999. /// <summary>
  1000. /// Adds a studio to the item
  1001. /// </summary>
  1002. /// <param name="name">The name.</param>
  1003. /// <exception cref="System.ArgumentNullException"></exception>
  1004. public void AddStudio(string name)
  1005. {
  1006. if (string.IsNullOrWhiteSpace(name))
  1007. {
  1008. throw new ArgumentNullException("name");
  1009. }
  1010. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1011. {
  1012. Studios.Add(name);
  1013. }
  1014. }
  1015. public void AddTag(string name)
  1016. {
  1017. if (string.IsNullOrWhiteSpace(name))
  1018. {
  1019. throw new ArgumentNullException("name");
  1020. }
  1021. if (!Tags.Contains(name, StringComparer.OrdinalIgnoreCase))
  1022. {
  1023. Tags.Add(name);
  1024. }
  1025. }
  1026. /// <summary>
  1027. /// Adds a tagline to the item
  1028. /// </summary>
  1029. /// <param name="name">The name.</param>
  1030. /// <exception cref="System.ArgumentNullException"></exception>
  1031. public void AddTagline(string name)
  1032. {
  1033. if (string.IsNullOrWhiteSpace(name))
  1034. {
  1035. throw new ArgumentNullException("name");
  1036. }
  1037. if (!Taglines.Contains(name, StringComparer.OrdinalIgnoreCase))
  1038. {
  1039. Taglines.Add(name);
  1040. }
  1041. }
  1042. /// <summary>
  1043. /// Adds a TrailerUrl to the item
  1044. /// </summary>
  1045. /// <param name="url">The URL.</param>
  1046. /// <param name="isDirectLink">if set to <c>true</c> [is direct link].</param>
  1047. /// <exception cref="System.ArgumentNullException">url</exception>
  1048. public void AddTrailerUrl(string url, bool isDirectLink)
  1049. {
  1050. if (string.IsNullOrWhiteSpace(url))
  1051. {
  1052. throw new ArgumentNullException("url");
  1053. }
  1054. var current = RemoteTrailers.FirstOrDefault(i => string.Equals(i.Url, url, StringComparison.OrdinalIgnoreCase));
  1055. if (current != null)
  1056. {
  1057. current.IsDirectLink = isDirectLink;
  1058. }
  1059. else
  1060. {
  1061. RemoteTrailers.Add(new MediaUrl
  1062. {
  1063. Url = url,
  1064. IsDirectLink = isDirectLink
  1065. });
  1066. }
  1067. }
  1068. /// <summary>
  1069. /// Adds a genre to the item
  1070. /// </summary>
  1071. /// <param name="name">The name.</param>
  1072. /// <exception cref="System.ArgumentNullException"></exception>
  1073. public void AddGenre(string name)
  1074. {
  1075. if (string.IsNullOrWhiteSpace(name))
  1076. {
  1077. throw new ArgumentNullException("name");
  1078. }
  1079. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1080. {
  1081. Genres.Add(name);
  1082. }
  1083. }
  1084. /// <summary>
  1085. /// Adds the production location.
  1086. /// </summary>
  1087. /// <param name="location">The location.</param>
  1088. /// <exception cref="System.ArgumentNullException">location</exception>
  1089. public void AddProductionLocation(string location)
  1090. {
  1091. if (string.IsNullOrWhiteSpace(location))
  1092. {
  1093. throw new ArgumentNullException("location");
  1094. }
  1095. if (ProductionLocations == null)
  1096. {
  1097. ProductionLocations = new List<string>();
  1098. }
  1099. if (!ProductionLocations.Contains(location, StringComparer.OrdinalIgnoreCase))
  1100. {
  1101. ProductionLocations.Add(location);
  1102. }
  1103. }
  1104. /// <summary>
  1105. /// Marks the item as either played or unplayed
  1106. /// </summary>
  1107. /// <param name="user">The user.</param>
  1108. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  1109. /// <param name="userManager">The user manager.</param>
  1110. /// <returns>Task.</returns>
  1111. /// <exception cref="System.ArgumentNullException"></exception>
  1112. public virtual async Task SetPlayedStatus(User user, bool wasPlayed, IUserDataRepository userManager)
  1113. {
  1114. if (user == null)
  1115. {
  1116. throw new ArgumentNullException();
  1117. }
  1118. var key = GetUserDataKey();
  1119. var data = userManager.GetUserData(user.Id, key);
  1120. if (wasPlayed)
  1121. {
  1122. data.PlayCount = Math.Max(data.PlayCount, 1);
  1123. if (!data.LastPlayedDate.HasValue)
  1124. {
  1125. data.LastPlayedDate = DateTime.UtcNow;
  1126. }
  1127. }
  1128. else
  1129. {
  1130. //I think it is okay to do this here.
  1131. // if this is only called when a user is manually forcing something to un-played
  1132. // then it probably is what we want to do...
  1133. data.PlayCount = 0;
  1134. data.PlaybackPositionTicks = 0;
  1135. data.LastPlayedDate = null;
  1136. }
  1137. data.Played = wasPlayed;
  1138. await userManager.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  1139. }
  1140. /// <summary>
  1141. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1142. /// </summary>
  1143. /// <returns>Task.</returns>
  1144. public virtual Task ChangedExternally()
  1145. {
  1146. return RefreshMetadata(CancellationToken.None);
  1147. }
  1148. /// <summary>
  1149. /// Finds a parent of a given type
  1150. /// </summary>
  1151. /// <typeparam name="T"></typeparam>
  1152. /// <returns>``0.</returns>
  1153. public T FindParent<T>()
  1154. where T : Folder
  1155. {
  1156. var parent = Parent;
  1157. while (parent != null)
  1158. {
  1159. var result = parent as T;
  1160. if (result != null)
  1161. {
  1162. return result;
  1163. }
  1164. parent = parent.Parent;
  1165. }
  1166. return null;
  1167. }
  1168. /// <summary>
  1169. /// Gets an image
  1170. /// </summary>
  1171. /// <param name="type">The type.</param>
  1172. /// <returns>System.String.</returns>
  1173. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1174. public string GetImage(ImageType type)
  1175. {
  1176. if (type == ImageType.Backdrop)
  1177. {
  1178. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1179. }
  1180. if (type == ImageType.Screenshot)
  1181. {
  1182. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1183. }
  1184. string val;
  1185. Images.TryGetValue(type, out val);
  1186. return val;
  1187. }
  1188. /// <summary>
  1189. /// Gets an image
  1190. /// </summary>
  1191. /// <param name="type">The type.</param>
  1192. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1193. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1194. public bool HasImage(ImageType type)
  1195. {
  1196. if (type == ImageType.Backdrop)
  1197. {
  1198. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1199. }
  1200. if (type == ImageType.Screenshot)
  1201. {
  1202. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1203. }
  1204. return !string.IsNullOrEmpty(GetImage(type));
  1205. }
  1206. /// <summary>
  1207. /// Sets an image
  1208. /// </summary>
  1209. /// <param name="type">The type.</param>
  1210. /// <param name="path">The path.</param>
  1211. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1212. public void SetImage(ImageType type, string path)
  1213. {
  1214. if (type == ImageType.Backdrop)
  1215. {
  1216. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1217. }
  1218. if (type == ImageType.Screenshot)
  1219. {
  1220. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1221. }
  1222. var typeKey = type;
  1223. // If it's null remove the key from the dictionary
  1224. if (string.IsNullOrEmpty(path))
  1225. {
  1226. if (Images.ContainsKey(typeKey))
  1227. {
  1228. Images.Remove(typeKey);
  1229. }
  1230. }
  1231. else
  1232. {
  1233. Images[typeKey] = path;
  1234. }
  1235. }
  1236. /// <summary>
  1237. /// Deletes the image.
  1238. /// </summary>
  1239. /// <param name="type">The type.</param>
  1240. /// <param name="index">The index.</param>
  1241. /// <returns>Task.</returns>
  1242. public Task DeleteImage(ImageType type, int? index)
  1243. {
  1244. if (type == ImageType.Backdrop)
  1245. {
  1246. if (!index.HasValue)
  1247. {
  1248. throw new ArgumentException("Please specify a backdrop image index to delete.");
  1249. }
  1250. var file = BackdropImagePaths[index.Value];
  1251. BackdropImagePaths.Remove(file);
  1252. // Delete the source file
  1253. File.Delete(file);
  1254. }
  1255. else if (type == ImageType.Screenshot)
  1256. {
  1257. if (!index.HasValue)
  1258. {
  1259. throw new ArgumentException("Please specify a screenshot image index to delete.");
  1260. }
  1261. var file = ScreenshotImagePaths[index.Value];
  1262. ScreenshotImagePaths.Remove(file);
  1263. // Delete the source file
  1264. File.Delete(file);
  1265. }
  1266. else
  1267. {
  1268. // Delete the source file
  1269. File.Delete(GetImage(type));
  1270. // Remove it from the item
  1271. SetImage(type, null);
  1272. }
  1273. // Refresh metadata
  1274. return RefreshMetadata(CancellationToken.None, forceSave: true);
  1275. }
  1276. }
  1277. }