-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtrello.go
2472 lines (2034 loc) · 62.8 KB
/
trello.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
package trello
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"time"
"gopkg.in/mgo.v2/bson"
"net/http"
"net/url"
iurl "github.com/requilence/url"
"regexp"
log "github.com/sirupsen/logrus"
"bytes"
"io"
"mime/multipart"
"os"
"path/filepath"
t "github.com/integram-org/trello/api"
"github.com/jinzhu/now"
"github.com/mrjones/oauth"
"github.com/requilence/integram"
"github.com/requilence/decent"
tg "github.com/requilence/telegram-bot-api"
)
var m = integram.HTMLRichText{}
// Config contains OAuthProvider
type Config struct {
integram.OAuthProvider
integram.BotConfig
}
var defaultBoardFilter = ChatBoardFilterSettings{CardCreated: true, CardCommented: true, CardMoved: true, PersonAssigned: true, Archived: true, Due: true}
const markSign = "✅ "
const dueDateFormat = "02.01 15:04"
const dueDateFullFormat = "02.01.2006 15:04"
const cardMemberStateUnassigned = 0
const cardMemberStateAssigned = 1
const cardLabelStateUnattached = 0
const cardLabelStateAttached = 1
// Service returns *integram.Service from trello.Config
func (cfg Config) Service() *integram.Service {
return &integram.Service{
Name: "trello",
NameToPrint: "Trello",
DefaultOAuth1: &integram.DefaultOAuth1{
Key: cfg.OAuthProvider.ID,
Secret: cfg.OAuthProvider.Secret,
RequestTokenURL: "https://trello.com/1/OAuthGetRequestToken",
AuthorizeTokenURL: "https://trello.com/1/OAuthAuthorizeToken",
AccessTokenURL: "https://trello.com/1/OAuthGetAccessToken",
AdditionalAuthorizationURLParams: map[string]string{
"name": "Integram",
"expiration": "never",
"scope": "read,write",
},
AccessTokenReceiver: accessTokenReceiver,
},
JobsPool: 10,
Jobs: []integram.Job{
{sendBoardsToIntegrate, 10, integram.JobRetryFibonacci},
{sendBoardsForCard, 10, integram.JobRetryFibonacci},
{subscribeBoard, 10, integram.JobRetryFibonacci},
{cacheAllCards, 1, integram.JobRetryFibonacci},
{commentCard, 10, integram.JobRetryFibonacci},
{downloadAttachment, 10, integram.JobRetryFibonacci},
{removeFile, 1, integram.JobRetryFibonacci},
{attachFileToCard, 3, integram.JobRetryFibonacci},
{resubscribeAllBoards, 1, integram.JobRetryFibonacci},
},
Actions: []interface{}{
boardToIntegrateSelected,
boardForCardSelected,
listForCardSelected,
textForCardEntered,
targetChatSelected,
cardReplied,
commentCard,
attachFileToCard,
afterBoardIntegratedActionSelected,
// afterCardCreatedActionSelected,
sendBoardFiltersKeyboard,
boardFilterButtonPressed,
сardDueDateEntered,
inlineCardButtonPressed,
сardDescEntered,
сardNameEntered,
},
TGNewMessageHandler: newMessageHandler,
TGInlineQueryHandler: inlineQueryHandler,
TGChosenInlineResultHandler: chosenInlineResultHandler,
WebhookHandler: webhookHandler,
OAuthSuccessful: oAuthSuccessful,
}
}
// ChatSettings contains filters information
type ChatSettings struct {
Boards map[string]ChatBoardSetting
}
// UserSettings contains boards data and target chats to deliver notifications
type UserSettings struct {
//Boards settings by ID
Boards map[string]UserBoardSetting
// Chat from which integration request is received
TargetChat *integram.Chat
}
// ChatBoardFilterSettings customize which events will produce messages
type ChatBoardFilterSettings struct {
CardCreated bool
CardCommented bool
CardMoved bool
PersonAssigned bool
Labeled bool
Voted bool
Archived bool
Checklisted bool
Due bool
}
// ChatBoardSetting contains Trello board settings
type ChatBoardSetting struct {
Name string // Board name
Enabled bool // Enable notifications on that board
Filter ChatBoardFilterSettings
OAuthToken string // backward compatibility for some of migrated from v1 users
TrelloWebhookID string // backward compatibility for some of migrated from v1 users
User int64 // ID of User who integrate this board into this Chat
}
// UserBoardSetting contains Trello board settings
type UserBoardSetting struct {
Name string // Board name
TrelloWebhookID string // Trello Webhook id
OAuthToken string // To avoid stuck webhook when OAUthToken was changed. Because Webhook relates to token, not to App
}
func userSettings(c *integram.Context) UserSettings {
s := UserSettings{}
c.User.Settings(&s)
return s
}
func chatSettings(c *integram.Context) ChatSettings {
s := ChatSettings{}
c.Chat.Settings(&s)
return s
}
type webhookInfo struct {
ID string
DateCreated time.Time
DateExpires time.Time
IDMember string
IDModel string
CallbackURL string
}
func oAuthSuccessful(c *integram.Context) error {
var err error
b := false
if c.User.Cache("auth_redirect", &b) {
err = c.NewMessage().SetText("Great! Now you can use reply-to-comment and inline buttons 🙌 You can return to your group").Send()
} else {
_, err = c.Service().DoJob(sendBoardsToIntegrate, c)
}
if err != nil {
return err
}
err = resubscribeAllBoards(c)
return err
}
func accessTokenReceiver(c *integram.Context, r *http.Request, requestToken *oauth.RequestToken) (token string, err error) {
values := r.URL.Query()
verificationCode := values.Get("oauth_verifier")
accessToken, err := c.OAuthProvider().OAuth1Client(c).AuthorizeToken(requestToken, verificationCode)
if err != nil || accessToken == nil {
c.Log().Error(err)
return "", err
}
return accessToken.Token, err
}
func api(c *integram.Context) *t.Client {
token := c.User.OAuthToken()
if token == "" {
cs := chatSettings(c)
//todo: bad workaround to handle some chats from v1
if len(cs.Boards) > 0 {
for _, board := range cs.Boards {
if board.User == 0 && board.OAuthToken != "" {
token = board.OAuthToken
}
}
}
}
return t.New(c.Service().DefaultOAuth1.Key, c.Service().DefaultOAuth1.Secret, token)
}
func me(c *integram.Context, api *t.Client) (*t.Member, error) {
me := &t.Member{}
if exists := c.User.Cache("me", me); exists {
return me, nil
}
var err error
me, err = api.Member("me")
if t.IsBadToken(err) {
c.User.ResetOAuthToken()
}
if err != nil {
c.Log().WithError(err).Error("Can't get me member")
return nil, err
}
c.User.SetCache("me", me, time.Hour)
c.SetServiceCache("nick_map_"+me.Username, c.User.UserName, time.Hour*24*365)
return me, nil
}
func getBoardData(c *integram.Context, api *t.Client, boardID string) ([]*t.List, []*t.Member, []*t.Label, error) {
var boardData struct {
Lists []*t.List
Members []*t.Member
Labels []*t.Label
}
b, err := api.Request("GET", "boards/"+boardID, nil, url.Values{"lists": {"open"}, "lists_fields": {"name"}, "members": {"all"}, "labels": {"all"}, "member_fields": {"fullName,username"}})
if t.IsBadToken(err) {
c.User.ResetOAuthToken()
}
if err != nil {
return nil, nil, nil, err
}
err = json.Unmarshal(b, &boardData)
if err != nil {
c.Log().WithField("id", boardID).WithError(err).Error("Can't get board lists")
return nil, nil, nil, err
}
err = c.SetServiceCache("lists_"+boardID, boardData.Lists, time.Hour*6)
err = c.SetServiceCache("members_"+boardID, boardData.Members, time.Hour*24*7)
err = c.SetServiceCache("labels_"+boardID, boardData.Labels, time.Hour*24*7)
if err != nil {
c.Log().WithError(err).Error("Can't save to cache")
return nil, nil, nil, err
}
return boardData.Lists, boardData.Members, boardData.Labels, nil
}
func listsByBoardID(c *integram.Context, api *t.Client, boardID string) ([]*t.List, error) {
var lists []*t.List
if exists := c.ServiceCache("lists_"+boardID, &lists); exists {
return lists, nil
}
var err error
lists, _, _, err = getBoardData(c, api, boardID)
if err != nil {
return nil, err
}
return lists, nil
}
func labelsByBoardID(c *integram.Context, api *t.Client, boardID string) ([]*t.Label, error) {
var labels []*t.Label
if exists := c.ServiceCache("labels_"+boardID, &labels); exists {
return labels, nil
}
var err error
_, _, labels, err = getBoardData(c, api, boardID)
if err != nil {
return nil, err
}
sort.Sort(byActuality(labels))
return labels, nil
}
func membersByBoardID(c *integram.Context, api *t.Client, boardID string) ([]*t.Member, error) {
var members []*t.Member
if exists := c.ServiceCache("members_"+boardID, &members); exists {
return members, nil
}
var err error
_, members, _, err = getBoardData(c, api, boardID)
if err != nil {
return nil, err
}
return members, nil
}
func boardsMaps(boards []*t.Board) map[string]*t.Board {
m := make(map[string]*t.Board)
for _, board := range boards {
m[board.Id] = board
}
return m
}
func boards(c *integram.Context, api *t.Client) ([]*t.Board, error) {
var boards []*t.Board
if exists := c.User.Cache("boards", &boards); exists {
return boards, nil
}
var err error
b, err := api.Request("GET", "members/me/boards", nil, url.Values{"filter": {"open"}})
if t.IsBadToken(err) {
c.User.ResetOAuthToken()
}
if err != nil {
return nil, err
}
err = json.Unmarshal(b, &boards)
if err != nil {
c.Log().WithError(err).Error("Can't get my boards")
return nil, err
}
err = c.User.SetCache("boards", boards, time.Hour)
if err != nil {
c.Log().WithError(err).Error("Can't save to cache")
return nil, err
}
return boards, nil
}
type byPriority struct {
Cards []*t.Card
MeID string
}
func (a byPriority) Len() int {
return len(a.Cards)
}
func (a byPriority) Swap(i, j int) {
a.Cards[i], a.Cards[j] = a.Cards[j], a.Cards[i]
}
func (a byPriority) DueBefore(i, j int) bool {
return (a.Cards[i].Due != nil && !a.Cards[i].Due.IsZero() && (a.Cards[j].Due == nil || a.Cards[j].Due.IsZero() || a.Cards[i].Due.Before(*(a.Cards[j].Due))))
}
func (a byPriority) Assigned(i, j int) bool {
if len(a.Cards[i].IdMembers) > 0 && integram.SliceContainsString(a.Cards[i].IdMembers, a.MeID) && (len(a.Cards[j].IdMembers) == 0 || !integram.SliceContainsString(a.Cards[j].IdMembers, a.MeID)) {
return true
}
return false
}
func (a byPriority) VotesMore(i, j int) bool {
return (len(a.Cards[i].IdMembersVoted) > len(a.Cards[j].IdMembersVoted))
}
func (a byPriority) PosLess(i, j int) bool {
return a.Cards[i].IdList == a.Cards[j].IdList && (a.Cards[i].Pos < a.Cards[j].Pos)
}
func (a byPriority) LastActivityOlder(i, j int) bool {
return (a.Cards[i].DateLastActivity != nil && !a.Cards[i].DateLastActivity.IsZero() && (a.Cards[j].DateLastActivity == nil || a.Cards[j].DateLastActivity.IsZero() || a.Cards[i].DateLastActivity.Before(*(a.Cards[j].DateLastActivity))))
}
func (a byPriority) LastBorderActivityMoreRecent(i, j int) bool {
return a.Cards[i].Board != nil && a.Cards[j].Board != nil && (a.Cards[i].Board.DateLastActivity != nil && !a.Cards[i].Board.DateLastActivity.IsZero() && (a.Cards[j].Board.DateLastActivity != nil && !a.Cards[j].Board.DateLastActivity.IsZero() && a.Cards[i].Board.DateLastActivity.After(*(a.Cards[j].Board.DateLastActivity))))
}
func (a byPriority) Less(i, j int) bool {
//todo: replace with bit mask
if a.Assigned(i, j) {
return true
}
if a.Assigned(j, i) {
return false
}
if a.DueBefore(i, j) {
return true
}
if a.DueBefore(j, i) {
return false
}
if a.VotesMore(i, j) {
return true
}
if a.VotesMore(j, i) {
return false
}
if a.PosLess(i, j) {
return true
}
if a.PosLess(j, i) {
return false
}
if a.LastBorderActivityMoreRecent(i, j) {
return true
}
if a.LastBorderActivityMoreRecent(j, i) {
return false
}
if a.LastActivityOlder(i, j) {
return true
}
return false
}
type byNewest []*t.Board
func (a byNewest) Len() int {
return len(a)
}
func (a byNewest) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a byNewest) Less(i, j int) bool {
return boardTimeForSorting(a[i]) > boardTimeForSorting(a[j])
}
type byActuality []*t.Label
func (a byActuality) Len() int {
return len(a)
}
func (a byActuality) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a byActuality) Less(i, j int) bool {
return a[i].Uses > a[j].Uses || (a[i].Uses == a[j].Uses) && a[i].Name != "" && a[j].Name == ""
}
func boardTimeForSorting(b *t.Board) int64 {
if b.DateLastActivity == nil {
if b.DateLastView == nil {
return 0
}
return b.DateLastView.Unix()
}
return b.DateLastActivity.Unix()
}
func existsWebhookByBoard(c *integram.Context, boardID string) (webhookInfo, error) {
res, err := api(c).Request("GET", "tokens/"+c.User.OAuthToken()+"/webhooks", nil, nil)
if err != nil {
return webhookInfo{}, err
}
webhooks := []webhookInfo{}
err = json.Unmarshal(res, &webhooks)
if err != nil {
return webhookInfo{}, err
}
log.Printf("webhooks: %+v\n", webhooks)
for _, webhook := range webhooks {
if webhook.IDModel == boardID && webhook.CallbackURL == c.User.ServiceHookURL() {
return webhook, nil
}
}
return webhookInfo{}, errors.New("not found")
}
func resubscribeAllBoards(c *integram.Context) error {
us := userSettings(c)
any := false
if us.Boards != nil {
uToken := c.User.OAuthToken()
for id, board := range us.Boards {
if board.OAuthToken != uToken || board.TrelloWebhookID == "" {
//todo: make a job
qp := url.Values{"description": {"Integram"}, "callbackURL": {c.User.ServiceHookURL()}, "idModel": {id}}
webhook := webhookInfo{}
res, err := api(c).Request("POST", "tokens/"+uToken+"/webhooks", nil, qp)
if err != nil {
c.Log().WithError(err).Error("resubscribeAllBoards")
} else {
err = json.Unmarshal(res, &webhook)
if err != nil {
c.Log().WithError(err).Error("resubscribeAllBoards")
} else {
board.OAuthToken = uToken
board.TrelloWebhookID = webhook.ID
us.Boards[id] = board
any = true
}
}
}
}
}
if !any {
return nil
}
return c.User.SaveSettings(us)
}
func scheduleSubscribeIfBoardNotAlreadyExists(c *integram.Context, b *t.Board, chatID int64) error {
us := userSettings(c)
if b == nil {
c.Log().Error("scheduleSubscribeIfBoardNotAlreadyExists nil board")
return nil
}
if us.Boards != nil {
if val, exists := us.Boards[b.Id]; exists {
if val.OAuthToken == c.User.OAuthToken() {
c.Chat.ID = chatID
cs := chatSettings(c)
if _, chatBoardExists := cs.Boards[b.Id]; chatBoardExists {
sendBoardFiltersKeyboard(c, b.Id)
return nil
}
return processWebhook(c, b, chatID, val.TrelloWebhookID)
}
}
}
_, err := c.Service().SheduleJob(subscribeBoard, 0, time.Now(), c, b, chatID)
return err
}
func processWebhook(c *integram.Context, b *t.Board, chatID int64, webhookID string) error {
boardSettings := UserBoardSetting{Name: b.Name, TrelloWebhookID: webhookID, OAuthToken: c.User.OAuthToken()}
if chatID != 0 {
c.User.AddChatToHook(chatID)
cs := &ChatSettings{}
initiatedInThePrivateChat := false
if c.Chat.ID != chatID {
initiatedInThePrivateChat = true
}
c.Chat.Settings(cs)
if cs.Boards == nil {
cs.Boards = make(map[string]ChatBoardSetting)
}
c.Chat.ID = chatID
cs.Boards[b.Id] = ChatBoardSetting{Name: b.Name, Enabled: true, User: c.User.ID, Filter: defaultBoardFilter}
err := c.Chat.SaveSettings(cs)
if err != nil {
return err
}
buttons := integram.Buttons{{b.Id, "🔧 Tune board " + b.Name}, {"anotherone", "➕ Add another one"}, {"done", "✅ Done"}}
if c.Chat.IsGroup() {
var msgWithButtons *integram.OutgoingMessage
if initiatedInThePrivateChat {
c.NewMessage().
SetText(fmt.Sprintf("Board \"%s\" integrated", b.Name)).
HideKeyboard().
SetChat(c.User.ID).
Send()
msgWithButtons = c.NewMessage().
SetText(fmt.Sprintf("%s was integrated board \"%s\" here. You can reply my messages to comment cards", c.User.Mention(), b.Name)).
SetChat(chatID)
} else {
msgWithButtons = c.NewMessage().
SetText(fmt.Sprintf("%s was integrated board \"%s\" here. You can reply my messages to comment cards", c.User.Mention(), b.Name)).
SetChat(chatID)
}
msgWithButtons.
SetKeyboard(buttons, true).
SetOneTimeKeyboard(true).
SetReplyAction(afterBoardIntegratedActionSelected).
Send()
} else {
c.NewMessage().
SetText(fmt.Sprintf("Board \"%s\" integrated here", b.Name)).
SetKeyboard(buttons, true).
SetOneTimeKeyboard(true).
SetChat(c.User.ID).
SetReplyAction(afterBoardIntegratedActionSelected).
Send()
}
}
s := userSettings(c)
if s.Boards == nil {
s.Boards = make(map[string]UserBoardSetting)
}
s.Boards[b.Id] = boardSettings
c.User.SaveSettings(s)
return nil
}
func afterBoardIntegratedActionSelected(c *integram.Context) error {
key, _ := c.KeyboardAnswer()
if key == "anotherone" {
// we can use directly because of boards cached
sendBoardsToIntegrate(c)
return nil
} else if key != "done" {
sendBoardFiltersKeyboard(c, key)
}
return nil
}
func authWasRevokedMessage(c *integram.Context){
c.User.ResetOAuthToken()
c.NewMessage().EnableAntiFlood().SetTextFmt("Looks like you have revoked the Integram access. In order to use me you need to authorize again: %s", oauthRedirectURL(c)).SetChat(c.User.ID).Send()
}
func subscribeBoard(c *integram.Context, b *t.Board, chatID int64) error {
qp := url.Values{"description": {"Integram"}, "callbackURL": {c.User.ServiceHookURL()}, "idModel": {b.Id}}
_, err := api(c).Request("POST", "tokens/"+c.User.OAuthToken()+"/webhooks", nil, qp)
webhook := webhookInfo{}
if err != nil {
if strings.Contains(err.Error(),"already exists") {
webhook, err = existsWebhookByBoard(c, b.Id)
if err != nil {
c.Log().WithError(err).WithField("boardID", b.Id).Error("Received ErrorWebhookExists but can't refetch")
return err
}
} else if strings.Contains(err.Error(), "401 Unauthorized"){
authWasRevokedMessage(c)
c.User.SetAfterAuthAction(subscribeBoard, b, chatID)
return nil
} else {
return err
}
} else {
webhook, err = existsWebhookByBoard(c, b.Id)
if err != nil{
return err
}
// instead of checking the provided webhook lets query Trello to ensure it has a webhook for sure
// in some cases Trello provides webhook but doesn't actually store it
/*err = json.Unmarshal(res, &webhook)
if err != nil {
return err
}*/
}
return processWebhook(c, b, chatID, webhook.ID)
}
func labelsFilterByID(labels []*t.Label, id string) *t.Label {
for _, label := range labels {
if label.Id == id {
return label
}
}
return nil
}
func membersFilterByID(members []*t.Member, id string) *t.Member {
for _, member := range members {
if member.Id == id {
return member
}
}
return nil
}
func boardsFilterByID(boards []*t.Board, id string) *t.Board {
for _, board := range boards {
if board.Id == id {
return board
}
}
return nil
}
func listsFilterByID(lists []*t.List, id string) *t.List {
for _, list := range lists {
if list.Id == id {
return list
}
}
return nil
}
func targetChatSelected(c *integram.Context, boardID string) error {
if boardID == "" {
err := errors.New("BoardID is empty")
return err
}
key, _ := c.KeyboardAnswer()
var chatID int64
boards, _ := boards(c, api(c))
board := boardsFilterByID(boards, boardID)
if key == "group" {
// Defer adding chatID by using Telegram's ?startgroup
chatID = 0
c.NewMessage().
SetText(fmt.Sprintf("Use this link to choose the group chat: https://telegram.me/%s?startgroup=%s", c.Bot().Username, boardID)).
HideKeyboard().
DisableWebPreview().
Send()
} else if key == "private" {
chatID = c.User.ID
} else if key != "" {
var err error
chatID, err = strconv.ParseInt(key, 10, 64)
if err != nil {
return err
}
}
return scheduleSubscribeIfBoardNotAlreadyExists(c, board, chatID)
}
func renderBoardFilters(c *integram.Context, boardID string, keyboard *integram.Keyboard) error {
cs := chatSettings(c)
if bs, ok := cs.Boards[boardID]; ok {
if bs.Enabled == false {
(*keyboard) = (*keyboard)[0:1]
}
for rowIndex, row := range *keyboard {
for colIndex, button := range row {
if button.Data == "switch" {
if bs.Enabled == true {
(*keyboard)[rowIndex][colIndex].Text = "☑️ Notifications enabled"
} else {
(*keyboard)[rowIndex][colIndex].Text = "Turn on notifications"
}
} else {
v := reflect.ValueOf(bs.Filter).FieldByName(button.Data)
if bs.Enabled && v.IsValid() && v.Bool() {
(*keyboard)[rowIndex][colIndex].Text = markSign + button.Text
}
}
}
}
return nil
}
return errors.New("Can't find board settings on user")
}
func storeCard(c *integram.Context, card *t.Card) {
c.SetServiceCache("card_"+card.Id, card, time.Hour*24*100)
var cards []*t.Card
c.User.Cache("cards", &cards)
alreadyExists := false
for _, cardR := range cards {
if cardR.Id == card.Id {
alreadyExists = true
break
}
}
if !alreadyExists {
err := c.User.UpdateCache("cards", bson.M{"$addToSet": bson.M{"val": card}}, &cards)
if err != nil {
c.Log().WithError(err).Errorf("Cards cache update error")
}
}
}
func getBoardFilterKeyboard(c *integram.Context, boardID string) *integram.Keyboard {
keyboard := integram.Keyboard{}
keyboard.AddRows(
integram.Buttons{{"switch", "🚫 Turn off all"}, {"finish", "🏁 Finish tunning"}},
integram.Buttons{{"CardCreated", "Card Created"}, {"CardCommented", "Commented"}, {"CardMoved", "Moved"}},
integram.Buttons{{"PersonAssigned", "Someone Assigned"}, {"Labeled", "Label attached"}, {"Voted", "Upvoted"}},
integram.Buttons{{"Due", "Due date set"}, {"Checklisted", "Checklisted"}, {"Archived", "Archived"}},
)
renderBoardFilters(c, boardID, &keyboard)
return &keyboard
}
func sendBoardFiltersKeyboard(c *integram.Context, boardID string) error {
boards, _ := boards(c, api(c))
board := boardsFilterByID(boards, boardID)
if board == nil {
return fmt.Errorf("board not found %v", boardID)
}
keyboard := getBoardFilterKeyboard(c, boardID)
msg := c.NewMessage()
if c.Message != nil {
msg.SetReplyToMsgID(c.Message.MsgID)
}
return msg.
SetText(fmt.Sprintf("%v tune notifications for \"%v\" board", c.User.Mention(), board.Name)).
SetKeyboard(keyboard, true).
SetSilent(true).
SetReplyToMsgID(c.Message.MsgID).
SetReplyAction(boardFilterButtonPressed, boardID).
Send()
}
func cleanMarkSign(s string) string {
if strings.HasPrefix(s, markSign) {
return s[len(markSign):]
}
return s
}
func boardFilterButtonPressed(c *integram.Context, boardID string) error {
answer, _ := c.KeyboardAnswer()
if answer == "finish" {
return c.NewMessage().
SetText("Ok!").
SetSilent(true).
SetReplyToMsgID(c.Message.MsgID).
HideKeyboard().
Send()
}
cs := chatSettings(c)
if bs, ok := cs.Boards[boardID]; ok {
if answer == "switch" {
bs.Enabled = !bs.Enabled
cs.Boards[boardID] = bs
c.Chat.SaveSettings(cs)
keyboard := getBoardFilterKeyboard(c, boardID)
onOrOff := "on"
if !bs.Enabled {
onOrOff = "off"
}
return c.NewMessage().
SetText(c.User.Mention()+", all notifications turned "+onOrOff).
SetKeyboard(keyboard, true).
SetSilent(true).
SetReplyToMsgID(c.Message.MsgID).
SetReplyAction(boardFilterButtonPressed, boardID).
Send()
}
v := reflect.ValueOf(&bs.Filter).Elem().FieldByName(answer)
if v.IsValid() && v.CanSet() {
v.SetBool(!v.Bool())
cs.Boards[boardID] = bs
c.Chat.SaveSettings(cs)
/*var s string
if v.Bool() {
s = "enabled"
} else {
s = "disabled"
}*/
keyboard := getBoardFilterKeyboard(c, boardID)
return c.NewMessage().
SetText(
decent.Shuffle(
"Ok, %v",
"Have done, %v",
"I changed it, %v",
"Done it for you, %v",
"👌 %v",
"👍 %v").
S(c.User.Mention())).
SetKeyboard(keyboard, true).
SetReplyToMsgID(c.Message.MsgID).
SetSilent(true).
SetReplyAction(boardFilterButtonPressed, boardID).
Send()
}
}
return errors.New("Can't change board filter value")
}
func boardToTuneSelected(c *integram.Context) error {
boardID, _ := c.KeyboardAnswer()
if boardID == "" {
return errors.New("Empty boardID")
}
return sendBoardFiltersKeyboard(c, boardID)
}
func boardToIntegrateSelected(c *integram.Context) error {
boardID, boardName := c.KeyboardAnswer()
log.Infof("boardToIntegrateSelected %s (%s)", boardName, boardID)
if c.Chat.IsGroup() {
boards, _ := boards(c, api(c))
board := boardsFilterByID(boards, boardID)
if board == nil {
c.Log().Errorf("boardToIntegrateSelected, boardsFilterByID returned nil (id=%s, len(boards)=%d)", boardID, len(boards))
return errors.New("board with id not found")
}
return scheduleSubscribeIfBoardNotAlreadyExists(c, board, c.Chat.ID)
}
but := integram.Buttons{}
if tc := userSettings(c); tc.TargetChat != nil && tc.TargetChat.ID != 0 {
but.Append(strconv.FormatInt(tc.TargetChat.ID, 10), tc.TargetChat.Title)
}
but.Append("group", "Choose the group")
but.Append("private", "Private messages")
c.NewMessage().
SetText("Please choose where you would like to receive Trello notifications for board "+boardName).
SetKeyboard(but.Markup(1), true).
SetReplyToMsgID(c.Message.MsgID).
SetReplyAction(targetChatSelected, boardID).
Send()
return nil
}
func boardForCardSelected(c *integram.Context) error {
boardID, boardName := c.KeyboardAnswer()
lists, err := listsByBoardID(c, api(c), boardID)
if err != nil {
return err
}
but := integram.Buttons{}
for _, list := range lists {
but.Append(list.Id, list.Name)