package httpapi import ( "errors" "io" "net/http" "xhchat/server/internal/account" "xhchat/server/internal/delivery" ) func (a *API) uploadAttachment(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) { id, recipient := r.PathValue("id"), r.URL.Query().Get("recipient") if !uuidPattern.MatchString(id) || !uuidPattern.MatchString(recipient) || r.Header.Get("Content-Type") != "application/octet-stream" { problem(w, 400, "invalid_attachment", "附件请求格式无效") return } if !a.limit(w, r, "attachment-upload:"+identity.Device.ID, 12) { return } body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, delivery.AttachmentLimit)) var tooLarge *http.MaxBytesError switch { case errors.As(err, &tooLarge): problem(w, 413, "attachment_too_large", "附件超过 8 MiB") return case err != nil || len(body) < 16: problem(w, 400, "invalid_attachment", "附件请求格式无效") return } err = a.delivery.UploadAttachment(r.Context(), identity.Device.ID, recipient, id, body) switch { case errors.Is(err, delivery.ErrUnavailable): problem(w, 404, "attachment_unavailable", "无法向指定设备发送附件") case errors.Is(err, delivery.ErrConflict): problem(w, 409, "attachment_conflict", "附件 ID 已使用") case err != nil: unavailable(w, err) default: w.WriteHeader(204) } } func (a *API) downloadAttachment(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) { id := r.PathValue("id") if !uuidPattern.MatchString(id) { problem(w, 404, "attachment_unavailable", "附件不可用") return } if !a.limit(w, r, "attachment-download:"+identity.Device.ID, 30) { return } body, err := a.delivery.DownloadAttachment(r.Context(), identity.Device.ID, id) switch { case errors.Is(err, delivery.ErrUnavailable): problem(w, 404, "attachment_unavailable", "附件不可用或已过期") case err != nil: unavailable(w, err) default: w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("Content-Disposition", "attachment") _, _ = w.Write(body) } }