-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
1897 lines (1718 loc) · 53.5 KB
/
main.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 (
"bytes"
"context"
"crypto/rand"
"database/sql"
"encoding/json"
"flag"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"os/signal"
"regexp"
"sort"
"strconv"
"strings"
"time"
"./makedraft"
"./migrations"
"golang.org/x/net/xsrftoken"
"github.com/BurntSushi/migration"
"github.com/bwmarrin/discordgo"
"github.com/go-co-op/gocron"
"github.com/google/shlex"
"github.com/gorilla/sessions"
_ "github.com/mattn/go-sqlite3"
)
type r38handler func(w http.ResponseWriter, r *http.Request, userId int64, tx *sql.Tx) error
const FOREST_BEAR_ID = "700900270153924608"
const FOREST_BEAR = ":forestbear:" + FOREST_BEAR_ID
const DRAFT_ALERTS_ROLE = "692079611680653442"
const DRAFT_FRIEND_ROLE = "692865288554938428"
const EVERYONE_ROLE = "685333271793500161"
const BOSS = "176164707026206720"
const PINK = 0xE50389
var secretKeyNoOneWillEverGuess = []byte(os.Getenv("SESSION_SECRET"))
var xsrfKey string
var store = sessions.NewCookieStore(secretKeyNoOneWillEverGuess)
var sock string
var dg *discordgo.Session
func main() {
useAuthPtr := flag.Bool("auth", true, "bool")
flag.Parse()
xsrfKey = os.Getenv("XSRF_KEY")
if len(xsrfKey) == 0 {
xsrfKeyBytes := make([]byte, 128)
_, err := rand.Read(xsrfKeyBytes)
if err != nil {
log.Printf("error generating XSRF key: %s. set using XSRF_KEY env variable", err.Error())
}
chars := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i, b := range xsrfKeyBytes {
xsrfKeyBytes[i] = chars[b%byte(len(chars))]
}
xsrfKey = string(xsrfKeyBytes)
}
database, err := migration.Open("sqlite3", "draft.db", migrations.Migrations)
if err != nil {
log.Printf("error opening db: %s", err.Error())
return
}
err = database.Ping()
if err != nil {
return
}
port, valid := os.LookupEnv("R38_PORT")
if !valid {
port = "12264"
}
sock, valid = os.LookupEnv("R38_SOCK")
if !valid {
sock = "./r38.sock"
}
server := &http.Server{
Addr: fmt.Sprintf(":%s", port),
Handler: NewHandler(database, *useAuthPtr),
}
dg, err = discordgo.New("Bot " + os.Getenv("DISCORD_BOT_TOKEN"))
if err != nil {
log.Printf("%s", err.Error())
} else {
defer func() {
log.Printf("Closing discord bot")
err = dg.Close()
if err != nil {
log.Printf("%s", err.Error())
}
}()
dg.AddHandler(DiscordReady)
dg.AddHandler(DiscordMsgCreate(database))
dg.AddHandler(DiscordReactionAdd(database))
dg.AddHandler(DiscordReactionRemove(database))
err = dg.Open()
if err != nil {
log.Printf("%s", err.Error())
}
}
scheduler := gocron.NewScheduler(time.UTC)
_, err = scheduler.Every(8).Hours().Do(ArchiveSpectatorChannels, database)
if err != nil {
log.Printf("error setting up spectator channel archive task: %s", err.Error())
}
scheduler.StartAsync()
log.Printf("Starting HTTP Server. Listening at %q", server.Addr)
go func() {
err = server.ListenAndServe() // this call blocks
if err != nil {
log.Printf("%s", err.Error())
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
<-stop
err = server.Shutdown(context.Background())
}
// NewHandler creates all server routes for serving the html.
func NewHandler(database *sql.DB, useAuth bool) http.Handler {
mux := http.NewServeMux()
addHandler := func(route string, serveFunc r38handler, readonly bool) {
isAuthRoute := strings.HasPrefix(route, "/auth/")
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var userID int64
if useAuth {
if isAuthRoute {
userID = 0
} else {
session, err := store.Get(r, "session-name")
if err != nil {
userID = 0
} else {
userIDStr := session.Values["userid"]
if userIDStr == nil {
userID = 0
} else {
userIDInt, err := strconv.Atoi(userIDStr.(string))
if err != nil {
userID = 0
} else {
userID = int64(userIDInt)
}
}
}
}
} else {
userID = 1
}
if userID == 1 {
q := r.URL.Query()
val := q.Get("as")
if val != "" {
userIDInt, err := strconv.Atoi(val)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
userID = int64(userIDInt)
}
}
ctx := r.Context()
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
tx, err := database.BeginTx(ctx, &sql.TxOptions{ReadOnly: readonly})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = serveFunc(w, r, userID, tx)
if err != nil {
tx.Rollback()
if strings.HasPrefix(route, "/api/") {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(JSONError{Error: err.Error()})
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
} else {
tx.Commit()
}
})
mux.Handle(route, handler)
}
fs := http.FileServer(http.Dir("static"))
mux.Handle("/static/", http.StripPrefix("/static/", fs))
if useAuth {
log.Printf("setting up auth routes...")
addHandler("/auth/discord/login", oauthDiscordLogin, true) // don't actually need db at all
addHandler("/auth/discord/callback", oauthDiscordCallback, false)
}
addHandler("/api/draft/", ServeAPIDraft, true)
addHandler("/api/draftlist/", ServeAPIDraftList, true)
addHandler("/api/pick/", ServeAPIPick, false)
addHandler("/api/join/", ServeAPIJoin, false)
addHandler("/api/skip/", ServeAPISkip, false)
addHandler("/api/prefs/", ServeAPIPrefs, true)
addHandler("/api/setpref/", ServeAPISetPref, false)
addHandler("/api/dev/forceEnd/", ServeAPIForceEnd, false)
addHandler("/", ServeVueApp, true)
return mux
}
func HandleLogin(w http.ResponseWriter, r *http.Request, userID int64, tx *sql.Tx) error {
t := template.Must(template.ParseFiles("login.tmpl"))
t.Execute(w, nil)
return nil
}
// ServeAPIDraft serves the /api/draft endpoint.
func ServeAPIDraft(w http.ResponseWriter, r *http.Request, userID int64, tx *sql.Tx) error {
re := regexp.MustCompile(`/api/draft/(\d+)`)
parseResult := re.FindStringSubmatch(r.URL.Path)
if parseResult == nil {
return fmt.Errorf("bad api url")
}
draftID, err := strconv.ParseInt(parseResult[1], 10, 64)
if err != nil {
return fmt.Errorf("bad api url: %s", err.Error())
}
draftJSON, err := GetFilteredJSON(tx, draftID, userID)
if err != nil {
return fmt.Errorf("error getting json: %s", err.Error())
}
fmt.Fprint(w, draftJSON)
return nil
}
// ServeAPIDraftList serves the /api/draftlist endpoint.
func ServeAPIDraftList(w http.ResponseWriter, r *http.Request, userID int64, tx *sql.Tx) error {
drafts, err := GetDraftList(userID, tx)
if err != nil {
return err
}
json.NewEncoder(w).Encode(drafts)
return nil
}
// ServeAPIPrefs serves the /api/prefs endpoint.
func ServeAPIPrefs(w http.ResponseWriter, r *http.Request, userID int64, tx *sql.Tx) error {
prefs, err := GetUserPrefs(userID, tx)
if err != nil {
return err
}
json.NewEncoder(w).Encode(prefs)
return nil
}
// ServeAPISetPref serves the /api/setpref endpoint.
func ServeAPISetPref(w http.ResponseWriter, r *http.Request, userID int64, tx *sql.Tx) error {
if r.Method != "POST" {
// we have to return an error manually here because we want to return
// a different http status code.
tx.Rollback()
http.Error(w, "invalid request method", http.StatusMethodNotAllowed)
return nil
}
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
return fmt.Errorf("error reading post body: %s", err.Error())
}
var pref PostedPref
err = json.Unmarshal(bodyBytes, &pref)
if err != nil {
return fmt.Errorf("error parsing post body: %s", err.Error())
}
if pref.FormatPref.Format != "" {
var query string
if dg != nil {
query := `select discord_id from users where id = ?`
row := tx.QueryRow(query, userID)
var discordId sql.NullString
err = row.Scan(&discordId)
if err != nil {
return err
}
if !discordId.Valid {
return fmt.Errorf("user %d with no discord ID can't enable formats", userID)
}
member, err := dg.GuildMember(makedraft.GUILD_ID, discordId.String)
if err != nil {
return err
}
isDraftFriend := false
for _, role := range member.Roles {
if role == DRAFT_FRIEND_ROLE {
isDraftFriend = true
}
}
if !isDraftFriend {
return fmt.Errorf("user %d is not draft friend, can't enable formats", userID)
}
}
var elig int
if pref.FormatPref.Elig {
elig = 1
} else {
elig = 0
}
query = `update userformats set elig = ? where user = ? and format = ?`
_, err = tx.Exec(query, elig, userID, pref.FormatPref.Format)
if err != nil {
return fmt.Errorf("error updating user pref: %s", err.Error())
}
}
if pref.MtgoName != "" {
query := `update users set mtgo_name = ? where id = ?`
_, err = tx.Exec(query, pref.MtgoName, userID)
if err != nil {
return fmt.Errorf("error updating user MTGO name: %s", err.Error())
}
}
return ServeAPIPrefs(w, r, userID, tx)
}
// ServeAPIPick serves the /api/pick endpoint.
func ServeAPIPick(w http.ResponseWriter, r *http.Request, userID int64, tx *sql.Tx) error {
if r.Method != "POST" {
// we have to return an error manually here because we want to return
// a different http status code.
tx.Rollback()
http.Error(w, "invalid request method", http.StatusMethodNotAllowed)
return nil
}
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
return fmt.Errorf("error reading post body: %s", err.Error())
}
var pick PostedPick
err = json.Unmarshal(bodyBytes, &pick)
if err != nil {
return fmt.Errorf("error parsing post body: %s", err.Error())
}
var draftID int64
if len(pick.CardIds) == 1 {
draftID, err = doSinglePick(tx, userID, pick.CardIds[0])
if err == nil && !xsrftoken.Valid(pick.XsrfToken, xsrfKey, strconv.FormatInt(userID, 16), fmt.Sprintf("pick%d", draftID)) {
err = fmt.Errorf("invalid XSRF token")
}
if err != nil {
// We can't send the actual error back to the client without leaking information about
// where the card they tried to pick actually is.
log.Printf("error making pick: %s", err.Error())
return fmt.Errorf("error making pick")
}
} else if len(pick.CardIds) == 2 {
return fmt.Errorf("cogwork librarian power not implemented yet")
} else {
return fmt.Errorf("invalid number of picked cards: %d", len(pick.CardIds))
}
draftJSON, err := GetFilteredJSON(tx, draftID, userID)
if err != nil {
return fmt.Errorf("error getting json: %s", err.Error())
}
fmt.Fprint(w, draftJSON)
return nil
}
// ServeAPIJoin serves the /api/join endpoint.
func ServeAPIJoin(w http.ResponseWriter, r *http.Request, userID int64, tx *sql.Tx) error {
if r.Method != "POST" {
// we have to return an error manually here because we want to return
// a different http status code.
tx.Rollback()
http.Error(w, "invalid request method", http.StatusMethodNotAllowed)
return nil
}
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
return fmt.Errorf("error reading post body: %s", err.Error())
}
var toJoin PostedJoin
err = json.Unmarshal(bodyBytes, &toJoin)
if err != nil {
return fmt.Errorf("error parsing post body: %s", err.Error())
}
draftID := toJoin.ID
err = doJoin(tx, userID, draftID)
if err != nil {
return fmt.Errorf("error joining draft %d: %s", draftID, err.Error())
}
draftJSON, err := GetFilteredJSON(tx, draftID, userID)
if err != nil {
return fmt.Errorf("error getting json: %s", err.Error())
}
fmt.Fprint(w, draftJSON)
return nil
}
// doJoin does the actual joining.
func doJoin(tx *sql.Tx, userID int64, draftID int64) error {
query := `select
count(1)
from seats
where draft = ?
and user = ?`
row := tx.QueryRow(query, draftID, userID)
var alreadyJoined int64
err := row.Scan(&alreadyJoined)
if err != nil {
return err
} else if alreadyJoined > 0 {
return fmt.Errorf("user %d already joined %d", userID, draftID)
}
query = `select
id, seats.reserveduser
from seats
where draft = ?
and user is null
order by seats.reserveduser = ? desc, random()
limit 1`
row = tx.QueryRow(query, draftID, userID)
var emptySeatID int64
var reservedUser sql.NullInt64
err = row.Scan(&emptySeatID, &reservedUser)
if err != nil {
return err
}
if reservedUser.Valid && reservedUser.Int64 != userID {
return fmt.Errorf("no non-reserved seats available for user %d in draft %d", userID, draftID)
}
query = `update seats set user = ? where id = ?`
_, err = tx.Exec(query, userID, emptySeatID)
if err != nil {
return err
}
if dg != nil {
query = `select spectatorchannelid from drafts where id = ?`
row = tx.QueryRow(query, draftID)
var channelID string
err = row.Scan(&channelID)
if err != nil {
log.Printf("no spectator channel found for draft %d", draftID)
} else {
query = `select discord_id from users where id = ?`
row = tx.QueryRow(query, userID)
var discordID string
err = row.Scan(&discordID)
if err != nil {
log.Printf("no discord ID for user %d", userID)
} else {
err = dg.ChannelPermissionSet(channelID, discordID, "1", 0, discordgo.PermissionViewChannel)
if err != nil {
log.Printf("error locking spectator channel for user %s: %s", discordID, err.Error())
}
}
}
}
return nil
}
// ServeAPISkip serves the /api/skip endpoint.
func ServeAPISkip(w http.ResponseWriter, r *http.Request, userID int64, tx *sql.Tx) error {
if r.Method != "POST" {
// we have to return an error manually here because we want to return
// a different http status code.
tx.Rollback()
http.Error(w, "invalid request method", http.StatusMethodNotAllowed)
return nil
}
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
return fmt.Errorf("error reading post body: %s", err.Error())
}
var toJoin PostedJoin
err = json.Unmarshal(bodyBytes, &toJoin)
if err != nil {
return fmt.Errorf("error parsing post body: %s", err.Error())
}
draftID := toJoin.ID
err = doSkip(tx, userID, draftID)
if err != nil {
return fmt.Errorf("error skipping draft %d: %s", draftID, err.Error())
}
draftJSON, err := GetFilteredJSON(tx, draftID, userID)
if err != nil {
return fmt.Errorf("error getting json: %s", err.Error())
}
fmt.Fprint(w, draftJSON)
return nil
}
// doSkip does the actual skipping.
func doSkip(tx *sql.Tx, userID int64, draftID int64) error {
query := `select
count(1)
from seats
where draft = ?
and user = ?`
row := tx.QueryRow(query, draftID, userID)
var alreadyJoined int64
err := row.Scan(&alreadyJoined)
if err != nil {
return err
} else if alreadyJoined > 0 {
return fmt.Errorf("user %d already joined %d", userID, draftID)
}
query = `select
id
from seats
where draft = ?
and reserveduser = ?
limit 1`
row = tx.QueryRow(query, draftID, userID)
var reservedSeatID int64
err = row.Scan(&reservedSeatID)
if err != nil {
return err
}
query = `insert into skips (user, draft) values (?, ?)`
_, err = tx.Exec(query, userID, draftID)
if err != nil {
return err
}
query = `select format from drafts where id = ?`
row = tx.QueryRow(query, draftID)
var format string
err = row.Scan(&format)
if err != nil {
return err
}
query = `update userformats set epoch = epoch - 1 where user = ? and format = ?`
_, err = tx.Exec(query, userID, format)
if err != nil {
return err
}
newUser, err := makedraft.AssignSeats(tx, draftID, format, 1)
if err != nil {
return err
}
if len(newUser) > 0 {
query = `update seats set reserveduser = ? where id = ?`
_, err = tx.Exec(query, newUser[0], reservedSeatID)
} else {
query = `update seats set reserveduser = null where id = ?`
_, err = tx.Exec(query, reservedSeatID)
}
if err != nil {
return err
}
return nil
}
// ServeAPIForceEnd serves the /api/dev/forceEnd testing endpoint.
func ServeAPIForceEnd(_ http.ResponseWriter, r *http.Request, userID int64, tx *sql.Tx) error {
if userID == 1 {
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
return fmt.Errorf("error reading post body: %s", err.Error())
}
var toJoin PostedJoin
err = json.Unmarshal(bodyBytes, &toJoin)
if err != nil {
return fmt.Errorf("error parsing post body: %s", err.Error())
}
draftID := toJoin.ID
return NotifyEndOfDraft(tx, draftID)
} else {
return http.ErrBodyNotAllowed
}
}
// ServeVueApp serves to vue.
func ServeVueApp(w http.ResponseWriter, r *http.Request, userID int64, tx *sql.Tx) error {
var userInfo UserInfo
if userID != 0 {
query := `select
id,
discord_name,
mtgo_name,
picture
from users
where id = ?`
row := tx.QueryRow(query, userID)
var mtgoName sql.NullString
err := row.Scan(&userInfo.ID, &userInfo.Name, &mtgoName, &userInfo.Picture)
if err != nil {
return err
}
if mtgoName.Valid {
userInfo.MtgoName = mtgoName.String
}
}
userInfoJSON, err := json.Marshal(userInfo)
if err != nil {
return err
}
data := VuePageData{UserJSON: string(userInfoJSON)}
t := template.Must(template.ParseFiles("vue.tmpl"))
t.Execute(w, data)
return nil
}
// doSinglePick performs a normal pick based on a user id and a card id. It returns the draft id and an error.
func doSinglePick(tx *sql.Tx, userID int64, cardID int64) (int64, error) {
draftID, _, announcements, round, err := doPick(tx, userID, cardID, true)
if err != nil {
return draftID, err
}
err = doEvent(tx, draftID, userID, announcements, cardID, sql.NullInt64{}, round)
if err != nil {
return draftID, err
}
return draftID, nil
}
// doPick actually performs a pick in the database.
// It returns the draftID, packID, announcements, round, and an error.
// Of those return values, packID and announcements are only really relevant for Cogwork Librarian,
// which is not currently fully implemented, but we leave them here anyway for when we want to do that.
func doPick(tx *sql.Tx, userID int64, cardID int64, pass bool) (int64, int64, []string, int64, error) {
announcements := []string{}
// First we need information about the card. Determine which pack the card is in,
// where that pack is at the table, who sits at that position, which draft that
// pack is a part of, and which round that card is in.
query := `select
packs.id,
seats.position,
seats.draft,
seats.user,
seats.round
from cards
join packs on cards.pack = packs.id
join seats on packs.seat = seats.id
where cards.id = ?`
row := tx.QueryRow(query, cardID)
var myPackID int64
var position int64
var draftID int64
var userID2 int64
var round int64
err := row.Scan(&myPackID, &position, &draftID, &userID2, &round)
if err != nil {
return draftID, myPackID, announcements, round, err
} else if userID != userID2 {
return draftID, myPackID, announcements, round, fmt.Errorf("card does not belong to the user.")
} else if round == 0 {
return draftID, myPackID, announcements, round, fmt.Errorf("card has already been picked.")
}
// Now get the pack id that the user is allowed to pick from in the draft that the
// card is from. Note that there might be no such pack.
query = `select
v_packs.id
from seats
join v_packs on seats.id = v_packs.seat
where seats.user = ?
and seats.draft = ?
and seats.round = v_packs.round
order by v_packs.count desc
limit 1`
row = tx.QueryRow(query, userID, draftID)
var myPackID2 int64
err = row.Scan(&myPackID2)
if err != nil {
return draftID, myPackID, announcements, round, err
} else if myPackID != myPackID2 {
return draftID, myPackID, announcements, round, fmt.Errorf("card is not in the next available pack.")
}
// once we're here, we know the pick is valid
// Determine which pack we're putting the drafted card into.
query = `select
v_packs.id,
v_packs.count
from v_packs
join seats on seats.id = v_packs.seat
where v_packs.round = 0
and seats.user = ?
and seats.draft = ?`
row = tx.QueryRow(query, userID, draftID)
var myPicksID int64
var myCount int64
err = row.Scan(&myPicksID, &myCount)
if err != nil {
return draftID, myPackID, announcements, round, err
}
// Are we passing the pack after we've picked the card?
if pass {
// Get the seat position that the pack will be passed to.
var newPosition int64
if round%2 == 0 {
newPosition = position - 1
if newPosition == -1 {
newPosition = 7
}
} else {
newPosition = position + 1
if newPosition == 8 {
newPosition = 0
}
}
// Now get the seat id that the pack will be passed to.
query = `select
seats.id,
users.discord_id
from seats
left join users on seats.user = users.id
where seats.draft = ?
and seats.position = ?`
row = tx.QueryRow(query, draftID, newPosition)
var newPositionID int64
var newPositionDiscordID sql.NullString
err = row.Scan(&newPositionID, &newPositionDiscordID)
if err != nil {
return draftID, myPackID, announcements, round, err
}
// Put the picked card into the player's picks.
query = `update cards set pack = ? where id = ?`
_, err = tx.Exec(query, myPicksID, cardID)
if err != nil {
return draftID, myPackID, announcements, round, err
}
// Move the pack to the next seat.
query = `update packs set seat = ? where id = ?`
_, err = tx.Exec(query, newPositionID, myPackID)
if err != nil {
return draftID, myPackID, announcements, round, err
}
// Get the number of remaining packs in the seat.
query = `select
count(1)
from v_packs
join seats on v_packs.seat = seats.id
where seats.user = ?
and v_packs.round = ?
and v_packs.count > 0
and seats.draft = ?`
row = tx.QueryRow(query, userID, round, draftID)
var packsLeftInSeat int64
err = row.Scan(&packsLeftInSeat)
if err != nil {
return draftID, myPackID, announcements, round, err
}
if packsLeftInSeat == 0 {
// If there are 0 packs left in the seat, check to see if the player we passed the pack to
// is in the same round as us. If the rounds match, NotifyByDraftAndPosition.
query = `select
count(1)
from seats a
join seats b on a.draft = b.draft
where a.user = ?
and b.position = ?
and a.draft = ?
and a.round = b.round`
row = tx.QueryRow(query, userID, newPosition, draftID)
var roundsMatch int64
err = row.Scan(&roundsMatch)
if err != nil {
log.Printf("cannot determine if rounds match for notify")
} else if roundsMatch == 1 && newPositionDiscordID.Valid {
log.Printf("attempting to notify position %d draft %d", newPosition, draftID)
err = NotifyByDraftAndDiscordID(draftID, newPositionDiscordID.String)
if err != nil {
log.Printf("error with notify")
}
}
// Now that we've passed the pack, check to see if we should advance to the next round.
// Update our round.
// WARNING: if you ever have a draft with anything other than 15 cards per pack, or you have
// something like Lore Seeker in your draft, this is going to break horribly.
// If we're only doing normal drafts, round is effectively something that can be calculated,
// but by explicitly storing it, we allow ourselves the possibility of expanding support to
// weirder formats.
query = `update seats set round = ? where user = ? and draft = ?`
_, err = tx.Exec(query, (myCount+1)/15+1, userID, draftID)
if err != nil {
return draftID, myPackID, announcements, round, err
}
// If the rounds do NOT match from earlier, we have a situation where players are in different
// rounds. Look for a blocking player.
if roundsMatch == 0 {
// We now know that we've passed a pack to someone in a different round.
// We know that player is necessarily in a round earlier than ours because
// we couldn't pass them a pack from a round they're already finished with.
// That means we did not send a notification, because that player can't yet
// pick from that pack.
// That means there is a chance someone else is blocking the draft and needs
// a friendly reminder to make their picks.
// Before we find the blocking player, we need to make sure we're not the
// only ones in this round.
// If we are the only ones in this round, we very likely just passed the
// blocking player their last pick of their round, so they are very likely
// the most recent ping. We don't want to double ping.
query = `select
count(1)
from seats
where draft = ?
group by round
order by round desc
limit 1`
row = tx.QueryRow(query, draftID)
var nextRoundPlayers int64
err = row.Scan(&nextRoundPlayers)
if err != nil {
log.Printf("error counting players and rounds")
} else if nextRoundPlayers == 8 && myCount+1 == 45 {
// The draft is over. Notify the admin.
err = NotifyEndOfDraft(tx, draftID)
if err != nil {
log.Printf("error notifying end of draft: %s", err.Error())
}
} else if nextRoundPlayers > 1 {
// Now we know that we are not the only player in this round.
// Get the position of all players that currently have a pick.
query = `select
seats.position,
users.discord_id
from seats
left join v_packs on seats.id = v_packs.seat
join users on seats.user = users.id
where v_packs.count > 0
and v_packs.round = seats.round
and seats.draft = ?
group by seats.id`
rows, err := tx.Query(query, draftID)
if err != nil {
log.Printf("error determining if there's a blocking player")
} else {
defer rows.Close()
rowCount := 0
var blockingPosition int64
var blockingDiscordID sql.NullString
for rows.Next() {
rowCount++
err = rows.Scan(&blockingPosition, &blockingDiscordID)
if err != nil {
log.Printf("some kind of error with scanning: %s", err.Error())
rowCount = 2
break
}
}
if rowCount == 1 && blockingDiscordID.Valid {
err = NotifyByDraftAndDiscordID(draftID, blockingDiscordID.String)
if err != nil {
log.Printf("error with blocking notify")
}
}
}
}
}
}
} else {
// we're in some sort of non-working cogwork librarian situation
// just take the card from the pack.
query = `update cards set pack = ? where id = ?`
_, err = tx.Exec(query, myPicksID, cardID)
if err != nil {
return draftID, myPackID, announcements, round, err
}
}
log.Printf("player %d in draft %d took card %d", userID, draftID, cardID)
return draftID, myPackID, announcements, round, nil
}
// NotifyByDraftAndDiscordID sends a discord alert to a user.
func NotifyByDraftAndDiscordID(draftID int64, discordID string) error {
return DiscordNotify(os.Getenv("PICK_ALERTS_CHANNEL_ID"),
fmt.Sprintf(`<@%s> you have new picks <http://draft.thefoley.net/draft/%d>`, discordID, draftID))
}
func NotifyEndOfDraft(tx *sql.Tx, draftID int64) error {
draftName, err := GetDraftName(tx, draftID)
if err != nil {
return err
}
err = PostFirstRoundPairings(tx, draftID, draftName)
if err != nil {
return err
}
err = NotifyAdminOfDraftCompletion(tx, draftID)
if err != nil {
return err
}
err = UnlockSpectatorChannel(tx, draftID)
return nil
}
func GetDraftName(tx *sql.Tx, draftID int64) (string, error) {
query := `select
name
from drafts
where drafts.id = ?`
row := tx.QueryRow(query, draftID)
var draftName string
err := row.Scan(&draftName)
if err != nil {
log.Print(err.Error())
}
return draftName, err
}
func PostFirstRoundPairings(tx *sql.Tx, draftID int64, draftName string) error {
query := `select
discord_id, discord_name
from users
inner join seats on users.id = seats.user
where seats.draft = ?
order by seats.position`