80 lines
2.0 KiB
Go
80 lines
2.0 KiB
Go
package wechat
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"write-server/internal/config"
|
|
)
|
|
|
|
type WechatStatus struct {
|
|
Configured bool `json:"configured"`
|
|
AppID string `json:"appId,omitempty"`
|
|
}
|
|
|
|
type WechatArticle struct {
|
|
Title string `json:"title"`
|
|
Author string `json:"author"`
|
|
Content string `json:"content"`
|
|
ContentSourceURL string `json:"content_source_url,omitempty"`
|
|
ThumbMediaURL string `json:"thumb_media_url,omitempty"`
|
|
ShowCoverPic int `json:"show_cover_pic"`
|
|
NeedOpenComment int `json:"need_open_comment"`
|
|
}
|
|
|
|
var imgRE = regexp.MustCompile(`!\[.*?\]\((.*?)\)`)
|
|
|
|
func GetWechatStatus() WechatStatus {
|
|
return WechatStatus{
|
|
Configured: config.WECHAT_APP_ID != "" && config.WECHAT_APP_SECRET != "",
|
|
AppID: config.WECHAT_APP_ID,
|
|
}
|
|
}
|
|
|
|
func MDRender(markdown, slug string) (string, []string) {
|
|
var imageURLs []string
|
|
matches := imgRE.FindAllStringSubmatch(markdown, -1)
|
|
for _, m := range matches {
|
|
if len(m) > 1 {
|
|
imageURLs = append(imageURLs, m[1])
|
|
}
|
|
}
|
|
|
|
html := strings.ReplaceAll(markdown, "\r\n", "\n")
|
|
|
|
h2RE := regexp.MustCompile(`(?m)^## (.+)$`)
|
|
html = h2RE.ReplaceAllString(html, `<h2>$1</h2>`)
|
|
|
|
boldRE := regexp.MustCompile(`\*\*(.+?)\*\*`)
|
|
html = boldRE.ReplaceAllString(html, `<strong>$1</strong>`)
|
|
|
|
html = imgRE.ReplaceAllString(html, `<img src="$1" />`)
|
|
|
|
linkRE := regexp.MustCompile(`\[(.+?)\]\((.+?)\)`)
|
|
html = linkRE.ReplaceAllString(html, `<a href="$2">$1</a>`)
|
|
|
|
html = `<div>` + html + `</div>`
|
|
|
|
return html, imageURLs
|
|
}
|
|
|
|
func SyncWechat(articles []WechatArticle) (map[string]interface{}, error) {
|
|
if config.SCF_PROXY == "" {
|
|
return nil, fmt.Errorf("SCF_PROXY not configured")
|
|
}
|
|
data, _ := json.Marshal(map[string]interface{}{"articles": articles})
|
|
resp, err := http.Post(config.SCF_PROXY+"/wechat/sync", "application/json", bytes.NewReader(data))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
body, _ := io.ReadAll(resp.Body)
|
|
var result map[string]interface{}
|
|
json.Unmarshal(body, &result)
|
|
return result, nil
|
|
} |