2
0

BaseItem.cs 58 KB

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