This repository has been archived by the owner on Aug 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
opengraph.go
60 lines (54 loc) · 1.98 KB
/
opengraph.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
package main
import (
"context"
"fmt"
"github.com/bouncepaw/mycomarkup/generator"
"regexp"
"strings"
"github.com/bouncepaw/mycomarkup/blocks"
"github.com/bouncepaw/mycomarkup/util"
)
// Used to clear opengraph description from html tags. This method is usually bad because of dangers of malformed HTML, but I'm going to use it only for Mycorrhiza-generated HTML, so it's okay. The question mark is required; without it the whole string is eaten away.
var htmlTagRe = regexp.MustCompile(`<.*?>`)
// OpenGraphHTML returns an html representation of og: meta tags.
func OpenGraphHTML(ctx context.Context, ast []interface{}) string {
ogImage, ogDescription := openGraphImageAndDescription(ast)
return strings.Join([]string{
ogTag("title", util.BeautifulName(util.HyphaNameFrom(ctx))),
ogTag("type", "article"),
ogTag("image", ogImage),
// TODO: there should be a full URL ⤵︎. Requires a different API for the lib.
ogTag("url", "/hypha/"+util.BeautifulName(util.HyphaNameFrom(ctx))),
ogTag("determiner", ""),
ogTag("description", ogDescription),
}, "\n")
}
// return image and description of the document for including in open graph.
func openGraphImageAndDescription(ast []interface{}) (ogImage, ogDescription string) {
// TODO: there should be a full URL ⤵︎
ogImage = "/favicon.ico"
foundDesc := false
foundImg := false
for _, block := range ast {
switch v := block.(type) {
case blocks.Paragraph:
if !foundDesc {
ogDescription = strings.TrimSpace(htmlTagRe.ReplaceAllString(generator.BlockToHTML(v), ""))
foundDesc = true
}
case blocks.Img:
if !foundImg && len(v.Entries) > 0 {
ogImage = v.Entries[0].Srclink.ImgSrc()
/*if !v.Entries[0].Srclink.OfKind(links.LinkExternal) {
// TODO: there should be a full URL ⤵︎
ogImage = doc.cfg.URL + ogImage
}*/
foundImg = true
}
}
}
return ogImage, ogDescription
}
func ogTag(property, content string) string {
return fmt.Sprintf(`<meta property="og:%s" content="%s"/>`, property, content)
}