BaseItem.cs 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793
  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, IHasMetadata
  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. private string _forcedSortName;
  318. /// <summary>
  319. /// Gets or sets the name of the forced sort.
  320. /// </summary>
  321. /// <value>The name of the forced sort.</value>
  322. public string ForcedSortName
  323. {
  324. get { return _forcedSortName; }
  325. set { _forcedSortName = value; _sortName = null; }
  326. }
  327. private string _sortName;
  328. /// <summary>
  329. /// Gets or sets the name of the sort.
  330. /// </summary>
  331. /// <value>The name of the sort.</value>
  332. [IgnoreDataMember]
  333. public string SortName
  334. {
  335. get
  336. {
  337. if (!string.IsNullOrEmpty(ForcedSortName))
  338. {
  339. return ForcedSortName;
  340. }
  341. return _sortName ?? (_sortName = CreateSortName());
  342. }
  343. }
  344. /// <summary>
  345. /// Creates the name of the sort.
  346. /// </summary>
  347. /// <returns>System.String.</returns>
  348. protected virtual string CreateSortName()
  349. {
  350. if (Name == null) return null; //some items may not have name filled in properly
  351. var sortable = Name.Trim().ToLower();
  352. sortable = ConfigurationManager.Configuration.SortRemoveCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), string.Empty));
  353. sortable = ConfigurationManager.Configuration.SortReplaceCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), " "));
  354. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  355. {
  356. var searchLower = search.ToLower();
  357. // Remove from beginning if a space follows
  358. if (sortable.StartsWith(searchLower + " "))
  359. {
  360. sortable = sortable.Remove(0, searchLower.Length + 1);
  361. }
  362. // Remove from middle if surrounded by spaces
  363. sortable = sortable.Replace(" " + searchLower + " ", " ");
  364. // Remove from end if followed by a space
  365. if (sortable.EndsWith(" " + searchLower))
  366. {
  367. sortable = sortable.Remove(sortable.Length - (searchLower.Length + 1));
  368. }
  369. }
  370. return sortable;
  371. }
  372. /// <summary>
  373. /// Gets or sets the parent.
  374. /// </summary>
  375. /// <value>The parent.</value>
  376. [IgnoreDataMember]
  377. public Folder Parent { get; set; }
  378. [IgnoreDataMember]
  379. public IEnumerable<Folder> Parents
  380. {
  381. get
  382. {
  383. var parent = Parent;
  384. while (parent != null)
  385. {
  386. yield return parent;
  387. parent = parent.Parent;
  388. }
  389. }
  390. }
  391. /// <summary>
  392. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  393. /// </summary>
  394. /// <value>The premiere date.</value>
  395. public DateTime? PremiereDate { get; set; }
  396. /// <summary>
  397. /// Gets or sets the end date.
  398. /// </summary>
  399. /// <value>The end date.</value>
  400. public DateTime? EndDate { get; set; }
  401. /// <summary>
  402. /// Gets or sets the display type of the media.
  403. /// </summary>
  404. /// <value>The display type of the media.</value>
  405. public string DisplayMediaType { get; set; }
  406. /// <summary>
  407. /// Gets or sets the backdrop image paths.
  408. /// </summary>
  409. /// <value>The backdrop image paths.</value>
  410. public List<string> BackdropImagePaths { get; set; }
  411. /// <summary>
  412. /// Gets or sets the backdrop image sources.
  413. /// </summary>
  414. /// <value>The backdrop image sources.</value>
  415. public List<ImageSourceInfo> ImageSources { get; set; }
  416. /// <summary>
  417. /// Gets or sets the official rating.
  418. /// </summary>
  419. /// <value>The official rating.</value>
  420. public string OfficialRating { get; set; }
  421. /// <summary>
  422. /// Gets or sets the official rating description.
  423. /// </summary>
  424. /// <value>The official rating description.</value>
  425. public string OfficialRatingDescription { get; set; }
  426. /// <summary>
  427. /// Gets or sets the custom rating.
  428. /// </summary>
  429. /// <value>The custom rating.</value>
  430. public string CustomRating { get; set; }
  431. /// <summary>
  432. /// Gets or sets the overview.
  433. /// </summary>
  434. /// <value>The overview.</value>
  435. public string Overview { get; set; }
  436. /// <summary>
  437. /// Gets or sets the people.
  438. /// </summary>
  439. /// <value>The people.</value>
  440. public List<PersonInfo> People { get; set; }
  441. /// <summary>
  442. /// Gets or sets the studios.
  443. /// </summary>
  444. /// <value>The studios.</value>
  445. public List<string> Studios { get; set; }
  446. /// <summary>
  447. /// Gets or sets the genres.
  448. /// </summary>
  449. /// <value>The genres.</value>
  450. public List<string> Genres { get; set; }
  451. /// <summary>
  452. /// Gets or sets the home page URL.
  453. /// </summary>
  454. /// <value>The home page URL.</value>
  455. public string HomePageUrl { get; set; }
  456. /// <summary>
  457. /// Gets or sets the community rating.
  458. /// </summary>
  459. /// <value>The community rating.</value>
  460. public float? CommunityRating { get; set; }
  461. /// <summary>
  462. /// Gets or sets the community rating vote count.
  463. /// </summary>
  464. /// <value>The community rating vote count.</value>
  465. public int? VoteCount { get; set; }
  466. /// <summary>
  467. /// Gets or sets the run time ticks.
  468. /// </summary>
  469. /// <value>The run time ticks.</value>
  470. public long? RunTimeTicks { 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. public Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool resetResolveArgs = true)
  661. {
  662. return RefreshMetadata(new MetadataRefreshOptions { ResetResolveArgs = resetResolveArgs }, cancellationToken);
  663. }
  664. /// <summary>
  665. /// Overrides the base implementation to refresh metadata for local trailers
  666. /// </summary>
  667. /// <param name="options">The options.</param>
  668. /// <param name="cancellationToken">The cancellation token.</param>
  669. /// <returns>true if a provider reports we changed</returns>
  670. public async Task<bool> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
  671. {
  672. if (options.ResetResolveArgs)
  673. {
  674. // Reload this
  675. ResetResolveArgs();
  676. }
  677. await ProviderManager.RefreshMetadata(this, options, cancellationToken).ConfigureAwait(false);
  678. return false;
  679. }
  680. [Obsolete]
  681. public virtual async Task<bool> RefreshMetadataDirect(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false)
  682. {
  683. // Refresh for the item
  684. var itemRefreshTask = ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh);
  685. cancellationToken.ThrowIfCancellationRequested();
  686. var themeSongsChanged = false;
  687. var themeVideosChanged = false;
  688. var localTrailersChanged = false;
  689. if (LocationType == LocationType.FileSystem && Parent != null)
  690. {
  691. var hasThemeMedia = this as IHasThemeMedia;
  692. if (hasThemeMedia != null)
  693. {
  694. themeSongsChanged = await RefreshThemeSongs(hasThemeMedia, cancellationToken, forceSave, forceRefresh).ConfigureAwait(false);
  695. themeVideosChanged = await RefreshThemeVideos(hasThemeMedia, cancellationToken, forceSave, forceRefresh).ConfigureAwait(false);
  696. }
  697. var hasTrailers = this as IHasTrailers;
  698. if (hasTrailers != null)
  699. {
  700. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, cancellationToken, forceSave, forceRefresh).ConfigureAwait(false);
  701. }
  702. }
  703. cancellationToken.ThrowIfCancellationRequested();
  704. // Get the result from the item task
  705. var updateReason = await itemRefreshTask.ConfigureAwait(false);
  706. var changed = updateReason.HasValue;
  707. if (changed || forceSave || themeSongsChanged || themeVideosChanged || localTrailersChanged)
  708. {
  709. cancellationToken.ThrowIfCancellationRequested();
  710. await LibraryManager.UpdateItem(this, updateReason ?? ItemUpdateType.Unspecified, cancellationToken).ConfigureAwait(false);
  711. }
  712. return changed;
  713. }
  714. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false)
  715. {
  716. var newItems = LoadLocalTrailers().ToList();
  717. var newItemIds = newItems.Select(i => i.Id).ToList();
  718. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  719. var tasks = newItems.Select(i => i.RefreshMetadata(new MetadataRefreshOptions
  720. {
  721. ForceSave = forceSave,
  722. ReplaceAllMetadata = forceRefresh,
  723. ResetResolveArgs = false
  724. }, cancellationToken));
  725. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  726. item.LocalTrailerIds = newItemIds;
  727. return itemsChanged || results.Contains(true);
  728. }
  729. private async Task<bool> RefreshThemeVideos(IHasThemeMedia item, CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false)
  730. {
  731. var newThemeVideos = LoadThemeVideos().ToList();
  732. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  733. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  734. var tasks = newThemeVideos.Select(i => i.RefreshMetadata(new MetadataRefreshOptions
  735. {
  736. ForceSave = forceSave,
  737. ReplaceAllMetadata = forceRefresh,
  738. ResetResolveArgs = false
  739. }, cancellationToken));
  740. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  741. item.ThemeVideoIds = newThemeVideoIds;
  742. return themeVideosChanged || results.Contains(true);
  743. }
  744. /// <summary>
  745. /// Refreshes the theme songs.
  746. /// </summary>
  747. private async Task<bool> RefreshThemeSongs(IHasThemeMedia item, CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false)
  748. {
  749. var newThemeSongs = LoadThemeSongs().ToList();
  750. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  751. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  752. var tasks = newThemeSongs.Select(i => i.RefreshMetadata(new MetadataRefreshOptions
  753. {
  754. ForceSave = forceSave,
  755. ReplaceAllMetadata = forceRefresh,
  756. ResetResolveArgs = false
  757. }, cancellationToken));
  758. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  759. item.ThemeSongIds = newThemeSongIds;
  760. return themeSongsChanged || results.Contains(true);
  761. }
  762. /// <summary>
  763. /// Gets or sets the provider ids.
  764. /// </summary>
  765. /// <value>The provider ids.</value>
  766. public Dictionary<string, string> ProviderIds { get; set; }
  767. /// <summary>
  768. /// Override this to false if class should be ignored for indexing purposes
  769. /// </summary>
  770. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  771. [IgnoreDataMember]
  772. public virtual bool IncludeInIndex
  773. {
  774. get { return true; }
  775. }
  776. /// <summary>
  777. /// Override this to true if class should be grouped under a container in indicies
  778. /// The container class should be defined via IndexContainer
  779. /// </summary>
  780. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  781. [IgnoreDataMember]
  782. public virtual bool GroupInIndex
  783. {
  784. get { return false; }
  785. }
  786. /// <summary>
  787. /// Override this to return the folder that should be used to construct a container
  788. /// for this item in an index. GroupInIndex should be true as well.
  789. /// </summary>
  790. /// <value>The index container.</value>
  791. [IgnoreDataMember]
  792. public virtual Folder IndexContainer
  793. {
  794. get { return null; }
  795. }
  796. /// <summary>
  797. /// Gets the user data key.
  798. /// </summary>
  799. /// <returns>System.String.</returns>
  800. public virtual string GetUserDataKey()
  801. {
  802. return Id.ToString();
  803. }
  804. /// <summary>
  805. /// Gets the preferred metadata language.
  806. /// </summary>
  807. /// <returns>System.String.</returns>
  808. public string GetPreferredMetadataLanguage()
  809. {
  810. string lang = null;
  811. var hasLang = this as IHasPreferredMetadataLanguage;
  812. if (hasLang != null)
  813. {
  814. lang = hasLang.PreferredMetadataLanguage;
  815. }
  816. if (string.IsNullOrEmpty(lang))
  817. {
  818. lang = Parents.OfType<IHasPreferredMetadataLanguage>()
  819. .Select(i => i.PreferredMetadataLanguage)
  820. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  821. }
  822. if (string.IsNullOrEmpty(lang))
  823. {
  824. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  825. }
  826. return lang;
  827. }
  828. /// <summary>
  829. /// Gets the preferred metadata language.
  830. /// </summary>
  831. /// <returns>System.String.</returns>
  832. public string GetPreferredMetadataCountryCode()
  833. {
  834. string lang = null;
  835. var hasLang = this as IHasPreferredMetadataLanguage;
  836. if (hasLang != null)
  837. {
  838. lang = hasLang.PreferredMetadataCountryCode;
  839. }
  840. if (string.IsNullOrEmpty(lang))
  841. {
  842. lang = Parents.OfType<IHasPreferredMetadataLanguage>()
  843. .Select(i => i.PreferredMetadataCountryCode)
  844. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  845. }
  846. if (string.IsNullOrEmpty(lang))
  847. {
  848. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  849. }
  850. return lang;
  851. }
  852. public virtual bool IsSaveLocalMetadataEnabled()
  853. {
  854. return ConfigurationManager.Configuration.SaveLocalMeta;
  855. }
  856. /// <summary>
  857. /// Determines if a given user has access to this item
  858. /// </summary>
  859. /// <param name="user">The user.</param>
  860. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  861. /// <exception cref="System.ArgumentNullException">user</exception>
  862. public bool IsParentalAllowed(User user)
  863. {
  864. if (user == null)
  865. {
  866. throw new ArgumentNullException("user");
  867. }
  868. var maxAllowedRating = user.Configuration.MaxParentalRating;
  869. if (maxAllowedRating == null)
  870. {
  871. return true;
  872. }
  873. var rating = CustomRatingForComparison;
  874. if (string.IsNullOrEmpty(rating))
  875. {
  876. rating = OfficialRatingForComparison;
  877. }
  878. if (string.IsNullOrEmpty(rating))
  879. {
  880. return !GetBlockUnratedValue(user.Configuration);
  881. }
  882. var value = LocalizationManager.GetRatingLevel(rating);
  883. // Could not determine the integer value
  884. if (!value.HasValue)
  885. {
  886. return true;
  887. }
  888. return value.Value <= maxAllowedRating.Value;
  889. }
  890. /// <summary>
  891. /// Gets the block unrated value.
  892. /// </summary>
  893. /// <param name="config">The configuration.</param>
  894. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  895. protected virtual bool GetBlockUnratedValue(UserConfiguration config)
  896. {
  897. return config.BlockNotRated;
  898. }
  899. /// <summary>
  900. /// Determines if this folder should be visible to a given user.
  901. /// Default is just parental allowed. Can be overridden for more functionality.
  902. /// </summary>
  903. /// <param name="user">The user.</param>
  904. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  905. /// <exception cref="System.ArgumentNullException">user</exception>
  906. public virtual bool IsVisible(User user)
  907. {
  908. if (user == null)
  909. {
  910. throw new ArgumentNullException("user");
  911. }
  912. return IsParentalAllowed(user);
  913. }
  914. /// <summary>
  915. /// Finds the particular item by searching through our parents and, if not found there, loading from repo
  916. /// </summary>
  917. /// <param name="id">The id.</param>
  918. /// <returns>BaseItem.</returns>
  919. /// <exception cref="System.ArgumentException"></exception>
  920. protected BaseItem FindParentItem(Guid id)
  921. {
  922. if (id == Guid.Empty)
  923. {
  924. throw new ArgumentException();
  925. }
  926. var parent = Parent;
  927. while (parent != null && !parent.IsRoot)
  928. {
  929. if (parent.Id == id) return parent;
  930. parent = parent.Parent;
  931. }
  932. return null;
  933. }
  934. /// <summary>
  935. /// Gets a value indicating whether this instance is folder.
  936. /// </summary>
  937. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  938. [IgnoreDataMember]
  939. public virtual bool IsFolder
  940. {
  941. get
  942. {
  943. return false;
  944. }
  945. }
  946. /// <summary>
  947. /// Determine if we have changed vs the passed in copy
  948. /// </summary>
  949. /// <param name="copy">The copy.</param>
  950. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  951. /// <exception cref="System.ArgumentNullException"></exception>
  952. public virtual bool HasChanged(BaseItem copy)
  953. {
  954. if (copy == null)
  955. {
  956. throw new ArgumentNullException();
  957. }
  958. if (IsInMixedFolder != copy.IsInMixedFolder)
  959. {
  960. Logger.Debug(Name + " changed due to different value for IsInMixedFolder.");
  961. return true;
  962. }
  963. var changed = copy.DateModified != DateModified;
  964. if (changed)
  965. {
  966. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  967. }
  968. return changed;
  969. }
  970. public virtual string GetClientTypeName()
  971. {
  972. return GetType().Name;
  973. }
  974. /// <summary>
  975. /// Determines if the item is considered new based on user settings
  976. /// </summary>
  977. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  978. /// <exception cref="System.ArgumentNullException"></exception>
  979. public bool IsRecentlyAdded()
  980. {
  981. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  982. }
  983. /// <summary>
  984. /// Adds a person to the item
  985. /// </summary>
  986. /// <param name="person">The person.</param>
  987. /// <exception cref="System.ArgumentNullException"></exception>
  988. public void AddPerson(PersonInfo person)
  989. {
  990. if (person == null)
  991. {
  992. throw new ArgumentNullException("person");
  993. }
  994. if (string.IsNullOrWhiteSpace(person.Name))
  995. {
  996. throw new ArgumentNullException();
  997. }
  998. // Normalize
  999. if (string.Equals(person.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  1000. {
  1001. person.Type = PersonType.GuestStar;
  1002. }
  1003. else if (string.Equals(person.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
  1004. {
  1005. person.Type = PersonType.Director;
  1006. }
  1007. else if (string.Equals(person.Role, PersonType.Producer, StringComparison.OrdinalIgnoreCase))
  1008. {
  1009. person.Type = PersonType.Producer;
  1010. }
  1011. else if (string.Equals(person.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
  1012. {
  1013. person.Type = PersonType.Writer;
  1014. }
  1015. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  1016. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  1017. {
  1018. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  1019. if (existing != null)
  1020. {
  1021. existing.Type = PersonType.GuestStar;
  1022. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  1023. return;
  1024. }
  1025. }
  1026. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  1027. {
  1028. // If the actor already exists without a role and we have one, fill it in
  1029. 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)));
  1030. if (existing == null)
  1031. {
  1032. // Wasn't there - add it
  1033. People.Add(person);
  1034. }
  1035. else
  1036. {
  1037. // Was there, if no role and we have one - fill it in
  1038. if (string.IsNullOrWhiteSpace(existing.Role) && !string.IsNullOrWhiteSpace(person.Role))
  1039. {
  1040. existing.Role = person.Role;
  1041. }
  1042. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  1043. }
  1044. }
  1045. else
  1046. {
  1047. var existing = People.FirstOrDefault(p =>
  1048. string.Equals(p.Name, person.Name, StringComparison.OrdinalIgnoreCase) &&
  1049. string.Equals(p.Type, person.Type, StringComparison.OrdinalIgnoreCase));
  1050. // Check for dupes based on the combination of Name and Type
  1051. if (existing == null)
  1052. {
  1053. People.Add(person);
  1054. }
  1055. else
  1056. {
  1057. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  1058. }
  1059. }
  1060. }
  1061. /// <summary>
  1062. /// Adds a studio to the item
  1063. /// </summary>
  1064. /// <param name="name">The name.</param>
  1065. /// <exception cref="System.ArgumentNullException"></exception>
  1066. public void AddStudio(string name)
  1067. {
  1068. if (string.IsNullOrWhiteSpace(name))
  1069. {
  1070. throw new ArgumentNullException("name");
  1071. }
  1072. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1073. {
  1074. Studios.Add(name);
  1075. }
  1076. }
  1077. /// <summary>
  1078. /// Adds a genre to the item
  1079. /// </summary>
  1080. /// <param name="name">The name.</param>
  1081. /// <exception cref="System.ArgumentNullException"></exception>
  1082. public void AddGenre(string name)
  1083. {
  1084. if (string.IsNullOrWhiteSpace(name))
  1085. {
  1086. throw new ArgumentNullException("name");
  1087. }
  1088. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1089. {
  1090. Genres.Add(name);
  1091. }
  1092. }
  1093. /// <summary>
  1094. /// Marks the played.
  1095. /// </summary>
  1096. /// <param name="user">The user.</param>
  1097. /// <param name="datePlayed">The date played.</param>
  1098. /// <param name="userManager">The user manager.</param>
  1099. /// <returns>Task.</returns>
  1100. /// <exception cref="System.ArgumentNullException"></exception>
  1101. public virtual async Task MarkPlayed(User user, DateTime? datePlayed, IUserDataManager userManager)
  1102. {
  1103. if (user == null)
  1104. {
  1105. throw new ArgumentNullException();
  1106. }
  1107. var key = GetUserDataKey();
  1108. var data = userManager.GetUserData(user.Id, key);
  1109. if (datePlayed.HasValue)
  1110. {
  1111. // Incremenet
  1112. data.PlayCount++;
  1113. }
  1114. // Ensure it's at least one
  1115. data.PlayCount = Math.Max(data.PlayCount, 1);
  1116. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate;
  1117. data.Played = true;
  1118. await userManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1119. }
  1120. /// <summary>
  1121. /// Marks the unplayed.
  1122. /// </summary>
  1123. /// <param name="user">The user.</param>
  1124. /// <param name="userManager">The user manager.</param>
  1125. /// <returns>Task.</returns>
  1126. /// <exception cref="System.ArgumentNullException"></exception>
  1127. public virtual async Task MarkUnplayed(User user, IUserDataManager userManager)
  1128. {
  1129. if (user == null)
  1130. {
  1131. throw new ArgumentNullException();
  1132. }
  1133. var key = GetUserDataKey();
  1134. var data = userManager.GetUserData(user.Id, key);
  1135. //I think it is okay to do this here.
  1136. // if this is only called when a user is manually forcing something to un-played
  1137. // then it probably is what we want to do...
  1138. data.PlayCount = 0;
  1139. data.PlaybackPositionTicks = 0;
  1140. data.LastPlayedDate = null;
  1141. data.Played = false;
  1142. await userManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1143. }
  1144. /// <summary>
  1145. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1146. /// </summary>
  1147. /// <returns>Task.</returns>
  1148. public virtual Task ChangedExternally()
  1149. {
  1150. return RefreshMetadata(CancellationToken.None);
  1151. }
  1152. /// <summary>
  1153. /// Finds a parent of a given type
  1154. /// </summary>
  1155. /// <typeparam name="T"></typeparam>
  1156. /// <returns>``0.</returns>
  1157. public T FindParent<T>()
  1158. where T : Folder
  1159. {
  1160. var parent = Parent;
  1161. while (parent != null)
  1162. {
  1163. var result = parent as T;
  1164. if (result != null)
  1165. {
  1166. return result;
  1167. }
  1168. parent = parent.Parent;
  1169. }
  1170. return null;
  1171. }
  1172. /// <summary>
  1173. /// Gets an image
  1174. /// </summary>
  1175. /// <param name="type">The type.</param>
  1176. /// <param name="imageIndex">Index of the image.</param>
  1177. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1178. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1179. public bool HasImage(ImageType type, int imageIndex)
  1180. {
  1181. if (type == ImageType.Backdrop)
  1182. {
  1183. return BackdropImagePaths.Count > imageIndex;
  1184. }
  1185. if (type == ImageType.Screenshot)
  1186. {
  1187. var hasScreenshots = this as IHasScreenshots;
  1188. return hasScreenshots != null && hasScreenshots.ScreenshotImagePaths.Count > imageIndex;
  1189. }
  1190. return !string.IsNullOrEmpty(this.GetImagePath(type));
  1191. }
  1192. public void SetImagePath(ImageType type, int index, string path)
  1193. {
  1194. if (type == ImageType.Backdrop)
  1195. {
  1196. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1197. }
  1198. if (type == ImageType.Screenshot)
  1199. {
  1200. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1201. }
  1202. var typeKey = type;
  1203. // If it's null remove the key from the dictionary
  1204. if (string.IsNullOrEmpty(path))
  1205. {
  1206. if (Images.ContainsKey(typeKey))
  1207. {
  1208. Images.Remove(typeKey);
  1209. }
  1210. }
  1211. else
  1212. {
  1213. Images[typeKey] = path;
  1214. }
  1215. }
  1216. /// <summary>
  1217. /// Deletes the image.
  1218. /// </summary>
  1219. /// <param name="type">The type.</param>
  1220. /// <param name="index">The index.</param>
  1221. /// <returns>Task.</returns>
  1222. public Task DeleteImage(ImageType type, int? index)
  1223. {
  1224. if (type == ImageType.Backdrop)
  1225. {
  1226. if (!index.HasValue)
  1227. {
  1228. throw new ArgumentException("Please specify a backdrop image index to delete.");
  1229. }
  1230. var file = BackdropImagePaths[index.Value];
  1231. BackdropImagePaths.Remove(file);
  1232. RemoveImageSourceForPath(file);
  1233. // Delete the source file
  1234. DeleteImagePath(file);
  1235. }
  1236. else if (type == ImageType.Screenshot)
  1237. {
  1238. if (!index.HasValue)
  1239. {
  1240. throw new ArgumentException("Please specify a screenshot image index to delete.");
  1241. }
  1242. var hasScreenshots = (IHasScreenshots)this;
  1243. var file = hasScreenshots.ScreenshotImagePaths[index.Value];
  1244. hasScreenshots.ScreenshotImagePaths.Remove(file);
  1245. // Delete the source file
  1246. DeleteImagePath(file);
  1247. }
  1248. else
  1249. {
  1250. // Delete the source file
  1251. DeleteImagePath(this.GetImagePath(type));
  1252. // Remove it from the item
  1253. this.SetImagePath(type, null);
  1254. }
  1255. // Refresh metadata
  1256. // Need to disable slow providers or the image might get re-downloaded
  1257. return RefreshMetadata(new MetadataRefreshOptions
  1258. {
  1259. ForceSave = true,
  1260. ImageRefreshMode = MetadataRefreshMode.None,
  1261. MetadataRefreshMode = MetadataRefreshMode.None
  1262. }, CancellationToken.None);
  1263. }
  1264. /// <summary>
  1265. /// Deletes the image path.
  1266. /// </summary>
  1267. /// <param name="path">The path.</param>
  1268. private void DeleteImagePath(string path)
  1269. {
  1270. var currentFile = new FileInfo(path);
  1271. // This will fail if the file is hidden
  1272. if (currentFile.Exists)
  1273. {
  1274. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  1275. {
  1276. currentFile.Attributes &= ~FileAttributes.Hidden;
  1277. }
  1278. currentFile.Delete();
  1279. }
  1280. }
  1281. /// <summary>
  1282. /// Validates that images within the item are still on the file system
  1283. /// </summary>
  1284. public bool ValidateImages()
  1285. {
  1286. var changed = false;
  1287. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1288. var deletedKeys = Images
  1289. .Where(image => !File.Exists(image.Value))
  1290. .Select(i => i.Key)
  1291. .ToList();
  1292. // Now remove them from the dictionary
  1293. foreach (var key in deletedKeys)
  1294. {
  1295. Images.Remove(key);
  1296. changed = true;
  1297. }
  1298. if (ValidateBackdrops())
  1299. {
  1300. changed = true;
  1301. }
  1302. if (ValidateScreenshots())
  1303. {
  1304. changed = true;
  1305. }
  1306. return changed;
  1307. }
  1308. /// <summary>
  1309. /// Validates that backdrops within the item are still on the file system
  1310. /// </summary>
  1311. private bool ValidateBackdrops()
  1312. {
  1313. var changed = false;
  1314. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1315. var deletedImages = BackdropImagePaths
  1316. .Where(path => !File.Exists(path))
  1317. .ToList();
  1318. // Now remove them from the dictionary
  1319. foreach (var path in deletedImages)
  1320. {
  1321. BackdropImagePaths.Remove(path);
  1322. RemoveImageSourceForPath(path);
  1323. changed = true;
  1324. }
  1325. return changed;
  1326. }
  1327. /// <summary>
  1328. /// Adds the image source.
  1329. /// </summary>
  1330. /// <param name="path">The path.</param>
  1331. /// <param name="url">The URL.</param>
  1332. public void AddImageSource(string path, string url)
  1333. {
  1334. RemoveImageSourceForPath(path);
  1335. var pathMd5 = path.ToLower().GetMD5();
  1336. ImageSources.Add(new ImageSourceInfo
  1337. {
  1338. ImagePathMD5 = pathMd5,
  1339. ImageUrlMD5 = url.ToLower().GetMD5()
  1340. });
  1341. }
  1342. /// <summary>
  1343. /// Gets the image source info.
  1344. /// </summary>
  1345. /// <param name="path">The path.</param>
  1346. /// <returns>ImageSourceInfo.</returns>
  1347. public ImageSourceInfo GetImageSourceInfo(string path)
  1348. {
  1349. if (ImageSources.Count == 0)
  1350. {
  1351. return null;
  1352. }
  1353. var pathMd5 = path.ToLower().GetMD5();
  1354. return ImageSources.FirstOrDefault(i => i.ImagePathMD5 == pathMd5);
  1355. }
  1356. /// <summary>
  1357. /// Removes the image source for path.
  1358. /// </summary>
  1359. /// <param name="path">The path.</param>
  1360. public void RemoveImageSourceForPath(string path)
  1361. {
  1362. if (ImageSources.Count == 0)
  1363. {
  1364. return;
  1365. }
  1366. var pathMd5 = path.ToLower().GetMD5();
  1367. // Remove existing
  1368. foreach (var entry in ImageSources
  1369. .Where(i => i.ImagePathMD5 == pathMd5)
  1370. .ToList())
  1371. {
  1372. ImageSources.Remove(entry);
  1373. }
  1374. }
  1375. /// <summary>
  1376. /// Determines whether [contains image with source URL] [the specified URL].
  1377. /// </summary>
  1378. /// <param name="url">The URL.</param>
  1379. /// <returns><c>true</c> if [contains image with source URL] [the specified URL]; otherwise, <c>false</c>.</returns>
  1380. public bool ContainsImageWithSourceUrl(string url)
  1381. {
  1382. if (ImageSources.Count == 0)
  1383. {
  1384. return false;
  1385. }
  1386. var md5 = url.ToLower().GetMD5();
  1387. return ImageSources.Any(i => i.ImageUrlMD5 == md5);
  1388. }
  1389. /// <summary>
  1390. /// Validates the screenshots.
  1391. /// </summary>
  1392. private bool ValidateScreenshots()
  1393. {
  1394. var changed = false;
  1395. var hasScreenshots = this as IHasScreenshots;
  1396. if (hasScreenshots == null)
  1397. {
  1398. return changed;
  1399. }
  1400. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1401. var deletedImages = hasScreenshots.ScreenshotImagePaths
  1402. .Where(path => !File.Exists(path))
  1403. .ToList();
  1404. // Now remove them from the dictionary
  1405. foreach (var path in deletedImages)
  1406. {
  1407. hasScreenshots.ScreenshotImagePaths.Remove(path);
  1408. changed = true;
  1409. }
  1410. return changed;
  1411. }
  1412. /// <summary>
  1413. /// Gets the image path.
  1414. /// </summary>
  1415. /// <param name="imageType">Type of the image.</param>
  1416. /// <param name="imageIndex">Index of the image.</param>
  1417. /// <returns>System.String.</returns>
  1418. /// <exception cref="System.InvalidOperationException">
  1419. /// </exception>
  1420. /// <exception cref="System.ArgumentNullException">item</exception>
  1421. public string GetImagePath(ImageType imageType, int imageIndex)
  1422. {
  1423. if (imageType == ImageType.Backdrop)
  1424. {
  1425. return BackdropImagePaths.Count > imageIndex ? BackdropImagePaths[imageIndex] : null;
  1426. }
  1427. if (imageType == ImageType.Screenshot)
  1428. {
  1429. var hasScreenshots = (IHasScreenshots)this;
  1430. return hasScreenshots.ScreenshotImagePaths.Count > imageIndex ? hasScreenshots.ScreenshotImagePaths[imageIndex] : null;
  1431. }
  1432. if (imageType == ImageType.Chapter)
  1433. {
  1434. return ItemRepository.GetChapter(Id, imageIndex).ImagePath;
  1435. }
  1436. string val;
  1437. Images.TryGetValue(imageType, out val);
  1438. return val;
  1439. }
  1440. /// <summary>
  1441. /// Gets the image date modified.
  1442. /// </summary>
  1443. /// <param name="imagePath">The image path.</param>
  1444. /// <returns>DateTime.</returns>
  1445. /// <exception cref="System.ArgumentNullException">item</exception>
  1446. public DateTime GetImageDateModified(string imagePath)
  1447. {
  1448. if (string.IsNullOrEmpty(imagePath))
  1449. {
  1450. throw new ArgumentNullException("imagePath");
  1451. }
  1452. var locationType = LocationType;
  1453. if (locationType == LocationType.Remote ||
  1454. locationType == LocationType.Virtual)
  1455. {
  1456. return FileSystem.GetLastWriteTimeUtc(imagePath);
  1457. }
  1458. var metaFileEntry = ResolveArgs.GetMetaFileByPath(imagePath);
  1459. // If we didn't the metafile entry, check the Season
  1460. if (metaFileEntry == null)
  1461. {
  1462. if (Parent != null)
  1463. {
  1464. metaFileEntry = Parent.ResolveArgs.GetMetaFileByPath(imagePath);
  1465. }
  1466. }
  1467. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1468. return metaFileEntry == null ? FileSystem.GetLastWriteTimeUtc(imagePath) : FileSystem.GetLastWriteTimeUtc(metaFileEntry);
  1469. }
  1470. /// <summary>
  1471. /// Gets the file system path to delete when the item is to be deleted
  1472. /// </summary>
  1473. /// <returns></returns>
  1474. public virtual IEnumerable<string> GetDeletePaths()
  1475. {
  1476. return new[] { Path };
  1477. }
  1478. public Task SwapImages(ImageType type, int index1, int index2)
  1479. {
  1480. if (type != ImageType.Screenshot && type != ImageType.Backdrop)
  1481. {
  1482. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  1483. }
  1484. var file1 = GetImagePath(type, index1);
  1485. var file2 = GetImagePath(type, index2);
  1486. FileSystem.SwapFiles(file1, file2);
  1487. // Directory watchers should repeat this, but do a quick refresh first
  1488. return RefreshMetadata(new MetadataRefreshOptions
  1489. {
  1490. ForceSave = true,
  1491. MetadataRefreshMode = MetadataRefreshMode.None
  1492. }, CancellationToken.None);
  1493. }
  1494. public virtual bool IsPlayed(User user)
  1495. {
  1496. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1497. return userdata != null && userdata.Played;
  1498. }
  1499. public virtual bool IsUnplayed(User user)
  1500. {
  1501. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1502. return userdata == null || !userdata.Played;
  1503. }
  1504. }
  1505. }