BaseItem.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.IO;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.Localization;
  6. using MediaBrowser.Controller.Providers;
  7. using MediaBrowser.Controller.Resolvers;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Runtime.Serialization;
  15. using System.Text;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Controller.Entities
  19. {
  20. /// <summary>
  21. /// Class BaseItem
  22. /// </summary>
  23. public abstract class BaseItem : IHasProviderIds
  24. {
  25. /// <summary>
  26. /// The trailer folder name
  27. /// </summary>
  28. public const string TrailerFolderName = "trailers";
  29. /// <summary>
  30. /// Gets or sets the name.
  31. /// </summary>
  32. /// <value>The name.</value>
  33. public virtual string Name { get; set; }
  34. /// <summary>
  35. /// Gets or sets the id.
  36. /// </summary>
  37. /// <value>The id.</value>
  38. public virtual Guid Id { get; set; }
  39. /// <summary>
  40. /// Gets or sets the path.
  41. /// </summary>
  42. /// <value>The path.</value>
  43. public virtual string Path { get; set; }
  44. /// <summary>
  45. /// Gets or sets the type of the location.
  46. /// </summary>
  47. /// <value>The type of the location.</value>
  48. public virtual LocationType LocationType
  49. {
  50. get
  51. {
  52. if (string.IsNullOrEmpty(Path))
  53. {
  54. return LocationType.Virtual;
  55. }
  56. return System.IO.Path.IsPathRooted(Path) ? LocationType.FileSystem : LocationType.Remote;
  57. }
  58. }
  59. /// <summary>
  60. /// This is just a helper for convenience
  61. /// </summary>
  62. /// <value>The primary image path.</value>
  63. [IgnoreDataMember]
  64. public string PrimaryImagePath
  65. {
  66. get { return GetImage(ImageType.Primary); }
  67. set { SetImage(ImageType.Primary, value); }
  68. }
  69. /// <summary>
  70. /// Gets or sets the images.
  71. /// </summary>
  72. /// <value>The images.</value>
  73. public virtual Dictionary<string, string> Images { get; set; }
  74. /// <summary>
  75. /// Gets or sets the date created.
  76. /// </summary>
  77. /// <value>The date created.</value>
  78. public DateTime DateCreated { get; set; }
  79. /// <summary>
  80. /// Gets or sets the date modified.
  81. /// </summary>
  82. /// <value>The date modified.</value>
  83. public DateTime DateModified { get; set; }
  84. /// <summary>
  85. /// The logger
  86. /// </summary>
  87. public static ILogger Logger { get; set; }
  88. public static ILibraryManager LibraryManager { get; set; }
  89. public static IServerConfigurationManager ConfigurationManager { get; set; }
  90. public static IProviderManager ProviderManager { get; 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 (LocationType != LocationType.FileSystem || 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 forced sort.
  330. /// </summary>
  331. /// <value>The name of the forced sort.</value>
  332. public string ForcedSortName { get; set; }
  333. private string _sortName;
  334. /// <summary>
  335. /// Gets or sets the name of the sort.
  336. /// </summary>
  337. /// <value>The name of the sort.</value>
  338. [IgnoreDataMember]
  339. public string SortName
  340. {
  341. get
  342. {
  343. return ForcedSortName ?? _sortName ?? (_sortName = CreateSortName());
  344. }
  345. }
  346. /// <summary>
  347. /// Creates the name of the sort.
  348. /// </summary>
  349. /// <returns>System.String.</returns>
  350. protected virtual string CreateSortName()
  351. {
  352. if (Name == null) return null; //some items may not have name filled in properly
  353. var sortable = Name.Trim().ToLower();
  354. sortable = ConfigurationManager.Configuration.SortRemoveCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), string.Empty));
  355. sortable = ConfigurationManager.Configuration.SortReplaceCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), " "));
  356. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  357. {
  358. var searchLower = search.ToLower();
  359. // Remove from beginning if a space follows
  360. if (sortable.StartsWith(searchLower + " "))
  361. {
  362. sortable = sortable.Remove(0, searchLower.Length + 1);
  363. }
  364. // Remove from middle if surrounded by spaces
  365. sortable = sortable.Replace(" " + searchLower + " ", " ");
  366. // Remove from end if followed by a space
  367. if (sortable.EndsWith(" " + searchLower))
  368. {
  369. sortable = sortable.Remove(sortable.Length - (searchLower.Length + 1));
  370. }
  371. }
  372. return sortable;
  373. }
  374. /// <summary>
  375. /// Gets or sets the parent.
  376. /// </summary>
  377. /// <value>The parent.</value>
  378. [IgnoreDataMember]
  379. public Folder Parent { get; set; }
  380. /// <summary>
  381. /// Gets the collection folder parent.
  382. /// </summary>
  383. /// <value>The collection folder parent.</value>
  384. [IgnoreDataMember]
  385. public Folder CollectionFolder
  386. {
  387. get
  388. {
  389. if (this is AggregateFolder)
  390. {
  391. return null;
  392. }
  393. if (IsFolder)
  394. {
  395. var iCollectionFolder = this as ICollectionFolder;
  396. if (iCollectionFolder != null)
  397. {
  398. return (Folder)this;
  399. }
  400. }
  401. var parent = Parent;
  402. while (parent != null)
  403. {
  404. var iCollectionFolder = parent as ICollectionFolder;
  405. if (iCollectionFolder != null)
  406. {
  407. return parent;
  408. }
  409. parent = parent.Parent;
  410. }
  411. return null;
  412. }
  413. }
  414. /// <summary>
  415. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  416. /// </summary>
  417. /// <value>The premiere date.</value>
  418. public DateTime? PremiereDate { get; set; }
  419. /// <summary>
  420. /// Gets or sets the display type of the media.
  421. /// </summary>
  422. /// <value>The display type of the media.</value>
  423. public virtual string DisplayMediaType { get; set; }
  424. /// <summary>
  425. /// Gets or sets the backdrop image paths.
  426. /// </summary>
  427. /// <value>The backdrop image paths.</value>
  428. public List<string> BackdropImagePaths { get; set; }
  429. /// <summary>
  430. /// Gets or sets the screenshot image paths.
  431. /// </summary>
  432. /// <value>The screenshot image paths.</value>
  433. public List<string> ScreenshotImagePaths { get; set; }
  434. /// <summary>
  435. /// Gets or sets the official rating.
  436. /// </summary>
  437. /// <value>The official rating.</value>
  438. public virtual string OfficialRating { get; set; }
  439. /// <summary>
  440. /// Gets or sets the custom rating.
  441. /// </summary>
  442. /// <value>The custom rating.</value>
  443. public virtual string CustomRating { get; set; }
  444. /// <summary>
  445. /// Gets or sets the language.
  446. /// </summary>
  447. /// <value>The language.</value>
  448. public string Language { get; set; }
  449. /// <summary>
  450. /// Gets or sets the overview.
  451. /// </summary>
  452. /// <value>The overview.</value>
  453. public string Overview { get; set; }
  454. /// <summary>
  455. /// Gets or sets the taglines.
  456. /// </summary>
  457. /// <value>The taglines.</value>
  458. public List<string> Taglines { get; set; }
  459. /// <summary>
  460. /// Gets or sets the people.
  461. /// </summary>
  462. /// <value>The people.</value>
  463. public List<PersonInfo> People { get; set; }
  464. /// <summary>
  465. /// Override this if you need to combine/collapse person information
  466. /// </summary>
  467. /// <value>All people.</value>
  468. [IgnoreDataMember]
  469. public virtual IEnumerable<PersonInfo> AllPeople
  470. {
  471. get { return People; }
  472. }
  473. /// <summary>
  474. /// Gets or sets the studios.
  475. /// </summary>
  476. /// <value>The studios.</value>
  477. public virtual List<string> Studios { get; set; }
  478. /// <summary>
  479. /// Gets or sets the genres.
  480. /// </summary>
  481. /// <value>The genres.</value>
  482. public virtual List<string> Genres { get; set; }
  483. /// <summary>
  484. /// Gets or sets the community rating.
  485. /// </summary>
  486. /// <value>The community rating.</value>
  487. public float? CommunityRating { get; set; }
  488. /// <summary>
  489. /// Gets or sets the run time ticks.
  490. /// </summary>
  491. /// <value>The run time ticks.</value>
  492. public long? RunTimeTicks { get; set; }
  493. /// <summary>
  494. /// Gets or sets the aspect ratio.
  495. /// </summary>
  496. /// <value>The aspect ratio.</value>
  497. public string AspectRatio { get; set; }
  498. /// <summary>
  499. /// Gets or sets the production year.
  500. /// </summary>
  501. /// <value>The production year.</value>
  502. public virtual int? ProductionYear { get; set; }
  503. /// <summary>
  504. /// If the item is part of a series, this is it's number in the series.
  505. /// This could be episode number, album track number, etc.
  506. /// </summary>
  507. /// <value>The index number.</value>
  508. public int? IndexNumber { get; set; }
  509. /// <summary>
  510. /// For an episode this could be the season number, or for a song this could be the disc number.
  511. /// </summary>
  512. /// <value>The parent index number.</value>
  513. public int? ParentIndexNumber { get; set; }
  514. /// <summary>
  515. /// The _local trailers
  516. /// </summary>
  517. private List<Video> _localTrailers;
  518. /// <summary>
  519. /// The _local trailers initialized
  520. /// </summary>
  521. private bool _localTrailersInitialized;
  522. /// <summary>
  523. /// The _local trailers sync lock
  524. /// </summary>
  525. private object _localTrailersSyncLock = new object();
  526. /// <summary>
  527. /// Gets the local trailers.
  528. /// </summary>
  529. /// <value>The local trailers.</value>
  530. [IgnoreDataMember]
  531. public List<Video> LocalTrailers
  532. {
  533. get
  534. {
  535. LazyInitializer.EnsureInitialized(ref _localTrailers, ref _localTrailersInitialized, ref _localTrailersSyncLock, LoadLocalTrailers);
  536. return _localTrailers;
  537. }
  538. private set
  539. {
  540. _localTrailers = value;
  541. if (value == null)
  542. {
  543. _localTrailersInitialized = false;
  544. }
  545. }
  546. }
  547. /// <summary>
  548. /// Loads local trailers from the file system
  549. /// </summary>
  550. /// <returns>List{Video}.</returns>
  551. private List<Video> LoadLocalTrailers()
  552. {
  553. ItemResolveArgs resolveArgs;
  554. try
  555. {
  556. resolveArgs = ResolveArgs;
  557. }
  558. catch (IOException ex)
  559. {
  560. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  561. return new List<Video>();
  562. }
  563. if (!resolveArgs.IsDirectory)
  564. {
  565. return new List<Video>();
  566. }
  567. var folder = resolveArgs.GetFileSystemEntryByName(TrailerFolderName);
  568. // Path doesn't exist. No biggie
  569. if (folder == null)
  570. {
  571. return new List<Video>();
  572. }
  573. IEnumerable<WIN32_FIND_DATA> files;
  574. try
  575. {
  576. files = FileSystem.GetFiles(folder.Value.Path);
  577. }
  578. catch (IOException ex)
  579. {
  580. Logger.ErrorException("Error loading trailers for {0}", ex, Name);
  581. return new List<Video>();
  582. }
  583. return LibraryManager.ResolvePaths<Video>(files, null).Select(video =>
  584. {
  585. // Try to retrieve it from the db. If we don't find it, use the resolved version
  586. var dbItem = LibraryManager.RetrieveItem(video.Id) as Video;
  587. if (dbItem != null)
  588. {
  589. dbItem.ResolveArgs = video.ResolveArgs;
  590. video = dbItem;
  591. }
  592. return video;
  593. }).ToList();
  594. }
  595. /// <summary>
  596. /// Overrides the base implementation to refresh metadata for local trailers
  597. /// </summary>
  598. /// <param name="cancellationToken">The cancellation token.</param>
  599. /// <param name="forceSave">if set to <c>true</c> [is new item].</param>
  600. /// <param name="forceRefresh">if set to <c>true</c> [force].</param>
  601. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  602. /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param>
  603. /// <returns>true if a provider reports we changed</returns>
  604. public virtual async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  605. {
  606. if (resetResolveArgs)
  607. {
  608. ResolveArgs = null;
  609. }
  610. // Lazy load these again
  611. LocalTrailers = null;
  612. // Refresh for the item
  613. var itemRefreshTask = ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh, allowSlowProviders);
  614. cancellationToken.ThrowIfCancellationRequested();
  615. // Refresh metadata for local trailers
  616. var trailerTasks = LocalTrailers.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  617. cancellationToken.ThrowIfCancellationRequested();
  618. // Await the trailer tasks
  619. await Task.WhenAll(trailerTasks).ConfigureAwait(false);
  620. cancellationToken.ThrowIfCancellationRequested();
  621. // Get the result from the item task
  622. var changed = await itemRefreshTask.ConfigureAwait(false);
  623. if (changed || forceSave)
  624. {
  625. cancellationToken.ThrowIfCancellationRequested();
  626. await LibraryManager.SaveItem(this, cancellationToken).ConfigureAwait(false);
  627. }
  628. return changed;
  629. }
  630. /// <summary>
  631. /// Clear out all metadata properties. Extend for sub-classes.
  632. /// </summary>
  633. public virtual void ClearMetaValues()
  634. {
  635. Images = null;
  636. ForcedSortName = null;
  637. PremiereDate = null;
  638. BackdropImagePaths = null;
  639. OfficialRating = null;
  640. CustomRating = null;
  641. Overview = null;
  642. Taglines = null;
  643. Language = null;
  644. Studios = null;
  645. Genres = null;
  646. CommunityRating = null;
  647. RunTimeTicks = null;
  648. AspectRatio = null;
  649. ProductionYear = null;
  650. ProviderIds = null;
  651. DisplayMediaType = GetType().Name;
  652. ResolveArgs = null;
  653. }
  654. /// <summary>
  655. /// Gets or sets the trailer URL.
  656. /// </summary>
  657. /// <value>The trailer URL.</value>
  658. public List<string> TrailerUrls { get; set; }
  659. /// <summary>
  660. /// Gets or sets the provider ids.
  661. /// </summary>
  662. /// <value>The provider ids.</value>
  663. public Dictionary<string, string> ProviderIds { get; set; }
  664. /// <summary>
  665. /// Override this to false if class should be ignored for indexing purposes
  666. /// </summary>
  667. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  668. [IgnoreDataMember]
  669. public virtual bool IncludeInIndex
  670. {
  671. get { return true; }
  672. }
  673. /// <summary>
  674. /// Override this to true if class should be grouped under a container in indicies
  675. /// The container class should be defined via IndexContainer
  676. /// </summary>
  677. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  678. [IgnoreDataMember]
  679. public virtual bool GroupInIndex
  680. {
  681. get { return false; }
  682. }
  683. /// <summary>
  684. /// Override this to return the folder that should be used to construct a container
  685. /// for this item in an index. GroupInIndex should be true as well.
  686. /// </summary>
  687. /// <value>The index container.</value>
  688. [IgnoreDataMember]
  689. public virtual Folder IndexContainer
  690. {
  691. get { return null; }
  692. }
  693. /// <summary>
  694. /// The _user data id
  695. /// </summary>
  696. protected Guid _userDataId; //cache this so it doesn't have to be re-constructed on every reference
  697. /// <summary>
  698. /// Return the id that should be used to key user data for this item.
  699. /// Default is just this Id but subclasses can use provider Ids for transportability.
  700. /// </summary>
  701. /// <value>The user data id.</value>
  702. [IgnoreDataMember]
  703. public virtual Guid UserDataId
  704. {
  705. get
  706. {
  707. return _userDataId == Guid.Empty ? (_userDataId = Id) : _userDataId;
  708. }
  709. }
  710. /// <summary>
  711. /// Determines if a given user has access to this item
  712. /// </summary>
  713. /// <param name="user">The user.</param>
  714. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  715. /// <exception cref="System.ArgumentNullException"></exception>
  716. public bool IsParentalAllowed(User user)
  717. {
  718. if (user == null)
  719. {
  720. throw new ArgumentNullException();
  721. }
  722. return user.Configuration.MaxParentalRating == null || Ratings.Level(CustomRating ?? OfficialRating) <= user.Configuration.MaxParentalRating;
  723. }
  724. /// <summary>
  725. /// Determines if this folder should be visible to a given user.
  726. /// Default is just parental allowed. Can be overridden for more functionality.
  727. /// </summary>
  728. /// <param name="user">The user.</param>
  729. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  730. /// <exception cref="System.ArgumentNullException">user</exception>
  731. public virtual bool IsVisible(User user)
  732. {
  733. if (user == null)
  734. {
  735. throw new ArgumentNullException("user");
  736. }
  737. return IsParentalAllowed(user);
  738. }
  739. /// <summary>
  740. /// Finds the particular item by searching through our parents and, if not found there, loading from repo
  741. /// </summary>
  742. /// <param name="id">The id.</param>
  743. /// <returns>BaseItem.</returns>
  744. /// <exception cref="System.ArgumentException"></exception>
  745. protected BaseItem FindParentItem(Guid id)
  746. {
  747. if (id == Guid.Empty)
  748. {
  749. throw new ArgumentException();
  750. }
  751. var parent = Parent;
  752. while (parent != null && !parent.IsRoot)
  753. {
  754. if (parent.Id == id) return parent;
  755. parent = parent.Parent;
  756. }
  757. //not found - load from repo
  758. return LibraryManager.RetrieveItem(id);
  759. }
  760. /// <summary>
  761. /// Gets a value indicating whether this instance is folder.
  762. /// </summary>
  763. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  764. [IgnoreDataMember]
  765. public virtual bool IsFolder
  766. {
  767. get
  768. {
  769. return false;
  770. }
  771. }
  772. /// <summary>
  773. /// Determine if we have changed vs the passed in copy
  774. /// </summary>
  775. /// <param name="copy">The copy.</param>
  776. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  777. /// <exception cref="System.ArgumentNullException"></exception>
  778. public virtual bool HasChanged(BaseItem copy)
  779. {
  780. if (copy == null)
  781. {
  782. throw new ArgumentNullException();
  783. }
  784. var changed = copy.DateModified != DateModified;
  785. if (changed)
  786. {
  787. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  788. }
  789. return changed;
  790. }
  791. /// <summary>
  792. /// Determines if the item is considered new based on user settings
  793. /// </summary>
  794. /// <param name="user">The user.</param>
  795. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  796. /// <exception cref="System.ArgumentNullException"></exception>
  797. public bool IsRecentlyAdded(User user)
  798. {
  799. if (user == null)
  800. {
  801. throw new ArgumentNullException();
  802. }
  803. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  804. }
  805. /// <summary>
  806. /// Adds people to the item
  807. /// </summary>
  808. /// <param name="people">The people.</param>
  809. /// <exception cref="System.ArgumentNullException"></exception>
  810. public void AddPeople(IEnumerable<PersonInfo> people)
  811. {
  812. if (people == null)
  813. {
  814. throw new ArgumentNullException();
  815. }
  816. foreach (var person in people)
  817. {
  818. AddPerson(person);
  819. }
  820. }
  821. /// <summary>
  822. /// Adds a person to the item
  823. /// </summary>
  824. /// <param name="person">The person.</param>
  825. /// <exception cref="System.ArgumentNullException"></exception>
  826. public void AddPerson(PersonInfo person)
  827. {
  828. if (person == null)
  829. {
  830. throw new ArgumentNullException();
  831. }
  832. if (string.IsNullOrWhiteSpace(person.Name))
  833. {
  834. throw new ArgumentNullException();
  835. }
  836. if (People == null)
  837. {
  838. People = new List<PersonInfo>();
  839. }
  840. // Check for dupes based on the combination of Name and Type
  841. if (!People.Any(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(person.Type, StringComparison.OrdinalIgnoreCase)))
  842. {
  843. People.Add(person);
  844. }
  845. }
  846. /// <summary>
  847. /// Adds studios to the item
  848. /// </summary>
  849. /// <param name="studios">The studios.</param>
  850. /// <exception cref="System.ArgumentNullException"></exception>
  851. public void AddStudios(IEnumerable<string> studios)
  852. {
  853. if (studios == null)
  854. {
  855. throw new ArgumentNullException();
  856. }
  857. foreach (var name in studios)
  858. {
  859. AddStudio(name);
  860. }
  861. }
  862. /// <summary>
  863. /// Adds a studio to the item
  864. /// </summary>
  865. /// <param name="name">The name.</param>
  866. /// <exception cref="System.ArgumentNullException"></exception>
  867. public void AddStudio(string name)
  868. {
  869. if (string.IsNullOrWhiteSpace(name))
  870. {
  871. throw new ArgumentNullException("name");
  872. }
  873. if (Studios == null)
  874. {
  875. Studios = new List<string>();
  876. }
  877. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  878. {
  879. Studios.Add(name);
  880. }
  881. }
  882. /// <summary>
  883. /// Adds a tagline to the item
  884. /// </summary>
  885. /// <param name="name">The name.</param>
  886. /// <exception cref="System.ArgumentNullException"></exception>
  887. public void AddTagline(string name)
  888. {
  889. if (string.IsNullOrWhiteSpace(name))
  890. {
  891. throw new ArgumentNullException("name");
  892. }
  893. if (Taglines == null)
  894. {
  895. Taglines = new List<string>();
  896. }
  897. if (!Taglines.Contains(name, StringComparer.OrdinalIgnoreCase))
  898. {
  899. Taglines.Add(name);
  900. }
  901. }
  902. /// <summary>
  903. /// Adds a TrailerUrl to the item
  904. /// </summary>
  905. /// <param name="url">The URL.</param>
  906. /// <exception cref="System.ArgumentNullException"></exception>
  907. public void AddTrailerUrl(string url)
  908. {
  909. if (string.IsNullOrWhiteSpace(url))
  910. {
  911. throw new ArgumentNullException("url");
  912. }
  913. if (TrailerUrls == null)
  914. {
  915. TrailerUrls = new List<string>();
  916. }
  917. if (!TrailerUrls.Contains(url, StringComparer.OrdinalIgnoreCase))
  918. {
  919. TrailerUrls.Add(url);
  920. }
  921. }
  922. /// <summary>
  923. /// Adds a genre to the item
  924. /// </summary>
  925. /// <param name="name">The name.</param>
  926. /// <exception cref="System.ArgumentNullException"></exception>
  927. public void AddGenre(string name)
  928. {
  929. if (string.IsNullOrWhiteSpace(name))
  930. {
  931. throw new ArgumentNullException();
  932. }
  933. if (Genres == null)
  934. {
  935. Genres = new List<string>();
  936. }
  937. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  938. {
  939. Genres.Add(name);
  940. }
  941. }
  942. /// <summary>
  943. /// Adds genres to the item
  944. /// </summary>
  945. /// <param name="genres">The genres.</param>
  946. /// <exception cref="System.ArgumentNullException"></exception>
  947. public void AddGenres(IEnumerable<string> genres)
  948. {
  949. if (genres == null)
  950. {
  951. throw new ArgumentNullException();
  952. }
  953. foreach (var name in genres)
  954. {
  955. AddGenre(name);
  956. }
  957. }
  958. /// <summary>
  959. /// Marks the item as either played or unplayed
  960. /// </summary>
  961. /// <param name="user">The user.</param>
  962. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  963. /// <param name="userManager">The user manager.</param>
  964. /// <returns>Task.</returns>
  965. /// <exception cref="System.ArgumentNullException"></exception>
  966. public virtual async Task SetPlayedStatus(User user, bool wasPlayed, IUserManager userManager)
  967. {
  968. if (user == null)
  969. {
  970. throw new ArgumentNullException();
  971. }
  972. var data = await userManager.GetUserData(user.Id, UserDataId).ConfigureAwait(false);
  973. if (wasPlayed)
  974. {
  975. data.PlayCount = Math.Max(data.PlayCount, 1);
  976. if (!data.LastPlayedDate.HasValue)
  977. {
  978. data.LastPlayedDate = DateTime.UtcNow;
  979. }
  980. }
  981. else
  982. {
  983. //I think it is okay to do this here.
  984. // if this is only called when a user is manually forcing something to un-played
  985. // then it probably is what we want to do...
  986. data.PlayCount = 0;
  987. data.PlaybackPositionTicks = 0;
  988. data.LastPlayedDate = null;
  989. }
  990. data.Played = wasPlayed;
  991. await userManager.SaveUserData(user.Id, UserDataId, data, CancellationToken.None).ConfigureAwait(false);
  992. }
  993. /// <summary>
  994. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  995. /// </summary>
  996. /// <returns>Task.</returns>
  997. public virtual Task ChangedExternally()
  998. {
  999. return RefreshMetadata(CancellationToken.None);
  1000. }
  1001. /// <summary>
  1002. /// Finds a parent of a given type
  1003. /// </summary>
  1004. /// <typeparam name="T"></typeparam>
  1005. /// <returns>``0.</returns>
  1006. public T FindParent<T>()
  1007. where T : Folder
  1008. {
  1009. var parent = Parent;
  1010. while (parent != null)
  1011. {
  1012. var result = parent as T;
  1013. if (result != null)
  1014. {
  1015. return result;
  1016. }
  1017. parent = parent.Parent;
  1018. }
  1019. return null;
  1020. }
  1021. /// <summary>
  1022. /// Gets an image
  1023. /// </summary>
  1024. /// <param name="type">The type.</param>
  1025. /// <returns>System.String.</returns>
  1026. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1027. public string GetImage(ImageType type)
  1028. {
  1029. if (type == ImageType.Backdrop)
  1030. {
  1031. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1032. }
  1033. if (type == ImageType.Screenshot)
  1034. {
  1035. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1036. }
  1037. if (Images == null)
  1038. {
  1039. return null;
  1040. }
  1041. string val;
  1042. Images.TryGetValue(type.ToString(), out val);
  1043. return val;
  1044. }
  1045. /// <summary>
  1046. /// Gets an image
  1047. /// </summary>
  1048. /// <param name="type">The type.</param>
  1049. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1050. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1051. public bool HasImage(ImageType type)
  1052. {
  1053. if (type == ImageType.Backdrop)
  1054. {
  1055. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1056. }
  1057. if (type == ImageType.Screenshot)
  1058. {
  1059. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1060. }
  1061. return !string.IsNullOrEmpty(GetImage(type));
  1062. }
  1063. /// <summary>
  1064. /// Sets an image
  1065. /// </summary>
  1066. /// <param name="type">The type.</param>
  1067. /// <param name="path">The path.</param>
  1068. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1069. public void SetImage(ImageType type, string path)
  1070. {
  1071. if (type == ImageType.Backdrop)
  1072. {
  1073. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1074. }
  1075. if (type == ImageType.Screenshot)
  1076. {
  1077. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1078. }
  1079. var typeKey = type.ToString();
  1080. // If it's null remove the key from the dictionary
  1081. if (string.IsNullOrEmpty(path))
  1082. {
  1083. if (Images != null)
  1084. {
  1085. if (Images.ContainsKey(typeKey))
  1086. {
  1087. Images.Remove(typeKey);
  1088. }
  1089. }
  1090. }
  1091. else
  1092. {
  1093. // Ensure it exists
  1094. if (Images == null)
  1095. {
  1096. Images = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  1097. }
  1098. Images[typeKey] = path;
  1099. }
  1100. }
  1101. /// <summary>
  1102. /// Deletes the image.
  1103. /// </summary>
  1104. /// <param name="type">The type.</param>
  1105. /// <returns>Task.</returns>
  1106. public async Task DeleteImage(ImageType type)
  1107. {
  1108. if (!HasImage(type))
  1109. {
  1110. return;
  1111. }
  1112. // Delete the source file
  1113. File.Delete(GetImage(type));
  1114. // Remove it from the item
  1115. SetImage(type, null);
  1116. // Refresh metadata
  1117. await RefreshMetadata(CancellationToken.None).ConfigureAwait(false);
  1118. }
  1119. }
  1120. }