/
player_server.go
761 lines (657 loc) · 18.6 KB
/
player_server.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
package server
import (
"context"
"encoding/json"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/aakordas/creature_manager/pkg/abilities"
"github.com/aakordas/creature_manager/pkg/creature"
"github.com/aakordas/creature_manager/pkg/saves"
"github.com/aakordas/creature_manager/pkg/skills"
"github.com/gorilla/mux"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// #C TODO: If the Mongo driver fails to connect to the Mongo daemon, provide
// only roll functionality.
var (
client *mongo.Client
playersDatabase *mongo.Database
dbContext *context.Context
database = "creatures"
players = "players"
contextTimeout = 5 * time.Second
)
const (
serverError = "server error"
databaseError = "database error"
// playerNotFoundError = "player not found"
invalidPlayerNameError = "invalid player name"
)
// Connect initializes the interface and connects an application to the provided
// database.
func Connect(db string) {
client, err := mongo.NewClient(options.Client().ApplyURI(db))
if err != nil {
log.Fatal(err)
}
// TODO: context.WithClose. Return the close function and pass it in Disconnect.
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
playersDatabase = client.Database(database)
}
// Disconnect disconnecs the client from the database.
func Disconnect() {
err := client.Disconnect(*dbContext)
if err != nil {
log.Fatal(err)
}
}
// sendErrorResponse creates and sends a custom error response.
func sendErrorResponse(w http.ResponseWriter, enc *json.Encoder, s, l string, h int) {
// w.WriteHeader(h)
response := &errorResponse{s, l}
jsonEncode(w, enc, response)
}
// findPlayer returns the SingleResult of looking up the name of a single player
// in the database.
func findPlayer(ctx context.Context, col *mongo.Collection, name string) *mongo.SingleResult {
findResult := col.FindOne(ctx, bson.M{
"name": name,
})
return findResult
}
// AddPlayer is the handler that creates new players in the database.
func AddPlayer(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
vars := mux.Vars(r)
playerName := vars["name"]
if playerName == "" {
sendErrorResponse(w, enc, invalidPlayerNameError,
"A player's name should contain only characters.",
http.StatusBadRequest,
)
return
}
ctx, cancel := context.WithTimeout(context.Background(), contextTimeout)
defer cancel()
playersCollection := playersDatabase.Collection(players)
// Ensure that the provided name does not already exist in the databae.
findResult := findPlayer(ctx, playersCollection, playerName)
// Can this even happen?
if findResult == nil {
log.Println("Error in FindOne")
sendErrorResponse(w, enc, databaseError,
"An error was encountered while accessing the database",
http.StatusInternalServerError,
)
return
}
if findResult.Err() != mongo.ErrNoDocuments {
sendErrorResponse(w, enc,
"player exists",
"A player with the provided name already exists in the database.",
http.StatusBadRequest,
)
return
}
// A brand new player is of first level, with the initial proficiency
// bonus of +2 and only has their name associated with them. Everything
// else will have to be added by subsequent requests.
entry, err := bson.Marshal(creature.Creature{
Name: playerName,
Level: 1,
ProficiencyBonus: creature.ProficiencyBonusPerLevel[1],
})
if err != nil {
log.Println(err)
sendErrorResponse(w, enc, serverError,
"An error was encountered while processing the request.",
http.StatusBadRequest,
)
return
}
_, err = playersCollection.InsertOne(ctx, entry)
if err != nil {
log.Println(err)
sendErrorResponse(w, enc, databaseError,
"There was an error inserting the new entry in the database",
http.StatusInternalServerError,
)
return
}
w.WriteHeader(http.StatusCreated)
}
// emptyResponse models a response with an empty object.
type emptyResponse struct {
}
func getInfo(w http.ResponseWriter, r *http.Request, v interface{}) {
enc := json.NewEncoder(w)
player, err := getPlayer(w, r)
if err != nil {
return
}
w.WriteHeader(http.StatusFound)
var res interface{}
switch v.(type) {
case creature.Creature:
res = player
case abilities.Abilities:
res = player.Abilities
case skills.Skills:
res = player.Skills
case saves.SavingThrows:
res = player.SavingThrows
}
if res == nil {
jsonEncode(w, enc, emptyResponse{})
return
}
jsonEncode(w, enc, res)
}
// GetPlayer is the handler that returns the information about a player in the
// database.
func GetPlayer(w http.ResponseWriter, r *http.Request) {
var p creature.Creature
getInfo(w, r, p)
}
// DeletePlayer is the handler that deletes the specified player document from
// the database.
func DeletePlayer(w http.ResponseWriter, r *http.Request) {
enc := json.NewEncoder(w)
vars := mux.Vars(r)
playerName := vars["name"]
if playerName == "" {
sendErrorResponse(w, enc, invalidPlayerNameError,
"A player's name should contain only characters.",
http.StatusBadRequest,
)
return
}
ctx, cancel := context.WithTimeout(context.Background(), contextTimeout)
defer cancel()
playersCollection := playersDatabase.Collection("players")
_, err := playersCollection.DeleteOne(ctx, bson.M{
"name": playerName,
})
if err != nil {
log.Println(err)
sendErrorResponse(w, enc, databaseError,
"There was an error deleting the entry from the database",
http.StatusInternalServerError,
)
return
}
w.WriteHeader(http.StatusAccepted)
}
type missingPlayerError struct {
Name string
}
// Error implements the Error interface for missingPlayerError.
func (e missingPlayerError) Error() string {
return "No player found with name " + e.Name
}
// getPlayer returns a creature.Creature.
func getPlayer(w http.ResponseWriter, r *http.Request) (*creature.Creature, error) {
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
vars := mux.Vars(r)
playerName := vars["name"]
if playerName == "" {
sendErrorResponse(w, enc, invalidPlayerNameError,
"A player's name should contain only characters.",
http.StatusBadRequest,
)
return nil, missingPlayerError{playerName}
}
ctx, cancel := context.WithTimeout(context.Background(), contextTimeout)
defer cancel()
playersCollection := playersDatabase.Collection(players)
findResult := findPlayer(ctx, playersCollection, playerName)
// Can this even happen?
if findResult == nil {
log.Println(findResult.Err())
sendErrorResponse(w, enc, databaseError,
"An error was encountered while accessing the database.",
http.StatusInternalServerError,
)
return nil, missingPlayerError{playerName}
}
var player creature.Creature
err := findResult.Decode(&player)
// If no player was found, return an empty object.
if err != nil {
w.WriteHeader(http.StatusNotFound)
jsonEncode(w, enc, emptyResponse{})
return nil, missingPlayerError{playerName}
}
return &player, nil
}
// GetAbilities is the handler that returns the abilities information of a
// player in the database.
func GetAbilities(w http.ResponseWriter, r *http.Request) {
var a abilities.Abilities
getInfo(w, r, a)
}
// validAbility checks if the provided value is a valid ability.
func validAbility(a string) bool {
switch strings.ToLower(a) {
case abilities.Strength, abilities.Dexterity, abilities.Constitution,
abilities.Intelligence, abilities.Wisdom, abilities.Charisma:
return true
default:
return false
}
}
// calculatePassivePerception returns the passive perception of the creature,
// based on its wisdom and proficiency modifiers
func calculatePassivePerception(c creature.Creature, w int, pb int) int {
modifier := abilities.AbilityScoresAndModifiers[w]
perceptionProficiency := c.Skills[skills.Perception]
if perceptionProficiency != nil {
return 10 + modifier + pb
}
return 10 + modifier
}
// SetAbility is the handler that sets the requested ability of a player to
// the provided value.
func SetAbility(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
vars := mux.Vars(r)
playerName := vars["name"]
if playerName == "" {
sendErrorResponse(w, enc, invalidPlayerNameError,
"A player's name should contain only characters.",
http.StatusBadRequest,
)
return
}
ability := vars["ability"]
if !validAbility(ability) {
sendErrorResponse(w, enc,
"invalid ability name",
"Please provide a valid ability name.",
http.StatusBadRequest,
)
return
}
v := vars["number"]
value, err := strconv.Atoi(v)
if err != nil {
sendErrorResponse(w, enc,
"invalid ability value",
"Please provide a valid value for the ability.",
http.StatusBadRequest,
)
return
}
if abilities.OutOfRange(value) {
sendErrorResponse(w, enc,
"ability value out of range",
"Please provide a value within range.",
http.StatusBadRequest,
)
return
}
ctx, cancel := context.WithTimeout(context.Background(), contextTimeout)
defer cancel()
playersCollection := playersDatabase.Collection(players)
player, err := getPlayer(w, r)
if err != nil {
sendErrorResponse(w, enc,
"Could not fetch the player.",
"There was an error retrieving the player from the database.",
http.StatusBadRequest,
)
return
}
modifier := abilities.AbilityScoresAndModifiers[value]
query := bson.M{
"abilities." + ability: value,
"abilities." + ability + "_modifier": modifier,
}
if ability == abilities.Wisdom {
query["passive_perception"] = calculatePassivePerception(*player, value, player.Level)
}
// Changes the modifier of a skill, if it depends on this ability.
for skill := range player.Skills {
_, err = playersCollection.UpdateMany(ctx, bson.M{
"name": playerName,
"skills." + skill + ".modifier": ability,
}, bson.M{
"$set": bson.M{
"skills." + skill + ".value": modifier + player.ProficiencyBonus,
}})
if err != nil {
log.Println(err)
sendErrorResponse(w, enc, databaseError,
"There was an error updating the entry in the database.",
http.StatusInternalServerError,
)
return
}
}
_, err = playersCollection.UpdateOne(ctx, bson.M{
"name": playerName,
}, bson.M{
"$set": query,
})
if err != nil {
log.Println(err)
sendErrorResponse(w, enc, databaseError,
"There was an error updating the entry in the database.",
http.StatusInternalServerError,
)
return
}
w.WriteHeader(http.StatusOK)
}
// setNoUpsert sets the provided attribute to the provided value.
func setNoUpsert(w http.ResponseWriter, r *http.Request, enc *json.Encoder, filter, update interface{}) {
w.Header().Set("Content-Type", "application/json")
ctx, cancel := context.WithTimeout(context.Background(), contextTimeout)
defer cancel()
playersCollection := playersDatabase.Collection(players)
_, err := playersCollection.UpdateOne(ctx, filter, update)
if err != nil {
log.Println(err)
sendErrorResponse(w, enc, databaseError,
"There was an error updating the entry in the database.",
http.StatusInternalServerError,
)
return
}
w.WriteHeader(http.StatusOK)
}
// SetHitPoints is the handler that sets the hitpoints of the requested creature
// to the provided value.
func SetHitPoints(w http.ResponseWriter, r *http.Request) {
enc := json.NewEncoder(w)
vars := mux.Vars(r)
v := vars["number"]
value, err := strconv.Atoi(v)
if err != nil {
sendErrorResponse(w, enc,
"invalid value",
"Please provide a valid numeric value.",
http.StatusBadRequest,
)
}
playerName := vars["name"]
if playerName == "" {
sendErrorResponse(w, enc, invalidPlayerNameError,
"A player's name should contain only characters.",
http.StatusBadRequest,
)
return
}
f := bson.M{
"name": playerName,
}
u := bson.M{
"$set": bson.M{
"hit_points": value,
}}
setNoUpsert(w, r, enc, f, u)
}
// SetLevel is the handler that sets the hitpoints of the requested creature to
// the provided value.
func SetLevel(w http.ResponseWriter, r *http.Request) {
enc := json.NewEncoder(w)
vars := mux.Vars(r)
playerName := vars["name"]
if playerName == "" {
sendErrorResponse(w, enc, invalidPlayerNameError,
"A player's name should contain only characters.",
http.StatusBadRequest,
)
return
}
v := vars["number"]
value, err := strconv.Atoi(v)
if err != nil {
sendErrorResponse(w, enc,
"invalid value",
"Please provide a valid numeric value.",
http.StatusBadRequest,
)
}
if creature.OutOfRange(value) {
sendErrorResponse(w, enc,
"level value out of range",
"Plase provide a value within range.",
http.StatusBadRequest,
)
return
}
player, err := getPlayer(w, r)
if err != nil {
sendErrorResponse(w, enc,
"Could not fetch the player.",
err.Error(),
http.StatusBadRequest,
)
return
}
proficiencyBonus := creature.ProficiencyBonusPerLevel[value]
f := bson.M{
"name": playerName,
}
u := bson.M{
"$set": bson.M{
"level": value,
"proficiency_bonus": proficiencyBonus,
"passive_perception": calculatePassivePerception(
*player,
player.Abilities.Wisdom,
proficiencyBonus,
),
}}
setNoUpsert(w, r, enc, f, u)
}
// SetArmorClass is the handler that sets the armor class of the requested
// creature to the provided value.
func SetArmorClass(w http.ResponseWriter, r *http.Request) {
enc := json.NewEncoder(w)
vars := mux.Vars(r)
v := vars["number"]
value, err := strconv.Atoi(v)
if err != nil {
sendErrorResponse(w, enc,
"invalid value",
"Please provide a valid numeric value.",
http.StatusBadRequest,
)
}
playerName := vars["name"]
if playerName == "" {
sendErrorResponse(w, enc, invalidPlayerNameError,
"A player's name should contain only characters.",
http.StatusBadRequest,
)
return
}
f := bson.M{
"name": playerName,
}
u := bson.M{
"$set": bson.M{
"armor_class": value,
}}
setNoUpsert(w, r, enc, f, u)
}
// GetSkills is the handler that returns the skills information of a player in
// the database.
func GetSkills(w http.ResponseWriter, r *http.Request) {
var s skills.Skills
getInfo(w, r, s)
}
// validSkill checks if the provided value is a valid skill.
func validSkill(s string) bool {
switch strings.ToLower(s) {
case skills.Acrobatics, skills.AnimalHandling, skills.Arcana,
skills.Athletics, skills.Deception, skills.History,
skills.Insight, skills.Intimidation, skills.Investigation,
skills.Medicine, skills.Nature, skills.Perception,
skills.Performance, skills.Persuasion, skills.Religion,
skills.SleightOfHand, skills.Stealth, skills.Survival:
return true
default:
return false
}
}
func setUpsert(w http.ResponseWriter, r *http.Request, enc *json.Encoder, filter, update interface{}) {
w.Header().Set("Content-Type", "application/json")
playersCollection := playersDatabase.Collection(players)
ctx, cancel := context.WithTimeout(context.Background(), contextTimeout)
defer cancel()
opts := options.Update().SetUpsert(true)
_, err := playersCollection.UpdateOne(ctx, filter, update, opts)
if err != nil {
log.Println(err)
sendErrorResponse(w, enc, databaseError,
"There was an error updating the entry in the database.",
http.StatusInternalServerError,
)
return
}
w.WriteHeader(http.StatusOK)
}
// SetSkill is the handler that sets the requested skill of a player to the
// provided value.
func SetSkill(w http.ResponseWriter, r *http.Request) {
enc := json.NewEncoder(w)
vars := mux.Vars(r)
playerName := vars["name"]
if playerName == "" {
sendErrorResponse(w, enc, invalidPlayerNameError,
"A player's name should contain only characters.",
http.StatusBadRequest,
)
return
}
skill := vars["skill"]
if !validSkill(skill) {
sendErrorResponse(w, enc,
"invalid skill name",
"Please provide a valid skill name.",
http.StatusBadRequest,
)
return
}
player, err := getPlayer(w, r)
if err != nil {
sendErrorResponse(w, enc,
"Could not fetch the player.",
err.Error(),
http.StatusBadRequest,
)
return
}
abilityModifier := skills.SkillToAbility[skill]
var modifier int
switch abilityModifier {
case abilities.Strength:
modifier = player.StrengthModifier
case abilities.Dexterity:
modifier = player.DexterityModifier
case abilities.Constitution:
modifier = player.ConstitutionModifier
case abilities.Intelligence:
modifier = player.IntelligenceModifier
case abilities.Wisdom:
modifier = player.WisdomModifier
case abilities.Charisma:
modifier = player.CharismaModifier
}
f := bson.M{
"name": playerName,
}
u := bson.M{
"$set": bson.M{
"skills." + skill: bson.M{
"value": modifier + player.ProficiencyBonus,
"modifier": abilityModifier,
}}}
setUpsert(w, r, enc, f, u)
}
// GetSaves is the handler that returns the saving throws information of a
// player in the database.
func GetSaves(w http.ResponseWriter, r *http.Request) {
var s saves.SavingThrows
getInfo(w, r, s)
}
// validSave checks if the provided value is a valid saving throw.
func validSave(s string) bool {
switch strings.ToLower(s) {
case saves.Strength, saves.Dexterity, saves.Constitution,
saves.Intelligence, saves.Wisdom, saves.Charisma:
return true
default:
return false
}
}
// SetSave is the handler that sets the requested saving throw of a player in
// the database.
func SetSave(w http.ResponseWriter, r *http.Request) {
enc := json.NewEncoder(w)
vars := mux.Vars(r)
playerName := vars["name"]
if playerName == "" {
sendErrorResponse(w, enc, invalidPlayerNameError,
"A player's name should contain only characters.",
http.StatusBadRequest,
)
return
}
save := vars["save"]
if !validSave(save) {
sendErrorResponse(w, enc,
"invalid saving throw name",
"Please provide a valid saving throw name.",
http.StatusBadRequest,
)
return
}
player, err := getPlayer(w, r)
if err != nil {
sendErrorResponse(w, enc,
"Could not fetch the player.",
err.Error(),
http.StatusBadRequest,
)
return
}
f := bson.M{
"name": playerName,
}
var modifier int
switch save {
case "strength":
modifier = player.StrengthModifier
case "dexterity":
modifier = player.DexterityModifier
case "constitution":
modifier = player.ConstitutionModifier
case "intelligence":
modifier = player.IntelligenceModifier
case "wisdom":
modifier = player.WisdomModifier
case "charisma":
modifier = player.CharismaModifier
}
u := bson.M{
"$set": bson.M{
"saving_throws." + save: modifier + player.ProficiencyBonus,
}}
setUpsert(w, r, enc, f, u)
}