BaseItem.cs 45 KB

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