-
Notifications
You must be signed in to change notification settings - Fork 18
/
optim.go
101 lines (92 loc) · 2.5 KB
/
optim.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
// Copyright 2022 tree xie
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pipeline
import (
"context"
"net/http"
"strings"
"github.com/vicanso/tiny-site/config"
"github.com/vicanso/tiny-site/storage"
"github.com/vicanso/tiny/pb"
"google.golang.org/grpc"
)
var tinyConn = mustNewTinyConnection()
func mustNewTinyConnection() *grpc.ClientConn {
tinyConfig := config.MustGetTinyConfig()
conn, err := grpc.Dial(tinyConfig.Addr, grpc.WithInsecure())
if err != nil {
panic(err)
}
return conn
}
func optim(ctx context.Context, img *storage.Image, quality int, format string) (*storage.Image, error) {
client := pb.NewOptimClient(tinyConn)
in := pb.OptimRequest{
Data: img.Data,
Quality: uint32(quality),
}
switch format {
case ImageTypePNG:
in.Output = pb.Type_PNG
case ImageTypeWEBP:
in.Output = pb.Type_WEBP
case ImageTypeAVIF:
in.Output = pb.Type_AVIF
default:
in.Output = pb.Type_JPEG
}
switch img.Type {
case ImageTypePNG:
in.Source = pb.Type_PNG
case ImageTypeWEBP:
in.Source = pb.Type_WEBP
case ImageTypeAVIF:
in.Output = pb.Type_AVIF
default:
in.Source = pb.Type_JPEG
}
reply, err := client.DoOptim(ctx, &in)
if err != nil {
return nil, err
}
img.Type = format
img.SetData(reply.Data)
return img, nil
}
func NewAutoOptimImage(quality int, header http.Header) ImageJob {
return func(ctx context.Context, img *storage.Image) (*storage.Image, error) {
format := img.Type
accept := header.Get("Accept")
acceptWebp := strings.Contains(accept, "image/webp")
acceptAvif := strings.Contains(accept, "image/avif")
if acceptAvif {
format = ImageTypeAVIF
} else if acceptWebp {
format = ImageTypeWEBP
if format == ImageTypePNG {
quality = 0
}
}
return optim(ctx, img, quality, format)
}
}
func NewOptimImage(quality int, formats ...string) ImageJob {
return func(ctx context.Context, img *storage.Image) (*storage.Image, error) {
format := img.Type
if len(formats) != 0 {
format = formats[0]
}
return optim(ctx, img, quality, format)
}
}