File size: 12,315 Bytes
b634468
fe6f745
b634468
 
 
 
 
 
 
 
 
 
4d0db28
5b4a85a
 
 
0df802f
 
 
 
 
 
70d0a2d
 
0df802f
 
 
 
70d0a2d
0df802f
 
 
70d0a2d
0df802f
70d0a2d
0df802f
 
 
 
 
 
 
 
 
 
5985ec8
0df802f
 
 
 
 
 
 
 
70d0a2d
0df802f
 
70d0a2d
0df802f
 
70d0a2d
 
0df802f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70d0a2d
f004e25
70d0a2d
f004e25
fe6f745
f004e25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b4a85a
f004e25
 
 
fbb64e4
 
 
 
 
 
 
 
f004e25
5b4a85a
 
 
 
b634468
fbb64e4
5b4a85a
f004e25
 
 
 
 
fbb64e4
 
 
 
 
f004e25
fbb64e4
 
 
70d0a2d
 
 
0df802f
6235346
0df802f
 
 
 
 
5c58a45
70d0a2d
0df802f
 
70d0a2d
0df802f
4d0db28
0df802f
 
 
 
70d0a2d
4d0db28
70d0a2d
 
61e2c02
f004e25
 
61e2c02
 
 
 
 
 
 
 
0df802f
4d0db28
 
70d0a2d
 
 
88eae92
70d0a2d
 
 
0df802f
 
 
 
 
 
 
70d0a2d
 
 
 
 
0df802f
 
 
 
 
b634468
f004e25
70d0a2d
 
 
 
 
5b4a85a
0df802f
70d0a2d
f004e25
0df802f
 
b634468
0df802f
5b4a85a
 
 
 
 
 
 
0df802f
 
 
70d0a2d
 
5b4a85a
f004e25
0df802f
70d0a2d
 
0df802f
 
69eb11c
0df802f
 
70d0a2d
 
0df802f
 
 
70d0a2d
 
 
 
 
 
5c58a45
70d0a2d
f004e25
0df802f
 
 
 
 
b634468
0df802f
70d0a2d
 
 
f004e25
0df802f
 
70d0a2d
0df802f
b634468
0df802f
 
 
 
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
// C:\Users\Hi\OneDrive\Desktop\TCCS\Chatbot\chatbot_server\services\facebookService.js
const axios = require('axios');
const https = require('https');

// 🎯 CHIẾN THUẬT CHỐNG TIMEOUT: Khởi tạo tác nhân HTTPS giữ kết nối sống (Keep-Alive)
// Giúp tái sử dụng socket cũ, đẩy tốc độ truyền tải Album ảnh lên gấp 3 lần và tránh nghẽn mạch.
const httpsAgent = new https.Agent({
    rejectUnauthorized: false,
    keepAlive: true, 
    keepAliveMsecs: 30000, // Giữ socket mở trong 30 giây để phục vụ lượt chat tiếp theo
    secureOptions: require('crypto').constants.SSL_OP_LEGACY_SERVER_CONNECT
});

// 🎯 RELAY QUA CLOUDFLARE WORKER ĐỂ TRÁNH BỊ HUGGING FACE BLOCK
const CF_RELAY_URL    = process.env.CF_RELAY_URL;
const CF_RELAY_SECRET = process.env.CF_RELAY_SECRET;

/**
 * Hàm làm sạch văn bản: Xóa HTML rác và các tag lệnh ẩn
 */
function cleanTextContent(text) {
    return (text || "")
        .replace(/<[^>]*>/g, "")
        .replace(/\[\[.*?\]\]/g, "")
        .trim();
}

/**
 * Hàm lọc và trích xuất TOÀN BỘ link ảnh có trong tin nhắn
 */
function extractAllImageUrls(text) {
    if (!text) return [];
    const urlRegex = /https?:\/\/[^\s"<>]+(?:\.jpg|\.jpeg|\.png|\.gif|\.webp|thumbnail\?[^\s"<>]+)/gi;
    const matches = text.match(urlRegex);
    return matches ? [...new Set(matches)] : [];
}

/**
 * Hàm phân tích tin nhắn để dựng cấu trúc Facebook (Quick Replies / Webview)
 */
