/
manikyr.go
386 lines (340 loc) · 9.14 KB
/
manikyr.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
// Package manikyr provides a sensible and filesystem
// structure agnostic image thumbnailing automation.
package manikyr
import (
"errors"
"fmt"
"os"
"path"
"runtime"
"github.com/disintegration/imaging"
"github.com/go-fsnotify/fsnotify"
)
var (
ErrRootNotWatched = errors.New("root is not watched")
ErrRootWatched = errors.New("root is already watched")
NearestNeighbor = imaging.NearestNeighbor
Box = imaging.Box
Linear = imaging.Linear
Hermite = imaging.Hermite
MitchellNetravali = imaging.MitchellNetravali
CatmullRom = imaging.CatmullRom
BSpline = imaging.BSpline
Gaussian = imaging.Gaussian
Bartlett = imaging.Bartlett
Lanczos = imaging.Lanczos
Hann = imaging.Hann
Hamming = imaging.Hamming
Blackman = imaging.Blackman
Welch = imaging.Welch
Cosine = imaging.Cosine
)
type EventType uint32
const (
Error EventType = 1 << iota
ThumbCreate
ThumbRemove
Watch
)
func (t EventType) String() string {
switch t {
case Error:
return "Error"
case ThumbCreate:
return "ThumbCreate"
case ThumbRemove:
return "ThumbRemove"
case Watch:
return "Watch"
default:
return "Unknown"
}
}
// Event represents a single event
// considering watching and thumbnailing files
type Event struct {
Root string
Path string
Type EventType
Error error
}
// String returns a string representation of the event
func (e Event) String() string {
if e.Type == Error {
return fmt.Sprintf("%s: %s @ %s \\%s", e.Type.String(), e.Error.Error(), e.Path, e.Root)
}
return fmt.Sprintf("%s: %s \\%s", e.Type.String(), e.Path, e.Root)
}
type rootWatcher struct {
path string
watcher *fsnotify.Watcher
events chan Event
done chan struct{}
}
// Manikyr watches specified directory roots for changes.
// If a new file matching the rules the user has set is created,
// it will get watched (directory), or thumbnailed (regular file)
// to a dynamic location with the chosen dimensions and algorithm.
// Subdirectory unwatching on deletion is automatic.
type Manikyr struct {
roots []*rootWatcher
thumbDirPerms os.FileMode
thumbWidth int
thumbHeight int
thumbAlgo imaging.ResampleFilter
ThumbDirGetter func(string) string
ThumbNameGetter func(string) string
ShouldCreateThumb func(string, string) bool
ShouldWatchSubdir func(string, string) bool
}
func init() {
// Utilize all CPU cores for performance
runtime.GOMAXPROCS(runtime.NumCPU())
}
func (m *Manikyr) EmitEvent(root string, t EventType, path string, err error) {
for _, rw := range m.roots {
if rw.path == root {
rw.events <-Event{
Root: rw.path,
Type: t,
Path: path,
Error: err,
}
return
}
}
}
// Root returns a list of currently watched root directory paths.
func (m *Manikyr) Roots() []string {
roots := make([]string, len(m.roots))
for i, rw := range m.roots {
roots[i] = rw.path
}
return roots
}
func (m *Manikyr) HasRoot(root string) bool {
for _, rw := range m.roots {
if rw.path == root {
return true
}
}
return false
}
// AddRoot adds and watches specified path as a new root, piping future errors to given channel.
// The error returned considers the watcher creation, not function.
func (m *Manikyr) AddRoot(root string, evtChan chan Event) error {
if m.HasRoot(root) {
return ErrRootWatched
}
w, err := fsnotify.NewWatcher()
if err != nil {
return err
}
doneChan := make(chan struct{})
rw := rootWatcher{
path: root,
events: evtChan,
done: doneChan,
watcher: w,
}
m.roots = append(m.roots, &rw)
go m.watch(&rw)
return rw.watcher.Add(root)
}
// RemoveRoot removes the named root directory path and unwatches it.
// A root should always be unwatched this way prior to actual
// path deletion in the filesystem.
// If the named path was not previously specified to be a root,
// a non-nil error is returned.
func (m *Manikyr) RemoveRoot(root string) error {
if !m.HasRoot(root) {
return ErrRootNotWatched
}
for i, rw := range m.roots {
if rw.path == root {
rw.watcher.Close()
rw.done <- struct{}{}
m.roots = append(m.roots[:i], m.roots[i+1:]...)
break
}
}
return nil
}
func (m *Manikyr) watch(rw *rootWatcher) {
defer rw.watcher.Close()
for {
select {
case evt := <-rw.watcher.Events:
if evt.Op == fsnotify.Create {
// If a file was created
// Get some info about the file
info, err := os.Stat(evt.Name)
if os.IsNotExist(err) {
m.EmitEvent(rw.path, Error, evt.Name, err)
continue
}
switch mode := info.Mode(); {
case mode.IsDir():
if m.ShouldWatchSubdir(rw.path, evt.Name) {
rw.watcher.Add(evt.Name)
}
case mode.IsRegular():
if m.ShouldCreateThumb(rw.path, evt.Name) {
go m.createThumb(rw.path, evt.Name)
}
}
} else {
// Something else happened to the file
_, err := os.Stat(evt.Name)
if os.IsNotExist(err) {
// Try to delete thumb.
m.removeThumb(rw.path, evt.Name)
continue
} else if err != nil {
m.EmitEvent(rw.path, Error, evt.Name, err)
continue
}
}
case err := <-rw.watcher.Errors:
m.EmitEvent(rw.path, Error, "", err)
case <-rw.done:
break
}
}
}
// AddSubdir adds a subdirectory to a root watcher.
// Both paths should be absolute.
func (m *Manikyr) AddSubdir(root, subdir string) {
for _, rw := range m.roots {
if rw.path == root {
err := rw.watcher.Add(subdir)
if err != nil {
m.EmitEvent(root, Error, subdir, err)
return
}
m.EmitEvent(root, Watch, subdir, nil)
return
}
}
m.EmitEvent(root, Error, subdir, ErrRootNotWatched)
}
// RemoveSubdir removes a subdirectory from a root watcher.
// Both paths should be absolute.
func (m *Manikyr) RemoveSubdir(root, subdir string) error {
for _, rw := range m.roots {
if rw.path == root {
return rw.watcher.Remove(subdir)
}
}
return ErrRootNotWatched
}
func (m *Manikyr) removeThumb(root, parentFile string) {
thumbPath := path.Join(m.ThumbDirGetter(parentFile), m.ThumbNameGetter(parentFile))
err := os.Remove(thumbPath)
if os.IsNotExist(err) {
return
} else if err != nil {
m.EmitEvent(root, Error, thumbPath, err)
return
}
m.EmitEvent(root, ThumbRemove, thumbPath, nil)
}
func (m *Manikyr) createThumb(root, parentFile string) {
img, err := openImageWhenReady(parentFile)
if err != nil {
m.EmitEvent(root, Error, parentFile, err)
return
}
localThumbs := m.ThumbDirGetter(parentFile)
_, err = os.Stat(localThumbs)
// If thumbDir does not exist...
if os.IsNotExist(err) {
// ..create it
err := os.Mkdir(localThumbs, m.thumbDirPerms)
if err != nil {
m.EmitEvent(root, Error, localThumbs, err)
return
}
} else if err != nil {
m.EmitEvent(root, Error, localThumbs, err)
return
}
// Save the thumbnail
thumb := imaging.Thumbnail(img, m.thumbWidth, m.thumbHeight, m.thumbAlgo)
thumbPath := path.Join(localThumbs, m.ThumbNameGetter(parentFile))
if err = imaging.Save(thumb, thumbPath); err != nil {
m.EmitEvent(root, Error, thumbPath, err)
return
}
m.EmitEvent(root, ThumbCreate, thumbPath, nil)
}
// Get the currently set thumbnail dimensions
func (m *Manikyr) ThumbSize() (int, int) {
return m.thumbWidth, m.thumbHeight
}
// Set thumbnail dimensions.
// Dimensions should be positive.
func (m *Manikyr) SetThumbSize(w, h int) {
if w < 1 {
w = 1
}
m.thumbWidth = w
if h < 1 {
h = 1
}
m.thumbHeight = h
}
// ThumbDirFileMode gets the currently set filemode for thumbnail directories.
func (m *Manikyr) ThumbDirFileMode() os.FileMode {
return m.thumbDirPerms
}
// SetThumbDirFileMode sets the filemode for thumbnail directories.
func (m *Manikyr) SetThumbDirFileMode(fm uint32) {
m.thumbDirPerms = os.FileMode(fm)
}
// ThumbAlgorithm gets the currently used algorithm for thumbnail creation.
func (m *Manikyr) ThumbAlgorithm() imaging.ResampleFilter {
return m.thumbAlgo
}
// SetThumbAlgorithm sets the used algorithm for thumbnail creation.
// See http://godoc.org/github.com/disintegration/imaging#ResampleFilter for more info.
func (m *Manikyr) SetThumbAlgorithm(filter imaging.ResampleFilter) {
m.thumbAlgo = filter
}
// Init watches and thumbnail existing files as if they
// were added after the root directory got watched.
// Regular files are checked for corresponding thumbnails
// before creating a new one.
func (m *Manikyr) Init(root string) error {
if !m.HasRoot(root) {
return ErrRootNotWatched
}
autoAdd(m, root, root)
return nil
}
// New creates a new Manikyr instance which holds a set of
// preferences and directory roots to apply those rules to.
// Default values should be kept safe, as in not doing
// any damage to the filesystem integrity if the instance is
// initialized as is.
func New() *Manikyr {
return &Manikyr{
roots: []*rootWatcher{},
thumbWidth: 128,
thumbHeight: 128,
thumbAlgo: NearestNeighbor,
thumbDirPerms: 0777,
ThumbDirGetter: func(parentFile string) string {
return os.TempDir()
},
ThumbNameGetter: func(parentFile string) string {
return path.Base(parentFile)
},
ShouldCreateThumb: func(root, parentFile string) bool {
return false
},
ShouldWatchSubdir: func(root, subdir string) bool {
return false
},
}
}