/
sizewise.go
103 lines (85 loc) · 2.28 KB
/
sizewise.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
package sizewise
import (
"bytes"
"fmt"
"time"
"github.com/georgesofianosgr/sizewise/pkg/config"
"github.com/georgesofianosgr/sizewise/pkg/resizer"
"github.com/georgesofianosgr/sizewise/pkg/storage"
"golang.org/x/sync/errgroup"
)
var ErrResizeTimeout = fmt.Errorf("timeout while resizing image")
func ModifyAndCacheImage(config *config.Config, storageKey string, modifier string, path string, onEntryRetrieved func([]byte) error) error {
modifiers, err := resizer.ParseModifiers(modifier)
if err != nil {
return err
}
foundStorage := storage.FindStorage(config.Storages, storageKey)
if foundStorage == nil {
return storage.ErrStorageNotFound
}
pathWithModifier := resizer.ModifiedPath(path, modifiers)
modifiedExists, err := foundStorage.EntryExists(pathWithModifier)
if err != nil {
return err
}
if modifiedExists {
content, err := readImage(foundStorage, pathWithModifier)
if err != nil {
return err
}
err = onEntryRetrieved(content)
if err != nil {
return err
}
return nil
}
// Resize pass content to callback and then write to storage
content, err := resizeImage(foundStorage, path, modifiers)
if err != nil {
return err
}
group := errgroup.Group{}
group.Go(func() error {
return onEntryRetrieved(content)
})
if foundStorage.ShouldCache() {
group.Go(func() error {
return foundStorage.WriteEntry(pathWithModifier, bytes.NewReader(content))
})
}
if err := group.Wait(); err != nil {
return err
}
return nil
}
func readImage(s storage.Storage, path string) ([]byte, error) {
content := bytes.Buffer{}
err := s.ReadEntry(path, &content)
if err != nil {
return nil, err
}
return content.Bytes(), nil
}
func resizeImage(s storage.Storage, originalPath string, modifiers resizer.Modifiers) ([]byte, error) {
content := bytes.Buffer{}
err := s.ReadEntry(originalPath, &content)
if err != nil {
return nil, err
}
resizedFileBuffer := bytes.Buffer{}
errChan := make(chan error, 1)
// Avoid blocking the main thread
go func() {
errChan <- resizer.Resize(&content, &resizedFileBuffer, modifiers.CalculatedWidth, modifiers.CalculatedHeight)
}()
select {
case err := <-errChan:
if err != nil {
return nil, err
}
case <-time.After(10 * time.Second):
return nil, ErrResizeTimeout
}
return resizedFileBuffer.Bytes(), nil
}