function formatMessage(text, psid) {
    const cleanText = cleanTextContent(text);

    // 1. XỬ LÝ FORM CHỐT ĐƠN WEBVIEW
    if (text.includes("[[SHOW_ORDER_FORM") || text.toUpperCase().includes("ACTION_CONFIRM")) {
        const appUrl = process.env.APP_URL || 'https://phanquocdat123-chatbot-robot-automation.hf.space';
        return {
            attachment: {
                type: "template",
                payload: {
                    template_type: "button",
                    text: cleanText || "Dạ Mẹ nhấn vào nút bên dưới để điền thông tin cho bé nhen! ❤️",
                    buttons: [{
                        type: "web_url",
                        url: `${appUrl}/order-form.html?userId=${psid}`,
                        title: "📝 ĐIỀN THÔNG TIN",
                        webview_height_ratio: "full",
                        messenger_extensions: false
                    }]
                }
            }
        };
    }

    // 2. TỰ ĐỘNG BẮT SĐT
    if (cleanText.toLowerCase().includes("sđt") || cleanText.toLowerCase().includes("số điện thoại")) {
        return {
            text: cleanText,
            quick_replies: [{ content_type: "user_phone_number" }]
        };
    }

    // 3. XỬ LÝ NÚT BẤM [Nhãn|Lệnh] DẠNG QUICK REPLIES
    const buttonRegex = /\[([^\]|]+)\|?([^\]]*)\]/g;
    const matches = [...text.matchAll(buttonRegex)];

    if (matches.length > 0) {
        const isAskingAddress = cleanText.toLowerCase().includes("địa chỉ");
        const quickReplies = matches.map(match => {
            const label = match[1].trim();
            const command = match[2] ? match[2].trim() : label;
            return {
                content_type: "text",
                title: label.substring(0, 20),
                payload: command
            };
        });

        if (isAskingAddress) {
            quickReplies.unshift({
                content_type: "text",
                title: "Mẫu: Tên - SĐT - ĐC",
                payload: "TEMPLATE_ADDRESS"
            });
        }

        return {
            text: cleanText || "Mẹ chọn ở dưới nhen:",
            quick_replies: quickReplies.slice(0, 13)
        };
    }

    return { text: cleanText };
}

/**
 * Hàm phụ trợ: Gọi trực tiếp đến Meta không qua trung gian khi gặp sự cố cứu hộ
 */
async function sendDirectlyToFacebook(fbUrl, payload, timeoutMs) {
    try {
        console.log("💻 [FB API] Đang gọi trực tiếp API Facebook Graph (Luồng cứu hộ)...");
        const response = await axios.post(fbUrl, payload, {
            headers: { 'Content-Type': 'application/json' },
            httpsAgent: httpsAgent,
            timeout: timeoutMs
        });
        if (response.data && response.data.error) {
            console.error("❌ [FB API - Direct] Facebook báo lỗi:", JSON.stringify(response.data.error));
        } else {
            console.log("✅ [FB API - Direct] Luồng cứu hộ gọi trực tiếp thành công!");
        }
        return response.data;
    } catch (directErr) {
        console.error("❌ [FB API] Luồng cứu hộ gọi trực tiếp cũng thất bại:", directErr.message);
        throw directErr;
    }
}

/**
 * Gửi tới Facebook API — tích hợp cơ chế tự động Fallback gọi trực tiếp nếu Relay lỗi/Timeout
 */
/**
 * Gửi tới Facebook API — Phân tách luồng độc lập, bảo vệ hệ thống khỏi nghẽn mạch
 */
async function sendToFacebook(fbUrl, payload, customTimeout = 10000) { 
    // Mặc định cho luồng chính là 10 giây để an toàn cho cả Album nặng
    if (CF_RELAY_URL && CF_RELAY_SECRET) {
        try {
            // 🌐 LUỒNG CHÍNH: CHỈ GỌI QUA CLOUDFLARE WORKER
            const response = await axios.post(CF_RELAY_URL, { fbUrl, payload }, {
                headers: {
                    'Content-Type': 'application/json',
                    'X-Relay-Secret': CF_RELAY_SECRET
                },
                httpsAgent: httpsAgent,
                timeout: customTimeout // Giữ thời gian đợi theo yêu cầu của từng loại tin nhắn
            });
            
            if (response.data && response.data.error) {
                console.error("❌ [FB API - Worker] Facebook báo lỗi:", JSON.stringify(response.data.error));
            }
            return response.data;
        } catch (err) {
            console.warn(`⚠️ [FB API - Worker] Gặp sự cố (${err.message}). KÍCH HOẠT LUỒNG CỨU HỘ GỌI TRỰC TIẾP...`);
            // 🚑 ĐƯỜNG LÙI CỨU HỘ: Chỉ chạy khi luồng Worker ở trên thất bại hoàn toàn
            // Nới rộng hẳn thời gian chờ lên 20 giây để Meta kịp phản hồi dữ liệu cấu trúc
            return await sendDirectlyToFacebook(fbUrl, payload, 20000);
        }
    } else {
        // Nếu môi trường Local không cài Worker -> Đi thẳng trực tiếp ngay từ đầu
        return await sendDirectlyToFacebook(fbUrl, payload, customTimeout);
    }
}

/**
 * Hàm chính thực hiện gửi tin nhắn thông minh
 */
