BaseMetadataProvider.cs 14 KB

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