-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.ts
222 lines (205 loc) · 6.46 KB
/
index.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
import Koa from "koa";
import Router from "koa-router";
import json from "koa-json";
import logger from "koa-logger";
import views from "koa-views";
import bodyParser from "koa-bodyparser";
import serve from "koa-static";
import session from "koa-session";
import auth from "koa-basic-auth";
import { createServer } from "http";
import * as crypto from "crypto";
import registerHelpers from "./helpers/hbsHelpers";
import { addAPIHeaders } from "./helpers/utils";
import config from "./config";
import { registerComponentsWithinDirectory } from "./helpers/componentRegistration";
import { getStats, initializeCategories } from "./helpers/scouting";
// import loginRouter from "./routers/login"; // contains base route "/"
import defaultRouter from "./routers/default"; // contains base route "/"
import scoutingDefaultRouter from "./routers/scoutingDefault"; // contains base route "/"
import resourcesRouter from "./routers/resources";
import resourcesAPIRouter from "./routers/api/resources";
import scoutingRouter from "./routers/scouting";
import scoutingAPIRouter from "./routers/api/scouting";
import tpsAPIRouter from "./routers/api/tps";
const app = new Koa();
const sessionConfig: Partial<session.opts> = {
key: config.auth.cookieKeys[0],
maxAge: 1000 * 60 * 60 * 24 * 3 // 3 days
};
app.keys = config.auth.cookieKeys.slice(1);
app.use(async (ctx, next) => {
if (ctx.request.url.startsWith("/api/")) {
addAPIHeaders(ctx);
}
return await next();
});
app.use(session(sessionConfig, app));
app.use(json());
app.use(logger());
app.use(bodyParser());
app.use(
views(__dirname + (__dirname.endsWith("build") ? "/../views" : "/views"), {
map: {
hbs: "handlebars"
},
extension: "hbs"
})
);
async function handleAuthenticate(ctx, next) {
try {
await next();
} catch (err) {
if (err.status === 401) {
ctx.status = 401;
ctx.set("WWW-Authenticate", "Basic");
ctx.body = "Unauthorized";
} else {
console.log(err);
// throw err;
}
}
}
app.use(async (ctx, next) => {
try {
if (
ctx.request.url.toString() == "/update" &&
ctx.request.header["user-agent"].toLowerCase().includes("github")
) {
let requestHash = Buffer.from(
ctx.request.header["x-hub-signature-256"].toString(),
"utf8"
);
let verifyHash = Buffer.from(
`sha256=${crypto
.createHmac("sha256", config.auth.ci.deploy)
.update(ctx.request.rawBody)
.digest("hex")}`,
"utf8"
);
if (crypto.timingSafeEqual(requestHash, verifyHash)) {
if (
(ctx.request.body as any).ref ==
`refs/heads/${config.branch}`
) {
ctx.body = "";
process.exit(0);
}
}
ctx.body = "";
} else {
await handleAuthenticate(ctx, next);
}
} catch (err) {
await handleAuthenticate(ctx, next);
}
});
if (config.auth.access.restricted) {
app.use(
auth({
name: config.auth.access.username,
pass: config.auth.access.password
})
);
}
registerHelpers();
registerComponentsWithinDirectory("./views/partials");
registerComponentsWithinDirectory("./views/scouting/partials");
const router = new Router<Koa.DefaultState, Koa.Context>();
// router.use("", loginRouter.routes());
if (config.features.includes("resources")) {
router.use("/app", resourcesRouter.routes());
router.use("/api/v1/resources", resourcesAPIRouter.routes());
} else if (config.features.includes("scouting")) {
// router.use("/", scoutingDefaultRouter.routes());
} else {
// router.use("/", defaultRouter.routes());
}
if (config.features.includes("scouting")) {
router.use("/scouting", scoutingRouter.routes());
router.use("/api/v1/scouting", scoutingAPIRouter.routes());
}
if (config.features.includes("tps")) {
router.use("/api/v1/tps", tpsAPIRouter.routes());
}
function formatNumber(num) {
if (num < 10) {
return num;
} else if (num >= 10 && num < 1000) {
return `${Math.floor(num / 10) * 10}+`;
} else if (num >= 1000 && num < 100_000) {
return `${Math.floor(num / 1000)}k+`;
} else if (num >= 100_000 && num < 1_000_000) {
return `${Math.floor(num / 1000)}k`;
} else if (num >= 1_000_000 && num < 100_000_000) {
return `${Math.floor(num / 1_000_000)}M+`;
} else if (num >= 100_000_000 && num < 1_000_000_000) {
return `${Math.floor(num / 1_000_000)}M`;
} else {
return `${Math.floor(num / 1_000_000_000)}B`;
}
}
function formatTime(num) {
let indicator = "s";
if (num >= 100) {
num = Math.floor(num / 60);
indicator = "min";
} else {
return `${num}${indicator}`;
}
if (num >= 10) {
num = Math.ceil(num / 60);
indicator = "hr";
} else {
return `${num}${indicator}`;
}
if (num >= 100) {
num = Math.floor(num / 24);
indicator = "d";
} else {
return `${num}${indicator}`;
}
if (num > 30) {
num = Math.floor(num / 30);
indicator = "mo";
} else {
return `${num}${indicator}`;
}
if (num > 12) {
num = Math.floor(num / 12);
indicator = "yr";
}
return `${num}${indicator}`;
}
router.get("/", async (ctx, next) => {
let stats: any = await getStats();
await ctx.render("index", {
stats: {
entries: formatNumber(stats.entries),
time: formatNumber(Math.ceil((stats.entries * 153) / 3600)),
dataPoints: formatNumber(stats.dataPoints),
scouters: formatNumber(stats.scouters),
teams: stats.teams,
states: stats.states,
countries: stats.countries
}
});
});
router.get("/discord", async (ctx) => {
ctx.redirect("https://discord.gg/gT9ZZDqTyx");
});
app.use(router.routes());
app.use(router.allowedMethods());
app.use(serve("./static", {}));
const httpServer = createServer(app.callback());
(async () => {
await initializeCategories(config.year);
httpServer.listen(config.server.port, () => {
console.log(
"Listening at http://" +
config.server.domain +
":" +
config.server.port
);
});
})();