summaryrefslogtreecommitdiff
path: root/front/src/routes/bots.jsx
blob: 48f285ac4384bb23399d26c5c07651c448751c16 (plain)
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
import Modal from "react-modal";
import { useAuthContext } from "../context/auth_context";
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";

Modal.setAppElement("#root");

const BotButton = ({ onSave, givenBot }) => {
  const [open, setOpen] = useState(false);
  const [name, setName] = useState(givenBot?.name || "");
  const [webhook, setWebhook] = useState(givenBot?.webhook || "");
  const [errors, setErrors] = useState(null);
  const [isPublic, setIsPublic] = useState(givenBot?.public || false);

  const setDefaults = () => {
    setName("");
    setWebhook("");
    setErrors(null);
  };

  const close = () => {
    if (!givenBot) {
      setDefaults();
    }
    setOpen(false);
  };

  const updateBot = () => {
    fetch(givenBot ? `/api/player/bots/${givenBot.id}` : "/api/player/bots", {
      credentials: "same-origin",
      method: givenBot ? "PUT" : "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        webhook: webhook.trim(),
        name: name.trim(),
        public: isPublic,
      }),
    })
      .then((r) => r.json())
      .then((d) => {
        if (d.success) {
          if (onSave) {
            onSave();
          }
          close();
        } else if (d.errors) {
          if (typeof d.errors === "object") {
            setErrors(
              Object.keys(d.errors).map(
                (field) => `${field}: ${d.errors[field].join(",")}`
              )
            );
          } else {
            setErrors([d.errors]);
          }
        }
      });
  };

  return (
    <div>
      <ul>
        <li>
          It is Highly Recommend to peek at{" "}
          <Link to="/man-pages">the man pages</Link>.
        </li>
      </ul>
      <button className="button" onClick={() => setOpen(true)}>
        {givenBot ? "Update" : "+ Add"} Bot
      </button>
      {givenBot && (
        <>
          <button
            style={{ marginLeft: "1rem" }}
            className="button gold"
            onClick={() => {
              navigator.clipboard.writeText(givenBot?.token);
              alert("Bot's token was copied to the clipboard.");
            }}
          >
            Copy Token
          </button>
          <button
            style={{ marginLeft: "1rem" }}
            className="button red"
            onClick={() =>
              fetch(`/api/player/bots/${givenBot.id}/redrive`)
                .then((r) => r.json())
                .then(({ message }) => alert(message))
            }
          >
            Schedule Redrive
          </button>
        </>
      )}
      <Modal
        isOpen={open}
        onRequestClose={close}
        className="modal"
        contentLabel="Add Bot"
      >
        <div style={{ minWidth: "20vw" }}>
          <h3>Add Bot</h3>
          <hr />
          <p>Bot Name *</p>
          <input
            style={{ width: "100%" }}
            value={name}
            onChange={(e) => setName(e.target.value)}
            required
          />
        </div>
        <div>
          <p>Webhook *</p>
          <input
            style={{ width: "100%" }}
            value={webhook}
            onChange={(e) => setWebhook(e.target.value)}
            required
          />
        </div>
        <p>
          Public *{" "}
          <input
            type="checkbox"
            value={name}
            checked={isPublic}
            onChange={(e) => setIsPublic(!isPublic)}
            required
          />
        </p>
        <div>
          {errors && (
            <div style={{ color: "red" }}>
              {errors.map((error, i) => (
                <p key={i}>{error}</p>
              ))}
            </div>
          )}
        </div>
        <div className="flex-end-row">
          <button className="button" onClick={updateBot}>
            {givenBot ? "Update" : "+ Add"}
          </button>
          <button className="button red" onClick={close}>
            Cancel
          </button>
        </div>
      </Modal>
    </div>
  );
};

export const BotCard = ({ botStruct, onSave }) => {
  const { name } = botStruct;
  return (
    <div className="key-card">
      <h4>{name}</h4>
      <BotButton onSave={onSave} givenBot={botStruct} />
    </div>
  );
};

export const Bots = () => {
  const {
    player: { id: userId },
  } = useAuthContext();
  const [bots, setBots] = useState(null);

  const refreshBots = () =>
    fetch("/api/player/bots")
      .then((r) => r.json())
      .then((bots) => setBots(bots));

  useEffect(() => {
    if (userId) {
      refreshBots();
    }
  }, [userId]);

  if (bots === null) return <p>Loading...</p>;

  return (
    <>
      <h1>Bots</h1>
      <BotButton onSave={refreshBots} />

      <div className="key-card-collection">
        {bots.length ? (
          bots.map((bot) => (
            <BotCard key={bot.id} onSave={refreshBots} botStruct={bot} />
          ))
        ) : (
          <p>Looks like you've got no bots, try adding one!</p>
        )}
      </div>
    </>
  );
};