ref: 40b380a7a4bb3ded2d29cf0a415b49660dc7c454
dir: /edit.go/
package main
import (
"bytes"
"errors"
"strings"
"fmt"
mastodon "codeberg.org/penny64/hellclient-go-mastodon"
"golang.org/x/net/html"
)
// Replace username links with their user@domain format
func prepareForEdit(status *mastodon.Status) (string, error) {
doc, err := html.Parse(strings.NewReader(status.Content))
if err != nil {
return "", errors.New("failed to parse post HTML")
}
mentions := 0
for node := range doc.Descendants() {
if node.Data == "a" && node.Type == html.ElementNode {
ismention := false
for attr := range node.Attr {
if node.Attr[attr].Key == "class" && strings.Contains(node.Attr[attr].Val, "mention") && !strings.Contains(node.Attr[attr].Val, "hashtag") {
ismention = true
continue
}
if node.Attr[attr].Key == "class" && strings.Contains(node.Attr[attr].Val, "hashtag") {
if node.FirstChild != nil && node.FirstChild.Type == html.TextNode {
node.Attr[attr].Val = fmt.Sprintf("#%s", node.FirstChild.Data)
node.Data = "div"
}
}
}
if ismention {
for attr := range node.Attr {
if node.Attr[attr].Key == "href" {
node.Attr[attr].Val = "@" + status.Mentions[mentions].Acct
mentions++
}
}
}
}
}
//Rip off the HTML body the parser made for us
for node := range doc.Descendants() {
if node.Data == "body" {
node.Type = html.DocumentNode
doc = node
}
}
var rendered bytes.Buffer
err = html.Render(&rendered, doc)
if err != nil {
return "", err
}
renderedPlainText := rendered.String()
return renderedPlainText, nil
}