-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
417 lines (366 loc) · 15.5 KB
/
index.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
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
const rateLimit = require("express-rate-limit")
const express = require('ultimate-express')
const app = express()
const cors = require('cors');
const {join} = require("node:path");
const mongoose = require("mongoose");
const cookieParser = require('cookie-parser');
const multiparty = require('multiparty');
const fs = require('fs');
const {Schema} = require("mongoose");
const icoToPng = require("ico-to-png");
const nodeSteam = require("steam-user");
const steamClient = new nodeSteam();
const sharp = require("sharp");
const expressLayouts = require('express-ejs-layouts');
const compression = require('compression');
const { constants: zConocoNoconocoConZstantan } = require("node:zlib");
const port = 4146
app.use(compression({
level: zConocoNoconocoConZstantan.Z_BEST_COMPRESSION,
filter: (req, res) => {
if (!req.url.startsWith("/api/games")) return false;
return compression.filter(req, res);
}
}));
app.use(express.json());
app.use(express.static('public/resources'));
app.set('trust proxy', 1);
app.set('views', join(__dirname, "public"));
app.set('view engine', 'ejs');
app.use(expressLayouts);
require('dotenv').config();
app.use(cookieParser());
app.use((req, res, next) => {
if (req.cookies.admin === process.env.ADMIN_PASSWORD) req.admin = true;
res.set("tdm-policy", "https://www.nineplus.sh/legal/tdm.json")
res.set("tdm-reservation", "1")
res.set("x-robots-tag", "noai")
next()
})
app.get('/.well-known/tdmrep.json', (req, res) => {res.redirect("https://www.nineplus.sh/.well-known/tdmrep.json")})
app.get('/robots.txt', (req, res) => {res.redirect("https://www.nineplus.sh/robots.txt")})
const GameSchema = new Schema({
name: String,
icon: Buffer,
iconnn: Boolean,
executables: Array,
steamID: Number
});
GameSchema.index({name: 'text'});
const Game = mongoose.model('Game', GameSchema);
const SuggestionSchema = new Schema({
executable: String,
arguments: String,
platform: String
});
const Suggestion = mongoose.model('Suggestion', SuggestionSchema);
function visualError(code, res, err) {
if(code === 404) {
res.status(404).render("error", {"image": "/idunno.png", "title": "I ate it", "description": ""});
} else if (code === 403) {
res.status(403).render("error", {"image": "/authenticate.png", "title": "Password required", "description": `
<form onsubmit="event.preventDefault();document.cookie=\`admin=\${mysupersecretpassword.value}\`;document.location.reload()">
<input type="password" id="mysupersecretpassword">
</form>
`});
} else if (code === 500) {
res.status(500).render("error", {"image": "/crashplus.png", "title": "Server puked", "description": err?.stack || "Reason unknown!"});
}
}
app.use(async (req, res, next) => {
res.locals.showers = await Game.find().select("-icon").sort({_id: -1}).limit(9).exec();
const quotes = [
`“average person plays more than 5 different games every year” factoid actualy just statistical error. average person plays less. gamePLUS Georg, who lives in cave & plays all his ${await Game.countDocuments({})} games, is an outlier adn should not have been counted`
]
res.locals.quote = quotes[Math.floor(Math.random() * quotes.length)];
next();
})
app.get("/error", (req,res) => {
throw new Error("Wah!")
})
app.get('/', async (req, res) => {
const graphData = await Game.aggregate([
{
$project: {
day: { $dateToString: { format: "%Y-%m-%d", date: { $toDate: "$_id" } } }
}
},
{
$group: {
_id: '$day',
count: { $sum: 1 }
}
},
{
$setWindowFields: {
sortBy: { _id: 1 },
output: {
total: {
$sum: '$count',
window: {
documents: ["unbounded", "current"]
}
}
}
}
},
{
$project: {
x: '$_id',
y: '$total',
_id: 0
}
},
{ $sort: { x: 1 } }
]);
let xLabels = []
let yLabels = []
xLabels.push("2024-05-13");
yLabels.push(0);
graphData.forEach(function(data) {
xLabels.push(data.x);
yLabels.push(data.y);
})
res.render('index', {isAdmin: req.admin, xLabels: JSON.stringify(xLabels), yLabels: JSON.stringify(yLabels)});
});
app.get('/create', (req, res) => {
if(!req.admin) return visualError(403, res);
res.render('gamecreate');
});
async function processGame(game, fields, files) {
let iconData;
let iconType;
if(!fields) throw new Error("The data you entered was not received by the server. No clue why this happens, but pressing refresh to re-send the data seems to get it to churn properly.");
if(fields.suggestion_id[0]) {
await Suggestion.findByIdAndDelete(fields.suggestion_id[0])
}
if(files.icon[0].size > 0) {
iconData = fs.readFileSync(files.icon[0].path);
iconType = files.icon[0].headers["content-type"];
} else if(fields.iconurl[0]) {
const iconRequest = await fetch(fields.iconurl[0]);
iconData = await Buffer.from(await iconRequest.arrayBuffer())
iconType = iconRequest.headers.get("content-type");
}
if(iconType === "image/x-icon" || iconType === "image/vnd.microsoft.icon") {
iconData = await icoToPng(iconData, 512)
}
if(iconData) game.icon = iconData;
game.name = fields.gamename[0];
game.iconnn = !!(fields.iconnn && fields.iconnn[0] === "on");
game.steamID = parseInt(fields.steamID[0]) || null;
game.executables = []
Object.keys(fields).forEach(entry => {
if(entry.startsWith("executable_platform_")) {
let executableIndex = entry.split("executable_platform_")[1];
game.executables.push({
name: fields[`executable_name_${executableIndex}`][0],
arguments: fields[`executable_arguments_${executableIndex}`][0],
platform: fields[`executable_platform_${executableIndex}`][0],
})
}
})
await game.save();
return game;
}
app.post('/create', (req, res, next) => {
if(!req.admin) return res.sendStatus(999);
let game = new Game();
new multiparty.Form().parse(req, async function(err, fields, files) {
try { game = await processGame(game, fields, files); } catch(e){return next(e)}
res.redirect(`/game/${game._id}?created=true`);
await fetch(process.env.DISCORD_WEBHOOK, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({content: `https://gameplus.nineplus.sh/game/${game._id}`}),
});
});
});
app.get('/search', async (req, res) => {
const find = await Game.find({$text: {$search: req.query.game}}).select("-icon").exec();
res.render('search', {find});
});
app.get('/game/:id', async (req, res) => {
if(!mongoose.isValidObjectId(req.params.id)) return visualError(404, res);
const game = await Game.findById(req.params.id).select("-icon").exec();
if(!game) return visualError(404, res);
res.render('game', {game, isAdmin: req.admin, isNotable: req.query.created});
});
app.get('/game/:id/edit', async (req, res) => {
if (!req.admin) return visualError(403, res);
const game = await Game.findById(req.params.id).select("-icon").exec();
if (!game) return res.status(404).send('Game not found');
res.render('gameedit', { game });
});
app.post('/game/:id/edit', async (req, res, next) => {
if(!req.admin) return res.sendStatus(999);
let game = await Game.findById(req.params.id);
if (!game) return res.status(404).send('Game not found');
new multiparty.Form().parse(req, async function(err, fields, files) {
try { game = await processGame(game, fields, files); } catch(e){return next(e)}
res.redirect(`/game/${game._id}`);
})
});
app.get('/game/:id/icon', async (req, res, next) => {
const game = await Game.findById(req.params.id).exec();
if(!game) return res.status(404);
res.contentType('image/png');
res.set("Content-Disposition", "inline;");
try {
res.status(200).send(
req.query.size ?
await sharp(game.icon).resize(parseInt(req.query.size), null, {
withoutEnlargement: true,
kernel: req.query.pixel || game.iconnn ? "nearest" : "lanczos3"
}).toBuffer()
: game.icon
);
} catch(err) {
console.error(err);
res.status(500).sendFile(__dirname + "/public/resources/fallback.png");
}
});
app.get('/games', async (req, res) => {
res.render("allgames", {games: await Game.find({}).sort({"name": 1}).select("-icon").exec()})
});
app.get('/api/game/:id', cors(), async (req, res) => {
if(!mongoose.isValidObjectId(req.params.id)) return res.status(400).send({message: "Your ID is not a valid MongoDB ObjectID. I don't think it's real."})
const game = await Game.findById(req.params.id).select("-icon").exec();
if(!game) return res.status(404).send({message: "Game nonexistent or eaten. Burp."});
return res.status(200).send(game);
})
app.get('/api/games', cors(), async (req, res) => {
const games = await Game.find(req.query.platform ? {
executables: {
$elemMatch: {
platform: req.query.platform
}
}
} : {}).select("-icon").exec();
const strippedGames = games.map(game => {
const filteredExecutables = game.executables.filter(executable => {
const thePlatform = executable.platform;
if(executable.arguments === "") delete executable.arguments;
if(req.query.platform) delete executable.platform;
return !req.query.platform || thePlatform === req.query.platform;
});
let gameObject = {
_id: game._id,
name: game.name,
executables: filteredExecutables
}
if(game.steamID) gameObject.steamID = game.steamID;
return gameObject;
})
res.json(strippedGames);
})
app.get('/learn', async (req, res) => {
const sampleGame = (await Game.aggregate([{$match: {"executables.platform": "win32", "steamID": { $ne: null }}}, {$sample: { size: 1 }}]))[0]
res.render('learn', {sampleGame});
});
app.get("/api/exists", cors(), async (req, res) => {
if(req.query.steamID) {
const game = await Game.exists({steamID: req.query.steamID});
if(game) return res.send({exists:true,id:game._id});
}
if(req.query.name) {
const game = await Game.findOne({name: req.query.name.replace("®","").replace("™","")});
if(!game) return res.send({exists:false});
return res.send({exists:true,id:game._id,hasAppID:!!game.steamID})
}
return res.send({exists:false})
})
app.get('/steam', async (req, res) => {
if(!req.admin || !process.env.SGDB_KEY) return res.sendStatus(999);
if(!req.query.id && !req.query.name) return res.status(400).send({"message": "You need to provide either an AppID or a name."});
let searchResult;
const { default: SGDB } = await import('steamgriddb');
const client = new SGDB(process.env.SGDB_KEY);
if(!req.query.id) {
const searchResults = await client.searchGame(req.query.name);
if(searchResults.length === 0) return res.status(404).send({"message": "SteamGridDB did not recognize this game."});
const filterizedSearchResults = searchResults.filter(result => result.types.includes("steam"));
searchResult =
searchResults[0].types.includes("steam") ?
searchResults[0]
:
filterizedSearchResults.length > 0 && searchResults[0].name === filterizedSearchResults[0].name
&& filterizedSearchResults[0].types.includes("steam") ?
filterizedSearchResults[0]
: null
} else {
try {
searchResult = await client.getGameBySteamAppId(req.query.id);
} catch(e) {
console.error(e);
return res.status(404).send({"message": "SteamGridDB did not recognize this game."});
}
}
if(!searchResult) return res.status(404).send({"message": "SteamGridDB recognized this game, but the Steam data is missing, so gamePLUS cannot autofill."});
const steamAppId = req.query.id || (await client.getGame({type: "id", id: searchResult.id}, {"platformdata": ["steam"]})).external_platform_data?.steam?.[0].id;
if(!steamAppId) return res.status(404).send({"message": "SteamGridDB recognized this game as a Steam game, but the data wasn't actually sent. This shouldn't happen."})
const appInfo = (await steamClient.getProductInfo([parseInt(steamAppId)], [])).apps[steamAppId].appinfo;
if(!appInfo.config) return res.status(404).send({"message": "Well done, you've gotten an exceptionally bizarre error! Steam gave no config for this game. None. Seriously. I'm not sure why this happens, try adding it by hand."})
const osOrder = ["windows", "macos", "linux"]
const sgdbIcons = (await client.getIconsById(searchResult.id)).map((entry) => entry.url)
return res.json({
name: appInfo.common.name,
executables: Object.values(appInfo.config.launch).sort((a,b) => osOrder.indexOf(a.config?.oslist) - osOrder.indexOf(b.config?.oslist)),
depots: Object.fromEntries(
Object.entries(appInfo.depots).filter(([key, value]) =>
key !== "branches" && key !== "baselanguages" && key !== "workshopdepot" && !value.depotfromapp && !value.dlcappid
)
),
icons: [
`https://cdn.cloudflare.steamstatic.com/steamcommunity/public/images/apps/${steamAppId}/${appInfo.common.clienticon}.ico`,
...sgdbIcons
],
sgdbUrl: `https://steamgriddb.com/game/${searchResult.id}/icons`,
steamAppId: steamAppId
})
})
const suggestLimit = rateLimit({
windowMs: 60 * 1000,
limit: 5,
standardHeaders: true,
legacyHeaders: false,
})
app.options('/api/suggest', cors({allowedHeaders:["Content-Type"]}))
app.post('/api/suggest', cors({allowedHeaders:["Content-Type"]}), suggestLimit, async (req, res) => {
let suggestion = new Suggestion();
suggestion.executable = req.body.executable;
suggestion.arguments = req.body.arguments;
suggestion.platform = req.body.platform;
await suggestion.save();
res.sendStatus(200);
});
app.get('/suggestions', async (req, res) => {
if (!req.admin) return visualError(403, res);
res.render("suggestions", {suggestions: await Suggestion.find({}).exec()})
})
app.delete('/suggestions/:id', async (req, res) => {
if (!req.admin) return res.sendStatus(999);
await Suggestion.findByIdAndDelete(req.params.id);
res.sendStatus(200);
})
app.all('*', (req, res) => {
if(req.path.startsWith("/api/")) return res.status(404).send({message: "This endpoint does not exist, or does not accept that method."});
return visualError(404, res);
})
app.use((err, req, res, next) => {
console.error(err.stack);
return visualError(500, res, err);
})
async function startApp() {
await mongoose.connect(process.env.MONGODB_URL);
console.log("Connected to database")
await steamClient.logOn({anonymous: true});
console.log("Anonymously signed into Steam")
app.listen(port, () => {
console.log(`gamePLUS listening on port ${port}`)
})
}
startApp();