Skip to content

Commit

Permalink
show default cover if no heatmap image is found
Browse files Browse the repository at this point in the history
  • Loading branch information
o-fl0w committed Nov 16, 2023
1 parent 7bc7d5e commit c704758
Showing 1 changed file with 18 additions and 12 deletions.
30 changes: 18 additions & 12 deletions internal/api/heatmap/heatmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package heatmap
import (
"context"
"errors"
"fmt"
"github.com/rs/zerolog/log"
"golang.org/x/image/draw"
"golang.org/x/sync/errgroup"
Expand All @@ -16,6 +15,8 @@ import (
)

var errImageNotFound = errors.New("image not found")
var errScreenshotImageNotFound = errors.New("screenshot image not found")
var errHeatmapImageNotFound = errors.New("heatmap image not found")

func fetchImage(ctx context.Context, fileUrl string) (image.Image, error) {
log.Ctx(ctx).Trace().Str("url", fileUrl).Msg("Fetching image")
Expand All @@ -30,6 +31,7 @@ func fetchImage(ctx context.Context, fileUrl string) (image.Image, error) {
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
log.Ctx(ctx).Debug().Msg("Image not found")
return nil, errImageNotFound
}

Expand All @@ -46,41 +48,45 @@ func buildHeatmapCover(ctx context.Context, coverUrl string, heatmapUrl string)
chCover := make(chan draw.Image, 1)
chHeatmap := make(chan image.Image, 1)

g, gCtx := errgroup.WithContext(ctx)
g, _ := errgroup.WithContext(ctx)

g.Go(func() error {
cover, err := fetchImage(log.Ctx(gCtx).With().Str("image", "cover").Logger().WithContext(gCtx), coverUrl)
defer close(chCover)
cover, err := fetchImage(log.Ctx(ctx).With().Str("image", "cover").Logger().WithContext(ctx), coverUrl)
if err != nil {
return fmt.Errorf("fetch cover: %w", err)
return errors.Join(errScreenshotImageNotFound, err)
}
dest, ok := cover.(draw.Image)
if !ok {
dest = image.NewRGBA(cover.Bounds())
draw.Copy(dest, image.Pt(0, 0), cover, cover.Bounds(), draw.Src, nil)
}
chCover <- dest
close(chCover)
return nil
})

g.Go(func() error {
heatmap, err := fetchImage(log.Ctx(gCtx).With().Str("image", "heatmap").Logger().WithContext(gCtx), heatmapUrl)
defer close(chHeatmap)
heatmap, err := fetchImage(log.Ctx(ctx).With().Str("image", "heatmap").Logger().WithContext(ctx), heatmapUrl)
if err != nil {
return fmt.Errorf("fetch heatmap: %w", err)
return errors.Join(errHeatmapImageNotFound, err)
}
chHeatmap <- heatmap
close(chHeatmap)
return nil
})

cover := <-chCover
heatmap := <-chHeatmap

err := g.Wait()
if err != nil {
return nil, err
if errors.Is(err, errScreenshotImageNotFound) {
return nil, err
} else {
return cover, nil
}
}

cover := <-chCover
heatmap := <-chHeatmap

heatmapCover := overlay(cover, heatmap)
return heatmapCover, nil
}
Expand Down

0 comments on commit c704758

Please sign in to comment.