-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrosspost.go
496 lines (444 loc) · 12.5 KB
/
crosspost.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
package main
// this part uses vk api execute method to get batched updates for vk
// and dispatch them to subscribers via channels
import (
"fmt"
"html"
"log"
"net/http"
"reflect"
"strconv"
"strings"
"sync"
"time"
vkApi "github.com/SevereCloud/vksdk/v2/api"
vkObject "github.com/SevereCloud/vksdk/v2/object"
tele "gopkg.in/telebot.v3"
)
const (
maxVidDuration = 102 // because 720p is below 50 MB(telegram limit) for up to 102 seconds
// bigger videos are posted via link
)
const (
flagAddLinkToPost uint64 = 1 << iota
)
type vkReqData struct {
id int64
lastPost int64
}
type vkReqResult struct {
Id int64 `json:"id"`
LastPost int64 `json:"lastPost"`
Posts []vkObject.WallWallpost `json:"posts"`
}
type vkAudio struct {
Url string `json:"url"`
Performer string `json:"artist"`
Title string `json:"title"`
}
type postLink struct {
formattedPostLink string
rawPostLink string
postLinkTextLen int
}
const (
mediaPhotoVideo = iota
mediaAudio
mediaDoc
nMediaTypes
)
type preparedMedia [nMediaTypes][]tele.Inputtable
type preparedAttachments struct {
media preparedMedia
links []string
}
func (m *preparedMedia) Empty() bool {
for i := range m {
if len(m[i]) > 0 {
return false
}
}
return true
}
func (att *preparedAttachments) Empty() bool {
return att.media.Empty() && len(att.links) == 0
}
type preparedPost struct {
att preparedAttachments
ownerID int
ID int
text string
copyHistory []preparedPost
Link postLink
}
type update struct {
posts []preparedPost
flags uint64
}
type updateInfo struct {
time int64
nPosts int
}
type stats struct {
nPostsGlobal int
updates []updateInfo
startTime int64
m sync.Mutex
}
func (s *stats) addUpdate(u updateInfo) {
s.m.Lock()
defer s.m.Unlock()
s.nPostsGlobal += u.nPosts
s.updates = append(s.updates, u)
}
func (s *stats) get() (int, int, int64) {
comp := func(l *updateInfo, r *updateInfo) bool {
return l.time < r.time
}
now := time.Now().Unix()
hourAgo := updateInfo{
time: now - 3600,
}
s.m.Lock()
defer s.m.Unlock()
lb := lowerBound(s.updates, &hourAgo, comp)
lastHour := 0
for i := lb; i < len(s.updates); i++ {
lastHour += s.updates[i].nPosts
}
uptime := now - s.startTime
return s.nPostsGlobal, lastHour, uptime
}
func makeObjects(batch []vkReqData) string {
if len(batch) == 0 {
return ""
}
pat := `{"id":%d, "lastPost": %d}`
res := fmt.Sprintf(pat, batch[0].id, batch[0].lastPost)
for _, cur := range batch[1:] {
res += `,` + fmt.Sprintf(pat, cur.id, cur.lastPost)
}
return res
}
func (cp *Crossposter) getAudio(audioIds []string) []tele.Inputtable {
res := []tele.Inputtable{}
if len(audioIds) == 0 {
return res
}
vkRes := []vkAudio{}
err := cp.vkAudio.RequestUnmarshal("audio.getById", &vkRes, vkApi.Params{
"audios": strings.Join(audioIds, ","),
})
if err != nil {
log.Printf("Failed to get audio:\n%s\n", err.Error())
return nil
}
for i, a := range vkRes {
if a.Url != "" {
r, err := http.Get(a.Url)
if err != nil {
log.Printf("Failed to get audio from url %s\n%s\n", a.Url, err.Error())
continue
}
res = append(res, &tele.Audio{
File: tele.FromReader(r.Body),
Title: a.Title,
Performer: a.Performer,
})
} else {
log.Printf("Failed to get audio %s\n", audioIds[i])
}
}
return res
}
func (cp *Crossposter) getVideo(videoIds []string) ([]tele.Inputtable, []string) {
vkRes, err := cp.vkAudio.VideoGet(map[string]interface{}{
"videos": strings.Join(videoIds, ","),
})
time.Sleep(time.Millisecond * 200)
if err != nil {
log.Printf("Failed to get video:\n%s\n", err.Error())
return nil, nil
}
res := []tele.Inputtable{}
resLinks := []string{}
for i := range vkRes.Items {
v := &vkRes.Items[i]
if v.Platform == "YouTube" {
resLinks = append(resLinks, convertYoutubeUrl(v.Player))
continue
}
if v.Duration < maxVidDuration && (v.Platform == "vk" || v.Platform == "") {
if url := findVideoURL(v); url == "" {
log.Printf("Couldn't find url for video %d_%d\n", v.OwnerID, v.ID)
} else {
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("User-Agent", kateUserAgent)
r, err := cp.vkAudio.Client.Get(url)
if err != nil {
log.Printf("Failed to get video from url\n%s\n", err.Error())
continue
}
res = append(res, &tele.Video{
File: tele.FromReader(r.Body),
})
time.Sleep(time.Millisecond * 200)
continue
}
}
resLinks = append(resLinks, fmt.Sprintf("vk.com/video%d_%d", v.OwnerID, v.ID))
}
return res, resLinks
}
func (cp *Crossposter) getAttachments(post *vkObject.WallWallpost) preparedAttachments {
// because telegram album contains either photo/video or audio or documents, we separate them
res := preparedAttachments{preparedMedia{}, []string{}}
audioIds := []string{}
videoIds := []string{}
for _, att := range post.Attachments {
switch att.Type {
case "photo":
url := getPhotoUrl(att.Photo)
res.media[mediaPhotoVideo] = append(res.media[mediaPhotoVideo],
&tele.Photo{File: tele.FromURL(url)})
case "audio":
audioIds = append(audioIds, strconv.Itoa(att.Audio.OwnerID)+"_"+strconv.Itoa(att.Audio.ID))
case "doc":
res.media[mediaDoc] = append(res.media[mediaDoc],
&tele.Document{File: tele.FromURL(att.Doc.URL)})
case "video":
vID := strconv.Itoa(att.Video.OwnerID) + "_" + strconv.Itoa(att.Video.ID)
if att.Video.AccessKey != "" {
vID += "_" + att.Video.AccessKey
}
videoIds = append(videoIds, vID)
}
}
audio := cp.getAudio(audioIds)
if len(audio) < len(audioIds) {
log.Printf("Only got %d/%d audios for %s\n", len(audio),
len(audioIds), fmt.Sprintf("https://vk.com/wall%d_%d", post.OwnerID, post.ID))
}
res.media[mediaAudio] = audio
if len(videoIds) > 0 {
vids, links := cp.getVideo(videoIds)
res.media[mediaPhotoVideo] = append(res.media[mediaPhotoVideo], vids...)
res.links = links
}
return res
}
func (cp *Crossposter) sendText(text string, link postLink, chat int64, opts tele.SendOptions) *tele.Message {
text = strings.Trim(text, " \t\n")
if len(text) == 0 {
return nil
}
if len(text) > 0 && link.postLinkTextLen > 0 {
text = text + "\n\n"
}
var firstMsg *tele.Message
appendedLink := false
maxMsgSize := 4096
for len(text) > 0 || (len(link.formattedPostLink) > 0 && !appendedLink) {
splitIndex, msgLen := findIndexToSplit(text, maxMsgSize)
msgText := inlineLinkRegex.ReplaceAllString(
html.EscapeString(text[0:splitIndex]),
"<a href='https://vk.com/$1$2'>$3</a>",
)
// if text fits in one message, check if it will fit with link too
if splitIndex == len(text) && msgLen+link.postLinkTextLen <= maxMsgSize {
msgText = msgText + link.formattedPostLink
appendedLink = true
}
newMsg, err := cp.tgBot.Send(tele.ChatID(chat), msgText, &opts)
time.Sleep(time.Second * 4)
if err != nil {
log.Printf("Failed to send text message for post %s:\n%s\n", link.rawPostLink, err.Error())
return nil
}
if firstMsg == nil {
firstMsg = newMsg
}
opts.ReplyTo = newMsg
text = strings.TrimLeft(text[splitIndex:], " \t\n")
}
return firstMsg
}
func (cp *Crossposter) sendWithAttachments(text string, link postLink, id int64, att preparedAttachments, opts tele.SendOptions) *tele.Message {
if len(att.links) != 0 {
text = text + "\n" + strings.Join(att.links, "\n")
}
maxMsgSize := 1024
_, msgSize := findIndexToSplit(text, 999999) // count rendered characters in a text
if link.postLinkTextLen > 0 {
if msgSize > 0 {
msgSize += 2 // two newlines
text = text + "\n\n"
}
msgSize += link.postLinkTextLen
}
var firstMsg *tele.Message = nil
if msgSize > maxMsgSize || att.media.Empty() {
firstMsg = cp.sendText(text, link, id, opts)
text = text[:0]
opts.ReplyTo = firstMsg
} else {
text = inlineLinkRegex.ReplaceAllString(
html.EscapeString(text),
"<a href='https://vk.com/$1$2'>$3</a>") +
link.formattedPostLink
}
for mediaType := range att.media {
if len(att.media[mediaType]) == 0 {
continue
}
msg, err := cp.tgBot.SendAlbum(tele.ChatID(id), att.media[mediaType], text, &opts)
// simplest way to not exceed 20 messages per minute
time.Sleep(time.Second * 4 * time.Duration(len(att.media[mediaType])))
if err != nil {
log.Printf("Failed to send attachment for post %s:\n%s\n", link.rawPostLink, err.Error())
if len(text) > 0 {
// if we failed to send text, give up and return,
// otherwise continue trying to send other attachments.
return nil
}
}
// we post attachments as a reply to initial message, while the initial message may be a reply
// to another message passed in opts in case of repost chains
if firstMsg == nil && len(msg) > 0 {
firstMsg = &msg[0]
opts.ReplyTo = firstMsg
}
text = text[:0]
}
return firstMsg
}
func (cp *Crossposter) forwardSinglePost(post *preparedPost, flags uint64, chatID int64, opts tele.SendOptions) *tele.Message {
link := post.Link
if flags&flagAddLinkToPost == 0 {
link.formattedPostLink = ""
link.postLinkTextLen = 0
}
if post.att.Empty() {
return cp.sendText(post.text, link, chatID, opts)
}
return cp.sendWithAttachments(post.text, link, chatID, post.att, opts)
}
func (cp *Crossposter) forwardPost(post *preparedPost, chatID int64, flags uint64) {
opts := tele.SendOptions{
ParseMode: "HTML",
}
for i := range post.copyHistory {
flags := flags
// if we have reposts from external pages, add reference to source regardless of setting
if post.copyHistory[i].ownerID != post.ownerID {
flags |= flagAddLinkToPost
}
opts.ReplyTo = cp.forwardSinglePost(&post.copyHistory[i], flags, chatID, opts)
}
cp.forwardSinglePost(post, flags, chatID, opts)
}
func (cp *Crossposter) listenAndForward(upd <-chan update, chatID int64) {
cp.wg.Add(1)
for update := range upd {
for i := range update.posts {
cp.forwardPost(&update.posts[i], chatID, uint64(update.flags))
}
}
cp.wg.Done()
}
func (cp *Crossposter) makeLinkToPost(post *vkObject.WallWallpost) postLink {
ownerData, _ := cp.resolveVkId(int64(post.OwnerID))
postLinkText := ownerData.Name
rawPostLink := fmt.Sprintf("https://vk.com/wall%d_%d", post.OwnerID, post.ID)
formattedPostLink := fmt.Sprintf("[<a href = '%s'>%s</a>]", rawPostLink, postLinkText)
postLinkLen := len([]rune(postLinkText)) + 2
return postLink{
formattedPostLink,
rawPostLink,
postLinkLen,
}
}
func (cp *Crossposter) preparePosts(posts []vkObject.WallWallpost, HandleReposts bool) []preparedPost {
res := make([]preparedPost, 0, len(posts))
for i := len(posts) - 1; i >= 0; i-- {
// We only skip ads if they're not intentionally reposted.
// For reposts HandleReposts is false, so the ads will be
// handled as ordinary posts.
if bool(posts[i].MarkedAsAds) && HandleReposts {
continue
}
var copyHistory []preparedPost = nil
if HandleReposts {
copyHistory = cp.preparePosts(posts[i].CopyHistory, false)
}
res = append(res, preparedPost{
att: cp.getAttachments(&posts[i]),
text: posts[i].Text,
copyHistory: copyHistory,
ID: posts[i].ID,
ownerID: posts[i].OwnerID,
Link: cp.makeLinkToPost(&posts[i]),
})
}
return res
}
func (cp *Crossposter) processBatch(batch []vkReqData) {
var res []vkReqResult
err := cp.vk.Execute(makeJs(batch, cp.nPostsToFetch), &res)
if err != nil {
log.Printf("Failed to execute:\n%s\n", err.Error())
switch e := err.(type) {
case *vkApi.ExecuteErrors:
for _, exErr := range *e {
log.Printf("Method: %s Code: %d Message: %s\n", exErr.Method, exErr.Code, exErr.Msg)
}
default:
log.Println("Unknown error type: ", reflect.TypeOf(err))
}
} else {
nUpdates := 0
time := time.Now().Unix()
for i := range res {
cp.updateTimeStamp(res[i].Id, res[i].LastPost)
nUpdates += len(res[i].Posts)
cp.ps.publish(res[i].Id, cp.preparePosts(res[i].Posts, true /*HandleReposts*/))
}
if nUpdates > 0 {
cp.stats.addUpdate(updateInfo{
time,
nUpdates,
})
}
}
}
func (cp *Crossposter) startCrossposting() {
batch := make([]vkReqData, 0, cp.batchSize)
for {
cp.ps.mu.RLock()
for id, pub := range cp.ps.pubToSub {
batch = append(batch, vkReqData{
id,
pub.lastPost,
})
if len(batch)%cp.batchSize == 0 {
cp.ps.mu.RUnlock()
cp.processBatch(batch)
time.Sleep(300 * time.Millisecond)
cp.ps.mu.RLock()
batch = batch[:0]
}
}
cp.ps.mu.RUnlock()
if len(batch) > 0 {
cp.processBatch(batch)
time.Sleep(300 * time.Millisecond)
batch = batch[:0]
}
select {
case <-cp.chDone:
return
case <-time.After(cp.updatePeriod):
continue
}
}
}