-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
304 lines (272 loc) · 7.89 KB
/
app.js
File metadata and controls
304 lines (272 loc) · 7.89 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
const clientId = "your_client_id";
const organizationId = "your_organization_id";
let customerToken = null;
let customerId = null;
let currentChatId = null;
let currentThreadId = null;
let isChatActive = false;
let lastEventIds = new Set();
let pollingIntervalId = null;
// ------------------------
// Authorize Customer
// ------------------------
async function authorizeCustomer() {
const url = "https://accounts.livechat.com/v2/customer/token";
const payload = {
grant_type: "cookie",
client_id: clientId,
organization_id: organizationId,
response_type: "token",
redirect_uri: window.location.origin,
};
try {
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify(payload),
});
if (!response.ok) throw new Error(`Auth failed: ${response.status}`);
const data = await response.json();
customerToken = data.access_token;
customerId = data.entity_id;
console.log("✅ Customer authorized:", customerId);
await listChats();
if (customerToken) startPolling();
} catch (error) {
console.error("❌ Authorization error:", error);
}
}
// ------------------------
// List Existing Chats
// ------------------------
async function listChats() {
try {
const res = await fetch(
`https://api.livechatinc.com/v3.5/customer/action/list_chats?organization_id=${organizationId}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${customerToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({}),
}
);
const data = await res.json();
const chat = data.chats_summary?.[0];
if (chat) {
currentChatId = chat.id;
currentThreadId = chat.last_thread_id;
isChatActive = chat.active;
console.log("💬 Existing chat:", currentChatId, "Active:", isChatActive);
} else {
currentChatId = null;
currentThreadId = null;
isChatActive = false;
console.log("💬 No existing chat.");
updateCloseButtonState();
}
} catch (err) {
console.error("Failed to list chats:", err);
}
}
// ------------------------
// Start Chat
// ------------------------
async function startChat(initialMessage) {
const res = await fetch(
`https://api.livechatinc.com/v3.5/customer/action/start_chat?organization_id=${organizationId}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${customerToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
chat: {
thread: {
events: [
{
type: "message",
text: initialMessage,
recipients: "all",
},
],
},
},
}),
}
);
const data = await res.json();
currentChatId = data.chat_id;
currentThreadId = data.thread_id;
isChatActive = true;
lastEventIds.add(data.event_id); // ✅ prevent polling dupes
appendMessageToChat("You", initialMessage);
console.log("✅ Chat started:", currentChatId);
isChatActive = true;
updateCloseButtonState();
}
// ------------------------
// Resume Chat
// ------------------------
async function resumeChat() {
const res = await fetch(
`https://api.livechatinc.com/v3.5/customer/action/resume_chat?organization_id=${organizationId}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${customerToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ chat: { id: currentChatId } }),
}
);
const data = await res.json();
currentThreadId = data.thread_id;
isChatActive = true;
console.log("🔁 Chat resumed:", currentChatId);
isChatActive = true;
updateCloseButtonState();
}
// ------------------------
// Send Message
// ------------------------
async function sendMessage(messageText) {
if (!customerToken) return;
if (!currentChatId) {
await startChat(messageText);
return;
}
if (!isChatActive) {
await resumeChat();
}
const res = await fetch(
`https://api.livechatinc.com/v3.5/customer/action/send_event?organization_id=${organizationId}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${customerToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
chat_id: currentChatId,
event: {
type: "message",
text: messageText,
recipients: "all",
},
}),
}
);
const data = await res.json();
lastEventIds.add(data.event_id); // ✅ track for deduping
appendMessageToChat("You", messageText);
}
// ------------------------
// Deactivate Chat
// ------------------------
async function deactivateChat() {
if (!currentChatId) return;
try {
const res = await fetch(
`https://api.livechatinc.com/v3.5/customer/action/deactivate_chat?organization_id=${organizationId}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${customerToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ id: currentChatId }),
}
);
if (res.ok) {
isChatActive = false;
appendMessageToChat("System", "The chat has been closed.");
console.log("🚫 Chat deactivated:", currentChatId);
stopPolling();
updateCloseButtonState();
}
} catch (e) {
console.error("Deactivate failed:", e);
}
}
// ------------------------
// Polling Logic
// ------------------------
function startPolling() {
if (pollingIntervalId) clearInterval(pollingIntervalId);
pollingIntervalId = setInterval(pollForMessages, 3000);
}
function stopPolling() {
if (pollingIntervalId) clearInterval(pollingIntervalId);
pollingIntervalId = null;
}
async function pollForMessages() {
if (!customerToken || !currentChatId || !currentThreadId) return;
try {
const res = await fetch(
`https://api.livechatinc.com/v3.5/customer/action/list_threads?organization_id=${organizationId}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${customerToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ chat_id: currentChatId }),
}
);
const data = await res.json();
const thread = data.threads?.find((t) => t.id === currentThreadId);
if (!thread?.events) return;
for (const event of thread.events) {
if (event.type === "message" && !lastEventIds.has(event.id)) {
const sender = event.author_id === customerId ? "You" : "Agent";
appendMessageToChat(sender, event.text);
lastEventIds.add(event.id);
}
}
} catch (e) {
console.error("Polling error:", e);
}
}
// ------------------------
// UI Helpers
// ------------------------
function appendMessageToChat(sender, text) {
const chatBox = document.getElementById("chat-box");
const div = document.createElement("div");
div.className = `chat-message ${sender.toLowerCase()}`;
div.textContent = `${sender}: ${text}`;
chatBox.appendChild(div);
}
function updateCloseButtonState() {
const btn = document.getElementById("close-btn");
if (isChatActive) {
btn.disabled = false;
btn.style.opacity = "1";
btn.style.cursor = "pointer";
} else {
btn.disabled = true;
btn.style.opacity = "0.5";
btn.style.cursor = "not-allowed";
}
}
// ------------------------
// DOM Ready
// ------------------------
window.addEventListener("DOMContentLoaded", async () => {
await authorizeCustomer();
document.getElementById("send-btn").addEventListener("click", async () => {
const input = document.getElementById("message-input");
const text = input.value.trim();
if (text) {
await sendMessage(text);
input.value = "";
}
});
document.getElementById("close-btn").addEventListener("click", async () => {
await deactivateChat();
});
});