Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ require (
go.opentelemetry.io/otel v1.37.0 // indirect
go.opentelemetry.io/otel/metric v1.37.0 // indirect
go.opentelemetry.io/otel/trace v1.37.0 // indirect
golang.org/x/image v0.31.0 // indirect
golang.org/x/net v0.43.0 // indirect
golang.org/x/sync v0.17.0 // indirect
golang.org/x/sys v0.36.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
golang.org/x/image v0.31.0 h1:mLChjE2MV6g1S7oqbXC0/UcKijjm5fnJLUYKIYrLESA=
golang.org/x/image v0.31.0/go.mod h1:R9ec5Lcp96v9FTF+ajwaH3uGxPH4fKfHHAVbUILxghA=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
Expand Down
6 changes: 5 additions & 1 deletion metal/cli/seo/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package seo

import (
"net/http"
"path/filepath"
"strings"
"testing"

Expand Down Expand Up @@ -54,14 +55,17 @@ func TestFetchReturnsJSONDecodeError(t *testing.T) {
func TestClientLoadsFixtures(t *testing.T) {
withRepoRoot(t)

spaDir := t.TempDir()
imagesDir := filepath.Join(spaDir, "posts", "images")

e := &env.Environment{
App: env.AppEnvironment{
Name: "SEO Test Fixtures",
URL: "https://seo.example.test",
Type: "local",
MasterKey: strings.Repeat("k", 32),
},
Seo: env.SeoEnvironment{SpaDir: t.TempDir()},
Seo: env.SeoEnvironment{SpaDir: spaDir, SpaImagesDir: imagesDir},
}

routes := router.NewWebsiteRoutes(e)
Expand Down
2 changes: 1 addition & 1 deletion metal/cli/seo/data.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ type TemplateData struct {
}

type TagOgData struct {
Type string `validate:"required,oneof=website"`
Type string `validate:"required,oneof=website article"`
Image string `validate:"required,url"`
ImageAlt string `validate:"required,min=10"`
ImageWidth string `validate:"required"`
Expand Down
1 change: 1 addition & 0 deletions metal/cli/seo/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const WebAboutUrl = "/about"

const WebPostsName = "Posts"
const WebPostsUrl = "/posts"
const WebPostDetailUrl = "/post"

const WebResumeName = "Resume"
const WebResumeUrl = "/resume"
Expand Down
19 changes: 17 additions & 2 deletions metal/cli/seo/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package seo
import (
"bytes"
"embed"
"errors"
"fmt"
"html/template"
"net/url"
Expand Down Expand Up @@ -310,6 +311,10 @@ func (g *Generator) Export(origin string, data TemplateData) error {
return fmt.Errorf("%s: creating directory for %s: %w", fileName, filepath.Dir(out), err)
}

if err = os.Remove(out); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("%s: removing stale export %s: %w", fileName, out, err)
}

cli.Blueln(fmt.Sprintf("Writing file on: %s", out))
if err = os.WriteFile(out, buffer.Bytes(), 0o644); err != nil {
return fmt.Errorf("%s: writing %s: %w", fileName, out, err)
Expand Down Expand Up @@ -439,9 +444,19 @@ func (g *Generator) BuildForPost(post payload.PostResponse, body []template.HTML
imageAlt := g.SanitizeAltText(post.Title, g.Page.SiteName)
description := g.SanitizeMetaDescription(post.Excerpt, Description)
image := g.PreferredImageURL(post.CoverImageURL, g.Page.AboutPhotoUrl)
imageType := "image/png"

if prepared, err := g.preparePostImage(post); err == nil && prepared.URL != "" {
image = prepared.URL
imageType = prepared.Mime
} else if err != nil {
cli.Errorln(fmt.Sprintf("failed to prepare post image for %s: %v", post.Slug, err))
}

return g.buildForPage(post.Title, path, body, func(data *TemplateData) {
data.OGTagOg.Image = image
data.OGTagOg.Type = "article"
data.OGTagOg.ImageType = imageType
data.Twitter.Image = image
data.Description = description
data.OGTagOg.ImageAlt = imageAlt
Expand All @@ -454,10 +469,10 @@ func (g *Generator) CanonicalPostPath(slug string) string {
cleaned = strings.Trim(cleaned, "/")

if cleaned == "" {
return WebPostsUrl
return WebPostDetailUrl
}

return WebPostsUrl + "/" + cleaned
return WebPostDetailUrl + "/" + cleaned
}

func (g *Generator) SanitizeMetaDescription(raw, fallback string) string {
Expand Down
190 changes: 189 additions & 1 deletion metal/cli/seo/generator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,24 @@ package seo
import (
"encoding/json"
"html/template"
"image"
"image/color"
"image/png"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"sync/atomic"
"testing"

"github.com/go-playground/validator/v10"

"github.com/oullin/database"
"github.com/oullin/handler/payload"
"github.com/oullin/metal/env"
"github.com/oullin/pkg/portal"
)

Expand Down Expand Up @@ -68,11 +78,16 @@ func TestGeneratorBuildAndExport(t *testing.T) {
t.Fatalf("unexpected manifest short name: %v", manifest["short_name"])
}

output := filepath.Join(page.OutputDir, "index.seo.html")

if err := os.WriteFile(output, []byte("stale"), 0o444); err != nil {
t.Fatalf("seed stale export: %v", err)
}

if err := gen.Export("index", data); err != nil {
t.Fatalf("export err: %v", err)
}

output := filepath.Join(page.OutputDir, "index.seo.html")
raw, err := os.ReadFile(output)
if err != nil {
t.Fatalf("read output: %v", err)
Expand Down Expand Up @@ -204,3 +219,176 @@ func TestGeneratorGenerateAllPages(t *testing.T) {
t.Fatalf("expected post body content in seo output: %q", postContent)
}
}

func TestGeneratorPreparePostImage(t *testing.T) {
withRepoRoot(t)

outputDir := t.TempDir()
srcDir := t.TempDir()
srcPath := filepath.Join(srcDir, "source.png")

img := image.NewRGBA(image.Rect(0, 0, 300, 300))
for y := 0; y < 300; y++ {
for x := 0; x < 300; x++ {
img.Set(x, y, color.RGBA{R: 200, G: 100, B: 50, A: 255})
}
}

fh, err := os.Create(srcPath)
if err != nil {
t.Fatalf("create source image: %v", err)
}

if err := png.Encode(fh, img); err != nil {
t.Fatalf("encode image: %v", err)
}

if err := fh.Close(); err != nil {
t.Fatalf("close image: %v", err)
}

fileURL := url.URL{Scheme: "file", Path: srcPath}

imagesDir := filepath.Join(outputDir, "posts", "images")

gen := &Generator{
Page: Page{
SiteName: "SEO Test Suite",
SiteURL: "https://seo.example.test",
OutputDir: outputDir,
},
Env: &env.Environment{Seo: env.SeoEnvironment{SpaDir: outputDir, SpaImagesDir: imagesDir}},
}

post := payload.PostResponse{Slug: "awesome-post", CoverImageURL: fileURL.String()}

prepared, err := gen.preparePostImage(post)
if err != nil {
t.Fatalf("prepare post image: %v", err)
}

if prepared.URL == "" {
t.Fatalf("expected prepared image url")
}

expectedSuffix := path.Join("posts", "images", "awesome-post.png")
if !strings.HasSuffix(prepared.URL, expectedSuffix) {
t.Fatalf("unexpected image url: %s", prepared.URL)
}

destPath := filepath.Join(imagesDir, "awesome-post.png")
info, err := os.Stat(destPath)
if err != nil {
t.Fatalf("stat destination image: %v", err)
}

if info.Size() == 0 {
t.Fatalf("expected destination image to have content")
}

fh, err = os.Open(destPath)
if err != nil {
t.Fatalf("open destination image: %v", err)
}
defer fh.Close()

resized, _, err := image.Decode(fh)
if err != nil {
t.Fatalf("decode destination image: %v", err)
}

bounds := resized.Bounds()
if bounds.Dx() != seoImageWidth || bounds.Dy() != seoImageHeight {
t.Fatalf("unexpected resized dimensions: got %dx%d", bounds.Dx(), bounds.Dy())
}

if prepared.Mime != "image/png" {
t.Fatalf("unexpected mime type: %s", prepared.Mime)
}

}

func TestGeneratorPreparePostImageRemote(t *testing.T) {
withRepoRoot(t)

outputDir := t.TempDir()

var requests int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&requests, 1)

img := image.NewRGBA(image.Rect(0, 0, 400, 400))
for y := 0; y < 400; y++ {
for x := 0; x < 400; x++ {
img.Set(x, y, color.RGBA{R: 10, G: 20, B: 30, A: 255})
}
}

if err := png.Encode(w, img); err != nil {
t.Fatalf("encode remote image: %v", err)
}
}))
defer server.Close()

imagesDir := filepath.Join(outputDir, "posts", "images")

gen := &Generator{
Page: Page{
SiteName: "SEO Test Suite",
SiteURL: "https://seo.example.test",
OutputDir: outputDir,
},
Env: &env.Environment{Seo: env.SeoEnvironment{SpaDir: outputDir, SpaImagesDir: imagesDir}},
}

post := payload.PostResponse{Slug: "remote-post", CoverImageURL: server.URL + "/cover.png"}

prepared, err := gen.preparePostImage(post)
if err != nil {
t.Fatalf("prepare post image: %v", err)
}

if prepared.URL == "" {
t.Fatalf("expected prepared image url")
}

expectedSuffix := path.Join("posts", "images", "remote-post.png")
if !strings.HasSuffix(prepared.URL, expectedSuffix) {
t.Fatalf("unexpected image url: %s", prepared.URL)
}

destPath := filepath.Join(imagesDir, "remote-post.png")
info, err := os.Stat(destPath)
if err != nil {
t.Fatalf("stat destination image: %v", err)
}

if info.Size() == 0 {
t.Fatalf("expected destination image to have content")
}

fh, err := os.Open(destPath)
if err != nil {
t.Fatalf("open destination image: %v", err)
}
defer fh.Close()

resized, _, err := image.Decode(fh)
if err != nil {
t.Fatalf("decode destination image: %v", err)
}

bounds := resized.Bounds()
if bounds.Dx() != seoImageWidth || bounds.Dy() != seoImageHeight {
t.Fatalf("unexpected resized dimensions: got %dx%d", bounds.Dx(), bounds.Dy())
}

if prepared.Mime != "image/png" {
t.Fatalf("unexpected mime type: %s", prepared.Mime)
}

if got := atomic.LoadInt32(&requests); got == 0 {
t.Fatalf("expected remote image to be requested at least once")
}

}
Loading
Loading