-
Notifications
You must be signed in to change notification settings - Fork 0
/
almanax.go
1206 lines (1045 loc) · 33.9 KB
/
almanax.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 main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/dofusdude/dodugo"
"github.com/google/uuid"
)
func handleGetMetaAlmanaxSubscriptions(w http.ResponseWriter, r *http.Request) {
HandleGenGetMetaSubscriptions(w, r, GetAlmanaxFeeds)
}
// CRUD
func toDTO(webhook AlmanaxWebhook) AlmanaxHookDTO {
prep := AlmanaxHookDTO{
Id: webhook.Id,
DailySettings: DailySettings{
Timezone: *webhook.DailySettings.Timezone,
MidnightOffset: *webhook.DailySettings.MidnightOffset,
},
Subscriptions: webhook.Subscriptions,
WantsIsoDate: webhook.WantsIsoDate,
Format: webhook.Format,
CreatedAt: webhook.CreatedAt,
UpdatedAt: webhook.UpdatedAt,
LastFiredAt: webhook.LastFiredAt,
WeeklyWeekday: webhook.WeeklyWeekday,
Intervals: webhook.Intervals,
}
if webhook.BonusWhitelist != nil && len(webhook.BonusWhitelist) > 0 {
prep.BonusWhitelist = webhook.BonusWhitelist
}
if webhook.BonusBlacklist != nil && len(webhook.BonusBlacklist) > 0 {
prep.BonusBlacklist = webhook.BonusBlacklist
}
if webhook.Mentions != nil && len(*webhook.Mentions) > 0 {
prep.Mentions = webhook.Mentions
}
return prep
}
func handleDeleteAlmanaxHook(w http.ResponseWriter, r *http.Request) {
requestsCRUDTotal.Inc()
requestsCRUDAlmanax.Inc()
id := r.Context().Value("id").(string)
var err error
var parsedId uuid.UUID
parsedId, err = uuid.Parse(id)
if err != nil {
http.Error(w, "Invalid id.", http.StatusBadRequest)
return
}
var repo Repository
if err = repo.Init(r.Context()); err != nil {
http.Error(w, "Internal error.", http.StatusInternalServerError)
return
}
defer repo.Deinit()
var hasWebhook bool
if hasWebhook, err = repo.HasAlmanaxWebhook(parsedId); err != nil {
http.Error(w, "Internal error.", http.StatusInternalServerError)
return
}
if !hasWebhook {
http.Error(w, "Not found.", http.StatusNotFound)
return
}
if err = repo.DeleteHook(parsedId); err != nil {
http.Error(w, "Internal error.", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
func getPossibleAlmanaxBonuses(ctx context.Context) (*Set[string], error) {
almClient := dodugo.NewAPIClient(dodugo.NewConfiguration())
almBonuses, _, err := almClient.MetaAPI.GetMetaAlmanaxBonuses(ctx, "en").Execute()
if err != nil {
return nil, err
}
possibleBonuses := NewSet[string]()
for _, bonus := range almBonuses {
possibleBonuses.Add(bonus.GetId())
}
return possibleBonuses, nil
}
func validateIntervals(intervals []string) ([]string, bool) {
intervalSet := NewSet[string]()
for _, interval := range intervals {
lowerInterval := strings.ToLower(interval)
intervalSet.Add(lowerInterval)
switch lowerInterval {
case "daily":
case "weekly":
case "monthly":
default:
return nil, false
}
}
return intervalSet.Slice(), true
}
func validateWeekday(weekday string) (string, bool) {
lowerWeekday := strings.ToLower(weekday)
switch lowerWeekday {
case "monday":
case "tuesday":
case "wednesday":
case "thursday":
case "friday":
case "saturday":
case "sunday":
default:
return lowerWeekday, false
}
return lowerWeekday, true
}
func handleCreateAlmanax(w http.ResponseWriter, r *http.Request) {
requestsCRUDTotal.Inc()
requestsCRUDAlmanax.Inc()
var err error
var createWebhook AlmanaxHookPost
if err = json.NewDecoder(r.Body).Decode(&createWebhook); err != nil {
http.Error(w, "Invalid request.", http.StatusBadRequest)
return
}
if createWebhook.Callback == "" {
http.Error(w, "Callback is required.", http.StatusBadRequest)
return
}
if createWebhook.Subscriptions == nil {
http.Error(w, "Subscriptions are required.", http.StatusBadRequest)
return
}
defaultTz := "Europe/Paris"
defaultTzOffset := 0
if createWebhook.DailySettings == nil {
createWebhook.DailySettings = &WebhookDailySettings{
Timezone: &defaultTz,
MidnightOffset: &defaultTzOffset,
}
}
if createWebhook.DailySettings.Timezone == nil {
createWebhook.DailySettings.Timezone = &defaultTz
}
if createWebhook.DailySettings.MidnightOffset == nil {
createWebhook.DailySettings.MidnightOffset = &defaultTzOffset
}
if createWebhook.Format != "discord" {
http.Error(w, "Callback must have a known format.", http.StatusBadRequest)
return
}
if !isDiscordWebhook(createWebhook.Callback) {
http.Error(w, "Callback is not a valid Discord URL.", http.StatusBadRequest)
return
}
if createWebhook.WantsIsoDate == nil {
defaultIsoDate := false
createWebhook.WantsIsoDate = &defaultIsoDate
}
if createWebhook.BonusBlacklist != nil && createWebhook.BonusWhitelist != nil {
http.Error(w, "You can't have both a bonus whitelist and a bonus blacklist.", http.StatusBadRequest)
return
}
_, err = time.LoadLocation(*createWebhook.DailySettings.Timezone)
if err != nil {
http.Error(w, "Timezone not valid.", http.StatusBadRequest)
return
}
if *createWebhook.DailySettings.MidnightOffset < 0 || *createWebhook.DailySettings.MidnightOffset > 23 {
http.Error(w, "Offset should be between 0 and 23 valid.", http.StatusBadRequest)
return
}
possibleBonuses, err := getPossibleAlmanaxBonuses(r.Context())
if err != nil {
http.Error(w, "Could not reach Almanax API.", http.StatusBadGateway)
return
}
for _, whitelistEntry := range createWebhook.BonusWhitelist {
if !possibleBonuses.Has(whitelistEntry) {
http.Error(w, "Unknown almanax bonus id: "+whitelistEntry+".", http.StatusBadRequest)
return
}
}
for _, blacklistEntry := range createWebhook.BonusBlacklist {
if !possibleBonuses.Has(blacklistEntry) {
http.Error(w, "Unknown almanax bonus id: "+blacklistEntry+".", http.StatusBadRequest)
return
}
}
if createWebhook.Intervals == nil || len(createWebhook.Intervals) == 0 {
createWebhook.Intervals = []string{"daily"}
}
var ok bool
if createWebhook.Intervals, ok = validateIntervals(createWebhook.Intervals); !ok {
http.Error(w, "An interval must be one of daily, weekly or monthly.", http.StatusBadRequest)
}
if createWebhook.WeeklyWeekday == nil && sliceContains(createWebhook.Intervals, "sunday") {
defaultWeekday := "monday"
createWebhook.WeeklyWeekday = &defaultWeekday
}
if createWebhook.WeeklyWeekday != nil {
if *createWebhook.WeeklyWeekday, ok = validateWeekday(*createWebhook.WeeklyWeekday); !ok {
http.Error(w, "Unknown weekly weekday: "+*createWebhook.WeeklyWeekday+".", http.StatusBadRequest)
}
}
var repo Repository
if err = repo.Init(r.Context()); err != nil {
http.Error(w, "Internal error.", http.StatusInternalServerError)
return
}
defer repo.Deinit()
var hasAlm bool
if hasAlm, err = repo.HasAlmanaxWebhookCallback(createWebhook.Callback); err != nil {
http.Error(w, "Internal error.", http.StatusInternalServerError)
return
}
if hasAlm {
http.Error(w, "Callback already exists.", http.StatusConflict)
return
}
requestedBonuses := map[string]*Set[string]{}
requestedMentions := map[string]*Set[uint64]{}
if createWebhook.Mentions != nil {
if len(*createWebhook.Mentions) > 150 {
http.Error(w, "Too many mentions.", http.StatusBadRequest)
return
}
for bonusId, mentions := range *createWebhook.Mentions {
if _, ok := requestedBonuses[bonusId]; !ok {
requestedBonuses[bonusId] = NewSet[string]()
}
if _, ok := requestedMentions[bonusId]; !ok {
requestedMentions[bonusId] = NewSet[uint64]()
}
if !possibleBonuses.Has(bonusId) {
http.Error(w, "Unknown almanax bonus id: "+bonusId+".", http.StatusBadRequest)
return
}
if requestedBonuses[bonusId].Has(bonusId) {
http.Error(w, "Duplicate bonus id: "+bonusId+".", http.StatusBadRequest)
return
}
requestedBonuses[bonusId].Add(bonusId)
for _, mention := range mentions {
if mention.PingDaysBefore != nil {
if *mention.PingDaysBefore < 1 || *mention.PingDaysBefore > 31 {
http.Error(w, "PingDaysBefore should be between 1 and 31.", http.StatusBadRequest)
return
}
}
requestedMentions[bonusId].Add(mention.DiscordId)
}
}
}
var uid uuid.UUID
if uid, err = repo.CreateAlmanaxHook(CreateAlmanaxHook{
Callback: createWebhook.Callback,
Subscriptions: createWebhook.Subscriptions,
Format: createWebhook.Format,
WantsIsoDate: *createWebhook.WantsIsoDate,
DailySettings: *createWebhook.DailySettings,
BonusWhitelist: createWebhook.BonusWhitelist,
BonusBlacklist: createWebhook.BonusBlacklist,
Mentions: createWebhook.Mentions,
Intervals: createWebhook.Intervals,
WeeklyWeekday: createWebhook.WeeklyWeekday,
}); err != nil {
if err.Error() == "some feeds not found" {
http.Error(w, "Some feeds not found.", http.StatusBadRequest)
return
} else {
http.Error(w, "Internal error.", http.StatusInternalServerError)
return
}
}
alm, err := getAlm(uid, repo)
if err != nil {
if err.Error() == "not found" {
http.Error(w, "Not found.", http.StatusNotFound)
return
} else {
http.Error(w, "Internal error.", http.StatusInternalServerError)
return
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
if err = json.NewEncoder(w).Encode(toDTO(alm)); err != nil {
http.Error(w, "Error encoding the response.", http.StatusInternalServerError)
return
}
}
func getAlm(parsedId uuid.UUID, repo Repository) (AlmanaxWebhook, error) {
var err error
var hasWebhook bool
hasWebhook, err = repo.HasAlmanaxWebhook(parsedId)
if err != nil {
return AlmanaxWebhook{}, err
}
if !hasWebhook {
return AlmanaxWebhook{}, errors.New("not found")
}
hook, err := repo.GetAlmanaxHook(parsedId)
if err != nil {
return AlmanaxWebhook{}, err
}
subbedFeeds, err := repo.GetAlmanaxHookSubscriptions(parsedId)
if err != nil {
return AlmanaxWebhook{}, err
}
for _, feed := range subbedFeeds {
hook.Subscriptions = append(hook.Subscriptions, Subscription{Id: feed.GetFeedName()})
}
return hook, nil
}
func handleGetAlmanax(w http.ResponseWriter, r *http.Request) {
requestsCRUDTotal.Inc()
requestsCRUDAlmanax.Inc()
id := r.Context().Value("id").(string)
var err error
var parsedId uuid.UUID
parsedId, err = uuid.Parse(id)
if err != nil {
http.Error(w, "Invalid id.", http.StatusBadRequest)
return
}
var repo Repository
if err = repo.Init(r.Context()); err != nil {
http.Error(w, "Internal error.", http.StatusInternalServerError)
return
}
defer repo.Deinit()
hook, err := getAlm(parsedId, repo)
if err != nil {
if err.Error() == "not found" {
http.Error(w, "Not found.", http.StatusNotFound)
return
} else {
http.Error(w, "Internal error.", http.StatusInternalServerError)
return
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err = json.NewEncoder(w).Encode(toDTO(hook)); err != nil {
http.Error(w, "Error encoding the response.", http.StatusInternalServerError)
return
}
}
func handlePutAlmanax(w http.ResponseWriter, r *http.Request) {
requestsCRUDTotal.Inc()
requestsCRUDAlmanax.Inc()
id := r.Context().Value("id").(string)
var err error
var parsedId uuid.UUID
parsedId, err = uuid.Parse(id)
if err != nil {
http.Error(w, "Invalid id.", http.StatusBadRequest)
return
}
var updateHook AlmanaxHookPut
if err = json.NewDecoder(r.Body).Decode(&updateHook); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var ok bool
if updateHook.Intervals, ok = validateIntervals(updateHook.Intervals); !ok {
http.Error(w, "An interval must be one of daily, weekly or monthly.", http.StatusBadRequest)
}
if updateHook.WeeklyWeekday != nil {
if *updateHook.WeeklyWeekday, ok = validateWeekday(*updateHook.WeeklyWeekday); !ok {
http.Error(w, "Unknown weekly weekday: "+*updateHook.WeeklyWeekday+".", http.StatusBadRequest)
}
}
if updateHook.BonusBlacklist != nil && updateHook.BonusWhitelist != nil {
http.Error(w, "Cannot set both bonus blacklist and whitelist.", http.StatusBadRequest)
return
}
possibleBonuses, err := getPossibleAlmanaxBonuses(r.Context())
if err != nil {
http.Error(w, "Could not reach Almanax API.", http.StatusBadGateway)
return
}
if updateHook.DailySettings != nil && updateHook.DailySettings.Timezone != nil {
_, err = time.LoadLocation(*updateHook.DailySettings.Timezone)
if err != nil {
http.Error(w, "Timezone not valid.", http.StatusBadRequest)
return
}
}
if updateHook.DailySettings != nil && updateHook.DailySettings.MidnightOffset != nil {
if *updateHook.DailySettings.MidnightOffset < 0 || *updateHook.DailySettings.MidnightOffset > 23 {
http.Error(w, "Offset should be between 0 and 23 valid.", http.StatusBadRequest)
return
}
}
if updateHook.BonusBlacklist != nil {
for _, blacklistEntry := range updateHook.BonusBlacklist {
if !possibleBonuses.Has(blacklistEntry) {
http.Error(w, "Unknown almanax bonus id: "+blacklistEntry+".", http.StatusBadRequest)
return
}
}
}
if updateHook.BonusWhitelist != nil {
for _, blacklistEntry := range updateHook.BonusWhitelist {
if !possibleBonuses.Has(blacklistEntry) {
http.Error(w, "Unknown almanax bonus id: "+blacklistEntry+".", http.StatusBadRequest)
return
}
}
}
if updateHook.Mentions != nil {
for bonusId := range *updateHook.Mentions {
if !possibleBonuses.Has(bonusId) {
http.Error(w, "Unknown almanax bonus id: "+bonusId+".", http.StatusBadRequest)
return
}
}
}
var repo Repository
if err = repo.Init(r.Context()); err != nil {
http.Error(w, "Internal error.", http.StatusInternalServerError)
return
}
defer repo.Deinit()
var found bool
found, err = repo.HasAlmanaxWebhook(parsedId)
if err != nil {
http.Error(w, "Internal error.", http.StatusInternalServerError)
return
}
if !found {
http.Error(w, "Not found.", http.StatusNotFound)
return
}
if err = repo.UpdateAlmanaxHook(updateHook, parsedId); err != nil {
if err.Error() == "some feeds not found" {
http.Error(w, "Some feeds not found.", http.StatusBadRequest)
return
} else {
http.Error(w, "Internal error.", http.StatusInternalServerError)
return
}
}
alm, err := getAlm(parsedId, repo)
if err != nil {
if err.Error() == "not found" {
http.Error(w, "Not found.", http.StatusNotFound)
return
} else {
http.Error(w, "Internal error.", http.StatusInternalServerError)
return
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err = json.NewEncoder(w).Encode(toDTO(alm)); err != nil {
http.Error(w, "Error encoding the response.", http.StatusInternalServerError)
return
}
}
// utils for filter and fire hooks
func isNewHour(tick time.Time) bool {
return tick.Minute() == 0
}
func endOfMonth(date time.Time) time.Time {
return date.AddDate(0, 1, -date.Day())
}
func almHookIsSetToFireNow(webhook AlmanaxWebhook, currTime time.Time) ([]string, error) {
var toFire []string
location, err := time.LoadLocation(*webhook.DailySettings.Timezone)
if err != nil {
return nil, err
}
localeTime := currTime.In(location)
if sliceContains(webhook.Intervals, "daily") && localeTime.Hour() == *webhook.DailySettings.MidnightOffset {
toFire = append(toFire, "daily")
}
if sliceContains(webhook.Intervals, "weekly") && strings.ToLower(localeTime.Weekday().String()) == *webhook.WeeklyWeekday && localeTime.Hour() == *webhook.DailySettings.MidnightOffset {
toFire = append(toFire, "weekly")
}
if sliceContains(webhook.Intervals, "monthly") && endOfMonth(localeTime).Day() == localeTime.Day() && localeTime.Hour() == *webhook.DailySettings.MidnightOffset {
toFire = append(toFire, "monthly")
}
return toFire, nil
}
func localTimeFormat(lang string, almDateString string, translations map[string]map[string]string) (string, error) {
parsedAlmTime, err := time.Parse("2006-01-02", almDateString)
if err != nil {
return "", err
}
var out string
translatedWeekday := translations[lang][parsedAlmTime.Weekday().String()]
out += translatedWeekday
switch lang {
case "fr":
out += ", " + parsedAlmTime.Format("02/01/2006")
case "en":
out += ", " + parsedAlmTime.Format("02/01/2006")
case "de":
out += ", " + parsedAlmTime.Format("02.01.2006")
case "es":
out += ", " + parsedAlmTime.Format("02/01/2006")
case "it":
out += ", " + parsedAlmTime.Format("02/01/2006")
default:
return "", nil
}
return out, nil
}
func getFutureAlmData(almData map[string]dodugo.AlmanaxEntry, timezone string, daysAhead int) (dodugo.AlmanaxEntry, error) {
location, err := time.LoadLocation(timezone)
if err != nil {
return dodugo.AlmanaxEntry{}, err
}
localDate := time.Now().In(location).Add(time.Hour * 24 * time.Duration(daysAhead)).Format("2006-01-02")
return almData[localDate], nil
}
func getLocalAlmData(almData map[string]dodugo.AlmanaxEntry, timezone string) (dodugo.AlmanaxEntry, error) {
location, err := time.LoadLocation(timezone)
if err != nil {
return dodugo.AlmanaxEntry{}, err
}
localDate := time.Now().In(location).Format("2006-01-02")
return almData[localDate], nil
}
func getLocalAlmDataRange(almData map[string]dodugo.AlmanaxEntry, timezone string, start time.Time, end time.Time) ([]dodugo.AlmanaxEntry, error) {
location, err := time.LoadLocation(timezone)
if err != nil {
return nil, err
}
var out []dodugo.AlmanaxEntry
for i := 0; i <= int(end.Sub(start).Hours()/24); i++ {
localDate := start.Add(time.Hour * 24 * time.Duration(i)).In(location).Format("2006-01-02")
out = append(out, almData[localDate])
}
return out, nil
}
func atLeastOneWebhookIsSetToFireNow(webhooks []AlmanaxWebhook, currTime time.Time) (bool, error) {
var toFire []string
var err error
for _, webhook := range webhooks {
if toFire, err = almHookIsSetToFireNow(webhook, currTime); err != nil {
return false, err
}
if len(toFire) > 0 {
return true, nil
}
}
return false, nil
}
func filterAlmanaxBonusWhiteBlacklist(webhook AlmanaxWebhook, almBonusType dodugo.GetMetaAlmanaxBonuses200ResponseInner) bool {
isWhitelisted := false
isBlacklisted := false
if webhook.BonusWhitelist != nil && len(webhook.BonusWhitelist) > 0 {
for _, bonus := range webhook.BonusWhitelist {
if bonus == almBonusType.GetId() {
isWhitelisted = true
break
}
}
} else if webhook.BonusBlacklist != nil && len(webhook.BonusBlacklist) > 0 {
for _, bonus := range webhook.BonusBlacklist {
if bonus == almBonusType.GetId() {
isBlacklisted = true
break
}
}
}
if webhook.BonusBlacklist != nil && isBlacklisted {
return true
}
if webhook.BonusWhitelist != nil && !isWhitelisted {
return true
}
return false
}
func buildAlmSpan(tickTime time.Time, intervalType string, tz string, almData map[string]dodugo.AlmanaxEntry) ([]dodugo.AlmanaxEntry, error) {
var err error
var location *time.Location
location, err = time.LoadLocation(tz)
if err != nil {
return nil, err
}
var start time.Time
var end time.Time
start = tickTime.In(location).Add(time.Hour * 24)
switch intervalType {
case "weekly":
end = tickTime.In(location).Add(time.Hour * 24 * 7)
case "monthly":
end = endOfMonth(start)
}
var localAlmData []dodugo.AlmanaxEntry
localAlmData, err = getLocalAlmDataRange(almData, tz, start, end)
if err != nil {
return nil, err
}
return localAlmData, nil
}
// fire hook handlers
func HandleTimeAlmanax(almFeed AlmanaxFeed, _ any, tickTime time.Time, _ time.Duration, repo Repository) ([]AlmanaxSend, error) {
var err error
if !isNewHour(tickTime) {
return nil, nil
}
var subbedWebhooks []AlmanaxWebhook
if subbedWebhooks, err = repo.GetAlmanaxSubsForFeed(almFeed); err != nil {
return nil, err
}
var atLeastFireOne bool
if atLeastFireOne, err = atLeastOneWebhookIsSetToFireNow(subbedWebhooks, tickTime); err != nil {
return nil, err
}
if len(subbedWebhooks) == 0 || !atLeastFireOne {
return nil, nil
}
parisTz, err := time.LoadLocation("Europe/Paris") // default dofus time
if err != nil {
return nil, err
}
var dodugoClient = dodugo.NewAPIClient(dodugo.NewConfiguration())
options := dodugoClient.AlmanaxAPI.GetAlmanaxRange(context.Background(), almFeed.Language)
options = options.Timezone(parisTz.String()).RangeFrom(tickTime.In(parisTz).Add(-24 * time.Hour).Format("2006-01-02")).RangeSize(33)
almRes, _, err := options.Execute()
if err != nil {
return nil, err
}
almData := make(map[string]dodugo.AlmanaxEntry)
for _, entry := range almRes {
almData[entry.GetDate()] = entry
}
var sendWebhooks []IHook
var onlyPres []bool
var intervals []string
for _, webhook := range subbedWebhooks {
var preMentions map[int][]MentionDTO
if webhook.Mentions != nil {
preMentions, err = buildPreviewMentions(*webhook.Mentions, almData, *webhook.DailySettings.Timezone)
if err != nil {
return nil, err
}
}
var toFire []string
if toFire, err = almHookIsSetToFireNow(webhook, tickTime); err != nil {
return nil, err
}
if len(toFire) == 0 {
continue
}
for _, intervalType := range toFire {
// check if filters will hide the hook completely
if intervalType == "daily" {
var localAlmData dodugo.AlmanaxEntry
localAlmData, err = getLocalAlmData(almData, *webhook.DailySettings.Timezone)
if err != nil {
return nil, err
}
almBonus := localAlmData.GetBonus()
almBonusType := almBonus.GetType()
filterOut := filterAlmanaxBonusWhiteBlacklist(webhook, almBonusType)
if filterOut && len(preMentions) == 0 {
continue
}
onlyPres = append(onlyPres, filterOut)
} else { // weekly or monthly
var localAlmData []dodugo.AlmanaxEntry
if localAlmData, err = buildAlmSpan(tickTime, intervalType, webhook.GetTimezone(), almData); err != nil {
return nil, err
}
var filteredAlmData []dodugo.AlmanaxEntry
for _, almEntry := range localAlmData {
almBonus := almEntry.GetBonus()
almBonusType := almBonus.GetType()
filterOut := filterAlmanaxBonusWhiteBlacklist(webhook, almBonusType)
if filterOut && len(preMentions) == 0 {
continue
}
filteredAlmData = append(filteredAlmData, almEntry)
}
if len(filteredAlmData) == 0 {
continue
}
onlyPres = append(onlyPres, false)
}
sendHooksTotal.Inc()
sendHooksAlmanax.Inc()
sendWebhooks = append(sendWebhooks, webhook)
intervals = append(intervals, intervalType)
}
}
if len(sendWebhooks) == 0 {
return nil, nil
}
translations, err := repo.GetAllWeekdayTranslations()
if err != nil {
return nil, err
}
return []AlmanaxSend{
{
Feed: almFeed,
BuildInfo: AlmanaxHookBuildInfo{
almData: almData,
translations: translations,
},
Webhooks: sendWebhooks,
OnlyPreMentions: onlyPres,
IntervalType: intervals,
TickTime: tickTime,
},
}, nil
}
func buildPreviewMentions(hookMentions map[string][]MentionDTO, almData map[string]dodugo.AlmanaxEntry, tz string) (map[int][]MentionDTO, error) {
mentionsAcc := make(map[int][]MentionDTO) // daysAhead => mentions
for bonus, mentions := range hookMentions {
for _, mention := range mentions {
if mention.PingDaysBefore == nil {
continue
}
futureAlmData, err := getFutureAlmData(almData, tz, *mention.PingDaysBefore)
if err != nil {
return nil, err
}
futureBonus := futureAlmData.GetBonus()
futureBonusType := futureBonus.GetType()
if futureBonusType.GetId() == bonus {
mentionsAcc[*mention.PingDaysBefore] = append(mentionsAcc[*mention.PingDaysBefore], mention)
}
}
}
return mentionsAcc, nil
}
func buildDiscordHookAlmanax(almanaxSend AlmanaxSend) ([]PreparedHook, error) {
var res []PreparedHook
var err error
for webhookIdx, webhook := range almanaxSend.Webhooks {
var discordWebhook DiscordWebhook
if almanaxSend.IntervalType[webhookIdx] == "daily" {
var localAlmData dodugo.AlmanaxEntry
localAlmData, err = getLocalAlmData(almanaxSend.BuildInfo.almData, webhook.GetTimezone())
if err != nil {
return nil, err
}
var almLocalDate string
if webhook.IsWantIsoDate() {
almLocalDate = localAlmData.GetDate()
} else {
almLocalDate, err = localTimeFormat(almanaxSend.Feed.Language, localAlmData.GetDate(), almanaxSend.BuildInfo.translations)
if err != nil {
return nil, err
}
}
var imgBestResolution string
tribute := localAlmData.GetTribute()
almItem := tribute.GetItem()
itemImageUrls := almItem.GetImageUrls()
if itemImageUrls.HasSd() {
urls := almItem.GetImageUrls()
imgBestResolution = urls.GetSd()
} else {
imgBestResolution = itemImageUrls.GetIcon()
}
almBonus := localAlmData.GetBonus()
almBonusType := almBonus.GetType()
mentionString := ""
var beforeMentions []DiscordEmbedField
if webhook.GetMentions() != nil {
hookMentions := *webhook.GetMentions()
if mentions, ok := hookMentions[almBonusType.GetId()]; ok {
var mentionStrings []string
for _, mention := range mentions {
idStr := strconv.FormatUint(mention.DiscordId, 10)
found := false
for _, alreadyInsertedMention := range mentionStrings {
if strings.Contains(alreadyInsertedMention, idStr) {
found = true // skip already inserted mentions (when using multiple ones for multiple days in advance)
break
}
}
if found {
continue
}
if mention.IsRole {
mentionStrings = append(mentionStrings, "<@&"+idStr+">")
}
mentionStrings = append(mentionStrings, "<@"+idStr+">")
}
mentionString = strings.Join(mentionStrings, " ")
}
var mentionsAcc map[int][]MentionDTO
mentionsAcc, err = buildPreviewMentions(hookMentions, almanaxSend.BuildInfo.almData, webhook.GetTimezone())
if err != nil {
return nil, err
}
for daysBefore, mentions := range mentionsAcc {
var futureAlmData dodugo.AlmanaxEntry
futureAlmData, err = getFutureAlmData(almanaxSend.BuildInfo.almData, webhook.GetTimezone(), daysBefore)
if err != nil {
return nil, err
}
futureBonus := futureAlmData.GetBonus()
futureBonusType := futureBonus.GetType()
var mentionStrings []string
for _, mention := range mentions {
idStr := strconv.FormatUint(mention.DiscordId, 10)
if mention.IsRole {
mentionStrings = append(mentionStrings, "<@&"+idStr+">")
} else {
mentionStrings = append(mentionStrings, "<@"+idStr+">")
}
}
langCode := almanaxSend.Feed.GetFeedName()[len(almanaxSend.Feed.GetFeedName())-2:] // TODO query db for lang code
var almTitle string
switch langCode {
case "fr":
if daysBefore == 1 {
almTitle = fmt.Sprintf("%s demain !", futureBonusType.GetName())
} else {
almTitle = fmt.Sprintf("%s dans %d jours !", futureBonusType.GetName(), daysBefore)
}
case "es":
if daysBefore == 1 {
almTitle = fmt.Sprintf("%s mañana!", futureBonusType.GetName())
} else {
almTitle = fmt.Sprintf("%s en %d días!", futureBonusType.GetName(), daysBefore)
}
case "de":
if daysBefore == 1 {
almTitle = fmt.Sprintf("%s morgen!", futureBonusType.GetName())
} else {
almTitle = fmt.Sprintf("%s in %d Tagen!", futureBonusType.GetName(), daysBefore)
}
case "it":
if daysBefore == 1 {
almTitle = fmt.Sprintf("%s domani!", futureBonusType.GetName())
} else {
almTitle = fmt.Sprintf("%s in %d giorni!", futureBonusType.GetName(), daysBefore)
}
default:
if daysBefore == 1 {
almTitle = fmt.Sprintf("%s tomorrow!", futureBonusType.GetName())
} else {
almTitle = fmt.Sprintf("%s in %d days!", futureBonusType.GetName(), daysBefore)
}
}
beforeMentions = append(beforeMentions, DiscordEmbedField{
Name: almTitle,
Value: fmt.Sprintf("%s\n%s", strings.Join(mentionStrings, " "), futureBonus.GetDescription()),
Inline: false,
})
}
}