forked from asm-products/firesize
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimagick.go
More file actions
210 lines (179 loc) · 4.57 KB
/
imagick.go
File metadata and controls
210 lines (179 loc) · 4.57 KB
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
package models
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/technoweenie/grohl"
)
type IMagick struct{}
type processPipelineStep func(workingDirectoryPath string, inputFilePath string, args *ProcessArgs) (outputFilePath string, err error)
var defaultPipeline = []processPipelineStep{
downloadRemote,
preProcessImage,
processImage,
}
// Process a remote asset url using graphicsmagick with the args supplied
// and write the response to w
func (p *IMagick) Process(w http.ResponseWriter, r *http.Request, args *ProcessArgs) (err error) {
tempDir, err := createTemporaryWorkspace()
if err != nil {
return
}
// defer os.RemoveAll(tempDir)
var filePath string
// No operations? Just proxy the request
if !args.HasOperations() {
return proxyRequest(w, args)
}
for _, step := range defaultPipeline {
filePath, err = step(tempDir, filePath, args)
if err != nil {
return
}
}
// serve response
http.ServeFile(w, r, filePath)
return
}
func createTemporaryWorkspace() (string, error) {
return ioutil.TempDir("", "_firesize")
}
func proxyRequest(w http.ResponseWriter, args *ProcessArgs) error {
resp, err := http.Get(args.Url)
if err != nil {
return err
}
defer resp.Body.Close()
_, err = io.Copy(w, resp.Body)
return err
}
func downloadRemote(tempDir string, _ string, args *ProcessArgs) (string, error) {
url := args.Url
inFile := filepath.Join(tempDir, "in")
grohl.Log(grohl.Data{
"processor": "imagick",
"download": url,
"local": inFile,
})
out, err := os.Create(inFile)
if err != nil {
return inFile, err
}
defer out.Close()
resp, err := http.Get(url)
if err != nil {
return inFile, err
}
defer resp.Body.Close()
_, err = io.Copy(out, resp.Body)
return inFile, err
}
func preProcessImage(tempDir string, inFile string, args *ProcessArgs) (string, error) {
if isAnimatedGif(inFile) {
args.Format = "gif" // Total hack cos format is incorrectly .png on example
return coalesceAnimatedGif(tempDir, inFile)
} else {
return inFile, nil
}
}
func processImage(tempDir string, inFile string, args *ProcessArgs) (string, error) {
outFile := filepath.Join(tempDir, "out")
cmdArgs, outFileWithFormat := args.CommandArgs(inFile, outFile)
grohl.Log(grohl.Data{
"processor": "imagick",
"args": cmdArgs,
})
executable := "convert"
cmd := exec.Command(executable, cmdArgs...)
var outErr bytes.Buffer
cmd.Stdout, cmd.Stderr = &outErr, &outErr
err := runWithTimeout(cmd, 60*time.Second)
if err != nil {
grohl.Log(grohl.Data{
"processor": "imagick",
"step": "convert",
"failure": err,
"args": cmdArgs,
"output": string(outErr.Bytes()),
})
}
return outFileWithFormat, err
}
func isAnimatedGif(inFile string) bool {
// identify -format %n updates-product-click.gif # => 105
cmd := exec.Command("identify", "-format", "%n", inFile)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := runWithTimeout(cmd, 10*time.Second)
if err != nil {
output := string(stderr.Bytes())
grohl.Log(grohl.Data{
"processor": "imagick",
"step": "identify",
"failure": err,
"output": output,
})
} else {
output := string(stdout.Bytes())
output = strings.TrimSpace(output)
numFrames, err := strconv.Atoi(output)
if err != nil {
grohl.Log(grohl.Data{
"processor": "imagick",
"step": "identify",
"failure": err,
"output": output,
"message": "non numeric identify output",
})
} else {
grohl.Log(grohl.Data{
"processor": "imagick",
"step": "identify",
"num-frames": numFrames,
})
return numFrames > 1
}
}
// if anything fucks out assume not animated
return false
}
func coalesceAnimatedGif(tempDir string, inFile string) (string, error) {
outFile := filepath.Join(tempDir, "temp")
// convert do.gif -coalesce temporary.gif
cmd := exec.Command("convert", inFile, "-coalesce", outFile)
var outErr bytes.Buffer
cmd.Stdout, cmd.Stderr = &outErr, &outErr
err := runWithTimeout(cmd, 60*time.Second)
if err != nil {
grohl.Log(grohl.Data{
"processor": "imagick",
"step": "coalesce",
"failure": err,
"output": string(outErr.Bytes()),
})
}
return outFile, err
}
func runWithTimeout(cmd *exec.Cmd, timeout time.Duration) error {
// Start the process
err := cmd.Start()
if err != nil {
return err
}
// Kill the process if it doesn't exit in time
defer time.AfterFunc(timeout, func() {
fmt.Println("command timed out")
cmd.Process.Kill()
}).Stop()
// Wait for the process to finish
return cmd.Wait()
}