BaseItem.cs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  1. using MediaBrowser.Controller.Configuration;
  2. using MediaBrowser.Controller.IO;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Controller.Localization;
  5. using MediaBrowser.Controller.Persistence;
  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 string _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 string FileSystemStamp
  175. {
  176. get
  177. {
  178. return _fileSystemStamp ?? (_fileSystemStamp = GetFileSystemStamp());
  179. }
  180. }
  181. /// <summary>
  182. /// Gets the type of the media.
  183. /// </summary>
  184. /// <value>The type of the media.</value>
  185. [IgnoreDataMember]
  186. public virtual string MediaType
  187. {
  188. get
  189. {
  190. return null;
  191. }
  192. }
  193. /// <summary>
  194. /// Gets a directory stamp, in the form of a string, that can be used for
  195. /// comparison purposes to determine if the file system entries for this item have changed.
  196. /// </summary>
  197. /// <returns>Guid.</returns>
  198. private string GetFileSystemStamp()
  199. {
  200. // If there's no path or the item is a file, there's nothing to do
  201. if (LocationType != LocationType.FileSystem || !ResolveArgs.IsDirectory)
  202. {
  203. return string.Empty;
  204. }
  205. var sb = new StringBuilder();
  206. // Record the name of each file
  207. // Need to sort these because accoring to msdn docs, our i/o methods are not guaranteed in any order
  208. foreach (var file in ResolveArgs.FileSystemChildren.OrderBy(f => f.cFileName))
  209. {
  210. sb.Append(file.cFileName);
  211. }
  212. foreach (var file in ResolveArgs.MetadataFiles.OrderBy(f => f.cFileName))
  213. {
  214. sb.Append(file.cFileName);
  215. }
  216. return sb.ToString();
  217. }
  218. /// <summary>
  219. /// The _resolve args
  220. /// </summary>
  221. private ItemResolveArgs _resolveArgs;
  222. /// <summary>
  223. /// The _resolve args initialized
  224. /// </summary>
  225. private bool _resolveArgsInitialized;
  226. /// <summary>
  227. /// The _resolve args sync lock
  228. /// </summary>
  229. private object _resolveArgsSyncLock = new object();
  230. /// <summary>
  231. /// We attach these to the item so that we only ever have to hit the file system once
  232. /// (this includes the children of the containing folder)
  233. /// Use ResolveArgs.FileSystemDictionary to check for the existence of files instead of File.Exists
  234. /// </summary>
  235. /// <value>The resolve args.</value>
  236. [IgnoreDataMember]
  237. public ItemResolveArgs ResolveArgs
  238. {
  239. get
  240. {
  241. try
  242. {
  243. LazyInitializer.EnsureInitialized(ref _resolveArgs, ref _resolveArgsInitialized, ref _resolveArgsSyncLock, () => CreateResolveArgs());
  244. }
  245. catch (IOException ex)
  246. {
  247. Logger.ErrorException("Error creating resolve args for ", ex, Path);
  248. throw;
  249. }
  250. return _resolveArgs;
  251. }
  252. set
  253. {
  254. _resolveArgs = value;
  255. _resolveArgsInitialized = value != null;
  256. // Null this out so that it can be lazy loaded again
  257. _fileSystemStamp = null;
  258. }
  259. }
  260. /// <summary>
  261. /// Resets the resolve args.
  262. /// </summary>
  263. /// <param name="pathInfo">The path info.</param>
  264. public void ResetResolveArgs(WIN32_FIND_DATA? pathInfo)
  265. {
  266. ResolveArgs = CreateResolveArgs(pathInfo);
  267. }
  268. /// <summary>
  269. /// Creates ResolveArgs on demand
  270. /// </summary>
  271. /// <param name="pathInfo">The path info.</param>
  272. /// <returns>ItemResolveArgs.</returns>
  273. /// <exception cref="System.IO.IOException">Unable to retrieve file system info for + path</exception>
  274. protected internal virtual ItemResolveArgs CreateResolveArgs(WIN32_FIND_DATA? pathInfo = null)
  275. {
  276. var path = Path;
  277. // non file-system entries will not have a path
  278. if (LocationType != LocationType.FileSystem || string.IsNullOrEmpty(path))
  279. {
  280. return new ItemResolveArgs(ConfigurationManager.ApplicationPaths)
  281. {
  282. FileInfo = new WIN32_FIND_DATA()
  283. };
  284. }
  285. if (UseParentPathToCreateResolveArgs)
  286. {
  287. path = System.IO.Path.GetDirectoryName(path);
  288. }
  289. pathInfo = pathInfo ?? FileSystem.GetFileData(path);
  290. if (!pathInfo.HasValue)
  291. {
  292. throw new IOException("Unable to retrieve file system info for " + path);
  293. }
  294. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths)
  295. {
  296. FileInfo = pathInfo.Value,
  297. Path = path,
  298. Parent = Parent
  299. };
  300. // Gather child folder and files
  301. if (args.IsDirectory)
  302. {
  303. var isPhysicalRoot = args.IsPhysicalRoot;
  304. // When resolving the root, we need it's grandchildren (children of user views)
  305. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  306. args.FileSystemDictionary = FileData.GetFilteredFileSystemEntries(args.Path, Logger, flattenFolderDepth: flattenFolderDepth, args: args, resolveShortcuts: isPhysicalRoot || args.IsVf);
  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 revenue.
  497. /// </summary>
  498. /// <value>The revenue.</value>
  499. public double? Revenue { get; set; }
  500. /// <summary>
  501. /// Gets or sets the production locations.
  502. /// </summary>
  503. /// <value>The production locations.</value>
  504. public List<string> ProductionLocations { get; set; }
  505. /// <summary>
  506. /// Gets or sets the community rating.
  507. /// </summary>
  508. /// <value>The community rating.</value>
  509. public float? CommunityRating { get; set; }
  510. /// <summary>
  511. /// Gets or sets the run time ticks.
  512. /// </summary>
  513. /// <value>The run time ticks.</value>
  514. public long? RunTimeTicks { get; set; }
  515. /// <summary>
  516. /// Gets or sets the aspect ratio.
  517. /// </summary>
  518. /// <value>The aspect ratio.</value>
  519. public string AspectRatio { get; set; }
  520. /// <summary>
  521. /// Gets or sets the production year.
  522. /// </summary>
  523. /// <value>The production year.</value>
  524. public virtual int? ProductionYear { get; set; }
  525. /// <summary>
  526. /// If the item is part of a series, this is it's number in the series.
  527. /// This could be episode number, album track number, etc.
  528. /// </summary>
  529. /// <value>The index number.</value>
  530. public int? IndexNumber { get; set; }
  531. /// <summary>
  532. /// For an episode this could be the season number, or for a song this could be the disc number.
  533. /// </summary>
  534. /// <value>The parent index number.</value>
  535. public int? ParentIndexNumber { get; set; }
  536. /// <summary>
  537. /// The _local trailers
  538. /// </summary>
  539. private List<Video> _localTrailers;
  540. /// <summary>
  541. /// The _local trailers initialized
  542. /// </summary>
  543. private bool _localTrailersInitialized;
  544. /// <summary>
  545. /// The _local trailers sync lock
  546. /// </summary>
  547. private object _localTrailersSyncLock = new object();
  548. /// <summary>
  549. /// Gets the local trailers.
  550. /// </summary>
  551. /// <value>The local trailers.</value>
  552. [IgnoreDataMember]
  553. public List<Video> LocalTrailers
  554. {
  555. get
  556. {
  557. LazyInitializer.EnsureInitialized(ref _localTrailers, ref _localTrailersInitialized, ref _localTrailersSyncLock, LoadLocalTrailers);
  558. return _localTrailers;
  559. }
  560. private set
  561. {
  562. _localTrailers = value;
  563. if (value == null)
  564. {
  565. _localTrailersInitialized = false;
  566. }
  567. }
  568. }
  569. /// <summary>
  570. /// Loads local trailers from the file system
  571. /// </summary>
  572. /// <returns>List{Video}.</returns>
  573. private List<Video> LoadLocalTrailers()
  574. {
  575. ItemResolveArgs resolveArgs;
  576. try
  577. {
  578. resolveArgs = ResolveArgs;
  579. }
  580. catch (IOException ex)
  581. {
  582. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  583. return new List<Video>();
  584. }
  585. if (!resolveArgs.IsDirectory)
  586. {
  587. return new List<Video>();
  588. }
  589. var folder = resolveArgs.GetFileSystemEntryByName(TrailerFolderName);
  590. // Path doesn't exist. No biggie
  591. if (folder == null)
  592. {
  593. return new List<Video>();
  594. }
  595. IEnumerable<WIN32_FIND_DATA> files;
  596. try
  597. {
  598. files = FileSystem.GetFiles(folder.Value.Path);
  599. }
  600. catch (IOException ex)
  601. {
  602. Logger.ErrorException("Error loading trailers for {0}", ex, Name);
  603. return new List<Video>();
  604. }
  605. return LibraryManager.ResolvePaths<Video>(files, null).Select(video =>
  606. {
  607. // Try to retrieve it from the db. If we don't find it, use the resolved version
  608. var dbItem = LibraryManager.RetrieveItem(video.Id) as Video;
  609. if (dbItem != null)
  610. {
  611. dbItem.ResolveArgs = video.ResolveArgs;
  612. video = dbItem;
  613. }
  614. return video;
  615. }).ToList();
  616. }
  617. /// <summary>
  618. /// Overrides the base implementation to refresh metadata for local trailers
  619. /// </summary>
  620. /// <param name="cancellationToken">The cancellation token.</param>
  621. /// <param name="forceSave">if set to <c>true</c> [is new item].</param>
  622. /// <param name="forceRefresh">if set to <c>true</c> [force].</param>
  623. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  624. /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param>
  625. /// <returns>true if a provider reports we changed</returns>
  626. public virtual async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  627. {
  628. if (resetResolveArgs)
  629. {
  630. ResolveArgs = null;
  631. }
  632. // Lazy load these again
  633. LocalTrailers = null;
  634. // Refresh for the item
  635. var itemRefreshTask = ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh, allowSlowProviders);
  636. cancellationToken.ThrowIfCancellationRequested();
  637. // Refresh metadata for local trailers
  638. var trailerTasks = LocalTrailers.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  639. cancellationToken.ThrowIfCancellationRequested();
  640. // Await the trailer tasks
  641. await Task.WhenAll(trailerTasks).ConfigureAwait(false);
  642. cancellationToken.ThrowIfCancellationRequested();
  643. // Get the result from the item task
  644. var changed = await itemRefreshTask.ConfigureAwait(false);
  645. if (changed || forceSave)
  646. {
  647. cancellationToken.ThrowIfCancellationRequested();
  648. await LibraryManager.SaveItem(this, cancellationToken).ConfigureAwait(false);
  649. }
  650. return changed;
  651. }
  652. /// <summary>
  653. /// Clear out all metadata properties. Extend for sub-classes.
  654. /// </summary>
  655. public virtual void ClearMetaValues()
  656. {
  657. Images = null;
  658. ForcedSortName = null;
  659. PremiereDate = null;
  660. BackdropImagePaths = null;
  661. OfficialRating = null;
  662. CustomRating = null;
  663. Overview = null;
  664. Taglines = null;
  665. Language = null;
  666. Studios = null;
  667. Genres = null;
  668. CommunityRating = null;
  669. RunTimeTicks = null;
  670. AspectRatio = null;
  671. ProductionYear = null;
  672. ProviderIds = null;
  673. DisplayMediaType = GetType().Name;
  674. ResolveArgs = null;
  675. }
  676. /// <summary>
  677. /// Gets or sets the trailer URL.
  678. /// </summary>
  679. /// <value>The trailer URL.</value>
  680. public List<string> TrailerUrls { get; set; }
  681. /// <summary>
  682. /// Gets or sets the provider ids.
  683. /// </summary>
  684. /// <value>The provider ids.</value>
  685. public Dictionary<string, string> ProviderIds { get; set; }
  686. /// <summary>
  687. /// Override this to false if class should be ignored for indexing purposes
  688. /// </summary>
  689. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  690. [IgnoreDataMember]
  691. public virtual bool IncludeInIndex
  692. {
  693. get { return true; }
  694. }
  695. /// <summary>
  696. /// Override this to true if class should be grouped under a container in indicies
  697. /// The container class should be defined via IndexContainer
  698. /// </summary>
  699. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  700. [IgnoreDataMember]
  701. public virtual bool GroupInIndex
  702. {
  703. get { return false; }
  704. }
  705. /// <summary>
  706. /// Override this to return the folder that should be used to construct a container
  707. /// for this item in an index. GroupInIndex should be true as well.
  708. /// </summary>
  709. /// <value>The index container.</value>
  710. [IgnoreDataMember]
  711. public virtual Folder IndexContainer
  712. {
  713. get { return null; }
  714. }
  715. /// <summary>
  716. /// Gets the user data key.
  717. /// </summary>
  718. /// <returns>System.String.</returns>
  719. public virtual string GetUserDataKey()
  720. {
  721. return Id.ToString();
  722. }
  723. /// <summary>
  724. /// Determines if a given user has access to this item
  725. /// </summary>
  726. /// <param name="user">The user.</param>
  727. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  728. /// <exception cref="System.ArgumentNullException"></exception>
  729. public bool IsParentalAllowed(User user)
  730. {
  731. if (user == null)
  732. {
  733. throw new ArgumentNullException();
  734. }
  735. return user.Configuration.MaxParentalRating == null || Ratings.Level(CustomRating ?? OfficialRating) <= user.Configuration.MaxParentalRating;
  736. }
  737. /// <summary>
  738. /// Determines if this folder should be visible to a given user.
  739. /// Default is just parental allowed. Can be overridden for more functionality.
  740. /// </summary>
  741. /// <param name="user">The user.</param>
  742. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  743. /// <exception cref="System.ArgumentNullException">user</exception>
  744. public virtual bool IsVisible(User user)
  745. {
  746. if (user == null)
  747. {
  748. throw new ArgumentNullException("user");
  749. }
  750. return IsParentalAllowed(user);
  751. }
  752. /// <summary>
  753. /// Finds the particular item by searching through our parents and, if not found there, loading from repo
  754. /// </summary>
  755. /// <param name="id">The id.</param>
  756. /// <returns>BaseItem.</returns>
  757. /// <exception cref="System.ArgumentException"></exception>
  758. protected BaseItem FindParentItem(Guid id)
  759. {
  760. if (id == Guid.Empty)
  761. {
  762. throw new ArgumentException();
  763. }
  764. var parent = Parent;
  765. while (parent != null && !parent.IsRoot)
  766. {
  767. if (parent.Id == id) return parent;
  768. parent = parent.Parent;
  769. }
  770. //not found - load from repo
  771. return LibraryManager.RetrieveItem(id);
  772. }
  773. /// <summary>
  774. /// Gets a value indicating whether this instance is folder.
  775. /// </summary>
  776. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  777. [IgnoreDataMember]
  778. public virtual bool IsFolder
  779. {
  780. get
  781. {
  782. return false;
  783. }
  784. }
  785. /// <summary>
  786. /// Determine if we have changed vs the passed in copy
  787. /// </summary>
  788. /// <param name="copy">The copy.</param>
  789. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  790. /// <exception cref="System.ArgumentNullException"></exception>
  791. public virtual bool HasChanged(BaseItem copy)
  792. {
  793. if (copy == null)
  794. {
  795. throw new ArgumentNullException();
  796. }
  797. var changed = copy.DateModified != DateModified;
  798. if (changed)
  799. {
  800. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  801. }
  802. return changed;
  803. }
  804. /// <summary>
  805. /// Determines if the item is considered new based on user settings
  806. /// </summary>
  807. /// <param name="user">The user.</param>
  808. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  809. /// <exception cref="System.ArgumentNullException"></exception>
  810. public bool IsRecentlyAdded(User user)
  811. {
  812. if (user == null)
  813. {
  814. throw new ArgumentNullException();
  815. }
  816. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  817. }
  818. /// <summary>
  819. /// Adds people to the item
  820. /// </summary>
  821. /// <param name="people">The people.</param>
  822. /// <exception cref="System.ArgumentNullException"></exception>
  823. public void AddPeople(IEnumerable<PersonInfo> people)
  824. {
  825. if (people == null)
  826. {
  827. throw new ArgumentNullException();
  828. }
  829. foreach (var person in people)
  830. {
  831. AddPerson(person);
  832. }
  833. }
  834. /// <summary>
  835. /// Adds a person to the item
  836. /// </summary>
  837. /// <param name="person">The person.</param>
  838. /// <exception cref="System.ArgumentNullException"></exception>
  839. public void AddPerson(PersonInfo person)
  840. {
  841. if (person == null)
  842. {
  843. throw new ArgumentNullException("person");
  844. }
  845. if (string.IsNullOrWhiteSpace(person.Name))
  846. {
  847. throw new ArgumentNullException();
  848. }
  849. if (People == null)
  850. {
  851. People = new List<PersonInfo> { person };
  852. return;
  853. }
  854. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  855. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  856. {
  857. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  858. if (existing != null)
  859. {
  860. existing.Type = PersonType.GuestStar;
  861. return;
  862. }
  863. }
  864. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  865. {
  866. // Only add actors if there isn't an existing one of type Actor or GuestStar
  867. if (!People.Any(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && (p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase) || p.Type.Equals(PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))))
  868. {
  869. People.Add(person);
  870. }
  871. }
  872. else
  873. {
  874. // Check for dupes based on the combination of Name and Type
  875. if (!People.Any(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(person.Type, StringComparison.OrdinalIgnoreCase)))
  876. {
  877. People.Add(person);
  878. }
  879. }
  880. }
  881. /// <summary>
  882. /// Adds studios to the item
  883. /// </summary>
  884. /// <param name="studios">The studios.</param>
  885. /// <exception cref="System.ArgumentNullException"></exception>
  886. public void AddStudios(IEnumerable<string> studios)
  887. {
  888. if (studios == null)
  889. {
  890. throw new ArgumentNullException();
  891. }
  892. foreach (var name in studios)
  893. {
  894. AddStudio(name);
  895. }
  896. }
  897. /// <summary>
  898. /// Adds a studio to the item
  899. /// </summary>
  900. /// <param name="name">The name.</param>
  901. /// <exception cref="System.ArgumentNullException"></exception>
  902. public void AddStudio(string name)
  903. {
  904. if (string.IsNullOrWhiteSpace(name))
  905. {
  906. throw new ArgumentNullException("name");
  907. }
  908. if (Studios == null)
  909. {
  910. Studios = new List<string>();
  911. }
  912. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  913. {
  914. Studios.Add(name);
  915. }
  916. }
  917. /// <summary>
  918. /// Adds a tagline to the item
  919. /// </summary>
  920. /// <param name="name">The name.</param>
  921. /// <exception cref="System.ArgumentNullException"></exception>
  922. public void AddTagline(string name)
  923. {
  924. if (string.IsNullOrWhiteSpace(name))
  925. {
  926. throw new ArgumentNullException("name");
  927. }
  928. if (Taglines == null)
  929. {
  930. Taglines = new List<string>();
  931. }
  932. if (!Taglines.Contains(name, StringComparer.OrdinalIgnoreCase))
  933. {
  934. Taglines.Add(name);
  935. }
  936. }
  937. /// <summary>
  938. /// Adds a TrailerUrl to the item
  939. /// </summary>
  940. /// <param name="url">The URL.</param>
  941. /// <exception cref="System.ArgumentNullException"></exception>
  942. public void AddTrailerUrl(string url)
  943. {
  944. if (string.IsNullOrWhiteSpace(url))
  945. {
  946. throw new ArgumentNullException("url");
  947. }
  948. if (TrailerUrls == null)
  949. {
  950. TrailerUrls = new List<string>();
  951. }
  952. if (!TrailerUrls.Contains(url, StringComparer.OrdinalIgnoreCase))
  953. {
  954. TrailerUrls.Add(url);
  955. }
  956. }
  957. /// <summary>
  958. /// Adds a genre to the item
  959. /// </summary>
  960. /// <param name="name">The name.</param>
  961. /// <exception cref="System.ArgumentNullException"></exception>
  962. public void AddGenre(string name)
  963. {
  964. if (string.IsNullOrWhiteSpace(name))
  965. {
  966. throw new ArgumentNullException("name");
  967. }
  968. if (Genres == null)
  969. {
  970. Genres = new List<string>();
  971. }
  972. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  973. {
  974. Genres.Add(name);
  975. }
  976. }
  977. /// <summary>
  978. /// Adds the production location.
  979. /// </summary>
  980. /// <param name="location">The location.</param>
  981. /// <exception cref="System.ArgumentNullException">location</exception>
  982. public void AddProductionLocation(string location)
  983. {
  984. if (string.IsNullOrWhiteSpace(location))
  985. {
  986. throw new ArgumentNullException("location");
  987. }
  988. if (ProductionLocations == null)
  989. {
  990. ProductionLocations = new List<string>();
  991. }
  992. if (!ProductionLocations.Contains(location, StringComparer.OrdinalIgnoreCase))
  993. {
  994. ProductionLocations.Add(location);
  995. }
  996. }
  997. /// <summary>
  998. /// Adds genres to the item
  999. /// </summary>
  1000. /// <param name="genres">The genres.</param>
  1001. /// <exception cref="System.ArgumentNullException"></exception>
  1002. public void AddGenres(IEnumerable<string> genres)
  1003. {
  1004. if (genres == null)
  1005. {
  1006. throw new ArgumentNullException();
  1007. }
  1008. foreach (var name in genres)
  1009. {
  1010. AddGenre(name);
  1011. }
  1012. }
  1013. /// <summary>
  1014. /// Marks the item as either played or unplayed
  1015. /// </summary>
  1016. /// <param name="user">The user.</param>
  1017. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  1018. /// <param name="userManager">The user manager.</param>
  1019. /// <returns>Task.</returns>
  1020. /// <exception cref="System.ArgumentNullException"></exception>
  1021. public virtual async Task SetPlayedStatus(User user, bool wasPlayed, IUserDataRepository userManager)
  1022. {
  1023. if (user == null)
  1024. {
  1025. throw new ArgumentNullException();
  1026. }
  1027. var key = GetUserDataKey();
  1028. var data = await userManager.GetUserData(user.Id, key).ConfigureAwait(false);
  1029. if (wasPlayed)
  1030. {
  1031. data.PlayCount = Math.Max(data.PlayCount, 1);
  1032. if (!data.LastPlayedDate.HasValue)
  1033. {
  1034. data.LastPlayedDate = DateTime.UtcNow;
  1035. }
  1036. }
  1037. else
  1038. {
  1039. //I think it is okay to do this here.
  1040. // if this is only called when a user is manually forcing something to un-played
  1041. // then it probably is what we want to do...
  1042. data.PlayCount = 0;
  1043. data.PlaybackPositionTicks = 0;
  1044. data.LastPlayedDate = null;
  1045. }
  1046. data.Played = wasPlayed;
  1047. await userManager.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  1048. }
  1049. /// <summary>
  1050. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1051. /// </summary>
  1052. /// <returns>Task.</returns>
  1053. public virtual Task ChangedExternally()
  1054. {
  1055. return RefreshMetadata(CancellationToken.None);
  1056. }
  1057. /// <summary>
  1058. /// Finds a parent of a given type
  1059. /// </summary>
  1060. /// <typeparam name="T"></typeparam>
  1061. /// <returns>``0.</returns>
  1062. public T FindParent<T>()
  1063. where T : Folder
  1064. {
  1065. var parent = Parent;
  1066. while (parent != null)
  1067. {
  1068. var result = parent as T;
  1069. if (result != null)
  1070. {
  1071. return result;
  1072. }
  1073. parent = parent.Parent;
  1074. }
  1075. return null;
  1076. }
  1077. /// <summary>
  1078. /// Gets an image
  1079. /// </summary>
  1080. /// <param name="type">The type.</param>
  1081. /// <returns>System.String.</returns>
  1082. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1083. public string GetImage(ImageType type)
  1084. {
  1085. if (type == ImageType.Backdrop)
  1086. {
  1087. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1088. }
  1089. if (type == ImageType.Screenshot)
  1090. {
  1091. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1092. }
  1093. if (Images == null)
  1094. {
  1095. return null;
  1096. }
  1097. string val;
  1098. Images.TryGetValue(type.ToString(), out val);
  1099. return val;
  1100. }
  1101. /// <summary>
  1102. /// Gets an image
  1103. /// </summary>
  1104. /// <param name="type">The type.</param>
  1105. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1106. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1107. public bool HasImage(ImageType type)
  1108. {
  1109. if (type == ImageType.Backdrop)
  1110. {
  1111. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1112. }
  1113. if (type == ImageType.Screenshot)
  1114. {
  1115. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1116. }
  1117. return !string.IsNullOrEmpty(GetImage(type));
  1118. }
  1119. /// <summary>
  1120. /// Sets an image
  1121. /// </summary>
  1122. /// <param name="type">The type.</param>
  1123. /// <param name="path">The path.</param>
  1124. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1125. public void SetImage(ImageType type, string path)
  1126. {
  1127. if (type == ImageType.Backdrop)
  1128. {
  1129. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1130. }
  1131. if (type == ImageType.Screenshot)
  1132. {
  1133. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1134. }
  1135. var typeKey = type.ToString();
  1136. // If it's null remove the key from the dictionary
  1137. if (string.IsNullOrEmpty(path))
  1138. {
  1139. if (Images != null)
  1140. {
  1141. if (Images.ContainsKey(typeKey))
  1142. {
  1143. Images.Remove(typeKey);
  1144. }
  1145. }
  1146. }
  1147. else
  1148. {
  1149. // Ensure it exists
  1150. if (Images == null)
  1151. {
  1152. Images = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  1153. }
  1154. Images[typeKey] = path;
  1155. }
  1156. }
  1157. /// <summary>
  1158. /// Deletes the image.
  1159. /// </summary>
  1160. /// <param name="type">The type.</param>
  1161. /// <returns>Task.</returns>
  1162. public async Task DeleteImage(ImageType type)
  1163. {
  1164. if (!HasImage(type))
  1165. {
  1166. return;
  1167. }
  1168. // Delete the source file
  1169. File.Delete(GetImage(type));
  1170. // Remove it from the item
  1171. SetImage(type, null);
  1172. // Refresh metadata
  1173. await RefreshMetadata(CancellationToken.None).ConfigureAwait(false);
  1174. }
  1175. }
  1176. }