-
Notifications
You must be signed in to change notification settings - Fork 719
Expand file tree
/
Copy pathmediaserver.go
More file actions
215 lines (171 loc) · 6.05 KB
/
mediaserver.go
File metadata and controls
215 lines (171 loc) · 6.05 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package gateway
import (
"bytes"
"context"
"crypto/sha1"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/42wim/matterbridge/bridge/config"
"github.com/sirupsen/logrus"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
type mediaServer interface {
handleFilesUpload(fi *config.FileInfo) (string, error)
}
type commonMediaServer struct {
logger *logrus.Entry
}
type httpPutMediaServer struct {
commonMediaServer
httpUploadPath string
httpDownloadPrefix string
}
type localMediaServer struct {
commonMediaServer
localPath string
httpDownloadPrefix string
}
type minioMediaServer struct {
commonMediaServer
minio *minio.Client
bucket string
uploadPrefix string
downloadPrefix string
ctx context.Context
}
var _ mediaServer = (*httpPutMediaServer)(nil)
var _ mediaServer = (*localMediaServer)(nil)
var _ mediaServer = (*minioMediaServer)(nil)
func createMediaServer(bg *config.BridgeValues, logger *logrus.Entry) (mediaServer, error) {
if bg.General.MediaServerUpload == "" && bg.General.MediaDownloadPath == "" {
return nil, nil // we don't have a attachfield or we don't have a mediaserver configured return
}
if bg.General.MediaServerUpload != "" {
parsed, err := url.Parse(bg.General.MediaServerUpload)
if err != nil {
return nil, fmt.Errorf("failed parsing mediaServerUpload URL: %w", err)
}
if parsed.Scheme == "http" || parsed.Scheme == "https" {
return &httpPutMediaServer{
commonMediaServer: commonMediaServer{
logger: logger,
},
httpUploadPath: bg.General.MediaServerUpload,
httpDownloadPrefix: bg.General.MediaServerDownload,
}, nil
}
if parsed.Scheme == "minio" {
optionsFromURL := parsed.Query()
secretAccessKey, _ := parsed.User.Password()
pathSplitted := strings.Split(strings.TrimLeft(parsed.Path, "/"), "/")
useSSL, err := strconv.ParseBool(optionsFromURL.Get("useSSL"))
if err != nil {
logger.Warn("error while parsing useSSL boolean, assuming false: ", err)
useSSL = false
}
if len(pathSplitted) == 0 {
return nil, fmt.Errorf("no bucket specified")
}
bucketName := pathSplitted[0]
uploadPrefix := strings.Join(pathSplitted[1:], "/")
ctx := context.Background()
minioClient, err := minio.New(parsed.Host, &minio.Options{
Creds: credentials.NewStaticV4(parsed.User.Username(), secretAccessKey, ""),
Secure: useSSL,
})
if err != nil {
return nil, fmt.Errorf("failed to initialize minio client: %w", err)
}
logger.WithFields(logrus.Fields{
"bucket": bucketName,
"uploadPrefix": uploadPrefix,
}).Debug("configured minio client")
exist, err := minioClient.BucketExists(ctx, bucketName)
if err != nil {
return nil, fmt.Errorf("failed checking if bucket exists: %w", err)
}
if !exist {
return nil, fmt.Errorf("specified bucket does not exists")
}
return &minioMediaServer{
commonMediaServer: commonMediaServer{
logger: logger,
},
ctx: ctx,
minio: minioClient,
bucket: bucketName,
uploadPrefix: uploadPrefix,
downloadPrefix: bg.General.MediaServerDownload,
}, nil
}
return nil, fmt.Errorf("unknown schema (protocol) for mediaServerUpload: '%s'", parsed.Scheme)
}
if bg.General.MediaDownloadPath != "" {
return &localMediaServer{
commonMediaServer: commonMediaServer{
logger: logger,
},
localPath: bg.General.MediaDownloadPath,
httpDownloadPrefix: bg.General.MediaServerDownload,
}, nil
}
return nil, nil // never reached
}
// handleFilesUpload which uses MediaServerUpload configuration to upload the file via HTTP PUT request.
// Returns error on failure.
func (h *httpPutMediaServer) handleFilesUpload(fi *config.FileInfo) (string, error) {
client := &http.Client{
Timeout: time.Second * 5,
}
// Use MediaServerUpload. Upload using a PUT HTTP request and basicauth.
sha1sum := fmt.Sprintf("%x", sha1.Sum(*fi.Data))[:8] //nolint:gosec
url := h.httpUploadPath + "/" + sha1sum + "/" + fi.Name
req, err := http.NewRequest("PUT", url, bytes.NewReader(*fi.Data))
if err != nil {
return "", fmt.Errorf("mediaserver upload failed, could not create request: %#v", err)
}
h.logger.Debugf("mediaserver upload url: %s", url)
req.Header.Set("Content-Type", "binary/octet-stream")
_, err = client.Do(req)
if err != nil {
return "", fmt.Errorf("mediaserver upload failed, could not Do request: %#v", err)
}
return h.httpDownloadPrefix + "/" + sha1sum + "/" + fi.Name, nil
}
// handleFilesUpload which uses MediaServerPath configuration, places the file on the current filesystem.
// Returns error on failure.
func (h *localMediaServer) handleFilesUpload(fi *config.FileInfo) (string, error) {
sha1sum := fmt.Sprintf("%x", sha1.Sum(*fi.Data))[:8] //nolint:gosec
dir := h.localPath + "/" + sha1sum
err := os.Mkdir(dir, os.ModePerm)
if err != nil && !os.IsExist(err) {
return "", fmt.Errorf("mediaserver path failed, could not mkdir: %s %#v", err, err)
}
path := dir + "/" + fi.Name
h.logger.Debugf("mediaserver path placing file: %s", path)
err = ioutil.WriteFile(path, *fi.Data, os.ModePerm)
if err != nil {
return "", fmt.Errorf("mediaserver path failed, could not writefile: %s %#v", err, err)
}
return h.httpDownloadPrefix + "/" + sha1sum + "/" + fi.Name, nil
}
// handleFilesUpload which uploads media to minio compatible server (S3)
// Returns error on failure.
func (h *minioMediaServer) handleFilesUpload(fi *config.FileInfo) (string, error) {
sha1sum := fmt.Sprintf("%x", sha1.Sum(*fi.Data))[:8]
url := h.uploadPrefix + "/" + sha1sum + "/" + fi.Name
objectSize := int64(len(*fi.Data)) // TODO: Using this, since we got this in memory anyway. Would be nicer to use fi.Size, but it is 0
info, err := h.minio.PutObject(h.ctx, h.bucket, url, bytes.NewReader(*fi.Data), objectSize, minio.PutObjectOptions{ContentType: "application/octet-stream"})
if err != nil {
return "", fmt.Errorf("mediaserver putfile failed: %w", err)
}
h.logger.Debugf("successfully uploaded %v, etag: %v", url, info.ETag)
return h.downloadPrefix + url, nil
}