-
Notifications
You must be signed in to change notification settings - Fork 13
/
create.go
103 lines (78 loc) · 2.27 KB
/
create.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package file
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"github.com/coretrix/hitrix/pkg/dto/file"
"github.com/coretrix/hitrix/pkg/entity"
"github.com/coretrix/hitrix/pkg/errors"
"github.com/coretrix/hitrix/service"
"github.com/coretrix/hitrix/service/component/oss"
)
func CreateFile(ctx context.Context, newFile *file.RequestDTOUploadImage) (*file.File, error) {
ormService := service.DI().OrmEngineForContext(ctx)
now := service.DI().Clock().Now()
ext := strings.Replace(filepath.Ext(newFile.Image.Filename), ".", "", 1)
tempFile, err := os.CreateTemp("", fmt.Sprintf("*.%s", ext))
clean := func() {
err = os.Remove(tempFile.Name())
if err != nil {
service.DI().ErrorLogger().LogError(fmt.Sprintf("failed deleting temp file %s\nError: %s", tempFile.Name(), err.Error()))
}
}
defer clean()
buf := make([]byte, 1024)
for {
n, err := newFile.Image.File.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
if n == 0 {
break
}
if _, err := tempFile.Write(buf[:n]); err != nil {
panic(err)
}
}
_ = tempFile.Close()
namespace := oss.Namespace(newFile.Namespace.String())
if namespace == "" {
return nil, errors.HandleCustomErrors(map[string]string{"Namespace": "namespace invalid"})
}
obj, err := service.DI().OSService().UploadImageFromFile(ormService, namespace, tempFile.Name())
if err != nil {
return nil, err
}
fileEntity := &entity.FileEntity{
File: &obj,
Namespace: newFile.Namespace.String(),
Status: entity.FileStatusNew.String(),
CreatedAt: service.DI().Clock().Now(),
}
ormService.Flush(fileEntity)
bucketConfig, err := service.DI().OSService().GetNamespaceBucketConfig(namespace)
if err != nil {
panic(err)
}
objectURL := ""
switch bucketConfig.Type {
case oss.BucketPublic:
objectURL, err = service.DI().OSService().GetObjectURL(namespace, fileEntity.File)
case oss.BucketPrivate:
objectURL, err = service.DI().OSService().GetObjectSignedURL(namespace, fileEntity.File, now.Add(30*time.Minute)) // TODO make this time dynamic
}
if err != nil {
panic(err)
}
return &file.File{
ID: fileEntity.ID,
URL: objectURL,
Filename: newFile.Image.Filename,
Namespace: oss.Namespace(fileEntity.Namespace),
IDType: file.IDTypeFileID,
}, nil
}