-
Notifications
You must be signed in to change notification settings - Fork 0
/
hdl_files.go
210 lines (181 loc) · 5.72 KB
/
hdl_files.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
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
/******************************************************************************
*
* Description :
*
* Handler of large file uploads/downloads. Validates request first then calls
* a handler.
*
*****************************************************************************/
package main
import (
"encoding/json"
"errors"
"io"
"log"
"net/http"
"strings"
"time"
"github.com/tinode/chat/server/store"
"github.com/tinode/chat/server/store/types"
)
func largeFileServe(wrt http.ResponseWriter, req *http.Request) {
now := types.TimeNow()
enc := json.NewEncoder(wrt)
mh := store.GetMediaHandler()
writeHttpResponse := func(msg *ServerComMessage, err error) {
// Gorilla CompressHandler requires Content-Type to be set.
wrt.Header().Set("Content-Type", "application/json; charset=utf-8")
wrt.WriteHeader(msg.Ctrl.Code)
enc.Encode(msg)
if err != nil {
log.Println("media serve", err)
}
}
// Check for API key presence
if isValid, _ := checkAPIKey(getAPIKey(req)); !isValid {
writeHttpResponse(ErrAPIKeyRequired(now), nil)
return
}
// Check authorization: either auth information or SID must be present
uid, challenge, err := authHttpRequest(req)
if err != nil {
writeHttpResponse(decodeStoreError(err, "", "", now, nil), err)
return
}
if challenge != nil {
writeHttpResponse(InfoChallenge("", now, challenge), nil)
return
}
if uid.IsZero() {
// Not authenticated
writeHttpResponse(ErrAuthRequired("", "", now), nil)
return
}
// Check if media handler requests redirection to another service.
if redirTo, err := mh.Redirect(req.Method, req.URL.String()); redirTo != "" {
wrt.Header().Set("Location", redirTo)
wrt.Header().Set("Content-Type", "application/json; charset=utf-8")
wrt.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
wrt.WriteHeader(http.StatusTemporaryRedirect)
enc.Encode(InfoFound("", "", now))
log.Println("media serve redirected", redirTo)
return
} else if err != nil {
writeHttpResponse(decodeStoreError(err, "", "", now, nil), err)
return
}
fd, rsc, err := mh.Download(req.URL.String())
if err != nil {
writeHttpResponse(decodeStoreError(err, "", "", now, nil), err)
return
}
defer rsc.Close()
wrt.Header().Set("Content-Type", fd.MimeType)
wrt.Header().Set("Content-Disposition", "attachment")
http.ServeContent(wrt, req, "", fd.UpdatedAt, rsc)
log.Println("media served OK")
}
// largeFileUpload receives files from client over HTTP(S) and saves them to local file
// system.
func largeFileUpload(wrt http.ResponseWriter, req *http.Request) {
log.Println("Upload request", req.RequestURI)
now := types.TimeNow()
enc := json.NewEncoder(wrt)
mh := store.GetMediaHandler()
writeHttpResponse := func(msg *ServerComMessage, err error) {
// Gorilla CompressHandler requires Content-Type to be set.
wrt.Header().Set("Content-Type", "application/json; charset=utf-8")
wrt.WriteHeader(msg.Ctrl.Code)
enc.Encode(msg)
log.Println("media upload:", msg.Ctrl.Code, msg.Ctrl.Text, "/", err)
}
// Check if this is a POST or a PUT request.
if req.Method != http.MethodPost && req.Method != http.MethodPut {
writeHttpResponse(ErrOperationNotAllowed("", "", now), errors.New("method '"+req.Method+"' not allowed"))
return
}
if globals.maxFileUploadSize > 0 {
// Enforce maximum upload size.
req.Body = http.MaxBytesReader(wrt, req.Body, globals.maxFileUploadSize)
}
// Check for API key presence
if isValid, _ := checkAPIKey(getAPIKey(req)); !isValid {
writeHttpResponse(ErrAPIKeyRequired(now), nil)
return
}
msgID := req.FormValue("id")
// Check authorization: either auth information or SID must be present
uid, challenge, err := authHttpRequest(req)
if err != nil {
writeHttpResponse(decodeStoreError(err, msgID, "", now, nil), err)
return
}
if challenge != nil {
writeHttpResponse(InfoChallenge(msgID, now, challenge), nil)
return
}
if uid.IsZero() {
// Not authenticated
writeHttpResponse(ErrAuthRequired(msgID, "", now), nil)
return
}
// Check if uploads are handled elsewhere.
if redirTo, err := mh.Redirect(req.Method, req.URL.String()); redirTo != "" {
wrt.Header().Set("Location", redirTo)
wrt.Header().Set("Content-Type", "application/json; charset=utf-8")
wrt.WriteHeader(http.StatusTemporaryRedirect)
enc.Encode(InfoFound("", "", now))
log.Println("media upload redirected", redirTo)
return
} else if err != nil {
writeHttpResponse(decodeStoreError(err, "", "", now, nil), err)
return
}
file, _, err := req.FormFile("file")
if err != nil {
if strings.Contains(err.Error(), "request body too large") {
writeHttpResponse(ErrTooLarge(msgID, "", now), err)
} else {
writeHttpResponse(ErrMalformed(msgID, "", now), err)
}
return
}
fdef := types.FileDef{}
fdef.Id = store.GetUidString()
fdef.InitTimes()
fdef.User = uid.String()
buff := make([]byte, 512)
if _, err = file.Read(buff); err != nil {
writeHttpResponse(ErrUnknown(msgID, "", now), err)
return
}
fdef.MimeType = http.DetectContentType(buff)
if _, err = file.Seek(0, io.SeekStart); err != nil {
writeHttpResponse(ErrUnknown(msgID, "", now), err)
return
}
url, err := mh.Upload(&fdef, file)
if err != nil {
writeHttpResponse(decodeStoreError(err, msgID, "", now, nil), err)
return
}
writeHttpResponse(NoErrParams(msgID, "", now, map[string]string{"url": url}), nil)
}
func largeFileRunGarbageCollection(period time.Duration, block int) chan<- bool {
// Unbuffered stop channel. Whoever stops it must wait for the process to finish.
stop := make(chan bool)
go func() {
gcTimer := time.Tick(period)
for {
select {
case <-gcTimer:
if err := store.Files.DeleteUnused(time.Now().Add(-time.Hour), block); err != nil {
log.Println("media gc:", err)
}
case <-stop:
return
}
}
}()
return stop
}