BaseMetadataProvider.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. using System.IO;
  2. using System.Linq;
  3. using System.Text;
  4. using MediaBrowser.Common.Extensions;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using System;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. namespace MediaBrowser.Controller.Providers
  14. {
  15. /// <summary>
  16. /// Class BaseMetadataProvider
  17. /// </summary>
  18. public abstract class BaseMetadataProvider
  19. {
  20. /// <summary>
  21. /// Gets the logger.
  22. /// </summary>
  23. /// <value>The logger.</value>
  24. protected ILogger Logger { get; set; }
  25. protected ILogManager LogManager { get; set; }
  26. /// <summary>
  27. /// Gets the configuration manager.
  28. /// </summary>
  29. /// <value>The configuration manager.</value>
  30. protected IServerConfigurationManager ConfigurationManager { get; private set; }
  31. /// <summary>
  32. /// The _id
  33. /// </summary>
  34. protected readonly Guid Id;
  35. /// <summary>
  36. /// The true task result
  37. /// </summary>
  38. protected static readonly Task<bool> TrueTaskResult = Task.FromResult(true);
  39. protected static readonly Task<bool> FalseTaskResult = Task.FromResult(false);
  40. protected static readonly SemaphoreSlim XmlParsingResourcePool = new SemaphoreSlim(5, 5);
  41. /// <summary>
  42. /// Supportses the specified item.
  43. /// </summary>
  44. /// <param name="item">The item.</param>
  45. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  46. public abstract bool Supports(BaseItem item);
  47. /// <summary>
  48. /// Gets a value indicating whether [requires internet].
  49. /// </summary>
  50. /// <value><c>true</c> if [requires internet]; otherwise, <c>false</c>.</value>
  51. public virtual bool RequiresInternet
  52. {
  53. get
  54. {
  55. return false;
  56. }
  57. }
  58. /// <summary>
  59. /// Gets the provider version.
  60. /// </summary>
  61. /// <value>The provider version.</value>
  62. protected virtual string ProviderVersion
  63. {
  64. get
  65. {
  66. return null;
  67. }
  68. }
  69. /// <summary>
  70. /// Gets a value indicating whether [refresh on version change].
  71. /// </summary>
  72. /// <value><c>true</c> if [refresh on version change]; otherwise, <c>false</c>.</value>
  73. protected virtual bool RefreshOnVersionChange
  74. {
  75. get
  76. {
  77. return false;
  78. }
  79. }
  80. /// <summary>
  81. /// Determines if this provider is relatively slow and, therefore, should be skipped
  82. /// in certain instances. Default is whether or not it requires internet. Can be overridden
  83. /// for explicit designation.
  84. /// </summary>
  85. /// <value><c>true</c> if this instance is slow; otherwise, <c>false</c>.</value>
  86. public virtual bool IsSlow
  87. {
  88. get { return RequiresInternet; }
  89. }
  90. /// <summary>
  91. /// Initializes a new instance of the <see cref="BaseMetadataProvider" /> class.
  92. /// </summary>
  93. protected BaseMetadataProvider(ILogManager logManager, IServerConfigurationManager configurationManager)
  94. {
  95. Logger = logManager.GetLogger(GetType().Name);
  96. LogManager = logManager;
  97. ConfigurationManager = configurationManager;
  98. Id = GetType().FullName.GetMD5();
  99. Initialize();
  100. }
  101. /// <summary>
  102. /// Initializes this instance.
  103. /// </summary>
  104. protected virtual void Initialize()
  105. {
  106. }
  107. /// <summary>
  108. /// Sets the persisted last refresh date on the item for this provider.
  109. /// </summary>
  110. /// <param name="item">The item.</param>
  111. /// <param name="value">The value.</param>
  112. /// <param name="providerVersion">The provider version.</param>
  113. /// <param name="status">The status.</param>
  114. /// <exception cref="System.ArgumentNullException">item</exception>
  115. public virtual void SetLastRefreshed(BaseItem item, DateTime value, string providerVersion, ProviderRefreshStatus status = ProviderRefreshStatus.Success)
  116. {
  117. if (item == null)
  118. {
  119. throw new ArgumentNullException("item");
  120. }
  121. BaseProviderInfo data;
  122. if (!item.ProviderData.TryGetValue(Id, out data))
  123. {
  124. data = new BaseProviderInfo();
  125. }
  126. data.LastRefreshed = value;
  127. data.LastRefreshStatus = status;
  128. data.ProviderVersion = providerVersion;
  129. // Save the file system stamp for future comparisons
  130. if (RefreshOnFileSystemStampChange && item.LocationType == LocationType.FileSystem)
  131. {
  132. data.FileStamp = GetCurrentFileSystemStamp(item);
  133. }
  134. item.ProviderData[Id] = data;
  135. }
  136. /// <summary>
  137. /// Sets the last refreshed.
  138. /// </summary>
  139. /// <param name="item">The item.</param>
  140. /// <param name="value">The value.</param>
  141. /// <param name="status">The status.</param>
  142. public void SetLastRefreshed(BaseItem item, DateTime value, ProviderRefreshStatus status = ProviderRefreshStatus.Success)
  143. {
  144. SetLastRefreshed(item, value, ProviderVersion, status);
  145. }
  146. /// <summary>
  147. /// Returns whether or not this provider should be re-fetched. Default functionality can
  148. /// compare a provided date with a last refresh time. This can be overridden for more complex
  149. /// determinations.
  150. /// </summary>
  151. /// <param name="item">The item.</param>
  152. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  153. /// <exception cref="System.ArgumentNullException"></exception>
  154. public bool NeedsRefresh(BaseItem item)
  155. {
  156. if (item == null)
  157. {
  158. throw new ArgumentNullException();
  159. }
  160. BaseProviderInfo data;
  161. if (!item.ProviderData.TryGetValue(Id, out data))
  162. {
  163. data = new BaseProviderInfo();
  164. }
  165. return NeedsRefreshInternal(item, data);
  166. }
  167. /// <summary>
  168. /// Needses the refresh internal.
  169. /// </summary>
  170. /// <param name="item">The item.</param>
  171. /// <param name="providerInfo">The provider info.</param>
  172. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  173. /// <exception cref="System.ArgumentNullException"></exception>
  174. protected virtual bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
  175. {
  176. if (item == null)
  177. {
  178. throw new ArgumentNullException("item");
  179. }
  180. if (providerInfo == null)
  181. {
  182. throw new ArgumentNullException("providerInfo");
  183. }
  184. if (CompareDate(item) > providerInfo.LastRefreshed)
  185. {
  186. return true;
  187. }
  188. if (RefreshOnFileSystemStampChange && item.LocationType == LocationType.FileSystem && HasFileSystemStampChanged(item, providerInfo))
  189. {
  190. return true;
  191. }
  192. if (RefreshOnVersionChange && !String.Equals(ProviderVersion, providerInfo.ProviderVersion))
  193. {
  194. return true;
  195. }
  196. if (RequiresInternet && DateTime.UtcNow > (providerInfo.LastRefreshed.AddDays(ConfigurationManager.Configuration.MetadataRefreshDays)))
  197. {
  198. return true;
  199. }
  200. if (providerInfo.LastRefreshStatus != ProviderRefreshStatus.Success)
  201. {
  202. return true;
  203. }
  204. return false;
  205. }
  206. /// <summary>
  207. /// Determines if the item's file system stamp has changed from the last time the provider refreshed
  208. /// </summary>
  209. /// <param name="item">The item.</param>
  210. /// <param name="providerInfo">The provider info.</param>
  211. /// <returns><c>true</c> if [has file system stamp changed] [the specified item]; otherwise, <c>false</c>.</returns>
  212. protected bool HasFileSystemStampChanged(BaseItem item, BaseProviderInfo providerInfo)
  213. {
  214. return GetCurrentFileSystemStamp(item) != providerInfo.FileStamp;
  215. }
  216. /// <summary>
  217. /// Override this to return the date that should be compared to the last refresh date
  218. /// to determine if this provider should be re-fetched.
  219. /// </summary>
  220. /// <param name="item">The item.</param>
  221. /// <returns>DateTime.</returns>
  222. protected virtual DateTime CompareDate(BaseItem item)
  223. {
  224. return DateTime.MinValue.AddMinutes(1); // want this to be greater than mindate so new items will refresh
  225. }
  226. /// <summary>
  227. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  228. /// </summary>
  229. /// <param name="item">The item.</param>
  230. /// <param name="force">if set to <c>true</c> [force].</param>
  231. /// <param name="cancellationToken">The cancellation token.</param>
  232. /// <returns>Task{System.Boolean}.</returns>
  233. /// <exception cref="System.ArgumentNullException"></exception>
  234. public abstract Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken);
  235. /// <summary>
  236. /// Gets the priority.
  237. /// </summary>
  238. /// <value>The priority.</value>
  239. public abstract MetadataProviderPriority Priority { get; }
  240. /// <summary>
  241. /// Returns true or false indicating if the provider should refresh when the contents of it's directory changes
  242. /// </summary>
  243. /// <value><c>true</c> if [refresh on file system stamp change]; otherwise, <c>false</c>.</value>
  244. protected virtual bool RefreshOnFileSystemStampChange
  245. {
  246. get
  247. {
  248. return false;
  249. }
  250. }
  251. protected virtual string[] FilestampExtensions
  252. {
  253. get { return new string[] { }; }
  254. }
  255. /// <summary>
  256. /// Determines if the parent's file system stamp should be used for comparison
  257. /// </summary>
  258. /// <param name="item">The item.</param>
  259. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  260. protected virtual bool UseParentFileSystemStamp(BaseItem item)
  261. {
  262. // True when the current item is just a file
  263. return !item.ResolveArgs.IsDirectory;
  264. }
  265. /// <summary>
  266. /// Gets the item's current file system stamp
  267. /// </summary>
  268. /// <param name="item">The item.</param>
  269. /// <returns>Guid.</returns>
  270. private Guid GetCurrentFileSystemStamp(BaseItem item)
  271. {
  272. if (UseParentFileSystemStamp(item) && item.Parent != null)
  273. {
  274. return GetFileSystemStamp(item.Parent);
  275. }
  276. return GetFileSystemStamp(item);
  277. }
  278. /// <summary>
  279. /// Gets the file system stamp.
  280. /// </summary>
  281. /// <param name="item">The item.</param>
  282. /// <returns>Guid.</returns>
  283. private Guid GetFileSystemStamp(BaseItem item)
  284. {
  285. // If there's no path or the item is a file, there's nothing to do
  286. if (item.LocationType != LocationType.FileSystem)
  287. {
  288. return Guid.Empty;
  289. }
  290. ItemResolveArgs resolveArgs;
  291. try
  292. {
  293. resolveArgs = item.ResolveArgs;
  294. }
  295. catch (IOException ex)
  296. {
  297. Logger.ErrorException("Error determining if path is directory: {0}", ex, item.Path);
  298. throw;
  299. }
  300. if (!resolveArgs.IsDirectory)
  301. {
  302. return Guid.Empty;
  303. }
  304. var sb = new StringBuilder();
  305. var extensions = FilestampExtensions;
  306. // Record the name of each file
  307. // Need to sort these because accoring to msdn docs, our i/o methods are not guaranteed in any order
  308. foreach (var file in resolveArgs.FileSystemChildren
  309. .Where(i => IncludeInFileStamp(i, extensions))
  310. .OrderBy(f => f.Name))
  311. {
  312. sb.Append(file.Name);
  313. }
  314. foreach (var file in resolveArgs.MetadataFiles
  315. .Where(i => IncludeInFileStamp(i, extensions))
  316. .OrderBy(f => f.Name))
  317. {
  318. sb.Append(file.Name);
  319. }
  320. return sb.ToString().GetMD5();
  321. }
  322. /// <summary>
  323. /// Includes the in file stamp.
  324. /// </summary>
  325. /// <param name="file">The file.</param>
  326. /// <param name="extensions">The extensions.</param>
  327. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  328. private bool IncludeInFileStamp(FileSystemInfo file, string[] extensions)
  329. {
  330. if ((file.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
  331. {
  332. return false;
  333. }
  334. return extensions.Length == 0 || extensions.Contains(file.Extension, StringComparer.OrdinalIgnoreCase);
  335. }
  336. }
  337. }