BaseMetadataProvider.cs 14 KB

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