Files

79 lines
2.3 KiB
Go

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, ok := readAttachment(w, r)
if !ok {
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 readAttachment(w http.ResponseWriter, r *http.Request) ([]byte, bool) {
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 nil, false
case err != nil || len(body) < 16:
problem(w, 400, "invalid_attachment", "附件请求格式无效")
return nil, false
}
return body, true
}
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:
writeAttachment(w, body)
}
}
func writeAttachment(w http.ResponseWriter, body []byte) {
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "attachment")
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(body)
}