BaseItem.cs 44 KB

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