AITestController.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. using Microsoft.AspNetCore.Mvc;
  2. using OASystem.API.OAMethodLib.DeepSeekAPI;
  3. using Flurl.Http.Configuration;
  4. using Microsoft.Extensions.Options;
  5. using OASystem.API.OAMethodLib.DoubaoAPI;
  6. using OASystem.API.OAMethodLib.Hotmail;
  7. using OASystem.API.OAMethodLib.HunYuanAPI;
  8. using OASystem.API.OAMethodLib.MicrosoftGraphMailbox;
  9. using OASystem.API.OAMethodLib.QiYeWeChatAPI;
  10. using OASystem.API.OAMethodLib.Quartz.Business;
  11. using OASystem.Domain.ViewModels.QiYeWeChat;
  12. using OASystem.RedisRepository;
  13. using System.IdentityModel.Tokens.Jwt;
  14. using System.Text.Json;
  15. using static OASystem.API.OAMethodLib.Hotmail.HotmailService;
  16. namespace OASystem.API.Controllers
  17. {
  18. /// <summary>
  19. /// AI测试控制器
  20. /// </summary>
  21. [Route("api/[controller]")]
  22. public class AITestController : ControllerBase
  23. {
  24. private readonly IHunyuanService _hunyuanService;
  25. private readonly IDoubaoService _doubaoService;
  26. private readonly ILogger<AITestController> _logger;
  27. private readonly IConfiguration _config;
  28. private readonly IQiYeWeChatApiService _qiYeWeChatApiService;
  29. private readonly System.Net.Http.IHttpClientFactory _httpClientFactory;
  30. private readonly HotmailService _hotmailService;
  31. private readonly IMicrosoftGraphMailboxService _microsoftGraphMailboxService;
  32. private readonly IOptionsMonitor<MicrosoftGraphMailboxOptions> _microsoftGraphMailboxOptions;
  33. private readonly IDeepSeekService _deepSeekService;
  34. public AITestController(
  35. IHunyuanService hunyuanService,
  36. IDoubaoService doubaoService,
  37. ILogger<AITestController> logger,
  38. IQiYeWeChatApiService qiYeWeChatApiService,
  39. HotmailService hotmailService,
  40. System.Net.Http.IHttpClientFactory httpClientFactory,
  41. IConfiguration config,
  42. IMicrosoftGraphMailboxService microsoftGraphMailboxService,
  43. IOptionsMonitor<MicrosoftGraphMailboxOptions> microsoftGraphMailboxOptions,
  44. IDeepSeekService deepSeekService
  45. )
  46. {
  47. _hunyuanService = hunyuanService;
  48. _doubaoService = doubaoService;
  49. _logger = logger;
  50. _qiYeWeChatApiService = qiYeWeChatApiService;
  51. _hotmailService = hotmailService;
  52. _httpClientFactory = httpClientFactory;
  53. _config = config;
  54. _microsoftGraphMailboxService = microsoftGraphMailboxService;
  55. _deepSeekService = deepSeekService;
  56. _microsoftGraphMailboxOptions = microsoftGraphMailboxOptions;
  57. }
  58. #region 企业微信发送邮件测试
  59. /// <summary>
  60. /// 企业微信发送邮件测试
  61. /// </summary>
  62. [HttpPost("sendEmail")]
  63. public async Task<ActionResult<string>> SendEmail([FromForm] IFormFile[] feils)
  64. {
  65. try
  66. {
  67. var req = new EmailRequestDto()
  68. {
  69. ToEmails = new List<string> { "johnny.yang@pan-american-intl.com" },
  70. CcEmails = new List<string> { "Roy.lei@pan-american-intl.com" },
  71. BccEmails = new List<string> { "Roy.lei@pan-american-intl.com" },
  72. Subject = "测试邮件 - 来自企业微信API",
  73. Body = "这是一封通过企业微信API发送的测试邮件,包含附件。",
  74. Files = feils
  75. };
  76. var response = await _qiYeWeChatApiService.EmailSendAsync(req);
  77. return Ok(response);
  78. }
  79. catch (Exception ex)
  80. {
  81. _logger.LogError(ex, "调用企业微信邮件API失败。");
  82. return StatusCode(500, new { Message = "调用企业微信邮件API失败,请检查配置或网络。", Detail = ex.Message });
  83. }
  84. }
  85. #endregion
  86. #region 豆包 AI
  87. /// <summary>
  88. /// 豆包基础对话
  89. /// </summary>
  90. [HttpPost("doubao-chat")]
  91. public async Task<ActionResult<string>> DoubaoChat(string question, bool isThinking = false)
  92. {
  93. try
  94. {
  95. var messages = new List<DouBaoChatMessage>
  96. {
  97. new DouBaoChatMessage { Role = DouBaoRole.user, Content = question }
  98. };
  99. var options = new CompleteChatOptions
  100. {
  101. ThinkingOptions = new thinkingOptions { IsThinking = isThinking }
  102. };
  103. var response = await _doubaoService.CompleteChatAsync(messages, options);
  104. return Ok(response);
  105. }
  106. catch (Exception ex)
  107. {
  108. _logger.LogError(ex, "调用豆包API失败。");
  109. return StatusCode(500, new { Message = "调用豆包API失败", Detail = ex.Message });
  110. }
  111. }
  112. /// <summary>
  113. /// 豆包上传文件
  114. /// </summary>
  115. [HttpPost("doubao-upload")]
  116. public async Task<ActionResult<DoubaoFileResponse>> DoubaoUpload(IFormFile file, string purpose = "user_data")
  117. {
  118. if (file == null || file.Length == 0)
  119. return BadRequest("请选择要上传的文件");
  120. try
  121. {
  122. var stream = file.OpenReadStream();
  123. var existsFileExpand = new List<string> { "pdf", "docx" };
  124. if (!existsFileExpand.Contains(file.FileName.Split('.').Last().ToLower()))
  125. {
  126. return BadRequest("请上传pdf、docx文件!不支持其他文件");
  127. }
  128. if (file.FileName.Split('.').Last().ToLower() == "docx")
  129. {
  130. using var docxStream = file.OpenReadStream();
  131. var pdfStream = DoubaoService.ConvertDocxStreamToPdfStream(docxStream);
  132. stream = pdfStream;
  133. }
  134. var response = await _doubaoService.UploadFileAsync(stream, file.FileName, purpose);
  135. stream.Dispose();
  136. return Ok(response);
  137. }
  138. catch (Exception ex)
  139. {
  140. _logger.LogError(ex, "豆包上传文件失败");
  141. return StatusCode(500, new { Message = "上传失败", Detail = ex.Message });
  142. }
  143. }
  144. /// <summary>
  145. /// 豆包获取文件列表
  146. /// </summary>
  147. [HttpGet("doubao-files")]
  148. public async Task<ActionResult<DoubaoFileListResponse>> DoubaoListFiles()
  149. {
  150. try
  151. {
  152. var response = await _doubaoService.ListFilesAsync();
  153. return Ok(response);
  154. }
  155. catch (Exception ex)
  156. {
  157. _logger.LogError(ex, "获取豆包文件列表失败");
  158. return StatusCode(500, new { Message = "获取失败", Detail = ex.Message });
  159. }
  160. }
  161. /// <summary>
  162. /// 豆包删除文件
  163. /// </summary>
  164. [HttpDelete("doubao-file/{fileId}")]
  165. public async Task<ActionResult<bool>> DoubaoDeleteFile(string fileId)
  166. {
  167. try
  168. {
  169. var response = await _doubaoService.DeleteFileAsync(fileId);
  170. return Ok(response);
  171. }
  172. catch (Exception ex)
  173. {
  174. _logger.LogError(ex, "删除豆包文件失败");
  175. return StatusCode(500, new { Message = "删除失败", Detail = ex.Message });
  176. }
  177. }
  178. /// <summary>
  179. /// 豆包多模态对话(支持文本+图片)
  180. /// </summary>
  181. /// <param name="request">表单请求参数</param>
  182. [HttpPost("doubao-multimodal-chat")]
  183. public async Task<ActionResult<string>> DoubaoMultimodalChat([FromForm] DoubaoMultimodalChatRequest request)
  184. {
  185. if (string.IsNullOrWhiteSpace(request.Question))
  186. return BadRequest("问题不能为空");
  187. try
  188. {
  189. var contentItems = new List<DoubaoMultimodalContentItem>
  190. {
  191. new DoubaoMultimodalContentItem { Type = "text", Text = request.Question.Trim() }
  192. };
  193. if (!string.IsNullOrWhiteSpace(request.FileId))
  194. {
  195. contentItems.Add(new DoubaoMultimodalContentItem
  196. {
  197. Type = "file",
  198. FileId = request.FileId.Trim(),
  199. });
  200. }
  201. if (request.Image != null && request.Image.Length > 0)
  202. {
  203. using var ms = new MemoryStream();
  204. await request.Image.CopyToAsync(ms);
  205. var base64 = Convert.ToBase64String(ms.ToArray());
  206. var mimeType = request.Image.ContentType ?? "image/jpeg";
  207. var dataUrl = $"data:{mimeType};base64,{base64}";
  208. contentItems.Add(new DoubaoMultimodalContentItem
  209. {
  210. Type = "image_url",
  211. ImageUrl = new DoubaoMultimodalImageUrl { Url = dataUrl }
  212. });
  213. }
  214. var messages = new List<DoubaoMultimodalChatMessage>
  215. {
  216. new DoubaoMultimodalChatMessage
  217. {
  218. Role = "user",
  219. Content = contentItems
  220. }
  221. };
  222. var options = new CompleteMultimodalChatOptions
  223. {
  224. ThinkingOptions = new DoubaoMultimodalThinkingOptions
  225. {
  226. IsThinking = request.IsThinking,
  227. ReasoningEffort = "medium"
  228. }
  229. };
  230. var response = await _doubaoService.CompleteMultimodalChatAsync(messages, options);
  231. return Ok(response ?? string.Empty);
  232. }
  233. catch (Exception ex)
  234. {
  235. _logger.LogError(ex, "调用豆包多模态API失败。");
  236. return StatusCode(500, new { Message = "调用豆包多模态API失败", Detail = ex.Message });
  237. }
  238. }
  239. #endregion
  240. #region 混元 AI
  241. /// <summary>
  242. /// 基础对话示例
  243. /// </summary>
  244. [HttpPost("chat")]
  245. public async Task<ActionResult<string>> BasicChat(string question)
  246. {
  247. try
  248. {
  249. var response = await _hunyuanService.ChatCompletionsHunyuan_t1_latestAsync(question);
  250. return Ok(response);
  251. }
  252. catch (Exception ex)
  253. {
  254. _logger.LogError(ex, "调用腾讯云混元API失败。");
  255. return StatusCode(500, new { Message = "调用腾讯云API失败,请检查配置或网络。", Detail = ex.Message });
  256. }
  257. }
  258. /// <summary>
  259. /// 模拟“根据文件提问”的API端点
  260. /// 注意:此示例中,文件内容通过请求体传入。
  261. /// 实际场景中,文件内容可能来自用户上传并解析(如PDF、TXT解析为文本)后的结果。
  262. /// </summary>
  263. [HttpPost("ask-with-file")]
  264. public async Task<ActionResult<string>> AskBasedOnFile([FromBody] AskWithFileRequest request)
  265. {
  266. if (string.IsNullOrEmpty(request.FileContent) || string.IsNullOrEmpty(request.Question))
  267. {
  268. return BadRequest(new { Message = "FileContent和Question字段不能为空。" });
  269. }
  270. try
  271. {
  272. var answer = await _hunyuanService.AskWithFileContextAsync(request.FileContent, request.Question, request.Model);
  273. return Ok(answer);
  274. }
  275. catch (Exception ex)
  276. {
  277. _logger.LogError(ex, "处理基于文件的提问失败。");
  278. return StatusCode(500, new { Message = "处理请求失败。", Detail = ex.Message });
  279. }
  280. }
  281. /// <summary>
  282. /// 用于测试的GET端点,快速验证服务可用性(使用示例数据)
  283. /// </summary>
  284. [HttpGet("test-file-query")]
  285. public async Task<ActionResult<string>> TestFileQuery()
  286. {
  287. // 示例文件内容和问题
  288. var sampleFileContent = "在软件开发中,依赖注入(Dependency Injection)是一种设计模式,用于实现控制反转(Inversion of Control, IoC)。它允许在类外部创建依赖对象,并通过构造函数、属性或方法将其‘注入’到类中,从而降低类之间的耦合度。";
  289. var sampleQuestion = "依赖注入的主要目的是什么?";
  290. var model = "hunyuan-lite"; // 可使用 "hunyuan-pro" 等
  291. try
  292. {
  293. var answer = await _hunyuanService.AskWithFileContextAsync(sampleFileContent, sampleQuestion, model);
  294. return Ok($"测试成功。问题:'{sampleQuestion}'\n回答:{answer}");
  295. }
  296. catch (Exception ex)
  297. {
  298. _logger.LogError(ex, "测试文件提问失败。");
  299. return StatusCode(500, new { Message = "测试失败。", Detail = ex.Message });
  300. }
  301. }
  302. /// <summary>
  303. /// 用于“根据文件提问”的请求体
  304. /// </summary>
  305. public class AskWithFileRequest
  306. {
  307. public string FileContent { get; set; } = string.Empty;
  308. public string Question { get; set; } = string.Empty;
  309. public string Model { get; set; } = "hunyuan-lite";
  310. }
  311. /// <summary>
  312. /// 豆包多模态对话请求体(form-data)
  313. /// </summary>
  314. public class DoubaoMultimodalChatRequest
  315. {
  316. public string Question { get; set; } = string.Empty;
  317. public IFormFile? Image { get; set; }
  318. public bool IsThinking { get; set; } = false;
  319. public string FileId { get; set; } = string.Empty;
  320. }
  321. #endregion
  322. #region DeepSeek 测试
  323. /// <summary>
  324. /// DeepSeek 带上下文的流式对话测试。响应为 NDJSON:每行一条 JSON,phase 为 reasoning、content 或 error。
  325. /// </summary>
  326. [HttpPost("deepseek-chat-stream-with-history")]
  327. public async Task<IActionResult> DeepSeekChatStreamWithHistory(
  328. [FromBody] DeepSeekChatStreamHistoryTestRequest request,
  329. CancellationToken cancellationToken = default)
  330. {
  331. if (request?.Messages == null || request.Messages.Count == 0)
  332. return BadRequest(new { message = "Messages 不能为空,且至少包含一条 user/system/assistant 消息。" });
  333. Response.ContentType = "application/x-ndjson; charset=utf-8";
  334. Response.Headers["Cache-Control"] = "no-cache";
  335. static string NdjsonLine(DeepSeekStreamChunk c) => JsonConvert.SerializeObject(new
  336. {
  337. phase = c.Phase == DeepSeekStreamPhase.Reasoning ? "reasoning" : "content",
  338. text = c.Text
  339. });
  340. try
  341. {
  342. await foreach (var chunk in _deepSeekService.ChatStreamWithHistoryAsync(
  343. request.Messages,
  344. string.IsNullOrWhiteSpace(request.Model) ? "deepseek-chat" : request.Model!.Trim(),
  345. request.Temperature,
  346. request.MaxTokens))
  347. {
  348. cancellationToken.ThrowIfCancellationRequested();
  349. await Response.WriteAsync(NdjsonLine(chunk) + "\n", cancellationToken);
  350. await Response.Body.FlushAsync(cancellationToken);
  351. }
  352. }
  353. catch (OperationCanceledException)
  354. {
  355. }
  356. catch (Exception ex)
  357. {
  358. _logger.LogError(ex, "DeepSeek 带历史流式对话失败");
  359. await Response.WriteAsync(
  360. JsonConvert.SerializeObject(new { phase = "error", text = ex.Message }) + "\n",
  361. cancellationToken);
  362. }
  363. return new EmptyResult();
  364. }
  365. /// <summary>
  366. /// DeepSeek 流式对话(含多轮)请求体
  367. /// </summary>
  368. public class DeepSeekChatStreamHistoryTestRequest
  369. {
  370. public List<DeepSeekHistoryMessage> Messages { get; set; } = new();
  371. public string? Model { get; set; } = "deepseek-chat";
  372. public float Temperature { get; set; } = 0.7f;
  373. public int MaxTokens { get; set; } = 4000;
  374. }
  375. #endregion
  376. /// <summary>
  377. /// hotmail 发送邮件
  378. /// </summary>
  379. [HttpPost("hotmailSeed")]
  380. public async Task<ActionResult<string>> HotmailSeed()
  381. {
  382. await _hotmailService.SendMailAsync(
  383. //"Roy.Lei.Atom@hotmail.com",
  384. "925554512@qq.com",
  385. //"johnny.yang@pan-american-intl.com",
  386. new HotmailService.MailDto()
  387. {
  388. Subject = "系统提醒",
  389. Content = "<p>这是一封Homail 发送的测试邮件</p>",
  390. //To = "Roy.lei@pan-american-intl.com"
  391. To = "johnny.yang@pan-american-intl.com"
  392. });
  393. return StatusCode(200, new { Message = "操作成功。" });
  394. }
  395. /// <summary>
  396. /// hotmail 发送邮件
  397. /// </summary>
  398. [HttpPost("HotmailMerged")]
  399. public async Task<ActionResult<string>> HotmailMerged()
  400. {
  401. // 1. 获取当前北京时间 (CST)
  402. var cstZone = CommonFun.GetCstZone();
  403. var nowInCst = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cstZone);
  404. // 2. 构造昨天的北京时间范围:00:00:00 到 23:59:59
  405. var yesterdayStart = nowInCst.Date.AddDays(-1); // 昨天的 00:00:00
  406. var yesterdayEnd = yesterdayStart.AddDays(1).AddTicks(-1); // 昨天的 23:59:59
  407. var res = await _hotmailService.GetMergedMessagesAsync(
  408. new List<string>() { "925554512@qq.com" },
  409. yesterdayStart,
  410. yesterdayEnd
  411. );
  412. return StatusCode(200, res);
  413. }
  414. /// <summary>
  415. /// hotmail 定时发送邮件 汇总 测试
  416. /// </summary>
  417. [HttpPost("hotmailSummarySeedQW")]
  418. public async Task<ActionResult<string>> HotmailSummary()
  419. {
  420. ProcessAndNotifySummary.ProcessAndNotifySummaryAsync();
  421. return StatusCode(200, "发送成功");
  422. }
  423. #region Microsoft Graph 邮箱测试(仅访问令牌)
  424. private const string GraphAccessTokenHeader = "X-Graph-Access-Token";
  425. /// <summary>
  426. /// 优先级:请求头 X-Graph-Access-Token → 查询 graphAccessToken → bodyToken(发信)。
  427. /// </summary>
  428. private string? ResolveGraphAccessToken(string? queryToken = null, string? bodyToken = null)
  429. {
  430. var header = Request.Headers[GraphAccessTokenHeader].FirstOrDefault();
  431. if (!string.IsNullOrWhiteSpace(header))
  432. return header.Trim();
  433. if (!string.IsNullOrWhiteSpace(queryToken))
  434. return queryToken.Trim();
  435. if (!string.IsNullOrWhiteSpace(bodyToken))
  436. return bodyToken.Trim();
  437. return null;
  438. }
  439. /// <summary>
  440. /// 查询当前用户 GET /v1.0/me。必须提供 Graph 访问令牌。
  441. /// </summary>
  442. [HttpGet("graph-mail/me")]
  443. public async Task<IActionResult> GraphMailMe(
  444. [FromQuery] string? graphAccessToken = null,
  445. CancellationToken cancellationToken = default)
  446. {
  447. var bearer = ResolveGraphAccessToken(graphAccessToken);
  448. if (string.IsNullOrWhiteSpace(bearer))
  449. return Unauthorized(new { message = "必须提供 Microsoft Graph 访问令牌:请求头 X-Graph-Access-Token 或查询参数 graphAccessToken" });
  450. try
  451. {
  452. var json = await _microsoftGraphMailboxService.GetMeRawJsonAsync(bearer, cancellationToken);
  453. if (string.IsNullOrEmpty(json))
  454. return StatusCode(502, new { message = "Graph 返回空正文" });
  455. return Content(json, "application/json");
  456. }
  457. catch (Exception ex)
  458. {
  459. _logger.LogError(ex, "Graph Mail /me 失败");
  460. return StatusCode(500, new { message = ex.Message });
  461. }
  462. }
  463. /// <summary>
  464. /// 查询收件箱。必须提供 Graph 访问令牌(需 Mail.Read)。默认 sinceUtc 为 UTC 近 24 小时。
  465. /// </summary>
  466. /// <param name="sinceUtc">起始时间(UTC),ISO8601</param>
  467. /// <param name="graphAccessToken">或使用请求头 X-Graph-Access-Token</param>
  468. /// <param name="cancellationToken">取消标记</param>
  469. [HttpGet("graph-mail/inbox")]
  470. public async Task<IActionResult> GraphMailInbox(
  471. [FromQuery] DateTime? sinceUtc = null,
  472. [FromQuery] string? graphAccessToken = null,
  473. CancellationToken cancellationToken = default)
  474. {
  475. var bearer = ResolveGraphAccessToken(graphAccessToken);
  476. if (string.IsNullOrWhiteSpace(bearer))
  477. return Unauthorized(new { message = "必须提供 Microsoft Graph 访问令牌:请求头 X-Graph-Access-Token 或查询参数 graphAccessToken" });
  478. var since = sinceUtc ?? DateTime.UtcNow.AddHours(-24);
  479. try
  480. {
  481. var json = await _microsoftGraphMailboxService.GetInboxMessagesJsonSinceAsync(since, bearer, cancellationToken);
  482. if (string.IsNullOrEmpty(json))
  483. return StatusCode(502, new { message = "Graph 返回空正文" });
  484. return Content(json, "application/json");
  485. }
  486. catch (Exception ex)
  487. {
  488. _logger.LogError(ex, "Graph Mail inbox 失败");
  489. return StatusCode(500, new { message = ex.Message });
  490. }
  491. }
  492. /// <summary>
  493. /// Graph sendMail 纯文本。必须提供令牌(需 Mail.Send):头 / 查询 / Body.graphAccessToken。
  494. /// </summary>
  495. [HttpPost("graph-mail/send")]
  496. public async Task<IActionResult> GraphMailSend(
  497. [FromBody] GraphMailSendTestRequest request,
  498. [FromQuery] string? graphAccessToken = null,
  499. CancellationToken cancellationToken = default)
  500. {
  501. if (request == null || string.IsNullOrWhiteSpace(request.ToEmail))
  502. return BadRequest(new { message = "ToEmail 不能为空" });
  503. var bearer = ResolveGraphAccessToken(graphAccessToken, request.GraphAccessToken);
  504. if (string.IsNullOrWhiteSpace(bearer))
  505. return Unauthorized(new { message = "必须提供 Microsoft Graph 访问令牌:X-Graph-Access-Token、?graphAccessToken 或 Body.graphAccessToken" });
  506. var subject = string.IsNullOrWhiteSpace(request.Subject)
  507. ? $"OASystem Graph 测试邮件 {DateTime.Now:yyyy-MM-dd HH:mm:ss}"
  508. : request.Subject!;
  509. var body = request.Body ?? string.Empty;
  510. try
  511. {
  512. await _microsoftGraphMailboxService.SendMailAsync(request.ToEmail.Trim(), subject, body, bearer, cancellationToken);
  513. return Ok(new { ok = true, message = "sendMail 已提交", to = request.ToEmail.Trim(), subject });
  514. }
  515. catch (HttpRequestException ex)
  516. {
  517. return StatusCode(502, new { message = "Graph HTTP 错误", detail = ex.Message });
  518. }
  519. catch (Exception ex)
  520. {
  521. _logger.LogError(ex, "Graph Mail send 失败");
  522. return StatusCode(500, new { message = ex.Message });
  523. }
  524. }
  525. public class EmailAuthRedisCache
  526. {
  527. public string? AccessToken { get; set; }
  528. public string? HomeAccountId { get; set; }
  529. public string? UserTokenCacheBase64 { get; set; }
  530. public string? ClientId { get; set; }
  531. }
  532. /// <summary>
  533. /// 从 Redis 读取 MSAL 缓存与 HomeAccountId,静默刷新 Graph access_token。
  534. /// </summary>
  535. [HttpGet("graph-mail/refresh-token")]
  536. public async Task<IActionResult> RefreshAccessToken([FromQuery] string? redisKey = null)
  537. {
  538. var key = string.IsNullOrWhiteSpace(redisKey) ? "Email:AuthCache:345" : redisKey.Trim();
  539. var redis = RedisFactory.CreateRedisRepository();
  540. var json = await redis.StringGetRawAsync(key);
  541. if (string.IsNullOrWhiteSpace(json))
  542. {
  543. return BadRequest(new { message = $"Redis 键 {key} 不存在或为空" });
  544. }
  545. EmailAuthRedisCache? cacheEntry;
  546. try
  547. {
  548. cacheEntry = JsonConvert.DeserializeObject<EmailAuthRedisCache>(json);
  549. }
  550. catch (System.Text.Json.JsonException ex)
  551. {
  552. _logger.LogWarning(ex, "Redis 键 {Key} 内容不是合法 JSON(应用 StringGetRawAsync + JSON,勿用 StringGetAsync<T>,后者为 BinaryFormatter)", key);
  553. return BadRequest(new { message = "Redis 值为 JSON 文本时须用 StringGetRawAsync 再反序列化;StringGetAsync<T> 仅适用于 BinaryFormatter 写入的数据", detail = ex.Message });
  554. }
  555. if (cacheEntry == null
  556. || string.IsNullOrWhiteSpace(cacheEntry.UserTokenCacheBase64)
  557. || string.IsNullOrWhiteSpace(cacheEntry.HomeAccountId))
  558. {
  559. return BadRequest(new { message = "JSON 中缺少 UserTokenCacheBase64 或 HomeAccountId" });
  560. }
  561. var accessToken = await _microsoftGraphMailboxService.RefreshAccessTokenAsync(
  562. cacheEntry.ClientId,
  563. "common",
  564. new[] { "Mail.Read", "User.Read", "Mail.Send" },
  565. cacheEntry.UserTokenCacheBase64,
  566. cacheEntry.HomeAccountId);
  567. return Ok(new { accessToken });
  568. }
  569. /// <summary>
  570. /// Graph 发信测试请求体
  571. /// </summary>
  572. public class GraphMailSendTestRequest
  573. {
  574. public string ToEmail { get; set; } = string.Empty;
  575. public string? Subject { get; set; }
  576. public string? Body { get; set; }
  577. /// <summary>Microsoft Graph 访问令牌(也可用请求头 X-Graph-Access-Token)</summary>
  578. public string? GraphAccessToken { get; set; }
  579. }
  580. #endregion
  581. }
  582. }