1 |
rakinar2 |
632 |
import express from "express"; |
2 |
|
|
import path from "path"; |
3 |
|
|
import { MessageType } from "../types/MessageType"; |
4 |
|
|
|
5 |
|
|
class ArchiveServer { |
6 |
|
|
private readonly app: express.Application; |
7 |
|
|
private readonly port: number; |
8 |
|
|
private readonly db: import("bun:sqlite").Database | import("better-sqlite3").Database; |
9 |
|
|
|
10 |
|
|
public constructor( |
11 |
|
|
db: import("bun:sqlite").Database | import("better-sqlite3").Database, |
12 |
|
|
port: number = +(process.env.ARCHIVE_SERVER_PORT ?? 7575) || 7575 |
13 |
|
|
) { |
14 |
|
|
this.db = db; |
15 |
|
|
this.app = express(); |
16 |
|
|
this.port = port; |
17 |
|
|
} |
18 |
|
|
|
19 |
|
|
private setup() { |
20 |
|
|
this.app.set("view engine", "ejs"); |
21 |
|
|
this.app.set("views", path.join(__dirname, "../html")); |
22 |
|
|
this.app.use(express.static(path.join(__dirname, "../../public"))); |
23 |
|
|
this.app.get( |
24 |
|
|
"/guilds/:guildId/channels/:channelId/messages", |
25 |
|
|
this.handleGetMessages.bind(this) |
26 |
|
|
); |
27 |
|
|
} |
28 |
|
|
|
29 |
|
|
private prepare(query: string, params: string[] = [], results = true) { |
30 |
|
|
const db = this.db as unknown as import("bun:sqlite").Database; |
31 |
|
|
const compiled = db.prepare(query, params); |
32 |
|
|
|
33 |
|
|
if (results) { |
34 |
|
|
return compiled.all(); |
35 |
|
|
} |
36 |
|
|
|
37 |
|
|
compiled.run(); |
38 |
|
|
} |
39 |
|
|
|
40 |
|
|
private handleGetMessages( |
41 |
|
|
request: express.Request<{ |
42 |
|
|
guildId: string; |
43 |
|
|
channelId: string; |
44 |
|
|
}>, |
45 |
|
|
response: express.Response |
46 |
|
|
) { |
47 |
|
|
const messages = this.prepare( |
48 |
|
|
"SELECT * FROM messages JOIN users ON users.id = messages.userId WHERE guildId = ? AND channelId = ? ORDER BY timestamp DESC;", |
49 |
|
|
[request.params.guildId, request.params.channelId] |
50 |
|
|
); |
51 |
|
|
|
52 |
|
|
response.render("messages", { |
53 |
|
|
guildId: request.params.guildId, |
54 |
|
|
channelId: request.params.channelId, |
55 |
|
|
messages |
56 |
|
|
}); |
57 |
|
|
} |
58 |
|
|
|
59 |
|
|
public start() { |
60 |
|
|
this.setup(); |
61 |
|
|
this.app.listen(this.port, () => { |
62 |
|
|
process.send?.({ |
63 |
|
|
type: MessageType.ServerReady, |
64 |
|
|
port: this.port |
65 |
|
|
}); |
66 |
|
|
}); |
67 |
|
|
} |
68 |
|
|
} |
69 |
|
|
|
70 |
|
|
export default ArchiveServer; |