BaseItem.cs 43 KB

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