phanquocdat123 commited on
Commit
5b4a85a
·
verified ·
1 Parent(s): fe6f745

Update services/facebookService.js

Browse files
Files changed (1) hide show
  1. services/facebookService.js +40 -34
services/facebookService.js CHANGED
@@ -1,19 +1,12 @@
1
  // services/facebookService.js
2
- const https = require('https');
3
  const axios = require('axios');
4
 
5
- // 🎯 DÙNG AXIOS + CUSTOM HTTPS AGENT ĐỂ BỎ QUA SSL FILTER CỦA HUGGING FACE
6
- const httpsAgent = new https.Agent({
7
- rejectUnauthorized: false,
8
- secureOptions: require('crypto').constants.SSL_OP_LEGACY_SERVER_CONNECT,
9
- minVersion: 'TLSv1', // Cho phép TLS version thấp hơn
10
- ciphers: 'ALL', // Cho phép tất cả cipher suites
11
- });
12
-
13
- const axiosInstance = axios.create({
14
- httpsAgent: httpsAgent,
15
- timeout: 15000,
16
- });
17
 
18
  /**
19
  * Hàm làm sạch văn bản: Xóa HTML rác và các tag lệnh ẩn
@@ -104,17 +97,35 @@ function formatMessage(text, psid) {
104
  }
105
 
106
  /**
107
- * Hàm gửi request đến Facebook API dùng axios (tránh lỗi SSL của node-fetch)
 
108
  */
