BaseItem.cs 43 KB

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