BaseItem.cs 51 KB

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