2024-02-04 10:40:20 +00:00
|
|
|
package services
|
|
|
|
|
|
|
|
import (
|
2024-03-10 10:38:42 +00:00
|
|
|
"mime/multipart"
|
|
|
|
"net/http"
|
2024-03-24 10:31:36 +00:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2024-03-10 10:38:42 +00:00
|
|
|
"strings"
|
|
|
|
|
2024-03-20 12:57:21 +00:00
|
|
|
"git.solsynth.dev/hydrogen/interactive/pkg/database"
|
|
|
|
"git.solsynth.dev/hydrogen/interactive/pkg/models"
|
2024-02-04 10:40:20 +00:00
|
|
|
"github.com/google/uuid"
|
2024-03-24 10:31:36 +00:00
|
|
|
"github.com/spf13/viper"
|
2024-02-04 10:40:20 +00:00
|
|
|
)
|
|
|
|
|
2024-03-24 10:31:36 +00:00
|
|
|
func GetAttachmentByUUID(fileId string) (models.Attachment, error) {
|
|
|
|
var attachment models.Attachment
|
|
|
|
if err := database.C.Where(models.Attachment{
|
|
|
|
FileID: fileId,
|
|
|
|
}).First(&attachment).Error; err != nil {
|
|
|
|
return attachment, err
|
|
|
|
}
|
|
|
|
return attachment, nil
|
|
|
|
}
|
|
|
|
|
2024-02-04 10:40:20 +00:00
|
|
|
func NewAttachment(user models.Account, header *multipart.FileHeader) (models.Attachment, error) {
|
|
|
|
attachment := models.Attachment{
|
|
|
|
FileID: uuid.NewString(),
|
|
|
|
Filesize: header.Size,
|
|
|
|
Filename: header.Filename,
|
|
|
|
Mimetype: "unknown/unknown",
|
2024-03-02 17:23:11 +00:00
|
|
|
Type: models.AttachmentOthers,
|
2024-02-04 10:40:20 +00:00
|
|
|
AuthorID: user.ID,
|
|
|
|
}
|
|
|
|
|
|
|
|
// Open file
|
|
|
|
file, err := header.Open()
|
|
|
|
if err != nil {
|
|
|
|
return attachment, err
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
// Detect mimetype
|
|
|
|
fileHeader := make([]byte, 512)
|
|
|
|
_, err = file.Read(fileHeader)
|
|
|
|
if err != nil {
|
|
|
|
return attachment, err
|
|
|
|
}
|
|
|
|
attachment.Mimetype = http.DetectContentType(fileHeader)
|
|
|
|
|
2024-03-10 10:38:42 +00:00
|
|
|
switch strings.Split(attachment.Mimetype, "/")[0] {
|
|
|
|
case "image":
|
|
|
|
attachment.Type = models.AttachmentPhoto
|
|
|
|
case "video":
|
|
|
|
attachment.Type = models.AttachmentVideo
|
|
|
|
case "audio":
|
|
|
|
attachment.Type = models.AttachmentAudio
|
|
|
|
default:
|
|
|
|
attachment.Type = models.AttachmentOthers
|
|
|
|
}
|
|
|
|
|
2024-02-04 10:40:20 +00:00
|
|
|
// Save into database
|
|
|
|
err = database.C.Save(&attachment).Error
|
|
|
|
|
|
|
|
return attachment, err
|
|
|
|
}
|
2024-03-24 10:31:36 +00:00
|
|
|
|
|
|
|
func DeleteAttachment(item models.Attachment) error {
|
|
|
|
if err := database.C.Delete(&item).Error; err != nil {
|
|
|
|
return err
|
|
|
|
} else {
|
|
|
|
basepath := viper.GetString("content")
|
|
|
|
fullpath := filepath.Join(basepath, item.FileID)
|
|
|
|
|
|
|
|
os.Remove(fullpath)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|