-
Notifications
You must be signed in to change notification settings - Fork 2
/
beancounter.ts
226 lines (217 loc) · 6.65 KB
/
beancounter.ts
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
if (process.env.NODE_ENV === "production") {
const Sentry = require("@sentry/node");
Sentry.init({
dsn: process.env.SENTRY_DSN,
});
}
import { promisify } from "util";
import * as R from "ramda";
import * as mqtt from "mqtt";
import { createHandyClient } from "handy-redis";
import { addRoll, addElimination, addKill } from "./stats";
import logger from "./logger";
import * as db from "./db";
import { addGameEvent } from "./table/games";
import { Command } from "./types";
import * as webPush from "web-push";
import { GAME_START_COUNTDOWN, TURN_SECONDS } from "./constants";
import { now } from "./timestamp";
import { getTable } from "./table/get";
process.on("unhandledRejection", (reason, p) => {
logger.error("Unhandled Rejection at: Promise", p, "reason:", reason);
// application specific logging, throwing an error, or other logic here
throw reason;
});
if (!process.env.VAPID_PUBLIC_KEY || !process.env.VAPID_PRIVATE_KEY) {
console.log(
"You must set the VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEY " +
"environment variables. You can use the following ones:"
);
console.log(webPush.generateVAPIDKeys());
} else {
webPush.setVapidDetails(
process.env.VAPID_URL!,
process.env.VAPID_PUBLIC_KEY!,
process.env.VAPID_PRIVATE_KEY!
);
}
const redisClient = createHandyClient({
host: process.env.REDIS_HOST,
});
var client = mqtt.connect(process.env.MQTT_URL, {
username: process.env.MQTT_USERNAME,
password: process.env.MQTT_PASSWORD,
});
client.subscribe("events");
client.subscribe("game_events");
client.on("message", async (topic, message) => {
if (topic === "events") {
const event = JSON.parse(message.toString());
if (event.type === "join") {
if (!event.user || event.bot) {
return;
}
// push notifications
if (!process.env.VAPID_PUBLIC_KEY || !process.env.VAPID_PRIVATE_KEY) {
return;
}
const subscriptions = await db.getPushSubscriptions("player-join");
const text = `${event.user.name} joined table "${event.table}"`;
subscriptions.forEach(async row => {
if (
row.subscription &&
event.user.id.toString() !== row.id.toString()
) {
console.log("PN", row.id, event.user.id);
try {
await webPush.sendNotification(
row.subscription,
JSON.stringify({
type: event.type,
timestamp: now(),
table: event.table,
text,
link: `https://qdice.wtf/${event.table}`,
}),
{
TTL: GAME_START_COUNTDOWN,
}
);
} catch (e) {
console.error("push subscription expired, removing", row.id, e);
try {
await db.removePushSubscription(row.id, row.subscription);
} catch (e) {
console.error(
"could not remove push subscription",
JSON.stringify({ id: row.id, subscription: row.subscription }),
e
);
}
}
}
});
} else if (event.type === "turn") {
// push notifications
if (!process.env.VAPID_PUBLIC_KEY || !process.env.VAPID_PRIVATE_KEY) {
return;
}
const subscriptions = await db.getPushSubscription(
"turn",
event.player.id
);
const text = `It's your turn on "${event.table}!"`;
if (subscriptions.some(row => row.subscription)) {
console.log("PN turn", event.player.id, subscriptions);
}
subscriptions.forEach(async row => {
if (!row.subscription) {
return;
}
try {
await webPush.sendNotification(
row.subscription,
JSON.stringify({
type: event.type,
timestamp: now(),
table: event.table,
text,
link: `https://qdice.wtf/${event.table}`,
}),
{
TTL: TURN_SECONDS,
}
);
} catch (e) {
console.error(
"push subscription expired, removing",
event.player.id,
e
);
try {
await db.removePushSubscription(event.player.id, row.subscription);
} catch (e) {
console.error(
"could not remove push subscription",
JSON.stringify({
id: event.player.id,
subscription: row.subscription,
}),
e
);
}
}
});
} else if (event.type === "countdown") {
const { table, players } = event;
// push notifications
if (!process.env.VAPID_PUBLIC_KEY || !process.env.VAPID_PRIVATE_KEY) {
return;
}
const subscriptions = await db.getPushSubscriptions("game-start");
const text = `A game countdown has started in "${table}"`;
subscriptions.forEach(async row => {
if (
row.subscription &&
!players.some((player: any) => player.id === row.id) // don't notify players in game
) {
try {
const request = await webPush.sendNotification(
row.subscription,
JSON.stringify({
type: event.type,
timestamp: now(),
table: event.table,
text,
link: `https://qdice.wtf/${event.table}`,
}),
{
TTL: GAME_START_COUNTDOWN,
}
);
console.log("PN", row.name, request);
} catch (e) {
// console.error(e);
// TODO remove subscription if unsubscribed or expired
}
}
});
} else if (event.type === "elimination") {
if (!event.player.bot) {
await addElimination(event.player, event.position);
await db.addElimination(event);
}
if (event.killer && !event.killer.bot) {
await addKill(event.killer);
}
}
} else if (topic === "game_events") {
const {
tableName,
gameId,
command,
}: {
tableName: string;
gameId: number;
command: Command;
} = JSON.parse(message.toString());
const eventId = await addGameEvent(tableName, gameId, command);
switch (command.type) {
case "Roll":
if (command.round > 1) {
await addRoll(
command.attacker,
command.fromRoll,
command.defender,
command.toRoll
);
}
break;
}
}
});
logger.info("Beancounter is connecting to postgres...");
(async () => {
await db.retry();
logger.info("Beancounter is counting beans.");
})();