Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1781 lines (1558 loc) · 49.3 KB
/
Copy pathapp.js
File metadata and controls
1781 lines (1558 loc) · 49.3 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
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require("express");
const mongoose = require("mongoose");
const { isValidObjectId } = require("mongoose");
const ejsMate = require("ejs-mate");
const methodOverride = require("method-override");
const passport = require("passport");
const LocalStrategy = require("passport-local");
const axios = require("axios");
const http = require("http");
const socketIO = require("socket.io");
const { GoogleGenerativeAI } = require("@google/generative-ai");
const fs = require("fs");
const path = require("path");
const csvWriter = require("csv-write-stream");
const genAI = new GoogleGenerativeAI("AIzaSyBzAaNuBfgF8-_S3xHkBEaQcXdO8Q3hVE0");
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const User = require("./models/user.js");
const Comment = require("./models/comment.js");
const Subscription = require("./models/subscription.js");
const WatchHistory = require("./models/watchhistory.js");
const Post = require("./models/Post.js");
const flash = require("connect-flash");
const bodyParser = require("body-parser");
const multer = require("multer");
const session = require("express-session");
const {
storage,
uploadOnCloudinary,
cloudinary,
upload,
} = require("./cloudConfig.js");
const Video = require("./models/vedio.js");
const MongoStore = require("connect-mongo");
const { log, Console, error } = require("console");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const Chat = require("./models/chat.js");
const app = express();
const server = http.createServer(app);
const io = socketIO(server);
const usp = io.of("/users-namespace");
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ limit: '10mb', extended: true }));
require("dotenv").config();
require("./auth.js");
const ensureAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
return next();
}
req.flash("error", "Please login first!");
res.redirect("/login");
};
app.use(flash());
app.use(methodOverride("_method"));
app.engine("ejs", ejsMate);
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, "/public")));
app.set("views", path.join(__dirname, "views"));
// console.log(process.env.ATLAS_DB);
// async function main() {
// await mongoose.connect('mongodb://127.0.0.1:27017/streamsphere');
// console.log('Connected to DB');
// }
// main().catch((err) =>
// console.log(err)
// );
async function main() {
await mongoose.connect(process.env.ATLAS_DB);
console.log("Connected to DB");
}
main().catch((err) => console.log(err));
const store = MongoStore.create({
mongoUrl: process.env.ATLAS_DB,
touchAfter: 24 * 60 * 60,
crypto: {
secret: process.env.SECRET,
},
});
store.on("error", function (e) {
console.log("session store error", e);
});
app.use(
session({
store,
secret: process.env.SECRET,
resave: true,
saveUninitialized: true,
cookie: {
httpOnly: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7,
},
})
);
app.use(passport.initialize());
app.use(passport.session());
app.use((req, res, next) => {
res.locals.success = req.flash("success");
res.locals.error = req.flash("error");
res.locals.currentUser = req.user;
next();
});
//homepage
app.get("/", async (req, res) => {
if (req.isAuthenticated()) {
res.redirect(`/user/${req.user._id}`);
}
const allVideos = await Video.find().populate("owner");
res.render("pages/index.ejs", { allVideos, req });
});
//login and signup
app.get("/login", (req, res) => {
if (!req.isAuthenticated()) {
res.render("users/login.ejs");
} else {
res.redirect(`/user/${req.user._id}`);
}
});
app.post(
"/login",
passport.authenticate("local", {
failureRedirect: "/login",
failureFlash: true,
}),
(req, res) => {
req.flash("success", "Welcome back!");
res.redirect(`/user/${req.user._id}`);
}
);
app.get("/signup", (req, res) => {
if (!req.isAuthenticated()) {
res.render("users/signup.ejs", {
error: req.flash("error"),
req,
success: req.flash("success"),
});
} else {
res.redirect(`/user/${req.user._id}`);
}
});
app.post("/signup", async (req, res) => {
try {
const { username, email, password } = req.body.user;
console.log(req.body);
let newUser = new User({ email, username });
const registeredUser = await User.register(newUser, password);
req.login(registeredUser, (err) => {
if (err) {
console.error(err);
req.flash("error", "Error signing up");
return res.redirect("/signup");
}
req.flash("success", "Registration successful! Welcome to Wanderlust.");
res.render("pages/category.ejs", { req, currentUser: req.user });
});
} catch (err) {
console.error(err);
req.flash("error", "Error signing up");
res.redirect("/signup");
}
});
app.get("/logout", (req, res) => {
req.logout((err) => {
if (err) {
console.error(err);
res.render("users/login.ejs", {
error: "Error logging out. Please try again.",
});
}
req.flash("success", "You are logged out. Goodbye!");
res.redirect("/");
});
});
//giving access to category
app.get("/category", ensureAuthenticated, async (req, res) => {
const user = await User.findById(req.params.id);
res.render("pages/category.ejs", { req, currentUser: req.user });
});
app.put("/user/:id/submit", ensureAuthenticated, async (req, res) => {
try {
const userId = req.params.id;
console.log(req.body, "req.body");
const categories = Array.isArray(req.body.categories)
? req.body.categories
: [req.body.categories];
console.log(categories);
const newUser = await User.findByIdAndUpdate(userId, {
categories: categories,
});
res.redirect(`/user/${userId}`);
} catch (error) {
console.error("Error updating user:", error);
res.status(500).send("Error updating user");
}
});
const getrecommendations = async (videoData) => {
try {//https://stream-sphere-ml.onrender.com
console.log(videoData)
const response = await fetch("https://stream-sphere-ml.onrender.com/", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(videoData),
});
if (!response.ok) {
const errorText = await response.text();
console.error('Error from API:', errorText); // Log the actual response for debugging
throw new Error(`API Error: ${response.status} ${response.statusText}`);
}
const data = await response.json();
console.log(data);
if (data.message === "Recommendations fetched successfully") {
return data.recommended_ids;
} else {
console.log("Error fetching recommendations:", data);
return [];
}
} catch (error) {
console.error("ML model is not running:", error);
return [];
}
};
app.get("/user/:id", ensureAuthenticated, async (req, res) => {
try {
const user = await User.findById(req.params.id).populate("watchHistory");
const userCategories = user.categories;
console.log(userCategories);
const allVideos = await Video.find({
categories: { $in: userCategories },
}).populate("owner");
const waitingUsers = [];
for (const requestID of user.waiting) {
const requestUser = await User.findById(requestID);
if (requestUser) {
waitingUsers.push(requestUser);
}
}
let recommendedVideos = [];
if (user.watchHistory.length > 0) {
const lastWatchHistoryEntry =
user.watchHistory[user.watchHistory.length - 1];
const watchHistory = await WatchHistory.findById(lastWatchHistoryEntry).populate("video");
const lastWatchedVideo = watchHistory.video;
const recommendationIds = await getrecommendations({
title: lastWatchedVideo.title,
});
recommendedVideos = await Video.find({ _id: { $in: recommendationIds } }).populate("owner");
if (recommendedVideos.length < 6) {
const additionalVideos = await Video.find({
categories: { $in: userCategories },
_id: { $nin: recommendedVideos.map((v) => v._id) },
}).populate("owner").limit(6 - recommendedVideos.length);
recommendedVideos = [...recommendedVideos, ...additionalVideos];
}
} else {
recommendedVideos = await Video.find({ categories: { $in: userCategories } }).populate("owner").limit(10);
}
res.render("pages/index.ejs", {
user,
currentUser: req.user,
req,
allVideos,
waitingUsers,
recommendedVideos,
});
} catch (error) {
console.error("Error fetching user's videos:", error);
res.status(500).send("Error fetching user's videos");
}
});
app.get("/user/:id/upload", ensureAuthenticated, (req, res) => {
res.render("pages/upload.ejs", { req, currentUser: req.user });
});
const { Parser } = require("json2csv");
app.post("/user/:id/upload", ensureAuthenticated, async (req, res) => {
try {
console.log("req.body", req.body);
const { title, description, categories, videoFileUrl, thumbnailUrl } =
req.body;
if (!title || !description || !videoFileUrl || !thumbnailUrl) {
req.flash("error", "Title and description are required.");
return res.redirect(`/user/${req.user._id}/upload`);
}
const publishVideo = await Video.create({
videoFile: videoFileUrl,
thumbnail: thumbnailUrl,
title,
description,
isPublished: false,
categories,
owner: req.user._id,
});
if (!publishVideo) {
console.error("Error publishing video:", publishVideo);
return res.redirect(`/user/${req.user._id}/upload`);
}
await publishVideo.save();
const videoId = publishVideo._id;
const data = await Video.find({ _id: videoId });
// Function to escape and format the data for CSV
function escapeField(field) {
if (typeof field === "string") {
// Remove Markdown characters and escape quotes
return field
.replace(/[*]+/g, "")
.replace(/"/g, '""')
.replace(/\n/g, " ")
.trim();
}
return field;
}
// Convert the data to the required format (array of values as strings)
function convertToCSVFormat(data) {
return data.map((item) => [
`"${item._id}"`, // ID as string
`"${item.videoFile}"`, // Video URL as string
`"${item.thumbnail}"`, // Thumbnail URL as string
`"${escapeField(item.title)}"`, // Title
`"${escapeField(item.description)}"`, // Description
`${item.views || 0}`, // Views as string (default to 0 if undefined)
`${item.isPublished}`, // Is Published status (boolean as string)
`"${item.categories.join(", ")}"`, // Categories (array converted to string)
`"${item.owner}"`, // Owner ID as string
`"${item.createdAt.toISOString()}"`, // Created at timestamp as string
`"${item.updatedAt.toISOString()}"`, // Updated at timestamp as string
]);
}
const csvDataArray = convertToCSVFormat(data);
try {
const csvFilePath = path.join(
__dirname,
"recommendation_system",
"datasets",
"videos_data.csv"
);
const fileExists = fs.existsSync(csvFilePath);
// Convert the data array to a string with proper line breaks
const csvDataString = csvDataArray.map((row) => row.join(",")).join("\n");
if (!fileExists) {
// Add headers if the file does not exist
const headers = [
"ID",
"Video URL",
"Thumbnail URL",
"Title",
"Description",
"Views",
"Is Published",
"Categories",
"Owner ID",
"Created At",
"Updated At",
];
// Write headers and data to the file
fs.writeFileSync(
csvFilePath,
headers.join(",") + "\n" + csvDataString + "\n",
{ flag: "w" }
);
} else {
// Append data to the file (ensure each row starts on a new line)
fs.appendFileSync(csvFilePath, csvDataString + "\n", { flag: "a" });
}
console.log("Data successfully written to videos_data.csv");
} catch (err) {
console.error("Error generating CSV:", err);
return res
.status(500)
.json({ success: false, message: "Failed to generate CSV" });
}
console.log("Video published and saved to CSV:", publishVideo);
res.status(200).json({ success: true });
} catch (error) {
console.error("Error uploading video:", error);
req.flash("error", "Error uploading video.");
res.redirect(`/user/${req.user._id}/upload`);
}
});
app.post(
"/upload-files",
upload.fields([
{ name: "videoFile", maxCount: 1 },
{ name: "thumbnail", maxCount: 1 },
]),
ensureAuthenticated,
async (req, res) => {
try {
const videoLocalPath = req.files["videoFile"][0].path;
const thumbnailLocalPath = req.files["thumbnail"][0].path;
const [thumbnailResponse, videoResponse] = await Promise.all([
uploadOnCloudinary(thumbnailLocalPath),
uploadOnCloudinary(videoLocalPath),
]);
if (!thumbnailResponse || !videoResponse) {
return res
.status(500)
.json({ success: false, message: "File upload failed" });
}
res.status(200).json({
success: true,
videoUrl: videoResponse.secure_url,
thumbnailUrl: thumbnailResponse.secure_url,
});
} catch (error) {
console.error("Error uploading files:", error);
res
.status(500)
.json({ success: false, message: "Error uploading files" });
}
}
);
async function fileToGenerativePart(url, mimeType) {
try {
console.log(`Downloading image from: ${url}`);
const response = await axios.get(url, { responseType: "arraybuffer" });
console.log("Image downloaded successfully.");
// Assign the downloaded data to a buffer variable
const buffer = Buffer.from(response.data); // Correctly define buffer
console.log("Image converted to buffer.");
const base64Image = buffer.toString("base64");
console.log("Image converted to Base64.");
return {
inlineData: {
data: base64Image,
mimeType,
},
};
} catch (error) {
console.error("Error in fileToGenerativePart:", error);
throw error;
}
}
async function deleteFromCloudinary(publicId) {
return new Promise((resolve, reject) => {
cloudinary.uploader.destroy(publicId, (error, result) => {
if (error) {
console.error("Error deleting from Cloudinary:", error);
return reject(error);
}
console.log("Successfully deleted from Cloudinary:", result);
resolve(result);
});
});
}
app.post("/delete-files", ensureAuthenticated, async (req, res) => {
const { videoUrl, thumbnailUrl } = req.body;
try {
// Extract public IDs from URLs
const videoPublicId = videoUrl.split("/").pop().split(".")[0]; // Adjust based on your URL format
const thumbnailPublicId = thumbnailUrl.split("/").pop().split(".")[0]; // Adjust based on your URL format
// Delete files from Cloudinary
await deleteFromCloudinary(videoPublicId);
await deleteFromCloudinary(thumbnailPublicId);
res
.status(200)
.json({ success: true, message: "Files deleted successfully." });
} catch (error) {
console.error("Error deleting files:", error);
res.status(500).json({ success: false, message: "Error deleting files." });
}
});
const marked = require("marked");
app.post("/generate-description", ensureAuthenticated, async (req, res) => {
try {
console.log("Generating description...", req.body);
const { thumbnailUrl } = req.body;
console.log(`Received thumbnail URL: ${thumbnailUrl}`);
const imagePart = await fileToGenerativePart(thumbnailUrl, "image/jpeg");
console.log("Image part generated:", imagePart);
const prompt = "Describe how this product might be manufactured.";
console.log("Prompt:", prompt);
const result = await model.generateContent([prompt, imagePart]);
console.log("Generative model result:", result);
const candidate = result.response.candidates[0];
console.log("First candidate:", candidate);
const description = candidate.content.parts[0];
console.log("Description generated:", description);
if (description) {
// Convert the description to HTML using marked
const descriptionHTML = marked.parse(description.text);
console.log("Generated HTML:", descriptionHTML);
res.status(200).json({
success: true,
description: descriptionHTML, // Send the HTML instead of plain text
});
} else {
console.log("Failed to generate description:", result);
res.status(500).json({
success: false,
message: "Failed to generate description",
});
}
} catch (error) {
console.error("Error generating description:", error);
res.status(500).json({
success: false,
message: "Error generating description",
});
}
});
app.get("/videos/:id", ensureAuthenticated, async (req, res) => {
res.redirect("/login");
});
//watch video
app.get("/user/:id/videos/:video", ensureAuthenticated, async (req, res) => {
try {
// Get the user's category
const userCategory = req.user.categories;
// Find the video based on the ID and category
const video = await Video.findOne({ _id: req.params.video }).populate(
"owner"
);
if (!video) {
return res.status(404).send("Video not found");
}
// Check if the user is subscribed to the video owner's channel
const videoOwnerId = video.owner._id.toString();
const subscription = await Subscription.findOne({
subscriber: req.user._id,
channel: videoOwnerId,
});
const subscribed = !!subscription;
// Count the number of likes on the video
const likesCount = await Like.countDocuments({ video: req.params.video });
// Fetch comments and organize them into threads
const comments = await Comment.find({ video: req.params.video })
.populate("owner")
.lean();
const threadedComments = organizeComments(comments);
// Add video to user's watch history
const existingWatchHistory = await WatchHistory.findOne({
user: req.user._id,
video: req.params.video,
});
if (!existingWatchHistory) {
const newWatchHistory = new WatchHistory({
user: req.user._id,
video: req.params.video,
});
await newWatchHistory.save();
// Update the user's watch history by adding the watch history entry ID
await User.findByIdAndUpdate(req.user._id, {
$push: { watchHistory: newWatchHistory._id },
});
}
// Get video recommendations
const videoData = {
channelName: video.owner.username,
title: video.title,
description: video.description,
};
const get_ids = await getrecommendations(videoData);
const get_videos = await Video.find({ _id: { $in: get_ids } }).populate("owner");
let allVideos = get_videos.filter(
(v) => v._id.toString() !== req.params.video
);
if (allVideos.length === 0) {
allVideos = await Video.find({ categories: userCategory }).populate("owner");
}
console.log(allVideos,"648")
res.render("pages/watch.ejs", {
req,
currentUser: req.user,
video,
otherVideos: allVideos,
comments: threadedComments,
subscribed,
likesCount,
});
} catch (err) {
console.error(err);
res.status(500).send("Internal Server Error");
}
});
app.get("/user/:id/history", ensureAuthenticated, async (req, res) => {
try {
const watchHistory = await WatchHistory.find({ user: req.params.id })
.populate("video")
.sort({ watchedAt: -1 });
if (!watchHistory) {
return res.status(404).send("No watch history found.");
}
res.render("pages/history.ejs", {
req,
currentUser: req.user,
watchHistory,
});
} catch (err) {
console.error(err);
res.status(500).send("Internal Server Error");
}
});
app.delete(
"/user/:id/history/:historyId",
ensureAuthenticated,
async (req, res) => {
try {
const { historyId, id } = req.params;
// Ensure the user can only delete their own history
const historyItem = await WatchHistory.findOne({
_id: historyId,
user: id,
});
if (!historyItem) {
return res.status(404).send("History item not found.");
}
// Remove the video from the user's watch history
await WatchHistory.deleteOne({ _id: historyId });
res.status(200).send("History item deleted successfully.");
} catch (error) {
console.error(error);
res.status(500).send("Internal server error.");
}
}
);
function organizeComments(comments) {
const commentMap = {};
comments.forEach((comment) => {
commentMap[comment._id] = comment;
comment.children = [];
});
const threadedComments = [];
comments.forEach((comment) => {
if (comment.parent) {
if (commentMap[comment.parent]) {
commentMap[comment.parent].children.push(comment);
}
} else {
threadedComments.push(comment);
}
});
return threadedComments;
}
//tweet
app.get("/t/:id", async (req, res) => {
try{
const currentuser = await User.findById(req.user._id);
const getTweet = await Post.find().populate("posted_by");
console.log(getTweet);
res.render("pages/Tweet.ejs",{req,currentuser,getTweet});
}
catch(error){
console.log(error,"error");
}
})
app.post("/t/:id", async (req, res) => {
try {
console.log(req.params.id);
const { id } = req.params;
const user = await User.findById(id);
if (!user) {
return res.status(404).send("User not found");
}
console.log(req.body);
let { postText, postImage } = req.body;
if (postImage !== null && postImage !== undefined) {
const uploadedImage = await cloudinary.uploader.upload(postImage);
console.log(uploadedImage);
postImage = uploadedImage.secure_url;
}
const newPost = new Post({
text: postText,
img: postImage || null,
posted_by: req.user._id
});
await newPost.save();
const populatedPost = await Post.findById(newPost._id).populate('posted_by', 'username avatar');
return res.status(200).json({
message: "Post created successfully",
newPost:populatedPost
});
} catch (error) {
console.error(error);
return res.status(500).send("Internal Server Error");
}
});
app.delete("/t/:id", async (req, res) => {
try {
const {id} = req.params;
const post = await Post.findById(id);
if(!post) return res.status(400).json({error:"Post not found"});
if(post.posted_by.toString() !== req.user._id.toString()){
return res.status(400).json({error:"not authorized"});
}
if(post.img){
const publicId = post.img.split("/").pop().split(".")[0];
await cloudinary.uploader.destroy(publicId);
}
await Post.findByIdAndDelete(id);
res.status(200).json({message:"success"});
} catch (error) {
console.log(error)
return res.status(500).send("Internal Server Error");
}
})
app.post("/t/:id/likeunlike", async (req, res) => {
try {
const { id } = req.params;
const post = await Post.findById(id);
if (!post) return res.status(400).json({ error: "Post not found" });
const userLikePost = post.likes.includes(req.user._id);
if (userLikePost) {
// Unlike post
await Post.findByIdAndUpdate(id, { $pull: { likes: req.user._id } });
res.status(200).json({ message: "success" });
} else {
// Like post
post.likes.push(req.user._id);
await post.save();
res.status(200).json({ message: "success" });
}
} catch (error) {
console.log(error);
res.status(500).json({ error: "Internal server error" });
}
})
app.post("/t/:id/reply", async (req, res) => {
try {
console.log(req.body)
const { id: postId } = req.params;
const { replyText } = req.body;
const userId = req.user._id;
const userProfilepic = req.user.avatar;
const username = req.user.username;
const text = replyText;
if (!text) return res.status(400).json({ error: "All fields are required" });
const post = await Post.findById(postId);
if (!post) return res.status(400).json({ error: "Post not found" });
const newReply = {
userId,
userPic:userProfilepic,
username,
text
};
console.log(newReply)
post.replies.push(newReply);
await post.save();
res.status(200).json({ reply: newReply });
} catch (error) {
console.error(error);
res.status(500).json({ error: "Server error" });
}
})
app.get('/t/r/:id',async(req,res)=>{
try {
const {id} = req.params;
const post = await Post.findById(id).populate('posted_by', 'username avatar');
const reply = post.replies
console.log(reply);
res.render('pages/showTweet.ejs',{req,replies:reply,tweet:post});
} catch (error) {
console.log(error);
return res.status(500).send("Internal Server Error");
}
})
//comment
app.post("/v/:videoId", async (req, res) => {
try {
const { content, parent } = req.body;
const videoId = req.params.videoId;
const newComment = new Comment({
content,
owner: req.user._id,
video: videoId,
parent: parent || null,
});
await newComment.save();
res.redirect(`back`);
} catch (error) {
res.status(500).send(error.message);
}
});
app.delete("/comments/:id", async (req, res) => {
try {
const commentId = req.params.id;
const comment = await Comment.findById(commentId);
if (!comment) {
return res.status(404).json({ message: "Comment not found" });
}
// Update child comments to set their parent to null
await Comment.updateMany(
{ parent: new mongoose.Types.ObjectId(commentId) }, // Use mongoose.Types.ObjectId to convert commentId correctly
{ $set: { parent: null } }
);
// Delete the comment itself
await Comment.deleteOne({ _id: commentId });
res.status(200).json({ message: "Comment deleted successfully" });
} catch (error) {
console.error("Error deleting comment:", error);
res.status(500).json({ message: "Server error" });
}
});
//subcribe
app.get("/s/:channelId", ensureAuthenticated, async (req, res) => {
const { channelId } = req.params;
console.log(channelId, "channelId");
const subscriberId = channelId;
const user = await User.findById(subscriberId);
const aggregate = [
{
$match: {
subscriber: subscriberId,
},
},
{
$group: {
_id: null,
totalCount: { $sum: 1 },
},
},
];
const subscribedList = await Subscription.aggregate(aggregate);
console.log(subscribedList, "subscribedList");
});
app.post("/s/:channelId", ensureAuthenticated, async (req, res) => {
try {
const { channelId } = req.params;
const userId = req.user._id;
const channel = await User.findById(channelId);
if (!channel) {
return res
.status(404)
.json({ success: false, message: "Channel not found" });
}
const existingSubscription = await Subscription.findOne({
subscriber: userId,
channel: channelId,
});
if (existingSubscription) {
await Subscription.findByIdAndDelete(existingSubscription._id);
console.log("Unsubscribed successfully");
return res.redirect(`/user/${userId}/dashboard/${channel.username}`)
} else {
await Subscription.create({
subscriber: userId,
channel: channelId,
});
console.log("Subscribed successfully");
return res.redirect(`/user/${userId}/dashboard/${channel.username}`)
}
} catch (error) {
console.error(error);
res.status(500).json({ success: false, message: "Internal Server Error" });
}
});
// Helper function to get subscriber count
async function getSubscriberCount(channelId) {
const aggregate = [
{ $match: { channel: channelId } },
{ $group: { _id: null, totalCount: { $sum: 1 } } },
];
const result = await Subscription.aggregate(aggregate);
return result.length > 0 ? result[0].totalCount : 0;
}
app.get("/user/:id/subscribed", ensureAuthenticated, async (req, res) => {
try {
const { id } = req.params;
const subscriptions = await Subscription.find({ subscriber: id }).populate(
"channel"
);
const subscribedChannels = subscriptions.map(
(subscription) => subscription.channel
);
const subscribedChannelIds = subscribedChannels.map(