~vpzom/bracketmonster

ref: 3f93e6a525a10bee455767ccfdf8e16d002b1ff2 bracketmonster/rosebush/src/server/index.tsx -rw-r--r-- 10.7 KiB
3f93e6a5Colin Reeder no-js match edit 6 months ago
                                                                                
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
import * as acceptLanguageNegotiator from "accept-language-negotiator";
import * as fs from "fs";
import getStream from "get-stream";
import * as http from "http";
import * as httpProxy from "http-proxy";
import isomorphicCookie from "isomorphic-cookie";
import jsesc from "jsesc";
import fetch, { HeadersInit, RequestInit } from "node-fetch";
import * as path from "path";
import { Fragment, JSX, h } from "preact";
import { Dictionary, IntlProvider } from "preact-jsx-i18n";
import { render } from "preact-render-to-string";
import { Route, RouteProps, Router } from "preact-router";
import * as serveStatic from "serve-static";
import * as querystring from "querystring";
import { shuffle } from "@pacote/shuffle";

import App, { UserInfo } from "../client/App";
import { COOKIE_AGE } from "../client/constants";
import Data, { LoadState } from "../client/Data";
import Helmet, { rewindClear } from "../client/Helmet";
import { PreloadedDataContext } from "../client/preload";
import routes from "../client/routes";

const API_HOST = process.env.API_HOST || "http://localhost:5000";
const SOCKET_HOST = process.env.SOCKET_HOST || "ws://localhost:5555";

const assets = JSON.parse(fs.readFileSync("dist/client/webpack-assets.json", "utf-8"));
const chunks: Array<{files: string[]; modules: string[]}> = JSON.parse(fs.readFileSync("dist/client/chunk-manifest.json", "utf-8"));
const staticServer = serveStatic("dist/client", {index: false, immutable: true});

const langCtx = require.context("../client/lang", false, /\.json$/);
const lang: {[key: string]: Dictionary} = {};
langCtx.keys().forEach(key => {
	lang[path.basename(key, path.extname(key))] = langCtx(key);
});

interface RouteInfo {
	path: string;
	component: string;
}

const routesChildren = routes.map(info => {
	return <Route path={info.path} component={require("../client/pages/" + info.component).default} routeInfo={info} />;
});

const routePreloads: {[key: string]: string[]} = {};

routes.forEach(info => {
	routePreloads[info.component] = [];
});

chunks.forEach(chunk => {
	chunk.modules.forEach(moduleReq => {
		if(!moduleReq || moduleReq.indexOf("/pages/") < 0) return;
		for(const page in routePreloads) {
			if(moduleReq.indexOf("/pages/" + page) < 0) continue;
			routePreloads[page].push(...chunk.files);
		}
	});
});

console.log("hi");

const apiServer = httpProxy.createProxyServer({});
apiServer.on("proxyReq", function(proxyReq, req) {
	const token = isomorphicCookie.load("rosebushToken", req);
	if(token) {
		proxyReq.setHeader("Authorization", "Bearer " + token);
	}
});

function apiFetchRaw(srcReq: http.IncomingMessage, url: string, init?: RequestInit): ReturnType<typeof fetch> {
	const token = isomorphicCookie.load("rosebushToken", srcReq);

	const headers: HeadersInit = (init && init.headers) ? init.headers : {};

	if(token && !("Authorization" in headers)) {
		// probably shouldn't cast this, but it's fine for now
		(headers as any).Authorization = "Bearer " + token;
	}

	return fetch(API_HOST + "/" + url, {...init, headers});
}

function apiFetch(srcReq: http.IncomingMessage, url: string, init?: RequestInit): ReturnType<typeof fetch> {
	return apiFetchRaw(srcReq, url, init)
		.then(res => {
			if(res.status < 200 || res.status >= 300) {
				return res.text()
					.then(text => Promise.reject(new Error(text)));
			}
			return res;
		});
}

const API_PREFIX = "/api/";

