BaseItem.cs 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  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 genres.
  481. /// </summary>
  482. /// <value>The genres.</value>
  483. public virtual List<string> Genres { get; set; }
  484. /// <summary>
  485. /// Gets or sets the community rating.
  486. /// </summary>
  487. /// <value>The community rating.</value>
  488. public float? CommunityRating { get; set; }
  489. /// <summary>
  490. /// Gets or sets the run time ticks.
  491. /// </summary>
  492. /// <value>The run time ticks.</value>
  493. public long? RunTimeTicks { get; set; }
  494. /// <summary>
  495. /// Gets or sets the aspect ratio.
  496. /// </summary>
  497. /// <value>The aspect ratio.</value>
  498. public string AspectRatio { get; set; }
  499. /// <summary>
  500. /// Gets or sets the production year.
  501. /// </summary>
  502. /// <value>The production year.</value>
  503. public virtual int? ProductionYear { get; set; }
  504. /// <summary>
  505. /// If the item is part of a series, this is it's number in the series.
  506. /// This could be episode number, album track number, etc.
  507. /// </summary>
  508. /// <value>The index number.</value>
  509. public int? IndexNumber { get; set; }
  510. /// <summary>
  511. /// For an episode this could be the season number, or for a song this could be the disc number.
  512. /// </summary>
  513. /// <value>The parent index number.</value>
  514. public int? ParentIndexNumber { get; set; }
  515. /// <summary>
  516. /// The _local trailers
  517. /// </summary>
  518. private List<Video> _localTrailers;
  519. /// <summary>
  520. /// The _local trailers initialized
  521. /// </summary>
  522. private bool _localTrailersInitialized;
  523. /// <summary>
  524. /// The _local trailers sync lock
  525. /// </summary>
  526. private object _localTrailersSyncLock = new object();
  527. /// <summary>
  528. /// Gets the local trailers.
  529. /// </summary>
  530. /// <value>The local trailers.</value>
  531. [IgnoreDataMember]
  532. public List<Video> LocalTrailers
  533. {
  534. get
  535. {
  536. LazyInitializer.EnsureInitialized(ref _localTrailers, ref _localTrailersInitialized, ref _localTrailersSyncLock, LoadLocalTrailers);
  537. return _localTrailers;
  538. }
  539. private set
  540. {
  541. _localTrailers = value;
  542. if (value == null)
  543. {
  544. _localTrailersInitialized = false;
  545. }
  546. }
  547. }
  548. /// <summary>
  549. /// Loads local trailers from the file system
  550. /// </summary>
  551. /// <returns>List{Video}.</returns>
  552. private List<Video> LoadLocalTrailers()
  553. {
  554. ItemResolveArgs resolveArgs;
  555. try
  556. {
  557. resolveArgs = ResolveArgs;
  558. }
  559. catch (IOException ex)
  560. {
  561. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  562. return new List<Video> { };
  563. }
  564. if (!resolveArgs.IsDirectory)
  565. {
  566. return new List<Video> { };
  567. }
  568. var folder = resolveArgs.GetFileSystemEntryByName(TrailerFolderName);
  569. // Path doesn't exist. No biggie
  570. if (folder == null)
  571. {
  572. return new List<Video> { };
  573. }
  574. IEnumerable<WIN32_FIND_DATA> files;
  575. try
  576. {
  577. files = FileSystem.GetFiles(folder.Value.Path);
  578. }
  579. catch (IOException ex)
  580. {
  581. Logger.ErrorException("Error loading trailers for {0}", ex, Name);
  582. return new List<Video> { };
  583. }
  584. return LibraryManager.ResolvePaths<Video>(files, null).Select(video =>
  585. {
  586. // Try to retrieve it from the db. If we don't find it, use the resolved version
  587. var dbItem = LibraryManager.RetrieveItem(video.Id) as Video;
  588. if (dbItem != null)
  589. {
  590. dbItem.ResolveArgs = video.ResolveArgs;
  591. video = dbItem;
  592. }
  593. return video;
  594. }).ToList();
  595. }
  596. /// <summary>
  597. /// Overrides the base implementation to refresh metadata for local trailers
  598. /// </summary>
  599. /// <param name="cancellationToken">The cancellation token.</param>
  600. /// <param name="forceSave">if set to <c>true</c> [is new item].</param>
  601. /// <param name="forceRefresh">if set to <c>true</c> [force].</param>
  602. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  603. /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param>
  604. /// <returns>true if a provider reports we changed</returns>
  605. public virtual async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  606. {
  607. if (resetResolveArgs)
  608. {
  609. ResolveArgs = null;
  610. }
  611. // Lazy load these again
  612. LocalTrailers = null;
  613. // Refresh for the item
  614. var itemRefreshTask = ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh, allowSlowProviders);
  615. cancellationToken.ThrowIfCancellationRequested();
  616. // Refresh metadata for local trailers
  617. var trailerTasks = LocalTrailers.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  618. cancellationToken.ThrowIfCancellationRequested();
  619. // Await the trailer tasks
  620. await Task.WhenAll(trailerTasks).ConfigureAwait(false);
  621. cancellationToken.ThrowIfCancellationRequested();
  622. // Get the result from the item task
  623. var changed = await itemRefreshTask.ConfigureAwait(false);
  624. if (changed || forceSave)
  625. {
  626. cancellationToken.ThrowIfCancellationRequested();
  627. await LibraryManager.SaveItem(this, cancellationToken).ConfigureAwait(false);
  628. }
  629. return changed;
  630. }
  631. /// <summary>
  632. /// Clear out all metadata properties. Extend for sub-classes.
  633. /// </summary>
  634. public virtual void ClearMetaValues()
  635. {
  636. Images = null;
  637. ForcedSortName = null;
  638. PremiereDate = null;
  639. BackdropImagePaths = null;
  640. OfficialRating = null;
  641. CustomRating = null;
  642. Overview = null;
  643. Taglines = null;
  644. Language = null;
  645. Studios = null;
  646. Genres = null;
  647. CommunityRating = null;
  648. RunTimeTicks = null;
  649. AspectRatio = null;
  650. ProductionYear = null;
  651. ProviderIds = null;
  652. DisplayMediaType = GetType().Name;
  653. ResolveArgs = null;
  654. }
  655. /// <summary>
  656. /// Gets or sets the trailer URL.
  657. /// </summary>
  658. /// <value>The trailer URL.</value>
  659. public List<string> TrailerUrls { get; set; }
  660. /// <summary>
  661. /// Gets or sets the provider ids.
  662. /// </summary>
  663. /// <value>The provider ids.</value>
  664. public Dictionary<string, string> ProviderIds { get; set; }
  665. /// <summary>
  666. /// Override this to false if class should be ignored for indexing purposes
  667. /// </summary>
  668. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  669. [IgnoreDataMember]
  670. public virtual bool IncludeInIndex
  671. {
  672. get { return true; }
  673. }
  674. /// <summary>
  675. /// Override this to true if class should be grouped under a container in indicies
  676. /// The container class should be defined via IndexContainer
  677. /// </summary>
  678. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  679. [IgnoreDataMember]
  680. public virtual bool GroupInIndex
  681. {
  682. get { return false; }
  683. }
  684. /// <summary>
  685. /// Override this to return the folder that should be used to construct a container
  686. /// for this item in an index. GroupInIndex should be true as well.
  687. /// </summary>
  688. /// <value>The index container.</value>
  689. [IgnoreDataMember]
  690. public virtual Folder IndexContainer
  691. {
  692. get { return null; }
  693. }
  694. /// <summary>
  695. /// The _user data id
  696. /// </summary>
  697. protected Guid _userDataId; //cache this so it doesn't have to be re-constructed on every reference
  698. /// <summary>
  699. /// Return the id that should be used to key user data for this item.
  700. /// Default is just this Id but subclasses can use provider Ids for transportability.
  701. /// </summary>
  702. /// <value>The user data id.</value>
  703. [IgnoreDataMember]
  704. public virtual Guid UserDataId
  705. {
  706. get
  707. {
  708. return _userDataId == Guid.Empty ? (_userDataId = Id) : _userDataId;
  709. }
  710. }
  711. /// <summary>
  712. /// Determines if a given user has access to this item
  713. /// </summary>
  714. /// <param name="user">The user.</param>
  715. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  716. /// <exception cref="System.ArgumentNullException"></exception>
  717. public bool IsParentalAllowed(User user)
  718. {
  719. if (user == null)
  720. {
  721. throw new ArgumentNullException();
  722. }
  723. return user.Configuration.MaxParentalRating == null || Ratings.Level(CustomRating ?? OfficialRating) <= user.Configuration.MaxParentalRating;
  724. }
  725. /// <summary>
  726. /// Determines if this folder should be visible to a given user.
  727. /// Default is just parental allowed. Can be overridden for more functionality.
  728. /// </summary>
  729. /// <param name="user">The user.</param>
  730. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  731. /// <exception cref="System.ArgumentNullException">user</exception>
  732. public virtual bool IsVisible(User user)
  733. {
  734. if (user == null)
  735. {
  736. throw new ArgumentNullException("user");
  737. }
  738. return IsParentalAllowed(user);
  739. }
  740. /// <summary>
  741. /// Finds the particular item by searching through our parents and, if not found there, loading from repo
  742. /// </summary>
  743. /// <param name="id">The id.</param>
  744. /// <returns>BaseItem.</returns>
  745. /// <exception cref="System.ArgumentException"></exception>
  746. protected BaseItem FindParentItem(Guid id)
  747. {
  748. if (id == Guid.Empty)
  749. {
  750. throw new ArgumentException();
  751. }
  752. var parent = Parent;
  753. while (parent != null && !parent.IsRoot)
  754. {
  755. if (parent.Id == id) return parent;
  756. parent = parent.Parent;
  757. }
  758. //not found - load from repo
  759. return LibraryManager.RetrieveItem(id);
  760. }
  761. /// <summary>
  762. /// Gets a value indicating whether this instance is folder.
  763. /// </summary>
  764. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  765. [IgnoreDataMember]
  766. public virtual bool IsFolder
  767. {
  768. get
  769. {
  770. return false;
  771. }
  772. }
  773. /// <summary>
  774. /// Determine if we have changed vs the passed in copy
  775. /// </summary>
  776. /// <param name="copy">The copy.</param>
  777. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  778. /// <exception cref="System.ArgumentNullException"></exception>
  779. public virtual bool HasChanged(BaseItem copy)
  780. {
  781. if (copy == null)
  782. {
  783. throw new ArgumentNullException();
  784. }
  785. var changed = copy.DateModified != DateModified;
  786. if (changed)
  787. {
  788. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  789. }
  790. return changed;
  791. }
  792. /// <summary>
  793. /// Determines if the item is considered new based on user settings
  794. /// </summary>
  795. /// <param name="user">The user.</param>
  796. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  797. /// <exception cref="System.ArgumentNullException"></exception>
  798. public bool IsRecentlyAdded(User user)
  799. {
  800. if (user == null)
  801. {
  802. throw new ArgumentNullException();
  803. }
  804. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  805. }
  806. /// <summary>
  807. /// Adds people to the item
  808. /// </summary>
  809. /// <param name="people">The people.</param>
  810. /// <exception cref="System.ArgumentNullException"></exception>
  811. public void AddPeople(IEnumerable<PersonInfo> people)
  812. {
  813. if (people == null)
  814. {
  815. throw new ArgumentNullException();
  816. }
  817. foreach (var person in people)
  818. {
  819. AddPerson(person);
  820. }
  821. }
  822. /// <summary>
  823. /// Adds a person to the item
  824. /// </summary>
  825. /// <param name="person">The person.</param>
  826. /// <exception cref="System.ArgumentNullException"></exception>
  827. public void AddPerson(PersonInfo person)
  828. {
  829. if (person == null)
  830. {
  831. throw new ArgumentNullException();
  832. }
  833. if (string.IsNullOrWhiteSpace(person.Name))
  834. {
  835. throw new ArgumentNullException();
  836. }
  837. if (People == null)
  838. {
  839. People = new List<PersonInfo>();
  840. }
  841. // Check for dupes based on the combination of Name and Type
  842. if (!People.Any(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(person.Type, StringComparison.OrdinalIgnoreCase)))
  843. {
  844. People.Add(person);
  845. }
  846. }
  847. /// <summary>
  848. /// Adds studios to the item
  849. /// </summary>
  850. /// <param name="studios">The studios.</param>
  851. /// <exception cref="System.ArgumentNullException"></exception>
  852. public void AddStudios(IEnumerable<string> studios)
  853. {
  854. if (studios == null)
  855. {
  856. throw new ArgumentNullException();
  857. }
  858. foreach (var name in studios)
  859. {
  860. AddStudio(name);
  861. }
  862. }
  863. /// <summary>
  864. /// Adds a studio to the item
  865. /// </summary>
  866. /// <param name="name">The name.</param>
  867. /// <exception cref="System.ArgumentNullException"></exception>
  868. public void AddStudio(string name)
  869. {
  870. if (string.IsNullOrWhiteSpace(name))
  871. {
  872. throw new ArgumentNullException("name");
  873. }
  874. if (Studios == null)
  875. {
  876. Studios = new List<string>();
  877. }
  878. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  879. {
  880. Studios.Add(name);
  881. }
  882. }
  883. /// <summary>
  884. /// Adds a tagline to the item
  885. /// </summary>
  886. /// <param name="name">The name.</param>
  887. /// <exception cref="System.ArgumentNullException"></exception>
  888. public void AddTagline(string name)
  889. {
  890. if (string.IsNullOrWhiteSpace(name))
  891. {
  892. throw new ArgumentNullException("name");
  893. }
  894. if (Taglines == null)
  895. {
  896. Taglines = new List<string>();
  897. }
  898. if (!Taglines.Contains(name, StringComparer.OrdinalIgnoreCase))
  899. {
  900. Taglines.Add(name);
  901. }
  902. }
  903. /// <summary>
  904. /// Adds a TrailerUrl to the item
  905. /// </summary>
  906. /// <param name="url">The URL.</param>
  907. /// <exception cref="System.ArgumentNullException"></exception>
  908. public void AddTrailerUrl(string url)
  909. {
  910. if (string.IsNullOrWhiteSpace(url))
  911. {
  912. throw new ArgumentNullException("url");
  913. }
  914. if (TrailerUrls == null)
  915. {
  916. TrailerUrls = new List<string>();
  917. }
  918. if (!TrailerUrls.Contains(url, StringComparer.OrdinalIgnoreCase))
  919. {
  920. TrailerUrls.Add(url);
  921. }
  922. }
  923. /// <summary>
  924. /// Adds a genre to the item
  925. /// </summary>
  926. /// <param name="name">The name.</param>
  927. /// <exception cref="System.ArgumentNullException"></exception>
  928. public void AddGenre(string name)
  929. {
  930. if (string.IsNullOrWhiteSpace(name))
  931. {
  932. throw new ArgumentNullException();
  933. }
  934. if (Genres == null)
  935. {
  936. Genres = new List<string>();
  937. }
  938. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  939. {
  940. Genres.Add(name);
  941. }
  942. }
  943. /// <summary>
  944. /// Adds genres to the item
  945. /// </summary>
  946. /// <param name="genres">The genres.</param>
  947. /// <exception cref="System.ArgumentNullException"></exception>
  948. public void AddGenres(IEnumerable<string> genres)
  949. {
  950. if (genres == null)
  951. {
  952. throw new ArgumentNullException();
  953. }
  954. foreach (var name in genres)
  955. {
  956. AddGenre(name);
  957. }
  958. }
  959. /// <summary>
  960. /// Marks the item as either played or unplayed
  961. /// </summary>
  962. /// <param name="user">The user.</param>
  963. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  964. /// <param name="userManager">The user manager.</param>
  965. /// <returns>Task.</returns>
  966. /// <exception cref="System.ArgumentNullException"></exception>
  967. public virtual async Task SetPlayedStatus(User user, bool wasPlayed, IUserManager userManager)
  968. {
  969. if (user == null)
  970. {
  971. throw new ArgumentNullException();
  972. }
  973. var data = await userManager.GetUserData(user.Id, UserDataId).ConfigureAwait(false);
  974. if (wasPlayed)
  975. {
  976. data.PlayCount = Math.Max(data.PlayCount, 1);
  977. if (!data.LastPlayedDate.HasValue)
  978. {
  979. data.LastPlayedDate = DateTime.UtcNow;
  980. }
  981. }
  982. else
  983. {
  984. //I think it is okay to do this here.
  985. // if this is only called when a user is manually forcing something to un-played
  986. // then it probably is what we want to do...
  987. data.PlayCount = 0;
  988. data.PlaybackPositionTicks = 0;
  989. data.LastPlayedDate = null;
  990. }
  991. data.Played = wasPlayed;
  992. await userManager.SaveUserData(user.Id, UserDataId, data, CancellationToken.None).ConfigureAwait(false);
  993. }
  994. /// <summary>
  995. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  996. /// </summary>
  997. /// <returns>Task.</returns>
  998. public virtual Task ChangedExternally()
  999. {
  1000. return RefreshMetadata(CancellationToken.None);
  1001. }
  1002. /// <summary>
  1003. /// Finds a parent of a given type
  1004. /// </summary>
  1005. /// <typeparam name="T"></typeparam>
  1006. /// <returns>``0.</returns>
  1007. public T FindParent<T>()
  1008. where T : Folder
  1009. {
  1010. var parent = Parent;
  1011. while (parent != null)
  1012. {
  1013. var result = parent as T;
  1014. if (result != null)
  1015. {
  1016. return result;
  1017. }
  1018. parent = parent.Parent;
  1019. }
  1020. return null;
  1021. }
  1022. /// <summary>
  1023. /// Gets an image
  1024. /// </summary>
  1025. /// <param name="type">The type.</param>
  1026. /// <returns>System.String.</returns>
  1027. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1028. public string GetImage(ImageType type)
  1029. {
  1030. if (type == ImageType.Backdrop)
  1031. {
  1032. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1033. }
  1034. if (type == ImageType.Screenshot)
  1035. {
  1036. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1037. }
  1038. if (Images == null)
  1039. {
  1040. return null;
  1041. }
  1042. string val;
  1043. Images.TryGetValue(type.ToString(), out val);
  1044. return val;
  1045. }
  1046. /// <summary>
  1047. /// Gets an image
  1048. /// </summary>
  1049. /// <param name="type">The type.</param>
  1050. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1051. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1052. public bool HasImage(ImageType type)
  1053. {
  1054. if (type == ImageType.Backdrop)
  1055. {
  1056. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1057. }
  1058. if (type == ImageType.Screenshot)
  1059. {
  1060. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1061. }
  1062. return !string.IsNullOrEmpty(GetImage(type));
  1063. }
  1064. /// <summary>
  1065. /// Sets an image
  1066. /// </summary>
  1067. /// <param name="type">The type.</param>
  1068. /// <param name="path">The path.</param>
  1069. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1070. public void SetImage(ImageType type, string path)
  1071. {
  1072. if (type == ImageType.Backdrop)
  1073. {
  1074. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1075. }
  1076. if (type == ImageType.Screenshot)
  1077. {
  1078. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1079. }
  1080. var typeKey = type.ToString();
  1081. // If it's null remove the key from the dictionary
  1082. if (string.IsNullOrEmpty(path))
  1083. {
  1084. if (Images != null)
  1085. {
  1086. if (Images.ContainsKey(typeKey))
  1087. {
  1088. Images.Remove(typeKey);
  1089. }
  1090. }
  1091. }
  1092. else
  1093. {
  1094. // Ensure it exists
  1095. if (Images == null)
  1096. {
  1097. Images = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  1098. }
  1099. Images[typeKey] = path;
  1100. }
  1101. }
  1102. /// <summary>
  1103. /// Deletes the image.
  1104. /// </summary>
  1105. /// <param name="type">The type.</param>
  1106. /// <returns>Task.</returns>
  1107. public async Task DeleteImage(ImageType type)
  1108. {
  1109. if (!HasImage(type))
  1110. {
  1111. return;
  1112. }
  1113. // Delete the source file
  1114. File.Delete(GetImage(type));
  1115. // Remove it from the item
  1116. SetImage(type, null);
  1117. // Refresh metadata
  1118. await RefreshMetadata(CancellationToken.None).ConfigureAwait(false);
  1119. }
  1120. }
  1121. }