294 lines
9.1 KiB
Go
294 lines
9.1 KiB
Go
package cabana
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"git.golem15.com/golem15/summercms/modules/bouncer"
|
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
|
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// AdminMailImage is one library image with absolute public URLs.
|
|
type AdminMailImage struct {
|
|
ID uint `json:"id"`
|
|
FileName string `json:"fileName"`
|
|
Title string `json:"title"`
|
|
URL string `json:"url"`
|
|
ThumbURL string `json:"thumbUrl,omitempty"`
|
|
}
|
|
|
|
// AdminMailImagesMeta is the meta of GET /mail/images.
|
|
type AdminMailImagesMeta struct {
|
|
CanUpload bool `json:"canUpload"`
|
|
Total int64 `json:"total"`
|
|
Page int `json:"page"`
|
|
PerPage int `json:"perPage"`
|
|
}
|
|
|
|
// AdminMailImagesResponse is the GET /mail/images answer (custom meta).
|
|
type AdminMailImagesResponse struct {
|
|
Data []AdminMailImage `json:"data"`
|
|
Meta AdminMailImagesMeta `json:"meta"`
|
|
}
|
|
|
|
const (
|
|
mailImagesPerPage = 40
|
|
mailImageMaxBytes = 5 << 20
|
|
)
|
|
|
|
var mailImageLimits = attach.Limits{
|
|
MaxBytes: mailImageMaxBytes,
|
|
Extensions: attach.DefaultImageExtensions,
|
|
Image: true,
|
|
}
|
|
|
|
// mailImagesList serves GET /mail/images: library images with absolute URLs,
|
|
// for holders of either mail permission. canUpload is true only for layouts.
|
|
func (s *service) mailImagesList(w http.ResponseWriter, r *http.Request) {
|
|
principal, ok := bouncer.User(r.Context())
|
|
if !ok || principal == nil || !principal.Backend {
|
|
WriteError(w, http.StatusUnauthorized, "unauthenticated", msgUnauthenticated)
|
|
return
|
|
}
|
|
if !tokenRouteGate(principal, w) {
|
|
return
|
|
}
|
|
if !Allows(principal, []string{PermissionManageMailTemplates, PermissionManageMailLayouts}) {
|
|
WriteError(w, http.StatusForbidden, "forbidden", msgForbidden)
|
|
return
|
|
}
|
|
cfg := s.config()
|
|
if _, err := attach.AbsolutePublicURL(cfg, "probe"); errors.Is(err, attach.ErrNoAbsoluteURL) {
|
|
WriteError(w, http.StatusConflict, "conflict", s.mailMessage(r.Context(), mailLang+"images.no_public_url"))
|
|
return
|
|
}
|
|
db, err := s.db()
|
|
if err != nil {
|
|
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
|
return
|
|
}
|
|
q := strings.TrimSpace(r.URL.Query().Get("q"))
|
|
page := 1
|
|
if raw := r.URL.Query().Get("page"); raw != "" {
|
|
if n, err := strconv.Atoi(raw); err == nil && n > 0 {
|
|
page = n
|
|
}
|
|
}
|
|
query := db.WithContext(r.Context()).Model(&attach.File{}).
|
|
Where("attachment_type = ? AND field = ?", mailImageLibraryMorph, "images")
|
|
if q != "" {
|
|
like := "%" + q + "%"
|
|
query = query.Where("file_name ILIKE ? OR title ILIKE ?", like, like)
|
|
}
|
|
var total int64
|
|
if err := query.Count(&total).Error; err != nil {
|
|
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
|
return
|
|
}
|
|
var files []attach.File
|
|
if err := query.Order("id DESC").Offset((page - 1) * mailImagesPerPage).Limit(mailImagesPerPage).Find(&files).Error; err != nil {
|
|
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
|
return
|
|
}
|
|
items := make([]AdminMailImage, 0, len(files))
|
|
for i := range files {
|
|
item, err := s.mailImageItem(r.Context(), &files[i])
|
|
if err != nil {
|
|
if errors.Is(err, attach.ErrNoAbsoluteURL) {
|
|
WriteError(w, http.StatusConflict, "conflict", s.mailMessage(r.Context(), mailLang+"images.no_public_url"))
|
|
return
|
|
}
|
|
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
|
return
|
|
}
|
|
items = append(items, item)
|
|
}
|
|
WriteData(w, http.StatusOK, items, AdminMailImagesMeta{
|
|
CanUpload: Allows(principal, []string{PermissionManageMailLayouts}),
|
|
Total: total,
|
|
Page: page,
|
|
PerPage: mailImagesPerPage,
|
|
})
|
|
}
|
|
|
|
// mailImagesShow serves GET /mail/images/{id}: one library image, or 404.
|
|
func (s *service) mailImagesShow(w http.ResponseWriter, r *http.Request) {
|
|
principal, ok := bouncer.User(r.Context())
|
|
if !ok || principal == nil || !principal.Backend {
|
|
WriteError(w, http.StatusUnauthorized, "unauthenticated", msgUnauthenticated)
|
|
return
|
|
}
|
|
if !tokenRouteGate(principal, w) {
|
|
return
|
|
}
|
|
if !Allows(principal, []string{PermissionManageMailTemplates, PermissionManageMailLayouts}) {
|
|
WriteError(w, http.StatusForbidden, "forbidden", msgForbidden)
|
|
return
|
|
}
|
|
id, err := strconv.ParseUint(r.PathValue("id"), 10, 64)
|
|
if err != nil || id == 0 {
|
|
writeNotFound(w, r)
|
|
return
|
|
}
|
|
db, err := s.db()
|
|
if err != nil {
|
|
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
|
return
|
|
}
|
|
var f attach.File
|
|
err = db.WithContext(r.Context()).
|
|
Where("id = ? AND attachment_type = ? AND field = ?", id, mailImageLibraryMorph, "images").
|
|
Take(&f).Error
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
writeNotFound(w, r)
|
|
return
|
|
}
|
|
if err != nil {
|
|
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
|
return
|
|
}
|
|
item, err := s.mailImageItem(r.Context(), &f)
|
|
if err != nil {
|
|
if errors.Is(err, attach.ErrNoAbsoluteURL) {
|
|
WriteError(w, http.StatusConflict, "conflict", s.mailMessage(r.Context(), mailLang+"images.no_public_url"))
|
|
return
|
|
}
|
|
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
|
return
|
|
}
|
|
WriteData(w, http.StatusOK, item, nil)
|
|
}
|
|
|
|
// mailImagesUpload serves POST /mail/images: layouts holders only, multipart
|
|
// "file", attached to the library host with an absolute public URL.
|
|
func (s *service) mailImagesUpload(w http.ResponseWriter, r *http.Request) {
|
|
principal, ok := bouncer.User(r.Context())
|
|
if !ok || principal == nil || !principal.Backend {
|
|
WriteError(w, http.StatusUnauthorized, "unauthenticated", msgUnauthenticated)
|
|
return
|
|
}
|
|
if !tokenRouteGate(principal, w) {
|
|
return
|
|
}
|
|
if !Allows(principal, []string{PermissionManageMailLayouts}) {
|
|
WriteError(w, http.StatusForbidden, "forbidden", msgForbidden)
|
|
return
|
|
}
|
|
if _, err := attach.AbsolutePublicURL(s.config(), "probe"); errors.Is(err, attach.ErrNoAbsoluteURL) {
|
|
WriteError(w, http.StatusConflict, "conflict", s.mailMessage(r.Context(), mailLang+"images.no_public_url"))
|
|
return
|
|
}
|
|
db, err := s.db()
|
|
if err != nil {
|
|
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
|
return
|
|
}
|
|
bucket := s.bucket()
|
|
if bucket == nil {
|
|
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
|
|
return
|
|
}
|
|
body := &bodyReader{r: http.MaxBytesReader(w, r.Body, s.uploadCap(nil))}
|
|
r.Body = io.NopCloser(body)
|
|
mr, err := r.MultipartReader()
|
|
if err != nil {
|
|
writeCRUDError(w, invalidBody())
|
|
return
|
|
}
|
|
part, err := mr.NextPart()
|
|
if err != nil {
|
|
writeCRUDError(w, invalidBody())
|
|
return
|
|
}
|
|
if part.FormName() != "file" || strings.TrimSpace(part.FileName()) == "" {
|
|
writeCRUDError(w, invalidBody())
|
|
return
|
|
}
|
|
var stored *attach.File
|
|
var item AdminMailImage
|
|
err = lagoon.Transaction(r.Context(), db, func(ctx context.Context, tx *gorm.DB) error {
|
|
host, err := mailImagesAdmin{}.SingletonRecord(ctx, tx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
library, ok := host.(*MailImageLibrary)
|
|
if !ok || library == nil || library.ID == 0 {
|
|
return errors.New("cabana: mail image library host missing")
|
|
}
|
|
f, err := attach.Store(ctx, tx, bucket, attach.Upload{FileName: part.FileName(), Body: part, Public: true}, mailImageLimits)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
stored = f
|
|
if _, err := mr.NextPart(); !errors.Is(err, io.EOF) {
|
|
if err == nil {
|
|
return invalidBody()
|
|
}
|
|
return err
|
|
}
|
|
if err := tx.Session(&gorm.Session{NewDB: true, Context: ctx}).Model(&attach.File{}).Where("id = ?", f.ID).Updates(map[string]any{
|
|
"attachment_id": uitoa(library.ID),
|
|
"attachment_type": mailImageLibraryMorph,
|
|
"field": "images",
|
|
}).Error; err != nil {
|
|
return err
|
|
}
|
|
f.AttachmentID = uitoa(library.ID)
|
|
f.AttachmentType = mailImageLibraryMorph
|
|
f.Field = "images"
|
|
item, err = s.mailImageItem(ctx, f)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
if stored != nil {
|
|
_ = attach.DeleteKeys(context.WithoutCancel(r.Context()), bucket, attach.BlobKeys(*stored))
|
|
}
|
|
if errors.Is(err, attach.ErrNoAbsoluteURL) {
|
|
WriteError(w, http.StatusConflict, "conflict", s.mailMessage(r.Context(), mailLang+"images.no_public_url"))
|
|
return
|
|
}
|
|
if errors.Is(err, attach.ErrNotImage) || errors.Is(err, attach.ErrFileType) || errors.Is(err, attach.ErrMIMEType) || errors.Is(err, attach.ErrTooLarge) {
|
|
writeCRUDError(w, &ValidationError{Details: map[string]any{"file": []string{err.Error()}}})
|
|
return
|
|
}
|
|
writeCRUDError(w, err)
|
|
return
|
|
}
|
|
WriteData(w, http.StatusCreated, item, nil)
|
|
}
|
|
|
|
func (s *service) mailImageItem(ctx context.Context, f *attach.File) (AdminMailImage, error) {
|
|
url, err := attach.AbsolutePublicURL(s.config(), attach.BlobKey(f.DiskName))
|
|
if err != nil {
|
|
return AdminMailImage{}, err
|
|
}
|
|
title := f.FileName
|
|
if f.Title != nil && *f.Title != "" {
|
|
title = *f.Title
|
|
}
|
|
item := AdminMailImage{ID: f.ID, FileName: f.FileName, Title: title, URL: url}
|
|
if bucket := s.bucket(); bucket != nil {
|
|
if key, err := f.ThumbKey(ctx, bucket, defaultThumbEdge, defaultThumbEdge, "auto"); err == nil && key != "" {
|
|
if abs, err := attach.AbsolutePublicURL(s.config(), key); err == nil {
|
|
item.ThumbURL = abs
|
|
}
|
|
}
|
|
}
|
|
return item, nil
|
|
}
|
|
|
|
// mailMessage translates a mail phrase key in the request locale.
|
|
func (s *service) mailMessage(ctx context.Context, key string) string {
|
|
tr := s.translator()
|
|
if tr == nil {
|
|
return key
|
|
}
|
|
return translateKey(ctx, tr, key)
|
|
}
|