|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "io/ioutil" |
| 6 | + "log" |
| 7 | + "net/http" |
| 8 | + "strconv" |
| 9 | + "strings" |
| 10 | + "time" |
| 11 | +) |
| 12 | + |
| 13 | +func BumpGuild(w http.ResponseWriter, r *http.Request) { |
| 14 | + var guild Guild |
| 15 | + |
| 16 | + // Read request body |
| 17 | + body, err := ioutil.ReadAll(r.Body) |
| 18 | + if err != nil { |
| 19 | + log.Print(err) |
| 20 | + WriteBumpResponse(w, http.StatusInternalServerError, "Unable to read request body", guild) |
| 21 | + return |
| 22 | + } |
| 23 | + |
| 24 | + // Unmarshal body into guild object |
| 25 | + err = json.Unmarshal(body, &guild) |
| 26 | + if err != nil { |
| 27 | + log.Print(err) |
| 28 | + if strings.Contains(err.Error(), "invalid character") { |
| 29 | + WriteBumpResponse(w, http.StatusBadRequest, "Request body contains invalid character", guild) |
| 30 | + return |
| 31 | + } |
| 32 | + WriteBumpResponse(w, http.StatusBadRequest, "Unable to process request body", guild) |
| 33 | + return |
| 34 | + } |
| 35 | + |
| 36 | + // check if GuildId's length is 18 |
| 37 | + if len(strconv.Itoa(guild.GuildId)) != 18 { |
| 38 | + errString := "GuildId does not conform to 18 character long integer requirement" |
| 39 | + log.Print(errString) |
| 40 | + WriteBumpResponse(w, http.StatusBadRequest, errString, guild) |
| 41 | + return |
| 42 | + } |
| 43 | + |
| 44 | + // Adding timestamp to guild object |
| 45 | + ts := time.Now().Unix() |
| 46 | + guild.Timestamp = ts |
| 47 | + |
| 48 | + if !gs.GuildInStore(guild) { |
| 49 | + // guild is not yet present in GuildStore |
| 50 | + gs.AddToStore(guild) |
| 51 | + WriteBumpResponse(w, http.StatusOK, "Guild added and bumped", guild) |
| 52 | + } else { |
| 53 | + // guild is present in GuildStore |
| 54 | + if gs.PastInterval(guild) { |
| 55 | + // guild.Timestamp has exceeded BUMP_INTERVAL, Timestamp has been updated (bumped) |
| 56 | + WriteBumpResponse(w, http.StatusOK, "Guild bumped", guild) |
| 57 | + } else { |
| 58 | + // guild.Timestamp has not exceeded BUMP_INTERVAL, not updated |
| 59 | + guild.Timestamp = gs.GetTimestamp(guild) |
| 60 | + WriteBumpResponse(w, http.StatusTooEarly, "Guild bumped too early", guild) |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + err = gs.WriteStore() |
| 65 | + if err != nil { |
| 66 | + log.Panic(err) |
| 67 | + WriteBumpResponse(w, http.StatusInternalServerError, "Could not store changes", guild) |
| 68 | + return |
| 69 | + } |
| 70 | +} |
0 commit comments