BaseItem.cs 58 KB

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