1/* 2Copyright 2011 The Perkeep Authors 3 4Licensed under the Apache License, Version 2.0 (the "License"); 5you may not use this file except in compliance with the License. 6You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10Unless required by applicable law or agreed to in writing, software 11distributed under the License is distributed on an "AS IS" BASIS, 12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13See the License for the specific language governing permissions and 14limitations under the License. 15*/ 16 17package server 18 19import ( 20 "io" 21 "io/ioutil" 22 "log" 23 "net/http" 24 25 "go4.org/types" 26 "perkeep.org/internal/httputil" 27 "perkeep.org/pkg/blob" 28 "perkeep.org/pkg/schema" 29) 30 31// uploadHelperResponse is the response from serveUploadHelper. 32type uploadHelperResponse struct { 33 Got []*uploadHelperGotItem `json:"got"` 34} 35 36type uploadHelperGotItem struct { 37 FileName string `json:"filename"` 38 ModTime types.Time3339 `json:"modtime"` 39 FormName string `json:"formname"` 40 FileRef blob.Ref `json:"fileref"` 41} 42 43func (ui *UIHandler) serveUploadHelper(rw http.ResponseWriter, req *http.Request) { 44 ctx := req.Context() 45 if ui.root.Storage == nil { 46 httputil.ServeJSONError(rw, httputil.ServerError("No BlobRoot configured")) 47 return 48 } 49 50 mr, err := req.MultipartReader() 51 if err != nil { 52 httputil.ServeJSONError(rw, httputil.ServerError("reading body: "+err.Error())) 53 return 54 } 55 56 var got []*uploadHelperGotItem 57 var modTime types.Time3339 58 for { 59 part, err := mr.NextPart() 60 if err == io.EOF { 61 break 62 } 63 if err != nil { 64 httputil.ServeJSONError(rw, httputil.ServerError("reading body: "+err.Error())) 65 break 66 } 67 if part.FormName() == "modtime" { 68 payload, err := ioutil.ReadAll(part) 69 if err != nil { 70 log.Printf("ui uploadhelper: unable to read part for modtime: %v", err) 71 continue 72 } 73 modTime = types.ParseTime3339OrZero(string(payload)) 74 continue 75 } 76 fileName := part.FileName() 77 if fileName == "" { 78 continue 79 } 80 br, err := schema.WriteFileFromReaderWithModTime(ctx, ui.root.Storage, fileName, modTime.Time(), part) 81 if err != nil { 82 httputil.ServeJSONError(rw, httputil.ServerError("writing to blobserver: "+err.Error())) 83 return 84 } 85 got = append(got, &uploadHelperGotItem{ 86 FileName: part.FileName(), 87 ModTime: modTime, 88 FormName: part.FormName(), 89 FileRef: br, 90 }) 91 } 92 93 httputil.ReturnJSON(rw, &uploadHelperResponse{Got: got}) 94} 95