109
- async function sendToFacebook(fbUrl, body) {
110
  try {
111
- const response = await axiosInstance.post(fbUrl, body, {
112
- headers: { 'Content-Type': 'application/json' }
113
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  if (response.data && response.data.error) {
115
  console.error("❌ [FB API] Lỗi từ Facebook:", JSON.stringify(response.data.error));
116
  }
117
  return response.data;
 
118
  } catch (err) {
119
  const errMsg = err.response ? JSON.stringify(err.response.data) : err.message;
120
  console.error("❌ [FB API] Gửi thất bại:", errMsg);
@@ -142,7 +153,6 @@ async function sendResponse(senderPsid, responseText) {
142
  const currentUrl = imageUrls[i];
143
  const currentBlock = blocks[i] || "";
144
 
145
- // Khớp mã sản phẩm thông minh
146
  const codeMatch =
147
  currentBlock.match(/\*\*Mã:\s*([^*\[\n]+)\*\*/i) ||
148
  currentBlock.match(/Mã\s*(?:sản phẩm)?:\s*([^\n\[|-]+)/i) ||
@@ -176,37 +186,33 @@ async function sendResponse(senderPsid, responseText) {
176
  }
177
  }
178
 
179
- // Gửi Carousel
180
  if (elements.length > 0) {
181
  await sendToFacebook(fbUrl, {
182
  recipient: { id: senderPsid },
183
  message: {
184
  attachment: {
185
  type: "template",
186
- payload: {
187
- template_type: "generic",
188
- elements: elements
189
- }
190
  }
191
  }
192
  });
193
  }
194
 
195
- // Gửi text hướng dẫn ở cuối Carousel
196
  const lines = responseText.split('\n');
197
- const bottomTextLines = lines.filter(line =>
198
- !line.includes('http') &&
199
- !line.toLowerCase().includes('mã:') &&
200
- !line.toLowerCase().includes('giá:') &&
201
- !line.toLowerCase().includes('action_add')
 
 
202
  );
203
 
204
- const bottomText = cleanTextContent(bottomTextLines.join('\n').trim());
205
  if (bottomText) {
206
- const formattedBottom = formatMessage(bottomText, senderPsid);
207
  await sendToFacebook(fbUrl, {
208
  recipient: { id: senderPsid },
209
- message: formattedBottom
210
  });
211
  }
212
 
@@ -235,7 +241,7 @@ async function sendResponse(senderPsid, responseText) {
235
  }
236
  }
237
 
238
- // Gửi tin nhắn text thông thường
239
  if (formatted && (formatted.text || formatted.attachment)) {
240
  await sendToFacebook(fbUrl, {
241
  recipient: { id: senderPsid },
 
1
  // services/facebookService.js
 
2
  const axios = require('axios');
3
 
4
+ // 🎯 RELAY QUA CLOUDFLARE WORKER ĐỂ TRÁNH BỊ HUGGING FACE BLOCK
5
+ // Sau khi deploy Cloudflare Worker, set biến môi trường:
6
+ // CF_RELAY_URL = https://fb-relay.YOUR_NAME.workers.dev
7
+ // CF_RELAY_SECRET = (chuỗi bí mật bạn tự đặt, ví dụ: "huongkid2024")
8
+ const CF_RELAY_URL = process.env.CF_RELAY_URL;
9
+ const CF_RELAY_SECRET = process.env.CF_RELAY_SECRET;
 
 
 
 
 
 
10
 
11
  /**
12
  * Hàm làm sạch văn bản: Xóa HTML rác và các tag lệnh ẩn
 
97
  }
98
 
99
  /**
100
+ * Gửi tới Facebook API — qua Cloudflare Worker relay nếu có cấu hình,
101
+ * fallback gọi thẳng nếu không (cho môi trường local dev)
102
  */
103
+ async function sendToFacebook(fbUrl, payload) {
104
  try {
105
+ let response;
106
+
107
+ if (CF_RELAY_URL && CF_RELAY_SECRET) {
108
+ // 🌐 QUA CLOUDFLARE WORKER (dùng trên Hugging Face)
109
+ response = await axios.post(CF_RELAY_URL, { fbUrl, payload }, {
110
+ headers: {
111
+ 'Content-Type': 'application/json',
112
+ 'X-Relay-Secret': CF_RELAY_SECRET
113
+ },
114
+ timeout: 20000
115
+ });
116
+ } else {
117
+ // 💻 GỌI THẲNG (dùng khi dev local)
118
+ response = await axios.post(fbUrl, payload, {
119
+ headers: { 'Content-Type': 'application/json' },
120
+ timeout: 15000
121
+ });
122
+ }
123
+
124
  if (response.data && response.data.error) {
125
  console.error("❌ [FB API] Lỗi từ Facebook:", JSON.stringify(response.data.error));
126
  }
127
  return response.data;
128
+
129
  } catch (err) {
130
  const errMsg = err.response ? JSON.stringify(err.response.data) : err.message;
131
  console.error("❌ [FB API] Gửi thất bại:", errMsg);
 
153
  const currentUrl = imageUrls[i];
154
  const currentBlock = blocks[i] || "";
155
 
 
156
  const codeMatch =
157
  currentBlock.match(/\*\*Mã:\s*([^*\[\n]+)\*\*/i) ||
158
  currentBlock.match(/Mã\s*(?:sản phẩm)?:\s*([^\n\[|-]+)/i) ||
 
186
  }
187
  }
188
 
 
189
  if (elements.length > 0) {
190
  await sendToFacebook(fbUrl, {
191
  recipient: { id: senderPsid },
192
  message: {
193
  attachment: {
194
  type: "template",
195
+ payload: { template_type: "generic", elements }
 
 
 
196
  }
197
  }
198
  });
199
  }
200
 
201
+ // Gửi text hướng dẫn ở cuối
202
  const lines = responseText.split('\n');
203
+ const bottomText = cleanTextContent(
204
+ lines.filter(line =>
205
+ !line.includes('http') &&
206
+ !line.toLowerCase().includes('mã:') &&
207
+ !line.toLowerCase().includes('giá:') &&
208
+ !line.toLowerCase().includes('action_add')
209
+ ).join('\n').trim()
210
  );
211
 
 
212
  if (bottomText) {
 
213
  await sendToFacebook(fbUrl, {
214
  recipient: { id: senderPsid },
215
+ message: formatMessage(bottomText, senderPsid)
216
  });
217
  }
218
 
 
241
  }
242
  }
243
 
244
+ // Gửi tin nhắn text
245
  if (formatted && (formatted.text || formatted.attachment)) {
246
  await sendToFacebook(fbUrl, {
247
  recipient: { id: senderPsid },