BaseItem.cs 53 KB

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