package api import ( "crypto/sha256" "encoding/hex" "fmt" "image" _ "image/gif" _ "image/jpeg" _ "image/png" "io" "net/http" "os" "path/filepath" "strings" "time" "github.com/go-chi/chi/v5" "github.com/yourorg/article-platform/internal/platform/httpx" "github.com/yourorg/article-platform/internal/platform/idgen" "github.com/yourorg/article-platform/internal/platform/middleware" "github.com/yourorg/article-platform/internal/platform/storage" ) // 媒体类型白名单与体积上限。 // // 白名单而非黑名单:黑名单永远漏,而媒体类型是可枚举的有限集合。 // 每类上限按真实业务定:封面图 20MB、视频 200MB、音频 50MB, // 这比「统一 1GB」安全得多 —— 后者等于给攻击者一个免费网盘。 var mediaRules = map[string]struct { maxBytes int64 exts []string }{ "image": {20 << 20, []string{"jpg", "jpeg", "png", "gif", "webp", "bmp", "avif"}}, "video": {200 << 20, []string{"mp4", "mov", "webm", "m4v"}}, "audio": {50 << 20, []string{"mp3", "m4a", "aac", "wav", "ogg", "flac"}}, } // MIME ↔ 扩展名双向映射,用于交叉校验: // 客户端说 content_type=image/png 但 filename=x.exe 时必须拒绝。 var mimeToExts = map[string][]string{ "image/jpeg": {"jpg", "jpeg"}, "image/png": {"png"}, "image/gif": {"gif"}, "image/webp": {"webp"}, "image/bmp": {"bmp"}, "image/avif": {"avif"}, "video/mp4": {"mp4", "m4v"}, "video/quicktime": {"mov"}, "video/webm": {"webm"}, "audio/mpeg": {"mp3"}, "audio/mp4": {"m4a", "aac"}, "audio/aac": {"aac"}, "audio/wav": {"wav"}, "audio/ogg": {"ogg"}, "audio/flac": {"flac"}, } type presignReq struct { Filename string `json:"filename"` ContentType string `json:"content_type"` Size int64 `json:"size"` MediaType string `json:"media_type"` // image | video | audio } type presignResp struct { AssetID string `json:"asset_id"` UploadURL string `json:"upload_url"` Method string `json:"method"` Headers map[string]string `json:"headers"` ObjectKey string `json:"object_key"` PublicURL string `json:"public_url"` ExpiresIn int `json:"expires_in"` } // presign 签发客户端直传凭证。 // // 核心原则:应用服务器一个字节的上传流量都不该经过。 // 服务端只校验意图(类型、体积、配额)并签名,字节从客户端直飞对象存储。 func (d *Deps) presign(w http.ResponseWriter, r *http.Request) { if d.Presigner == nil { httpx.WriteError(w, httpx.NewError(http.StatusServiceUnavailable, httpx.CodeInternal, "对象存储未配置,请联系管理员")) return } var req presignReq if err := httpx.Decode(r, &req); err != nil { httpx.WriteError(w, err) return } req.Filename = strings.TrimSpace(req.Filename) req.MediaType = strings.ToLower(strings.TrimSpace(req.MediaType)) req.ContentType = strings.ToLower(strings.TrimSpace(req.ContentType)) if req.Filename == "" { httpx.WriteError(w, httpx.InvalidParam("filename 不能为空")) return } if req.Size <= 0 { httpx.WriteError(w, httpx.InvalidParam("size 必须大于 0")) return } rule, ok := mediaRules[req.MediaType] if !ok { httpx.WriteError(w, httpx.InvalidParam("media_type 只能是 image / video / audio")) return } if req.Size > rule.maxBytes { httpx.WriteError(w, httpx.NewError(http.StatusRequestEntityTooLarge, "FILE_TOO_LARGE", fmt.Sprintf("%s 类型最大 %d MB", req.MediaType, rule.maxBytes>>20))) return } ext := strings.TrimPrefix(strings.ToLower(filepath.Ext(req.Filename)), ".") if !containsStr(rule.exts, ext) { httpx.WriteError(w, httpx.InvalidParam( fmt.Sprintf("扩展名 .%s 不在 %s 白名单内", ext, req.MediaType))) return } // MIME 与扩展名必须一致。挡住「声明 png 实传 exe」这类绕过。 allowedExts, hasMime := mimeToExts[req.ContentType] if !hasMime { httpx.WriteError(w, httpx.InvalidParam("不支持的 content_type: "+req.ContentType)) return } if !containsStr(allowedExts, ext) { httpx.WriteError(w, httpx.NewError(http.StatusBadRequest, "MIME_MISMATCH", fmt.Sprintf("content_type=%s 与扩展名 .%s 不匹配", req.ContentType, ext))) return } // 配额:单用户未完成的 pending 上传数上限,防刷 uid := middleware.UserID(r.Context()) pendingCount, err := d.Media.CountPending(r.Context(), d.Pool, uid) if err != nil { d.Log.Warn("查询上传配额失败", "err", err) } if pendingCount >= 50 { httpx.WriteError(w, httpx.NewError(http.StatusTooManyRequests, httpx.CodeRateLimited, "未完成的上传过多,请先完成或等待过期")) return } assetID := idgen.NewUUIDv7() // 用 assetID 做占位 key 前缀,confirm 时若客户端提供了真实 sha256 会重命名为内容寻址 key。 // 这样既保证 key 唯一,又能在 confirm 后做去重。 placeholderKey := fmt.Sprintf("pending/%s/%s.%s", uid, assetID, ext) ttl := 15 * time.Minute uploadURL, err := d.Presigner.SignPut(placeholderKey, req.ContentType, req.Size, ttl) if err != nil { d.Log.Error("签名失败", "err", err) httpx.WriteError(w, err) return } if err := d.Media.InsertPending(r.Context(), d.Pool, assetID, uid, placeholderKey, d.Cfg.S3.Bucket, req.Filename, req.ContentType, req.Size); err != nil { d.Log.Error("写入媒体记录失败", "err", err) httpx.WriteError(w, err) return } if d.Metrics != nil { d.Metrics.MediaPresigned.Inc() } httpx.WriteJSON(w, http.StatusOK, presignResp{ AssetID: assetID, UploadURL: uploadURL, Method: "PUT", Headers: map[string]string{ "Content-Type": req.ContentType, "Content-Length": fmt.Sprintf("%d", req.Size), }, ObjectKey: placeholderKey, PublicURL: d.Presigner.PublicURL(placeholderKey), ExpiresIn: int(ttl.Seconds()), }) } type confirmReq struct { AssetID string `json:"asset_id"` // 客户端上传完成后计算的 SHA-256(可选,但强烈建议提供) // 提供后会重命名为内容寻址 key,实现跨用户去重 SHA256 string `json:"sha256,omitempty"` Width int `json:"width,omitempty"` Height int `json:"height,omitempty"` DurationSeconds int `json:"duration_seconds,omitempty"` } // confirm 客户端上传完成后回调,把 asset 标记为 ready。 // // 生产环境这里应该用 HeadObject 校验对象真实存在、真实大小与声明一致, // 并用 worker 下载头部字节解析真实宽高(不信任客户端上报的 width/height)。 // 当前实现记录客户端上报值并标记 ready,HeadObject 校验在 S3 客户端接好后补上。 func (d *Deps) confirmMedia(w http.ResponseWriter, r *http.Request) { var req confirmReq if err := httpx.Decode(r, &req); err != nil { httpx.WriteError(w, err) return } if req.AssetID == "" { httpx.WriteError(w, httpx.InvalidParam("asset_id 不能为空")) return } uid := middleware.UserID(r.Context()) asset, err := d.Media.GetByID(r.Context(), d.Pool, req.AssetID) if err != nil { httpx.WriteError(w, httpx.NotFound("媒体记录不存在")) return } // 只能确认自己上传的资源 if asset.OwnerID != uid { httpx.WriteError(w, httpx.ErrForbidden) return } // 校验必须在幂等短路之前:否则已 ready 的资源会跳过所有入参校验, // 非法 sha256 也能拿到 200,等于把校验形同虚设。 if !validSHA256(req.SHA256) { httpx.WriteError(w, httpx.InvalidParam("sha256 格式非法(需 64 位十六进制)")) return } // 已 ready 直接返回(幂等:客户端重试不会重复处理) if asset.Status == "ready" { httpx.WriteJSON(w, http.StatusOK, asset) return } newKey := storage.ObjectKey(req.SHA256, filepath.Ext(asset.ObjectKey), time.Now()) if err := d.Media.MarkReady(r.Context(), d.Pool, req.AssetID, newKey, req.SHA256, req.Width, req.Height, req.DurationSeconds); err != nil { d.Log.Error("确认媒体失败", "err", err) httpx.WriteError(w, err) return } publicURL := "" if d.Presigner != nil { publicURL = d.Presigner.PublicURL(newKey) } if d.Metrics != nil { d.Metrics.MediaConfirmed.Inc() } httpx.WriteJSON(w, http.StatusOK, map[string]any{ "asset_id": req.AssetID, "object_key": newKey, "public_url": publicURL, "status": "ready", "width": req.Width, "height": req.Height, }) } // getMedia 查询自己的媒体资源 func (d *Deps) getMedia(w http.ResponseWriter, r *http.Request) { asset, err := d.Media.GetByID(r.Context(), d.Pool, chi.URLParam(r, "assetID")) if err != nil { httpx.WriteError(w, httpx.NotFound("媒体记录不存在")) return } if asset.OwnerID != middleware.UserID(r.Context()) { httpx.WriteError(w, httpx.ErrForbidden) return } if d.Presigner != nil && asset.Status == "ready" { asset.URL = d.Presigner.PublicURL(asset.ObjectKey) if g, err := d.Presigner.SignGet(asset.ObjectKey, 2*time.Hour); err == nil { asset.SignedURL = g } } httpx.WriteJSON(w, http.StatusOK, asset) } func containsStr(list []string, s string) bool { for _, x := range list { if x == s { return true } } return false } func validSHA256(s string) bool { if len(s) != 64 { return false } _, err := hex.DecodeString(s) return err == nil } // uploadDirectAsset 处理客户端标准 multipart/form-data 文件上传 // 针对 uni-app、Web、Admin 等前端的单文件上传与本地化/CDN 交付 func (d *Deps) uploadDirectAsset(w http.ResponseWriter, r *http.Request) { // 最大支持 200MB 的请求体 if err := r.ParseMultipartForm(32 << 20); err != nil { httpx.WriteError(w, httpx.InvalidParam("无法解析上传文件表单: "+err.Error())) return } file, header, err := r.FormFile("file") if err != nil { httpx.WriteError(w, httpx.InvalidParam("未找到上传文件(file 字段)")) return } defer file.Close() declaredType := strings.ToLower(strings.TrimSpace(r.FormValue("media_type"))) if declaredType == "" { declaredType = "image" } rule, ok := mediaRules[declaredType] if !ok { declaredType = "image" rule = mediaRules["image"] } // 检查大小 if header.Size > rule.maxBytes { httpx.WriteError(w, httpx.NewError(http.StatusRequestEntityTooLarge, "FILE_TOO_LARGE", fmt.Sprintf("%s 类型最大 %d MB", declaredType, rule.maxBytes>>20))) return } ext := strings.TrimPrefix(strings.ToLower(filepath.Ext(header.Filename)), ".") if ext == "" || !containsStr(rule.exts, ext) { if declaredType == "image" { ext = "jpg" } else if declaredType == "video" { ext = "mp4" } else { ext = "mp3" } } uploadsDir := "./uploads" if err := os.MkdirAll(uploadsDir, 0755); err != nil { httpx.WriteError(w, httpx.NewError(http.StatusInternalServerError, httpx.CodeInternal, "创建上传目录失败")) return } assetID := "ast_" + strings.ReplaceAll(idgen.NewUUIDv7(), "-", "")[:16] saveName := fmt.Sprintf("%s.%s", assetID, ext) savePath := filepath.Join(uploadsDir, saveName) dst, err := os.Create(savePath) if err != nil { httpx.WriteError(w, httpx.NewError(http.StatusInternalServerError, httpx.CodeInternal, "保存文件失败")) return } hasher := sha256.New() multiWriter := io.MultiWriter(dst, hasher) written, err := io.Copy(multiWriter, file) _ = dst.Close() if err != nil { _ = os.Remove(savePath) httpx.WriteError(w, httpx.NewError(http.StatusInternalServerError, httpx.CodeInternal, "写入文件失败")) return } sha256Hex := hex.EncodeToString(hasher.Sum(nil)) var width, height *int var format *string if declaredType == "image" { if imgFile, err := os.Open(savePath); err == nil { if cfg, fmtName, err := image.DecodeConfig(imgFile); err == nil { wVal, hVal := cfg.Width, cfg.Height width = &wVal height = &hVal format = &fmtName } else { // 尝试 WebP 探测 _ = imgFile.Close() if data, err := os.ReadFile(savePath); err == nil { if wVal, hVal, ok := probeWebP(data); ok { width = &wVal height = &hVal fmtName := "webp" format = &fmtName } } } _ = imgFile.Close() } } // 如果当前用户已登录,尝试记录到 media_assets uid := middleware.UserID(r.Context()) if uid != "" { wVal, hVal := 0, 0 if width != nil { wVal = *width } if height != nil { hVal = *height } newKey := "uploads/" + saveName _ = d.Media.InsertPending(r.Context(), d.Pool, idgen.NewUUIDv7(), uid, newKey, "local", header.Filename, header.Header.Get("Content-Type"), written) _ = d.Media.MarkReady(r.Context(), d.Pool, assetID, newKey, sha256Hex, wVal, hVal, 0) } publicURL := "/uploads/" + saveName httpx.WriteJSON(w, http.StatusOK, map[string]any{ "asset_id": assetID, "url": publicURL, "public_url": publicURL, "media_type": declaredType, "width": width, "height": height, "format": format, "file_size_bytes": written, "duration_seconds": 0, "transcode_status": "ready", }) } func probeWebP(data []byte) (int, int, bool) { if len(data) < 30 || string(data[0:4]) != "RIFF" || string(data[8:12]) != "WEBP" { return 0, 0, false } switch string(data[12:16]) { case "VP8 ": if len(data) >= 30 && data[23] == 0x9d && data[24] == 0x01 && data[25] == 0x2a { w := int(data[26]) | int(data[27]&0x3f)<<8 h := int(data[28]) | int(data[29]&0x3f)<<8 return w, h, true } case "VP8L": if len(data) >= 25 && data[20] == 0x2f { b0, b1, b2, b3 := uint32(data[21]), uint32(data[22]), uint32(data[23]), uint32(data[24]) val := b0 | (b1 << 8) | (b2 << 16) | (b3 << 24) w := int(val&0x3fff) + 1 h := int((val>>14)&0x3fff) + 1 return w, h, true } case "VP8X": if len(data) >= 30 { w := int(data[24]) | int(data[25])<<8 | int(data[26])<<16 + 1 h := int(data[27]) | int(data[28])<<8 | int(data[29])<<16 + 1 return w, h, true } } return 0, 0, false }