AITestController.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  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. /// system | user | assistant 角色。
  326. /// </summary>
  327. [HttpPost("deepseek-chat-stream-with-history")]
  328. public async Task<IActionResult> DeepSeekChatStreamWithHistory(
  329. [FromBody] DeepSeekChatStreamHistoryTestRequest request,
  330. CancellationToken cancellationToken = default)
  331. {
  332. if (request?.Messages == null || request.Messages.Count == 0)
  333. return BadRequest(new { message = "Messages 不能为空,且至少包含一条 user/system/assistant 消息。" });
  334. Response.ContentType = "application/x-ndjson; charset=utf-8";
  335. Response.Headers["Cache-Control"] = "no-cache";
  336. static string NdjsonLine(DeepSeekStreamChunk c) => JsonConvert.SerializeObject(new
  337. {
  338. phase = c.Phase == DeepSeekStreamPhase.Reasoning ? "reasoning" : "content",
  339. text = c.Text
  340. });
  341. try
  342. {
  343. await foreach (var chunk in _deepSeekService.ChatStreamWithHistoryAsync(
  344. request.Messages,
  345. string.IsNullOrWhiteSpace(request.Model) ? "deepseek-chat" : request.Model!.Trim(),
  346. request.Temperature,
  347. request.MaxTokens))
  348. {
  349. cancellationToken.ThrowIfCancellationRequested();
  350. await Response.WriteAsync(NdjsonLine(chunk) + "\n", cancellationToken);
  351. await Response.Body.FlushAsync(cancellationToken);
  352. }
  353. await Response.WriteAsync(JsonConvert.SerializeObject(new { phase = "success", text = "结束" }) + "\n", cancellationToken);
  354. await Response.Body.FlushAsync(cancellationToken);
  355. }
  356. catch (OperationCanceledException)
  357. {
  358. }
  359. catch (Exception ex)
  360. {
  361. _logger.LogError(ex, "DeepSeek 带历史流式对话失败");
  362. await Response.WriteAsync(
  363. JsonConvert.SerializeObject(new { phase = "error", text = ex.Message }) + "\n",
  364. cancellationToken);
  365. }
  366. return new EmptyResult();
  367. }
  368. /// <summary>
  369. /// DeepSeek 流式对话(含多轮)请求体
  370. /// </summary>
  371. public class DeepSeekChatStreamHistoryTestRequest
  372. {
  373. public List<DeepSeekHistoryMessage> Messages { get; set; } = new();
  374. public string? Model { get; set; } = "deepseek-chat";
  375. public float Temperature { get; set; } = 0.7f;
  376. public int MaxTokens { get; set; } = 4000;
  377. }
  378. #endregion
  379. /// <summary>
  380. /// hotmail 发送邮件
  381. /// </summary>
  382. [HttpPost("hotmailSeed")]
  383. public async Task<ActionResult<string>> HotmailSeed()
  384. {
  385. await _hotmailService.SendMailAsync(
  386. //"Roy.Lei.Atom@hotmail.com",
  387. "925554512@qq.com",
  388. //"johnny.yang@pan-american-intl.com",
  389. new HotmailService.MailDto()
  390. {
  391. Subject = "系统提醒",
  392. Content = "<p>这是一封Homail 发送的测试邮件</p>",
  393. //To = "Roy.lei@pan-american-intl.com"
  394. To = "johnny.yang@pan-american-intl.com"
  395. });
  396. return StatusCode(200, new { Message = "操作成功。" });
  397. }
  398. /// <summary>
  399. /// hotmail 发送邮件
  400. /// </summary>
  401. [HttpPost("HotmailMerged")]
  402. public async Task<ActionResult<string>> HotmailMerged()
  403. {
  404. // 1. 获取当前北京时间 (CST)
  405. var cstZone = CommonFun.GetCstZone();
  406. var nowInCst = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cstZone);
  407. // 2. 构造昨天的北京时间范围:00:00:00 到 23:59:59
  408. var yesterdayStart = nowInCst.Date.AddDays(-1); // 昨天的 00:00:00
  409. var yesterdayEnd = yesterdayStart.AddDays(1).AddTicks(-1); // 昨天的 23:59:59
  410. var res = await _hotmailService.GetMergedMessagesAsync(
  411. new List<string>() { "925554512@qq.com" },
  412. yesterdayStart,
  413. yesterdayEnd
  414. );
  415. return StatusCode(200, res);
  416. }
  417. /// <summary>
  418. /// hotmail 定时发送邮件 汇总 测试
  419. /// </summary>
  420. [HttpPost("hotmailSummarySeedQW")]
  421. public async Task<ActionResult<string>> HotmailSummary()
  422. {
  423. ProcessAndNotifySummary.ProcessAndNotifySummaryAsync();
  424. return StatusCode(200, "发送成功");
  425. }
  426. #region Microsoft Graph 邮箱测试(仅访问令牌)
  427. private const string GraphAccessTokenHeader = "X-Graph-Access-Token";
  428. /// <summary>
  429. /// 优先级:请求头 X-Graph-Access-Token → 查询 graphAccessToken → bodyToken(发信)。
  430. /// </summary>
  431. private string? ResolveGraphAccessToken(string? queryToken = null, string? bodyToken = null)
  432. {
  433. var header = Request.Headers[GraphAccessTokenHeader].FirstOrDefault();
  434. if (!string.IsNullOrWhiteSpace(header))
  435. return header.Trim();
  436. if (!string.IsNullOrWhiteSpace(queryToken))
  437. return queryToken.Trim();
  438. if (!string.IsNullOrWhiteSpace(bodyToken))
  439. return bodyToken.Trim();
  440. return null;
  441. }
  442. /// <summary>
  443. /// 查询当前用户 GET /v1.0/me。必须提供 Graph 访问令牌。
  444. /// </summary>
  445. [HttpGet("graph-mail/me")]
  446. public async Task<IActionResult> GraphMailMe(
  447. [FromQuery] string? graphAccessToken = null,
  448. CancellationToken cancellationToken = default)
  449. {
  450. var bearer = ResolveGraphAccessToken(graphAccessToken);
  451. if (string.IsNullOrWhiteSpace(bearer))
  452. return Unauthorized(new { message = "必须提供 Microsoft Graph 访问令牌:请求头 X-Graph-Access-Token 或查询参数 graphAccessToken" });
  453. try
  454. {
  455. var json = await _microsoftGraphMailboxService.GetMeRawJsonAsync(bearer, cancellationToken);
  456. if (string.IsNullOrEmpty(json))
  457. return StatusCode(502, new { message = "Graph 返回空正文" });
  458. return Content(json, "application/json");
  459. }
  460. catch (Exception ex)
  461. {
  462. _logger.LogError(ex, "Graph Mail /me 失败");
  463. return StatusCode(500, new { message = ex.Message });
  464. }
  465. }
  466. /// <summary>
  467. /// 查询收件箱。必须提供 Graph 访问令牌(需 Mail.Read)。默认 sinceUtc 为 UTC 近 24 小时。
  468. /// </summary>
  469. /// <param name="sinceUtc">起始时间(UTC),ISO8601</param>
  470. /// <param name="graphAccessToken">或使用请求头 X-Graph-Access-Token</param>
  471. /// <param name="cancellationToken">取消标记</param>
  472. [HttpGet("graph-mail/inbox")]
  473. public async Task<IActionResult> GraphMailInbox(
  474. [FromQuery] DateTime? sinceUtc = null,
  475. [FromQuery] string? graphAccessToken = null,
  476. CancellationToken cancellationToken = default)
  477. {
  478. var bearer = ResolveGraphAccessToken(graphAccessToken);
  479. if (string.IsNullOrWhiteSpace(bearer))
  480. return Unauthorized(new { message = "必须提供 Microsoft Graph 访问令牌:请求头 X-Graph-Access-Token 或查询参数 graphAccessToken" });
  481. var since = sinceUtc ?? DateTime.UtcNow.AddHours(-24);
  482. try
  483. {
  484. var json = await _microsoftGraphMailboxService.GetInboxMessagesJsonSinceAsync(since, bearer, cancellationToken);
  485. if (string.IsNullOrEmpty(json))
  486. return StatusCode(502, new { message = "Graph 返回空正文" });
  487. return Content(json, "application/json");
  488. }
  489. catch (Exception ex)
  490. {
  491. _logger.LogError(ex, "Graph Mail inbox 失败");
  492. return StatusCode(500, new { message = ex.Message });
  493. }
  494. }
  495. /// <summary>
  496. /// Graph sendMail 纯文本。必须提供令牌(需 Mail.Send):头 / 查询 / Body.graphAccessToken。
  497. /// </summary>
  498. [HttpPost("graph-mail/send")]
  499. public async Task<IActionResult> GraphMailSend(
  500. [FromBody] GraphMailSendTestRequest request,
  501. [FromQuery] string? graphAccessToken = null,
  502. CancellationToken cancellationToken = default)
  503. {
  504. if (request == null || string.IsNullOrWhiteSpace(request.ToEmail))
  505. return BadRequest(new { message = "ToEmail 不能为空" });
  506. var bearer = ResolveGraphAccessToken(graphAccessToken, request.GraphAccessToken);
  507. if (string.IsNullOrWhiteSpace(bearer))
  508. return Unauthorized(new { message = "必须提供 Microsoft Graph 访问令牌:X-Graph-Access-Token、?graphAccessToken 或 Body.graphAccessToken" });
  509. var subject = string.IsNullOrWhiteSpace(request.Subject)
  510. ? $"OASystem Graph 测试邮件 {DateTime.Now:yyyy-MM-dd HH:mm:ss}"
  511. : request.Subject!;
  512. var body = request.Body ?? string.Empty;
  513. try
  514. {
  515. await _microsoftGraphMailboxService.SendMailAsync(request.ToEmail.Trim(), subject, body, bearer, cancellationToken);
  516. return Ok(new { ok = true, message = "sendMail 已提交", to = request.ToEmail.Trim(), subject });
  517. }
  518. catch (HttpRequestException ex)
  519. {
  520. return StatusCode(502, new { message = "Graph HTTP 错误", detail = ex.Message });
  521. }
  522. catch (Exception ex)
  523. {
  524. _logger.LogError(ex, "Graph Mail send 失败");
  525. return StatusCode(500, new { message = ex.Message });
  526. }
  527. }
  528. public class EmailAuthRedisCache
  529. {
  530. public string? AccessToken { get; set; }
  531. public string? HomeAccountId { get; set; }
  532. public string? UserTokenCacheBase64 { get; set; }
  533. public string? ClientId { get; set; }
  534. }
  535. /// <summary>
  536. /// 从 Redis 读取 MSAL 缓存与 HomeAccountId,静默刷新 Graph access_token。
  537. /// </summary>
  538. [HttpGet("graph-mail/refresh-token")]
  539. public async Task<IActionResult> RefreshAccessToken([FromQuery] string? redisKey = null)
  540. {
  541. var key = string.IsNullOrWhiteSpace(redisKey) ? "Email:AuthCache:345" : redisKey.Trim();
  542. var redis = RedisFactory.CreateRedisRepository();
  543. var json = await redis.StringGetRawAsync(key);
  544. if (string.IsNullOrWhiteSpace(json))
  545. {
  546. return BadRequest(new { message = $"Redis 键 {key} 不存在或为空" });
  547. }
  548. EmailAuthRedisCache? cacheEntry;
  549. try
  550. {
  551. cacheEntry = JsonConvert.DeserializeObject<EmailAuthRedisCache>(json);
  552. }
  553. catch (System.Text.Json.JsonException ex)
  554. {
  555. _logger.LogWarning(ex, "Redis 键 {Key} 内容不是合法 JSON(应用 StringGetRawAsync + JSON,勿用 StringGetAsync<T>,后者为 BinaryFormatter)", key);
  556. return BadRequest(new { message = "Redis 值为 JSON 文本时须用 StringGetRawAsync 再反序列化;StringGetAsync<T> 仅适用于 BinaryFormatter 写入的数据", detail = ex.Message });
  557. }
  558. if (cacheEntry == null
  559. || string.IsNullOrWhiteSpace(cacheEntry.UserTokenCacheBase64)
  560. || string.IsNullOrWhiteSpace(cacheEntry.HomeAccountId))
  561. {
  562. return BadRequest(new { message = "JSON 中缺少 UserTokenCacheBase64 或 HomeAccountId" });
  563. }
  564. var accessToken = await _microsoftGraphMailboxService.RefreshAccessTokenAsync(
  565. cacheEntry.ClientId,
  566. "common",
  567. new[] { "Mail.Read", "User.Read", "Mail.Send" },
  568. cacheEntry.UserTokenCacheBase64,
  569. cacheEntry.HomeAccountId);
  570. return Ok(new { accessToken });
  571. }
  572. /// <summary>
  573. /// Graph 发信测试请求体
  574. /// </summary>
  575. public class GraphMailSendTestRequest
  576. {
  577. public string ToEmail { get; set; } = string.Empty;
  578. public string? Subject { get; set; }
  579. public string? Body { get; set; }
  580. /// <summary>Microsoft Graph 访问令牌(也可用请求头 X-Graph-Access-Token)</summary>
  581. public string? GraphAccessToken { get; set; }
  582. }
  583. #endregion
  584. }
  585. }