async function sendResponse(senderPsid, responseText) {
    try {
        const accessToken = process.env.FB_PAGE_ACCESS_TOKEN;
        const imageUrls = extractAllImageUrls(responseText);
        const fbUrl = `https://graph.facebook.com/v19.0/me/messages?access_token=${accessToken}`;

        // --- TRƯỜNG HỢP NHIỀU SẢN PHẨM (Dựng Album Carousel) ---
        if (imageUrls.length >= 2) {
            console.log(`📚 [FB Service] Đang cấu trúc Album Carousel cho ${imageUrls.length} sản phẩm...`);

            const blocks = responseText.split(/https?:\/\/[^\s"<>]+/gi);
            const elements = [];

            for (let i = 0; i < imageUrls.length; i++) {
                const currentUrl = imageUrls[i];
                const currentBlock = blocks[i] || "";

                const codeMatch =
                    currentBlock.match(/\*\*Mã:\s*([^*\[\n]+)\*\*/i) ||
                    currentBlock.match(/Mã\s*(?:sản phẩm)?:\s*([^\n\[|:-]+)/i) ||
                    currentBlock.match(/(?:🔹|👉|#)\s*Mã\s*:\s*([A-Z0-9]+)/i) || 
                    currentBlock.match(/\b([A-Z]+[0-9]+)\b/);
                
                let itemCode = "MẪU";
                if (codeMatch) {
                    itemCode = (codeMatch[1] || codeMatch[0]).trim().toUpperCase();
                } else {
                    const backupMatch = currentBlock.match(/([A-Z]+[0-9]+)/i);
                    if (backupMatch) itemCode = backupMatch[1].toUpperCase();
                }

                const nameMatch = currentBlock.match(/(?:👕|👚|🌱|👉|^)\s*([^\n$*|]+)/m);
                let itemName = nameMatch ? nameMatch[1].trim() : "Thời trang cho bé";
                if (itemName.toLowerCase().includes("giá") || itemName.length < 3) {
                    itemName = "Quần áo trẻ em xịn";
                }

                const priceMatch =
                    currentBlock.match(/Giá:\s*\*?([^*|\n]+)\*?/i) ||
                    currentBlock.match(/(\d{1,3}(?:\.\d{3})*\s*(?:k|đ|đồng|vnd))/i);
                const itemPrice = priceMatch ? priceMatch[1].trim() : "Liên hệ shop";

                if (elements.length < 10) {
                    elements.push({
                        title: `Mã: ${itemCode} - ${itemName}`.substring(0, 80),
                        image_url: currentUrl,
                        subtitle: `💰 Giá: ${itemPrice}\nMẹ bấm nút bên dưới để chọn nhen!`.substring(0, 80),
                        buttons: [{
                            type: "postback",
                            title: `🛍️ CHỌN MẪU ${itemCode}`,
                            payload: `[ACTION_ADD:${itemCode}]`
                        }]
                    });
                }
            }

            if (elements.length > 0) {
                console.log("📤 [FB Service] Đang bắn Album Carousel sang Meta...");
                // Nới timeout lên 20 giây cho gói Album nặng hình ảnh
                await sendToFacebook(fbUrl, {
                    recipient: { id: senderPsid },
                    message: {
                        attachment: {
                            type: "template",
                            payload: { template_type: "generic", elements }
                        }
                    }
                }, 20000); 
            }

            // Gửi text hướng dẫn ở cuối Album
            const lines = responseText.split('\n');
            const bottomText = cleanTextContent(
                lines.filter(line =>
                    !line.includes('http') &&
                    !line.toLowerCase().includes('mã:') &&
                    !line.toLowerCase().includes('giá:') &&
                    !line.toLowerCase().includes('action_add')
                ).join('\n').trim()
            );

            if (bottomText) {
                await sendToFacebook(fbUrl, {
                    recipient: { id: senderPsid },
                    message: formatMessage(bottomText, senderPsid)
                }, 6000);
            }

            console.log(`✅ [FB Service] Đã gửi xong Album Carousel cho khách: ${senderPsid}`);
            return;
        }

        // --- TRƯỜNG HỢP THÔNG THƯỜNG (1 ẢNH HOẶC KHÔNG CÓ ẢNH) ---
        const formatted = formatMessage(responseText, senderPsid);

        // Gửi 1 ảnh lẻ
        if (imageUrls.length === 1) {
            console.log(`📸 [FB Service] Gửi 1 ảnh sản phẩm lẻ: ${imageUrls[0]}`);
            try {
                await sendToFacebook(fbUrl, {
                    recipient: { id: senderPsid },
                    message: {
                        attachment: {
                            type: "image",
                            payload: { url: imageUrls[0], is_reusable: true }
                        }
                    }
                }, 8000);
            } catch (imgErr) {
                console.error("⚠️ Lỗi gửi ảnh đơn:", imgErr.message);
            }
        }

        // Gửi tin nhắn text thông thường
        if (formatted && (formatted.text || formatted.attachment)) {
            await sendToFacebook(fbUrl, {
                recipient: { id: senderPsid },
                message: formatted
            }, 6000);
        }

        console.log(`✅ [FB Service] Đã xử lý tin nhắn cho khách: ${senderPsid}`);
    } catch (err) {
        console.error("❌ [FB Service] Lỗi nghiêm trọng tại sendResponse:", err.message);
    }
}

module.exports = { sendResponse };