Skip to content

Commit b84dfb7

Browse files
author
Josh Cave
committed
more bugfixing. helpers werent very effective. b etter to just return bytes
1 parent 33b779f commit b84dfb7

File tree

1 file changed

+76
-45
lines changed

1 file changed

+76
-45
lines changed

fileupload.go

Lines changed: 76 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ import (
2020
"strings"
2121

2222
"github.com/kennygrant/sanitize"
23-
pngquant "github.com/manhtai/gopngquant"
2423
)
2524

2625
func FromRequestToFile(req *http.Request, path string) (string, string, error) {
@@ -103,14 +102,19 @@ func NewProcessingOps() *operations {
103102
return ops
104103
}
105104

106-
func (o *operation) addParam(key string, val interface{}) {
105+
func (o *operation) AddParam(key string, val interface{}) {
107106
if o.Params == nil {
108107
o.Params = make(map[string]interface{})
109108
}
110109
o.Params[key] = val
111110
}
112111

113-
func (o *operations) add(op string) {
112+
func (o *operation) AddFloat(key string, val float64) {
113+
str := strconv.FormatFloat(val, 'f', 6, 64)
114+
o.AddParam(key, str)
115+
}
116+
117+
func (o *operations) Add(op string) {
114118
if o.Ops == nil {
115119
o.Ops = make([]*operation, 0)
116120
}
@@ -119,7 +123,11 @@ func (o *operations) add(op string) {
119123
})
120124
}
121125

122-
func (o *operations) last() *operation {
126+
func (o *operations) OpAt(index int) *operation {
127+
return o.Ops[index]
128+
}
129+
130+
func (o *operations) LastOp() *operation {
123131
return o.Ops[len(o.Ops)-1]
124132
}
125133

@@ -143,7 +151,7 @@ func ProcessedImage(r io.Reader, imageType string, width int, height int, qualit
143151

144152
originalImageType := "jpg"
145153
if convert {
146-
ops.add("convert")
154+
ops.Add("convert")
147155

148156
// converting
149157
if imageType == "jpg" {
@@ -152,15 +160,15 @@ func ProcessedImage(r io.Reader, imageType string, width int, height int, qualit
152160
} else if imageType == "png" {
153161
originalImageType = "jpg"
154162
}
155-
ops.last().addParam("type", imageType)
163+
ops.LastOp().AddParam("type", imageType)
156164
}
157165

158-
ops.add("fit")
159-
ops.last().addParam("width", width) //absolute max
160-
ops.last().addParam("height", height) // dont need its ratio based
161-
ops.last().addParam("stripmeta", true) // dont need its ratio based
162-
ops.last().addParam("quality", quality)
163-
// ops.last().addParam("compression", quality)
166+
ops.Add("fit")
167+
ops.LastOp().AddParam("width", width) //absolute max
168+
ops.LastOp().AddParam("height", height) // dont need its ratio based
169+
ops.LastOp().AddParam("stripmeta", true) // dont need its ratio based
170+
ops.LastOp().AddParam("quality", quality)
171+
// ops.LastOp().AddParam("compression", quality)
164172
bOps, err := json.Marshal(ops.Ops)
165173
if err != nil {
166174
return nil, err
@@ -273,71 +281,77 @@ func NewImageHelper(endpoint string, fs FileSaver) *imageProcessHelper {
273281
}
274282
}
275283

276-
func (ip *imageProcessHelper) GetDimensions(bts io.Reader, ext string) (width int, height int, err error) {
284+
func GetFileExt(filename string) string {
285+
ext := filepath.Ext(strings.ToLower(filename))
286+
return ext
287+
}
288+
289+
func GetImageDimensions(imgData io.Reader, ext string) (width int, height int, err error) {
277290
ext = strings.ToLower(ext)
278291
var imgConfig image.Config
279292
if strings.HasSuffix(ext, "jpeg") || strings.HasSuffix(ext, "jpg") {
280-
imgConfig, err = jpeg.DecodeConfig(bytes.NewBuffer(bts))
293+
imgConfig, err = jpeg.DecodeConfig(imgData)
281294
} else {
282-
imgConfig, err = png.DecodeConfig(bytes.NewBuffer(bts))
295+
imgConfig, err = png.DecodeConfig(imgData)
283296
}
284297
if err != nil {
285298
return -1, -1, fmt.Errorf("failed to get the original image dimensions %v", err)
286299
}
287300
return imgConfig.Width, imgConfig.Width, nil
288301
}
289302

290-
func (ip *imageProcessHelper) ProcessImage(filename string, imgData io.Reader, ops *operations) (byts *bytes.Buffer, fileName string, url string, err error) {
291-
ext := filepath.Ext(filename)
303+
func ProcessImage(filename string, imgData io.Reader, ops *operations) (byts []byte, err error) {
304+
return ProcessImageWithEndpoint(os.Getenv("IMAGE_PROCESSING_ENDPOINT"), filename, imgData, ops)
305+
}
292306

307+
func ProcessImageWithEndpoint(endpoint string, filename string, imgData io.Reader, ops *operations) (b []byte, err error) {
308+
if strings.HasSuffix(endpoint, "/") {
309+
endpoint += "/"
310+
}
311+
ext := filepath.Ext(filename)
293312
bOps, err := json.Marshal(ops.Ops)
294313
if err != nil {
295-
return nil, "", "", fmt.Errorf("json.Marshal %v", err)
314+
return nil, fmt.Errorf("json.Marshal %v", err)
296315
}
297-
endpoint := ip.endpoint + "pipeline?operations=" + u.QueryEscape(string(bOps))
298-
var b bytes.Buffer
299-
mpW := multipart.NewWriter(&b)
316+
endpoint += "pipeline?operations=" + u.QueryEscape(string(bOps))
317+
var buf bytes.Buffer
318+
mpW := multipart.NewWriter(&buf)
300319
fw, err := mpW.CreateFormFile("file", "placeholder."+ext)
301320
if err != nil {
302-
return nil, "", "", fmt.Errorf("mpW.CreateFormFile %v", err)
321+
return nil, fmt.Errorf("mpW.CreateFormFile %v", err)
303322
// ctx.ErrorJSON(http.StatusOK, "couldn't create form file ", err)
304323
}
305324
_, err = io.Copy(fw, imgData)
306325
if err != nil {
307326
// ctx.ErrorJSON(http.StatusOK, "failed to copy from reqFile", err)
308-
return nil, "", "", fmt.Errorf("failed to copy to multipart writer %v", err)
327+
return nil, fmt.Errorf("failed to copy to multipart writer %v", err)
309328
}
310329
err = mpW.Close()
311330
if err != nil {
312-
return nil, "", "", fmt.Errorf("failed to close multipart writer %v", err)
331+
return nil, fmt.Errorf("failed to close multipart writer %v", err)
313332
}
314333

315-
req, err := http.NewRequest("POST", endpoint, &b)
334+
req, err := http.NewRequest("POST", endpoint, &buf)
316335
if err != nil {
317-
return nil, "", "", fmt.Errorf("failed to copy from req %v", err)
336+
return nil, fmt.Errorf("failed to copy from req %v", err)
318337
}
319338
req.Header.Set("Content-Type", mpW.FormDataContentType())
320339

321340
client := &http.Client{}
322341
res, err := client.Do(req)
323342
if err != nil {
324-
return nil, "", "", fmt.Errorf("statuscode %v", err)
343+
return nil, fmt.Errorf("statuscode %v", err)
325344
}
326345
if res.StatusCode != 200 {
327-
return nil, "", "", fmt.Errorf("error status code is: %d", res.StatusCode)
346+
return nil, fmt.Errorf("failed with status code: %d", res.StatusCode)
328347
}
329348
defer res.Body.Close()
330349

331-
if ext == "png" {
332-
cmpressedPNG := make([]byte, 0)
333-
buf := bytes.NewBuffer(cmpressedPNG)
334-
err = pngquant.CompressPng(res.Body, buf, 5)
335-
if err != nil {
336-
return nil, "", "", fmt.Errorf("pngquant.CompressPng %v", err)
337-
}
338-
return ip.fileSaver.SaveFile(filename, buf)
350+
b, err = ioutil.ReadAll(res.Body)
351+
if err != nil {
352+
return nil, fmt.Errorf("failed reading final bytes %v", err)
339353
}
340-
return ip.fileSaver.SaveFile(filename, res.Body)
354+
return b, nil
341355
}
342356

343357
type LocalFileStorage struct {
@@ -346,27 +360,44 @@ type LocalFileStorage struct {
346360
}
347361

348362
func NewLocalFileStorage(attachmentsFolder string, attachmentsFolderBaseURL string) *LocalFileStorage {
363+
if !strings.HasSuffix(attachmentsFolderBaseURL, "/") {
364+
attachmentsFolderBaseURL += "/"
365+
}
349366
return &LocalFileStorage{
350367
attachmentsFolder,
351368
attachmentsFolderBaseURL,
352369
}
353370
}
354371

355-
func (fs *LocalFileStorage) SaveFile(filename string, r io.Reader) (bts *bytes.Buffer, fileName string, url string, err error) {
356-
filename = getValidFileName(fs.AttachmentsFolder, filename)
372+
func (fs *LocalFileStorage) GetURL(filename string) (url string) {
373+
return fs.AttachmentsFolderBaseURL + filename
374+
}
375+
376+
func (fs *LocalFileStorage) OpenFile(filename string) (b []byte, fileName string, url string, err error) {
357377
f, err := os.OpenFile(fs.AttachmentsFolder+filename, os.O_RDWR|os.O_CREATE, 0666)
358378
if err != nil {
359379
return nil, "", "", fmt.Errorf("Failed to create a file on the filesystem: %v", err)
360380
}
361-
defer f.Close()
381+
b, err = ioutil.ReadAll(f)
362382
if err != nil {
383+
return nil, "", "", fmt.Errorf("failed to save the original image: %v", err)
384+
}
385+
return b, filename, fs.GetURL(filename), nil
386+
}
363387

364-
return nil, "", "", fmt.Errorf("failed to get bytes from the original image: %v", err)
388+
func (fs *LocalFileStorage) SaveFile(filename string, r io.Reader) (fileName string, url string, err error) {
389+
filename = getValidFileName(fs.AttachmentsFolder, filename)
390+
f, err := os.OpenFile(fs.AttachmentsFolder+filename, os.O_RDWR|os.O_CREATE, 0666)
391+
if err != nil {
392+
return "", "", fmt.Errorf("Failed to create a file on the filesystem: %v", err)
365393
}
366-
copy := io.TeeReader(r, f)
367-
bts, err = ioutil.ReadAll(copy)
394+
defer f.Close()
368395
if err != nil {
369-
return nil, "", "", fmt.Errorf("failed to save the original image: %v", err)
396+
return "", "", fmt.Errorf("failed to get bytes from the original image: %v", err)
397+
}
398+
_, err = io.Copy(f, r)
399+
if err != nil {
400+
return "", "", fmt.Errorf("failed to save the original image: %v", err)
370401
}
371-
return bytes.NewBuffer(bts), filename, fs.AttachmentsFolderBaseURL + filename, nil
402+
return filename, fs.AttachmentsFolderBaseURL + filename, nil
372403
}

0 commit comments

Comments
 (0)