-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscriptss.js
288 lines (242 loc) · 12.3 KB
/
scriptss.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
// Load more replies when 'View More' is clicked
function loadMoreReplies(doubtId, replies, repliesContainer, viewMoreBtn) {
// Hide the current "View More" button
viewMoreBtn.style.display = 'none';
// Load the next 5 replies
const nextReplies = replies.slice(lastLoadedIndex + 2, lastLoadedIndex + 7);
nextReplies.forEach(reply => {
const mostVotedClass = reply.votes >= 3 ? 'most-voted' : '';
const replyElement = document.createElement('div');
replyElement.classList.add('reply');
replyElement.innerHTML = `
<strong>${reply.userName}</strong> <em>${new Date(reply.timestamp).toLocaleString()}</em>
<p>${reply.content}</p>
${
auth.currentUser && auth.currentUser.email === reply.userEmail
? `<button class="edit-btn" onclick="editReply('${doubtId}', '${reply.id}')">Edit</button>`
: '' // Only show the edit button if the logged-in user is the one who posted the reply
}
<button class="vote-btn" onclick="voteReply('${doubtId}', '${reply.id}', 'up')"><i class="fas fa-thumbs-up"></i></button>
<button class="vote-btn" onclick="voteReply('${doubtId}', '${reply.id}', 'down')"><i class="fas fa-thumbs-down"></i></button>
<span class="vote-count">${reply.votes}</span>
`;
if (mostVotedClass) {
replyElement.classList.add(mostVotedClass);
}
repliesContainer.appendChild(replyElement);
});
// Update the lastLoadedIndex
lastLoadedIndex += 5;
// Check if there are more replies to load
if (lastLoadedIndex + 2 < replies.length) {
// Create a new "View More" button
const newViewMoreBtn = document.createElement('button');
newViewMoreBtn.classList.add('view-more-btn');
newViewMoreBtn.innerText = 'View More';
newViewMoreBtn.onclick = () => loadMoreReplies(doubtId, replies, repliesContainer, newViewMoreBtn);
repliesContainer.appendChild(newViewMoreBtn);
}
}
// Submit a reply
function submitReply(doubtId) {
const replyText = document.getElementById(`replyText-${doubtId}`).value.trim();
if (replyText) {
if (auth.currentUser) {
const user = auth.currentUser;
let userName = user.displayName || "Replier"; // Get replier's name
// Check if the user's email is '[email protected]' and add the verified icon
if (user.email === '[email protected]') {
userName = `${userName} <i class="fas fa-check-circle" style="color: blue;"></i>`; // Blue checkmark for verified user
}
const timestamp = new Date().toISOString();
const replyData = {
content: replyText,
userName, // Use the modified user name with the checkmark if necessary
userEmail: user.email, // Save the user's email along with the reply
timestamp,
votes: 0
};
// Log values for debugging
console.log("Submitting reply for doubtId:", doubtId);
console.log("Reply data:", replyData);
// Ensure Firebase path is correct
const newReplyKey = database.ref('replies/' + doubtId).push().key;
console.log("New reply key:", newReplyKey); // Log the new key for the reply
// Save reply to Firebase
database.ref('replies/' + doubtId + '/' + newReplyKey).set(replyData).then(() => {
console.log("Reply saved successfully!");
loadReplies(doubtId); // Reload replies to display the new one
document.getElementById(`replyText-${doubtId}`).value = ''; // Clear the reply input
}).catch(error => {
console.error('Error saving the reply:', error.message); // Log error message
alert('Error saving the reply: ' + error.message); // Handle any errors while saving the reply
});
} else {
showPopup(); // Prompt user to sign up or log in if they aren't logged in
}
} else {
alert("Please type an answer before submitting.");
}
}
// Vote for a post
function votePost(doubtId, voteType) {
if (auth.currentUser) {
const userId = auth.currentUser.uid;
// Check if user has already voted
database.ref('votes/posts/' + doubtId + '/' + userId).once('value').then(snapshot => {
if (!snapshot.exists()) {
const newVoteValue = voteType === 'up' ? 1 : -1;
database.ref('votes/posts/' + doubtId + '/' + userId).set(newVoteValue);
// Update the vote count for the post
updatePostVotes(doubtId, voteType);
} else {
alert("You can vote only once!");
}
});
} else {
alert("Please log in to vote.");
}
}
// Update votes for a post
function updatePostVotes(doubtId, voteType) {
let change = voteType === 'up' ? 1 : -1;
database.ref('doubts/' + doubtId + '/votes').transaction(currentVotes => {
return (currentVotes || 0) + change;
}).then(() => {
loadDoubts(); // Reload the doubts after updating the vote
});
}
// Vote for a reply
function voteReply(doubtId, replyId, voteType) {
if (auth.currentUser) {
const userId = auth.currentUser.uid;
// Check if user has already voted
database.ref('votes/replies/' + doubtId + '/' + replyId + '/' + userId).once('value').then(snapshot => {
if (!snapshot.exists()) {
const newVoteValue = voteType === 'up' ? 1 : -1;
database.ref('votes/replies/' + doubtId + '/' + replyId + '/' + userId).set(newVoteValue);
// Update the vote count for the reply
updateReplyVotes(doubtId, replyId, voteType);
} else {
alert("You can vote only once!");
}
});
} else {
alert("Please log in to vote.");
}
}
// Update votes for a reply
function updateReplyVotes(doubtId, replyId, voteType) {
let change = voteType === 'up' ? 1 : -1;
database.ref('replies/' + doubtId + '/' + replyId + '/votes').transaction(currentVotes => {
return (currentVotes || 0) + change;
}).then(() => {
loadReplies(doubtId); // Reload the replies after updating the vote
});
}
// Edit post
function editPost(doubtId) {
const doubtRef = database.ref('doubts/' + doubtId);
doubtRef.once('value').then(snapshot => {
const currentContent = snapshot.val().content;
const newContent = prompt("Edit your post:", currentContent); // Pre-load current content into the prompt
if (newContent !== null && newContent !== currentContent) {
doubtRef.update({ content: newContent }).then(() => {
loadDoubts(); // Reload doubts after editing
});
}
});
}
// Edit reply - ensure only the original poster can edit
function editReply(doubtId, replyId) {
const replyRef = database.ref('replies/' + doubtId + '/' + replyId);
replyRef.once('value').then(snapshot => {
const replyData = snapshot.val();
if (auth.currentUser && auth.currentUser.email === replyData.userEmail) {
const currentContent = replyData.content;
const newContent = prompt("Edit your reply:", currentContent); // Pre-load current content into the prompt
if (newContent !== null && newContent !== currentContent) {
replyRef.update({ content: newContent }).then(() => {
loadReplies(doubtId); // Reload replies after editing
});
}
} else {
alert("You can only edit your own replies.");
}
});
}
// Function to fetch replies from the last 48 hours based on user's email
function fetchUserNotifications() {
if (!auth.currentUser) return; // Don't fetch if user isn't logged in
const userEmail = auth.currentUser.email;
const notificationsContainer = document.getElementById('notificationsDropdown');
const notificationBell = document.getElementById('notificationBell');
notificationsContainer.innerHTML = '<p>Loading...</p>'; // Show loading state
const twoDaysAgo = Date.now() - (48 * 60 * 60 * 1000); // Get timestamp 48 hours ago
database.ref('doubts').orderByChild('userEmail').equalTo(userEmail).once('value')
.then(snapshot => {
if (!snapshot.exists()) {
notificationsContainer.innerHTML = '<p>No recent replies.</p>';
notificationBell.classList.remove('new-notification'); // Remove red dot
return;
}
let repliesToShow = [];
let promises = [];
Object.entries(snapshot.val()).forEach(([doubtId, doubtData]) => {
let postContent = doubtData.content.substring(0, 50) + "..."; // Get first 50 characters of the post
let promise = database.ref(`replies/${doubtId}`)
.orderByChild('timestamp')
.startAt(twoDaysAgo)
.once('value')
.then(repliesSnapshot => {
if (repliesSnapshot.exists()) {
repliesSnapshot.forEach(replySnap => {
const reply = replySnap.val();
let replyContent = reply.content.split(' ').slice(0, 10).join(' ') + '...'; // Truncate reply content to 10 words
repliesToShow.push({
doubtId,
postContent, // Shortened post content
content: replyContent, // Truncated reply content
userName: reply.userName,
timestamp: reply.timestamp // Ensure the timestamp is being saved correctly
});
});
}
});
promises.push(promise);
});
Promise.all(promises).then(() => {
if (repliesToShow.length === 0) {
notificationsContainer.innerHTML = '<p>No recent replies.</p>';
notificationBell.classList.remove('new-notification'); // Remove red dot
return;
}
// Sort replies by most recent first (newest at the top)
repliesToShow.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
// Display notifications (newest at the top)
notificationsContainer.innerHTML = repliesToShow.map(reply => `
<div class="notification-item">
<strong>${reply.userName}</strong> replied to your post
<em>(${reply.postContent})</em>: ${reply.content}
<p><em>${new Date(reply.timestamp).toLocaleString()}</em></p>
</div>
`).join('');
notificationBell.classList.add('new-notification'); // Add red dot on bell
});
})
.catch(error => {
console.error("Error fetching notifications:", error);
notificationsContainer.innerHTML = '<p>Error loading notifications.</p>';
});
}
// Auto-update notifications every 30 seconds
setInterval(fetchUserNotifications, 30000);
// Fetch notifications when page loads
fetchUserNotifications();
// Function to toggle notifications dropdown
function toggleNotifications() {
const dropdown = document.getElementById('notificationsDropdown');
dropdown.style.display = (dropdown.style.display === 'block') ? 'none' : 'block';
// Remove the red dot after opening notifications
document.getElementById('notificationBell').classList.remove('new-notification');
}