2026-03-02 11:26:40 +00:00
|
|
|
package uploadfiles
|
|
|
|
|
|
|
|
|
|
import (
|
2026-03-04 11:33:39 +00:00
|
|
|
"os"
|
|
|
|
|
"path/filepath"
|
|
|
|
|
"strings"
|
|
|
|
|
|
2026-03-02 11:26:40 +00:00
|
|
|
"emperror.dev/errors"
|
2026-03-04 11:33:39 +00:00
|
|
|
"github.com/disintegration/imaging"
|
2026-03-02 11:26:40 +00:00
|
|
|
"lmika.dev/lmika/weiro/models"
|
|
|
|
|
)
|
|
|
|
|
|
2026-03-04 11:33:39 +00:00
|
|
|
const (
|
|
|
|
|
applicationOctetStream = "application/octet-stream"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var supportedRencodableImageTypes = map[string]bool{
|
|
|
|
|
"image/jpeg": true,
|
|
|
|
|
"image/png": true,
|
|
|
|
|
applicationOctetStream: true,
|
|
|
|
|
}
|
|
|
|
|
var supportedReencoableExtensions = map[string]bool{
|
|
|
|
|
".jpg": true,
|
|
|
|
|
".jpeg": true,
|
|
|
|
|
".png": true,
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-02 11:26:40 +00:00
|
|
|
func (p *Provider) StripeEXIFData(site models.Site, up models.Upload) error {
|
|
|
|
|
uploadFilename := p.uploadFileName(site, up)
|
|
|
|
|
|
2026-03-04 11:33:39 +00:00
|
|
|
if !supportedRencodableImageTypes[up.MIMEType] {
|
|
|
|
|
return errors.New("unsupported image format: " + up.MIMEType)
|
|
|
|
|
}
|
|
|
|
|
if up.MIMEType == applicationOctetStream && !supportedReencoableExtensions[filepath.Ext(uploadFilename)] {
|
|
|
|
|
return errors.New("unsupported image format")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
img, err := imaging.Open(uploadFilename)
|
2026-03-02 11:26:40 +00:00
|
|
|
if err != nil {
|
2026-03-04 11:33:39 +00:00
|
|
|
return errors.Wrap(err, "failed to open image file")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
tmpName := strings.TrimSuffix(uploadFilename, filepath.Ext(uploadFilename)) + ".tmp." + filepath.Ext(uploadFilename)
|
|
|
|
|
if err := imaging.Save(img, tmpName); err != nil {
|
|
|
|
|
return errors.Wrap(err, "failed to save image file")
|
2026-03-02 11:26:40 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-04 11:33:39 +00:00
|
|
|
if err := os.Remove(uploadFilename); err != nil {
|
|
|
|
|
_ = os.Remove(tmpName)
|
|
|
|
|
return errors.Wrap(err, "failed to remove image file")
|
2026-03-02 11:26:40 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-04 11:33:39 +00:00
|
|
|
if err := os.Rename(tmpName, uploadFilename); err != nil {
|
|
|
|
|
return errors.Wrap(err, "failed to rename image file")
|
2026-03-02 11:26:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|