2024-01-20 21:37:49 +03:00
|
|
|
package service
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-04-29 23:01:24 +03:00
|
|
|
"fmt"
|
2024-01-20 21:37:49 +03:00
|
|
|
"mime/multipart"
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
2024-04-29 23:01:24 +03:00
|
|
|
"github.com/spf13/afero"
|
2024-01-20 21:37:49 +03:00
|
|
|
"gitrepo.ru/neonxp/nquest/pkg/models"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
)
|
|
|
|
|
|
|
|
type File struct {
|
2024-04-29 23:01:24 +03:00
|
|
|
DB *gorm.DB
|
|
|
|
store afero.Fs
|
2024-01-20 21:37:49 +03:00
|
|
|
}
|
|
|
|
|
2024-04-29 23:01:24 +03:00
|
|
|
func NewFile(db *gorm.DB, store afero.Fs) *File {
|
2024-01-20 21:37:49 +03:00
|
|
|
return &File{
|
2024-04-29 23:01:24 +03:00
|
|
|
DB: db,
|
|
|
|
store: store,
|
2024-01-20 21:37:49 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (u *File) Upload(
|
|
|
|
ctx context.Context,
|
|
|
|
filename string,
|
|
|
|
contentType string,
|
|
|
|
size int,
|
2024-04-29 23:01:24 +03:00
|
|
|
questID uuid.UUID,
|
2024-01-20 21:37:49 +03:00
|
|
|
r multipart.File,
|
|
|
|
) (uuid.UUID, error) {
|
2024-04-29 23:01:24 +03:00
|
|
|
defer r.Close()
|
2024-01-20 21:37:49 +03:00
|
|
|
file := &models.File{
|
2024-01-28 22:19:41 +03:00
|
|
|
ID: uuid.New(),
|
2024-01-20 21:37:49 +03:00
|
|
|
Filename: filename,
|
|
|
|
ContentType: contentType,
|
2024-04-29 23:01:24 +03:00
|
|
|
QuestID: questID,
|
2024-01-20 21:37:49 +03:00
|
|
|
Size: size,
|
2024-04-29 23:01:24 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := u.store.MkdirAll(questID.String(), 0755); err != nil {
|
|
|
|
return file.ID, err
|
|
|
|
}
|
|
|
|
|
|
|
|
filePath := fmt.Sprintf("%s/%s", questID.String(), filename)
|
|
|
|
if err := afero.WriteReader(u.store, filePath, r); err != nil {
|
|
|
|
return file.ID, err
|
2024-01-20 21:37:49 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return file.ID, u.DB.WithContext(ctx).Create(file).Error
|
|
|
|
}
|
|
|
|
|
2024-04-29 23:01:24 +03:00
|
|
|
func (u *File) GetFilesByQuest(ctx context.Context, quest uuid.UUID) ([]*models.File, error) {
|
|
|
|
list := make([]*models.File, 0)
|
2024-01-20 21:37:49 +03:00
|
|
|
|
2024-04-29 23:01:24 +03:00
|
|
|
return list, u.DB.WithContext(ctx).Find(&list, `quest_id = ?`, quest.String()).Error
|
2024-01-20 21:37:49 +03:00
|
|
|
}
|