ImagebedClient.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. using Hangfire;
  2. using Masuit.MyBlogs.Core.Configs;
  3. using Masuit.Tools.Html;
  4. using Masuit.Tools.Logging;
  5. using System.Net.Http.Headers;
  6. using System.Text.RegularExpressions;
  7. using System.Web;
  8. namespace Masuit.MyBlogs.Core.Common
  9. {
  10. /// <summary>
  11. /// 图床客户端
  12. /// </summary>
  13. public sealed class ImagebedClient
  14. {
  15. private readonly HttpClient _httpClient;
  16. private readonly IConfiguration _config;
  17. /// <summary>
  18. /// 图床客户端
  19. /// </summary>
  20. /// <param name="httpClient"></param>
  21. /// <param name="config"></param>
  22. public ImagebedClient(HttpClient httpClient, IConfiguration config)
  23. {
  24. _config = config;
  25. _httpClient = httpClient;
  26. }
  27. private readonly List<string> _failedList = new();
  28. /// <summary>
  29. /// 上传图片
  30. /// </summary>
  31. /// <param name="stream"></param>
  32. /// <param name="file"></param>
  33. /// <returns></returns>
  34. public Task<(string url, bool success)> UploadImage(Stream stream, string file, CancellationToken cancellationToken)
  35. {
  36. if (stream.Length < 51200)
  37. {
  38. return Task.FromResult<(string, bool)>((null, false));
  39. }
  40. file = Regex.Replace(Path.GetFileName(file), @"\p{P}|\p{S}", "");
  41. var gitlabs = AppConfig.GitlabConfigs.Where(c => c.FileLimitSize >= stream.Length && !_failedList.Contains(c.ApiUrl)).OrderByRandom().ToList();
  42. if (gitlabs.Count > 0)
  43. {
  44. var gitlab = gitlabs[0];
  45. if (gitlab.ApiUrl.Contains("api.github.com"))
  46. {
  47. return UploadGithub(gitlab, stream, file, cancellationToken);
  48. }
  49. return UploadGitlab(gitlab, stream, file, cancellationToken);
  50. }
  51. return Task.FromResult<(string, bool)>((null, false));
  52. }
  53. /// <summary>
  54. /// github图床
  55. /// </summary>
  56. /// <param name="config"></param>
  57. /// <param name="stream"></param>
  58. /// <param name="file"></param>
  59. /// <returns></returns>
  60. private Task<(string url, bool success)> UploadGithub(GitlabConfig config, Stream stream, string file, CancellationToken cancellationToken)
  61. {
  62. var path = $"{DateTime.Now:yyyy\\/MM\\/dd}/{file}";
  63. _httpClient.DefaultRequestHeaders.UserAgent.Add(ProductInfoHeaderValue.Parse("Awesome-Octocat-App"));
  64. _httpClient.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse("token " + config.AccessToken);
  65. return _httpClient.PutAsJsonAsync(config.ApiUrl + HttpUtility.UrlEncode(path), new
  66. {
  67. message = SnowFlake.NewId,
  68. committer = new
  69. {
  70. name = SnowFlake.NewId,
  71. email = "[email protected]"
  72. },
  73. content = Convert.ToBase64String(stream.ToArray())
  74. }, cancellationToken).ContinueWith(t =>
  75. {
  76. if (t.IsCompletedSuccessfully)
  77. {
  78. using var resp = t.Result;
  79. using var content = resp.Content;
  80. if (resp.IsSuccessStatusCode)
  81. {
  82. return (config.RawUrl.Split(',').OrderByRandom().FirstOrDefault() + path, true);
  83. }
  84. }
  85. LogManager.Info("图片上传到gitee失败。");
  86. return (null, false);
  87. });
  88. }
  89. /// <summary>
  90. /// github图床
  91. /// </summary>
  92. /// <param name="config"></param>
  93. /// <param name="stream"></param>
  94. /// <param name="file"></param>
  95. /// <returns></returns>
  96. private Task<(string url, bool success)> UploadGitlab(GitlabConfig config, Stream stream, string file, CancellationToken cancellationToken)
  97. {
  98. var path = $"{DateTime.Now:yyyy\\/MM\\/dd}/{file}";
  99. _httpClient.DefaultRequestHeaders.Add("PRIVATE-TOKEN", config.AccessToken);
  100. return _httpClient.PostAsJsonAsync(config.ApiUrl.Contains("/v3/") ? config.ApiUrl : config.ApiUrl + HttpUtility.UrlEncode(path), new
  101. {
  102. file_path = path,
  103. branch_name = config.Branch,
  104. branch = config.Branch,
  105. author_email = CommonHelper.SystemSettings["ReceiveEmail"],
  106. author_name = SnowFlake.NewId,
  107. encoding = "base64",
  108. content = Convert.ToBase64String(stream.ToArray()),
  109. commit_message = SnowFlake.NewId
  110. }, cancellationToken).ContinueWith(t =>
  111. {
  112. if (t.IsCompletedSuccessfully)
  113. {
  114. using var resp = t.Result;
  115. using var content = resp.Content;
  116. if (resp.IsSuccessStatusCode || content.ReadAsStringAsync().Result.Contains("already exists"))
  117. {
  118. return (config.RawUrl + path, true);
  119. }
  120. }
  121. LogManager.Info($"图片上传到gitlab({config.ApiUrl})失败。");
  122. _failedList.Add(config.ApiUrl);
  123. return (null, false);
  124. });
  125. }
  126. /// <summary>
  127. /// 替换img标签的src属性
  128. /// </summary>
  129. /// <param name="content"></param>
  130. /// <returns></returns>
  131. public async Task<string> ReplaceImgSrc(string content, CancellationToken cancellationToken)
  132. {
  133. if (bool.TryParse(_config["Imgbed:EnableLocalStorage"], out var b) && b)
  134. {
  135. return content;
  136. }
  137. var srcs = content.MatchImgSrcs();
  138. foreach (var src in srcs)
  139. {
  140. if (src.StartsWith("http"))
  141. {
  142. continue;
  143. }
  144. var path = Path.Combine(AppContext.BaseDirectory + "wwwroot", src.Replace("/", @"\")[1..]);
  145. if (!File.Exists(path))
  146. {
  147. continue;
  148. }
  149. await using var stream = File.OpenRead(path);
  150. var (url, success) = await UploadImage(stream, path, cancellationToken);
  151. if (success)
  152. {
  153. content = content.Replace(src, url);
  154. BackgroundJob.Enqueue(() => File.Delete(path));
  155. }
  156. }
  157. return content;
  158. }
  159. }
  160. }