BaseItem.cs 57 KB

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