aboutsummaryrefslogtreecommitdiff
path: root/internal/ogtags/parse.go
blob: 8828e59b04585761f28bfafb62a0ed1f9c19965e (plain)
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
package ogtags

import (
	"strings"

	"golang.org/x/net/html"
)

// extractOGTags traverses the HTML document and extracts approved Open Graph tags
func (c *OGTagCache) extractOGTags(doc *html.Node) map[string]string {
	ogTags := make(map[string]string)

	var traverseNodes func(*html.Node)
	traverseNodes = func(n *html.Node) {
		// isOGMetaTag only checks if it's a <meta> tag.
		// The actual filtering happens in extractMetaTagInfo now.
		if isOGMetaTag(n) {
			property, content := c.extractMetaTagInfo(n)
			if property != "" {
				ogTags[property] = content
			}
		}

		for child := n.FirstChild; child != nil; child = child.NextSibling {
			traverseNodes(child)
		}
	}

	traverseNodes(doc)
	return ogTags
}

// isOGMetaTag checks if a node is *any* meta tag
func isOGMetaTag(n *html.Node) bool {
	if n == nil {
		return false
	}
	return n.Type == html.ElementNode && n.Data == "meta"
}

// extractMetaTagInfo extracts property and content from a meta tag
// *and* checks if the property is approved.
// Returns empty property string if the tag is not approved.
func (c *OGTagCache) extractMetaTagInfo(n *html.Node) (property, content string) {
	var rawProperty string // Store the property found before approval check

	for _, attr := range n.Attr {
		if attr.Key == "property" || attr.Key == "name" {
			rawProperty = attr.Val
		}
		if attr.Key == "content" {
			content = attr.Val
		}
	}

	// Check if the rawProperty is approved
	isApproved := false
	for _, prefix := range c.approvedPrefixes {
		if strings.HasPrefix(rawProperty, prefix) {
			isApproved = true
			break
		}
	}
	// Check exact approved tags if not already approved by prefix
	if !isApproved {
		for _, tag := range c.approvedTags {
			if rawProperty == tag {
				isApproved = true
				break
			}
		}
	}

	// Only return the property if it's approved
	if isApproved {
		property = rawProperty
	}

	// Content is returned regardless, but property will be "" if not approved
	return property, content
}