BaseItem.cs 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352
  1. using MediaBrowser.Controller.Configuration;
  2. using MediaBrowser.Controller.IO;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Controller.Localization;
  5. using MediaBrowser.Controller.Persistence;
  6. using MediaBrowser.Controller.Providers;
  7. using MediaBrowser.Controller.Resolvers;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Runtime.Serialization;
  15. using System.Text;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Controller.Entities
  19. {
  20. /// <summary>
  21. /// Class BaseItem
  22. /// </summary>
  23. public abstract class BaseItem : IHasProviderIds
  24. {
  25. protected BaseItem()
  26. {
  27. Genres = new List<string>();
  28. TrailerUrls = new List<string>();
  29. Studios = new List<string>();
  30. People = new List<PersonInfo>();
  31. }
  32. /// <summary>
  33. /// The trailer folder name
  34. /// </summary>
  35. public const string TrailerFolderName = "trailers";
  36. /// <summary>
  37. /// Gets or sets the name.
  38. /// </summary>
  39. /// <value>The name.</value>
  40. public virtual string Name { get; set; }
  41. /// <summary>
  42. /// Gets or sets the id.
  43. /// </summary>
  44. /// <value>The id.</value>
  45. public virtual Guid Id { get; set; }
  46. /// <summary>
  47. /// Gets or sets the path.
  48. /// </summary>
  49. /// <value>The path.</value>
  50. public virtual string Path { get; set; }
  51. /// <summary>
  52. /// Gets or sets the type of the location.
  53. /// </summary>
  54. /// <value>The type of the location.</value>
  55. public virtual LocationType LocationType
  56. {
  57. get
  58. {
  59. if (string.IsNullOrEmpty(Path))
  60. {
  61. return LocationType.Virtual;
  62. }
  63. return System.IO.Path.IsPathRooted(Path) ? LocationType.FileSystem : LocationType.Remote;
  64. }
  65. }
  66. /// <summary>
  67. /// This is just a helper for convenience
  68. /// </summary>
  69. /// <value>The primary image path.</value>
  70. [IgnoreDataMember]
  71. public string PrimaryImagePath
  72. {
  73. get { return GetImage(ImageType.Primary); }
  74. set { SetImage(ImageType.Primary, value); }
  75. }
  76. /// <summary>
  77. /// Gets or sets the images.
  78. /// </summary>
  79. /// <value>The images.</value>
  80. public virtual Dictionary<string, string> Images { get; set; }
  81. /// <summary>
  82. /// Gets or sets the date created.
  83. /// </summary>
  84. /// <value>The date created.</value>
  85. public DateTime DateCreated { get; set; }
  86. /// <summary>
  87. /// Gets or sets the date modified.
  88. /// </summary>
  89. /// <value>The date modified.</value>
  90. public DateTime DateModified { get; set; }
  91. /// <summary>
  92. /// The logger
  93. /// </summary>
  94. public static ILogger Logger { get; set; }
  95. public static ILibraryManager LibraryManager { get; set; }
  96. public static IServerConfigurationManager ConfigurationManager { get; set; }
  97. public static IProviderManager ProviderManager { get; set; }
  98. /// <summary>
  99. /// Returns a <see cref="System.String" /> that represents this instance.
  100. /// </summary>
  101. /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
  102. public override string ToString()
  103. {
  104. return Name;
  105. }
  106. /// <summary>
  107. /// Returns true if this item should not attempt to fetch metadata
  108. /// </summary>
  109. /// <value><c>true</c> if [dont fetch meta]; otherwise, <c>false</c>.</value>
  110. [IgnoreDataMember]
  111. public virtual bool DontFetchMeta
  112. {
  113. get
  114. {
  115. if (Path != null)
  116. {
  117. return Path.IndexOf("[dontfetchmeta]", StringComparison.OrdinalIgnoreCase) != -1;
  118. }
  119. return false;
  120. }
  121. }
  122. /// <summary>
  123. /// Determines whether the item has a saved local image of the specified name (jpg or png).
  124. /// </summary>
  125. /// <param name="name">The name.</param>
  126. /// <returns><c>true</c> if [has local image] [the specified item]; otherwise, <c>false</c>.</returns>
  127. /// <exception cref="System.ArgumentNullException">name</exception>
  128. public bool HasLocalImage(string name)
  129. {
  130. if (string.IsNullOrEmpty(name))
  131. {
  132. throw new ArgumentNullException("name");
  133. }
  134. return ResolveArgs.ContainsMetaFileByName(name + ".jpg") ||
  135. ResolveArgs.ContainsMetaFileByName(name + ".png");
  136. }
  137. /// <summary>
  138. /// Should be overridden to return the proper folder where metadata lives
  139. /// </summary>
  140. /// <value>The meta location.</value>
  141. [IgnoreDataMember]
  142. public virtual string MetaLocation
  143. {
  144. get
  145. {
  146. return Path ?? "";
  147. }
  148. }
  149. /// <summary>
  150. /// The _provider data
  151. /// </summary>
  152. private Dictionary<Guid, BaseProviderInfo> _providerData;
  153. /// <summary>
  154. /// Holds persistent data for providers like last refresh date.
  155. /// Providers can use this to determine if they need to refresh.
  156. /// The BaseProviderInfo class can be extended to hold anything a provider may need.
  157. /// Keyed by a unique provider ID.
  158. /// </summary>
  159. /// <value>The provider data.</value>
  160. public Dictionary<Guid, BaseProviderInfo> ProviderData
  161. {
  162. get
  163. {
  164. return _providerData ?? (_providerData = new Dictionary<Guid, BaseProviderInfo>());
  165. }
  166. set
  167. {
  168. _providerData = value;
  169. }
  170. }
  171. /// <summary>
  172. /// The _file system stamp
  173. /// </summary>
  174. private string _fileSystemStamp;
  175. /// <summary>
  176. /// Gets a directory stamp, in the form of a string, that can be used for
  177. /// comparison purposes to determine if the file system entries for this item have changed.
  178. /// </summary>
  179. /// <value>The file system stamp.</value>
  180. [IgnoreDataMember]
  181. public string FileSystemStamp
  182. {
  183. get
  184. {
  185. return _fileSystemStamp ?? (_fileSystemStamp = GetFileSystemStamp());
  186. }
  187. }
  188. /// <summary>
  189. /// Gets the type of the media.
  190. /// </summary>
  191. /// <value>The type of the media.</value>
  192. [IgnoreDataMember]
  193. public virtual string MediaType
  194. {
  195. get
  196. {
  197. return null;
  198. }
  199. }
  200. /// <summary>
  201. /// Gets a directory stamp, in the form of a string, that can be used for
  202. /// comparison purposes to determine if the file system entries for this item have changed.
  203. /// </summary>
  204. /// <returns>Guid.</returns>
  205. private string GetFileSystemStamp()
  206. {
  207. // If there's no path or the item is a file, there's nothing to do
  208. if (LocationType != LocationType.FileSystem || !ResolveArgs.IsDirectory)
  209. {
  210. return string.Empty;
  211. }
  212. var sb = new StringBuilder();
  213. // Record the name of each file
  214. // Need to sort these because accoring to msdn docs, our i/o methods are not guaranteed in any order
  215. foreach (var file in ResolveArgs.FileSystemChildren.OrderBy(f => f.cFileName))
  216. {
  217. sb.Append(file.cFileName);
  218. }
  219. foreach (var file in ResolveArgs.MetadataFiles.OrderBy(f => f.cFileName))
  220. {
  221. sb.Append(file.cFileName);
  222. }
  223. return sb.ToString();
  224. }
  225. /// <summary>
  226. /// The _resolve args
  227. /// </summary>
  228. private ItemResolveArgs _resolveArgs;
  229. /// <summary>
  230. /// The _resolve args initialized
  231. /// </summary>
  232. private bool _resolveArgsInitialized;
  233. /// <summary>
  234. /// The _resolve args sync lock
  235. /// </summary>
  236. private object _resolveArgsSyncLock = new object();
  237. /// <summary>
  238. /// We attach these to the item so that we only ever have to hit the file system once
  239. /// (this includes the children of the containing folder)
  240. /// Use ResolveArgs.FileSystemDictionary to check for the existence of files instead of File.Exists
  241. /// </summary>
  242. /// <value>The resolve args.</value>
  243. [IgnoreDataMember]
  244. public ItemResolveArgs ResolveArgs
  245. {
  246. get
  247. {
  248. try
  249. {
  250. LazyInitializer.EnsureInitialized(ref _resolveArgs, ref _resolveArgsInitialized, ref _resolveArgsSyncLock, () => CreateResolveArgs());
  251. }
  252. catch (IOException ex)
  253. {
  254. Logger.ErrorException("Error creating resolve args for ", ex, Path);
  255. throw;
  256. }
  257. return _resolveArgs;
  258. }
  259. set
  260. {
  261. _resolveArgs = value;
  262. _resolveArgsInitialized = value != null;
  263. // Null this out so that it can be lazy loaded again
  264. _fileSystemStamp = null;
  265. }
  266. }
  267. /// <summary>
  268. /// Resets the resolve args.
  269. /// </summary>
  270. /// <param name="pathInfo">The path info.</param>
  271. public void ResetResolveArgs(WIN32_FIND_DATA? pathInfo)
  272. {
  273. ResolveArgs = CreateResolveArgs(pathInfo);
  274. }
  275. /// <summary>
  276. /// Creates ResolveArgs on demand
  277. /// </summary>
  278. /// <param name="pathInfo">The path info.</param>
  279. /// <returns>ItemResolveArgs.</returns>
  280. /// <exception cref="System.IO.IOException">Unable to retrieve file system info for + path</exception>
  281. protected internal virtual ItemResolveArgs CreateResolveArgs(WIN32_FIND_DATA? pathInfo = null)
  282. {
  283. var path = Path;
  284. // non file-system entries will not have a path
  285. if (LocationType != LocationType.FileSystem || string.IsNullOrEmpty(path))
  286. {
  287. return new ItemResolveArgs(ConfigurationManager.ApplicationPaths)
  288. {
  289. FileInfo = new WIN32_FIND_DATA()
  290. };
  291. }
  292. if (UseParentPathToCreateResolveArgs)
  293. {
  294. path = System.IO.Path.GetDirectoryName(path);
  295. }
  296. pathInfo = pathInfo ?? FileSystem.GetFileData(path);
  297. if (!pathInfo.HasValue)
  298. {
  299. throw new IOException("Unable to retrieve file system info for " + path);
  300. }
  301. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths)
  302. {
  303. FileInfo = pathInfo.Value,
  304. Path = path,
  305. Parent = Parent
  306. };
  307. // Gather child folder and files
  308. if (args.IsDirectory)
  309. {
  310. var isPhysicalRoot = args.IsPhysicalRoot;
  311. // When resolving the root, we need it's grandchildren (children of user views)
  312. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  313. args.FileSystemDictionary = FileData.GetFilteredFileSystemEntries(args.Path, Logger, flattenFolderDepth: flattenFolderDepth, args: args, resolveShortcuts: isPhysicalRoot || args.IsVf);
  314. }
  315. //update our dates
  316. EntityResolutionHelper.EnsureDates(this, args);
  317. return args;
  318. }
  319. /// <summary>
  320. /// 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
  321. /// original ones.
  322. /// </summary>
  323. /// <value><c>true</c> if [use parent path to create resolve args]; otherwise, <c>false</c>.</value>
  324. [IgnoreDataMember]
  325. protected virtual bool UseParentPathToCreateResolveArgs
  326. {
  327. get
  328. {
  329. return false;
  330. }
  331. }
  332. /// <summary>
  333. /// Gets or sets the name of the forced sort.
  334. /// </summary>
  335. /// <value>The name of the forced sort.</value>
  336. public string ForcedSortName { get; set; }
  337. private string _sortName;
  338. /// <summary>
  339. /// Gets or sets the name of the sort.
  340. /// </summary>
  341. /// <value>The name of the sort.</value>
  342. [IgnoreDataMember]
  343. public string SortName
  344. {
  345. get
  346. {
  347. return ForcedSortName ?? _sortName ?? (_sortName = CreateSortName());
  348. }
  349. }
  350. /// <summary>
  351. /// Creates the name of the sort.
  352. /// </summary>
  353. /// <returns>System.String.</returns>
  354. protected virtual string CreateSortName()
  355. {
  356. if (Name == null) return null; //some items may not have name filled in properly
  357. var sortable = Name.Trim().ToLower();
  358. sortable = ConfigurationManager.Configuration.SortRemoveCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), string.Empty));
  359. sortable = ConfigurationManager.Configuration.SortReplaceCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), " "));
  360. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  361. {
  362. var searchLower = search.ToLower();
  363. // Remove from beginning if a space follows
  364. if (sortable.StartsWith(searchLower + " "))
  365. {
  366. sortable = sortable.Remove(0, searchLower.Length + 1);
  367. }
  368. // Remove from middle if surrounded by spaces
  369. sortable = sortable.Replace(" " + searchLower + " ", " ");
  370. // Remove from end if followed by a space
  371. if (sortable.EndsWith(" " + searchLower))
  372. {
  373. sortable = sortable.Remove(sortable.Length - (searchLower.Length + 1));
  374. }
  375. }
  376. return sortable;
  377. }
  378. /// <summary>
  379. /// Gets or sets the parent.
  380. /// </summary>
  381. /// <value>The parent.</value>
  382. [IgnoreDataMember]
  383. public Folder Parent { get; set; }
  384. /// <summary>
  385. /// Gets the collection folder parent.
  386. /// </summary>
  387. /// <value>The collection folder parent.</value>
  388. [IgnoreDataMember]
  389. public Folder CollectionFolder
  390. {
  391. get
  392. {
  393. if (this is AggregateFolder)
  394. {
  395. return null;
  396. }
  397. if (IsFolder)
  398. {
  399. var iCollectionFolder = this as ICollectionFolder;
  400. if (iCollectionFolder != null)
  401. {
  402. return (Folder)this;
  403. }
  404. }
  405. var parent = Parent;
  406. while (parent != null)
  407. {
  408. var iCollectionFolder = parent as ICollectionFolder;
  409. if (iCollectionFolder != null)
  410. {
  411. return parent;
  412. }
  413. parent = parent.Parent;
  414. }
  415. return null;
  416. }
  417. }
  418. /// <summary>
  419. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  420. /// </summary>
  421. /// <value>The premiere date.</value>
  422. public DateTime? PremiereDate { get; set; }
  423. /// <summary>
  424. /// Gets or sets the end date.
  425. /// </summary>
  426. /// <value>The end date.</value>
  427. public DateTime? EndDate { get; set; }
  428. /// <summary>
  429. /// Gets or sets the display type of the media.
  430. /// </summary>
  431. /// <value>The display type of the media.</value>
  432. public virtual string DisplayMediaType { get; set; }
  433. /// <summary>
  434. /// Gets or sets the backdrop image paths.
  435. /// </summary>
  436. /// <value>The backdrop image paths.</value>
  437. public List<string> BackdropImagePaths { get; set; }
  438. /// <summary>
  439. /// Gets or sets the screenshot image paths.
  440. /// </summary>
  441. /// <value>The screenshot image paths.</value>
  442. public List<string> ScreenshotImagePaths { get; set; }
  443. /// <summary>
  444. /// Gets or sets the official rating.
  445. /// </summary>
  446. /// <value>The official rating.</value>
  447. public virtual string OfficialRating { get; set; }
  448. /// <summary>
  449. /// Gets or sets the custom rating.
  450. /// </summary>
  451. /// <value>The custom rating.</value>
  452. public virtual string CustomRating { get; set; }
  453. /// <summary>
  454. /// Gets or sets the language.
  455. /// </summary>
  456. /// <value>The language.</value>
  457. public string Language { get; set; }
  458. /// <summary>
  459. /// Gets or sets the overview.
  460. /// </summary>
  461. /// <value>The overview.</value>
  462. public string Overview { get; set; }
  463. /// <summary>
  464. /// Gets or sets the taglines.
  465. /// </summary>
  466. /// <value>The taglines.</value>
  467. public List<string> Taglines { get; set; }
  468. /// <summary>
  469. /// Gets or sets the people.
  470. /// </summary>
  471. /// <value>The people.</value>
  472. public List<PersonInfo> People { get; set; }
  473. /// <summary>
  474. /// Override this if you need to combine/collapse person information
  475. /// </summary>
  476. /// <value>All people.</value>
  477. [IgnoreDataMember]
  478. public virtual IEnumerable<PersonInfo> AllPeople
  479. {
  480. get { return People; }
  481. }
  482. /// <summary>
  483. /// Gets or sets the studios.
  484. /// </summary>
  485. /// <value>The studios.</value>
  486. public virtual List<string> Studios { get; set; }
  487. /// <summary>
  488. /// Gets or sets the genres.
  489. /// </summary>
  490. /// <value>The genres.</value>
  491. public virtual List<string> Genres { get; set; }
  492. /// <summary>
  493. /// Gets or sets the home page URL.
  494. /// </summary>
  495. /// <value>The home page URL.</value>
  496. public string HomePageUrl { get; set; }
  497. /// <summary>
  498. /// Gets or sets the budget.
  499. /// </summary>
  500. /// <value>The budget.</value>
  501. public double? Budget { get; set; }
  502. /// <summary>
  503. /// Gets or sets the revenue.
  504. /// </summary>
  505. /// <value>The revenue.</value>
  506. public double? Revenue { get; set; }
  507. /// <summary>
  508. /// Gets or sets the production locations.
  509. /// </summary>
  510. /// <value>The production locations.</value>
  511. public List<string> ProductionLocations { get; set; }
  512. /// <summary>
  513. /// Gets or sets the community rating.
  514. /// </summary>
  515. /// <value>The community rating.</value>
  516. public float? CommunityRating { get; set; }
  517. /// <summary>
  518. /// Gets or sets the run time ticks.
  519. /// </summary>
  520. /// <value>The run time ticks.</value>
  521. public long? RunTimeTicks { get; set; }
  522. /// <summary>
  523. /// Gets or sets the aspect ratio.
  524. /// </summary>
  525. /// <value>The aspect ratio.</value>
  526. public string AspectRatio { get; set; }
  527. /// <summary>
  528. /// Gets or sets the production year.
  529. /// </summary>
  530. /// <value>The production year.</value>
  531. public virtual int? ProductionYear { get; set; }
  532. /// <summary>
  533. /// If the item is part of a series, this is it's number in the series.
  534. /// This could be episode number, album track number, etc.
  535. /// </summary>
  536. /// <value>The index number.</value>
  537. public int? IndexNumber { get; set; }
  538. /// <summary>
  539. /// For an episode this could be the season number, or for a song this could be the disc number.
  540. /// </summary>
  541. /// <value>The parent index number.</value>
  542. public int? ParentIndexNumber { get; set; }
  543. /// <summary>
  544. /// The _local trailers
  545. /// </summary>
  546. private List<Video> _localTrailers;
  547. /// <summary>
  548. /// The _local trailers initialized
  549. /// </summary>
  550. private bool _localTrailersInitialized;
  551. /// <summary>
  552. /// The _local trailers sync lock
  553. /// </summary>
  554. private object _localTrailersSyncLock = new object();
  555. /// <summary>
  556. /// Gets the local trailers.
  557. /// </summary>
  558. /// <value>The local trailers.</value>
  559. [IgnoreDataMember]
  560. public List<Video> LocalTrailers
  561. {
  562. get
  563. {
  564. LazyInitializer.EnsureInitialized(ref _localTrailers, ref _localTrailersInitialized, ref _localTrailersSyncLock, LoadLocalTrailers);
  565. return _localTrailers;
  566. }
  567. private set
  568. {
  569. _localTrailers = value;
  570. if (value == null)
  571. {
  572. _localTrailersInitialized = false;
  573. }
  574. }
  575. }
  576. /// <summary>
  577. /// Loads local trailers from the file system
  578. /// </summary>
  579. /// <returns>List{Video}.</returns>
  580. private List<Video> LoadLocalTrailers()
  581. {
  582. ItemResolveArgs resolveArgs;
  583. try
  584. {
  585. resolveArgs = ResolveArgs;
  586. }
  587. catch (IOException ex)
  588. {
  589. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  590. return new List<Video>();
  591. }
  592. if (!resolveArgs.IsDirectory)
  593. {
  594. return new List<Video>();
  595. }
  596. var folder = resolveArgs.GetFileSystemEntryByName(TrailerFolderName);
  597. // Path doesn't exist. No biggie
  598. if (folder == null)
  599. {
  600. return new List<Video>();
  601. }
  602. IEnumerable<WIN32_FIND_DATA> files;
  603. try
  604. {
  605. files = FileSystem.GetFiles(folder.Value.Path);
  606. }
  607. catch (IOException ex)
  608. {
  609. Logger.ErrorException("Error loading trailers for {0}", ex, Name);
  610. return new List<Video>();
  611. }
  612. return LibraryManager.ResolvePaths<Video>(files, null).Select(video =>
  613. {
  614. // Try to retrieve it from the db. If we don't find it, use the resolved version
  615. var dbItem = LibraryManager.RetrieveItem(video.Id) as Video;
  616. if (dbItem != null)
  617. {
  618. dbItem.ResolveArgs = video.ResolveArgs;
  619. video = dbItem;
  620. }
  621. return video;
  622. }).ToList();
  623. }
  624. /// <summary>
  625. /// Overrides the base implementation to refresh metadata for local trailers
  626. /// </summary>
  627. /// <param name="cancellationToken">The cancellation token.</param>
  628. /// <param name="forceSave">if set to <c>true</c> [is new item].</param>
  629. /// <param name="forceRefresh">if set to <c>true</c> [force].</param>
  630. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  631. /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param>
  632. /// <returns>true if a provider reports we changed</returns>
  633. public virtual async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  634. {
  635. if (resetResolveArgs)
  636. {
  637. ResolveArgs = null;
  638. }
  639. // Lazy load these again
  640. LocalTrailers = null;
  641. // Refresh for the item
  642. var itemRefreshTask = ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh, allowSlowProviders);
  643. cancellationToken.ThrowIfCancellationRequested();
  644. // Refresh metadata for local trailers
  645. var trailerTasks = LocalTrailers.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  646. cancellationToken.ThrowIfCancellationRequested();
  647. // Await the trailer tasks
  648. await Task.WhenAll(trailerTasks).ConfigureAwait(false);
  649. cancellationToken.ThrowIfCancellationRequested();
  650. // Get the result from the item task
  651. var changed = await itemRefreshTask.ConfigureAwait(false);
  652. if (changed || forceSave)
  653. {
  654. cancellationToken.ThrowIfCancellationRequested();
  655. await LibraryManager.SaveItem(this, cancellationToken).ConfigureAwait(false);
  656. }
  657. return changed;
  658. }
  659. /// <summary>
  660. /// Clear out all metadata properties. Extend for sub-classes.
  661. /// </summary>
  662. public virtual void ClearMetaValues()
  663. {
  664. Images = null;
  665. ForcedSortName = null;
  666. PremiereDate = null;
  667. BackdropImagePaths = null;
  668. OfficialRating = null;
  669. CustomRating = null;
  670. Overview = null;
  671. Taglines = null;
  672. Language = null;
  673. Studios = null;
  674. Genres = null;
  675. CommunityRating = null;
  676. RunTimeTicks = null;
  677. AspectRatio = null;
  678. ProductionYear = null;
  679. ProviderIds = null;
  680. DisplayMediaType = GetType().Name;
  681. ResolveArgs = null;
  682. }
  683. /// <summary>
  684. /// Gets or sets the trailer URL.
  685. /// </summary>
  686. /// <value>The trailer URL.</value>
  687. public List<string> TrailerUrls { get; set; }
  688. /// <summary>
  689. /// Gets or sets the provider ids.
  690. /// </summary>
  691. /// <value>The provider ids.</value>
  692. public Dictionary<string, string> ProviderIds { get; set; }
  693. /// <summary>
  694. /// Override this to false if class should be ignored for indexing purposes
  695. /// </summary>
  696. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  697. [IgnoreDataMember]
  698. public virtual bool IncludeInIndex
  699. {
  700. get { return true; }
  701. }
  702. /// <summary>
  703. /// Override this to true if class should be grouped under a container in indicies
  704. /// The container class should be defined via IndexContainer
  705. /// </summary>
  706. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  707. [IgnoreDataMember]
  708. public virtual bool GroupInIndex
  709. {
  710. get { return false; }
  711. }
  712. /// <summary>
  713. /// Override this to return the folder that should be used to construct a container
  714. /// for this item in an index. GroupInIndex should be true as well.
  715. /// </summary>
  716. /// <value>The index container.</value>
  717. [IgnoreDataMember]
  718. public virtual Folder IndexContainer
  719. {
  720. get { return null; }
  721. }
  722. /// <summary>
  723. /// Gets the user data key.
  724. /// </summary>
  725. /// <returns>System.String.</returns>
  726. public virtual string GetUserDataKey()
  727. {
  728. return Id.ToString();
  729. }
  730. /// <summary>
  731. /// Determines if a given user has access to this item
  732. /// </summary>
  733. /// <param name="user">The user.</param>
  734. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  735. /// <exception cref="System.ArgumentNullException"></exception>
  736. public bool IsParentalAllowed(User user)
  737. {
  738. if (user == null)
  739. {
  740. throw new ArgumentNullException();
  741. }
  742. return user.Configuration.MaxParentalRating == null || Ratings.Level(CustomRating ?? OfficialRating) <= user.Configuration.MaxParentalRating;
  743. }
  744. /// <summary>
  745. /// Determines if this folder should be visible to a given user.
  746. /// Default is just parental allowed. Can be overridden for more functionality.
  747. /// </summary>
  748. /// <param name="user">The user.</param>
  749. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  750. /// <exception cref="System.ArgumentNullException">user</exception>
  751. public virtual bool IsVisible(User user)
  752. {
  753. if (user == null)
  754. {
  755. throw new ArgumentNullException("user");
  756. }
  757. return IsParentalAllowed(user);
  758. }
  759. /// <summary>
  760. /// Finds the particular item by searching through our parents and, if not found there, loading from repo
  761. /// </summary>
  762. /// <param name="id">The id.</param>
  763. /// <returns>BaseItem.</returns>
  764. /// <exception cref="System.ArgumentException"></exception>
  765. protected BaseItem FindParentItem(Guid id)
  766. {
  767. if (id == Guid.Empty)
  768. {
  769. throw new ArgumentException();
  770. }
  771. var parent = Parent;
  772. while (parent != null && !parent.IsRoot)
  773. {
  774. if (parent.Id == id) return parent;
  775. parent = parent.Parent;
  776. }
  777. //not found - load from repo
  778. return LibraryManager.RetrieveItem(id);
  779. }
  780. /// <summary>
  781. /// Gets a value indicating whether this instance is folder.
  782. /// </summary>
  783. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  784. [IgnoreDataMember]
  785. public virtual bool IsFolder
  786. {
  787. get
  788. {
  789. return false;
  790. }
  791. }
  792. /// <summary>
  793. /// Determine if we have changed vs the passed in copy
  794. /// </summary>
  795. /// <param name="copy">The copy.</param>
  796. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  797. /// <exception cref="System.ArgumentNullException"></exception>
  798. public virtual bool HasChanged(BaseItem copy)
  799. {
  800. if (copy == null)
  801. {
  802. throw new ArgumentNullException();
  803. }
  804. var changed = copy.DateModified != DateModified;
  805. if (changed)
  806. {
  807. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  808. }
  809. return changed;
  810. }
  811. /// <summary>
  812. /// Determines if the item is considered new based on user settings
  813. /// </summary>
  814. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  815. /// <exception cref="System.ArgumentNullException"></exception>
  816. public bool IsRecentlyAdded()
  817. {
  818. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  819. }
  820. /// <summary>
  821. /// Adds people to the item
  822. /// </summary>
  823. /// <param name="people">The people.</param>
  824. /// <exception cref="System.ArgumentNullException"></exception>
  825. public void AddPeople(IEnumerable<PersonInfo> people)
  826. {
  827. if (people == null)
  828. {
  829. throw new ArgumentNullException();
  830. }
  831. foreach (var person in people)
  832. {
  833. AddPerson(person);
  834. }
  835. }
  836. /// <summary>
  837. /// Adds a person to the item
  838. /// </summary>
  839. /// <param name="person">The person.</param>
  840. /// <exception cref="System.ArgumentNullException"></exception>
  841. public void AddPerson(PersonInfo person)
  842. {
  843. if (person == null)
  844. {
  845. throw new ArgumentNullException("person");
  846. }
  847. if (string.IsNullOrWhiteSpace(person.Name))
  848. {
  849. throw new ArgumentNullException();
  850. }
  851. if (People == null)
  852. {
  853. People = new List<PersonInfo> { person };
  854. return;
  855. }
  856. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  857. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  858. {
  859. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  860. if (existing != null)
  861. {
  862. existing.Type = PersonType.GuestStar;
  863. return;
  864. }
  865. }
  866. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  867. {
  868. // Only add actors if there isn't an existing one of type Actor or GuestStar
  869. if (!People.Any(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && (p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase) || p.Type.Equals(PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))))
  870. {
  871. People.Add(person);
  872. }
  873. }
  874. else
  875. {
  876. // Check for dupes based on the combination of Name and Type
  877. if (!People.Any(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(person.Type, StringComparison.OrdinalIgnoreCase)))
  878. {
  879. People.Add(person);
  880. }
  881. }
  882. }
  883. /// <summary>
  884. /// Adds studios to the item
  885. /// </summary>
  886. /// <param name="studios">The studios.</param>
  887. /// <exception cref="System.ArgumentNullException"></exception>
  888. public void AddStudios(IEnumerable<string> studios)
  889. {
  890. if (studios == null)
  891. {
  892. throw new ArgumentNullException();
  893. }
  894. foreach (var name in studios)
  895. {
  896. AddStudio(name);
  897. }
  898. }
  899. /// <summary>
  900. /// Adds a studio to the item
  901. /// </summary>
  902. /// <param name="name">The name.</param>
  903. /// <exception cref="System.ArgumentNullException"></exception>
  904. public void AddStudio(string name)
  905. {
  906. if (string.IsNullOrWhiteSpace(name))
  907. {
  908. throw new ArgumentNullException("name");
  909. }
  910. if (Studios == null)
  911. {
  912. Studios = new List<string>();
  913. }
  914. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  915. {
  916. Studios.Add(name);
  917. }
  918. }
  919. /// <summary>
  920. /// Adds a tagline to the item
  921. /// </summary>
  922. /// <param name="name">The name.</param>
  923. /// <exception cref="System.ArgumentNullException"></exception>
  924. public void AddTagline(string name)
  925. {
  926. if (string.IsNullOrWhiteSpace(name))
  927. {
  928. throw new ArgumentNullException("name");
  929. }
  930. if (Taglines == null)
  931. {
  932. Taglines = new List<string>();
  933. }
  934. if (!Taglines.Contains(name, StringComparer.OrdinalIgnoreCase))
  935. {
  936. Taglines.Add(name);
  937. }
  938. }
  939. /// <summary>
  940. /// Adds a TrailerUrl to the item
  941. /// </summary>
  942. /// <param name="url">The URL.</param>
  943. /// <exception cref="System.ArgumentNullException"></exception>
  944. public void AddTrailerUrl(string url)
  945. {
  946. if (string.IsNullOrWhiteSpace(url))
  947. {
  948. throw new ArgumentNullException("url");
  949. }
  950. if (TrailerUrls == null)
  951. {
  952. TrailerUrls = new List<string>();
  953. }
  954. if (!TrailerUrls.Contains(url, StringComparer.OrdinalIgnoreCase))
  955. {
  956. TrailerUrls.Add(url);
  957. }
  958. }
  959. /// <summary>
  960. /// Adds a genre to the item
  961. /// </summary>
  962. /// <param name="name">The name.</param>
  963. /// <exception cref="System.ArgumentNullException"></exception>
  964. public void AddGenre(string name)
  965. {
  966. if (string.IsNullOrWhiteSpace(name))
  967. {
  968. throw new ArgumentNullException("name");
  969. }
  970. if (Genres == null)
  971. {
  972. Genres = new List<string>();
  973. }
  974. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  975. {
  976. Genres.Add(name);
  977. }
  978. }
  979. /// <summary>
  980. /// Adds the production location.
  981. /// </summary>
  982. /// <param name="location">The location.</param>
  983. /// <exception cref="System.ArgumentNullException">location</exception>
  984. public void AddProductionLocation(string location)
  985. {
  986. if (string.IsNullOrWhiteSpace(location))
  987. {
  988. throw new ArgumentNullException("location");
  989. }
  990. if (ProductionLocations == null)
  991. {
  992. ProductionLocations = new List<string>();
  993. }
  994. if (!ProductionLocations.Contains(location, StringComparer.OrdinalIgnoreCase))
  995. {
  996. ProductionLocations.Add(location);
  997. }
  998. }
  999. /// <summary>
  1000. /// Adds genres to the item
  1001. /// </summary>
  1002. /// <param name="genres">The genres.</param>
  1003. /// <exception cref="System.ArgumentNullException"></exception>
  1004. public void AddGenres(IEnumerable<string> genres)
  1005. {
  1006. if (genres == null)
  1007. {
  1008. throw new ArgumentNullException();
  1009. }
  1010. foreach (var name in genres)
  1011. {
  1012. AddGenre(name);
  1013. }
  1014. }
  1015. /// <summary>
  1016. /// Marks the item as either played or unplayed
  1017. /// </summary>
  1018. /// <param name="user">The user.</param>
  1019. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  1020. /// <param name="userManager">The user manager.</param>
  1021. /// <returns>Task.</returns>
  1022. /// <exception cref="System.ArgumentNullException"></exception>
  1023. public virtual async Task SetPlayedStatus(User user, bool wasPlayed, IUserDataRepository userManager)
  1024. {
  1025. if (user == null)
  1026. {
  1027. throw new ArgumentNullException();
  1028. }
  1029. var key = GetUserDataKey();
  1030. var data = await userManager.GetUserData(user.Id, key).ConfigureAwait(false);
  1031. if (wasPlayed)
  1032. {
  1033. data.PlayCount = Math.Max(data.PlayCount, 1);
  1034. if (!data.LastPlayedDate.HasValue)
  1035. {
  1036. data.LastPlayedDate = DateTime.UtcNow;
  1037. }
  1038. }
  1039. else
  1040. {
  1041. //I think it is okay to do this here.
  1042. // if this is only called when a user is manually forcing something to un-played
  1043. // then it probably is what we want to do...
  1044. data.PlayCount = 0;
  1045. data.PlaybackPositionTicks = 0;
  1046. data.LastPlayedDate = null;
  1047. }
  1048. data.Played = wasPlayed;
  1049. await userManager.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  1050. }
  1051. /// <summary>
  1052. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1053. /// </summary>
  1054. /// <returns>Task.</returns>
  1055. public virtual Task ChangedExternally()
  1056. {
  1057. return RefreshMetadata(CancellationToken.None);
  1058. }
  1059. /// <summary>
  1060. /// Finds a parent of a given type
  1061. /// </summary>
  1062. /// <typeparam name="T"></typeparam>
  1063. /// <returns>``0.</returns>
  1064. public T FindParent<T>()
  1065. where T : Folder
  1066. {
  1067. var parent = Parent;
  1068. while (parent != null)
  1069. {
  1070. var result = parent as T;
  1071. if (result != null)
  1072. {
  1073. return result;
  1074. }
  1075. parent = parent.Parent;
  1076. }
  1077. return null;
  1078. }
  1079. /// <summary>
  1080. /// Gets an image
  1081. /// </summary>
  1082. /// <param name="type">The type.</param>
  1083. /// <returns>System.String.</returns>
  1084. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1085. public string GetImage(ImageType type)
  1086. {
  1087. if (type == ImageType.Backdrop)
  1088. {
  1089. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1090. }
  1091. if (type == ImageType.Screenshot)
  1092. {
  1093. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1094. }
  1095. if (Images == null)
  1096. {
  1097. return null;
  1098. }
  1099. string val;
  1100. Images.TryGetValue(type.ToString(), out val);
  1101. return val;
  1102. }
  1103. /// <summary>
  1104. /// Gets an image
  1105. /// </summary>
  1106. /// <param name="type">The type.</param>
  1107. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1108. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1109. public bool HasImage(ImageType type)
  1110. {
  1111. if (type == ImageType.Backdrop)
  1112. {
  1113. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1114. }
  1115. if (type == ImageType.Screenshot)
  1116. {
  1117. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1118. }
  1119. return !string.IsNullOrEmpty(GetImage(type));
  1120. }
  1121. /// <summary>
  1122. /// Sets an image
  1123. /// </summary>
  1124. /// <param name="type">The type.</param>
  1125. /// <param name="path">The path.</param>
  1126. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1127. public void SetImage(ImageType type, string path)
  1128. {
  1129. if (type == ImageType.Backdrop)
  1130. {
  1131. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1132. }
  1133. if (type == ImageType.Screenshot)
  1134. {
  1135. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1136. }
  1137. var typeKey = type.ToString();
  1138. // If it's null remove the key from the dictionary
  1139. if (string.IsNullOrEmpty(path))
  1140. {
  1141. if (Images != null)
  1142. {
  1143. if (Images.ContainsKey(typeKey))
  1144. {
  1145. Images.Remove(typeKey);
  1146. }
  1147. }
  1148. }
  1149. else
  1150. {
  1151. // Ensure it exists
  1152. if (Images == null)
  1153. {
  1154. Images = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  1155. }
  1156. Images[typeKey] = path;
  1157. }
  1158. }
  1159. /// <summary>
  1160. /// Deletes the image.
  1161. /// </summary>
  1162. /// <param name="type">The type.</param>
  1163. /// <returns>Task.</returns>
  1164. public async Task DeleteImage(ImageType type)
  1165. {
  1166. if (!HasImage(type))
  1167. {
  1168. return;
  1169. }
  1170. // Delete the source file
  1171. File.Delete(GetImage(type));
  1172. // Remove it from the item
  1173. SetImage(type, null);
  1174. // Refresh metadata
  1175. await RefreshMetadata(CancellationToken.None).ConfigureAwait(false);
  1176. }
  1177. }
  1178. }