BaseItem.cs 44 KB

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