BaseMetadataProvider.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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 ILogger Logger { get; set; }
  19. protected ILogManager LogManager { get; 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(ILogManager logManager)
  98. {
  99. Logger = logManager.GetLogger(GetType().Name);
  100. LogManager = logManager;
  101. Initialize();
  102. }
  103. /// <summary>
  104. /// Initializes this instance.
  105. /// </summary>
  106. protected virtual void Initialize()
  107. {
  108. }
  109. /// <summary>
  110. /// Sets the persisted last refresh date on the item for this provider.
  111. /// </summary>
  112. /// <param name="item">The item.</param>
  113. /// <param name="value">The value.</param>
  114. /// <param name="providerVersion">The provider version.</param>
  115. /// <param name="status">The status.</param>
  116. /// <exception cref="System.ArgumentNullException">item</exception>
  117. protected virtual void SetLastRefreshed(BaseItem item, DateTime value, string providerVersion, ProviderRefreshStatus status = ProviderRefreshStatus.Success)
  118. {
  119. if (item == null)
  120. {
  121. throw new ArgumentNullException("item");
  122. }
  123. var data = item.ProviderData.GetValueOrDefault(Id, new BaseProviderInfo { ProviderId = Id });
  124. data.LastRefreshed = value;
  125. data.LastRefreshStatus = status;
  126. data.ProviderVersion = providerVersion;
  127. // Save the file system stamp for future comparisons
  128. if (RefreshOnFileSystemStampChange)
  129. {
  130. data.FileSystemStamp = GetCurrentFileSystemStamp(item);
  131. }
  132. item.ProviderData[Id] = data;
  133. }
  134. /// <summary>
  135. /// Sets the last refreshed.
  136. /// </summary>
  137. /// <param name="item">The item.</param>
  138. /// <param name="value">The value.</param>
  139. /// <param name="status">The status.</param>
  140. protected virtual void SetLastRefreshed(BaseItem item, DateTime value, ProviderRefreshStatus status = ProviderRefreshStatus.Success)
  141. {
  142. SetLastRefreshed(item, value, ProviderVersion, status);
  143. }
  144. /// <summary>
  145. /// Returns whether or not this provider should be re-fetched. Default functionality can
  146. /// compare a provided date with a last refresh time. This can be overridden for more complex
  147. /// determinations.
  148. /// </summary>
  149. /// <param name="item">The item.</param>
  150. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  151. /// <exception cref="System.ArgumentNullException"></exception>
  152. public bool NeedsRefresh(BaseItem item)
  153. {
  154. if (item == null)
  155. {
  156. throw new ArgumentNullException();
  157. }
  158. var providerInfo = item.ProviderData.GetValueOrDefault(Id, new BaseProviderInfo());
  159. return NeedsRefreshInternal(item, providerInfo);
  160. }
  161. /// <summary>
  162. /// Needses the refresh internal.
  163. /// </summary>
  164. /// <param name="item">The item.</param>
  165. /// <param name="providerInfo">The provider info.</param>
  166. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  167. /// <exception cref="System.ArgumentNullException"></exception>
  168. protected virtual bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
  169. {
  170. if (item == null)
  171. {
  172. throw new ArgumentNullException("item");
  173. }
  174. if (providerInfo == null)
  175. {
  176. throw new ArgumentNullException("providerInfo");
  177. }
  178. if (CompareDate(item) > providerInfo.LastRefreshed)
  179. {
  180. return true;
  181. }
  182. if (RefreshOnFileSystemStampChange && HasFileSystemStampChanged(item, providerInfo))
  183. {
  184. return true;
  185. }
  186. if (RefreshOnVersionChange && !string.Equals(ProviderVersion, providerInfo.ProviderVersion))
  187. {
  188. return true;
  189. }
  190. return false;
  191. }
  192. /// <summary>
  193. /// Determines if the item's file system stamp has changed from the last time the provider refreshed
  194. /// </summary>
  195. /// <param name="item">The item.</param>
  196. /// <param name="providerInfo">The provider info.</param>
  197. /// <returns><c>true</c> if [has file system stamp changed] [the specified item]; otherwise, <c>false</c>.</returns>
  198. protected bool HasFileSystemStampChanged(BaseItem item, BaseProviderInfo providerInfo)
  199. {
  200. return GetCurrentFileSystemStamp(item) != providerInfo.FileSystemStamp;
  201. }
  202. /// <summary>
  203. /// Override this to return the date that should be compared to the last refresh date
  204. /// to determine if this provider should be re-fetched.
  205. /// </summary>
  206. /// <param name="item">The item.</param>
  207. /// <returns>DateTime.</returns>
  208. protected virtual DateTime CompareDate(BaseItem item)
  209. {
  210. return DateTime.MinValue.AddMinutes(1); // want this to be greater than mindate so new items will refresh
  211. }
  212. /// <summary>
  213. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  214. /// </summary>
  215. /// <param name="item">The item.</param>
  216. /// <param name="force">if set to <c>true</c> [force].</param>
  217. /// <param name="cancellationToken">The cancellation token.</param>
  218. /// <returns>Task{System.Boolean}.</returns>
  219. /// <exception cref="System.ArgumentNullException"></exception>
  220. public async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  221. {
  222. if (item == null)
  223. {
  224. throw new ArgumentNullException();
  225. }
  226. cancellationToken.ThrowIfCancellationRequested();
  227. Logger.Info("Running for {0}", item.Path ?? item.Name ?? "--Unknown--");
  228. // This provides the ability to cancel just this one provider
  229. var innerCancellationTokenSource = new CancellationTokenSource();
  230. Kernel.Instance.ProviderManager.OnProviderRefreshBeginning(this, item, innerCancellationTokenSource);
  231. try
  232. {
  233. var task = FetchAsyncInternal(item, force, CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token);
  234. await task.ConfigureAwait(false);
  235. if (task.IsFaulted)
  236. {
  237. // Log the AggregateException
  238. if (task.Exception != null)
  239. {
  240. Logger.ErrorException("AggregateException:", task.Exception);
  241. }
  242. return false;
  243. }
  244. return task.Result;
  245. }
  246. catch (OperationCanceledException ex)
  247. {
  248. Logger.Info("{0} cancelled for {1}", GetType().Name, item.Name);
  249. // If the outer cancellation token is the one that caused the cancellation, throw it
  250. if (cancellationToken.IsCancellationRequested && ex.CancellationToken == cancellationToken)
  251. {
  252. throw;
  253. }
  254. return false;
  255. }
  256. catch (Exception ex)
  257. {
  258. Logger.ErrorException("failed refreshing {0}", ex, item.Name);
  259. SetLastRefreshed(item, DateTime.UtcNow, ProviderRefreshStatus.Failure);
  260. return true;
  261. }
  262. finally
  263. {
  264. innerCancellationTokenSource.Dispose();
  265. Kernel.Instance.ProviderManager.OnProviderRefreshCompleted(this, item);
  266. }
  267. }
  268. /// <summary>
  269. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  270. /// </summary>
  271. /// <param name="item">The item.</param>
  272. /// <param name="force">if set to <c>true</c> [force].</param>
  273. /// <param name="cancellationToken">The cancellation token.</param>
  274. /// <returns>Task{System.Boolean}.</returns>
  275. protected abstract Task<bool> FetchAsyncInternal(BaseItem item, bool force, CancellationToken cancellationToken);
  276. /// <summary>
  277. /// Gets the priority.
  278. /// </summary>
  279. /// <value>The priority.</value>
  280. public abstract MetadataProviderPriority Priority { get; }
  281. /// <summary>
  282. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  283. /// </summary>
  284. public void Dispose()
  285. {
  286. Dispose(true);
  287. GC.SuppressFinalize(this);
  288. }
  289. /// <summary>
  290. /// Releases unmanaged and - optionally - managed resources.
  291. /// </summary>
  292. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  293. protected virtual void Dispose(bool dispose)
  294. {
  295. }
  296. /// <summary>
  297. /// Returns true or false indicating if the provider should refresh when the contents of it's directory changes
  298. /// </summary>
  299. /// <value><c>true</c> if [refresh on file system stamp change]; otherwise, <c>false</c>.</value>
  300. protected virtual bool RefreshOnFileSystemStampChange
  301. {
  302. get
  303. {
  304. return false;
  305. }
  306. }
  307. /// <summary>
  308. /// Determines if the parent's file system stamp should be used for comparison
  309. /// </summary>
  310. /// <param name="item">The item.</param>
  311. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  312. protected virtual bool UseParentFileSystemStamp(BaseItem item)
  313. {
  314. // True when the current item is just a file
  315. return !item.ResolveArgs.IsDirectory;
  316. }
  317. /// <summary>
  318. /// Gets the item's current file system stamp
  319. /// </summary>
  320. /// <param name="item">The item.</param>
  321. /// <returns>Guid.</returns>
  322. private Guid GetCurrentFileSystemStamp(BaseItem item)
  323. {
  324. if (UseParentFileSystemStamp(item) && item.Parent != null)
  325. {
  326. return item.Parent.FileSystemStamp;
  327. }
  328. return item.FileSystemStamp;
  329. }
  330. }
  331. /// <summary>
  332. /// Determines when a provider should execute, relative to others
  333. /// </summary>
  334. public enum MetadataProviderPriority
  335. {
  336. // Run this provider at the beginning
  337. /// <summary>
  338. /// The first
  339. /// </summary>
  340. First = 1,
  341. // Run this provider after all first priority providers
  342. /// <summary>
  343. /// The second
  344. /// </summary>
  345. Second = 2,
  346. // Run this provider after all second priority providers
  347. /// <summary>
  348. /// The third
  349. /// </summary>
  350. Third = 3,
  351. // Run this provider last
  352. /// <summary>
  353. /// The last
  354. /// </summary>
  355. Last = 4
  356. }
  357. }