async function prepareData(srcReq: http.IncomingMessage, node: JSX.Element): Promise<unknown> {
	function selfFetch(url: string, init?: RequestInit) {
		if(url.startsWith(API_PREFIX)) {
			return apiFetchRaw(srcReq, url.substring(API_PREFIX.length), init);
		}
		else {
			throw new Error("Cannot preload data from outside of API");
		}
	}

	if(node && node.type === Route && "__loadData" in node.props.component) {
		const content = (node.props.component as any).__loadData(node.props, selfFetch);
		const data: {[K in keyof typeof content]: LoadState<unknown>} = {};
		await Promise.all(Object.keys(content).map(key => {
			return Data.wrapPromise(content[key])
			.then(result => {
					data[key] = result;
			});
		}));

		return data;
	}
}

http.createServer(async (req_, res) => {
	const req = req_ as (typeof req_ & {url: string});
	if(req.url.startsWith(API_PREFIX)) {
		req.url = req.url.substring(API_PREFIX.length - 1);
		apiServer.web(req, res, {target: API_HOST}, err => {
			console.error(err);
			try {
				res.writeHead(500);
				res.end("Connection to API server failed");
			} catch(err2) {
				console.error(err2);
			}
		});
	}
	else if(req.url.startsWith("/static/")) {
		req.url = req.url.substring(8);
		(staticServer as ((req: http.IncomingMessage, res: http.ServerResponse, callback: (err: unknown) => void) => void))(req, res, err => {
			if(err) {
				console.error(err);
				res.writeHead(500);
				res.write("Error serving content");
				res.end();
			}
			res.writeHead(404);
			res.write("Not Found");
			res.end();
		});
	}
	else if(req.url.startsWith("/formSubmit/")) {
		if(req.method !== "POST") {
			res.writeHead(405);
			res.write("formSubmit can only be used with POST");
			res.end();
			return;
		}
		const rest = req.url.substring(12);
		try {
			const fields = querystring.decode(await getStream(req));
			if(rest === "login") {
				const resp = await apiFetchRaw(req, "unstable/loginSessions", {method: "POST", body: JSON.stringify({
					username: fields.username,
					password: fields.password,
				})});

				if(resp.status < 200 || resp.status >= 300) {
					const text = await resp.text();
					res.writeHead(resp.status);
					res.write(text);
					res.end();
					return;
				}

				const result = await resp.json();

				const token = result.token;

				res.writeHead(
					303,
					{"Set-Cookie": "rosebushToken=" + token + "; Path=/; Max-Age=" + COOKIE_AGE, Location: fields.continue || "/myBrackets"}
				);
				res.write("Successfully logged in.");
				res.end();
			}
			else if(rest === "newBracket") {
				let newUserToken = null;
				const newHeaders: {[key: string]: string} = {};
				if(fields.newUser) {
					const resp = await apiFetch(req, "v1/users", {method: "POST"})
						.then(resp => resp.json());

					newUserToken = resp.token;
				}

				if(newUserToken !== null) {
					newHeaders.Authorization = "Bearer " + newUserToken;
				}	

				let players = String(fields.playerList).split("\n");

				if(fields.shufflePlayers) {
					players = shuffle(players);
				}

				const resp = await apiFetchRaw(req, "v1/brackets", {method: "POST", body: JSON.stringify({
					name: fields.bracketName,
					players,
					type: fields.bracketType,
					use_scores: !!fields.use_scores,
				}), headers: newHeaders});

				if(resp.status < 200 || resp.status >= 300) {
					const text = await resp.text();
					res.writeHead(resp.status);
					res.write(text);
					res.end();
					return;
				}

				const result = await resp.json();

				const newID = result.id;

				const outHeaders: {[key: string]: string} = {
					Location: "/bracket/" + newID,
				};

				if(newUserToken !== null) {
					outHeaders["Set-Cookie"] = "rosebushToken=" + newUserToken + "; Path=/; Max-Age=" + COOKIE_AGE;
				}

				res.writeHead(
					303,
					outHeaders,
				);
				res.write("Created bracket " + newID);
				res.end();
			}
			else if(rest === "bracketInfoEdit") {
				const resp = await apiFetchRaw(
					req,
					"v1/brackets/" + fields.bracket,
					{
						method: "PATCH",
						body: JSON.stringify({
							name: fields.bracketName,
							description_md: fields.description_md,
						}),
					},
				);

				if(resp.status < 200 || resp.status >= 300) {
					const text = await resp.text();
					res.writeHead(resp.status);
					res.write(text);
					res.end();
					return;
				}

				res.writeHead(303, {Location: "/bracket/" + fields.bracket});
				res.write("Successfully edited.");
				res.end();
			}
			else if(rest === "matchEdit") {
				let winner;

				if(fields.winner === "null") winner = null;
				else winner = parseInt(String(fields.winner), 10);

				const resp = await apiFetchRaw(
					req,
					"v1/brackets/" + fields.bracket + "/matches/" + fields.match,
					{
						method: "PATCH",
						body: JSON.stringify({
							scores: (fields["score[]"] as string[]).map(str => parseInt(str, 10)),
							winner,
						}),
					},
				);

				if(resp.status < 200 || resp.status >= 300) {
					const text = await resp.text();
					res.writeHead(resp.status);
					res.write(text);
					res.end();
					return;
				}

				res.writeHead(303, {Location: "/bracket/" + fields.bracket});
				res.write("Successfully edited.");
				res.end();
			}
			else {
				res.writeHead(404);
				res.write("Not Found");
				res.end();
			}
		} catch(e) {
			console.error(e);
			res.writeHead(500);
			res.write("Internal Server Error");
			res.end();
		}
	}
	else {
		const acceptLanguage = req.headers["accept-language"];
		const language = acceptLanguage ?
			acceptLanguageNegotiator.lookup(String(acceptLanguage), Object.keys(lang), "en") :
			"en";
		const dictionary = lang[language];
		try {
			const currentRoute: JSX.Element | undefined = Router.prototype.getMatchingChildren(routesChildren, req.url, true)[0];

			const [userInfo, preloadedData]: [UserInfo | null | undefined, unknown] = await Promise.all([
					isomorphicCookie.load("rosebushToken", req) ?
						apiFetch(req, "unstable/users/~me")
							.then(res => res.json()) :
						null,
					prepareData(req, currentRoute),
			]);

			const app = <PreloadedDataContext.Provider value={{take: () => preloadedData}}>
				<IntlProvider dictionary={dictionary}>
					<App url={req.url} initUserInfo={userInfo} routes={routesChildren} />
				</IntlProvider>
			</PreloadedDataContext.Provider>;

			const content = render(app, {}, {pretty: true});
			const helmetInfo = rewindClear();

			const routeInfo: RouteInfo | undefined = currentRoute?.props?.routeInfo;

			const preloads = routeInfo ?
				routePreloads[routeInfo.component] :
				[];

			const headContent = render(<Fragment>{Helmet.renderContent(helmetInfo)}</Fragment>, {}, {pretty: true});

			res.writeHead(200, {"Content-type": "text/html; charset=UTF-8"});
			res.write(`<!DOCTYPE html>
<html>
	<head>
		<meta name="viewport" content="width=device-width, initial-scale=1">
		${headContent}
		<script type="text/javascript">
			var SOCKET_HOST = ${JSON.stringify(SOCKET_HOST)};
			var INIT_USER_INFO = ${JSON.stringify(userInfo)};
			var LANGUAGE = ${JSON.stringify(language)};
			var PRELOADED_DATA = ${jsesc(preloadedData, {isScriptContext: true})};
		</script>
		${preloads.map(file => {
			return `<link rel="preload" href="/static/${file}" as="script">`;
		}).join("\n")}
		<link rel="stylesheet" href="${assets.main.css}">
	</head>
	<body>
		<div id="root">
${content}
		</div>
		<script type="text/javascript" src="${assets.main.js}"></script>
	</body>
</html>`);
			res.end();
		} catch(ex) {
			console.error(ex);

			res.writeHead(500);
			res.end("Internal Server Error");
		}
	}
}).listen(5757);