BaseItem.cs 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664
  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. args.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 = args.FileSystemDictionary.Keys.ToList();
  294. foreach (var subPath in paths
  295. .Where(subPath => !subPath.EndsWith(":\\", StringComparison.OrdinalIgnoreCase) && paths.Any(i => subPath.StartsWith(i.TrimEnd(System.IO.Path.DirectorySeparatorChar) + System.IO.Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))))
  296. {
  297. Logger.Info("Ignoring duplicate path: {0}", subPath);
  298. args.FileSystemDictionary.Remove(subPath);
  299. }
  300. }
  301. }
  302. //update our dates
  303. EntityResolutionHelper.EnsureDates(FileSystem, this, args, false);
  304. IsOffline = false;
  305. return args;
  306. }
  307. /// <summary>
  308. /// 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
  309. /// original ones.
  310. /// </summary>
  311. /// <value><c>true</c> if [use parent path to create resolve args]; otherwise, <c>false</c>.</value>
  312. [IgnoreDataMember]
  313. protected virtual bool UseParentPathToCreateResolveArgs
  314. {
  315. get
  316. {
  317. return false;
  318. }
  319. }
  320. /// <summary>
  321. /// Gets or sets the name of the forced sort.
  322. /// </summary>
  323. /// <value>The name of the forced sort.</value>
  324. public string ForcedSortName { get; set; }
  325. private string _sortName;
  326. /// <summary>
  327. /// Gets or sets the name of the sort.
  328. /// </summary>
  329. /// <value>The name of the sort.</value>
  330. [IgnoreDataMember]
  331. public string SortName
  332. {
  333. get
  334. {
  335. if (!string.IsNullOrEmpty(ForcedSortName))
  336. {
  337. return ForcedSortName;
  338. }
  339. return _sortName ?? (_sortName = CreateSortName());
  340. }
  341. }
  342. /// <summary>
  343. /// Creates the name of the sort.
  344. /// </summary>
  345. /// <returns>System.String.</returns>
  346. protected virtual string CreateSortName()
  347. {
  348. if (Name == null) return null; //some items may not have name filled in properly
  349. var sortable = Name.Trim().ToLower();
  350. sortable = ConfigurationManager.Configuration.SortRemoveCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), string.Empty));
  351. sortable = ConfigurationManager.Configuration.SortReplaceCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), " "));
  352. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  353. {
  354. var searchLower = search.ToLower();
  355. // Remove from beginning if a space follows
  356. if (sortable.StartsWith(searchLower + " "))
  357. {
  358. sortable = sortable.Remove(0, searchLower.Length + 1);
  359. }
  360. // Remove from middle if surrounded by spaces
  361. sortable = sortable.Replace(" " + searchLower + " ", " ");
  362. // Remove from end if followed by a space
  363. if (sortable.EndsWith(" " + searchLower))
  364. {
  365. sortable = sortable.Remove(sortable.Length - (searchLower.Length + 1));
  366. }
  367. }
  368. return sortable;
  369. }
  370. /// <summary>
  371. /// Gets or sets the parent.
  372. /// </summary>
  373. /// <value>The parent.</value>
  374. [IgnoreDataMember]
  375. public Folder Parent { get; set; }
  376. [IgnoreDataMember]
  377. public IEnumerable<Folder> Parents
  378. {
  379. get
  380. {
  381. var parent = Parent;
  382. while (parent != null)
  383. {
  384. yield return parent;
  385. parent = parent.Parent;
  386. }
  387. }
  388. }
  389. /// <summary>
  390. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  391. /// </summary>
  392. /// <value>The premiere date.</value>
  393. public DateTime? PremiereDate { get; set; }
  394. /// <summary>
  395. /// Gets or sets the end date.
  396. /// </summary>
  397. /// <value>The end date.</value>
  398. public DateTime? EndDate { get; set; }
  399. /// <summary>
  400. /// Gets or sets the display type of the media.
  401. /// </summary>
  402. /// <value>The display type of the media.</value>
  403. public string DisplayMediaType { get; set; }
  404. /// <summary>
  405. /// Gets or sets the backdrop image paths.
  406. /// </summary>
  407. /// <value>The backdrop image paths.</value>
  408. public List<string> BackdropImagePaths { get; set; }
  409. /// <summary>
  410. /// Gets or sets the backdrop image sources.
  411. /// </summary>
  412. /// <value>The backdrop image sources.</value>
  413. public List<ImageSourceInfo> ImageSources { get; set; }
  414. /// <summary>
  415. /// Gets or sets the official rating.
  416. /// </summary>
  417. /// <value>The official rating.</value>
  418. public string OfficialRating { get; set; }
  419. /// <summary>
  420. /// Gets or sets the official rating description.
  421. /// </summary>
  422. /// <value>The official rating description.</value>
  423. public string OfficialRatingDescription { get; set; }
  424. /// <summary>
  425. /// Gets or sets the custom rating.
  426. /// </summary>
  427. /// <value>The custom rating.</value>
  428. public string CustomRating { get; set; }
  429. /// <summary>
  430. /// Gets or sets the overview.
  431. /// </summary>
  432. /// <value>The overview.</value>
  433. public string Overview { get; set; }
  434. /// <summary>
  435. /// Gets or sets the people.
  436. /// </summary>
  437. /// <value>The people.</value>
  438. public List<PersonInfo> People { get; set; }
  439. /// <summary>
  440. /// Override this if you need to combine/collapse person information
  441. /// </summary>
  442. /// <value>All people.</value>
  443. [IgnoreDataMember]
  444. public virtual IEnumerable<PersonInfo> AllPeople
  445. {
  446. get { return People; }
  447. }
  448. [IgnoreDataMember]
  449. public virtual IEnumerable<string> AllStudios
  450. {
  451. get { return Studios; }
  452. }
  453. [IgnoreDataMember]
  454. public virtual IEnumerable<string> AllGenres
  455. {
  456. get { return Genres; }
  457. }
  458. /// <summary>
  459. /// Gets or sets the studios.
  460. /// </summary>
  461. /// <value>The studios.</value>
  462. public List<string> Studios { get; set; }
  463. /// <summary>
  464. /// Gets or sets the genres.
  465. /// </summary>
  466. /// <value>The genres.</value>
  467. public List<string> Genres { get; set; }
  468. /// <summary>
  469. /// Gets or sets the home page URL.
  470. /// </summary>
  471. /// <value>The home page URL.</value>
  472. public string HomePageUrl { get; set; }
  473. /// <summary>
  474. /// Gets or sets the community rating.
  475. /// </summary>
  476. /// <value>The community rating.</value>
  477. public float? CommunityRating { get; set; }
  478. /// <summary>
  479. /// Gets or sets the community rating vote count.
  480. /// </summary>
  481. /// <value>The community rating vote count.</value>
  482. public int? VoteCount { get; set; }
  483. /// <summary>
  484. /// Gets or sets the run time ticks.
  485. /// </summary>
  486. /// <value>The run time ticks.</value>
  487. public long? RunTimeTicks { get; set; }
  488. /// <summary>
  489. /// Gets or sets the original run time ticks.
  490. /// </summary>
  491. /// <value>The original run time ticks.</value>
  492. public long? OriginalRunTimeTicks { get; set; }
  493. /// <summary>
  494. /// Gets or sets the production year.
  495. /// </summary>
  496. /// <value>The production year.</value>
  497. public int? ProductionYear { get; set; }
  498. /// <summary>
  499. /// If the item is part of a series, this is it's number in the series.
  500. /// This could be episode number, album track number, etc.
  501. /// </summary>
  502. /// <value>The index number.</value>
  503. public int? IndexNumber { get; set; }
  504. /// <summary>
  505. /// For an episode this could be the season number, or for a song this could be the disc number.
  506. /// </summary>
  507. /// <value>The parent index number.</value>
  508. public int? ParentIndexNumber { get; set; }
  509. [IgnoreDataMember]
  510. public virtual string OfficialRatingForComparison
  511. {
  512. get { return OfficialRating; }
  513. }
  514. [IgnoreDataMember]
  515. public virtual string CustomRatingForComparison
  516. {
  517. get { return CustomRating; }
  518. }
  519. /// <summary>
  520. /// Loads local trailers from the file system
  521. /// </summary>
  522. /// <returns>List{Video}.</returns>
  523. private IEnumerable<Trailer> LoadLocalTrailers()
  524. {
  525. ItemResolveArgs resolveArgs;
  526. try
  527. {
  528. resolveArgs = ResolveArgs;
  529. if (!resolveArgs.IsDirectory)
  530. {
  531. return new List<Trailer>();
  532. }
  533. }
  534. catch (IOException ex)
  535. {
  536. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  537. return new List<Trailer>();
  538. }
  539. var files = new List<FileSystemInfo>();
  540. var folder = resolveArgs.GetFileSystemEntryByName(TrailerFolderName);
  541. // Path doesn't exist. No biggie
  542. if (folder != null)
  543. {
  544. try
  545. {
  546. files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  547. }
  548. catch (IOException ex)
  549. {
  550. Logger.ErrorException("Error loading trailers for {0}", ex, Name);
  551. }
  552. }
  553. // Support xbmc trailers (-trailer suffix on video file names)
  554. files.AddRange(resolveArgs.FileSystemChildren.Where(i =>
  555. {
  556. try
  557. {
  558. if ((i.Attributes & FileAttributes.Directory) != FileAttributes.Directory)
  559. {
  560. if (System.IO.Path.GetFileNameWithoutExtension(i.Name).EndsWith(XbmcTrailerFileSuffix, StringComparison.OrdinalIgnoreCase) && !string.Equals(Path, i.FullName, StringComparison.OrdinalIgnoreCase))
  561. {
  562. return true;
  563. }
  564. }
  565. }
  566. catch (IOException ex)
  567. {
  568. Logger.ErrorException("Error accessing path {0}", ex, i.FullName);
  569. }
  570. return false;
  571. }));
  572. return LibraryManager.ResolvePaths<Trailer>(files, null).Select(video =>
  573. {
  574. // Try to retrieve it from the db. If we don't find it, use the resolved version
  575. var dbItem = LibraryManager.RetrieveItem(video.Id) as Trailer;
  576. if (dbItem != null)
  577. {
  578. dbItem.ResetResolveArgs(video.ResolveArgs);
  579. video = dbItem;
  580. }
  581. return video;
  582. }).ToList();
  583. }
  584. /// <summary>
  585. /// Loads the theme songs.
  586. /// </summary>
  587. /// <returns>List{Audio.Audio}.</returns>
  588. private IEnumerable<Audio.Audio> LoadThemeSongs()
  589. {
  590. ItemResolveArgs resolveArgs;
  591. try
  592. {
  593. resolveArgs = ResolveArgs;
  594. if (!resolveArgs.IsDirectory)
  595. {
  596. return new List<Audio.Audio>();
  597. }
  598. }
  599. catch (IOException ex)
  600. {
  601. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  602. return new List<Audio.Audio>();
  603. }
  604. var files = new List<FileSystemInfo>();
  605. var folder = resolveArgs.GetFileSystemEntryByName(ThemeSongsFolderName);
  606. // Path doesn't exist. No biggie
  607. if (folder != null)
  608. {
  609. try
  610. {
  611. files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  612. }
  613. catch (IOException ex)
  614. {
  615. Logger.ErrorException("Error loading theme songs for {0}", ex, Name);
  616. }
  617. }
  618. // Support plex/xbmc convention
  619. files.AddRange(resolveArgs.FileSystemChildren
  620. .Where(i => string.Equals(System.IO.Path.GetFileNameWithoutExtension(i.Name), ThemeSongFilename, StringComparison.OrdinalIgnoreCase) && EntityResolutionHelper.IsAudioFile(i.Name))
  621. );
  622. return LibraryManager.ResolvePaths<Audio.Audio>(files, null).Select(audio =>
  623. {
  624. // Try to retrieve it from the db. If we don't find it, use the resolved version
  625. var dbItem = LibraryManager.RetrieveItem(audio.Id) as Audio.Audio;
  626. if (dbItem != null)
  627. {
  628. dbItem.ResetResolveArgs(audio.ResolveArgs);
  629. audio = dbItem;
  630. }
  631. return audio;
  632. }).ToList();
  633. }
  634. /// <summary>
  635. /// Loads the video backdrops.
  636. /// </summary>
  637. /// <returns>List{Video}.</returns>
  638. private IEnumerable<Video> LoadThemeVideos()
  639. {
  640. ItemResolveArgs resolveArgs;
  641. try
  642. {
  643. resolveArgs = ResolveArgs;
  644. if (!resolveArgs.IsDirectory)
  645. {
  646. return new List<Video>();
  647. }
  648. }
  649. catch (IOException ex)
  650. {
  651. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  652. return new List<Video>();
  653. }
  654. var folder = resolveArgs.GetFileSystemEntryByName(ThemeVideosFolderName);
  655. // Path doesn't exist. No biggie
  656. if (folder == null)
  657. {
  658. return new List<Video>();
  659. }
  660. IEnumerable<FileSystemInfo> files;
  661. try
  662. {
  663. files = new DirectoryInfo(folder.FullName).EnumerateFiles();
  664. }
  665. catch (IOException ex)
  666. {
  667. Logger.ErrorException("Error loading video backdrops for {0}", ex, Name);
  668. return new List<Video>();
  669. }
  670. return LibraryManager.ResolvePaths<Video>(files, null).Select(item =>
  671. {
  672. // Try to retrieve it from the db. If we don't find it, use the resolved version
  673. var dbItem = LibraryManager.RetrieveItem(item.Id) as Video;
  674. if (dbItem != null)
  675. {
  676. dbItem.ResetResolveArgs(item.ResolveArgs);
  677. item = dbItem;
  678. }
  679. return item;
  680. }).ToList();
  681. }
  682. /// <summary>
  683. /// Overrides the base implementation to refresh metadata for local trailers
  684. /// </summary>
  685. /// <param name="cancellationToken">The cancellation token.</param>
  686. /// <param name="forceSave">if set to <c>true</c> [is new item].</param>
  687. /// <param name="forceRefresh">if set to <c>true</c> [force].</param>
  688. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  689. /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param>
  690. /// <returns>true if a provider reports we changed</returns>
  691. public virtual async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  692. {
  693. if (resetResolveArgs)
  694. {
  695. // Reload this
  696. ResetResolveArgs();
  697. }
  698. // Refresh for the item
  699. var itemRefreshTask = ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh, allowSlowProviders);
  700. cancellationToken.ThrowIfCancellationRequested();
  701. var themeSongsChanged = false;
  702. var themeVideosChanged = false;
  703. var localTrailersChanged = false;
  704. if (LocationType == LocationType.FileSystem && Parent != null)
  705. {
  706. var hasThemeMedia = this as IHasThemeMedia;
  707. if (hasThemeMedia != null)
  708. {
  709. themeSongsChanged = await RefreshThemeSongs(hasThemeMedia, cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  710. themeVideosChanged = await RefreshThemeVideos(hasThemeMedia, cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  711. }
  712. var hasTrailers = this as IHasTrailers;
  713. if (hasTrailers != null)
  714. {
  715. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  716. }
  717. }
  718. cancellationToken.ThrowIfCancellationRequested();
  719. // Get the result from the item task
  720. var updateReason = await itemRefreshTask.ConfigureAwait(false);
  721. var changed = updateReason.HasValue;
  722. if (changed || forceSave || themeSongsChanged || themeVideosChanged || localTrailersChanged)
  723. {
  724. cancellationToken.ThrowIfCancellationRequested();
  725. await LibraryManager.UpdateItem(this, updateReason ?? ItemUpdateType.Unspecified, cancellationToken).ConfigureAwait(false);
  726. }
  727. return changed;
  728. }
  729. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  730. {
  731. var newItems = LoadLocalTrailers().ToList();
  732. var newItemIds = newItems.Select(i => i.Id).ToList();
  733. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  734. var tasks = newItems.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
  735. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  736. item.LocalTrailerIds = newItemIds;
  737. return itemsChanged || results.Contains(true);
  738. }
  739. private async Task<bool> RefreshThemeVideos(IHasThemeMedia item, CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  740. {
  741. var newThemeVideos = LoadThemeVideos().ToList();
  742. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  743. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  744. var tasks = newThemeVideos.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
  745. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  746. item.ThemeVideoIds = newThemeVideoIds;
  747. return themeVideosChanged || results.Contains(true);
  748. }
  749. /// <summary>
  750. /// Refreshes the theme songs.
  751. /// </summary>
  752. private async Task<bool> RefreshThemeSongs(IHasThemeMedia item, CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  753. {
  754. var newThemeSongs = LoadThemeSongs().ToList();
  755. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  756. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  757. var tasks = newThemeSongs.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
  758. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  759. item.ThemeSongIds = newThemeSongIds;
  760. return themeSongsChanged || results.Contains(true);
  761. }
  762. /// <summary>
  763. /// Gets or sets the provider ids.
  764. /// </summary>
  765. /// <value>The provider ids.</value>
  766. public Dictionary<string, string> ProviderIds { get; set; }
  767. /// <summary>
  768. /// Override this to false if class should be ignored for indexing purposes
  769. /// </summary>
  770. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  771. [IgnoreDataMember]
  772. public virtual bool IncludeInIndex
  773. {
  774. get { return true; }
  775. }
  776. /// <summary>
  777. /// Override this to true if class should be grouped under a container in indicies
  778. /// The container class should be defined via IndexContainer
  779. /// </summary>
  780. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  781. [IgnoreDataMember]
  782. public virtual bool GroupInIndex
  783. {
  784. get { return false; }
  785. }
  786. /// <summary>
  787. /// Override this to return the folder that should be used to construct a container
  788. /// for this item in an index. GroupInIndex should be true as well.
  789. /// </summary>
  790. /// <value>The index container.</value>
  791. [IgnoreDataMember]
  792. public virtual Folder IndexContainer
  793. {
  794. get { return null; }
  795. }
  796. /// <summary>
  797. /// Gets the user data key.
  798. /// </summary>
  799. /// <returns>System.String.</returns>
  800. public virtual string GetUserDataKey()
  801. {
  802. return Id.ToString();
  803. }
  804. /// <summary>
  805. /// Determines if a given user has access to this item
  806. /// </summary>
  807. /// <param name="user">The user.</param>
  808. /// <param name="localizationManager">The localization manager.</param>
  809. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  810. /// <exception cref="System.ArgumentNullException">user</exception>
  811. public bool IsParentalAllowed(User user, ILocalizationManager localizationManager)
  812. {
  813. if (user == null)
  814. {
  815. throw new ArgumentNullException("user");
  816. }
  817. var maxAllowedRating = user.Configuration.MaxParentalRating;
  818. if (maxAllowedRating == null)
  819. {
  820. return true;
  821. }
  822. var rating = CustomRatingForComparison;
  823. if (string.IsNullOrEmpty(rating))
  824. {
  825. rating = OfficialRatingForComparison;
  826. }
  827. if (string.IsNullOrEmpty(rating))
  828. {
  829. return !GetBlockUnratedValue(user.Configuration);
  830. }
  831. var value = localizationManager.GetRatingLevel(rating);
  832. // Could not determine the integer value
  833. if (!value.HasValue)
  834. {
  835. return true;
  836. }
  837. return value.Value <= maxAllowedRating.Value;
  838. }
  839. /// <summary>
  840. /// Gets the block unrated value.
  841. /// </summary>
  842. /// <param name="config">The configuration.</param>
  843. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  844. protected virtual bool GetBlockUnratedValue(UserConfiguration config)
  845. {
  846. return config.BlockNotRated;
  847. }
  848. /// <summary>
  849. /// Determines if this folder should be visible to a given user.
  850. /// Default is just parental allowed. Can be overridden for more functionality.
  851. /// </summary>
  852. /// <param name="user">The user.</param>
  853. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  854. /// <exception cref="System.ArgumentNullException">user</exception>
  855. public virtual bool IsVisible(User user)
  856. {
  857. if (user == null)
  858. {
  859. throw new ArgumentNullException("user");
  860. }
  861. return IsParentalAllowed(user, LocalizationManager);
  862. }
  863. /// <summary>
  864. /// Finds the particular item by searching through our parents and, if not found there, loading from repo
  865. /// </summary>
  866. /// <param name="id">The id.</param>
  867. /// <returns>BaseItem.</returns>
  868. /// <exception cref="System.ArgumentException"></exception>
  869. protected BaseItem FindParentItem(Guid id)
  870. {
  871. if (id == Guid.Empty)
  872. {
  873. throw new ArgumentException();
  874. }
  875. var parent = Parent;
  876. while (parent != null && !parent.IsRoot)
  877. {
  878. if (parent.Id == id) return parent;
  879. parent = parent.Parent;
  880. }
  881. return null;
  882. }
  883. /// <summary>
  884. /// Gets a value indicating whether this instance is folder.
  885. /// </summary>
  886. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  887. [IgnoreDataMember]
  888. public virtual bool IsFolder
  889. {
  890. get
  891. {
  892. return false;
  893. }
  894. }
  895. /// <summary>
  896. /// Determine if we have changed vs the passed in copy
  897. /// </summary>
  898. /// <param name="copy">The copy.</param>
  899. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  900. /// <exception cref="System.ArgumentNullException"></exception>
  901. public virtual bool HasChanged(BaseItem copy)
  902. {
  903. if (copy == null)
  904. {
  905. throw new ArgumentNullException();
  906. }
  907. var changed = copy.DateModified != DateModified;
  908. if (changed)
  909. {
  910. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  911. }
  912. return changed;
  913. }
  914. public virtual string GetClientTypeName()
  915. {
  916. return GetType().Name;
  917. }
  918. /// <summary>
  919. /// Determines if the item is considered new based on user settings
  920. /// </summary>
  921. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  922. /// <exception cref="System.ArgumentNullException"></exception>
  923. public bool IsRecentlyAdded()
  924. {
  925. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  926. }
  927. /// <summary>
  928. /// Adds a person to the item
  929. /// </summary>
  930. /// <param name="person">The person.</param>
  931. /// <exception cref="System.ArgumentNullException"></exception>
  932. public void AddPerson(PersonInfo person)
  933. {
  934. if (person == null)
  935. {
  936. throw new ArgumentNullException("person");
  937. }
  938. if (string.IsNullOrWhiteSpace(person.Name))
  939. {
  940. throw new ArgumentNullException();
  941. }
  942. // Normalize
  943. if (string.Equals(person.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  944. {
  945. person.Type = PersonType.GuestStar;
  946. }
  947. else if (string.Equals(person.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
  948. {
  949. person.Type = PersonType.Director;
  950. }
  951. else if (string.Equals(person.Role, PersonType.Producer, StringComparison.OrdinalIgnoreCase))
  952. {
  953. person.Type = PersonType.Producer;
  954. }
  955. else if (string.Equals(person.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
  956. {
  957. person.Type = PersonType.Writer;
  958. }
  959. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  960. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  961. {
  962. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  963. if (existing != null)
  964. {
  965. existing.Type = PersonType.GuestStar;
  966. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  967. return;
  968. }
  969. }
  970. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  971. {
  972. // If the actor already exists without a role and we have one, fill it in
  973. 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)));
  974. if (existing == null)
  975. {
  976. // Wasn't there - add it
  977. People.Add(person);
  978. }
  979. else
  980. {
  981. // Was there, if no role and we have one - fill it in
  982. if (string.IsNullOrWhiteSpace(existing.Role) && !string.IsNullOrWhiteSpace(person.Role))
  983. {
  984. existing.Role = person.Role;
  985. }
  986. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  987. }
  988. }
  989. else
  990. {
  991. var existing = People.FirstOrDefault(p =>
  992. string.Equals(p.Name, person.Name, StringComparison.OrdinalIgnoreCase) &&
  993. string.Equals(p.Type, person.Type, StringComparison.OrdinalIgnoreCase));
  994. // Check for dupes based on the combination of Name and Type
  995. if (existing == null)
  996. {
  997. People.Add(person);
  998. }
  999. else
  1000. {
  1001. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  1002. }
  1003. }
  1004. }
  1005. /// <summary>
  1006. /// Adds a studio to the item
  1007. /// </summary>
  1008. /// <param name="name">The name.</param>
  1009. /// <exception cref="System.ArgumentNullException"></exception>
  1010. public void AddStudio(string name)
  1011. {
  1012. if (string.IsNullOrWhiteSpace(name))
  1013. {
  1014. throw new ArgumentNullException("name");
  1015. }
  1016. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1017. {
  1018. Studios.Add(name);
  1019. }
  1020. }
  1021. /// <summary>
  1022. /// Adds a genre to the item
  1023. /// </summary>
  1024. /// <param name="name">The name.</param>
  1025. /// <exception cref="System.ArgumentNullException"></exception>
  1026. public void AddGenre(string name)
  1027. {
  1028. if (string.IsNullOrWhiteSpace(name))
  1029. {
  1030. throw new ArgumentNullException("name");
  1031. }
  1032. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1033. {
  1034. Genres.Add(name);
  1035. }
  1036. }
  1037. /// <summary>
  1038. /// Marks the played.
  1039. /// </summary>
  1040. /// <param name="user">The user.</param>
  1041. /// <param name="datePlayed">The date played.</param>
  1042. /// <param name="userManager">The user manager.</param>
  1043. /// <returns>Task.</returns>
  1044. /// <exception cref="System.ArgumentNullException"></exception>
  1045. public virtual async Task MarkPlayed(User user, DateTime? datePlayed, IUserDataManager userManager)
  1046. {
  1047. if (user == null)
  1048. {
  1049. throw new ArgumentNullException();
  1050. }
  1051. var key = GetUserDataKey();
  1052. var data = userManager.GetUserData(user.Id, key);
  1053. if (datePlayed.HasValue)
  1054. {
  1055. // Incremenet
  1056. data.PlayCount++;
  1057. }
  1058. // Ensure it's at least one
  1059. data.PlayCount = Math.Max(data.PlayCount, 1);
  1060. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate;
  1061. data.Played = true;
  1062. await userManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1063. }
  1064. /// <summary>
  1065. /// Marks the unplayed.
  1066. /// </summary>
  1067. /// <param name="user">The user.</param>
  1068. /// <param name="userManager">The user manager.</param>
  1069. /// <returns>Task.</returns>
  1070. /// <exception cref="System.ArgumentNullException"></exception>
  1071. public virtual async Task MarkUnplayed(User user, IUserDataManager userManager)
  1072. {
  1073. if (user == null)
  1074. {
  1075. throw new ArgumentNullException();
  1076. }
  1077. var key = GetUserDataKey();
  1078. var data = userManager.GetUserData(user.Id, key);
  1079. //I think it is okay to do this here.
  1080. // if this is only called when a user is manually forcing something to un-played
  1081. // then it probably is what we want to do...
  1082. data.PlayCount = 0;
  1083. data.PlaybackPositionTicks = 0;
  1084. data.LastPlayedDate = null;
  1085. data.Played = false;
  1086. await userManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1087. }
  1088. /// <summary>
  1089. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1090. /// </summary>
  1091. /// <returns>Task.</returns>
  1092. public virtual Task ChangedExternally()
  1093. {
  1094. return RefreshMetadata(CancellationToken.None);
  1095. }
  1096. /// <summary>
  1097. /// Finds a parent of a given type
  1098. /// </summary>
  1099. /// <typeparam name="T"></typeparam>
  1100. /// <returns>``0.</returns>
  1101. public T FindParent<T>()
  1102. where T : Folder
  1103. {
  1104. var parent = Parent;
  1105. while (parent != null)
  1106. {
  1107. var result = parent as T;
  1108. if (result != null)
  1109. {
  1110. return result;
  1111. }
  1112. parent = parent.Parent;
  1113. }
  1114. return null;
  1115. }
  1116. /// <summary>
  1117. /// Gets an image
  1118. /// </summary>
  1119. /// <param name="type">The type.</param>
  1120. /// <param name="imageIndex">Index of the image.</param>
  1121. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1122. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1123. public bool HasImage(ImageType type, int imageIndex)
  1124. {
  1125. if (type == ImageType.Backdrop)
  1126. {
  1127. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1128. }
  1129. if (type == ImageType.Screenshot)
  1130. {
  1131. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1132. }
  1133. return !string.IsNullOrEmpty(this.GetImagePath(type));
  1134. }
  1135. public void SetImagePath(ImageType type, int index, string path)
  1136. {
  1137. if (type == ImageType.Backdrop)
  1138. {
  1139. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1140. }
  1141. if (type == ImageType.Screenshot)
  1142. {
  1143. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1144. }
  1145. var typeKey = type;
  1146. // If it's null remove the key from the dictionary
  1147. if (string.IsNullOrEmpty(path))
  1148. {
  1149. if (Images.ContainsKey(typeKey))
  1150. {
  1151. Images.Remove(typeKey);
  1152. }
  1153. }
  1154. else
  1155. {
  1156. Images[typeKey] = path;
  1157. }
  1158. }
  1159. /// <summary>
  1160. /// Deletes the image.
  1161. /// </summary>
  1162. /// <param name="type">The type.</param>
  1163. /// <param name="index">The index.</param>
  1164. /// <returns>Task.</returns>
  1165. public Task DeleteImage(ImageType type, int? index)
  1166. {
  1167. if (type == ImageType.Backdrop)
  1168. {
  1169. if (!index.HasValue)
  1170. {
  1171. throw new ArgumentException("Please specify a backdrop image index to delete.");
  1172. }
  1173. var file = BackdropImagePaths[index.Value];
  1174. BackdropImagePaths.Remove(file);
  1175. RemoveImageSourceForPath(file);
  1176. // Delete the source file
  1177. DeleteImagePath(file);
  1178. }
  1179. else if (type == ImageType.Screenshot)
  1180. {
  1181. if (!index.HasValue)
  1182. {
  1183. throw new ArgumentException("Please specify a screenshot image index to delete.");
  1184. }
  1185. var hasScreenshots = (IHasScreenshots)this;
  1186. var file = hasScreenshots.ScreenshotImagePaths[index.Value];
  1187. hasScreenshots.ScreenshotImagePaths.Remove(file);
  1188. // Delete the source file
  1189. DeleteImagePath(file);
  1190. }
  1191. else
  1192. {
  1193. // Delete the source file
  1194. DeleteImagePath(this.GetImagePath(type));
  1195. // Remove it from the item
  1196. this.SetImagePath(type, null);
  1197. }
  1198. // Refresh metadata
  1199. // Need to disable slow providers or the image might get re-downloaded
  1200. return RefreshMetadata(CancellationToken.None, forceSave: true, allowSlowProviders: false);
  1201. }
  1202. /// <summary>
  1203. /// Deletes the image path.
  1204. /// </summary>
  1205. /// <param name="path">The path.</param>
  1206. private void DeleteImagePath(string path)
  1207. {
  1208. var currentFile = new FileInfo(path);
  1209. // This will fail if the file is hidden
  1210. if (currentFile.Exists)
  1211. {
  1212. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  1213. {
  1214. currentFile.Attributes &= ~FileAttributes.Hidden;
  1215. }
  1216. currentFile.Delete();
  1217. }
  1218. }
  1219. /// <summary>
  1220. /// Validates that images within the item are still on the file system
  1221. /// </summary>
  1222. public void ValidateImages()
  1223. {
  1224. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1225. var deletedKeys = Images
  1226. .Where(image => !File.Exists(image.Value))
  1227. .Select(i => i.Key)
  1228. .ToList();
  1229. // Now remove them from the dictionary
  1230. foreach (var key in deletedKeys)
  1231. {
  1232. Images.Remove(key);
  1233. }
  1234. }
  1235. /// <summary>
  1236. /// Validates that backdrops within the item are still on the file system
  1237. /// </summary>
  1238. public void ValidateBackdrops()
  1239. {
  1240. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1241. var deletedImages = BackdropImagePaths
  1242. .Where(path => !File.Exists(path))
  1243. .ToList();
  1244. // Now remove them from the dictionary
  1245. foreach (var path in deletedImages)
  1246. {
  1247. BackdropImagePaths.Remove(path);
  1248. RemoveImageSourceForPath(path);
  1249. }
  1250. }
  1251. /// <summary>
  1252. /// Adds the image source.
  1253. /// </summary>
  1254. /// <param name="path">The path.</param>
  1255. /// <param name="url">The URL.</param>
  1256. public void AddImageSource(string path, string url)
  1257. {
  1258. RemoveImageSourceForPath(path);
  1259. var pathMd5 = path.ToLower().GetMD5();
  1260. ImageSources.Add(new ImageSourceInfo
  1261. {
  1262. ImagePathMD5 = pathMd5,
  1263. ImageUrlMD5 = url.ToLower().GetMD5()
  1264. });
  1265. }
  1266. /// <summary>
  1267. /// Gets the image source info.
  1268. /// </summary>
  1269. /// <param name="path">The path.</param>
  1270. /// <returns>ImageSourceInfo.</returns>
  1271. public ImageSourceInfo GetImageSourceInfo(string path)
  1272. {
  1273. if (ImageSources.Count == 0)
  1274. {
  1275. return null;
  1276. }
  1277. var pathMd5 = path.ToLower().GetMD5();
  1278. return ImageSources.FirstOrDefault(i => i.ImagePathMD5 == pathMd5);
  1279. }
  1280. /// <summary>
  1281. /// Removes the image source for path.
  1282. /// </summary>
  1283. /// <param name="path">The path.</param>
  1284. public void RemoveImageSourceForPath(string path)
  1285. {
  1286. if (ImageSources.Count == 0)
  1287. {
  1288. return;
  1289. }
  1290. var pathMd5 = path.ToLower().GetMD5();
  1291. // Remove existing
  1292. foreach (var entry in ImageSources
  1293. .Where(i => i.ImagePathMD5 == pathMd5)
  1294. .ToList())
  1295. {
  1296. ImageSources.Remove(entry);
  1297. }
  1298. }
  1299. /// <summary>
  1300. /// Determines whether [contains image with source URL] [the specified URL].
  1301. /// </summary>
  1302. /// <param name="url">The URL.</param>
  1303. /// <returns><c>true</c> if [contains image with source URL] [the specified URL]; otherwise, <c>false</c>.</returns>
  1304. public bool ContainsImageWithSourceUrl(string url)
  1305. {
  1306. if (ImageSources.Count == 0)
  1307. {
  1308. return false;
  1309. }
  1310. var md5 = url.ToLower().GetMD5();
  1311. return ImageSources.Any(i => i.ImageUrlMD5 == md5);
  1312. }
  1313. /// <summary>
  1314. /// Validates the screenshots.
  1315. /// </summary>
  1316. public void ValidateScreenshots()
  1317. {
  1318. var hasScreenshots = (IHasScreenshots)this;
  1319. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1320. var deletedImages = hasScreenshots.ScreenshotImagePaths
  1321. .Where(path => !File.Exists(path))
  1322. .ToList();
  1323. // Now remove them from the dictionary
  1324. foreach (var path in deletedImages)
  1325. {
  1326. hasScreenshots.ScreenshotImagePaths.Remove(path);
  1327. }
  1328. }
  1329. /// <summary>
  1330. /// Gets the image path.
  1331. /// </summary>
  1332. /// <param name="imageType">Type of the image.</param>
  1333. /// <param name="imageIndex">Index of the image.</param>
  1334. /// <returns>System.String.</returns>
  1335. /// <exception cref="System.InvalidOperationException">
  1336. /// </exception>
  1337. /// <exception cref="System.ArgumentNullException">item</exception>
  1338. public string GetImagePath(ImageType imageType, int imageIndex)
  1339. {
  1340. if (imageType == ImageType.Backdrop)
  1341. {
  1342. return BackdropImagePaths.Count > imageIndex ? BackdropImagePaths[imageIndex] : null;
  1343. }
  1344. if (imageType == ImageType.Screenshot)
  1345. {
  1346. var hasScreenshots = (IHasScreenshots)this;
  1347. return hasScreenshots.ScreenshotImagePaths.Count > imageIndex ? hasScreenshots.ScreenshotImagePaths[imageIndex] : null;
  1348. }
  1349. if (imageType == ImageType.Chapter)
  1350. {
  1351. return ItemRepository.GetChapter(Id, imageIndex).ImagePath;
  1352. }
  1353. string val;
  1354. Images.TryGetValue(imageType, out val);
  1355. return val;
  1356. }
  1357. /// <summary>
  1358. /// Gets the image date modified.
  1359. /// </summary>
  1360. /// <param name="imagePath">The image path.</param>
  1361. /// <returns>DateTime.</returns>
  1362. /// <exception cref="System.ArgumentNullException">item</exception>
  1363. public DateTime GetImageDateModified(string imagePath)
  1364. {
  1365. if (string.IsNullOrEmpty(imagePath))
  1366. {
  1367. throw new ArgumentNullException("imagePath");
  1368. }
  1369. var locationType = LocationType;
  1370. if (locationType == LocationType.Remote ||
  1371. locationType == LocationType.Virtual)
  1372. {
  1373. return FileSystem.GetLastWriteTimeUtc(imagePath);
  1374. }
  1375. var metaFileEntry = ResolveArgs.GetMetaFileByPath(imagePath);
  1376. // If we didn't the metafile entry, check the Season
  1377. if (metaFileEntry == null)
  1378. {
  1379. if (Parent != null)
  1380. {
  1381. metaFileEntry = Parent.ResolveArgs.GetMetaFileByPath(imagePath);
  1382. }
  1383. }
  1384. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1385. return metaFileEntry == null ? FileSystem.GetLastWriteTimeUtc(imagePath) : FileSystem.GetLastWriteTimeUtc(metaFileEntry);
  1386. }
  1387. /// <summary>
  1388. /// Gets the file system path to delete when the item is to be deleted
  1389. /// </summary>
  1390. /// <returns></returns>
  1391. public virtual IEnumerable<string> GetDeletePaths()
  1392. {
  1393. return new[] { Path };
  1394. }
  1395. public Task SwapImages(ImageType type, int index1, int index2)
  1396. {
  1397. if (type != ImageType.Screenshot && type != ImageType.Backdrop)
  1398. {
  1399. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  1400. }
  1401. var file1 = GetImagePath(type, index1);
  1402. var file2 = GetImagePath(type, index2);
  1403. FileSystem.SwapFiles(file1, file2);
  1404. // Directory watchers should repeat this, but do a quick refresh first
  1405. return RefreshMetadata(CancellationToken.None, forceSave: true, allowSlowProviders: false);
  1406. }
  1407. }
  1408. }