-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
187 lines (155 loc) · 6.37 KB
/
main.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
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.17.1/firebase-app.js";
import { getFirestore, doc, setDoc, addDoc, collection, onSnapshot, serverTimestamp, query, orderBy, getDoc } from "https://www.gstatic.com/firebasejs/9.17.1/firebase-firestore.js";
// Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyDMGCzjVLZUVZHCCxBDql5npVz_wcKxEX4",
authDomain: "chat-room-eda59.firebaseapp.com",
projectId: "chat-room-eda59",
storageBucket: "chat-room-eda59.appspot.com",
messagingSenderId: "1063922969354",
appId: "1:1063922969354:web:c1693925c907a1681368f3"
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
// DOM elements
const usernameInput = document.getElementById("username");
const roomCodeInput = document.getElementById("room-code");
const createRoomBtn = document.getElementById("create-room-btn");
const joinRoomBtn = document.getElementById("join-room-btn");
const chatSection = document.getElementById("chat-section");
const authSection = document.getElementById("auth-section");
const chatBox = document.getElementById("chat-box");
const messageInput = document.getElementById("message-input");
const sendBtn = document.getElementById("send-btn");
const leaveRoomBtn = document.getElementById("leave-room-btn");
const roomTitle = document.getElementById("room-id");
let roomId;
let username;
// Perspective API key
const perspectiveApiKey = 'AIzaSyDQpDRlAG4toBVY2vzV1blqwx9VzC1U0HA';
// Function to check for profanity using Perspective API
async function containsProfanity(message) {
const url = `https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze?key=${perspectiveApiKey}`;
const data = {
comment: { text: message },
languages: ["en"],
requestedAttributes: {
TOXICITY: {},
SEVERE_TOXICITY: {},
INSULT: {},
PROFANITY: {},
THREAT: {}
}
};
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
});
const result = await response.json();
const scores = result.attributeScores;
return (
scores.TOXICITY.summaryScore.value >= 0.4 ||
scores.SEVERE_TOXICITY.summaryScore.value >= 0.4 ||
scores.INSULT.summaryScore.value >= 0.4 ||
scores.PROFANITY.summaryScore.value >= 0.4 ||
scores.THREAT.summaryScore.value >= 0.4
);
}
// Toast notification
function showToast(message) {
const toast = document.getElementById("toast");
toast.textContent = message;
toast.classList.add("show");
setTimeout(() => toast.classList.remove("show"), 6000);
}
// Show chat section
function showChatSection() {
authSection.style.display = "none";
chatSection.style.display = "block";
}
function clearChatBox() {
chatBox.innerHTML = "";
}
// Listen for new messages in the Firestore database
function listenForMessages() {
const q = query(collection(db, "rooms", roomId, "messages"), orderBy("timestamp"));
onSnapshot(q, (snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === "added") {
const { username, text } = change.doc.data();
const msgEl = document.createElement("p");
const usernameSpan = document.createElement("span");
usernameSpan.style.color = "#1f51ff";
usernameSpan.textContent = username;
usernameSpan.style.fontWeight = "bold";
const messageText = document.createTextNode(`: ${text}`);
msgEl.appendChild(usernameSpan);
msgEl.appendChild(messageText);
chatBox.appendChild(msgEl);
}
});
chatBox.scrollTop = chatBox.scrollHeight;
});
}
// Create a new room
createRoomBtn.addEventListener("click", async () => {
username = usernameInput.value.trim();
if (!username) return showToast("Please enter a username.");
roomId = Math.random().toString(36).substring(2, 8);
await setDoc(doc(db, "rooms", roomId), {});
roomTitle.textContent = `${roomId}`;
showChatSection();
listenForMessages();
});
// Join an existing room
joinRoomBtn.addEventListener("click", async () => {
username = usernameInput.value.trim();
roomId = roomCodeInput.value.trim();
if (!username || !roomId) return showToast("Please enter both a username and room code.");
const roomDoc = await getDoc(doc(db, "rooms", roomId));
if (!roomDoc.exists()) return showToast("Room not found.");
roomTitle.textContent = `${roomId}`;
showChatSection();
listenForMessages();
});
// Send a message
sendBtn.addEventListener("click", sendMessage);
messageInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") sendMessage();
});
async function sendMessage() {
let message = messageInput.value.trim();
if (!message) return;
// Check if the message is longer than 100 characters
if (message.length > 100) {
showToast("Your message is too long! Maximum length is 100 characters.");
return;
}
// Check for profanity using Perspective API
if (await containsProfanity(message)) {
showToast("Your message was flagged by our systems and wasn't sent. Try again!");
return;
}
// Send message to Firestore
await addDoc(collection(db, "rooms", roomId, "messages"), {
username,
text: message,
timestamp: serverTimestamp()
});
messageInput.value = ""; // Clear the input field
}
// Leave the room and reload the page
leaveRoomBtn.addEventListener("click", () => {
location.reload();
});
const roomCodeElement = document.getElementById("room-id");
roomCodeElement.addEventListener("click", () => {
const roomCode = roomCodeElement.textContent.trim();
console.log("Room Code: ", roomCode);
navigator.clipboard.writeText(roomCode)
.then(() => showToast("Room code copied to clipboard!"))
.catch((error) => console.error("Failed to copy text:", error));
});