BaseItem.cs 44 KB

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