-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
204 lines (186 loc) · 5.61 KB
/
server.js
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
const { Client, Intents } = require("discord.js");
const path = require("path");
const util = require("util");
const { MongoClient, ServerApiVersion } = require("mongodb");
const fs = require("fs");
const crypto = require("crypto");
const { PassThrough } = require("stream");
const ndjson = require("ndjson");
const { google } = require("googleapis");
const firebaseAdmin = require("firebase-admin");
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(
require("./.data/credentials/service-account.json")
),
databaseURL:
"https://showdownspace-default-rtdb.asia-southeast1.firebasedatabase.app",
});
const googleAuth = new google.auth.GoogleAuth({
keyFile: "./.data/credentials/service-account.json",
scopes: ["https://www.googleapis.com/auth/drive"],
});
google.options({ auth: googleAuth });
const unscopedGoogleAuth = new google.auth.GoogleAuth({
keyFile: "./.data/credentials/service-account.json",
});
require("source-map-support").install();
const loggly = require("node-loggly-bulk").createClient({
token: process.env.LOGGLY_TOKEN,
subdomain: process.env.LOGGLY_SUBDOMAIN,
tags: ["showdownspace-bot"],
json: true,
});
// Require the fastify framework and instantiate it
const logStream = new PassThrough();
logStream.pipe(process.stdout);
logStream.pipe(ndjson.parse({ strict: false })).on("data", (m) => {
loggly.log(m);
});
const fastify = require("fastify")({
// set this to true for detailed logging:
logger: {
stream: logStream,
},
bodyLimit: 10 * 1048576,
});
const log = fastify.log;
let latestDeployment;
fs.mkdirSync(".data/blobs", { recursive: true });
if (fs.existsSync(".data/latest_deployment")) {
latestDeployment = fs.readFileSync(".data/latest_deployment", "utf8");
log.info("Latest deployment found.");
} else {
log.info("No deployment found.");
}
async function loadLatestDeployment() {
const file = fs.realpathSync(
".data/deployments/" + latestDeployment + "/index.js"
);
return require(file);
}
// MongoDB
const mongo = new MongoClient(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1,
});
mongo.connect();
const db = mongo.db();
// Discord
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_PRESENCES,
Intents.FLAGS.DIRECT_MESSAGES,
],
partials: ["CHANNEL"],
});
client.once("ready", () => {
console.log("Ready!");
});
const discordToken = process.env.DISCORD_TOKEN;
client.login(discordToken);
const context = {
processState: {},
client,
db,
fastify,
discordToken,
log,
firebaseAdmin,
google,
googleAuth,
unscopedGoogleAuth,
};
client.on("interactionCreate", async (interaction) => {
const logic = await loadLatestDeployment();
return logic.handleInteraction(context, interaction);
});
client.on("messageCreate", async (message) => {
const logic = await loadLatestDeployment();
return logic.handleMessage(context, message);
});
// Setup our static files
fastify.register(require("fastify-static"), {
root: path.join(__dirname, "public"),
prefix: "/", // optional: default '/'
});
// fastify-formbody lets us parse incoming forms
fastify.register(require("fastify-formbody"));
// point-of-view is a templating manager for fastify
fastify.register(require("point-of-view"), {
engine: {
handlebars: require("handlebars"),
},
});
function raise(code, message) {
const err = new Error(message);
err.statusCode = code;
throw err;
}
fastify.post("/deploy", async (request, reply) => {
if (request.body.token !== process.env.CODE_DEPLOY_TOKEN) {
raise(401, "Invalid deploy key");
}
for (const { filename, data, hash } of request.body.files) {
const blobPath = `.data/blobs/${hash}`;
if (data == null && !fs.existsSync(blobPath)) {
raise(400, "Missing data for hash " + hash);
}
if (data != null) {
fs.writeFileSync(blobPath, data, "utf8");
}
}
const hashes = request.body.files.map((f) => f.hash).sort();
const deploymentHash = crypto
.createHash("sha256")
.update(hashes.join(","))
.digest("hex");
const deploymentPath = `.data/deployments/${deploymentHash}`;
fs.mkdirSync(deploymentPath, { recursive: true });
for (const { filename, data, hash } of request.body.files) {
const blobPath = `.data/blobs/${hash}`;
try {
fs.linkSync(blobPath, `${deploymentPath}/${filename}`);
} catch (error) {
if (error.code !== "EEXIST") {
throw error;
}
}
}
fs.writeFileSync(".data/latest_deployment", deploymentHash);
latestDeployment = deploymentHash;
return "meow";
});
fastify.all("/showdown", async (request, reply) => {
const logic = await loadLatestDeployment();
return logic.handleHttpRequest(context, request, reply);
});
// Our main GET home page route, pulls from src/pages/index.hbs
fastify.get("/", function (request, reply) {
// params is an object we'll pass to our handlebars template
let params = {
greeting: "Hello Node!",
};
// request.query.paramName <-- a querystring example
reply.view("/src/pages/index.hbs", params);
});
// A POST route to handle form submissions
fastify.post("/", function (request, reply) {
let params = {
greeting: "Hello Form!",
};
// request.body.paramName <-- a form post example
reply.view("/src/pages/index.hbs", params);
});
// Run the server and report out to the logs
fastify.listen(process.env.PORT, "0.0.0.0", function (err, address) {
if (err) {
fastify.log.error(err);
process.exit(1);
}
console.log(`Your app is listening on ${address}`);
fastify.log.info(`server listening on ${address}`);
});