linstrom/media/addFile.go

98 lines
2.4 KiB
Go

package media
import (
"context"
"database/sql"
"errors"
"io"
"os"
"path"
"git.mstar.dev/mstar/goutils/other"
"github.com/gabriel-vasile/mimetype"
"github.com/minio/minio-go/v7"
"github.com/rs/zerolog/log"
"git.mstar.dev/mstar/linstrom/config"
"git.mstar.dev/mstar/linstrom/shared"
"git.mstar.dev/mstar/linstrom/storage-new/dbgen"
"git.mstar.dev/mstar/linstrom/storage-new/models"
)
var ErrFileAlreadyExists = errors.New("a file with that name already exists")
func (s *Server) AddFile(
fileReader io.Reader,
filename, userId string,
blurred bool,
altText string,
) (string, error) {
fileCount, err := dbgen.MediaMetadata.Where(dbgen.MediaMetadata.OwnedById.Eq(sql.NullString{Valid: true, String: userId}), dbgen.MediaMetadata.Name.Eq(filename)).
Count()
if err != nil {
return "", err
}
if fileCount > 0 {
return "", ErrFileAlreadyExists
}
transcoderInDir := config.GlobalConfig.Transcoder.InDir()
filePath := path.Join(transcoderInDir, filename)
file, err := os.Create(filePath)
if err != nil {
return "", err
}
if _, err = io.Copy(file, fileReader); err != nil {
_ = file.Close()
return "", err
}
_ = file.Close()
if s.transcoderClient == nil {
return s.addFileAsIs(filename, userId, filePath, nil, blurred, altText)
} else {
return s.addFileWithTranscoder(filename, userId, filePath, blurred, altText)
}
}
// adFileAsIs uploads the given file. If mtype (short for mimetype, shortened because of module naming conflict)
// is not nil, use that as the file's mimetype. Otherwise, the mimetype will be detected manually
func (s *Server) addFileAsIs(
filename, userId, filepath string,
mtype *string,
blurred bool,
altText string,
) (string, error) {
if mtype == nil {
mType, err := mimetype.DetectFile(filepath)
if err != nil {
return "", err
}
mtype = other.IntoPointer(mType.String())
}
id := shared.NewId()
s3Result, err := s.client.FPutObject(
context.TODO(),
config.GlobalConfig.S3.BucketName,
id,
filepath,
minio.PutObjectOptions{},
)
if err != nil {
return "", err
}
log.Debug().Any("result", s3Result).Msg("Upload result")
fileMetadata := models.MediaMetadata{
ID: id,
OwnedById: sql.NullString{Valid: true, String: userId},
Remote: false,
Location: s3Result.Key,
Type: *mtype,
Name: filename,
AltText: altText,
Blurred: blurred,
}
err = dbgen.MediaMetadata.Create(&fileMetadata)
if err != nil {
return "", err
}
return id, nil
}