-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
375 lines (333 loc) · 9.62 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
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
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const UserModel = require('./model/User');
const NgoModel = require('./model/NGOs');
const { lightFormat } = require('date-fns');
const { auth } = require('express-openid-connect');
const cors = require('cors');
const { GoogleGenerativeAI } = require('@google/generative-ai');
const http = require('http');
const socketIo = require('socket.io');
const path = require('path');
require('dotenv').config();
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const uri = `mongodb+srv://Oren:${process.env.MONGOPASS}@socially.whgla2v.mongodb.net/socially?retryWrites=true&w=majority`;
const app = express();
const port = 3000;
const corsOptions = {
origin: '*', // Allow all origins
credentials: true, // Enable credentials
};
connect();
let socket;
app.use(cors(corsOptions));
app.use(express.json({ limit: '50mb' }));
app.use(
express.urlencoded({ limit: '50mb', extended: true, parameterLimit: 50000 })
);
const server = http.createServer(app);
const io = socketIo(server, {
cors: corsOptions,
});
io.on('connection', (socketConnection) => {
console.log('client connected');
socket = socketConnection;
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
async function connect() {
try {
await mongoose.connect(uri);
console.log('Connected to MongoDB');
} catch (e) {
console.error(e);
}
}
connect();
async function saveUser(userFlag, username, email) {
if (userFlag) {
return;
}
const user = new UserModel({
username: username,
email: email,
});
await user
.save()
.then(() => console.log('User created'))
.catch((err) => console.error(err));
}
async function saveNgo(userFlag, username, email) {
if (userFlag) {
return;
}
const user = new NgoModel({
username: username,
email: email,
});
await user
.save()
.then(() => console.log('Ngo created'))
.catch((err) => console.error(err));
}
const config = {
authRequired: false,
auth0Logout: true,
secret: process.env.SECRET,
baseURL: process.env.BASEURL,
clientID: process.env.CLIENTID,
issuerBaseURL: process.env.ISSUER,
};
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
app.use(express.static('public'));
app.use('/css', express.static(__dirname + 'public/css'));
app.use('/js', express.static(__dirname + 'public/js'));
app.use('/img', express.static(__dirname + 'public/img'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(auth(config));
app.set('views', './views');
app.set('view engine', 'ejs');
app.get(['', '/home'], async (req, res) => {
if (req.oidc.isAuthenticated()) {
const user = await UserModel.findOne({
username: req.oidc.user.name,
email: req.oidc.user.email,
}).catch((err) => console.log(err));
const ngo = await NgoModel.findOne({
username: req.oidc.user.name,
email: req.oidc.user.email,
}).catch((err) => console.log(err));
if (user) {
return res.redirect('/dashboard');
} else if (ngo) {
return res.redirect('/ngo-dashboard');
} else {
return res.render('chooseRole');
}
} else {
return res.render('index');
}
});
app.get('/callback', (req, res) => {
res.redirect('/dashboard');
});
app.get('/about', (req, res) => {
res.render('about');
});
app.get('/signup', (req, res) => {
res.render('sign-up/signup');
});
app.get('/nearbyactivity', (req, res) => {
res.render('nearbystuff');
});
app.get('/findyourgroup', (req, res) => {
res.render('findYourGroup');
});
app.get('/finalpage', (req, res) => {
res.render('finalPage');
});
app.get('/chooserole', (req, res) => {
res.render('chooseRole');
});
app.get('/enroll', (req, res) => {
res.render('enroll');
});
app.get('/index', (req, res) => {
res.render('index');
});
const isAuthenticated = (req, res, next) => {
if (req.oidc.isAuthenticated()) {
return next();
} else {
res.redirect('/');
}
};
app.get('/dashboard', isAuthenticated, async (req, res) => {
console.log('Accessing dashboard route');
const username = req.oidc.user.name;
const locationInfo = req.oidc.user.email;
const pictureUrl = req.oidc.user.picture;
await UserModel.findOne({ email: locationInfo })
.then((user) => saveUser(user, username, locationInfo))
.catch((err) => console.error(err));
res.render('dashboard', {
username: username,
location: locationInfo,
picture: pictureUrl,
});
console.log('Username:', username);
console.log('Location:', locationInfo);
});
app.get('/ngo-dashboard', isAuthenticated, async (req, res) => {
console.log('Accessing ngo dashboard route');
const username = req.oidc.user.name;
const locationInfo = req.oidc.user.email;
await NgoModel.findOne({ email: locationInfo })
.then((user) => saveNgo(user, username, locationInfo))
.catch((err) => console.error(err));
res.render('ngoDashboard', {
username: username,
location: locationInfo,
});
console.log('Username:', username);
console.log('Location:', locationInfo);
});
app.get('/get-user-groups', async (req, res) => {
const locationInfo = req.oidc.user.email;
let groupArr = [];
await UserModel.findOne({ email: locationInfo }).then(
(user) => (groupArr = user.groups)
);
res.json(groupArr);
});
app.get('/get-user-ngos', async (req, res) => {
const locationInfo = req.oidc.user.email;
let ngoArr = [];
await UserModel.findOne({ email: locationInfo }).then(
(user) => (ngoArr = user.ngos)
);
res.json(ngoArr);
});
app.get('/get-ngo-events', async (req, res) => {
const locationInfo = req.oidc.user.email;
let eventsArr = [];
await NgoModel.findOne({ email: locationInfo }).then(
(user) => (eventsArr = user.events)
);
res.json(eventsArr);
});
app.get('/get-events', async (req, res) => {
let eventsArr = [];
await NgoModel.find().then((ngos) => {
ngos.forEach((ngo) => {
eventsArr = [...eventsArr, ...ngo.events];
});
});
res.json(eventsArr);
});
app.put('/add-user-group/:group', async (req, res) => {
const group = JSON.parse(req.params.group);
const locationInfo = req.oidc.user.email;
let userGroups = 0;
await UserModel.findOne({ email: locationInfo }).then((user) => {
userGroups = user.groups;
});
if (userGroups.find((userGroup) => userGroup.name == group.name)) {
console.log('Exists already');
} else {
await UserModel.findOneAndUpdate(
{ email: locationInfo },
{ $push: { groups: group } }
).then(() => console.log('Added group'));
}
});
app.post('/add-ngo-event/:event', async (req, res) => {
const event = JSON.parse(req.params.event);
//Formating date and time
event.date = lightFormat(new Date(event.date), 'yyyy-MM-dd');
const dateArray = event.time.split(':');
event.time = lightFormat(
new Date(2000, 1, 1, dateArray[0], dateArray[1]),
'hh:mm a'
);
const locationInfo = req.oidc.user.email;
let ngoEvents = 0;
await NgoModel.findOne({ email: locationInfo }).then((ngo) => {
ngoEvents = ngo.events;
});
if (ngoEvents.find((ngoEvent) => ngoEvent.title == event.title)) {
res.status(400).send('event with the same name already exists');
} else {
await NgoModel.findOneAndUpdate(
{ email: locationInfo },
{ $push: { events: event } }
).then(() => console.log('Added event'));
res.status(200).send('Event created');
}
});
app.put('/add-user-ngo/:ngo', async (req, res) => {
try {
const ngo = JSON.parse(req.params.ngo);
const locationInfo = req.oidc.user.email;
let userNgos = [];
await UserModel.findOne({ email: locationInfo }).then((user) => {
userNgos = user.ngos;
//console.log('User NGOs:', userNgos);
});
if (userNgos.find((userNgo) => userNgo.title == ngo.title)) {
//console.log('NGO already exists');
res.send('NGO already exists');
} else {
await UserModel.findOneAndUpdate(
{ email: locationInfo },
{ $push: { ngos: ngo } }
);
//console.log('NGO added successfully');
res.send('NGO added successfully');
}
} catch (error) {
console.error('Error:', error);
res.status(500).send('Internal Server Error');
}
});
app.post('/', async (req, res) => {
const prompt = req.body.prompt.trim();
});
const generationConfig = {
stopSequences: ['red'],
maxOutputTokens: 5,
temperature: 0.9,
topP: 0.1,
topK: 16,
};
const model = genAI.getGenerativeModel({
model: 'MODEL_NAME',
generationConfig,
});
app.post('/generate', async (req, res) => {
const { base64Image, prompt } = req.body;
// console.log(base64Image, prompt);
const imagePart = {
inlineData: {
data: base64Image,
mimeType: 'image/png',
},
};
try {
let result;
if (base64Image) {
const model = genAI.getGenerativeModel({ model: 'gemini-pro-vision' });
result = await model.generateContentStream([prompt, imagePart]);
} else {
const model = genAI.getGenerativeModel({
model: 'gemini-pro',
generationConfig,
});
result = await model.generateContentStream(prompt);
}
let text = '';
for await (const chunk of result.stream) {
const chunkText = chunk.text();
console.log(chunkText);
text += chunkText;
if (socket) {
try {
socket.emit('content', chunkText);
} catch (error) {
console.error('Error emitting content:', error.message);
}
}
}
if (socket) {
socket.disconnect();
}
res.status(200).json({ message: 'success' });
} catch (err) {
console.error('Error generating content:', err.message);
res.status(500).json({ error: 'Error generating content' });
}
});