summaryrefslogtreecommitdiff
path: root/imageprocessor/imageprocessor.go
blob: 905b522219e7419b4899ee87bb23f89e75170f46 (plain)
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
package imageprocessor

import (
	"mandible/uploadedfile"
)

type multiProcessType []ProcessType

func (this multiProcessType) Process(image *uploadedfile.UploadedFile) error {
	for _, processor := range this {
		err := processor.Process(image)
		if err != nil {
			return err
		}
	}

	return nil
}

type asyncProcessType []ProcessType

func (this asyncProcessType) Process(image *uploadedfile.UploadedFile) error {
	errs := make(chan error, len(this))

	for _, processor := range this {
		go func(p ProcessType) {
			errs <- p.Process(image)
		}(processor)
	}

	for i := 0; i < len(this); i++ {
		select {
		case err := <-errs:
			if err != nil {
				return err
			}
		}
	}

	return nil
}

type ProcessType interface {
	Process(image *uploadedfile.UploadedFile) error
}

type ImageProcessor struct {
	processor ProcessType
}

func (this *ImageProcessor) Run(image *uploadedfile.UploadedFile) error {
	return this.processor.Process(image)
}

func Factory(maxFileSize int64, file *uploadedfile.UploadedFile) (*ImageProcessor, error) {
	size, err := file.FileSize()
	if err != nil {
		return &ImageProcessor{}, err
	}

	processor := multiProcessType{}
	processor = append(processor, &ImageOrienter{})

	if size > maxFileSize {
		processor = append(processor, &ImageScaler{maxFileSize})
	}

	async := asyncProcessType{}

	for _, t := range file.GetThumbs() {
		async = append(async, t)
	}

	if len(async) > 0 {
		processor = append(processor, async)
	}

	return &ImageProcessor{processor}, nil
}