BaseItem.cs 58 KB

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