-
Notifications
You must be signed in to change notification settings - Fork 31
/
MastodonMgr.go
1413 lines (1275 loc) · 44.3 KB
/
MastodonMgr.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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// WebCall Copyright 2023 timur.mobi. All rights reserved.
package main
import (
"context"
"fmt"
"time"
"strings"
"strconv"
"errors"
"sync"
"io"
"os"
"net/http"
"math/rand"
"golang.org/x/net/html"
"github.com/mattn/go-mastodon"
"github.com/mehrvarz/webcall/skv"
"golang.org/x/crypto/bcrypt"
"encoding/gob"
"bytes"
bolt "go.etcd.io/bbolt"
)
var ErrTotalPostMsgQuota = errors.New("TotalPostMsgQuota")
var ErrUserPostMsgQuota = errors.New("PostMsgQuota per user")
var ErrConfigFormat = errors.New("Error config format")
var ErrAuthenticate = errors.New("Error Authenticate")
var ErrStreamingUser = errors.New("Error StreamingUser")
var ErrDb = errors.New("Error db")
const quotaMsgsPostedInLast30Min = 100
const quotaMsgsPostedPerUserInLast30Min = 5
const dbMastodon = "rtcmastodon.db"
const dbMid = "dbMid" // a map of all active mid's
type MidEntry struct { // key = mid
MastodonIdCallee string
Created int64
}
type PostMsgEvent struct {
calleeID string
timestamp time.Time
msgID mastodon.ID
}
type MastodonMgr struct {
c *mastodon.Client
hostUrl string
midMutex sync.RWMutex
kvMastodon skv.KV
postedMsgEventsSlice []*PostMsgEvent
postedMsgEventsMutex sync.RWMutex
running bool
ctx context.Context
cancel context.CancelFunc
}
func NewMastodonMgr() *MastodonMgr {
return &MastodonMgr{
//inviterMap: make(map[string]*Inviter),
//midMap: make(map[string]*MidEntry),
}
}
func (mMgr *MastodonMgr) mastodonInit() {
fmt.Print("mastodonInit Enter Mastodon target domain name: ")
var domainname string
_, err := fmt.Scanln(&domainname)
if err != nil {
fmt.Printf("# mastodonInit Scanln error: %v\n", err)
os.Exit(1)
}
fmt.Printf("Mastodon domain name: %s\n", domainname)
server := "https://"+domainname
srv, err := mastodon.RegisterApp(context.Background(), &mastodon.AppConfig{
Server: server,
ClientName: "WebCall-Telephony",
Scopes: "read write", // follow push",
RedirectURIs: "urn:ietf:wg:oauth:2.0:oob",
Website: "https://timur.mobi/webcall",
})
if err != nil {
fmt.Printf("# mastodonInit Couldn't register app. Error: %v\n", err)
os.Exit(1)
}
fmt.Println("Please autorize webcall to use your account.")
fmt.Println("Open browser with this URL:")
fmt.Printf("%s\n", srv.AuthURI)
var client *mastodon.Client
for {
fmt.Print("Enter authorization code: ")
var err error
var codeStr string
_, err = fmt.Scanln(&codeStr)
if err != nil {
fmt.Printf("# mastodonInit Scanln error: %v\n", err)
os.Exit(1)
}
//fmt.Printf("number of items read: %d\n", n)
fmt.Printf("authorization code: %s\n", codeStr)
fmt.Printf("ClientID: %s\n", srv.ClientID)
fmt.Printf("ClientSecret: %s\n", srv.ClientSecret)
client = mastodon.NewClient(&mastodon.Config{
Server: server,
ClientID: srv.ClientID,
ClientSecret: srv.ClientSecret,
})
err = client.AuthenticateToken(context.Background(), codeStr, "urn:ietf:wg:oauth:2.0:oob")
if err != nil {
fmt.Printf("# mastodonInit AuthenticateToken Error: %v\nTry again or press ^C.\n", err)
fmt.Println("--------------------------------------------------------------")
} else {
break
}
}
fmt.Printf("mastodonInit generated AccessToken=%s\n", client.Config.AccessToken)
me, err := client.GetAccountCurrentUser(context.Background())
if err != nil {
fmt.Printf("# mastodonInit Couldn't get user. Error: %v\n", err)
os.Exit(1)
}
fmt.Printf("mastodonInit account username=%s\n", me.Username)
//fmt.Printf("me=%v\n", me)
// generate + print config-key 'mastodonhandler'
// TODO store me.Username as 2nd arg (between domainname and client.Config.Server)
fmt.Printf("mastodonInit config.ini entry:\n")
fmt.Printf("mastodonhandler = %s|%s|%s|%s|%s\n",
domainname, client.Config.Server, client.Config.ClientID, client.Config.ClientSecret,
client.Config.AccessToken)
}
func (mMgr *MastodonMgr) mastodonStart(config string) error {
// only start if not already running
if mMgr.running {
fmt.Printf("# mastodonStart already running\n")
return nil
}
// config format: 'mastodon-domain|server-url|ClientID|ClientSecret|username|password'
tokSlice := strings.Split(config, "|")
if len(tokSlice)!=5 {
fmt.Printf("# mastodonStart config must have 5 tokens, has %d (%s)\n",len(tokSlice),config)
return ErrConfigFormat
}
fmt.Printf("mastodonStart (%s) ...\n",tokSlice[0])
// create mMgr.hostUrl
// note hostname and httpsPort are init config-vars, they do not changed at runtime
mMgr.hostUrl = "https://"+hostname
if httpsPort>0 {
mMgr.hostUrl += ":"+strconv.FormatInt(int64(httpsPort),10)
}
fmt.Printf("mastodonStart mMgr.hostUrl=(%s)\n",mMgr.hostUrl)
fmt.Printf("mastodonStart mastodon.NewClient (%s) (%s) (%s) (%s)\n",
tokSlice[1],tokSlice[2],tokSlice[3],tokSlice[4])
mMgr.c = mastodon.NewClient(&mastodon.Config{
Server: tokSlice[1],
ClientID: tokSlice[2],
ClientSecret: tokSlice[3],
AccessToken: tokSlice[4],
})
fmt.Printf("mastodonStart c.Config=(%s)\n",mMgr.c.Config)
mMgr.ctx, mMgr.cancel = context.WithCancel(context.Background())
fmt.Printf("mastodonStart authenticated\n")
chl,err := mMgr.c.StreamingUser(mMgr.ctx)
if err != nil {
fmt.Printf("# mastodonStart fail StreamingUser (%v)\n",err)
return err
}
if chl == nil {
fmt.Printf("# mastodonStart fail StreamingUser no chl\n")
return ErrStreamingUser
}
fmt.Printf("mastodonStart got StreamingUser\n")
mMgr.kvMastodon,err = skv.DbOpen(dbMastodon,dbPath)
if err!=nil {
fmt.Printf("# error DbOpen %s path %s err=%v\n",dbMastodon,dbPath,err)
return ErrDb
}
err = mMgr.kvMastodon.CreateBucket(dbMid)
if err!=nil {
fmt.Printf("# error db %s CreateBucket %s err=%v\n",dbMastodon,dbMid,err)
mMgr.kvMastodon.Close()
return ErrDb
}
mMgr.postedMsgEventsSlice = nil //[]PostMsgEvent
mMgr.running = true
go func() {
time.Sleep(5 * time.Second)
fmt.Printf("mastodonStart reading StreamingUser...\n")
for {
select {
case <-mMgr.ctx.Done():
fmt.Printf("mastodonhandler abort on context.Done\n")
mMgr.running = false
return
case evt := <-chl:
//fmt.Printf("mastodonhandler chl evt: %v\n",evt)
switch event := evt.(type) {
case *mastodon.NotificationEvent:
// direct msgs
fmt.Printf("* mastodonhandler Notif-Type=(%v) Acct=(%v)\n",
event.Notification.Type, event.Notification.Account.Acct)
// event.Notification.Type "mention" or "follow"
// Notification.Type=="follow" causes nil pointer panic on event.Notification.Status
if event.Notification.Type!="mention" {
continue
}
content := event.Notification.Status.Content
//fmt.Printf("mastodonhandler Content=(%v)\n",content)
// sample html-notification with textMessage ' setup':
//<p><span class="h-card"><a href="https://mastodon.social/@timurmobi" class="u-url mention" rel="nofollow noopener noreferrer" target="_blank">@<span>timurmobi</span></a></span> setup</p>
// to get the textMessage we first remove the <p> tag at start and end
// then we html-parse the remaining content and ignore all html-tages
if strings.HasPrefix(content,"<p>") {
content = content[3:]
if strings.HasSuffix(content,"</p>") {
content = content[0:len(content)-4]
}
//fmt.Printf("mastodonhandler stripped p Content=(%v)\n",content)
}
command := ""
htmlTokens := html.NewTokenizer(strings.NewReader(content))
depth := 0
loop:
for {
tt := htmlTokens.Next()
switch tt {
case html.StartTagToken:
//t := htmlTokens.Token()
//fmt.Println("StartTagToken",t.Data)
depth++
case html.EndTagToken:
//t := htmlTokens.Token()
//fmt.Println("EndTagToken",t.Data)
depth--
case html.TextToken:
if depth==0 {
t := htmlTokens.Token()
textMessage := t.Data
if textMessage!="" {
fmt.Printf("mastodonhandler TextToken=(%v)\n",textMessage) // ' test2'
command += textMessage + " "
}
break
}
case html.ErrorToken:
//fmt.Printf("mastodonhandler ErrorToken re-loop\n")
break loop
}
}
//fmt.Printf("mastodonhandler Notif-Type=(%v) done\n", event.Notification.Type)
mMgr.processMessage(command,event,tokSlice[0])
//case *mastodon.UpdateEvent:
// // none-direct msgs
// if event.Status.Content!="" {
// fmt.Printf("mastodonhandler UpdateEvent content=(%v)\n",event.Status.Content)
// } else {
// fmt.Printf("mastodonhandler UpdateEvent reblog=(%v)\n",event.Status.Reblog)
// }
case *mastodon.DeleteEvent:
// interesting: when an inviter deletes his 'please reply' msg
// webcall gets a notification here (or maybe I misunderstood something)
fmt.Printf("mastodonhandler DeleteEvent id=(%v)\n",event.ID)
case *mastodon.ErrorEvent:
fmt.Printf("# mastodonhandler ErrorEvent '%v'\n",event.Error())
if !mMgr.running {
break
}
if strings.Index(event.Error(),"404 Not Found")>=0 ||
strings.Index(event.Error(),"403 Forbidden")>=0 ||
strings.Index(event.Error(),"503 Service Unavailable")>=0 ||
strings.Index(event.Error(),"unknown authority")>=0 ||
strings.Index(event.Error(),"Internal Server Error")>=0 ||
strings.Index(event.Error(),"INTERNAL_ERROR")>=0 {
// slow down
time.Sleep(15 * time.Second)
} else if strings.Index(event.Error(),"Invalid access token")>=0 {
// "bad request: 401 Unauthorized: Error: Invalid access token"
} else if strings.Index(event.Error(),"GOAWAY")>=0 {
// "http2: server sent GOAWAY and closed the connection..."
// looks like reconnects happens automatically
}
// "stream error: stream ID (int); INTERNAL_ERROR; received from peer"
// stream error: stream ID 1; INTERNAL_ERROR; received from peer'
// "bad request: 502 Bad Gateway"
// "Get "https://streaming.mastodon.social/api/v1/streaming/user": EOF" x
// "Get "https://streaming.mastodon.social/api/v1/streaming/user": read tcp [2600:3c03::f03c:91ff:fea0:a854]:46208->[2a01:4f8:c01e:e5::1]:443: read: connection reset by peer"
// "unexpected EOF"
// slow down
time.Sleep(5 * time.Second)
if !mMgr.running {
break
}
//default:
// fmt.Printf("mastodonhandler default\n")
}
}
}
mMgr.running = false
}()
return nil
}
func (mMgr *MastodonMgr) dbSync() {
// called by timer.go callBackupScript()
if mMgr.kvMastodon!=nil {
kv := mMgr.kvMastodon.(skv.SKV)
if err := kv.Db.Sync(); err != nil {
fmt.Printf("# mastodon dbSync error: %s\n", err)
}
}
}
func (mMgr *MastodonMgr) processMessage(msg string, event *mastodon.NotificationEvent, domainName string) {
msg = strings.TrimSpace(msg)
mastodonUserId := event.Notification.Account.Acct // from
if strings.Index(mastodonUserId,"@")<0 {
// this notif was sent by a user on "our" instance
mastodonUserId += "@"+domainName
}
msgID := fmt.Sprint(event.Notification.Status.ID)
if msgID=="" || msgID == "<nil>" {
// can't work without a msgID
fmt.Printf("# mastodon processMessage empty event.Notification.Status.ID\n")
return
}
inReplyToID := fmt.Sprint(event.Notification.Status.InReplyToID)
if inReplyToID == "<nil>" { inReplyToID = "" }
tok := strings.Split(msg, " ")
fmt.Printf("mastodon processMessage msg=(%v) msgId=%v InReplyToID=%v RecipientCount=%d lenTok=%d\n",
msg, msgID, inReplyToID, -1, len(tok))
if len(tok)>0 {
command := strings.ToLower(strings.TrimSpace(tok[0]))
switch {
case command=="setup":
fmt.Printf("mastodon command setup (%v)\n", mastodonUserId)
mMgr.commandSetup(mastodonUserId,true)
return
case command=="remove":
// here we delete the webcall id specified in mastodonUserId
fmt.Printf("mastodon command remove (%v)\n", mastodonUserId)
// TODO user needs to first enable command 'remove' in the web-app
mMgr.commandRemove(mastodonUserId,true)
return
case command=="ping":
// send pong msg back with 20s delay
sendmsg :="@"+mastodonUserId+" pong"
fmt.Printf("mastodon command pong reply (%s)\n",sendmsg)
mMgr.postMsgEx(sendmsg,mastodonUserId,20,func(err error) {
if err!=nil {
fmt.Printf("# mastodon command pong reply err=%v (to=%v)\n",err,mastodonUserId)
} else {
fmt.Printf("mastodon command pong reply to=%v\n", mastodonUserId)
}
})
return
}
}
}
func (mMgr *MastodonMgr) commandSetup(mastodonUserId string, postback bool) {
mappingMutex.RLock()
mappingData,ok := mapping[mastodonUserId]
mappingMutex.RUnlock()
if ok {
// if mastodonUserId is already an alt-ID, then sending a register-link is useless
fmt.Printf("mastodon command setup (%s) already associated with (%s)\n",
mastodonUserId,mappingData.CalleeId)
if postback {
sendmsg :="@"+mastodonUserId+" is already associated"
fmt.Printf("mastodon command setup post (%s)\n",sendmsg)
mMgr.postMsgEx(sendmsg, mastodonUserId, 0, func(err error) {
if err!=nil {
fmt.Printf("# mastodon command setup post err=%v (to=%v)\n",err,mastodonUserId)
} else {
fmt.Printf("mastodon command setup post sent to=%v\n", mastodonUserId)
}
})
}
return
}
// now check for main-id
var dbEntry DbEntry
var dbUser DbUser
err := kvMain.Get(dbRegisteredIDs, mastodonUserId, &dbEntry)
if err != nil {
if strings.Index(err.Error(), "skv key not found") < 0 {
// some other error
fmt.Printf("# mastodon command setup get dbRegisteredID %s err=%v\n",mastodonUserId,err)
return
}
// this is good: key not found
} else {
// dbRegisteredIDs key was found
dbUserKey := fmt.Sprintf("%s_%d", mastodonUserId, dbEntry.StartTime)
err = kvMain.Get(dbUserBucket, dbUserKey, &dbUser)
if err != nil {
if strings.Index(err.Error(), "skv key not found") < 0 {
// some other error
fmt.Printf("# mastodon command setup get dbUserBucket %s err=%v\n",mastodonUserId,err)
return
}
// TODO this is good? key not found
} else {
// key exists
sendmsg :="@"+mastodonUserId+" user exists"
fmt.Printf("mastodon command setup (%s)\n",sendmsg)
if postback {
mMgr.postMsgEx(sendmsg, mastodonUserId, 0, func(err error) {
if err!=nil {
fmt.Printf("# mastodon command setup2 post err=%v (to=%v)\n",err,mastodonUserId)
} else {
fmt.Printf("mastodon command setup2 post sent to=%v\n", mastodonUserId)
}
})
}
return
}
}
// mastodonUserId is not yet being used
// NOTE: msg1 must end with a blank
msg1 := "Setup your WebCall ID: "
// NOTE: msg2 must start with a blank
msg2 := "" //" (active for 20 minutes)" // see "20*60" in cleanupMastodonMidMap()
// arg2: no callerID to notify after callee-login
// arg4: no msgID to notify after callee-login
err = mMgr.offerRegisterLink(mastodonUserId, "", msg1, msg2, "", "/callee/mastodon/setup", postback)
if err!=nil {
fmt.Printf("# mastodon processMessage offerRegisterLink err=%v\n",err)
// post msg telling user that request has failed
// what makes responding here difficult is that offerRegisterLink() may fail on different things:
// create secret, error on kvMastodon.Put(dbMid/dbInviter/dbCid), error on postMsgEx()
sendmsg :="@"+mastodonUserId+" sorry, I am not able to proceed with your request"
mMgr.postMsgEx(sendmsg, mastodonUserId, 0, func(err error) {
if err!=nil {
fmt.Printf("# mastodon processMessage offerRegisterLink post (%s) failed %v\n",sendmsg,err)
} else {
fmt.Printf("mastodon processMessage offerRegisterLink posted (%s)\n",sendmsg)
}
})
}
}
func (mMgr *MastodonMgr) commandRemove(mastodonUserId string, postback bool) {
// first check mapping[]
mappingMutex.RLock()
mappingData,ok := mapping[mastodonUserId]
mappingMutex.RUnlock()
if ok {
var err error
fmt.Printf("mastodon command remove: found mapping %s->%s\n",
mastodonUserId, mappingData.CalleeId)
if mappingData.CalleeId!="" && mappingData.CalleeId!=mastodonUserId {
// this is a calleeID with an (associated) alt-id
mappingMutex.Lock()
delete(mapping,mastodonUserId)
mappingMutex.Unlock()
// remove alt-id from mappingData.CalleeId
err = mMgr.storeAltId(mappingData.CalleeId, "", "")
if postback {
sendmsg :="@"+mastodonUserId+" on your request your ID has been deactivated"
if err!=nil {
// post msg telling user that remove has failed
sendmsg ="@"+mastodonUserId+" sorry, I am unable to proceed with your request"
}
mMgr.postMsgEx(sendmsg, mastodonUserId, 0, func(err error) {
if err!=nil {
fmt.Printf("# mastodon command remove: post (%s) failed (%v)\n",sendmsg,err)
} else {
fmt.Printf("mastodon command remove: (%s) posted\n",sendmsg)
}
})
}
// do NOT delete the user account of mappingData.CalleeId
// end processMessage here
return
}
// TODO must check this
// fall through
}
// now check for main-id
var dbEntryRegistered DbEntry
err := kvMain.Get(dbRegisteredIDs,mastodonUserId,&dbEntryRegistered)
if err!=nil {
if strings.Index(err.Error(),"key not found")>0 {
fmt.Printf("# mastodon command remove user=%s err=%v\n", mastodonUserId, err)
}
// ignore! no need to notify user by msg (looks like an invalid request)
} else {
// mastodonUserId is a registered calleeID
// if user is currently online / logged-in as callee
hubMapMutex.RLock()
hub := hubMap[mastodonUserId]
hubMapMutex.RUnlock()
if hub != nil {
// disconnect online callee user
hub.closeCallee("unregister") // -> hub.exitFunc()
// new callee.js will delete cookie on "User ID unknown"
}
dbUserKey := fmt.Sprintf("%s_%d", mastodonUserId, dbEntryRegistered.StartTime)
// delete/outdate mapped tmpIDs of outdated mastodonUserId
errcode,altIDs := getMapping(mastodonUserId,"")
if errcode==0 && altIDs!="" {
tokenSlice := strings.Split(altIDs, "|")
for _, tok := range tokenSlice {
deleteMapping(mastodonUserId,tok,"")
}
}
// also delete mastodonUserId's contacts
err = kvContacts.Delete(dbContactsBucket, mastodonUserId)
if err!=nil {
fmt.Printf("# mastodon command remove contacts of id=%s err=%v\n",
mastodonUserId, err)
// not fatal
}
kv := kvMain.(skv.SKV)
err = kv.Delete(dbUserBucket, dbUserKey)
if err!=nil {
// this is fatal
fmt.Printf("# mastodon command remove user-key=%s err=%v\n", dbUserKey, err)
} else {
fmt.Printf("mastodon command remove user-key=%s done\n", dbUserKey)
err = kvMain.Delete(dbRegisteredIDs, mastodonUserId)
if err!=nil {
// this is fatal
fmt.Printf("# mastodon command remove user-id=%s err=%v\n", mastodonUserId, err)
} else {
fmt.Printf("mastodon command remove user-id=%s done\n", mastodonUserId)
}
}
if err!=nil {
if postback {
// send msg telling user that remove has failed
sendmsg :="@"+mastodonUserId+" sorry, I am not able to proceed with your request"
mMgr.postMsgEx(sendmsg, mastodonUserId, 0, func(err error) {
if err!=nil {
fmt.Printf("# mastodon command remove: post (%s) failed (%v)\n",sendmsg,err)
} else {
fmt.Printf("mastodon command remove: posted (%s)\n",sendmsg)
}
})
}
return
}
// dbUser has been deactivated
// TODO NOTE: callee-user may still be online
// send msg telling user that their webcall account has been deactivated
if postback {
sendmsg :="@"+mastodonUserId+" on your request your ID has been deleted"
mMgr.postMsgEx(sendmsg, mastodonUserId, 0, func(err error) {
if err!=nil {
fmt.Printf("# mastodon command remove: post (%s) failed (%v)\n",sendmsg,err)
} else {
fmt.Printf("mastodon command remove: posted (%s)\n",sendmsg)
}
})
}
// also delete missed calls
var missedCallsSlice []CallerInfo
err = kvCalls.Put(dbMissedCalls, mastodonUserId, missedCallsSlice, false)
if err!=nil {
fmt.Printf("# mastodon command remove (%s) fail store dbMissedCalls\n", mastodonUserId)
// not fatal
}
// also delete HashedPw
err = kvHashedPw.Delete(dbHashedPwBucket, mastodonUserId)
if err!=nil {
fmt.Printf("# mastodon command remove (%s) fail delete hashedPw\n", mastodonUserId)
// not fatal
}
}
// end processMessage here
}
func (mMgr *MastodonMgr) offerRegisterLink(mastodonUserId string, mastodonCallerUserId string, msg1 string, msg2 string, msgID string, path string, postback bool) error {
// offer link to /pickup, with which mastodonUserId can be registered
// first we need a unique mID (refering to mastodonUserId)
//TODO we could check right here if mastodonUserId is already given
// like in httpGetMidUser()
// hubMapMutex.RLock()
// hub := hubMap[mastodonUserId]
// hubMapMutex.RUnlock()
// if hub!=nil {
mMgr.midMutex.Lock()
mID,err := mMgr.makeSecretID() //"xxxxxxxxxxx"
if err!=nil {
// this is fatal
mMgr.midMutex.Unlock()
fmt.Printf("# offerRegisterLink register makeSecretID err=(%v)\n", err)
return err
}
midEntry := &MidEntry{}
midEntry.MastodonIdCallee = mastodonUserId
midEntry.Created = time.Now().Unix()
if mMgr.kvMastodon==nil {
fmt.Printf("# offerRegisterLink mMgr.kvMastodon==nil\n")
return errors.New("no mMgr.kvMastodon")
}
err = mMgr.kvMastodon.Put(dbMid, mID, midEntry, false)
if err != nil {
fmt.Printf("# offerRegisterLink mID=%v failed to store midEntry\n", mID)
return err
}
mMgr.midMutex.Unlock()
sendmsg :="@"+mastodonUserId+" " + msg1 + mMgr.hostUrl + path + "?mid=" + mID + msg2
fmt.Printf("offerRegisterLink PostStatus (%s)\n",sendmsg)
if postback {
mMgr.postMsgEx(sendmsg, mastodonUserId, 0, func(err error) {
if err!=nil {
fmt.Printf("# offerRegisterLink post err=%v (to=%v)\n",err,mastodonUserId)
// TODO unfortunately we can't inform the user of this problem
} else {
fmt.Printf("offerRegisterLink posted to=%v\n", mastodonUserId)
}
})
}
return nil
}
func (mMgr *MastodonMgr) makeSecretID() (string,error) {
// called by offerRegisterLink()
// mMgr.midMutex must be locked outside
tries := 0
for {
tries++
intID := uint64(rand.Int63n(int64(99999999999)))
if(intID<uint64(10000000000)) {
continue;
}
newSecretId := strconv.FormatInt(int64(intID),10)
if mMgr.kvMastodon==nil {
fmt.Printf("# offerRegisterLink mMgr.kvMastodon==nil\n")
return "",errors.New("no mMgr.kvMastodon")
}
midEntry := &MidEntry{}
err := mMgr.kvMastodon.Get(dbMid, newSecretId, midEntry)
if err == nil {
// already taken
continue;
}
if tries>=10 {
fmt.Printf("# secretID (%s) tries=%d\n", newSecretId, tries)
return "",errors.New("failed to create unique newSecretId")
}
return newSecretId,nil
}
}
func (mMgr *MastodonMgr) postMsgEx(sendmsg string, onBehalfOfUser string, delaySecs int, callback func(error)) error {
fmt.Printf("postMsgEx PostStatus (%s)\n",sendmsg)
mMgr.cleanupPostedMsgEvents(nil)
// TODO move constants 100 and 5 (per 30m) to top
// rate limit total number of posted msgs (100 per 30min)
msgsPostedTotalInLast30Min := len(mMgr.postedMsgEventsSlice)
if msgsPostedTotalInLast30Min >= quotaMsgsPostedInLast30Min {
fmt.Printf("# postMsgEx quota # of msgs posted in the last 30min %d >= %d\n",
msgsPostedTotalInLast30Min, quotaMsgsPostedInLast30Min)
if callback!=nil { callback(ErrTotalPostMsgQuota) }
return ErrTotalPostMsgQuota
}
// rate limit # of msgs posted onBehalfOfUser (5 per 30min)
mMgr.postedMsgEventsMutex.RLock()
msgsPostedInLast30Min := 0
for _,postedMsgEvent := range mMgr.postedMsgEventsSlice {
if postedMsgEvent.calleeID == onBehalfOfUser {
msgsPostedInLast30Min++
}
}
mMgr.postedMsgEventsMutex.RUnlock()
if msgsPostedInLast30Min >= quotaMsgsPostedPerUserInLast30Min {
fmt.Printf("# postMsgEx quota # of msgs posted for %s in the last 30min %d >= %d\n",
onBehalfOfUser, msgsPostedInLast30Min, quotaMsgsPostedPerUserInLast30Min)
if callback!=nil { callback(ErrUserPostMsgQuota) }
return ErrUserPostMsgQuota
}
mMgr.postedMsgEventsMutex.Lock()
postMsgEvent := PostMsgEvent{onBehalfOfUser,time.Now(),""}
mMgr.postedMsgEventsSlice = append(mMgr.postedMsgEventsSlice,&postMsgEvent)
mMgr.postedMsgEventsMutex.Unlock()
go func() {
if delaySecs>0 {
time.Sleep(time.Duration(delaySecs) * time.Second)
}
// NOTE PostStatus() stalls until msg is sent, which can take a random amount of time (say 27s)
status,err := mMgr.c.PostStatus(mMgr.ctx, &mastodon.Toot{
Status: sendmsg,
Visibility: "direct",
})
if err!=nil {
fmt.Printf("# postMsgEx PostStatus err=%v\n",err)
} else {
fmt.Printf("postMsgEx PostStatus sent id=%v (last 30min: total=%d, for%s=%d)\n",
status.ID, msgsPostedTotalInLast30Min, onBehalfOfUser, msgsPostedInLast30Min)
postMsgEvent.msgID = status.ID
}
if callback!=nil { callback(err) }
}()
return nil
}
func (mMgr *MastodonMgr) httpGetMidUser(w http.ResponseWriter, r *http.Request, cookie *http.Cookie, remoteAddr string) {
// /getmiduser
fmt.Printf("httpGetMidUser...\n")
url_arg_array, ok := r.URL.Query()["mid"]
if !ok {
fmt.Printf("# httpGetMidUser fail URL.Query mid\n")
return
}
if len(url_arg_array[0]) < 1 {
fmt.Printf("# httpGetMidUser len(url_arg_array[0])<1 (%v)\n",url_arg_array)
return
}
mid := url_arg_array[0]
fmt.Printf("httpGetMidUser mid=%s\n",mid)
if(mid=="") {
// no mid given
fmt.Printf("# httpGetMidUser no mid=%v ip=%v\n",mid,remoteAddr)
return
}
//fmt.Printf("httpGetMidUser mid=%s ip=%v\n",mid,remoteAddr)
cid := ""
url_arg_array, ok = r.URL.Query()["cid"]
if ok && len(url_arg_array[0]) >= 1 {
cid = url_arg_array[0]
}
fmt.Printf("httpGetMidUser mid=%s cid=%s ip=%v\n",mid,cid,remoteAddr)
calleeIdOnMastodon := ""
midEntry := &MidEntry{}
err := mMgr.kvMastodon.Get(dbMid, mid, midEntry)
if err != nil {
fmt.Printf("! httpGetMidUser invalid or outdated mid=%s err=%v\n",mid,err)
return
}
calleeIdOnMastodon = midEntry.MastodonIdCallee
fmt.Printf("httpGetMidUser get midEntry mid=%s calleeIdOnMastodon=%s ok\n",mid,calleeIdOnMastodon)
isValidCalleeID := "false"
isOnlineCalleeID := "false"
wsCliMastodonID := ""
calleeID := ""
if(calleeIdOnMastodon=="") {
// given mid is invalid
fmt.Printf("! httpGetMidUser invalid or outdated mid=%s calleeIdOnMastodon=%v ip=%v\n",
mid,calleeIdOnMastodon,remoteAddr)
return
}
// calleeIdOnMastodon is set, therefor: mid is valid
// let's see if calleeIdOnMastodon is mapped to a 11-digit calleeID
fmt.Printf("httpGetMidUser mid=%s calleeIdOnMastodon=%v ip=%v\n",
mid, calleeIdOnMastodon, remoteAddr)
calleeID = calleeIdOnMastodon
mappingMutex.RLock()
mappingData,ok := mapping[calleeIdOnMastodon]
mappingMutex.RUnlock()
if ok {
fmt.Printf("httpGetMidUser calleeIdOnMastodon=%v is mapped %s\n",calleeIdOnMastodon,mappingData.CalleeId)
isValidCalleeID = "true"
if mappingData.CalleeId!="" {
// calleeIdOnMastodon is mapped to a 11-digit calleeID
calleeID = mappingData.CalleeId
fmt.Printf("httpGetMidUser mapped calleeID=%s calleeIdOnMastodon=%v ip=%v\n",
calleeID,calleeIdOnMastodon,remoteAddr)
}
}
// lets see if calleeID is online (or at least a valid account)
hubMapMutex.RLock()
hub := hubMap[calleeID]
hubMapMutex.RUnlock()
if hub!=nil {
// calleeID is online (so it is valid)
isOnlineCalleeID = "true"
isValidCalleeID = "true"
if hub.CalleeClient!=nil {
// hub.CalleeClient.mastodonID is set by registerID in /registermid (httpRegisterMid())
wsCliMastodonID = hub.CalleeClient.mastodonID
}
} else {
// no hub currently exists: calleeID is NOT online: check if calleeID is a valid account
if isValidCalleeID!="true" {
dbUser := mMgr.isValidCallee(calleeID)
if dbUser!=nil {
// calleeID is NOT online, but account is valid
isValidCalleeID = "true"
wsCliMastodonID = dbUser.MastodonID
}
}
}
cMastodonID := ""
cMastodonIDOnline := ""
if cid!="" {
cdbUser := mMgr.isValidCallee(cid)
if cdbUser!=nil {
// cid account is valid
cMastodonID = cdbUser.MastodonID
hubMapMutex.RLock()
hub := hubMap[cMastodonID]
hubMapMutex.RUnlock()
if hub!=nil {
cMastodonIDOnline = "true"
}
}
}
// NOTE: calleeID may be same as calleeIdOnMastodon, or may be a 11-digit ID
// NOTE: wsCliMastodonID may be calleeIdOnMastodon or empty string
codedString := calleeIdOnMastodon+"|"+isValidCalleeID+"|"+isOnlineCalleeID+"|"+
calleeID+"|"+wsCliMastodonID+"||"+cMastodonID+"|"+cMastodonIDOnline
fmt.Printf("httpGetMidUser codedString=%v\n",codedString)
fmt.Fprintf(w,codedString)
return
}
func (mMgr *MastodonMgr) isValidCallee(calleeID string) *DbUser {
var dbEntry DbEntry
mappingMutex.RLock()
mappingData,ok := mapping[calleeID]
mappingMutex.RUnlock()
if ok && mappingData.CalleeId != "" {
// calleeID found in mapping[] and mappingData.CalleeId is set
// this means: calleeID is a mastodon or a mapping ID, and mappingData.CalleeId the 11-digit ID
fmt.Printf("isValidCallee(%s) used for mapping\n",calleeID)
var dbUser = &DbUser{}
dbUser.MastodonID = calleeID
return dbUser
}
fmt.Printf("isValidCallee(%s) NOT used for mapping\n",calleeID)
err := kvMain.Get(dbRegisteredIDs, calleeID, &dbEntry)
if err != nil {
if strings.Index(err.Error(),"key not found")>0 {
// this is not an error
fmt.Printf("isValidCallee(%s) NOT used as main id\n",calleeID)
} else {
fmt.Printf("# isValidCallee(%s) dbEntry err=%v\n",calleeID,err)
}
} else {
dbUserKey := fmt.Sprintf("%s_%d", calleeID, dbEntry.StartTime)
var dbUser DbUser
err = kvMain.Get(dbUserBucket, dbUserKey, &dbUser)
if err != nil {
// no error: account does not (yet) exist or was deleted
//fmt.Printf("# isValidCallee(%s) dbUser err=%v\n",calleeID,err)
} else {
// calleeID has a valid account
return &dbUser
}
}
return nil
}
func (mMgr *MastodonMgr) storeAltId(calleeID string, mastodonUserID string, remoteAddr string) error {
// set mastodonUserID as alt-id for calleeID (11-digit)
// - store mastodonUserID in dbUser and in mapping[]
// - so 11-digit ID does not need to be entered again next time a mastodon call request comes in
// called by httpStoreAltID(), sendCallerLink(), command=="remove" (with mastodonUserID=="")
var dbEntry DbEntry
err := kvMain.Get(dbRegisteredIDs,calleeID,&dbEntry)
if err!=nil {
// calleeID was not yet registered
fmt.Printf("# storeAltId numeric(%s) fail db=%s bucket=%s not yet registered\n",
calleeID, dbMainName, dbRegisteredIDs)
return err
}
dbUserKey := fmt.Sprintf("%s_%d",calleeID, dbEntry.StartTime)
var dbUser DbUser
err = kvMain.Get(dbUserBucket, dbUserKey, &dbUser)
if err!=nil {
fmt.Printf("# storeAltId numeric(%s) fail on dbUserBucket ip=%s\n", calleeID, remoteAddr)
return err
}
if mastodonUserID=="" {
// remove AltId: only clear dbUser.MastodonID
dbUser.MastodonID = mastodonUserID
dbUser.MastodonSendTootOnCall = false
dbUser.AskCallerBeforeNotify = false
} else {
// create AltId
if dbUser.MastodonID!="" && dbUser.MastodonID!=mastodonUserID {
// SUSPICIOUS?
fmt.Printf("! storeAltId numeric(%s) dbUser.MastodonID=%s != mastodonUserID=%s\n",
calleeID, dbUser.MastodonID, mastodonUserID)
}
dbUser.MastodonID = mastodonUserID
dbUser.MastodonSendTootOnCall = false
dbUser.AskCallerBeforeNotify = false
// if mapping[mastodonUserID] != calleeID, set it
oldCalleeID := ""
mappingMutex.Lock()
mappingData,ok := mapping[mastodonUserID]
if ok {
oldCalleeID = mappingData.CalleeId
}
mapping[mastodonUserID] = MappingDataType{calleeID,"none"}
mappingMutex.Unlock()
if oldCalleeID!="" && oldCalleeID!=calleeID {
// this happens if CalleeId=mastodonID and calleeID=11-digits
// ! storeAltId mapping[[email protected]] != calleeID=19325349797
fmt.Printf("! storeAltId mapping[%s]=%s != calleeID=%s (add)\n",
mastodonUserID, oldCalleeID, calleeID)
// IMPORTANT: in dbUser of oldCalleeID: clear mastodonID
mMgr.storeAltId(oldCalleeID,"",remoteAddr)
}
}
err = kvMain.Put(dbUserBucket, dbUserKey, dbUser, false)
if err!=nil {
// fatal very bad
fmt.Printf("# storeAltId numeric(%s) error db=%s bucket=%s put err=%v\n",
calleeID,dbMainName,dbRegisteredIDs,err)
return err
}
fmt.Printf("storeAltId numeric(%s) stored mastodonUserID=%s\n",
calleeID, mastodonUserID)
return nil
}
func (mMgr *MastodonMgr) httpStoreAltID(w http.ResponseWriter, r *http.Request, urlPath string, remoteAddr string, startRequestTime time.Time) {
// called by http /storealtid/
mID := urlPath[12:] // length if '/storealtid/'
argIdx := strings.Index(mID,"?")
if argIdx>=0 {
mID = mID[0:argIdx]