BaseMetadataProvider.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. public virtual ItemUpdateType ItemUpdateType
  70. {
  71. get { return RequiresInternet ? ItemUpdateType.MetadataDownload : ItemUpdateType.MetadataImport; }
  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, IServerConfigurationManager configurationManager)
  98. {
  99. Logger = logManager.GetLogger(GetType().Name);
  100. LogManager = logManager;
  101. ConfigurationManager = configurationManager;
  102. Id = GetType().FullName.GetMD5();
  103. Initialize();
  104. }
  105. /// <summary>
  106. /// Initializes this instance.
  107. /// </summary>
  108. protected virtual void Initialize()
  109. {
  110. }
  111. /// <summary>
  112. /// Sets the persisted last refresh date on the item for this provider.
  113. /// </summary>
  114. /// <param name="item">The item.</param>
  115. /// <param name="value">The value.</param>
  116. /// <param name="providerVersion">The provider version.</param>
  117. /// <param name="status">The status.</param>
  118. /// <exception cref="System.ArgumentNullException">item</exception>
  119. public virtual void SetLastRefreshed(BaseItem item, DateTime value, string providerVersion, ProviderRefreshStatus status = ProviderRefreshStatus.Success)
  120. {
  121. if (item == null)
  122. {
  123. throw new ArgumentNullException("item");
  124. }
  125. BaseProviderInfo data;
  126. if (!item.ProviderData.TryGetValue(Id, out data))
  127. {
  128. data = new BaseProviderInfo();
  129. }
  130. data.LastRefreshed = value;
  131. data.LastRefreshStatus = status;
  132. data.ProviderVersion = providerVersion;
  133. // Save the file system stamp for future comparisons
  134. if (RefreshOnFileSystemStampChange && item.LocationType == LocationType.FileSystem)
  135. {
  136. try
  137. {
  138. data.FileStamp = GetCurrentFileSystemStamp(item);
  139. }
  140. catch (IOException ex)
  141. {
  142. Logger.ErrorException("Error getting file stamp for {0}", ex, item.Path);
  143. }
  144. }
  145. item.ProviderData[Id] = data;
  146. }
  147. /// <summary>
  148. /// Sets the last refreshed.
  149. /// </summary>
  150. /// <param name="item">The item.</param>
  151. /// <param name="value">The value.</param>
  152. /// <param name="status">The status.</param>
  153. public void SetLastRefreshed(BaseItem item, DateTime value, ProviderRefreshStatus status = ProviderRefreshStatus.Success)
  154. {
  155. SetLastRefreshed(item, value, ProviderVersion, status);
  156. }
  157. /// <summary>
  158. /// Returns whether or not this provider should be re-fetched. Default functionality can
  159. /// compare a provided date with a last refresh time. This can be overridden for more complex
  160. /// determinations.
  161. /// </summary>
  162. /// <param name="item">The item.</param>
  163. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  164. /// <exception cref="System.ArgumentNullException"></exception>
  165. public bool NeedsRefresh(BaseItem item)
  166. {
  167. if (item == null)
  168. {
  169. throw new ArgumentNullException();
  170. }
  171. BaseProviderInfo data;
  172. if (!item.ProviderData.TryGetValue(Id, out data))
  173. {
  174. data = new BaseProviderInfo();
  175. }
  176. return NeedsRefreshInternal(item, data);
  177. }
  178. /// <summary>
  179. /// Needses the refresh internal.
  180. /// </summary>
  181. /// <param name="item">The item.</param>
  182. /// <param name="providerInfo">The provider info.</param>
  183. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  184. /// <exception cref="System.ArgumentNullException"></exception>
  185. protected virtual bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
  186. {
  187. if (item == null)
  188. {
  189. throw new ArgumentNullException("item");
  190. }
  191. if (providerInfo == null)
  192. {
  193. throw new ArgumentNullException("providerInfo");
  194. }
  195. if (CompareDate(item) > providerInfo.LastRefreshed)
  196. {
  197. return true;
  198. }
  199. if (RefreshOnFileSystemStampChange && item.LocationType == LocationType.FileSystem && HasFileSystemStampChanged(item, providerInfo))
  200. {
  201. return true;
  202. }
  203. if (RefreshOnVersionChange && !String.Equals(ProviderVersion, providerInfo.ProviderVersion))
  204. {
  205. return true;
  206. }
  207. if (RequiresInternet && DateTime.UtcNow > (providerInfo.LastRefreshed.AddDays(ConfigurationManager.Configuration.MetadataRefreshDays)))
  208. {
  209. return true;
  210. }
  211. if (providerInfo.LastRefreshStatus != ProviderRefreshStatus.Success)
  212. {
  213. return true;
  214. }
  215. return false;
  216. }
  217. /// <summary>
  218. /// Determines if the item's file system stamp has changed from the last time the provider refreshed
  219. /// </summary>
  220. /// <param name="item">The item.</param>
  221. /// <param name="providerInfo">The provider info.</param>
  222. /// <returns><c>true</c> if [has file system stamp changed] [the specified item]; otherwise, <c>false</c>.</returns>
  223. protected bool HasFileSystemStampChanged(BaseItem item, BaseProviderInfo providerInfo)
  224. {
  225. return GetCurrentFileSystemStamp(item) != providerInfo.FileStamp;
  226. }
  227. /// <summary>
  228. /// Override this to return the date that should be compared to the last refresh date
  229. /// to determine if this provider should be re-fetched.
  230. /// </summary>
  231. /// <param name="item">The item.</param>
  232. /// <returns>DateTime.</returns>
  233. protected virtual DateTime CompareDate(BaseItem item)
  234. {
  235. return DateTime.MinValue.AddMinutes(1); // want this to be greater than mindate so new items will refresh
  236. }
  237. /// <summary>
  238. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  239. /// </summary>
  240. /// <param name="item">The item.</param>
  241. /// <param name="force">if set to <c>true</c> [force].</param>
  242. /// <param name="cancellationToken">The cancellation token.</param>
  243. /// <returns>Task{System.Boolean}.</returns>
  244. /// <exception cref="System.ArgumentNullException"></exception>
  245. public abstract Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken);
  246. /// <summary>
  247. /// Gets the priority.
  248. /// </summary>
  249. /// <value>The priority.</value>
  250. public abstract MetadataProviderPriority Priority { get; }
  251. /// <summary>
  252. /// Returns true or false indicating if the provider should refresh when the contents of it's directory changes
  253. /// </summary>
  254. /// <value><c>true</c> if [refresh on file system stamp change]; otherwise, <c>false</c>.</value>
  255. protected virtual bool RefreshOnFileSystemStampChange
  256. {
  257. get
  258. {
  259. return false;
  260. }
  261. }
  262. protected virtual string[] FilestampExtensions
  263. {
  264. get { return new string[] { }; }
  265. }
  266. /// <summary>
  267. /// Determines if the parent's file system stamp should be used for comparison
  268. /// </summary>
  269. /// <param name="item">The item.</param>
  270. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  271. protected virtual bool UseParentFileSystemStamp(BaseItem item)
  272. {
  273. // True when the current item is just a file
  274. return !item.ResolveArgs.IsDirectory;
  275. }
  276. /// <summary>
  277. /// Gets the item's current file system stamp
  278. /// </summary>
  279. /// <param name="item">The item.</param>
  280. /// <returns>Guid.</returns>
  281. private Guid GetCurrentFileSystemStamp(BaseItem item)
  282. {
  283. if (UseParentFileSystemStamp(item) && item.Parent != null)
  284. {
  285. return GetFileSystemStamp(item.Parent);
  286. }
  287. return GetFileSystemStamp(item);
  288. }
  289. /// <summary>
  290. /// Gets the file system stamp.
  291. /// </summary>
  292. /// <param name="item">The item.</param>
  293. /// <returns>Guid.</returns>
  294. private Guid GetFileSystemStamp(BaseItem item)
  295. {
  296. // If there's no path or the item is a file, there's nothing to do
  297. if (item.LocationType != LocationType.FileSystem)
  298. {
  299. return Guid.Empty;
  300. }
  301. ItemResolveArgs resolveArgs;
  302. try
  303. {
  304. resolveArgs = item.ResolveArgs;
  305. }
  306. catch (IOException ex)
  307. {
  308. Logger.ErrorException("Error determining if path is directory: {0}", ex, item.Path);
  309. throw;
  310. }
  311. if (!resolveArgs.IsDirectory)
  312. {
  313. return Guid.Empty;
  314. }
  315. var sb = new StringBuilder();
  316. var extensions = FilestampExtensions;
  317. // Record the name of each file
  318. // Need to sort these because accoring to msdn docs, our i/o methods are not guaranteed in any order
  319. foreach (var file in resolveArgs.FileSystemChildren
  320. .Where(i => IncludeInFileStamp(i, extensions))
  321. .OrderBy(f => f.Name))
  322. {
  323. sb.Append(file.Name);
  324. }
  325. foreach (var file in resolveArgs.MetadataFiles
  326. .Where(i => IncludeInFileStamp(i, extensions))
  327. .OrderBy(f => f.Name))
  328. {
  329. sb.Append(file.Name);
  330. }
  331. return sb.ToString().GetMD5();
  332. }
  333. /// <summary>
  334. /// Includes the in file stamp.
  335. /// </summary>
  336. /// <param name="file">The file.</param>
  337. /// <param name="extensions">The extensions.</param>
  338. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  339. private bool IncludeInFileStamp(FileSystemInfo file, string[] extensions)
  340. {
  341. if ((file.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
  342. {
  343. return false;
  344. }
  345. return extensions.Length == 0 || extensions.Contains(file.Extension, StringComparer.OrdinalIgnoreCase);
  346. }
  347. }
  348. }