BaseItem.cs 43 KB

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