BaseItem.cs 44 KB

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