weiro/providers/uploadfiles/exif.go

59 lines
1.5 KiB
Go
Raw Normal View History

package uploadfiles
import (
"os"
"path/filepath"
"strings"
"emperror.dev/errors"
"github.com/disintegration/imaging"
"lmika.dev/lmika/weiro/models"
)
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,
}
func (p *Provider) StripeEXIFData(site models.Site, up models.Upload) error {
uploadFilename := p.uploadFileName(site, up)
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)
if err != nil {
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")
}
if err := os.Remove(uploadFilename); err != nil {
_ = os.Remove(tmpName)
return errors.Wrap(err, "failed to remove image file")
}
if err := os.Rename(tmpName, uploadFilename); err != nil {
return errors.Wrap(err, "failed to rename image file")
}
return nil
}