BaseMetadataProvider.cs 16 KB

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