-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
324 lines (220 loc) · 7.71 KB
/
app.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
// jhint esversion:6
const {
exec
} = require('child_process');
const express = require("express");
const bodyparser = require("body-parser");
const path = require('path');
const ejs = require("ejs");
const fs = require('fs');
const multer = require('multer'); // For handling file uploads
const {
spawn
} = require('child_process');
const app = express();
app.set('view engine', 'ejs');
app.use(express.static("public"));
app.use(bodyparser.urlencoded({
extended: true
}));
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'uploads/');
},
filename: function(req, file, cb) {
cb(null, file.originalname);
}
});
const upload = multer({
storage
});
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.set("view cache", false);
app.get("/", function(req, res) {
res.render("home");
});
app.post("/", function(req, res) {
const token = req.body.token;
const id = req.body.appid;
const apps = req.body.apps;
exec(`python Python/longtoken.py "${token}" "${id}" "${apps}"`, (error, stdout, stderr) => {
if (error) {
console.error(`Error executing Python script: ${error.message}`);
// Handle the error
} else {
const output = stdout ? stdout.toString() : '';
res.render("home", {
ha: output
});
// Redirect or send a response back
// Assuming you have the variables extracted from the output
};
});
});
const runPythonScript = (id, token) => {
return new Promise((resolve, reject) => {
exec(`python Python/generatecsv.py "${id}" "${token}"`, (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error.message}`);
reject(error);
return;
}
// The Python script has completed successfully
resolve();
});
});
};
app.get("/Facebook", function(req, res) {
res.render("facebook");
});
app.get('/engagement', function(req, res) {
// Get the engagement rate from the query parameter
const engagementRate = parseFloat(req.query.engagement);
// Render the "engagement" template and pass the "engagement" variable
res.render('engagement', {
engagement: engagementRate.toFixed(2)
});
});
// app.js
app.get("/analysis", function(req, res) {
// Get the query parameter "analysis" from the URL
const analysisResultsJson = req.query.analysis;
// Parse the JSON string back into a JavaScript object
const analysisResults = JSON.parse(analysisResultsJson);
// Render the analysisResults page and pass the analysisResults as a variable
res.render("analysis", { analysisResults });
});
app.get("/ads",function(req,res){
const plotFilePathsJSON = req.query.plotFilePaths;
try {
// Parse the plotFilePaths JSON string back to an array
const plotFilePaths = JSON.parse(decodeURIComponent(plotFilePathsJSON));
// Now you have the array of plot file paths, and you can use it to render your EJS template
res.render('ads', { plotFilePaths });
} catch (error) {
console.error('Error parsing plot file paths:', error);
res.status(500).send('Internal Server Error');
}
})
// Endpoint to run the Facebook Python script and serve the generated CSV file
app.post("/Facebook", upload.single('csvFile'), async (req, res) => {
const token = req.body.longtoken;
const id = req.body.appID;
const submitButton = req.body.submit;
if (submitButton === 'script1') {
try {
// Run the Python script and wait for it to complete
await runPythonScript(id, token);
// Wait for 20 seconds before sending the CSV file
setTimeout(() => {
const csvFilePath = path.join(__dirname, 'data.csv');
res.setHeader('Content-Disposition', 'attachment; filename="data.csv"');
res.setHeader('Content-Type', 'text/csv');
res.sendFile(csvFilePath, (err) => {
if (err) {
console.error(`Error sending CSV file: ${err}`);
res.status(500).send('Error sending CSV file');
}
});
}, 20000);
// Adjust the delay as needed
} catch (error) {
console.error(`Error running Python script: ${error.message}`);
res.status(500).send('An error occurred during script execution.');
}
}
else if (submitButton === 'script2') {
const filePath = req.file.path;
const pythonProcess = spawn('python', ['Python/engagement.py', filePath]);
let resultData = '';
pythonProcess.stdout.on('data', (data) => {
resultData += data.toString();
});
pythonProcess.stderr.on('data', (data) => {
console.error(`Python Error: ${data}`);
res.status(500).send('Internal Server Error');
});
pythonProcess.on('close', (code) => {
if (code === 0) {
const engagementRate = parseFloat(resultData);
const engagement = engagementRate.toFixed(2);
res.redirect(`/engagement?engagement=${engagement}`);}
});
}
else if (submitButton === 'script') {
const csvFilePath = req.file.path;
// Execute the Python script
const pythonProcess = spawn('python', ['Python/firstAnalysis.py', csvFilePath]);
let analysisResults = '';
pythonProcess.stdout.on('data', (data) => {
analysisResults += data.toString();
});
pythonProcess.stderr.on('data', (data) => {
console.error(`Python Error: ${data}`);
res.status(500).send('Internal Server Error');
});
pythonProcess.on('close', (code) => {
if (code === 0) {
// Parse the analysis results from the Python script output (if needed)
// For example, if the Python script outputs JSON data, you can parse it here
try {
analysisResults = JSON.parse(analysisResults);
const queryParams = encodeURIComponent(JSON.stringify(analysisResults));
res.redirect(`/analysis?analysis=${queryParams}`);
} catch (error) {
console.error('Error parsing analysis results:', error);
res.status(500).send('Internal Server Error');
return;
}
// Render the analysisResults page and pass the analysisResults as a variable
} else {
console.error(`Python process exited with code ${code}`);
res.status(500).send('Internal Server Error');
}
});
}
else if (submitButton=== 'script4') {
const csvFilePath = req.file.path;
// Execute the Python script
const pythonProcess = spawn('python', ['Python/adsAnalysis.py', csvFilePath]);
let plotFilePaths = [];
let responseSent = false; // Flag to track if the response has been sent
pythonProcess.stdout.on('data', (data) => {
plotFilePaths.push(data.toString());
});
pythonProcess.stderr.on('data', (data) => {
console.error(`Python Error: ${data}`);
if (!responseSent) {
responseSent = true;
res.status(500).send('Internal Server Error');
}
});
pythonProcess.on('close', (code) => {
if (code === 0 && !responseSent) {
try {
// Convert the array of plot file paths to a JSON string
const analysisResults = JSON.stringify(plotFilePaths);
const queryParams = encodeURIComponent(analysisResults);
// Redirect to the ads route and pass the plotFilePaths as a query parameter
res.redirect(`/ads?plotFilePaths=${queryParams}`);
} catch (error) {
console.error('Error parsing analysis results:', error);
res.status(500).send('Internal Server Error');
}
} else if (!responseSent) {
console.error(`Python process exited with code ${code}`);
responseSent = true;
res.status(500).send('Internal Server Error');
}
});
}
else {
res.status(400).send('Invalid form submission.');
}
});
app.get("/contact", function(req, res) {
res.render("contact");
});
app.listen(3000, () => {
console.log(`Server is running on port 3000`);
});