-
Notifications
You must be signed in to change notification settings - Fork 3
/
api.go
265 lines (210 loc) · 5.78 KB
/
api.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package server
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"mime"
"mime/multipart"
"net/http"
"strings"
"github.com/gorilla/mux"
"github.com/knoebber/dotfile/db"
"github.com/knoebber/dotfile/dotfile"
"github.com/knoebber/dotfile/usererror"
"github.com/pkg/errors"
)
// Gathers a file/commits and marshals it into file tracking data.
func handleFileJSON(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
fileData, err := db.FileData(db.Connection, vars["username"], vars["alias"])
if err != nil {
apiError(w, err)
return
}
setJSON(w, fileData)
}
// Sets a list of aliases that username owns to the response body.
func handleFileListJSON(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
username := vars["username"]
addPath := r.URL.Query().Get("path") == "true"
files, err := db.FilesByUsername(db.Connection, username, nil)
if err != nil {
apiError(w, err)
return
}
result := make([]string, len(files))
for i, f := range files {
result[i] = f.Alias
if addPath {
result[i] += " " + f.Path
}
}
setJSON(w, result)
}
func handleRawCompressedCommit(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
commit, err := db.Commit(db.Connection, vars["username"], vars["alias"], vars["hash"])
if err != nil {
rawContentError(w, err)
return
}
_, err = w.Write(commit.Revision)
if err != nil {
rawContentError(w, err)
return
}
return
}
func validateAPIUser(w http.ResponseWriter, r *http.Request) int64 {
username, token, ok := r.BasicAuth()
if !ok {
authError(w, errors.New("basic auth not provided"))
return 0
}
userID, err := db.UserLoginAPI(db.Connection, username, token)
if err != nil {
authError(w, err)
return 0
}
return userID
}
func multipartReader(w http.ResponseWriter, r *http.Request) *multipart.Reader {
mediaType, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
apiError(w, err)
return nil
}
if !strings.HasPrefix(mediaType, "multipart/") {
apiError(w, errors.New("expected multipart content type"))
return nil
}
return multipart.NewReader(r.Body, params["boundary"])
}
func readPushedFileData(p *multipart.Part) (*dotfile.TrackingData, error) {
if p.Header.Get("Content-Type") != "application/json" {
return nil, errors.New("expected json part to be content type application/json")
}
result := new(dotfile.TrackingData)
if err := json.NewDecoder(p).Decode(result); err != nil {
return nil, errors.Wrap(err, "decoding pushed tracked file")
}
if err := p.Close(); err != nil {
return nil, errors.Wrap(err, "closing json part")
}
return result, nil
}
func savePushedRevision(ft *db.FileTransaction, p *multipart.Part, commitMap map[string]*dotfile.Commit) error {
hash := p.FileName()
buff := new(bytes.Buffer)
n, err := buff.ReadFrom(p)
if err != nil {
return errors.Wrapf(err, "reading revision %q from push (%d bytes)", hash, n)
}
if err = p.Close(); err != nil {
return errors.Wrap(err, "closing revision part")
}
c, ok := commitMap[hash]
if !ok {
return fmt.Errorf("pushed revision %q doesn't exist in file data json", hash)
}
if err := ft.SaveCommit(buff, c); err != nil {
return err
}
log.Printf("saved %s (%d bytes)", hash, n)
return nil
}
func push(mr *multipart.Reader, userID int64, alias string) error {
jsonPart, err := mr.NextPart()
if err != nil {
return errors.Wrap(err, "reading json part")
}
fileData, err := readPushedFileData(jsonPart)
if err != nil {
return err
}
tx, err := db.Connection.Begin()
if err != nil {
return errors.Wrap(err, "starting transaction for handle push")
}
ft, err := db.NewFileTransaction(tx, userID, alias)
if err != nil {
return db.Rollback(tx, err)
}
if !ft.FileExists {
if err := ft.SaveFile(userID, alias, fileData.Path); err != nil {
return db.Rollback(tx, err)
}
} else {
if ft.Path != fileData.Path {
return db.Rollback(tx, usererror.Invalid(fmt.Sprintf(
"local path %q does not match remote path %q",
ft.Path, fileData.Path)))
}
}
commitMap := fileData.MapCommits()
for {
revisionPart, err := mr.NextPart()
if err == io.EOF {
break
}
if err != nil {
return db.Rollback(tx, errors.Wrap(err, "reading revision part"))
}
if err = savePushedRevision(ft, revisionPart, commitMap); err != nil {
return db.Rollback(tx, err)
}
}
if err = ft.SetRevision(fileData.Revision); err != nil {
return db.Rollback(tx, err)
}
if err := tx.Commit(); err != nil {
return errors.Wrap(err, "committing handle push transaction")
}
return nil
}
// Request body is expected to be multipart.
// The first part is a JSON encoding of dotfile.TrackingData
// Subsequent parts are new revisions that need to be saved.
// Each revision part should have be named as its hash.
func handlePush(w http.ResponseWriter, r *http.Request) {
var mr *multipart.Reader
userID := validateAPIUser(w, r)
if userID < 1 {
return
}
if mr = multipartReader(w, r); mr == nil {
return
}
if err := push(mr, userID, mux.Vars(r)["alias"]); err != nil {
apiError(w, err)
return
}
}
func setJSON(w http.ResponseWriter, body interface{}) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(body); err != nil {
log.Printf("encoding json body: %s", err)
w.WriteHeader(http.StatusInternalServerError)
}
}
func authError(w http.ResponseWriter, err error) {
log.Printf("api authentication error %s", err)
w.WriteHeader(http.StatusUnauthorized)
}
func apiError(w http.ResponseWriter, err error) {
var usererr *usererror.Error
if db.NotFound(err) {
// Clients expect this when a file doesn't exist.
w.WriteHeader(http.StatusNotFound)
return
}
log.Printf("api error: %s", err)
if errors.As(err, &usererr) {
http.Error(w, usererr.Message, http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusInternalServerError)
}