linstrom/media/addFile.go
mstar c813c4784a
All checks were successful
/ docker (push) Successful in 1m54s
Add media upload functionality
2025-06-17 16:48:24 +02:00

74 lines
1.9 KiB
Go

package media
import (
"context"
"database/sql"
"git.mstar.dev/mstar/goutils/other"
"git.mstar.dev/mstar/linstrom/storage-new/dbgen"
"github.com/gabriel-vasile/mimetype"
"io"
"os"
"path"
"github.com/minio/minio-go/v7"
"git.mstar.dev/mstar/linstrom/config"
"git.mstar.dev/mstar/linstrom/shared"
"git.mstar.dev/mstar/linstrom/storage-new/models"
)
func (s *Server) AddFile(fileReader io.Reader, filename, userId string) error {
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)
} else {
return s.addFileWithTranscoder(filename, userId, filePath)
}
}
// 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) error {
if mtype == nil {
mType, err := mimetype.DetectFile(filepath)
if err != nil {
return err
}
mtype = other.IntoPointer(mType.String())
}
s3Result, err := s.client.FPutObject(
context.TODO(),
config.GlobalConfig.S3.BucketName,
UsernameFilename(userId, filename),
filepath,
minio.PutObjectOptions{},
)
if err != nil {
return err
}
fileMetadata := models.MediaMetadata{
ID: shared.NewId(),
OwnedById: sql.NullString{Valid: true, String: userId},
Remote: false,
Location: s3Result.Location,
Type: *mtype,
Name: UsernameFilename(userId, filename),
AltText: "",
Blurred: false,
}
err = dbgen.MediaMetadata.Create(&fileMetadata)
if err != nil {
return err
}
return nil
}