File size: 19,877 Bytes
57a7575
 
 
5dbc4a4
57a7575
 
5dbc4a4
57a7575
1
2
3
4
5
6
7
8
{
  "id": "3db70fe2-dc0b-488c-ba97-79875c0af2e2",
  "title": "Untitled",
  "content": "\"use strict\";\n\n/**\n * Được Fix Hay Làm Màu Bởi: @gấu lỏ\n * 20/08/2025\n * Kết hợp sendMessage.js và sendTypMqtt.js\n * Tích hợp trạng thái \"đang soạn tin nhắn\"\n */\n\nvar utils = require(\"../utils\");\nvar log = require(\"npmlog\");\nvar bluebird = require(\"bluebird\");\nvar fs = require(\"fs-extra\");\nconst { Readable } = require(\"stream\");\n\nvar allowedProperties = {\n  attachment: true,\n  url: true,\n  sticker: true,\n  emoji: true,\n  emojiSize: true,\n  body: true,\n  mentions: true,\n  location: true,\n};\n\nvar AntiText = \"Your criminal activity was detected while attempting to send an Appstate file\";\nvar Location_Stack;\n\nfunction toReadableStream(any) {\n  if (utils.isReadableStream(any)) return any;\n\n  if (Buffer.isBuffer(any)) {\n    const r = new Readable();\n    r._read = () => {};\n    r.push(any);\n    r.push(null);\n    r.path = \"buffer.bin\";\n    return r;\n  }\n\n  if (typeof any === \"string\") {\n    if (/^https?:\\/\\//i.test(any)) return null;\n    return fs.createReadStream(any);\n  }\n  return null;\n}\n\nfunction isAudioPath(p = \"\") {\n  return [\".mp3\", \".wav\", \".m4a\", \".aac\", \".ogg\", \".flac\", \".opus\"].some(ext => p.toLowerCase().endsWith(ext));\n}\n\nmodule.exports = function (defaultFuncs, api, ctx) {\n  let count_req = 0;\n\n  const MAX_REQ_ID = 2 ** 31 - 1;\n  const TYPING_BEFORE_SEND_MS = 600; // gõ typing 600ms trước khi gửi\n\n  // (Giữ nguyên) Typing indicator nội bộ qua MQTT — vẫn để đây làm Fallback\n  function makeTypingIndicator(typ, threadID, callback) {\n    if (!ctx.mqttClient || !ctx.mqttClient.connected) {\n      if (typeof callback === \"function\") callback(new Error(\"MQTT client not connected\"));\n      return;\n    }\n    threadID = utils.formatID(threadID.toString());\n\n    try {\n      count_req = count_req >= MAX_REQ_ID ? 1 : count_req + 1;\n\n      var wsContent = {\n        app_id: 2220391788200892,\n        payload: JSON.stringify({\n          label: 3,\n          payload: JSON.stringify({\n            thread_key: threadID,\n            is_group_thread: +(threadID.length >= 16),\n            is_typing: +typ,\n            attribution: 0,\n          }),\n          version: 5849951561777440,\n        }),\n        request_id: count_req,\n        type: 4,\n      };\n\n      ctx.mqttClient.publish(\"/ls_req\", JSON.stringify(wsContent), {}, (err) => {\n        if (typeof callback === \"function\") callback(err || null);\n      });\n    } catch (err) {\n      if (typeof callback === \"function\") callback(err);\n    }\n  }\n\n  function uploadAttachment(attachments, callback) {\n    const uploads = [];\n\n    for (let i = 0; i < attachments.length; i++) {\n      const stream = toReadableStream(attachments[i]);\n      if (!stream) continue;\n\n      const form = {\n        upload_1024: stream,\n        // giữ nguyên cấu trúc: audio thì voice_clip=true, còn lại (video, ảnh, file) = false\n        voice_clip: String(isAudioPath(String(stream.path || \"\"))),\n      };\n\n      uploads.push(\n        defaultFuncs\n          .postFormData(\n            \"https://upload.facebook.com/ajax/mercury/upload.php\",\n            ctx.jar,\n            form,\n            {}\n          )\n          .then(utils.parseAndCheckLogin(ctx, defaultFuncs))\n          .then(function (resData) {\n            if (resData?.error) throw resData;\n            if (!resData?.payload?.metadata?.[0]) {\n              throw { error: \"Upload failed: empty metadata\" };\n            }\n            // metadata[0] có thể là {image_id}, {file_id}, {video_id}, {audio_id}\n            return resData.payload.metadata[0];\n          })\n      );\n    }\n\n    if (uploads.length === 0) return callback(null, []);\n\n    bluebird\n      .all(uploads)\n      .then((resData) => callback(null, resData))\n      .catch(function (err) {\n        log.error(\"uploadAttachment\", err);\n        return callback(err);\n      });\n  }\n\n  function getUrl(url, callback) {\n    var form = {\n      image_height: 960,\n      image_width: 960,\n      uri: url,\n    };\n\n    defaultFuncs\n      .post(\"https://www.facebook.com/message_share_attachment/fromURI/\", ctx.jar, form)\n      .then(utils.parseAndCheckLogin(ctx, defaultFuncs))\n      .then(function (resData) {\n        if (resData.error) return callback(resData);\n        if (!resData.payload) return callback({ error: \"Invalid url\" });\n        callback(null, resData.payload.share_data.share_params);\n      })\n      .catch(function (err) {\n        log.error(\"getUrl\", err);\n        return callback(err);\n      });\n  }\n\n  function sendContent(form, threadID, isSingleUser, messageAndOTID, callback) {\n    if (utils.getType(threadID) === \"Array\") {\n      for (var i = 0; i < threadID.length; i++) {\n        form[\"specific_to_list[\" + i + \"]\"] = \"fbid:\" + threadID[i];\n      }\n      form[\"specific_to_list[\" + threadID.length + \"]\"] = \"fbid:\" + ctx.userID;\n      form[\"client_thread_id\"] = \"root:\" + messageAndOTID;\n      log.info(\"sendMessage\", \"Sending message to multiple users: \" + threadID);\n    } else {\n      if (isSingleUser) {\n        form[\"specific_to_list[0]\"] = \"fbid:\" + threadID;\n        form[\"specific_to_list[1]\"] = \"fbid:\" + ctx.userID;\n        form[\"other_user_fbid\"] = threadID;\n      } else {\n        form[\"thread_fbid\"] = threadID;\n      }\n    }\n\n    if (ctx.globalOptions.pageID) {\n      form[\"author\"] = \"fbid:\" + ctx.globalOptions.pageID;\n      form[\"specific_to_list[1]\"] = \"fbid:\" + ctx.globalOptions.pageID;\n      form[\"creator_info[creatorID]\"] = ctx.userID;\n      form[\"creator_info[creatorType]\"] = \"direct_admin\";\n      form[\"creator_info[labelType]\"] = \"sent_message\";\n      form[\"creator_info[pageID]\"] = ctx.globalOptions.pageID;\n      form[\"request_user_id\"] = ctx.globalOptions.pageID;\n      form[\"creator_info[profileURI]\"] = \"https://www.facebook.com/profile.php?id=\" + ctx.userID;\n    }\n\n    if (global.Fca.Require.FastConfig.AntiSendAppState == true) {\n      try {\n        if (Location_Stack != undefined || Location_Stack != null) {\n          let location = Location_Stack.replace(\"Error\", \"\").split(\"\\n\")[7].split(\" \");\n          let format = {\n            Source: location[6].split(\"s:\")[0].replace(\"(\", \"\") + \"s\",\n            Line: location[6].split(\"s:\")[1].replace(\")\", \"\"),\n          };\n          form.body = AntiText + \"\\n- Source: \" + format.Source + \"\\n- Line: \" + format.Line;\n        }\n      } catch (e) {}\n    }\n\n    defaultFuncs\n      .post(\"https://www.facebook.com/messaging/send/\", ctx.jar, form)\n      .then(utils.parseAndCheckLogin(ctx, defaultFuncs))\n      .then(function (resData) {\n        Location_Stack = undefined;\n        if (!resData) return callback({ error: \"Send message failed.\" });\n        if (resData.error) {\n          if (resData.error === 1545012) {\n            log.warn(\n              \"sendMessage\",\n              \"Got error 1545012. This might mean that you're not part of the conversation \" + threadID\n            );\n          }\n          return callback(resData);\n        }\n\n        var messageInfo = resData.payload.actions.reduce(function (p, v) {\n          return (\n            {\n              threadID: v.thread_fbid,\n              messageID: v.message_id,\n              timestamp: v.timestamp,\n            } || p\n          );\n        }, null);\n        return callback(null, messageInfo);\n      })\n      .catch(function (err) {\n        log.error(\"sendMessage\", err);\n        if (utils.getType(err) == \"Object\" && err.error === \"Not logged in.\") {\n          ctx.loggedIn = false;\n        }\n        return callback(err, null);\n      });\n  }\n\n  function decideIsSingleUser(threadID, isGroup) {\n    if (Array.isArray(threadID)) return false;\n    if (isGroup !== null) return !isGroup;\n\n    if (global.Fca?.Data?.event && typeof global.Fca.Data.event.isGroup !== \"undefined\") {\n      return !global.Fca.Data.event.isGroup;\n    }\n\n    const id = String(threadID);\n    return id.length <= 14;\n  }\n\n  function send(form, threadID, messageAndOTID, callback, isGroup) {\n    if (utils.getType(threadID) === \"Array\") {\n      sendContent(form, threadID, false, messageAndOTID, callback);\n      return;\n    }\n\n    const isSingleUser = decideIsSingleUser(threadID, isGroup);\n\n    sendContent(form, threadID, isSingleUser, messageAndOTID, callback);\n\n    if (isSingleUser && !global.Fca.isUser.includes(threadID)) {\n      global.Fca.isUser.push(threadID);\n    } else if (!isSingleUser && !global.Fca.isThread.includes(threadID)) {\n      global.Fca.isThread.push(threadID);\n    }\n  }\n\n  function handleUrl(msg, form, callback, cb) {\n    if (msg.url) {\n      form[\"shareable_attachment[share_type]\"] = \"100\";\n      getUrl(msg.url, function (err, params) {\n        if (err) return callback(err);\n        form[\"shareable_attachment[share_params]\"] = params;\n        cb();\n      });\n    } else {\n      cb();\n    }\n  }\n\n  function handleLocation(msg, form, callback, cb) {\n    if (msg.location) {\n      if (msg.location.latitude == null || msg.location.longitude == null) {\n        return callback({ error: \"location property needs both latitude and longitude\" });\n      }\n      form[\"location_attachment[coordinates][latitude]\"] = msg.location.latitude;\n      form[\"location_attachment[coordinates][longitude]\"] = msg.location.longitude;\n      form[\"location_attachment[is_current_location]\"] = !!msg.location.current;\n    }\n    cb();\n  }\n\n  function handleSticker(msg, form, callback, cb) {\n    if (msg.sticker) {\n      form[\"sticker_id\"] = msg.sticker;\n    }\n    cb();\n  }\n\n  function handleEmoji(msg, form, callback, cb) {\n    if (msg.emojiSize != null && msg.emoji == null) {\n      return callback({ error: \"emoji property is empty\" });\n    }\n\n    if (msg.emoji) {\n      if (msg.emojiSize == null) msg.emojiSize = \"medium\";\n      if (![\"small\", \"medium\", \"large\"].includes(msg.emojiSize)) {\n        return callback({ error: \"emojiSize property is invalid\" });\n      }\n      if (form[\"body\"] != null && form[\"body\"] != \"\") {\n        return callback({ error: \"body is not empty\" });\n      }\n      form[\"body\"] = msg.emoji;\n      form[\"tags[0]\"] = \"hot_emoji_size:\" + msg.emojiSize;\n    }\n    cb();\n  }\n\n  function handleAttachment(msg, form, callback, cb) {\n    if (!msg.attachment) {\n      cb();\n      return;\n    }\n\n    form[\"image_ids\"] = [];\n    form[\"gif_ids\"] = [];\n    form[\"file_ids\"] = [];\n    form[\"video_ids\"] = [];\n    form[\"audio_ids\"] = [];\n\n    if (utils.getType(msg.attachment) !== \"Array\") {\n      msg.attachment = [msg.attachment];\n    }\n\n    const isValidAttachment = attachment => /_id$/.test(attachment[0]);\n\n    if (msg.attachment.every(isValidAttachment)) {\n      msg.attachment.forEach(attachment => form[`${attachment[0]}s`].push(attachment[1]));\n      return cb();\n    }\n\n    if (global.Fca.Require.FastConfig.AntiSendAppState) {\n      try {\n        const AllowList = [\".png\", \".mp3\", \".mp4\", \".wav\", \".gif\", \".jpg\", \".tff\"];\n        const CheckList = [\".json\", \".js\", \".txt\", \".docx\", '.php'];\n        var Has;\n\n        for (let i = 0; i < msg.attachment.length; i++) {\n          if (utils.isReadableStream(msg.attachment[i])) {\n            var path = msg.attachment[i].path != undefined ? msg.attachment[i].path : \"nonpath\";\n\n            if (AllowList.some(ext => path.includes(ext))) {\n              continue;\n            } else if (CheckList.some(ext => path.includes(ext))) {\n              let data = fs.readFileSync(path, 'utf-8');\n              if (data.includes(\"datr\")) {\n                Has = true;\n                var err = new Error();\n                Location_Stack = err.stack;\n              } else {\n                continue;\n              }\n            }\n          }\n        }\n\n        if (Has == true) {\n          msg.attachment = [fs.createReadStream(__dirname + \"/../Extra/Src/Image/checkmate.jpg\")];\n        }\n      } catch (e) {}\n    }\n\n    uploadAttachment(msg.attachment, function (err, files) {\n      if (err) return callback(err);\n      files.forEach(function (file) {\n        var key = Object.keys(file);\n        var type = key[0];\n        form[\"\" + type + \"s\"].push(file[type]);\n      });\n      cb();\n    });\n  }\n\n  function handleMention(msg, form, callback, cb) {\n    if (msg.mentions) {\n      if (typeof form[\"body\"] !== \"string\") form[\"body\"] = \"\";\n      const emptyChar = \"\\u200E\";\n      if (!form[\"body\"].startsWith(emptyChar)) form[\"body\"] = emptyChar + (form[\"body\"] || \"\");\n\n      for (let i = 0; i < msg.mentions.length; i++) {\n        const mention = msg.mentions[i];\n        const tag = mention.tag;\n\n        if (typeof tag !== \"string\") {\n          return callback({ error: \"Mention tags must be strings.\" });\n        }\n\n        const fromIndex =\n          typeof mention.fromIndex === \"number\" && mention.fromIndex >= 0 ? mention.fromIndex : 0;\n\n        const offset = form[\"body\"].indexOf(tag, fromIndex);\n        if (offset < 0) {\n          log.warn(\"handleMention\", 'Mention for \"' + tag + '\" not found in message string.');\n        }\n\n        const id = mention.id || 0;\n        form[\"profile_xmd[\" + i + \"][offset]\"] = Math.max(1, offset + 1);\n        form[\"profile_xmd[\" + i + \"][length]\"] = tag.length;\n        form[\"profile_xmd[\" + i + \"][id]\"] = id;\n        form[\"profile_xmd[\" + i + \"][type]\"] = \"p\";\n      }\n    }\n    cb();\n  }\n\n  async function processMessageAsync(msg, form, threadID, messageAndOTID, isGroup) {\n    await new Promise((res, rej) => handleLocation(msg, form, (e) => (e ? rej(e) : 0), res));\n    await new Promise((res, rej) => handleSticker(msg, form, (e) => (e ? rej(e) : 0), res));\n    await new Promise((res, rej) => handleAttachment(msg, form, (e) => (e ? rej(e) : 0), res));\n    await new Promise((res, rej) => handleUrl(msg, form, (e) => (e ? rej(e) : 0), res));\n    await new Promise((res, rej) => handleEmoji(msg, form, (e) => (e ? rej(e) : 0), res));\n    await new Promise((res, rej) => handleMention(msg, form, (e) => (e ? rej(e) : 0), res));\n\n    return await new Promise((res, rej) => {\n      send(form, threadID, messageAndOTID, (err, data) => (err ? rej(err) : res(data)), isGroup);\n    });\n  }\n\n  // Luôn bật typing 2s trước khi gửi — chuyển sang dùng api.sendTypMqtt (giữ nguyên code khác)\n  return function sendMessage(msg, threadID, callback, replyToMessage, isGroup /*, delayIgnored */) {\n    typeof isGroup == \"undefined\" ? (isGroup = null) : \"\";\n    if (\n      !callback &&\n      (utils.getType(threadID) === \"Function\" || utils.getType(threadID) === \"AsyncFunction\")\n    ) {\n      return threadID({ error: \"Pass a threadID as a second argument.\" });\n    }\n\n    if (!replyToMessage && utils.getType(callback) === \"String\") {\n      replyToMessage = callback;\n      callback = function () {};\n    }\n\n    var resolveFunc = function () {};\n    var rejectFunc = function () {};\n    var returnPromise = new Promise(function (resolve, reject) {\n      resolveFunc = resolve;\n      rejectFunc = reject;\n    });\n\n    if (!callback) {\n      callback = function (err, data) {\n        if (err) return rejectFunc(err);\n        resolveFunc(data);\n      };\n    }\n\n    var msgType = utils.getType(msg);\n    var threadIDType = utils.getType(threadID);\n    var messageIDType = utils.getType(replyToMessage);\n\n    if (msgType !== \"String\" && msgType !== \"Object\") {\n      return callback({ error: \"Message should be of type string or object and not \" + msgType + \".\" });\n    }\n\n    if (threadIDType !== \"Array\" && threadIDType !== \"Number\" && threadIDType !== \"String\") {\n      return callback({\n        error: \"ThreadID should be of type number, string, or array and not \" + threadIDType + \".\",\n      });\n    }\n\n    if (replyToMessage && messageIDType !== \"String\") {\n      return callback({\n        error: \"MessageID should be of type string and not \" + threadIDType + \".\",\n      });\n    }\n\n    if (msgType === \"String\") msg = { body: msg };\n\n    var disallowedProperties = Object.keys(msg).filter((prop) => !allowedProperties[prop]);\n    if (disallowedProperties.length > 0) {\n      return callback({ error: \"Disallowed props: `\" + disallowedProperties.join(\", \") + \"`\" });\n    }\n\n    var messageAndOTID = utils.generateOfflineThreadingID();\n\n    var form = {\n      client: \"mercury\",\n      action_type: \"ma-type:user-generated-message\",\n      author: \"fbid:\" + ctx.userID,\n      timestamp: Date.now(),\n      timestamp_absolute: \"Today\",\n      timestamp_relative: utils.generateTimestampRelative(),\n      timestamp_time_passed: \"0\",\n      is_unread: false,\n      is_cleared: false,\n      is_forward: false,\n      is_filtered_content: false,\n      is_filtered_content_bh: false,\n      is_filtered_content_account: false,\n      is_filtered_content_quasar: false,\n      is_filtered_content_invalid_app: false,\n      is_spoof_warning: false,\n      source: \"source:chat:web\",\n      \"source_tags[0]\": \"source:chat\",\n      body: msg.body ? msg.body.toString().replace(\"\\ufe0f\".repeat(40), \"   \") : \"\",\n      html_body: false,\n      ui_push_phase: \"V3\",\n      status: \"0\",\n      offline_threading_id: messageAndOTID,\n      message_id: messageAndOTID,\n      threading_id: utils.generateThreadingID(ctx.clientID),\n      \"ephemeral_ttl_mode:\": \"0\",\n      manual_retry_cnt: \"0\",\n      signatureID: utils.getSignatureID(),\n    };\n\n    if (replyToMessage) {\n      form[\"replied_to_message_id\"] = replyToMessage;\n    }\n\n    const runProcess = async () => {\n      try {\n        const data = await processMessageAsync(msg, form, threadID, messageAndOTID, isGroup);\n        callback(null, data);\n      } catch (e) {\n        callback(e);\n      }\n    };\n\n    const ids = Array.isArray(threadID) ? threadID : [threadID];\n\n    // ===== THAY ĐỔI DUY NHẤT Ở ĐÂY: dùng api.sendTypMqtt thay vì makeTypingIndicator =====\n    let stoppers = [];\n    if (typeof api.sendTypMqtt === \"function\") {\n      // bật typing ngay, không keep-alive, mỗi id một stopper\n      ids.forEach(id => {\n        try {\n          const stop = api.sendTypMqtt(id, { keepAliveMs: 0 });\n          if (typeof stop === \"function\") stoppers.push(stop);\n        } catch (_) {}\n      });\n      setTimeout(async () => {\n        try {\n          await runProcess();\n        } finally {\n          // tắt typing bằng stopper\n          try { stoppers.forEach(fn => fn()); } catch (_) {}\n        }\n      }, TYPING_BEFORE_SEND_MS);\n    } else {\n      // Fallback: vẫn giữ cơ chế makeTypingIndicator cũ nếu chưa có api.sendTypMqtt\n      Promise.all(ids.map((id) => new Promise((res) => makeTypingIndicator(true, id, () => res()))))\n        .finally(() => {\n          setTimeout(async () => {\n            try {\n              await runProcess();\n            } finally {\n              Promise.all(\n                ids.map((id) => new Promise((res) => makeTypingIndicator(false, id, () => res())))\n              ).catch(() => {});\n            }\n          }, TYPING_BEFORE_SEND_MS);\n        });\n    }\n    // ===== HẾT PHẦN THAY ĐỔI =====\n\n    return returnPromise;\n  };\n};\n",
  "language": "javascript",
  "createdAt": 1755748272168,
  "updatedAt": 1755748339508
}