1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo.git synced 2024-12-28 13:49:13 -05:00
forgejo/modules/card/card.go

324 lines
10 KiB
Go
Raw Normal View History

Add a "summary card" to issues & PRs for consumption by OpenGraph clients (#6053) ## Overview Hi all, I'm a first-time contributor to Forgejo. I was looking for something interesting to contribute and the first thing that caught my attention was https://codeberg.org/forgejo/forgejo/issues/6043, a request for an enhancement to include "issue previews" when publishing links to social media platforms. As a bit of background, the way these platforms work is that they search for meta tags in the posted link's content, and if they find a meta `og:image` (along with other meta tags) they'll pull the image to include in the social media post. Forgejo currently provides an `og:image` tag but it just renders the repository or repository-owner's avatar. This PR will render `og:image` for an issue or PR into a link to `{...}/summary-card`, which is a dynamically generated image that contains a summary of the issue. ## Design Notes ### Rendering / Rasterization The tricky part of solving this problem is rendering an image that combines some text, some images, and some layout elements. To address this, I've created a `card` module which allows for a handful of operations: - Create a new rendered image (a "Card") - Add a margin to a card - Split the card, horizontally or vertically, into two pieces with a proportional layout (eg. 70%/30%, as desired), each of which are "Cards" that render into the same root image - Render text into a card, with line-wrapping and text-alignment capabilities - Render an image onto a card - Fetches an external image as safely as possible (for server-side fetch of Gravatar, etc.) The card module can be reused to create `og:image` summary cards for any object in the future, although obviously it's capabilities are limited. The current implementation is on issues/PRs. I considered a few alternative approaches before taking this approach, and here's why I rejected those options: - Provide the summary card as an SVG object which could be rendered much more easily with a template file -- however, support for SVG isn't defined as positive for OpenGraph, and a quick look through some existing implementations suggest that it is not widely supported, if at all - Rendering as HTML/CSS, or SVG, and then using an external tool to convert into a PNG (or other static) image -- this would be much nicer and easier to implement, but would require tying in some very heavy-weight dependencies - Rendering using a more sophisticated graphics library, eg. cairo -- also would be nicer and easier to implement, but again a heavy dependency for a small functionality As a result of the limited capabilities of the new card module, summary cards don't have icons on them (which would require SVG rasterization) or pretty status badges with colors and rounded rects. In the future if better drawing capabilities were added, the graphics could be improved, but it doesn't seem too important. ### External Avatars In order to rasterize a user's avatar onto the summary card, it might have to be retrieved by the server from the external source (eg. Gravatar). A `fetchExternalImage` routine attempts to do this in the safest way possible to protect the server from any possible security exposure from this; (a) verifying that the content-types are acceptable, (b) ensuring that the file-size and image-size are within the safe bounds that are used for custom avatars, (c) using a very-short timeout to avoid stalling the server if an external dependency is offline. ### Caching Summary cards are cached after rendered. This has the downside of causing updates to statuses, avatars, titles, etc. being stale on the summary card for the cache TTL. However, during testing I found that some social media engines like Mastodon will cause the summary card to be accessed a significant number of times after being referenced by a post, causing a mini-tornado of requests. The cache compensates for this to avoid server load in this situation. ### Scope I'm considering out-of-scope: - Summary cards on other objects (eg. repos, users) can be left for future implementation ## Checklist The [contributor guide](https://forgejo.org/docs/next/contributor/) contains information that will be helpful to first time contributors. There also are a few [conditions for merging Pull Requests in Forgejo repositories](https://codeberg.org/forgejo/governance/src/branch/main/PullRequestsAgreement.md). You are also welcome to join the [Forgejo development chatroom](https://matrix.to/#/#forgejo-development:matrix.org). ### Tests - I added test coverage for Go changes... - [x] in their respective `*_test.go` for unit tests. - [x] in the `tests/integration` directory if it involves interactions with a live Forgejo server. - ~~I added test coverage for JavaScript changes...~~ n/a, no JS changes - [x] ~~in `web_src/js/*.test.js` if it can be unit tested.~~ - [x] ~~in `tests/e2e/*.test.e2e.js` if it requires interactions with a live Forgejo server (see also the [developer guide for JavaScript testing](https://codeberg.org/forgejo/forgejo/src/branch/forgejo/tests/e2e/README.md#end-to-end-tests)).~~ - Manual testing - [x] Access & attach screenshots of both an issue and a pull-request's summary card; see below - [x] Ensure reasonable (non-crash) behavior of rendering text with glyphs outside the font -- correctly rendered as replacement unicode chars - [x] Using a public test instance, verify that og:image behavior looks good on platforms like Mastodon and BlueSky - [x] Bluesky: ✅ - [x] Mastodon: ✅ (Note that the summary card will be requested many times as the post is federated; either each server, or each client, will fetch it itself) - [x] OpenGraph test site (https://www.opengraph.xyz/): ✅ - [x] Discord: Looks OK ✅; needs "twitter:card" to be set to "summary_large_image" to display the large-scale image, but (a) that's probably annoying to use, (b) probably wrong because it doesn't match Twitter Card's spec for a "photographic image", and (c) don't want to encourage/continue use of vendor-specific tag - [x] Verify cases with user avatar missing (or autogen), and repo avatar missing (falls back to repo owner avatar) Pull request summary card: ![image](/attachments/b64283e3-9a3c-4f19-9d00-961662ffe86b) Issue summary card: ![image](/attachments/318ce589-02e0-493e-b10c-5b2cb2627db2) (images to the right are the custom repo avatar, w/ fallback to the repo owner avatar) ### Documentation - [ ] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change. - [x] I did not document these changes and I do not expect someone else to do it. - OpenGraph capabilities are expected to work in the background without user awareness, and so there is no need for documentation to explain the capabilities for users. ### Release notes - [ ] I do not want this change to show in the release notes. - [x] I want the title to show in the release notes with a link to this pull request. - [ ] I want the content of the `release-notes/<pull request number>.md` to be be used for the release notes instead of the title. Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/6053 Reviewed-by: Gusted <gusted@noreply.codeberg.org> Co-authored-by: Mathieu Fenniak <mathieu@fenniak.net> Co-committed-by: Mathieu Fenniak <mathieu@fenniak.net>
2024-11-29 10:02:03 -05:00
// Copyright 2024 The Forgejo Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package card
import (
"bytes"
"image"
"image/color"
"io"
"math"
"net/http"
"strings"
"sync"
"time"
_ "image/gif" // for processing gif images
_ "image/jpeg" // for processing jpeg images
_ "image/png" // for processing png images
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/proxy"
"code.gitea.io/gitea/modules/setting"
"github.com/golang/freetype"
"github.com/golang/freetype/truetype"
"golang.org/x/image/draw"
"golang.org/x/image/font"
"golang.org/x/image/font/gofont/goregular"
_ "golang.org/x/image/webp" // for processing webp images
)
type Card struct {
Img *image.RGBA
Font *truetype.Font
Margin int
}
var fontCache = sync.OnceValues(func() (*truetype.Font, error) {
return truetype.Parse(goregular.TTF)
})
// NewCard creates a new card with the given dimensions in pixels
func NewCard(width, height int) (*Card, error) {
img := image.NewRGBA(image.Rect(0, 0, width, height))
draw.Draw(img, img.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
font, err := fontCache()
if err != nil {
return nil, err
}
return &Card{
Img: img,
Font: font,
Margin: 0,
}, nil
}
// Split splits the card horizontally or vertically by a given percentage; the first card returned has the percentage
// size, and the second card has the remainder. Both cards draw to a subsection of the same image buffer.
func (c *Card) Split(vertical bool, percentage int) (*Card, *Card) {
bounds := c.Img.Bounds()
bounds = image.Rect(bounds.Min.X+c.Margin, bounds.Min.Y+c.Margin, bounds.Max.X-c.Margin, bounds.Max.Y-c.Margin)
if vertical {
mid := (bounds.Dx() * percentage / 100) + bounds.Min.X
subleft := c.Img.SubImage(image.Rect(bounds.Min.X, bounds.Min.Y, mid, bounds.Max.Y)).(*image.RGBA)
subright := c.Img.SubImage(image.Rect(mid, bounds.Min.Y, bounds.Max.X, bounds.Max.Y)).(*image.RGBA)
return &Card{Img: subleft, Font: c.Font},
&Card{Img: subright, Font: c.Font}
}
mid := (bounds.Dy() * percentage / 100) + bounds.Min.Y
subtop := c.Img.SubImage(image.Rect(bounds.Min.X, bounds.Min.Y, bounds.Max.X, mid)).(*image.RGBA)
subbottom := c.Img.SubImage(image.Rect(bounds.Min.X, mid, bounds.Max.X, bounds.Max.Y)).(*image.RGBA)
return &Card{Img: subtop, Font: c.Font},
&Card{Img: subbottom, Font: c.Font}
}
// SetMargin sets the margins for the card
func (c *Card) SetMargin(margin int) {
c.Margin = margin
}
type (
VAlign int64
HAlign int64
)
const (
Top VAlign = iota
Middle
Bottom
)
const (
Left HAlign = iota
Center
Right
)
// DrawText draws text within the card, respecting margins and alignment
func (c *Card) DrawText(text string, textColor color.Color, sizePt float64, valign VAlign, halign HAlign) ([]string, error) {
ft := freetype.NewContext()
ft.SetDPI(72)
ft.SetFont(c.Font)
ft.SetFontSize(sizePt)
ft.SetClip(c.Img.Bounds())
ft.SetDst(c.Img)
ft.SetSrc(image.NewUniform(textColor))
face := truetype.NewFace(c.Font, &truetype.Options{Size: sizePt, DPI: 72})
fontHeight := ft.PointToFixed(sizePt).Ceil()
bounds := c.Img.Bounds()
bounds = image.Rect(bounds.Min.X+c.Margin, bounds.Min.Y+c.Margin, bounds.Max.X-c.Margin, bounds.Max.Y-c.Margin)
boxWidth, boxHeight := bounds.Size().X, bounds.Size().Y
// draw.Draw(c.Img, bounds, image.NewUniform(color.Gray{128}), image.Point{}, draw.Src) // Debug draw box
// Try to apply wrapping to this text; we'll find the most text that will fit into one line, record that line, move
// on. We precalculate each line before drawing so that we can support valign="middle" correctly which requires
// knowing the total height, which is related to how many lines we'll have.
lines := make([]string, 0)
textWords := strings.Split(text, " ")
currentLine := ""
heightTotal := 0
for {
if len(textWords) == 0 {
// Ran out of words.
if currentLine != "" {
heightTotal += fontHeight
lines = append(lines, currentLine)
}
break
}
nextWord := textWords[0]
proposedLine := currentLine
if proposedLine != "" {
proposedLine += " "
}
proposedLine += nextWord
proposedLineWidth := font.MeasureString(face, proposedLine)
if proposedLineWidth.Ceil() > boxWidth {
// no, proposed line is too big; we'll use the last "currentLine"
heightTotal += fontHeight
if currentLine != "" {
lines = append(lines, currentLine)
currentLine = ""
// leave nextWord in textWords and keep going
} else {
// just nextWord by itself doesn't fit on a line; well, we can't skip it, but we'll consume it
// regardless as a line by itself. It will be clipped by the drawing routine.
lines = append(lines, nextWord)
textWords = textWords[1:]
}
} else {
// yes, it will fit
currentLine = proposedLine
textWords = textWords[1:]
}
}
textY := 0
switch valign {
case Top:
textY = fontHeight
case Bottom:
textY = boxHeight - heightTotal + fontHeight
case Middle:
textY = ((boxHeight - heightTotal) / 2) + fontHeight
}
for _, line := range lines {
lineWidth := font.MeasureString(face, line)
textX := 0
switch halign {
case Left:
textX = 0
case Right:
textX = boxWidth - lineWidth.Ceil()
case Center:
textX = (boxWidth - lineWidth.Ceil()) / 2
}
pt := freetype.Pt(bounds.Min.X+textX, bounds.Min.Y+textY)
_, err := ft.DrawString(line, pt)
if err != nil {
return nil, err
}
textY += fontHeight
}
return lines, nil
}
// DrawImage fills the card with an image, scaled to maintain the original aspect ratio and centered with respect to the non-filled dimension
func (c *Card) DrawImage(img image.Image) {
bounds := c.Img.Bounds()
targetRect := image.Rect(bounds.Min.X+c.Margin, bounds.Min.Y+c.Margin, bounds.Max.X-c.Margin, bounds.Max.Y-c.Margin)
srcBounds := img.Bounds()
srcAspect := float64(srcBounds.Dx()) / float64(srcBounds.Dy())
targetAspect := float64(targetRect.Dx()) / float64(targetRect.Dy())
var scale float64
if srcAspect > targetAspect {
// Image is wider than target, scale by width
scale = float64(targetRect.Dx()) / float64(srcBounds.Dx())
} else {
// Image is taller or equal, scale by height
scale = float64(targetRect.Dy()) / float64(srcBounds.Dy())
}
newWidth := int(math.Round(float64(srcBounds.Dx()) * scale))
newHeight := int(math.Round(float64(srcBounds.Dy()) * scale))
// Center the image within the target rectangle
offsetX := (targetRect.Dx() - newWidth) / 2
offsetY := (targetRect.Dy() - newHeight) / 2
scaledRect := image.Rect(targetRect.Min.X+offsetX, targetRect.Min.Y+offsetY, targetRect.Min.X+offsetX+newWidth, targetRect.Min.Y+offsetY+newHeight)
draw.CatmullRom.Scale(c.Img, scaledRect, img, srcBounds, draw.Over, nil)
}
func fallbackImage() image.Image {
// can't usage image.Uniform(color.White) because it's infinitely sized causing a panic in the scaler in DrawImage
img := image.NewRGBA(image.Rect(0, 0, 1, 1))
img.Set(0, 0, color.White)
return img
}
// As defensively as possible, attempt to load an image from a presumed external and untrusted URL
func (c *Card) fetchExternalImage(url string) (image.Image, bool) {
// Use a short timeout; in the event of any failure we'll be logging and returning a placeholder, but we don't want
// this rendering process to be slowed down
client := &http.Client{
Timeout: 1 * time.Second, // 1 second timeout
Transport: &http.Transport{
Proxy: proxy.Proxy(),
},
}
resp, err := client.Get(url)
if err != nil {
log.Warn("error when fetching external image from %s: %w", url, err)
return nil, false
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Warn("non-OK error code when fetching external image from %s: %s", url, resp.Status)
return nil, false
}
contentType := resp.Header.Get("Content-Type")
// Support content types are in-sync with the allowed custom avatar file types
if contentType != "image/png" && contentType != "image/jpeg" && contentType != "image/gif" && contentType != "image/webp" {
log.Warn("fetching external image returned unsupported Content-Type which was ignored: %s", contentType)
return nil, false
}
body := io.LimitReader(resp.Body, setting.Avatar.MaxFileSize)
bodyBytes, err := io.ReadAll(body)
if err != nil {
log.Warn("error when fetching external image from %s: %w", url, err)
return nil, false
}
if int64(len(bodyBytes)) == setting.Avatar.MaxFileSize {
log.Warn("while fetching external image response size hit MaxFileSize (%d) and was discarded from url %s", setting.Avatar.MaxFileSize, url)
return nil, false
}
bodyBuffer := bytes.NewReader(bodyBytes)
imgCfg, imgType, err := image.DecodeConfig(bodyBuffer)
if err != nil {
log.Warn("error when decoding external image from %s: %w", url, err)
return nil, false
}
// Verify that we have a match between actual data understood in the image body and the reported Content-Type
if (contentType == "image/png" && imgType != "png") ||
(contentType == "image/jpeg" && imgType != "jpeg") ||
(contentType == "image/gif" && imgType != "gif") ||
(contentType == "image/webp" && imgType != "webp") {
log.Warn("while fetching external image, mismatched image body (%s) and Content-Type (%s)", imgType, contentType)
return nil, false
}
// do not process image which is too large, it would consume too much memory
if imgCfg.Width > setting.Avatar.MaxWidth {
log.Warn("while fetching external image, width %d exceeds Avatar.MaxWidth %d", imgCfg.Width, setting.Avatar.MaxWidth)
return nil, false
}
if imgCfg.Height > setting.Avatar.MaxHeight {
log.Warn("while fetching external image, height %d exceeds Avatar.MaxHeight %d", imgCfg.Height, setting.Avatar.MaxHeight)
return nil, false
}
_, err = bodyBuffer.Seek(0, io.SeekStart) // reset for actual decode
if err != nil {
log.Warn("error w/ bodyBuffer.Seek")
return nil, false
}
img, _, err := image.Decode(bodyBuffer)
if err != nil {
log.Warn("error when decoding external image from %s: %w", url, err)
return nil, false
}
return img, true
}
func (c *Card) DrawExternalImage(url string) {
image, ok := c.fetchExternalImage(url)
if !ok {
image = fallbackImage()
}
c.DrawImage(image)
}