HotmailService.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. using Microsoft.AspNetCore.WebUtilities;
  2. using Microsoft.Graph;
  3. using Microsoft.Graph.Models;
  4. using Microsoft.Graph.Models.ODataErrors;
  5. using Microsoft.Kiota.Abstractions.Authentication;
  6. using System.Collections.Concurrent;
  7. using System.Text.Json;
  8. using System.Text.Json.Serialization;
  9. using JsonSerializer = System.Text.Json.JsonSerializer;
  10. namespace OASystem.API.OAMethodLib.Hotmail
  11. {
  12. public class HotmailService
  13. {
  14. private readonly IHttpClientFactory _httpClientFactory;
  15. private readonly IConfiguration _config;
  16. private readonly SqlSugarClient _sqlSugar;
  17. public const string RedisKeyPrefix = "MailAlchemy:Token:";
  18. public HotmailService(IHttpClientFactory httpClientFactory, IConfiguration config, SqlSugarClient sqlSugar)
  19. {
  20. _httpClientFactory = httpClientFactory;
  21. _config = config;
  22. _sqlSugar = sqlSugar;
  23. }
  24. /// <summary>
  25. /// 统一获取 Redis Key
  26. /// </summary>
  27. public static string GetRedisKey(string email) => $"{RedisKeyPrefix}{email.Trim().ToLower()}";
  28. /// <summary>
  29. /// hotmail 信息验证
  30. /// </summary>
  31. /// <param name="config"></param>
  32. /// <returns></returns>
  33. public (bool, string) ConfigVerify(HotmailConfig? config)
  34. {
  35. if (config == null) return (true, "当前用户未配置 hotmail 基础信息。");
  36. if (string.IsNullOrEmpty(config.UserName)) return (true, "当前用户未配置 hotmail 基础信息。");
  37. if (string.IsNullOrEmpty(config.ClientId)) return (true, "当前用户未配置 hotmail 租户标识符 (Guid)。");
  38. if (string.IsNullOrEmpty(config.TenantId)) return (true, "当前用户未配置 hotmail 应用程序的客户端标识。");
  39. if (string.IsNullOrEmpty(config.ClientSecret)) return (true, "当前用户未配置 hotmail 应用程序密钥。");
  40. if (string.IsNullOrEmpty(config.RedirectUri)) return (true, "当前用户未配置 hotmail OAuth2 回调重定向地址。");
  41. return (true, "");
  42. }
  43. /// <summary>
  44. /// Microsoft 鉴权预处理
  45. /// </summary>
  46. public async Task<(int status, string msg)> PrepareAuth(int userId)
  47. {
  48. // 1. 基础配置校验 (SqlSugar 优化)
  49. var userConfig = await GetUserMailConfig(userId);
  50. if (userConfig == null || string.IsNullOrWhiteSpace(userConfig.UserName))
  51. return (-1, "账号基础配置缺失");
  52. // 2. 状态检查 (Redis)
  53. var redisKey = GetRedisKey(userConfig.UserName);
  54. var repo = RedisRepository.RedisFactory.CreateRedisRepository();
  55. var cachedJson = await repo.StringGetAsync<string>(redisKey);
  56. if (!string.IsNullOrWhiteSpace(cachedJson))
  57. return (0, "已通过验证,无需重复操作");
  58. // 3. 参数净化与严谨性
  59. var clientId = userConfig.ClientId?.Trim();
  60. var redirectUri = userConfig.RedirectUri?.Trim().Split('\r', '\n')[0]; // 取第一行并修剪
  61. if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(redirectUri))
  62. return (-1, "ClientId 或 RedirectUri 配置无效");
  63. // 4. 构建长效授权 URL
  64. const string authEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize";
  65. var queryParams = new Dictionary<string, string?>
  66. {
  67. { "client_id", clientId },
  68. { "response_type", "code" },
  69. { "redirect_uri", redirectUri },
  70. { "response_mode", "query" },
  71. // 核心:必须包含 offline_access 且建议加上 openid
  72. { "scope", "openid offline_access Mail.ReadWrite Mail.Send User.Read" },
  73. { "state", userId.ToString() }, // 简单场景使用 userId,安全场景建议使用加密 Hash
  74. { "prompt", "consent" } // 关键:确保触发长效令牌授权
  75. };
  76. var authUrl = QueryHelpers.AddQueryString(authEndpoint, queryParams);
  77. // 准则 4a: 直接返回结果
  78. return (1, authUrl);
  79. }
  80. public async Task<List<MailDto>> GetMergedMessagesAsync(List<string> emails, DateTime cstStart, DateTime cstEnd)
  81. {
  82. // 线程安全的合并容器
  83. var allMessages = new ConcurrentBag<MailDto>();
  84. // 转换过滤条件 (建议预先处理)
  85. string startFilter = CommonFun.ToGraphUtcString(cstStart);
  86. string endFilter = CommonFun.ToGraphUtcString(cstEnd);
  87. // 配置并发参数:限制最大并行度,防止被 Graph API 熔断
  88. var parallelOptions = new ParallelOptions
  89. {
  90. MaxDegreeOfParallelism = 5 // 根据服务器性能调整
  91. };
  92. await Parallel.ForEachAsync(emails, parallelOptions, async (email, ct) =>
  93. {
  94. try
  95. {
  96. var client = await GetClientAsync(email);
  97. var response = await client.Me.Messages.GetAsync(q =>
  98. {
  99. q.QueryParameters.Filter = $"receivedDateTime ge {startFilter} and receivedDateTime le {endFilter}";
  100. q.QueryParameters.Select = new[] { "id", "subject", "from", "bodyPreview", "receivedDateTime" };
  101. q.QueryParameters.Orderby = new[] { "receivedDateTime desc" };
  102. q.QueryParameters.Top = 50; // 生产环境建议增加 Top 限制
  103. }, ct);
  104. if (response?.Value != null)
  105. {
  106. var chinaTimeZone = TimeZoneInfo.FindSystemTimeZoneById("China Standard Time");
  107. foreach (var m in response.Value)
  108. {
  109. allMessages.Add(new MailDto
  110. {
  111. MessageId = m.Id,
  112. Subject = m.Subject,
  113. Content = m.BodyPreview,
  114. From = m.From?.EmailAddress?.Address,
  115. To = email,
  116. ReceivedTime = m.ReceivedDateTime?.DateTime != null
  117. ? TimeZoneInfo.ConvertTimeFromUtc(m.ReceivedDateTime.Value.DateTime, chinaTimeZone)
  118. : DateTime.MinValue,
  119. Source = email // 显式来源
  120. });
  121. }
  122. }
  123. }
  124. catch (Exception ex)
  125. {
  126. // 生产环境应接入 ILogger
  127. //_logger.LogError(ex, "Failed to fetch mail for {Email}", email);
  128. }
  129. });
  130. // 最终排序并输出
  131. return allMessages.OrderByDescending(m => m.ReceivedTime).ToList();
  132. }
  133. /// <summary>
  134. /// 指定账户发送邮件
  135. /// </summary>
  136. public async Task<MailSendResult> SendMailAsync(string fromEmail, MailDto mail)
  137. {
  138. try
  139. {
  140. var client = await GetClientAsync(fromEmail);
  141. var requestBody = new Microsoft.Graph.Me.SendMail.SendMailPostRequestBody
  142. {
  143. Message = new Message
  144. {
  145. Subject = mail.Subject,
  146. Body = new ItemBody
  147. {
  148. Content = mail.Content,
  149. ContentType = BodyType.Html
  150. },
  151. ToRecipients = new List<Recipient>
  152. {
  153. new Recipient { EmailAddress = new EmailAddress { Address = mail.To } }
  154. }
  155. }
  156. };
  157. // 执行发送
  158. await client.Me.SendMail.PostAsync(requestBody);
  159. return new MailSendResult { IsSuccess = true, Message = "邮件发送成功!" };
  160. }
  161. catch (ODataError odataError) // 捕获 Graph 特有异常
  162. {
  163. // 常见的错误:ErrorInvalidUser, ErrorQuotaExceeded, ErrorMessageSubmissionBlocked
  164. var code = odataError.Error?.Code ?? "Unknown";
  165. var msg = odataError.Error?.Message ?? "微软 API 调用异常";
  166. return new MailSendResult
  167. {
  168. IsSuccess = false,
  169. ErrorCode = code,
  170. Message = $"发送失败: {msg}"
  171. };
  172. }
  173. catch (Exception ex)
  174. {
  175. return new MailSendResult
  176. {
  177. IsSuccess = false,
  178. ErrorCode = "InternalError",
  179. Message = $"系统内部错误: {ex.Message}"
  180. };
  181. }
  182. }
  183. /// <summary>
  184. /// 获取邮箱配置信息 - single
  185. /// </summary>
  186. /// <returns></returns>
  187. public async Task<HotmailConfig?> GetUserMailConfig(int userId)
  188. {
  189. var allConfigs = await GetUserMailConfigListAsync();
  190. if (allConfigs == null || !allConfigs.Any()) return null;
  191. var userConfig = allConfigs.FirstOrDefault(x => x.UserId == userId);
  192. return userConfig;
  193. }
  194. /// <summary>
  195. /// 获取邮箱配置信息 - ALL
  196. /// </summary>
  197. /// <returns></returns>
  198. public async Task<List<HotmailConfig>?> GetUserMailConfigListAsync()
  199. {
  200. var remark = await _sqlSugar.Queryable<Sys_SetData>()
  201. .Where(x => x.IsDel == 0 && x.Id == 1555 && x.STid == 137)
  202. .Select(x => x.Remark)
  203. .FirstAsync();
  204. if (string.IsNullOrWhiteSpace(remark)) return null;
  205. try
  206. {
  207. var allConfigs = JsonConvert.DeserializeObject<List<HotmailConfig>>(remark);
  208. return allConfigs;
  209. }
  210. catch (Exception)
  211. {
  212. return null;
  213. }
  214. }
  215. /// <summary>
  216. /// 线程锁
  217. /// </summary>
  218. private static readonly ConcurrentDictionary<string, SemaphoreSlim> _userLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
  219. /// <summary>
  220. /// 获取 Graph 客户端,处理 Token 自动刷新 (线程安全版)
  221. /// </summary>
  222. private async Task<GraphServiceClient> GetClientAsync(string email)
  223. {
  224. // 获取或创建针对该 Email 的独立信号量锁
  225. var userLock = _userLocks.GetOrAdd(email, _ => new SemaphoreSlim(1, 1));
  226. await userLock.WaitAsync();
  227. try
  228. {
  229. var redisKey = GetRedisKey(email);
  230. // 建议:每次获取 Repo 实例,避免单例 Repo 内部并发冲突
  231. var repo = RedisRepository.RedisFactory.CreateRedisRepository();
  232. var cachedJson = await repo.StringGetAsync<string>(redisKey);
  233. if (string.IsNullOrEmpty(cachedJson))
  234. throw new UnauthorizedAccessException($"Account {email} not initialized in Redis.");
  235. var token = System.Text.Json.JsonSerializer.Deserialize<UserToken>(cachedJson!)!;
  236. // 令牌过期预校验 (带锁保护,防止并发刷新导致的 Token 失效)
  237. if (token.ExpiresAt < DateTime.UtcNow.AddMinutes(5))
  238. {
  239. // 内部逻辑:调用 Graph 刷新接口 -> 更新 token 对象 -> 写入 Redis
  240. token = await RefreshAndSaveTokenAsync(token);
  241. // 调试建议:记录刷新日志
  242. // _logger.LogInformation("Token refreshed for {Email}", email);
  243. }
  244. // 3. 构造认证提供者 (Scoped 局部化)
  245. // 使用 StaticTokenProvider 封装当前的 AccessToken
  246. var tokenProvider = new StaticTokenProvider(token.AccessToken);
  247. var authProvider = new BaseBearerTokenAuthenticationProvider(tokenProvider);
  248. // 4. 返回全新的客户端实例,确保 RequestAdapter 隔离
  249. return new GraphServiceClient(authProvider);
  250. }
  251. catch (Exception ex)
  252. {
  253. // _logger.LogError(ex, "GetClientAsync failed for {Email}", email);
  254. throw;
  255. }
  256. finally
  257. {
  258. userLock.Release(); // 必须在 finally 中释放锁
  259. }
  260. }
  261. public async Task<UserToken> RefreshAndSaveTokenAsync(UserToken oldToken)
  262. {
  263. // 1. 实时获取该用户对应的配置信息
  264. // 准则:不再信任全局 _config,而是根据 Email 溯源配置
  265. var allConfigs = await GetUserMailConfigListAsync();
  266. var currentConfig = allConfigs?.FirstOrDefault(x =>
  267. x.UserName.Equals(oldToken.Email, StringComparison.OrdinalIgnoreCase));
  268. if (currentConfig == null)
  269. throw new Exception($"刷新失败:未能在配置库中找到账号 {oldToken.Email} 的关联 Client 信息。");
  270. // 2. 使用该账号专属的凭据构造请求
  271. var httpClient = _httpClientFactory.CreateClient();
  272. var kvp = new Dictionary<string, string>
  273. {
  274. { "client_id", currentConfig.ClientId.Trim() },
  275. { "client_secret", currentConfig.ClientSecret.Trim() },
  276. { "grant_type", "refresh_token" },
  277. { "refresh_token", oldToken.RefreshToken },
  278. { "scope", "openid offline_access Mail.ReadWrite Mail.Send User.Read" } // 保持 Scope 一致性
  279. };
  280. var response = await httpClient.PostAsync("https://login.microsoftonline.com/common/oauth2/v2.0/token", new FormUrlEncodedContent(kvp));
  281. if (!response.IsSuccessStatusCode)
  282. {
  283. var error = await response.Content.ReadAsStringAsync();
  284. throw new Exception($"微软刷新接口拒绝请求: {error}");
  285. }
  286. using var doc = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());
  287. var root = doc.RootElement;
  288. // 3. 构造新令牌 (注意:每次刷新都会返回新的 RefreshToken,必须覆盖旧的)
  289. var newToken = new UserToken
  290. {
  291. Email = oldToken.Email,
  292. AccessToken = root.GetProperty("access_token").GetString()!,
  293. // 关键:微软可能会滚动更新 RefreshToken,务必取回最新的
  294. RefreshToken = root.TryGetProperty("refresh_token", out var rt) ? rt.GetString()! : oldToken.RefreshToken,
  295. ExpiresAt = DateTime.UtcNow.AddSeconds(root.GetProperty("expires_in").GetInt32()),
  296. Source = "Microsoft_Graph_Refreshed"
  297. };
  298. // 4. 同步更新 Redis (保持 90 天长效)
  299. var redisKey = GetRedisKey(oldToken.Email);
  300. await RedisRepository.RedisFactory.CreateRedisRepository()
  301. .StringSetAsync(redisKey, JsonSerializer.Serialize(newToken), TimeSpan.FromDays(90));
  302. return newToken;
  303. }
  304. /// <summary>
  305. /// 静态 Token 提供者辅助类
  306. /// </summary>
  307. public class StaticTokenProvider : IAccessTokenProvider
  308. {
  309. private readonly string _token;
  310. public StaticTokenProvider(string token) => _token = token;
  311. public Task<string> GetAuthorizationTokenAsync(Uri uri, Dictionary<string, object>? context = null, CancellationToken ct = default) => Task.FromResult(_token);
  312. public AllowedHostsValidator AllowedHostsValidator { get; } = new();
  313. }
  314. #region 数据模型
  315. public class MailSendResult
  316. {
  317. public bool IsSuccess { get; set; }
  318. public string Message { get; set; } = string.Empty;
  319. public string? ErrorCode { get; set; } // Microsoft 提供的错误码
  320. public string Source => "Microsoft_Graph_API";
  321. }
  322. /// <summary>
  323. /// Hotmail 邮件服务 OAuth2 配置信息实体
  324. /// </summary>
  325. public class HotmailConfig
  326. {
  327. /// <summary>
  328. /// 用户唯一标识
  329. /// </summary>
  330. [JsonPropertyName("userId")]
  331. public int UserId { get; set; }
  332. /// <summary>
  333. /// 账号用户名
  334. /// </summary>
  335. [JsonPropertyName("userName")]
  336. public string UserName { get; set; }
  337. /// <summary>
  338. /// Azure AD 租户标识符 (Guid)
  339. /// </summary>
  340. [JsonPropertyName("tenantId")]
  341. public string TenantId { get; set; }
  342. /// <summary>
  343. /// 注册应用程序的客户端标识
  344. /// </summary>
  345. [JsonPropertyName("clientId")]
  346. public string ClientId { get; set; }
  347. /// <summary>
  348. /// 客户端密钥(敏感数据建议加密存储)
  349. /// </summary>
  350. [JsonPropertyName("clientSecret")]
  351. public string ClientSecret { get; set; }
  352. /// <summary>
  353. /// 租户类型(如 common, organizations 或具体域名)
  354. /// </summary>
  355. [JsonPropertyName("tenant")]
  356. public string Tenant { get; set; } = "common";
  357. /// <summary>
  358. /// OAuth2 回调重定向地址
  359. /// </summary>
  360. [JsonPropertyName("redirectUri")]
  361. public string RedirectUri { get; set; }
  362. }
  363. public class UserToken
  364. {
  365. public string Email { get; set; }
  366. public string AccessToken { get; set; }
  367. public string RefreshToken { get; set; }
  368. public DateTime ExpiresAt { get; set; }
  369. public string Source { get; set; }
  370. }
  371. /// <summary>
  372. /// 邮件请求对象
  373. /// </summary>
  374. public class MailDto
  375. {
  376. /// <summary>
  377. /// 邮件唯一标识符 (UID/Message-ID)
  378. /// </summary>
  379. [JsonPropertyName("messageId")]
  380. public string? MessageId { get; set; }
  381. /// <summary>
  382. /// 邮件主题
  383. /// </summary>
  384. [JsonPropertyName("subject")]
  385. public string? Subject { get; set; }
  386. /// <summary>
  387. /// 发件人地址 (e.g. "sender@example.com")
  388. /// </summary>
  389. [JsonPropertyName("from")]
  390. public string? From { get; set; }
  391. /// <summary>
  392. /// 收件人地址
  393. /// </summary>
  394. [JsonPropertyName("to")]
  395. public string? To { get; set; }
  396. /// <summary>
  397. /// 邮件正文内容 (HTML 或纯文本)
  398. /// </summary>
  399. [JsonPropertyName("content")]
  400. public string? Content { get; set; }
  401. /// <summary>
  402. /// 接收时间 - 使用 DateTimeOffset 以确保跨时区准确性
  403. /// </summary>
  404. [JsonPropertyName("receivedTime")]
  405. public DateTimeOffset? ReceivedTime { get; set; }
  406. /// <summary>
  407. /// 数据来源标识 (用于区分不同配置源或采集渠道,如 "Hotmail", "Gmail", "Sys_SetData")
  408. /// </summary>
  409. [JsonPropertyName("source")]
  410. public string? Source { get; set; } = "Hotmail";
  411. }
  412. #endregion
  413. }
  414. }