-
Notifications
You must be signed in to change notification settings - Fork 1
/
update_art_thumbnail.go
95 lines (80 loc) · 1.93 KB
/
update_art_thumbnail.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
package updateloop
import (
"bytes"
"context"
"github.com/chai2010/webp"
"github.com/disintegration/imaging"
"github.com/flandiayingman/arkwaifu/internal/app/art"
"github.com/rs/zerolog/log"
"golang.org/x/sync/errgroup"
"image"
"runtime"
"time"
)
func (s *Service) attemptUpdateArtThumbnails(ctx context.Context) {
arts, err := s.artService.SelectArtsWhoseVariantAbsent("thumbnail")
if err != nil {
log.Error().
Err(err).
Caller().
Msg("Failed to select arts.")
}
if len(arts) > 0 {
err := s.updateArtsThumbnail(ctx, arts)
if err != nil {
log.Error().
Err(err).
Caller().
Msg("Failed to update arts thumbnail.")
}
}
}
func (s *Service) updateArtsThumbnail(ctx context.Context, arts []*art.Art) error {
log.Info().Msgf("Begin updating arts thumbnail, using %d goroutines", runtime.NumCPU())
begin := time.Now()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
eg, ctx := errgroup.WithContext(ctx)
eg.SetLimit(runtime.NumCPU())
for _, art := range arts {
art := art
eg.Go(func() error {
return s.updateArtThumbnail(ctx, art)
})
}
err := eg.Wait()
if err != nil {
return err
}
log.Info().Msgf("End updating arts thumbnail, elapsed %v", time.Since(begin))
return nil
}
func (s *Service) updateArtThumbnail(ctx context.Context, a *art.Art) error {
content, err := s.artService.TakeContent(a.ID, art.VariationOrigin)
if err != nil {
return err
}
img, _, err := image.Decode(bytes.NewReader(content))
if err != nil {
return err
}
img = imaging.Fit(img, 360, 360*4, imaging.Lanczos)
buf := bytes.Buffer{}
err = webp.Encode(&buf, img, &webp.Options{
Lossless: false,
Quality: 75,
Exact: false,
})
if err != nil {
return err
}
err = s.artService.UpsertVariants(art.NewVariant(a.ID, art.VariationThumbnail))
if err != nil {
return err
}
err = s.artService.StoreContent(a.ID, art.VariationThumbnail, buf.Bytes())
if err != nil {
return err
}
return nil
}