-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
210 lines (178 loc) · 6.23 KB
/
server.js
File metadata and controls
210 lines (178 loc) · 6.23 KB
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
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
require("dotenv").config();
const { buildImage } = require("./imageCreation.js");
const {
uploadImageToS3,
createPostContainer,
confirmPost,
createPrivateApiPost,
} = require("./imagePosting.js");
const {
getUserHash,
saveUserRequest,
checkSpam,
authenticateAdmin,
addToBlacklist,
removeFromBlacklist,
checkBlacklist,
getBlacklist,
checkBadIp,
} = require("./securityMiddleware.js");
const https = require("https");
const fs = require("fs");
const PORT = 9999;
app.use(bodyParser.json());
app.use(cors());
//// START SERVER
if (process.env.ENVIRONMENT === "PRODUCTION") {
// USE HTTPS
const sslOptions = {
key: fs.readFileSync("/etc/letsencrypt/live/api.anonibot.com/privkey.pem"),
cert: fs.readFileSync("/etc/letsencrypt/live/api.anonibot.com/cert.pem"),
ca: fs.readFileSync("/etc/letsencrypt/live/api.anonibot.com/chain.pem"),
};
const server = https.createServer(sslOptions, app);
server.listen(PORT, () => {
console.log("PRODUCTION: Server initialized on PORT " + PORT);
console.log("POSTING TIME LIMIT SET TO " + process.env.POST_TIME_LIMIT + " HOURS")
});
} else if (process.env.ENVIRONMENT === "DEVELOPMENT") {
// USE HTTP
app.listen(PORT, () => {
console.log("DEVELOPMENT: Server initialized on PORT " + PORT);
});
}
// GET IMAGE PREVIEW REQUEST
app.post("/getPreview", (req, res) => {
try {
const { text, theme, font, size } = req.body;
console.log(`[GET /getPreview] Received preview request...`);
if (!text || !theme || !font || !size) {
return res.status(400).send("Required parameters not present");
}
buildImage(text, theme, font, size)
.then((imageBuffer) => {
res.send(imageBuffer.toString("base64"));
console.log("[GET /getPreview] Preview sent successfully");
})
.catch((err) => {
console.error(err);
res.status(500).send("An error occurred while creating the image.");
});
} catch (err) {
console.error(err);
res.status(500).send("An error occurred while handling the request.");
}
});
// CREATE POST REQUEST
app.post(
"/createPost",
checkBlacklist,
process.env.ENVIRONMENT === "DEVELOPMENT" ? async (req, res, next) => next() : checkSpam,
checkBadIp,
async (req, res) => {
console.log(`[POST /createPost] Processing post creation request...`);
// Validate request
const { text, theme, font, size } = req.body;
const userHash = getUserHash(req.ip);
console.log(`[POST /createPost] Text ${text}, User ${userHash}`);
if (!text || !theme || !font || !size) {
console.log("[POST /createPost] Rejected: Parameters not valid");
return res.status(400).send("Required parameters not received.");
}
const imageBuffer = await buildImage(text, theme, font, size);
try {
// Perform Instagram post
try {
const imageURL = await uploadImageToS3(imageBuffer);
const containerId = await createPostContainer(imageURL);
await confirmPost(containerId);
console.log("[POST /createPost] SUCCESS: Image posted with public API");
await saveUserRequest(userHash, new Date().toISOString());
// Save user request here once the public API succeeds
res.status(200).send("Image posted successfully");
return;
} catch (publicApiErr) {
console.log("Error while posting image with PUBLIC API");
// If the error occurs with public API, try with private API
try {
await createPrivateApiPost(imageBuffer);
console.log(
"[POST /createPost] SUCCESS: Image posted with private API"
);
// Save user request here once the private API succeeds
await saveUserRequest(userHash, new Date().toISOString());
res.status(200).send("Image posted successfully");
return;
} catch (privateApiErr) {
console.log("Error while posting image with PRIVATE API");
throw privateApiErr; // Re-throw the error to be caught in the outer catch block
}
}
} catch (err) {
// Handle errors and respond with error message
console.error("[POST /createPost] Error processing request", err);
res
.status(500)
.send(
"An error occurred while creating or posting the image: " +
err.message
);
}
}
);
// GET USER REQUESTS TABLE
app.get("/userRequests", authenticateAdmin, async (req, res) => {
try {
res.json(await getAnonibotRequests());
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET BLACKLIST TABLE
app.get("/blacklist", authenticateAdmin, async (req, res) => {
console.log("[GET /blacklist] AnonibotBlacklist table requested");
try {
const blacklistTable = await getBlacklist();
res.json(blacklistTable);
console.log("[GET /blacklist] Blacklist sent");
} catch (err) {
console.error("[GET] Error fetching AnonibotBlacklist table:", err);
res.status(500).json({ error: "Internal Server Error" });
}
});
// ADD USER TO BLACKLIST
app.post("/blacklist", authenticateAdmin, async (req, res) => {
try {
console.log("[POST /blacklist] Blacklisting user...");
const userHash = req.query.userHash;
await addToBlacklist(userHash);
res.json({ message: "User blacklisted successfully" });
} catch (err) {
console.error("[POST /blacklist] Error blacklisting user:", err);
res.status(500).json({ error: "Internal Server Error" });
}
});
// REMOVE USER FROM BLACKLIST
app.delete("/blacklist", authenticateAdmin, async (req, res) => {
try {
console.log("[DELETE /blacklist] Removing user from the blacklist...");
const userHash = req.query.userHash;
await removeFromBlacklist(userHash);
res.json({ message: "User removed from the blacklist successfully" });
} catch (err) {
console.error(
"[DELETE /blacklist] Error removing user from the blacklist:",
err
);
res.status(500).json({ error: "Internal Server Error" });
}
});
app.post("/saveRequest", (req,res) => {
const userHash = getUserHash(req.ip);
saveUserRequest(userHash, new Date().toISOString());
console.log("KEYWORDS: FORCE SAVE REQUEST")
} )