HotmailService.cs 22 KB

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