forked from indes/flowerss-bot
-
Notifications
You must be signed in to change notification settings - Fork 3
/
service.go
336 lines (286 loc) · 8.04 KB
/
service.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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package bot
import (
"fmt"
"regexp"
"strings"
"github.com/reaitten/flowerss-bot/internal/config"
"github.com/reaitten/flowerss-bot/internal/model"
"go.uber.org/zap"
tb "gopkg.in/tucnak/telebot.v2"
)
// FeedForChannelRegister register fetcher for channel
func FeedForChannelRegister(m *tb.Message, url string, channelMention string) {
msg, err := B.Send(m.Chat, "Processing...")
channelChat, err := B.ChatByID(channelMention)
adminList, err := B.AdminsOf(channelChat)
senderIsAdmin := false
botIsAdmin := false
for _, admin := range adminList {
if m.Sender.ID == admin.User.ID {
senderIsAdmin = true
}
if B.Me.ID == admin.User.ID {
botIsAdmin = true
}
}
if !botIsAdmin {
msg, _ = B.Edit(msg, fmt.Sprintf("Please add bot as a channel manager first"))
return
}
if !senderIsAdmin {
msg, _ = B.Edit(msg, fmt.Sprintf("Non-channel managers cannot perform this operation"))
return
}
source, err := model.FindOrNewSourceByUrl(url)
if err != nil {
msg, _ = B.Edit(msg, fmt.Sprintf("%s, Subscription failed", err))
return
}
err = model.RegistFeed(channelChat.ID, source.ID)
zap.S().Infof("%d for %d subscribe [%d]%s %s", m.Chat.ID, channelChat.ID, source.ID, source.Title, source.Link)
if err == nil {
newText := fmt.Sprintf(
"Channel [%s](https://t.me/%s) subscription [%s](%s) success",
channelChat.Title,
channelChat.Username,
source.Title,
source.Link,
)
_, err = B.Edit(msg, newText,
&tb.SendOptions{
DisableWebPagePreview: true,
ParseMode: tb.ModeMarkdown,
})
} else {
_, _ = B.Edit(msg, "Subscription failed")
}
}
func registFeed(chat *tb.Chat, url string) {
msg, err := B.Send(chat, "Processing...")
url = model.ProcessWechatURL(url)
source, err := model.FindOrNewSourceByUrl(url)
if err != nil {
msg, _ = B.Edit(msg, fmt.Sprintf("%s, Subscription failed", err))
return
}
err = model.RegistFeed(chat.ID, source.ID)
zap.S().Infof("%d subscribe [%d]%s %s", chat.ID, source.ID, source.Title, source.Link)
if err == nil {
_, _ = B.Edit(msg, fmt.Sprintf("[%s](%s) Successfully subscribed", source.Title, source.Link),
&tb.SendOptions{
DisableWebPagePreview: true,
ParseMode: tb.ModeMarkdown,
})
} else {
_, _ = B.Edit(msg, "Subscription failed")
}
}
//SendError send error user
func SendError(c *tb.Chat) {
_, _ = B.Send(c, "Please enter the correct instruction!")
}
//BroadcastNews send new contents message to subscriber
func BroadcastNews(source *model.Source, subs []*model.Subscribe, contents []*model.Content) {
zap.S().Infow("broadcast news",
"fetcher id", source.ID,
"fetcher title", source.Title,
"subscriber count", len(subs),
"new contents", len(contents),
)
for _, content := range contents {
previewText := trimDescription(content.Description, config.PreviewText)
for _, sub := range subs {
tpldata := &config.TplData{
SourceTitle: source.Title,
ContentTitle: content.Title,
RawLink: content.RawLink,
PreviewText: previewText,
TelegraphURL: content.TelegraphURL,
Tags: sub.Tag,
EnableTelegraph: sub.EnableTelegraph == 1 && content.TelegraphURL != "",
}
u := &tb.User{
ID: int(sub.UserID),
}
o := &tb.SendOptions{
DisableWebPagePreview: config.DisableWebPagePreview,
ParseMode: config.MessageMode,
DisableNotification: sub.EnableNotification != 1,
}
msg, err := tpldata.Render(config.MessageMode)
if err != nil {
zap.S().Errorw("broadcast news error, tpldata.Render err",
"error", err.Error(),
)
return
}
if _, err := B.Send(u, msg, o); err != nil {
if strings.Contains(err.Error(), "Forbidden") {
zap.S().Errorw("broadcast news error, bot stopped by user",
"error", err.Error(),
"user id", sub.UserID,
"source id", sub.SourceID,
"title", source.Title,
"link", source.Link,
)
sub.Unsub()
}
/*
Telegram return error if markdown message has incomplete format.
Print the msg to warn the user
api error: Bad Request: can't parse entities: Can't find end of the entity starting at byte offset 894
*/
if strings.Contains(err.Error(), "parse entities") {
zap.S().Errorw("broadcast news error, markdown error",
"markdown msg", msg,
"error", err.Error(),
)
}
}
}
}
}
// BroadcastSourceError send fetcher updata error message to subscribers
func BroadcastSourceError(source *model.Source) {
subs := model.GetSubscriberBySource(source)
var u tb.User
for _, sub := range subs {
message := fmt.Sprintf("[%s](%s) Accumulatively %d consecutive update failed, temporarily stop the update", source.Title, source.Link, config.ErrorThreshold)
u.ID = int(sub.UserID)
_, _ = B.Send(&u, message, &tb.SendOptions{
ParseMode: tb.ModeMarkdown,
})
}
}
// CheckAdmin check user is admin of group/channel
func CheckAdmin(upd *tb.Update) bool {
if upd.Message != nil {
if HasAdminType(upd.Message.Chat.Type) {
adminList, _ := B.AdminsOf(upd.Message.Chat)
for _, admin := range adminList {
if admin.User.ID == upd.Message.Sender.ID {
return true
}
}
return false
}
return true
} else if upd.Callback != nil {
if HasAdminType(upd.Callback.Message.Chat.Type) {
adminList, _ := B.AdminsOf(upd.Callback.Message.Chat)
for _, admin := range adminList {
if admin.User.ID == upd.Callback.Sender.ID {
return true
}
}
return false
}
return true
}
return false
}
// IsUserAllowed check user is allowed to use bot
func isUserAllowed(upd *tb.Update) bool {
if upd == nil {
return false
}
var userID int64
if upd.Message != nil {
userID = int64(upd.Message.Sender.ID)
} else if upd.Callback != nil {
userID = int64(upd.Callback.Sender.ID)
} else {
return false
}
if len(config.AllowUsers) == 0 {
return true
}
for _, allowUserID := range config.AllowUsers {
if allowUserID == userID {
return true
}
}
zap.S().Infow("user not allowed", "userID", userID)
return false
}
func userIsAdminOfGroup(userID int, groupChat *tb.Chat) (isAdmin bool) {
adminList, err := B.AdminsOf(groupChat)
isAdmin = false
if err != nil {
return
}
for _, admin := range adminList {
if userID == admin.User.ID {
isAdmin = true
}
}
return
}
// UserIsAdminChannel check if the user is the administrator of channel
func UserIsAdminChannel(userID int, channelChat *tb.Chat) (isAdmin bool) {
adminList, err := B.AdminsOf(channelChat)
isAdmin = false
if err != nil {
return
}
for _, admin := range adminList {
if userID == admin.User.ID {
isAdmin = true
}
}
return
}
// HasAdminType check if the message is sent in the group/channel environment
func HasAdminType(t tb.ChatType) bool {
hasAdmin := []tb.ChatType{tb.ChatGroup, tb.ChatSuperGroup, tb.ChatChannel, tb.ChatChannelPrivate}
for _, n := range hasAdmin {
if t == n {
return true
}
}
return false
}
// GetMentionFromMessage get message mention
func GetMentionFromMessage(m *tb.Message) (mention string) {
if m.Text != "" {
for _, entity := range m.Entities {
if entity.Type == tb.EntityMention {
if mention == "" {
mention = m.Text[entity.Offset : entity.Offset+entity.Length]
return
}
}
}
} else {
for _, entity := range m.CaptionEntities {
if entity.Type == tb.EntityMention {
if mention == "" {
mention = m.Caption[entity.Offset : entity.Offset+entity.Length]
return
}
}
}
}
return
}
var relaxUrlMatcher = regexp.MustCompile(`^(https?://.*?)($| )`)
// GetURLAndMentionFromMessage get URL and mention from message
func GetURLAndMentionFromMessage(m *tb.Message) (url string, mention string) {
for _, entity := range m.Entities {
if entity.Type == tb.EntityMention {
if mention == "" {
mention = m.Text[entity.Offset : entity.Offset+entity.Length]
}
}
if entity.Type == tb.EntityURL {
if url == "" {
url = m.Text[entity.Offset : entity.Offset+entity.Length]
}
}
}
var payloadMatching = relaxUrlMatcher.FindStringSubmatch(m.Payload)
if url == "" && len(payloadMatching) > 0 && payloadMatching[0] != "" {
url = payloadMatching[0]
}
return
}