BaseItem.cs 43 KB

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