-
Notifications
You must be signed in to change notification settings - Fork 107
/
Copy pathroutes.ts
239 lines (195 loc) · 6.58 KB
/
routes.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
227
228
229
230
231
232
233
234
235
236
237
238
239
import bodyParser = require("body-parser");
import * as express from "express";
import * as moment from "moment";
import mustacheExpress = require("mustache-express");
import { URL } from "url";
import { ClientEnvironment } from "../common/ClientEnvironment";
import { probablyUniqueString, ParseJSONOrDefault } from "../common/Toolbox";
import { configureBasicRulesContent } from "./configureBasicRulesContent";
import { getAccount, upsertUser } from "./dbconnection";
import { configureMetricsRoutes } from "./metrics";
import {
configureLoginRedirect,
configureLogout,
configurePatreonWebhookReceiver,
startNewsUpdates,
updateSessionAccountFeatures
} from "./patreon";
import { PlayerViewManager } from "./playerviewmanager";
import configureStorageRoutes from "./storageroutes";
import { AccountStatus } from "./user";
import { configureOpen5eContent } from "./configureOpen5eContent";
import { configureAffiliateRoutes } from "./configureAffiliateRoutes";
const baseUrl = process.env.BASE_URL || "";
const patreonClientId = process.env.PATREON_CLIENT_ID || "PATREON_CLIENT_ID";
const defaultAccountLevel = process.env.DEFAULT_ACCOUNT_LEVEL || "free";
const googleAnalyticsId = process.env.GOOGLE_ANALYTICS_ID || "";
export type Req = Express.Request & express.Request;
export type Res = Express.Response & express.Response;
const appVersion = require("../package.json").version;
const getClientOptions = (session: Express.Session) => {
const encounterId = session.encounterId || probablyUniqueString();
const patreonLoginUrl =
"http://www.patreon.com/oauth2/authorize" +
`?response_type=code&client_id=${patreonClientId}` +
`&redirect_uri=${baseUrl}/r/patreon` +
`&scope=` +
encodeURIComponent(`identity identity.memberships identity[email]`) +
`&state=${encounterId}`;
const environment: ClientEnvironment = {
EncounterId: encounterId,
BaseUrl: baseUrl,
PatreonLoginUrl: patreonLoginUrl,
IsLoggedIn: session.isLoggedIn || false,
HasStorage: session.hasStorage || false,
HasEpicInitiative: session.hasEpicInitiative || false,
SendMetrics: process.env.METRICS_DB_CONNECTION_STRING != undefined,
PostedEncounter: null,
SentryDSN: process.env.SENTRY_DSN || null
};
if (session.postedEncounter) {
environment.PostedEncounter = session.postedEncounter;
delete session.postedEncounter;
}
return {
environmentJSON: JSON.stringify(environment),
baseUrl,
appVersion,
googleAnalyticsId,
accountLevel: getAccountLevel(session)
};
};
function getAccountLevel(session) {
if (!session.isLoggedIn) {
return "LoggedOut";
}
if (!session.hasStorage) {
return "LoggedInFree";
}
if (!session.hasEpicInitiative) {
return "AccountSync";
}
return "EpicInitiative";
}
export default function (
app: express.Application,
playerViews: PlayerViewManager
): void {
const mustacheEngine = mustacheExpress();
let cacheMaxAge = moment.duration(7, "days").asMilliseconds();
if (process.env.NODE_ENV === "development") {
mustacheEngine.cache._max = 0;
cacheMaxAge = 0;
}
app.engine("html", mustacheEngine);
app.set("view engine", "html");
app.set("views", __dirname + "/../html");
app.use(express.static(__dirname + "/../public", { maxAge: cacheMaxAge }));
app.use(
bodyParser.json({
verify: function (req, res, buf, encoding) {
req["rawBody"] = buf.toString();
}
})
);
app.use(bodyParser.urlencoded({ extended: false }));
configureMetricsRoutes(app);
app.get("/", async (req: Req, res: Res) => {
const session = req.session;
if (session === undefined) {
throw "Session is not available";
}
session.encounterId = await playerViews.InitializeNew();
const renderOptions = getClientOptions(session);
return res.render("landing", renderOptions);
});
configureAffiliateRoutes(app);
app.get("/e/:id", (req: Req, res: Res) => {
const session = req.session;
if (session === undefined) {
throw "Session is not available";
}
session.encounterId = req.params.id;
const urlObject = new URL(req.url, baseUrl);
const queryString = urlObject.search;
res.redirect("/e/" + queryString);
});
app.get("/e/", async (req: Req, res: Res) => {
const session = req.session;
if (session === undefined) {
throw "Session is not available";
}
if (defaultAccountLevel !== "free") {
await setupLocalDefaultUser(session);
}
updateSession(session);
const options = getClientOptions(session);
return res.render("tracker", options);
});
app.get("/p/:id", (req: Req, res: Res) => {
const session = req.session;
if (session == null) {
throw "Session is not available";
}
session.encounterId = req.params.id;
res.render("playerview", getClientOptions(session));
});
app.get("/playerviews/:id", async (req: Req, res: Res) => {
const playerView = await playerViews.Get(req.params.id);
res.json(playerView);
});
configureBasicRulesContent(app);
configureOpen5eContent(app);
const importEncounter = async (req, res: Res) => {
const newViewId = await playerViews.InitializeNew();
const session = req.session;
if (typeof req.body.Combatants === "string") {
session.postedEncounter = {
Combatants: ParseJSONOrDefault(req.body.Combatants, [])
};
} else {
session.postedEncounter = req.body;
}
res.redirect("/e/" + newViewId);
};
app.post("/launchencounter/", importEncounter);
app.post("/importencounter/", importEncounter);
app.get("/transferlocalstorage/", (req: Req, res: Res) => {
res.render("transferlocalstorage", { baseUrl });
});
configureLoginRedirect(app);
configureLogout(app);
configurePatreonWebhookReceiver(app);
configureStorageRoutes(app);
startNewsUpdates(app);
}
async function setupLocalDefaultUser(session: Express.Session) {
let accountStatus = AccountStatus.None;
if (defaultAccountLevel === "accountsync") {
session.hasStorage = true;
accountStatus = AccountStatus.Pledge;
}
if (defaultAccountLevel === "epicinitiative") {
session.hasStorage = true;
session.hasEpicInitiative = true;
accountStatus = AccountStatus.Epic;
}
session.isLoggedIn = true;
const user = await upsertUser(
process.env.DEFAULT_PATREON_ID || "defaultPatreonId",
accountStatus,
""
);
if (user) {
session.userId = user._id;
}
return;
}
async function updateSession(session: Express.Session) {
if (session.userId) {
const account = await getAccount(session.userId);
if (account) {
updateSessionAccountFeatures(session, account.accountStatus);
}
}
}