Небольшой рефакторинг, изменение принципа создания поста

This commit is contained in:
B4D_US3R 2025-04-11 17:13:54 +05:00
parent d99d47e4e1
commit 4d1d1360dc

106
main.go
View file

@ -9,7 +9,6 @@ import (
"net/url" "net/url"
"os" "os"
"path/filepath" "path/filepath"
"regexp"
"strings" "strings"
"time" "time"
@ -18,7 +17,6 @@ import (
"github.com/mmcdole/gofeed" "github.com/mmcdole/gofeed"
"github.com/urfave/cli/v3" "github.com/urfave/cli/v3"
"golang.org/x/net/html" "golang.org/x/net/html"
"golang.org/x/net/html/atom"
) )
type MastodonClientData struct { type MastodonClientData struct {
@ -35,14 +33,17 @@ type KikiSettings struct {
func getSecrets(path string) *mastodon.Config { func getSecrets(path string) *mastodon.Config {
var clientData MastodonClientData var clientData MastodonClientData
secretConfig, err := os.ReadFile(path) secretConfig, err := os.ReadFile(path)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
err = yaml.Unmarshal(secretConfig, &clientData) err = yaml.Unmarshal(secretConfig, &clientData)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
config := &mastodon.Config{ config := &mastodon.Config{
Server: clientData.Instance, Server: clientData.Instance,
ClientID: clientData.ClientID, ClientID: clientData.ClientID,
@ -53,40 +54,19 @@ func getSecrets(path string) *mastodon.Config {
return config return config
} }
func returnImgArray(htmlText string) []string {
var imgArray []string
parser, err := html.Parse(strings.NewReader(htmlText))
if err != nil {
log.Println(err)
}
for n := range parser.Descendants() {
if n.Type == html.ElementNode && n.DataAtom == atom.Img {
for _, img := range n.Attr {
if img.Key == "src" {
imgArray = append(imgArray, img.Val)
}
}
}
}
return imgArray
}
func hasHTMLTags(s string) bool {
re := regexp.MustCompile(`<(?i)[a-z][a-z0-9]*[^>]*>`)
return re.MatchString(s)
}
func getKikiConfig(path string) KikiSettings { func getKikiConfig(path string) KikiSettings {
var kikiSettings KikiSettings var kikiSettings KikiSettings
kikiConfigFile, err := os.ReadFile(path) kikiConfigFile, err := os.ReadFile(path)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
err = yaml.Unmarshal(kikiConfigFile, &kikiSettings) err = yaml.Unmarshal(kikiConfigFile, &kikiSettings)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
return kikiSettings return kikiSettings
} }
@ -98,6 +78,7 @@ func clientConfiguration(Instance string) {
Website: "catgirls.asia", Website: "catgirls.asia",
RedirectURIs: "urn:ietf:wg:oauth:2.0:oob", RedirectURIs: "urn:ietf:wg:oauth:2.0:oob",
} }
app, err := mastodon.RegisterApp(context.Background(), appConfig) app, err := mastodon.RegisterApp(context.Background(), appConfig)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
@ -135,6 +116,7 @@ func clientConfiguration(Instance string) {
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
log.Println(string(marshaledYaml)) log.Println(string(marshaledYaml))
secretConfig, err := os.OpenFile("secret.conf", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644) secretConfig, err := os.OpenFile("secret.conf", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644)
if err != nil { if err != nil {
@ -182,17 +164,62 @@ func picBytesArray(picturesArray []string) [][]byte {
func uploadPictures(mastoClient mastodon.Client, filesBytes [][]byte) []*mastodon.Attachment { func uploadPictures(mastoClient mastodon.Client, filesBytes [][]byte) []*mastodon.Attachment {
var attachments []*mastodon.Attachment var attachments []*mastodon.Attachment
for _, file := range filesBytes { for _, file := range filesBytes {
att, err := mastoClient.UploadMediaFromBytes(context.Background(), file) att, err := mastoClient.UploadMediaFromBytes(context.Background(), file)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return attachments return attachments
} }
attachments = append(attachments, att) attachments = append(attachments, att)
} }
return attachments return attachments
} }
func createToot(mastoClient mastodon.Client, newsDesc string) (mastodon.Toot, error) {
var tootText string
var imgArray []string
var attachments []*mastodon.Attachment
toot := mastodon.Toot{
Visibility: "unlisted",
Sensitive: true,
}
uString := html.UnescapeString(newsDesc)
pHtml, err := html.Parse(strings.NewReader(uString))
if err != nil {
return mastodon.Toot{}, err
}
for n := range pHtml.Descendants() {
if n.Type != html.ElementNode {
tootText += (n.Data + "\n")
}
if n.Type == html.ElementNode && n.Data == "img" {
for _, attr := range n.Attr {
if attr.Key == "src" {
imgArray = append(imgArray, attr.Val)
}
}
}
}
if len(imgArray) != 0 {
attachments = uploadPictures(mastoClient, picBytesArray(imgArray))
}
toot.Status = tootText
for _, attach := range attachments {
toot.MediaIDs = append(toot.MediaIDs, attach.ID)
}
return toot, nil
}
func main() { func main() {
cmd := &cli.Command{ cmd := &cli.Command{
Name: "kiki", Name: "kiki",
@ -203,16 +230,20 @@ func main() {
Usage: "Инициализировать клиента", Usage: "Инициализировать клиента",
Action: func(ctx context.Context, cmd *cli.Command) error { Action: func(ctx context.Context, cmd *cli.Command) error {
confFile, err := filepath.Abs("config.yaml") confFile, err := filepath.Abs("config.yaml")
kikiConfig := getKikiConfig(confFile)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
kikiConfig := getKikiConfig(confFile)
instanceUrlParser, err := url.Parse(kikiConfig.Instance) instanceUrlParser, err := url.Parse(kikiConfig.Instance)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
instanceUrlParser.Scheme = "https" instanceUrlParser.Scheme = "https"
clientConfiguration(instanceUrlParser.String()) clientConfiguration(instanceUrlParser.String())
return nil return nil
}, },
}, },
@ -221,31 +252,28 @@ func main() {
Usage: "Запуск транслятора", Usage: "Запуск транслятора",
Action: func(ctx context.Context, cmd *cli.Command) error { Action: func(ctx context.Context, cmd *cli.Command) error {
var lastGUID string var lastGUID string
mastoClient := mastodon.NewClient(getSecrets("secret.conf"))
confFile, err := filepath.Abs("config.yaml") confFile, err := filepath.Abs("config.yaml")
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
kikiConfig := getKikiConfig(confFile) kikiConfig := getKikiConfig(confFile)
mastoClient := mastodon.NewClient(getSecrets("secret.conf"))
ticker := time.NewTicker(1 * time.Minute) ticker := time.NewTicker(1 * time.Minute)
defer ticker.Stop() defer ticker.Stop()
for range ticker.C { for range ticker.C {
news := newsText(kikiConfig.RSSUri) news := newsText(kikiConfig.RSSUri)
if news[0].GUID != lastGUID { if news[0].GUID != lastGUID {
toot := mastodon.Toot{
Visibility: "unlisted",
Sensitive: true,
}
log.Println(news[0].Description) log.Println(news[0].Description)
toot.Status = news[0].Description
lastGUID = news[0].GUID toot, err := createToot(*mastoClient, news[0].Description)
if hasHTMLTags(news[0].Description) { if err != nil {
attachments := uploadPictures(*mastoClient, picBytesArray(returnImgArray(news[0].Description))) log.Println(err)
for _, attach := range attachments {
toot.MediaIDs = append(toot.MediaIDs, attach.ID)
}
} }
createPost(*mastoClient, toot) createPost(*mastoClient, toot)
lastGUID = news[0].GUID
} }
} }
return nil return nil