automatically detect image types and set primary photo if first

This commit is contained in:
Hayden 2023-12-01 11:45:20 -06:00
parent 3f455cb574
commit 51e3ad11c4
No known key found for this signature in database
GPG key ID: 17CF79474E257545
4 changed files with 39 additions and 9 deletions

View file

@ -3,6 +3,7 @@ package v1
import (
"errors"
"net/http"
"path/filepath"
"github.com/hay-kot/homebox/backend/internal/core/services"
"github.com/hay-kot/homebox/backend/internal/data/ent/attachment"
@ -67,7 +68,15 @@ func (ctrl *V1Controller) HandleItemAttachmentCreate() errchain.HandlerFunc {
attachmentType := r.FormValue("type")
if attachmentType == "" {
attachmentType = attachment.TypeAttachment.String()
// Attempt to auto-detect the type of the file
ext := filepath.Ext(attachmentName)
switch ext {
case ".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp", ".tiff":
attachmentType = attachment.TypePhoto.String()
default:
attachmentType = attachment.TypeAttachment.String()
}
}
id, err := ctrl.routeID(r)

View file

@ -52,11 +52,30 @@ func ToItemAttachment(attachment *ent.Attachment) ItemAttachment {
}
func (r *AttachmentRepo) Create(ctx context.Context, itemId, docId uuid.UUID, typ attachment.Type) (*ent.Attachment, error) {
return r.db.Attachment.Create().
bldr := r.db.Attachment.Create().
SetType(typ).
SetDocumentID(docId).
SetItemID(itemId).
Save(ctx)
SetItemID(itemId)
// Autoset primary to true if this is the first attachment
// that is of type photo
if typ == attachment.TypePhoto {
cnt, err := r.db.Attachment.Query().
Where(
attachment.HasItemWith(item.ID(itemId)),
attachment.TypeEQ(typ),
).
Count(ctx)
if err != nil {
return nil, err
}
if cnt == 0 {
bldr = bldr.SetPrimary(true)
}
}
return bldr.Save(ctx)
}
func (r *AttachmentRepo) Get(ctx context.Context, id uuid.UUID) (*ent.Attachment, error) {
@ -75,7 +94,7 @@ func (r *AttachmentRepo) Update(ctx context.Context, itemId uuid.UUID, data *Ite
bldr := r.db.Attachment.UpdateOneID(itemId).
SetType(typ)
// Primary only applies to photos
// Primary only applies to photos
if typ == attachment.TypePhoto {
bldr = bldr.SetPrimary(data.Primary)
} else {