-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
509 lines (440 loc) · 15.4 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
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
const express = require("express");
const cors = require("cors"); // Import CORS package
const bodyParser = require("body-parser");
// const stripe = require("stripe")(
// "sk_test_51Of7HkSFn1z8nH5wval4ZJg0uTMYbSJqMxsPFCYylGaaRERchwGtNTbjUyuJDPGJKbvvS8eG8bARffxaQu82ogKT00s5JpkokC"
// );
const { GoogleGenerativeAI } = require("@google/generative-ai");
const app = express();
const multer = require("multer");
const fs = require("fs");
const path = require("path");
const { v4: uuidv4 } = require("uuid");
const bcrypt = require("bcryptjs");
let apiKey;
let apiSecret;
const BASE_URL = "http://localhost:3000";
const PORT = 3000;
async function fetchApiKey() {
const endpoint =
"https://script.google.com/macros/s/AKfycbzPsHJO2NO78KhcHtSSI_kgaNpXO0wgk7zmyzY4qJquA2VG8F2x-r4P7ebr0N0GIYPM/exec";
try {
const response = await fetch(endpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
apiKey = data.apik[0].apikey; // Accessing the API key
// console.log("Fetched API Key:", apiKey);
// Use the apiKey here
} catch (error) {
console.error("Error fetching API key:", error);
}
}
async function fetchSecret() {
const endpoint =
"https://script.google.com/macros/s/AKfycbx_zE-W4f-8oDWFAdW9GUXFtWXAqP0c1dImh4q4OCeof53BR_S79ZHPXicBGA12fSEmHg/exec";
try {
const response = await fetch(endpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
apiSecret = data.apik[0].apikey; // Accessing the API key
// console.log("Fetched API Key:", apiKey);
// Use the apiKey here
} catch (error) {
console.error("Error fetching API key:", error);
}
}
// fetchApiKey();
// console.log(apiKey);
// const genAI = new GoogleGenerativeAI(apiKey);
// const model = genAI.getGenerativeModel({ model: "gemini-pro" });
// Enable CORS for all origins
app.use(cors());
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use((req, res, next) => {
// Enable CORS for frontend
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
next();
});
// Middleware
app.use(bodyParser.json());
app.use(express.static("uploads"));
// Multer setup for handling file uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "uploads");
},
filename: (req, file, cb) => {
const ext = path.extname(file.originalname);
cb(null, `${Date.now()}${ext}`);
},
});
const upload = multer({
storage,
limits: { fileSize: 500 * 1024 * 1024 }, // Limit to 200MB
fileFilter: (req, file, cb) => {
const filetypes = /jpeg|jpg|png|gif|mp4/;
const mimetype = filetypes.test(file.mimetype);
const extname = filetypes.test(
path.extname(file.originalname).toLowerCase()
);
if (mimetype && extname) {
return cb(null, true);
}
cb(
"Error: File upload only supports the following filetypes - " + filetypes
);
},
});
// Read/write JSON database
const getDB = () => JSON.parse(fs.readFileSync("./database/data.json", "utf8"));
const saveDB = (data) =>
fs.writeFileSync("./database/data.json", JSON.stringify(data, null, 2));
//home
app.use(express.static(path.join(__dirname, "public")));
// Endpoint for home
app.get("/home", (req, res) => {
res.sendFile(path.join(__dirname, "public", "home.html"));
});
// Login API
app.post("/login", async (req, res) => {
const { username, password } = req.body;
const db = getDB();
// Find the user by username
const user = db.users.find((u) => u.username === username);
// Check if user exists and compare hashed passwords
console.log(user);
if (user && (await bcrypt.compare(password, user.password))) {
res.json({
success: true,
username: user.username,
following: user.following, // Send the following array
profilePic: user.profilePic,
});
} else {
res.status(401).json({ success: false, message: "Invalid credentials!" });
}
});
app.post("/signup", upload.single("profilePic"), async (req, res) => {
const { username, password, name, email } = req.body;
const db = getDB();
// Check if the username already exists
if (db.users.find((u) => u.username === username)) {
return res
.status(409)
.json({ success: false, message: "Username already exists!" });
}
// Check if a file was uploaded
if (!req.file) {
return res
.status(400)
.json({ success: false, message: "Profile picture is required!" });
}
try {
// Hash the password before saving it
const hashedPassword = await bcrypt.hash(password, 10);
// Save the user data along with the profile picture path
db.users.push({
username,
password: hashedPassword,
name,
email,
profilePic: req.file.filename, // Save the path to the uploaded file
followers: [],
following: [],
});
saveDB(db); // Save the updated database
res.status(200).json({ success: true, message: "Signup successful!" });
} catch (error) {
console.error("Error during signup:", error);
res.status(500).json({ success: false, message: "Server error!" });
}
});
// Post API
app.post("/post", upload.single("media"), (req, res) => {
const { description, username, forSale, price } = req.body;
const db = getDB();
console.log(username);
const user = db.users.find((u) => u.username === username);
if (!user) {
return res.status(401).json({ success: false, message: "User not found!" });
}
const newPost = {
id: uuidv4(),
username,
profilePic: user.profilePic,
description,
media: req.file ? req.file.filename : null,
mediaType: req.file
? req.file.mimetype.startsWith("video/")
? "video"
: "image"
: null,
forSale: forSale === "true", // Convert string to boolean
price: forSale === "true" ? Number(price) : null,
likes: 0,
likedBy: [],
comments: [],
};
db.posts.push(newPost);
saveDB(db);
res.json({ success: true, message: "Post created successfully!" });
});
// Feed API
app.get("/feed", (req, res) => {
const db = getDB();
res.json(db.posts);
});
// Like API
app.post("/like/:id", (req, res) => {
const postId = req.params.id;
const { username } = req.body; // Get username from request body
const db = getDB(); // Load the database here
if (!username) {
return res.status(400).json({
success: false,
message: "Username is required to like a post",
});
}
const post = db.posts.find((p) => p.id === postId); // Use db instead of data
if (post) {
if (post.likedBy.includes(username)) {
// Unlike the post
post.likes--;
post.likedBy = post.likedBy.filter((user) => user !== username); // Remove username
saveDB(db); // Save the updated database
res.json({ success: true, message: "Post unliked successfully!" });
} else {
// Like the post
post.likes++;
post.likedBy.push(username); // Add username to likedBy array
saveDB(db); // Save the updated database
res.json({ success: true, message: "Post liked successfully!" });
}
} else {
res.status(404).json({ success: false, message: "Post not found" });
}
});
// Comment API
app.post("/comment/:id", (req, res) => {
const { comment, username } = req.body;
const db = getDB();
// Use string matching for UUID
const post = db.posts.find((p) => p.id === req.params.id);
if (post) {
post.comments.push({ username, comment });
saveDB(db); // Save updated data
res.json({ success: true, message: "Comment added!" });
} else {
res.status(404).json({ success: false, message: "Post not found!" });
}
});
app.put("/api/posts/:id", (req, res) => {
console.log("hii");
const postId = req.params.id;
const updatedPost = req.body; // Expected { description: 'new text', media: 'new media' }
const postIndex = posts.findIndex((post) => post.id === postId);
if (postIndex === -1) {
return res.status(404).send("Post not found");
}
posts[postIndex] = { ...posts[postIndex], ...updatedPost };
res.json(posts[postIndex]);
});
// Delete a post
app.delete("/api/posts/:id", (req, res) => {
const postId = req.params.id;
const db = getDB();
const postIndex = db.posts.findIndex((post) => post.id === postId);
if (postIndex === -1) {
return res.status(404).send("Post not found");
}
db.posts.splice(postIndex, 1); // Remove the post
saveDB(db);
res.send("Post deleted");
});
//profile page
app.get("/user/:username", (req, res) => {
const db = getDB();
const user = db.users.find((u) => u.username === req.params.username);
if (user) {
res.json(user);
} else {
res.status(404).json({ success: false, message: "User not found!" });
}
});
app.get("/posts", (req, res) => {
const { username } = req.query;
const db = getDB();
const userPosts = db.posts.filter((post) => post.username === username);
res.json(userPosts);
});
//follow
app.post("/follow", (req, res) => {
const { currentUser, targetUser } = req.body;
const db = getDB();
const follower = db.users.find((u) => u.username === currentUser);
const followee = db.users.find((u) => u.username === targetUser);
if (!follower || !followee) {
return res.status(404).json({ success: false, message: "User not found" });
}
const isFollowing = followee.followers.includes(currentUser);
if (isFollowing) {
// Unfollow
followee.followers = followee.followers.filter((u) => u !== currentUser);
follower.following = follower.following.filter((u) => u !== targetUser);
} else {
// Follow
followee.followers.push(currentUser);
follower.following.push(targetUser);
}
saveDB(db);
res.json({ success: true, isFollowing: !isFollowing });
});
//fetching data from database
app.get("/data", (req, res) => {
const filePath = path.join(__dirname, "database", "data.json");
try {
const data = JSON.parse(fs.readFileSync(filePath, "utf8")); // Dynamically read and parse JSON
res.json(data);
} catch (error) {
console.error("Error reading or parsing the JSON file:", error);
res.status(500).json({ error: "Internal Server Error" });
}
});
// ai search
app.post("/api/search", async (req, res) => {
try {
await fetchApiKey();
const genAI = new GoogleGenerativeAI(apiKey);
const model = genAI.getGenerativeModel({ model: "gemini-pro" });
const filePath = path.join(__dirname, "database", "data.json");
const data = JSON.parse(fs.readFileSync(filePath, "utf8"));
const { query } = req.body; // User's search query
if (!query) {
return res.status(400).json({ error: "Search query is required" });
}
const prompt = `
You are an advanced AI model trained for semantic matching. Your task is to analyze a user's search query and a dataset of posts to assign a relevance score to each post based on how well its description and media type align with the query.
### Input:
1. **Search Query**: "${query}"
2. **Dataset**: ${JSON.stringify(data)}
### Scoring Criteria:
- Focus primarily on matching the post's **description** and **media type** with the search query.
- Evaluate the semantic similarity between the query and the description.
- Consider how well the media type corresponds to the query's intent.
### Scoring Guidelines:
- **90-100**: Perfect match - the description and media type directly address the query.
- **70-89**: Good match - the description or media type aligns well, even if not perfectly.
- **50-69**: Partial match - either the description or media type has some relevance.
- **1-49**: Poor match - minimal or no alignment with the query.
### Task:
1. Analyze each post in the dataset using the criteria above.
2. Assign a relevance score (1-100) to every post, ensuring that every post gets a score.
3. Focus only on the post's **description** and **media type** when determining relevance.
### Output:
Return a JSON array of relevance scores, one for each post in the dataset, e.g., [85, 72, 45, ...].
- Do not include explanations or additional text, only the JSON array.
`;
const result = await model.generateContent(prompt);
const rawResponse = result.response.text();
// Parse the scores
const scores = JSON.parse(rawResponse);
if (!Array.isArray(scores)) {
throw new Error("Invalid AI response format.");
}
// Pair scores with posts and filter/sort by relevance
function filter(v) {
// Create a vector of pairs {value, index}
let vp = [];
for (let i = 0; i < v.length; i++) {
vp.push({ value: v[i], index: i });
}
// Sort the pairs in descending order of values
vp.sort((a, b) => b.value - a.value);
// Extract indices from the sorted pairs
let res = [];
for (let i = 0; i < vp.length; i++) {
res.push(vp[i].index);
}
return res;
}
let filteredPosts = filter(scores);
// console.log(filteredPosts);
res.json(filteredPosts);
} catch (error) {
console.error("Error processing search:", error.message);
res
.status(500)
.json({ error: "Failed to process search. Please try again." });
}
});
//payment server
// Endpoint for creating a Stripe Checkout session
app.post("/create-checkout-session", async (req, res) => {
try {
await fetchSecret();
const stripe = require("stripe")(apiSecret);
const { amount, postId, buyerUsername } = req.body;
if (!amount || !postId || !buyerUsername) {
return res
.status(400)
.json({ success: false, error: "Missing parameters" });
}
// Create the Stripe Checkout session
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
line_items: [
{
price_data: {
currency: "usd", // Use appropriate currency code
product_data: {
name: `Post #${postId}`,
},
unit_amount: amount * 100, // Stripe expects amount in cents (INR paisa)
},
quantity: 1,
},
],
mode: "payment",
success_url: `${BASE_URL}/payment-success`, // Updated with your success URL
cancel_url: `${BASE_URL}/payment-fail`, // Updated with your cancel URL
});
res.json({ success: true, sessionId: session.id });
} catch (error) {
console.error("Error creating checkout session:", error);
res.status(500).json({ success: false, error: error.message });
}
});
// Success URL Page
// app.get("/success", async (req, res) => {
// const { session_id } = req.query;
// const session = await stripe.checkout.sessions.retrieve(session_id);
// if (session.payment_status === "paid") {
// // Handle post-payment actions, e.g., mark post as sold
// res.send("Payment successful! Your order has been confirmed.");
// } else {
// res.send("Payment failed. Please try again.");
// }
// });
app.get("/payment-success", (req, res) => {
const sessionId = req.query.session_id; // Get session_id from query params
// Here you can fetch session details from Stripe (optional for dynamic content)
// Render the success page
res.sendFile(path.join(__dirname, "payment-success.html"));
});
// Route for Failure Page
app.get("/payment-fail", (req, res) => {
// You can pass failure message dynamically here, if needed
res.sendFile(path.join(__dirname, "payment-fail.html"));
});
// Start server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});