BaseItem.cs 44 KB

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