HotmailService.cs 21 KB

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