BaseItem.cs 44 KB

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