forked from indes/flowerss-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autoload.go
272 lines (233 loc) · 6.19 KB
/
autoload.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package config
import (
"bytes"
"flag"
"fmt"
"log"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"testing"
"text/template"
"github.com/spf13/viper"
tb "gopkg.in/telebot.v3"
)
func init() {
if isInTests() {
// 测试环境
RunMode = TestMode
initTPL()
return
}
workDirFlag := flag.String("d", "./", "work directory of flowerss")
configFile := flag.String("c", "", "config file of flowerss")
printVersionFlag := flag.Bool("v", false, "prints flowerss-bot version")
testTpl := flag.Bool("testtpl", false, "test template")
testing.Init()
flag.Parse()
if *printVersionFlag {
// print version
fmt.Printf(AppVersionInfo())
os.Exit(0)
}
workDir := filepath.Clean(*workDirFlag)
if *configFile != "" {
viper.SetConfigFile(*configFile)
} else {
viper.SetConfigFile(filepath.Join(workDir, "config.yml"))
}
fmt.Printf(logo)
fmt.Printf("\n")
err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
panic(fmt.Errorf("Fatal error config file: %s", err))
}
initTPL()
if *testTpl {
validateTPL()
os.Exit(0)
}
BotToken = viper.GetString("bot_token")
Socks5 = viper.GetString("socks5")
UserAgent = viper.GetString("user_agent")
if viper.IsSet("telegraph_token") {
EnableTelegraph = true
TelegraphToken = viper.GetStringSlice("telegraph_token")
}
if viper.IsSet("telegraph_account") {
EnableTelegraph = true
TelegraphAccountName = viper.GetString("telegraph_account")
if viper.IsSet("telegraph_author_name") {
TelegraphAuthorName = viper.GetString("telegraph_author_name")
}
if viper.IsSet("telegraph_author_url") {
TelegraphAuthorURL = viper.GetString("telegraph_author_url")
}
}
if viper.IsSet("preview_text") {
PreviewText = viper.GetInt("preview_text")
}
if viper.IsSet("allowed_users") {
intAllowUsers := viper.GetStringSlice("allowed_users")
for _, useIDStr := range intAllowUsers {
userID, err := strconv.ParseInt(useIDStr, 10, 64)
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s", err))
}
AllowUsers = append(AllowUsers, userID)
}
}
if viper.IsSet("disable_web_page_preview") {
DisableWebPagePreview = viper.GetBool("disable_web_page_preview")
}
if viper.IsSet("telegram.endpoint") {
TelegramEndpoint = viper.GetString("telegram.endpoint")
}
if viper.IsSet("error_threshold") {
ErrorThreshold = uint(viper.GetInt("error_threshold"))
}
if viper.IsSet("update_interval") {
UpdateInterval = viper.GetInt("update_interval")
}
if viper.IsSet("mysql.host") {
EnableMysql = true
Mysql = MysqlConfig{
Host: viper.GetString("mysql.host"),
Port: viper.GetInt("mysql.port"),
User: viper.GetString("mysql.user"),
Password: viper.GetString("mysql.password"),
DB: viper.GetString("mysql.database"),
}
}
if !EnableMysql {
if viper.IsSet("sqlite.path") {
SQLitePath = viper.GetString("sqlite.path")
} else {
SQLitePath = filepath.Join(workDir, "data.db")
}
log.Println("DB Path:", SQLitePath)
// 判断并创建SQLite目录
dir := path.Dir(SQLitePath)
_, err := os.Stat(dir)
if err != nil {
err := os.MkdirAll(dir, os.ModeDir)
if err != nil {
log.Printf("mkdir failed![%v]\n", err)
}
}
}
if viper.IsSet("log.db_log") {
DBLogMode = viper.GetBool("log.db_log")
}
}
func (t TplData) Render(mode tb.ParseMode) (string, error) {
var buf []byte
wb := bytes.NewBuffer(buf)
if mode == tb.ModeMarkdown {
mkd := regexp.MustCompile("(\\[|\\*|\\`|\\_)")
t.SourceTitle = mkd.ReplaceAllString(t.SourceTitle, "\\$1")
t.ContentTitle = mkd.ReplaceAllString(t.ContentTitle, "\\$1")
t.PreviewText = mkd.ReplaceAllString(t.PreviewText, "\\$1")
} else if mode == tb.ModeHTML {
t.SourceTitle = t.replaceHTMLTags(t.SourceTitle)
t.ContentTitle = t.replaceHTMLTags(t.ContentTitle)
t.PreviewText = t.replaceHTMLTags(t.PreviewText)
}
if err := MessageTpl.Execute(wb, t); err != nil {
return "", err
}
return strings.TrimSpace(string(wb.Bytes())), nil
}
func (t TplData) replaceHTMLTags(s string) string {
rStr := strings.ReplaceAll(s, "&", "&")
rStr = strings.ReplaceAll(rStr, "\"", """)
rStr = strings.ReplaceAll(rStr, "<", "<")
rStr = strings.ReplaceAll(rStr, ">", ">")
return rStr
}
func validateTPL() {
testData := []TplData{
TplData{
"RSS 源标识 - 无预览无telegraph的消息",
"这是标题",
"https://www.github.com/",
"",
"",
"",
false,
},
TplData{
"RSS源标识 - 有预览无telegraph的消息",
"这是标题",
"https://www.github.com/",
"这里是很长很长很长的消息预览字数补丁紫薯补丁紫薯补丁紫薯补丁紫薯补丁[1](123)",
"",
"#标签",
false,
},
TplData{
"RSS源标识 - 有预览有telegraph的消息",
"这是标题",
"https://www.github.com/",
"这里是很长很长很长的消息预览字数补丁紫薯补丁紫薯补丁紫薯补丁紫薯补丁",
"https://telegra.ph/markdown-07-07",
"#标签1 #标签2",
true,
},
}
for _, d := range testData {
fmt.Println("\n////////////////////////////////////////////")
fmt.Println(d.Render(MessageMode))
}
fmt.Println("\n////////////////////////////////////////////")
}
func initTPL() {
var tplMsg string
if viper.IsSet("message_tpl") {
tplMsg = viper.GetString("message_tpl")
} else {
tplMsg = defaultMessageTpl
}
MessageTpl = template.Must(template.New("message").Parse(tplMsg))
if viper.IsSet("message_mode") {
switch strings.ToLower(viper.GetString("message_mode")) {
case "md", "markdown":
MessageMode = tb.ModeMarkdown
case "html":
MessageMode = tb.ModeHTML
default:
MessageMode = tb.ModeDefault
}
} else {
MessageMode = defaultMessageTplMode
}
}
func getInt(s string) int {
num, _ := strconv.Atoi(s)
return num
}
func (m *MysqlConfig) GetMysqlConnectingString() string {
usr := m.User
pwd := m.Password
host := m.Host
port := m.Port
db := m.DB
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=true", usr, pwd, host, port, db)
}
func isInTests() bool {
if flag.Lookup("test.v") != nil {
return true
}
for _, arg := range os.Args {
if strings.HasPrefix(arg, "-test") {
if arg == "-testtpl" {
continue
}
return true
}
}
return false
}