BaseMetadataProvider.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Model.Logging;
  6. using System;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace MediaBrowser.Controller.Providers
  10. {
  11. /// <summary>
  12. /// Class BaseMetadataProvider
  13. /// </summary>
  14. public abstract class BaseMetadataProvider : IDisposable
  15. {
  16. /// <summary>
  17. /// Gets the logger.
  18. /// </summary>
  19. /// <value>The logger.</value>
  20. protected ILogger Logger { get; set; }
  21. protected ILogManager LogManager { get; set; }
  22. /// <summary>
  23. /// Gets the configuration manager.
  24. /// </summary>
  25. /// <value>The configuration manager.</value>
  26. protected IServerConfigurationManager ConfigurationManager { get; private set; }
  27. // Cache these since they will be used a lot
  28. /// <summary>
  29. /// The false task result
  30. /// </summary>
  31. protected static readonly Task<bool> FalseTaskResult = Task.FromResult(false);
  32. /// <summary>
  33. /// The true task result
  34. /// </summary>
  35. protected static readonly Task<bool> TrueTaskResult = Task.FromResult(true);
  36. /// <summary>
  37. /// The _id
  38. /// </summary>
  39. protected Guid _id;
  40. /// <summary>
  41. /// Gets the id.
  42. /// </summary>
  43. /// <value>The id.</value>
  44. public virtual Guid Id
  45. {
  46. get
  47. {
  48. if (_id == Guid.Empty) _id = GetType().FullName.GetMD5();
  49. return _id;
  50. }
  51. }
  52. /// <summary>
  53. /// Supportses the specified item.
  54. /// </summary>
  55. /// <param name="item">The item.</param>
  56. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  57. public abstract bool Supports(BaseItem item);
  58. /// <summary>
  59. /// Gets a value indicating whether [requires internet].
  60. /// </summary>
  61. /// <value><c>true</c> if [requires internet]; otherwise, <c>false</c>.</value>
  62. public virtual bool RequiresInternet
  63. {
  64. get
  65. {
  66. return false;
  67. }
  68. }
  69. /// <summary>
  70. /// Gets the provider version.
  71. /// </summary>
  72. /// <value>The provider version.</value>
  73. protected virtual string ProviderVersion
  74. {
  75. get
  76. {
  77. return null;
  78. }
  79. }
  80. /// <summary>
  81. /// Gets a value indicating whether [refresh on version change].
  82. /// </summary>
  83. /// <value><c>true</c> if [refresh on version change]; otherwise, <c>false</c>.</value>
  84. protected virtual bool RefreshOnVersionChange
  85. {
  86. get
  87. {
  88. return false;
  89. }
  90. }
  91. /// <summary>
  92. /// Determines if this provider is relatively slow and, therefore, should be skipped
  93. /// in certain instances. Default is whether or not it requires internet. Can be overridden
  94. /// for explicit designation.
  95. /// </summary>
  96. /// <value><c>true</c> if this instance is slow; otherwise, <c>false</c>.</value>
  97. public virtual bool IsSlow
  98. {
  99. get { return RequiresInternet; }
  100. }
  101. /// <summary>
  102. /// Initializes a new instance of the <see cref="BaseMetadataProvider" /> class.
  103. /// </summary>
  104. protected BaseMetadataProvider(ILogManager logManager, IServerConfigurationManager configurationManager)
  105. {
  106. Logger = logManager.GetLogger(GetType().Name);
  107. LogManager = logManager;
  108. ConfigurationManager = configurationManager;
  109. Initialize();
  110. }
  111. /// <summary>
  112. /// Initializes this instance.
  113. /// </summary>
  114. protected virtual void Initialize()
  115. {
  116. }
  117. /// <summary>
  118. /// Sets the persisted last refresh date on the item for this provider.
  119. /// </summary>
  120. /// <param name="item">The item.</param>
  121. /// <param name="value">The value.</param>
  122. /// <param name="providerVersion">The provider version.</param>
  123. /// <param name="status">The status.</param>
  124. /// <exception cref="System.ArgumentNullException">item</exception>
  125. protected virtual void SetLastRefreshed(BaseItem item, DateTime value, string providerVersion, ProviderRefreshStatus status = ProviderRefreshStatus.Success)
  126. {
  127. if (item == null)
  128. {
  129. throw new ArgumentNullException("item");
  130. }
  131. var data = item.ProviderData.GetValueOrDefault(Id, new BaseProviderInfo { ProviderId = Id });
  132. data.LastRefreshed = value;
  133. data.LastRefreshStatus = status;
  134. data.ProviderVersion = providerVersion;
  135. // Save the file system stamp for future comparisons
  136. if (RefreshOnFileSystemStampChange)
  137. {
  138. data.FileSystemStamp = GetCurrentFileSystemStamp(item);
  139. }
  140. item.ProviderData[Id] = data;
  141. }
  142. /// <summary>
  143. /// Sets the last refreshed.
  144. /// </summary>
  145. /// <param name="item">The item.</param>
  146. /// <param name="value">The value.</param>
  147. /// <param name="status">The status.</param>
  148. protected virtual void SetLastRefreshed(BaseItem item, DateTime value, ProviderRefreshStatus status = ProviderRefreshStatus.Success)
  149. {
  150. SetLastRefreshed(item, value, ProviderVersion, status);
  151. }
  152. /// <summary>
  153. /// Returns whether or not this provider should be re-fetched. Default functionality can
  154. /// compare a provided date with a last refresh time. This can be overridden for more complex
  155. /// determinations.
  156. /// </summary>
  157. /// <param name="item">The item.</param>
  158. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  159. /// <exception cref="System.ArgumentNullException"></exception>
  160. public bool NeedsRefresh(BaseItem item)
  161. {
  162. if (item == null)
  163. {
  164. throw new ArgumentNullException();
  165. }
  166. var providerInfo = item.ProviderData.GetValueOrDefault(Id, new BaseProviderInfo());
  167. return NeedsRefreshInternal(item, providerInfo);
  168. }
  169. /// <summary>
  170. /// Needses the refresh internal.
  171. /// </summary>
  172. /// <param name="item">The item.</param>
  173. /// <param name="providerInfo">The provider info.</param>
  174. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  175. /// <exception cref="System.ArgumentNullException"></exception>
  176. protected virtual bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
  177. {
  178. if (item == null)
  179. {
  180. throw new ArgumentNullException("item");
  181. }
  182. if (providerInfo == null)
  183. {
  184. throw new ArgumentNullException("providerInfo");
  185. }
  186. if (CompareDate(item) > providerInfo.LastRefreshed)
  187. {
  188. return true;
  189. }
  190. if (RefreshOnFileSystemStampChange && HasFileSystemStampChanged(item, providerInfo))
  191. {
  192. return true;
  193. }
  194. if (RefreshOnVersionChange && !string.Equals(ProviderVersion, providerInfo.ProviderVersion))
  195. {
  196. return true;
  197. }
  198. return false;
  199. }
  200. /// <summary>
  201. /// Determines if the item's file system stamp has changed from the last time the provider refreshed
  202. /// </summary>
  203. /// <param name="item">The item.</param>
  204. /// <param name="providerInfo">The provider info.</param>
  205. /// <returns><c>true</c> if [has file system stamp changed] [the specified item]; otherwise, <c>false</c>.</returns>
  206. protected bool HasFileSystemStampChanged(BaseItem item, BaseProviderInfo providerInfo)
  207. {
  208. return GetCurrentFileSystemStamp(item) != providerInfo.FileSystemStamp;
  209. }
  210. /// <summary>
  211. /// Override this to return the date that should be compared to the last refresh date
  212. /// to determine if this provider should be re-fetched.
  213. /// </summary>
  214. /// <param name="item">The item.</param>
  215. /// <returns>DateTime.</returns>
  216. protected virtual DateTime CompareDate(BaseItem item)
  217. {
  218. return DateTime.MinValue.AddMinutes(1); // want this to be greater than mindate so new items will refresh
  219. }
  220. /// <summary>
  221. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  222. /// </summary>
  223. /// <param name="item">The item.</param>
  224. /// <param name="force">if set to <c>true</c> [force].</param>
  225. /// <param name="cancellationToken">The cancellation token.</param>
  226. /// <returns>Task{System.Boolean}.</returns>
  227. /// <exception cref="System.ArgumentNullException"></exception>
  228. public async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  229. {
  230. if (item == null)
  231. {
  232. throw new ArgumentNullException();
  233. }
  234. cancellationToken.ThrowIfCancellationRequested();
  235. Logger.Info("Running for {0}", item.Path ?? item.Name ?? "--Unknown--");
  236. // This provides the ability to cancel just this one provider
  237. var innerCancellationTokenSource = new CancellationTokenSource();
  238. Kernel.Instance.ProviderManager.OnProviderRefreshBeginning(this, item, innerCancellationTokenSource);
  239. try
  240. {
  241. var task = FetchAsyncInternal(item, force, CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token);
  242. await task.ConfigureAwait(false);
  243. if (task.IsFaulted)
  244. {
  245. // Log the AggregateException
  246. if (task.Exception != null)
  247. {
  248. Logger.ErrorException("AggregateException:", task.Exception);
  249. }
  250. return false;
  251. }
  252. return task.Result;
  253. }
  254. catch (OperationCanceledException ex)
  255. {
  256. Logger.Info("{0} cancelled for {1}", GetType().Name, item.Name);
  257. // If the outer cancellation token is the one that caused the cancellation, throw it
  258. if (cancellationToken.IsCancellationRequested && ex.CancellationToken == cancellationToken)
  259. {
  260. throw;
  261. }
  262. return false;
  263. }
  264. catch (Exception ex)
  265. {
  266. Logger.ErrorException("failed refreshing {0}", ex, item.Name);
  267. SetLastRefreshed(item, DateTime.UtcNow, ProviderRefreshStatus.Failure);
  268. return true;
  269. }
  270. finally
  271. {
  272. innerCancellationTokenSource.Dispose();
  273. Kernel.Instance.ProviderManager.OnProviderRefreshCompleted(this, item);
  274. }
  275. }
  276. /// <summary>
  277. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  278. /// </summary>
  279. /// <param name="item">The item.</param>
  280. /// <param name="force">if set to <c>true</c> [force].</param>
  281. /// <param name="cancellationToken">The cancellation token.</param>
  282. /// <returns>Task{System.Boolean}.</returns>
  283. protected abstract Task<bool> FetchAsyncInternal(BaseItem item, bool force, CancellationToken cancellationToken);
  284. /// <summary>
  285. /// Gets the priority.
  286. /// </summary>
  287. /// <value>The priority.</value>
  288. public abstract MetadataProviderPriority Priority { get; }
  289. /// <summary>
  290. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  291. /// </summary>
  292. public void Dispose()
  293. {
  294. Dispose(true);
  295. GC.SuppressFinalize(this);
  296. }
  297. /// <summary>
  298. /// Releases unmanaged and - optionally - managed resources.
  299. /// </summary>
  300. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  301. protected virtual void Dispose(bool dispose)
  302. {
  303. }
  304. /// <summary>
  305. /// Returns true or false indicating if the provider should refresh when the contents of it's directory changes
  306. /// </summary>
  307. /// <value><c>true</c> if [refresh on file system stamp change]; otherwise, <c>false</c>.</value>
  308. protected virtual bool RefreshOnFileSystemStampChange
  309. {
  310. get
  311. {
  312. return false;
  313. }
  314. }
  315. /// <summary>
  316. /// Determines if the parent's file system stamp should be used for comparison
  317. /// </summary>
  318. /// <param name="item">The item.</param>
  319. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  320. protected virtual bool UseParentFileSystemStamp(BaseItem item)
  321. {
  322. // True when the current item is just a file
  323. return !item.ResolveArgs.IsDirectory;
  324. }
  325. /// <summary>
  326. /// Gets the item's current file system stamp
  327. /// </summary>
  328. /// <param name="item">The item.</param>
  329. /// <returns>Guid.</returns>
  330. private Guid GetCurrentFileSystemStamp(BaseItem item)
  331. {
  332. if (UseParentFileSystemStamp(item) && item.Parent != null)
  333. {
  334. return item.Parent.FileSystemStamp;
  335. }
  336. return item.FileSystemStamp;
  337. }
  338. }
  339. /// <summary>
  340. /// Determines when a provider should execute, relative to others
  341. /// </summary>
  342. public enum MetadataProviderPriority
  343. {
  344. // Run this provider at the beginning
  345. /// <summary>
  346. /// The first
  347. /// </summary>
  348. First = 1,
  349. // Run this provider after all first priority providers
  350. /// <summary>
  351. /// The second
  352. /// </summary>
  353. Second = 2,
  354. // Run this provider after all second priority providers
  355. /// <summary>
  356. /// The third
  357. /// </summary>
  358. Third = 3,
  359. // Run this provider last
  360. /// <summary>
  361. /// The last
  362. /// </summary>
  363. Last = 4
  364. }
  365. }