-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
218 lines (177 loc) · 4.32 KB
/
main.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
package main
import (
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"net/http"
"os"
"os/user"
"sync"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/gin-gonic/gin"
"github.com/satori/go.uuid"
"github.com/unterstrich-kolkhoz/img-thumbnailer/config"
"gopkg.in/gographics/imagick.v3/imagick"
)
var resizeMutex sync.Mutex
func resize(src string, format string, w int, h int, compression uint) (string, error) {
resizeMutex.Lock()
defer resizeMutex.Unlock()
if w == 0 && h == 0 {
return "", errors.New("width and height of image cannot both be unset")
}
imagick.Initialize()
defer imagick.Terminate()
mw := imagick.NewMagickWand()
defer mw.Destroy()
err := mw.ReadImage(src)
if err != nil {
return "", err
}
fw := float64(w)
fh := float64(h)
ow := float64(mw.GetImageWidth())
oh := float64(mw.GetImageHeight())
if w == 0 {
scaling := fh / oh
w = int(math.Floor(scaling*ow + 0.5))
} else if h == 0 {
scaling := fw / ow
h = int(math.Floor(scaling*oh + 0.5))
} else if ow/oh > fw/fh {
scaling := fh / oh
nw := math.Floor(fw/scaling + 0.5)
dw := int(ow - nw)
if dw >= 1 {
mw.CropImage(uint(nw), uint(oh), int(dw)/2, 0)
}
}
err = mw.ResizeImage(uint(w), uint(h), imagick.FILTER_LANCZOS)
if err != nil {
return "", err
}
err = mw.SetImageFormat(format)
if err != nil {
return "", err
}
err = mw.SetImageCompressionQuality(compression)
if err != nil {
return "", err
}
f, err := ioutil.TempFile("", "thumbnailer")
if err != nil {
return "", err
}
defer f.Close()
err = mw.WriteImageFile(f)
if err != nil {
return "", err
}
return f.Name(), nil
}
func getFile(url string) (string, error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
if code := resp.StatusCode; code != 200 {
err = errors.New(fmt.Sprintf("Error getting the file '%s': HTTP %d",
url, code))
return "", err
}
f, err := ioutil.TempFile("", "thumbnailer")
if err != nil {
return "", err
}
defer f.Close()
if _, err := io.Copy(f, resp.Body); err != nil {
return "", err
}
return f.Name(), nil
}
func upload(bucket string, region string, path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", errors.New(fmt.Sprintf("Unable to open file: %v", err))
}
defer file.Close()
usr, err := user.Current()
if err != nil {
return "", err
}
dir := usr.HomeDir
name, err := uuid.NewV4()
if err != nil {
return "", err
}
sess, err := session.NewSession(&aws.Config{
Region: aws.String(region),
Credentials: credentials.NewSharedCredentials(dir+"/.aws/credentials", "thumbnailer"),
})
if err != nil {
return "", err
}
uploader := s3manager.NewUploader(sess)
info, err := uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String(bucket),
Key: aws.String(name.String()),
Body: file,
})
if err != nil {
return "", err
}
return info.Location, nil
}
type Body struct {
Width int `json:"width"`
Height int `json:"height"`
Compression uint `json:"compression" binding:"required"`
Format string `json:"format" binding:"required"`
Url string `json:"url" binding:"required"`
}
func handleResize(bucket string, region string) func(c *gin.Context) {
return func(c *gin.Context) {
var body Body
if err := c.ShouldBindJSON(&body); err != nil {
c.String(http.StatusBadRequest, "Invalid body: ", err.Error())
return
}
fname, err := getFile(body.Url)
if err != nil {
c.String(http.StatusBadRequest, err.Error())
return
}
path, err := resize(fname, body.Format, body.Width, body.Height,
body.Compression)
if err != nil {
c.String(http.StatusBadRequest, err.Error())
return
}
url, err := upload(bucket, region, path)
if err != nil {
log.Println(err.Error())
c.String(http.StatusBadRequest, err.Error())
return
}
c.JSON(http.StatusOK, gin.H{"url": url})
}
}
func main() {
configfile := flag.String("config", "./etc/img-thumbnailer/server.conf", "Configuration file location")
flag.Parse()
conf, err := config.ReadConfig(*configfile)
if err != nil {
log.Fatal("Loading configuration failed: ", err)
}
r := gin.Default()
r.POST("/", handleResize(conf.Bucket, conf.Region))
r.Run(conf.Port)
}