eCourt-Doc-Edit/backend/WordVersioning.Api/Controllers/OpenController.cs

107 lines
6 KiB
C#
Raw Normal View History

Phase 12 v9.2: download-first + backend open-links (Word 16.101+ broke ms-word) การทดสอบ 6 รอบบนเครื่องจริง (Mac, Word 16.101) พิสูจน์ว่า ms-word:ofe ถูกเมินแบบไม่ deterministic ทุกรูปแบบ (http/https/query/ไม่มี query/ file:// — Word ไม่ยิง request ถึง server เลย เด้งหน้าเลือกไฟล์แทน) open -a Word <local file> ใช้ได้แต่เรียกจากเว็บไม่ได้ (sandbox + backend รัน server กลางใน production) → สรุปทางเดียวที่ deterministic คือ download-first - Backend: OpenLinkService (HMAC อายุสั้น ValidateOnStart) + OpenController /api/open/{t}/{e}/v/{did}/{vid}/file.docx และ /d/{objectKey} — ทุกอย่างอยู่ใน path ไม่มี query string (Word เมิน URL มี query), [AllowAnonymous] ด้วยลายเซ็นแทน Bearer, stream จาก MinIO + disposition ชื่อไทยเหมือนเดิม · download-link + generate-draft ออก open-link แทน presigned ของ MinIO (http) · ลบ dead code presigned ทิ้ง - Web: openDocxUrl = ดาวน์โหลดทันทีทุกครั้ง + ยิง ms-word ควบคู่แบบ best-effort + notice "ไฟล์อยู่ Downloads" — เอา heuristic สลับแอป ออก (โดนหน้าเลือกไฟล์ของ Word หลอกจนไม่ดาวน์โหลด) - Spec v9.2 + ตารางทดสอบเครื่องจริงใน acceptance-review + CLAUDE.md กฎ 13 (ms-word = best-effort เท่านั้น) + ทางเลือก helper อนาคต - backend 86 / web 58 / add-in 66 + build ครบ; QA reviewer PASS (1 round, minors 4 แก้ครบ) หมายเหตุ deploy: ต้องตั้ง OpenLinks__Secret (ค่าลับจริง) และ OpenLinks__BaseUrl (https domain ของ backend) — fail ดังตั้งแต่สตาร์ทถ้าไม่ตั้ง Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-09-10 13:39:23 +07:00
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using WordVersioning.Api.Data;
using WordVersioning.Api.Services;
namespace WordVersioning.Api.Controllers;
/// <summary>FR-7/FR-15/FR-16 — endpoint เปิดไฟล์อายุสั้นของ backend เอง (ลายเซ็น HMAC ใน path แทน Bearer)
/// ให้ ms-word:ofe / เบราว์เซอร์ดึงไฟล์ผ่าน https ของ backend โดยตรง — Word for Mac รุ่นใหม่ (16.101+)
/// ยอมรับเฉพาะ URL ที่เป็น https และไม่มี query string จึงฝัง token/expiry/รหัสไฟล์ลง path ทั้งหมด</summary>
[ApiController]
[Route("api/open")]
public class OpenController(
AppDbContext db,
IObjectStorageService storage,
IOpenLinkService openLinks,
IOptions<MinioOptions> minioOptions,
ILogger<OpenController> logger) : ControllerBase
{
/// <summary>เปิดไฟล์ของ version: /api/open/{t}/{e}/v/{documentId}/{versionId}/file.{docx|pdf}</summary>
[HttpGet("{t}/{e}/v/{documentId:guid}/{versionId:guid}/{fileName}")]
[AllowAnonymous] // การรับรองคือลายเซ็นใน URL (วิ่งเข้า Word/เบราว์เซอร์ที่แนบ header ไม่ได้)
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> OpenVersion(
string t, string e, Guid documentId, Guid versionId, string fileName, CancellationToken ct)
{
var format = fileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase) ? "pdf" : "docx";
if (!openLinks.Validate($"v:{documentId}:{versionId}", format, t, e))
return Expired();
var isPdf = format == "pdf";
var row = await db.DocumentVersions
.AsNoTracking()
.Where(v => v.DocumentId == documentId && v.Id == versionId)
.Join(db.Documents, v => v.DocumentId, d => d.Id,
(v, d) => new { v.ObjectKey, v.PdfObjectKey, v.VersionNumber, d.FileName })
.FirstOrDefaultAsync(ct);
if (row is null)
return NotFound($"ไม่พบ version {versionId} ของ document {documentId}");
var objectKey = isPdf ? row.PdfObjectKey : row.ObjectKey;
if (objectKey is null)
return NotFound("version นี้ไม่มีสำเนา PDF");
var baseName = row.FileName.EndsWith(".docx", StringComparison.OrdinalIgnoreCase)
? row.FileName[..^5] : row.FileName;
return await StreamFromStorage(objectKey, $"{baseName}_v{row.VersionNumber}.{(isPdf ? "pdf" : "docx")}", isPdf, ct);
}
/// <summary>เปิดไฟล์ร่าง (FR-16): /api/open/{t}/{e}/d/drafts/{templateId}/{ไฟล์}.docx</summary>
[HttpGet("{t}/{e}/d/{**objectKey}")]
[AllowAnonymous]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> OpenDraft(string t, string e, string objectKey, CancellationToken ct)
{
// objectKey = drafts/{templateId}/{yyyyMMddHHmmss}_{guid}.docx (จบ .docx อยู่แล้ว — ชื่อไทยจริง
// ประกอบจากชื่อ template ตอน stream ไม่ใช่จาก URL ซึ่งต้องเป็น ascii)
if (!objectKey.StartsWith("drafts/", StringComparison.Ordinal)
|| !openLinks.Validate($"d:{objectKey}", "docx", t, e))
return Expired();
var parts = objectKey.Split('/');
if (parts.Length != 3 || !Guid.TryParse(parts[1], out var templateId))
return Expired();
var template = await db.Templates.AsNoTracking()
.Where(x => x.Id == templateId)
.Select(x => x.Name)
.FirstOrDefaultAsync(ct);
if (template is null)
return NotFound("ไม่พบ template ต้นทางของไฟล์ร่าง");
var timestamp = parts[2].Split('_').FirstOrDefault() ?? string.Empty;
var fileName = DocxGenerationService.BuildGeneratedFileName(template,
DateTimeOffset.TryParseExact(timestamp, "yyyyMMddHHmmss", null,
System.Globalization.DateTimeStyles.AssumeUniversal | System.Globalization.DateTimeStyles.AdjustToUniversal,
out var created) ? created : DateTimeOffset.UtcNow);
return await StreamFromStorage(objectKey, fileName, isPdf: false, ct);
}
private IActionResult Expired() =>
NotFound("ลิงก์หมดอายุหรือไม่ถูกต้อง — กรุณากดเปิดไฟล์ใหม่อีกครั้ง");
private async Task<IActionResult> StreamFromStorage(string objectKey, string fileName, bool isPdf, CancellationToken ct)
{
Stream stream;
try
{
stream = await storage.GetStreamAsync(minioOptions.Value.VersionsBucket, objectKey, ct);
}
catch (KeyNotFoundException)
{
logger.LogError("Open link target missing in storage key={ObjectKey}", objectKey);
return NotFound("ไฟล์ไม่พบใน storage");
}
// disposition นโยบายเดียวกับ presigned เดิม: PDF inline, docx attachment ชื่อไทยตาม RFC 5987
// (File() ไม่แตะ Content-Disposition เมื่อไม่ส่ง fileDownloadName — เราเซ็ตเองจึงอยู่รอด)
Response.Headers.ContentDisposition =
$"{(isPdf ? "inline" : "attachment")}; filename*=UTF-8''{Uri.EscapeDataString(fileName)}";
return File(stream, isPdf ? PdfUploadValidation.PdfContentType : DocxUploadValidation.DocxContentType);
}
}