CrawlerHandler.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using Masuit.MyBlogs.Core.Common;
  2. using Masuit.Tools;
  3. using Microsoft.AspNetCore.Http;
  4. using System;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. namespace Masuit.MyBlogs.Core.Extensions.UEditor
  10. {
  11. /// <summary>
  12. /// Crawler 的摘要说明
  13. /// </summary>
  14. public class CrawlerHandler : Handler
  15. {
  16. public CrawlerHandler(HttpContext context) : base(context)
  17. {
  18. }
  19. public override string Process()
  20. {
  21. string[] sources = Request.Form["source[]"];
  22. if (sources?.Length > 0)
  23. {
  24. return WriteJson(new
  25. {
  26. state = "SUCCESS",
  27. list = sources.AsParallel().Select(s => new Crawler(s).Fetch()).Select(x => new
  28. {
  29. state = x.State,
  30. source = x.SourceUrl,
  31. url = x.ServerUrl
  32. })
  33. });
  34. }
  35. return WriteJson(new
  36. {
  37. state = "参数错误:没有指定抓取源"
  38. });
  39. }
  40. }
  41. public class Crawler
  42. {
  43. public string SourceUrl { get; set; }
  44. public string ServerUrl { get; set; }
  45. public string State { get; set; }
  46. private readonly HttpClient _httpClient = new HttpClient();
  47. public Crawler(string sourceUrl)
  48. {
  49. SourceUrl = sourceUrl;
  50. }
  51. public Crawler Fetch()
  52. {
  53. if (!SourceUrl.IsExternalAddress())
  54. {
  55. State = "INVALID_URL";
  56. return this;
  57. }
  58. var response = _httpClient.GetAsync(SourceUrl).Result;
  59. if (response.StatusCode != HttpStatusCode.OK)
  60. {
  61. State = "Url returns " + response.StatusCode;
  62. return this;
  63. }
  64. ServerUrl = PathFormatter.Format(Path.GetFileName(SourceUrl), UeditorConfig.GetString("catcherPathFormat"));
  65. try
  66. {
  67. using (var stream = response.Content.ReadAsStreamAsync().Result)
  68. {
  69. var savePath = AppContext.BaseDirectory + "wwwroot" + ServerUrl;
  70. var (url, success) = new ImagebedClient(_httpClient).UploadImage(stream, savePath).Result;
  71. if (success)
  72. {
  73. ServerUrl = url;
  74. }
  75. else
  76. {
  77. if (!Directory.Exists(Path.GetDirectoryName(savePath)))
  78. {
  79. Directory.CreateDirectory(Path.GetDirectoryName(savePath));
  80. }
  81. using (var ms = new MemoryStream())
  82. {
  83. stream.CopyTo(ms);
  84. File.WriteAllBytes(savePath, ms.GetBuffer());
  85. }
  86. }
  87. }
  88. State = "SUCCESS";
  89. }
  90. catch (Exception e)
  91. {
  92. State = "抓取错误:" + e.Message;
  93. }
  94. return this;
  95. }
  96. }
  97. }