-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
183 lines (161 loc) · 4.83 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
package main
import (
"context"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"cloud.google.com/go/firestore"
"cloud.google.com/go/storage"
"github.com/raymonstah/asianamericanswiki/functions/api"
"github.com/raymonstah/asianamericanswiki/internal/humandao"
"github.com/urfave/cli/v2"
)
var opts struct {
Image string
Name string
Webp bool
Dry bool
}
func main() {
app := &cli.App{
Name: "A CLI tool to upload an image.",
Flags: []cli.Flag{
&cli.PathFlag{Name: "image", Destination: &opts.Image},
&cli.StringFlag{Name: "name", Required: true, Destination: &opts.Name},
&cli.BoolFlag{Name: "webp", Destination: &opts.Webp},
&cli.BoolFlag{Name: "dry", Destination: &opts.Dry},
},
Action: run,
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
type Handler struct {
storageClient *storage.Client
fsClient *firestore.Client
humanDAO *humandao.DAO
}
func run(c *cli.Context) error {
ctx := c.Context
fsClient, err := firestore.NewClient(ctx, api.ProjectID)
if err != nil {
return fmt.Errorf("unable to create firestore client: %w", err)
}
client, err := storage.NewClient(ctx)
if err != nil {
return fmt.Errorf("unable to create storage client: %w", err)
}
humanDAO := humandao.NewDAO(fsClient)
h := Handler{
fsClient: fsClient,
storageClient: client,
humanDAO: humanDAO,
}
if err := h.Do(ctx); err != nil {
return err
}
return nil
}
func (h *Handler) Do(ctx context.Context) error {
path := strings.ToLower(opts.Name)
path = strings.ReplaceAll(path, " ", "-")
human, err := h.humanDAO.Human(ctx, humandao.HumanInput{Path: path})
if err != nil {
return fmt.Errorf("unable to get human: %w", err)
}
id := human.ID
pathToImage := opts.Image
if opts.Webp {
tempDir, err := os.MkdirTemp(os.TempDir(), "webp")
if err != nil {
return fmt.Errorf("unable to create temp dir: %w", err)
}
// no image provided, use the image from Cloud Storage
if pathToImage == "" {
cloudStoragePath := filepath.Base(human.FeaturedImage)
fmt.Println("cloudStoragePath:", cloudStoragePath)
object := h.storageClient.Bucket(api.ImagesStorageBucket).Object(cloudStoragePath)
reader, err := object.NewReader(ctx)
if err != nil {
return fmt.Errorf("unable to read image from cloud storage path %v: %w", cloudStoragePath, err)
}
parts := strings.Split(cloudStoragePath, ".")
extension := ""
if len(parts) == 1 {
attrs, err := object.Attrs(ctx)
if err != nil {
return fmt.Errorf("unable to get image attrs: %w", err)
}
if strings.Contains(attrs.ContentType, "jpeg") {
extension = ".jpeg"
} else if strings.Contains(attrs.ContentType, "png") {
extension = ".png"
} else {
return fmt.Errorf("unsupported file type: %v", attrs.ContentType)
}
}
pathToImage = filepath.Join(tempDir, cloudStoragePath+extension)
dest, err := os.Create(pathToImage)
if err != nil {
return fmt.Errorf("unable to write image from cloud storage: %w", err)
}
fmt.Println("wrote image from cloud storage to temp dir", pathToImage)
if _, err := io.Copy(dest, reader); err != nil {
return fmt.Errorf("unable to copy image from cloud storage: %w", err)
}
defer func() {
if len(parts) == 1 {
fmt.Println("overwrite happened -- skipping delete")
return
}
fmt.Printf("deleting old image %v", cloudStoragePath)
if err := object.Delete(ctx); err != nil {
log.Default().Panic("error deleting image", err)
}
}()
}
fileName := filepath.Base(pathToImage)
fileNameParts := strings.Split(fileName, ".")
fileNameWithoutExtension := fileNameParts[0]
webpImage := fileNameWithoutExtension + ".webp"
sourceImagePath := filepath.Join(tempDir, fileName)
pathToWebp := filepath.Join(tempDir, webpImage)
args := []string{"-path", tempDir, "-format", "webp", "-quality", "10", sourceImagePath}
cmd := exec.Command("mogrify", args...)
if err := cmd.Run(); err != nil {
fmt.Printf("mogrify %v\n", strings.Join(args, " "))
return fmt.Errorf("unable to convert image to webp: %w", err)
}
fmt.Printf("wrote webp image to %v\n", pathToWebp)
pathToImage = pathToWebp
}
raw, err := os.ReadFile(pathToImage)
if err != nil {
return err
}
if opts.Dry {
fmt.Println("dry mode detected -- exiting.")
return nil
}
imgName := fmt.Sprintf("%v", id)
obj := h.storageClient.Bucket(api.ImagesStorageBucket).Object(imgName)
writer := obj.NewWriter(ctx)
if _, err := writer.Write(raw); err != nil {
return err
}
if err := writer.Close(); err != nil {
return err
}
featuredImageURL := fmt.Sprintf("https://storage.googleapis.com/%v/%v", api.ImagesStorageBucket, imgName)
human.FeaturedImage = featuredImageURL
if err := h.humanDAO.UpdateHuman(ctx, human); err != nil {
return fmt.Errorf("unable to update human: %w", err)
}
log.Println("done: ", featuredImageURL)
return nil
}