BaseItem.cs 43 KB

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