fca-umaru-v1 40.1.23 → 40.1.24

Sign up to get free protection for your applications and to get access to all the features.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fca-umaru-v1",
3
- "version": "40.1.23",
3
+ "version": "40.1.24",
4
4
  "description": "A Facebook chat API that doesn't rely on XMPP",
5
5
  "scripts": {
6
6
  "test": "mocha",
package/src/listenMqtt.js CHANGED
@@ -1 +1 @@
1
- const e=require("../utils"),t=require("npmlog"),a=require("mqtt"),s=require("websocket-stream"),r=require("https-proxy-agent"),n=require("events"),i=function(){};let o={},l=function(){};const d=["/legacy_web","/webrtc","/rtc_multi","/onevc","/br_sr","/sr_res","/t_ms","/thread_typing","/orca_typing_notifications","/notify_disconnect","/orca_presence","/legacy_web_mtouch"];function g(t,n,i,g){const m=i.globalOptions.online,p=Math.floor(9007199254740991*Math.random())+1,h={u:i.i_userID||i.userID,s:p,chat_on:m,fg:!1,d:e.getGUID(),ct:"websocket",aid:"219994525426954",mqtt_sid:"",cp:3,ecp:10,st:[],pm:[],dc:"",no_auto_fg:!0,gas:null,pack:[],a:i.globalOptions.userAgent,aids:null},u=i.jar.getCookies("https://www.facebook.com").join("; ");let _;_=i.mqttEndpoint?i.mqttEndpoint+"&sid="+p:i.region?"wss://edge-chat.facebook.com/chat?region="+i.region.toLocaleLowerCase()+"&sid="+p:"wss://edge-chat.facebook.com/chat?sid="+p;const y={clientId:"mqttwsclient",protocolId:"MQIsdp",protocolVersion:3,username:JSON.stringify(h),clean:!0,wsOptions:{headers:{Cookie:u,Origin:"https://www.facebook.com","User-Agent":i.globalOptions.userAgent,Referer:"https://www.facebook.com/",Host:new URL(_).hostname},origin:"https://www.facebook.com",protocolVersion:13},keepalive:10,reschedulePings:!1};if(void 0!==i.globalOptions.proxy){const e=new r(i.globalOptions.proxy);y.wsOptions.agent=e}i.mqttClient=new a.Client((e=>s(_,y.wsOptions)),y);const b=i.mqttClient;b.on("error",(function(e){b.end(),i.globalOptions.autoReconnect?l():g({type:"stop_listen",error:"Connection refused: Server unavailable"},null)})),b.on("close",(function(){b.end(),t.post("https://www.facebook.com/api/graphqlbatch/",i.jar,o).then(e.parseAndCheckLogin(i,t)).then((t=>{if("Array"!=e.getType(t))throw{error:"Not logged in",res:t};g("Connection closed.")})).catch((t=>("Object"!=e.getType(t)||"Not logged in"!==t.error&&"Not logged in."!==t.error||(i.loggedIn=!1),g(t))))})),b.on("connect",(function(){let e;d.forEach((function(e){b.subscribe(e)}));const t={sync_api_version:10,max_deltas_able_to_process:1e3,delta_batch_size:500,encoding:"JSON",entity_fbid:i.i_userID||i.userID};i.syncToken?(e="/messenger_sync_get_diffs",t.last_seq_id=i.lastSeqId,t.sync_token=i.syncToken):(e="/messenger_sync_create_queue",t.initial_titan_sequence_id=i.lastSeqId,t.device_params=null),b.publish(e,JSON.stringify(t),{qos:1,retain:!1}),b.publish("/foreground_state",JSON.stringify({foreground:m}),{qos:1}),b.publish("/set_client_settings",JSON.stringify({make_user_available_when_in_foreground:!0}),{qos:1});const a=setTimeout((function(){b.end(),l()}),5e3);i.tmsWait=function(){clearTimeout(a),i.globalOptions.emitReady&&g({type:"ready",error:null}),delete i.tmsWait}})),b.on("message",(function(a,s,r){let o=Buffer.isBuffer(s)?Buffer.from(s).toString():s;try{o=JSON.parse(o)}catch(e){o={}}if("jewel_requests_add"===o.type)g(null,{type:"friend_request_received",actorFbId:o.from.toString(),timestamp:Date.now().toString()});else if("jewel_requests_remove_old"===o.type)g(null,{type:"friend_request_cancel",actorFbId:o.from.toString(),timestamp:Date.now().toString()});else if("/t_ms"===a){i.tmsWait&&"function"==typeof i.tmsWait&&i.tmsWait(),o.firstDeltaSeqId&&o.syncToken&&(i.lastSeqId=o.firstDeltaSeqId,i.syncToken=o.syncToken),o.lastIssuedSeqId&&(i.lastSeqId=parseInt(o.lastIssuedSeqId));for(const e in o.deltas)c(t,n,i,g,{delta:o.deltas[e]})}else if("/thread_typing"===a||"/orca_typing_notifications"===a){const t={type:"typ",isTyping:!!o.state,from:o.sender_fbid.toString(),threadID:e.formatID((o.thread||o.sender_fbid).toString())};g(null,t)}else if("/orca_presence"===a&&!i.globalOptions.updatePresence)for(const e in o.list){const t=o.list[e],a={type:"presence",userID:t.u.toString(),timestamp:1e3*t.l,statuses:t.p};g(null,a)}}))}function c(a,s,r,n,i){if("NewMessage"==i.delta.class){if(r.globalOptions.pageID&&r.globalOptions.pageID!=i.queue)return;!function t(a){if(a==i.delta.attachments?.length){let t;try{t=e.formatDeltaMessage(i)}catch(e){return n({error:"Problem parsing message object.",detail:e,res:i,type:"parse_error"})}return t&&r.globalOptions.autoMarkDelivery&&m(r,s,t.threadID,t.messageID),r.globalOptions.selfListen||t.senderID!==r.i_userID&&t.senderID!==r.userID?void n(null,t):void 0}if(Array.isArray(i.delta.attachments) && "photo"!=i.delta.attachments[a]?.mercury?.attach_type)return t(a+1);s.resolvePhotoUrl(i?.delta?.attachments[a]?.fbid,((e,s)=>(e||(i.delta.attachments[a].mercury.metadata.url=s),t(a+1))))}(0)}if("ClientPayload"==i.delta.class){const l=e.decodeClientPayload(i.delta.payload);if(l&&l.deltas){for(const i in l.deltas){var o=l.deltas[i];if(o.deltaMessageReaction&&r.globalOptions.listenEvents)n(null,{type:"message_reaction",threadID:(o.deltaMessageReaction.threadKey.threadFbId?o.deltaMessageReaction.threadKey.threadFbId:o.deltaMessageReaction.threadKey.otherUserFbId).toString(),messageID:o.deltaMessageReaction.messageId,reaction:o.deltaMessageReaction.reaction,senderID:0==o.deltaMessageReaction.senderId?o.deltaMessageReaction.userId.toString():o.deltaMessageReaction.senderId.toString(),userID:(o.deltaMessageReaction.userId||o.deltaMessageReaction.senderId).toString()});else if(o.deltaRecallMessageData&&r.globalOptions.listenEvents)n(null,{type:"message_unsend",threadID:(o.deltaRecallMessageData.threadKey.threadFbId?o.deltaRecallMessageData.threadKey.threadFbId:o.deltaRecallMessageData.threadKey.otherUserFbId).toString(),messageID:o.deltaRecallMessageData.messageID,senderID:o.deltaRecallMessageData.senderID.toString(),deletionTimestamp:o.deltaRecallMessageData.deletionTimestamp,timestamp:o.deltaRecallMessageData.timestamp});else if(o.deltaRemoveMessage&&r.globalOptions.listenEvents)n(null,{type:"message_self_delete",threadID:(o.deltaRemoveMessage.threadKey.threadFbId?o.deltaRemoveMessage.threadKey.threadFbId:o.deltaRemoveMessage.threadKey.otherUserFbId).toString(),messageID:1==o.deltaRemoveMessage.messageIds.length?o.deltaRemoveMessage.messageIds[0]:o.deltaRemoveMessage.messageIds,senderID:s.getCurrentUserID(),deletionTimestamp:o.deltaRemoveMessage.deletionTimestamp,timestamp:o.deltaRemoveMessage.timestamp});else if(o.deltaMessageReply){let i=void 0===o.deltaMessageReply.message||void 0===o.deltaMessageReply.message.data||void 0===o.deltaMessageReply.message.data.prng?[]:JSON.parse(o.deltaMessageReply.message.data.prng),l=i.map((e=>e.i)),d=i.map((e=>e.o)),g=i.map((e=>e.l));const c={};for(let e=0;e<l.length;e++)c[l[e]]=(o.deltaMessageReply.message.body||"").substring(d[e],d[e]+g[e]);const p={type:"message_reply",threadID:(o.deltaMessageReply.message.messageMetadata.threadKey.threadFbId?o.deltaMessageReply.message.messageMetadata.threadKey.threadFbId:o.deltaMessageReply.message.messageMetadata.threadKey.otherUserFbId).toString(),messageID:o.deltaMessageReply.message.messageMetadata.messageId,senderID:o.deltaMessageReply.message.messageMetadata.actorFbId.toString(),attachments:o.deltaMessageReply.message.attachments?.map((function(e){const t=JSON.parse(e.mercuryJSON);return Object.assign(e,t),e})).map((t=>{let a;try{a=e._formatAttachment(t)}catch(e){a=t,a.error=e,a.type="unknown"}return a})),body:o.deltaMessageReply.message.body||"",isGroup:!!o.deltaMessageReply.message.messageMetadata.threadKey.threadFbId,mentions:c,timestamp:o.deltaMessageReply.message.messageMetadata.timestamp,participantIDs:(o.deltaMessageReply.message.participants||[]).map((e=>e.toString()))};if(o.deltaMessageReply.repliedToMessage){i=void 0===o.deltaMessageReply.repliedToMessage||void 0===o.deltaMessageReply.repliedToMessage.data||void 0===o.deltaMessageReply.repliedToMessage.data.prng?[]:JSON.parse(o.deltaMessageReply.repliedToMessage.data.prng),l=i.map((e=>e.i)),d=i.map((e=>e.o)),g=i.map((e=>e.l));const t={};for(let e=0;e<l.length;e++)t[l[e]]=(o.deltaMessageReply.repliedToMessage.body||"").substring(d[e],d[e]+g[e]);p.messageReply={threadID:(o.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId?o.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId:o.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.otherUserFbId).toString(),messageID:o.deltaMessageReply.repliedToMessage.messageMetadata.messageId,senderID:o.deltaMessageReply.repliedToMessage.messageMetadata.actorFbId.toString(),attachments:o.deltaMessageReply.repliedToMessage.attachments.map((function(e){const t=JSON.parse(e.mercuryJSON);return Object.assign(e,t),e})).map((t=>{let a;try{a=e._formatAttachment(t)}catch(e){a=t,a.error=e,a.type="unknown"}return a})),body:o.deltaMessageReply.repliedToMessage.body||"",isGroup:!!o.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId,mentions:t,timestamp:o.deltaMessageReply.repliedToMessage.messageMetadata.timestamp,participantIDs:(o.deltaMessageReply.repliedToMessage.participants||[]).map((e=>e.toString()))}}else{if(o.deltaMessageReply.replyToMessageId)return a.post("https://www.facebook.com/api/graphqlbatch/",r.jar,{av:r.globalOptions.pageID,queries:JSON.stringify({o0:{doc_id:"2848441488556444",query_params:{thread_and_message_id:{thread_id:p.threadID,message_id:o.deltaMessageReply.replyToMessageId.id}}}})}).then(e.parseAndCheckLogin(r,a)).then((t=>{if(t[t.length-1].error_results>0)throw t[0].o0.errors;if(0===t[t.length-1].successful_results)throw{error:"forcedFetch: there was no successful_results",res:t};const a=t[0].o0.data.message,s={};for(const e in a.message.ranges)s[a.message.ranges[e].entity.id]=(a.message.text||"").substr(a.message.ranges[e].offset,a.message.ranges[e].length);p.messageReply={threadID:p.threadID,messageID:a.message_id,senderID:a.message_sender.id.toString(),attachments:a.message.blob_attachment.map((t=>{let a;try{a=e._formatAttachment({blob_attachment:t})}catch(e){a=t,a.error=e,a.type="unknown"}return a})),body:a.message.text||"",isGroup:p.isGroup,mentions:s,timestamp:parseInt(a.timestamp_precise)}})).catch((e=>{t.error("forcedFetch",e)})).finally((function(){r.globalOptions.autoMarkDelivery&&m(r,s,p.threadID,p.messageID),(r.globalOptions.selfListen||p.senderID!==r.i_userID&&p.senderID!==r.userID)&&n(null,p)}));p.delta=o}return r.globalOptions.autoMarkDelivery&&m(r,s,p.threadID,p.messageID),r.globalOptions.selfListen||p.senderID!==r.i_userID&&p.senderID!==r.userID?void n(null,p):void 0}}return}}if("NewMessage"===i.delta.class||r.globalOptions.listenEvents)switch(i.delta.class){case"ReadReceipt":try{l=e.formatDeltaReadReceipt(i.delta)}catch(e){return n({error:"Problem parsing message object.",detail:e,res:i.delta,type:"parse_error"})}return void n(null,l);case"AdminTextMessage":switch(i.delta.type){case"change_thread_theme":case"change_thread_nickname":case"change_thread_icon":case"change_thread_admins":case"group_poll":var l;try{l=e.formatDeltaEvent(i.delta)}catch(e){return n({error:"Problem parsing message object.",detail:e,res:i.delta,type:"parse_error"})}return void n(null,l);default:return}case"ForcedFetch":if(!i.delta.threadKey)return;var d=i.delta.messageId,g=i.delta.threadKey.threadFbId;if(d&&g){const s={av:r.globalOptions.pageID,queries:JSON.stringify({o0:{doc_id:"2848441488556444",query_params:{thread_and_message_id:{thread_id:g.toString(),message_id:d}}}})};a.post("https://www.facebook.com/api/graphqlbatch/",r.jar,s).then(e.parseAndCheckLogin(r,a)).then((a=>{if(a[a.length-1].error_results>0)throw a[0].o0.errors;if(0===a[a.length-1].successful_results)throw{error:"forcedFetch: there was no successful_results",res:a};const s=a[0].o0.data.message;if("Object"==e.getType(s))switch(t.info("forcedFetch",s),s.__typename){case"ThreadImageMessage":(r.globalOptions.selfListenEvent||s.message_sender.id.toString()!==r.i_userID&&s.message_sender.id.toString()!==r.userID)&&r.loggedIn&&n(null,{type:"event",threadID:e.formatID(g.toString()),messageID:s.message_id,logMessageType:"log:thread-image",logMessageData:{attachmentID:s.image_with_metadata&&s.image_with_metadata.legacy_attachment_id,width:s.image_with_metadata&&s.image_with_metadata.original_dimensions.x,height:s.image_with_metadata&&s.image_with_metadata.original_dimensions.y,url:s.image_with_metadata&&s.image_with_metadata.preview.uri},logMessageBody:s.snippet,timestamp:s.timestamp_precise,author:s.message_sender.id});break;case"UserMessage":t.info("ff-Return",{type:"message",senderID:e.formatID(s.message_sender.id),body:s.message.text||"",threadID:e.formatID(g.toString()),messageID:s.message_id,attachments:[{type:"share",ID:s.extensible_attachment.legacy_attachment_id,url:s.extensible_attachment.story_attachment.url,title:s.extensible_attachment.story_attachment.title_with_entities.text,description:s.extensible_attachment.story_attachment.description.text,source:s.extensible_attachment.story_attachment.source,image:((s.extensible_attachment.story_attachment.media||{}).image||{}).uri,width:((s.extensible_attachment.story_attachment.media||{}).image||{}).width,height:((s.extensible_attachment.story_attachment.media||{}).image||{}).height,playable:(s.extensible_attachment.story_attachment.media||{}).is_playable||!1,duration:(s.extensible_attachment.story_attachment.media||{}).playable_duration_in_ms||0,subattachments:s.extensible_attachment.subattachments,properties:s.extensible_attachment.story_attachment.properties}],mentions:{},timestamp:parseInt(s.timestamp_precise),isGroup:s.message_sender.id!=g.toString()}),n(null,{type:"message",senderID:e.formatID(s.message_sender.id),body:s.message.text||"",threadID:e.formatID(g.toString()),messageID:s.message_id,attachments:[{type:"share",ID:s.extensible_attachment.legacy_attachment_id,url:s.extensible_attachment.story_attachment.url,title:s.extensible_attachment.story_attachment.title_with_entities.text,description:s.extensible_attachment.story_attachment.description.text,source:s.extensible_attachment.story_attachment.source,image:((s.extensible_attachment.story_attachment.media||{}).image||{}).uri,width:((s.extensible_attachment.story_attachment.media||{}).image||{}).width,height:((s.extensible_attachment.story_attachment.media||{}).image||{}).height,playable:(s.extensible_attachment.story_attachment.media||{}).is_playable||!1,duration:(s.extensible_attachment.story_attachment.media||{}).playable_duration_in_ms||0,subattachments:s.extensible_attachment.subattachments,properties:s.extensible_attachment.story_attachment.properties}],mentions:{},timestamp:parseInt(s.timestamp_precise),isGroup:s.message_sender.id!=g.toString()})}else t.error("forcedFetch",s)})).catch((e=>{t.error("forcedFetch",e)}))}break;case"ThreadName":case"ParticipantsAddedToGroupThread":case"ParticipantLeftGroupThread":case"ApprovalQueue":var c;try{c=e.formatDeltaEvent(i.delta)}catch(e){return n({error:"Problem parsing message object.",detail:e,res:i.delta,type:"parse_error"})}return(r.globalOptions.selfListenEvent||c.author.toString()!==r.i_userID&&c.author.toString()!==r.userID)&&r.loggedIn?void n(null,c):void 0}}function m(e,a,s,r){s&&r&&a.markAsDelivered(s,r,(r=>{r?t.error("markAsDelivered",r):e.globalOptions.autoMarkRead&&a.markAsRead(s,(e=>{e&&t.error("markAsDelivered",e)}))}))}module.exports=function(t,a,s){let r=i;return l=function(){return s.t_mqttCalled=!1,t.post("https://www.facebook.com/api/graphqlbatch/",s.jar,o).then(e.parseAndCheckLogin(s,t)).then((n=>{if("Array"!=e.getType(n)){const e=new Error("Not logged in");throw e.res=n,e.error="Not logged in",e}if(n&&n[n.length-1].error_results>0)throw n[0].o0.errors;if(0===n[n.length-1].successful_results)throw{error:"getSeqId: there was no successful_results",res:n};if(!n[0].o0.data.viewer.message_threads.sync_sequence_id){const e=new Error("No sync_sequence_id found.");throw e.res=n,e.error="getSeqId: no sync_sequence_id found.",e}s.lastSeqId=n[0].o0.data.viewer.message_threads.sync_sequence_id,g(t,a,s,r)})).catch((t=>{throw"Object"!=e.getType(t)||"Not logged in"!==t.error&&"Not logged in."!==t.error||(s.loggedIn=!1),t}))},function(e){const d=new class extends n{stopListening(e){e=e||(()=>{}),r=i,s.mqttClient&&(s.mqttClient.unsubscribe("/webrtc"),s.mqttClient.unsubscribe("/rtc_multi"),s.mqttClient.unsubscribe("/onevc"),s.mqttClient.publish("/browser_close","{}"),s.mqttClient.end(!1,(function(...t){e(t),s.mqttClient=void 0})))}async stopListeningSync(){return new Promise((e=>{this.stopListening(((...t)=>{e(t)}))}))}};return r=e||function(e,t){if(e)return d.emit("error",e);d.emit("message",t)},s.firstListen||(s.lastSeqId=null),s.syncToken=void 0,s.t_mqttCalled=!1,o={av:s.globalOptions.pageID,queries:JSON.stringify({o0:{doc_id:"3336396659757871",query_params:{limit:1,before:null,tags:["INBOX"],includeDeliveryReceipts:!1,includeSeqID:!0}}})},s.firstListen&&s.lastSeqId?g(t,a,s,r):l().catch((()=>{g(t,a,s,r)})),s.firstListen=!1,a.stopListening=d.stopListening,a.stopListeningSync=d.stopListeningSync,d}};
1
+ const e=require("../utils"),t=require("npmlog"),a=require("mqtt"),s=require("websocket-stream"),r=require("https-proxy-agent"),n=require("events"),i=function(){};let o={},l=function(){};const d=["/legacy_web","/webrtc","/rtc_multi","/onevc","/br_sr","/sr_res","/t_ms","/thread_typing","/orca_typing_notifications","/notify_disconnect","/orca_presence","/legacy_web_mtouch"];function g(t,n,i,g){const m=i.globalOptions.online,p=Math.floor(9007199254740991*Math.random())+1,h={u:i.i_userID||i.userID,s:p,chat_on:m,fg:!1,d:e.getGUID(),ct:"websocket",aid:"219994525426954",mqtt_sid:"",cp:3,ecp:10,st:[],pm:[],dc:"",no_auto_fg:!0,gas:null,pack:[],a:i.globalOptions.userAgent,aids:null},u=i.jar.getCookies("https://www.facebook.com").join("; ");let _;_=i.mqttEndpoint?i.mqttEndpoint+"&sid="+p:i.region?"wss://edge-chat.facebook.com/chat?region="+i.region.toLocaleLowerCase()+"&sid="+p:"wss://edge-chat.facebook.com/chat?sid="+p;const y={clientId:"mqttwsclient",protocolId:"MQIsdp",protocolVersion:3,username:JSON.stringify(h),clean:!0,wsOptions:{headers:{Cookie:u,Origin:"https://www.facebook.com","User-Agent":i.globalOptions.userAgent,Referer:"https://www.facebook.com/",Host:new URL(_).hostname},origin:"https://www.facebook.com",protocolVersion:13},keepalive:10,reschedulePings:!1};if(void 0!==i.globalOptions.proxy){const e=new r(i.globalOptions.proxy);y.wsOptions.agent=e}i.mqttClient=new a.Client((e=>s(_,y.wsOptions)),y);const b=i.mqttClient;b.on("error",(function(e){b.end(),i.globalOptions.autoReconnect?l():g({type:"stop_listen",error:"Connection refused: Server unavailable"},null)})),b.on("close",(function(){b.end(),t.post("https://www.facebook.com/api/graphqlbatch/",i.jar,o).then(e.parseAndCheckLogin(i,t)).then((t=>{if("Array"!=e.getType(t))throw{error:"Not logged in",res:t};g("Connection closed.")})).catch((t=>("Object"!=e.getType(t)||"Not logged in"!==t.error&&"Not logged in."!==t.error||(i.loggedIn=!1),g(t))))})),b.on("connect",(function(){let e;d.forEach((function(e){b.subscribe(e)}));const t={sync_api_version:10,max_deltas_able_to_process:1e3,delta_batch_size:500,encoding:"JSON",entity_fbid:i.i_userID||i.userID};i.syncToken?(e="/messenger_sync_get_diffs",t.last_seq_id=i.lastSeqId,t.sync_token=i.syncToken):(e="/messenger_sync_create_queue",t.initial_titan_sequence_id=i.lastSeqId,t.device_params=null),b.publish(e,JSON.stringify(t),{qos:1,retain:!1}),b.publish("/foreground_state",JSON.stringify({foreground:m}),{qos:1}),b.publish("/set_client_settings",JSON.stringify({make_user_available_when_in_foreground:!0}),{qos:1});const a=setTimeout((function(){b.end(),l()}),5e3);i.tmsWait=function(){clearTimeout(a),i.globalOptions.emitReady&&g({type:"ready",error:null}),delete i.tmsWait}})),b.on("message",(function(a,s,r){let o=Buffer.isBuffer(s)?Buffer.from(s).toString():s;try{o=JSON.parse(o)}catch(e){o={}}if("jewel_requests_add"===o.type)g(null,{type:"friend_request_received",actorFbId:o.from.toString(),timestamp:Date.now().toString()});else if("jewel_requests_remove_old"===o.type)g(null,{type:"friend_request_cancel",actorFbId:o.from.toString(),timestamp:Date.now().toString()});else if("/t_ms"===a){i.tmsWait&&"function"==typeof i.tmsWait&&i.tmsWait(),o.firstDeltaSeqId&&o.syncToken&&(i.lastSeqId=o.firstDeltaSeqId,i.syncToken=o.syncToken),o.lastIssuedSeqId&&(i.lastSeqId=parseInt(o.lastIssuedSeqId));for(const e in o.deltas)c(t,n,i,g,{delta:o.deltas[e]})}else if("/thread_typing"===a||"/orca_typing_notifications"===a){const t={type:"typ",isTyping:!!o.state,from:o.sender_fbid.toString(),threadID:e.formatID((o.thread||o.sender_fbid).toString())};g(null,t)}else if("/orca_presence"===a&&!i.globalOptions.updatePresence)for(const e in o.list){const t=o.list[e],a={type:"presence",userID:t.u.toString(),timestamp:1e3*t.l,statuses:t.p};g(null,a)}}))}function c(a,s,r,n,i){if("NewMessage"==i.delta.class){if(r.globalOptions.pageID&&r.globalOptions.pageID!=i.queue)return;!function t(a){if(a==i.delta.attachments?.length){let t;try{t=e.formatDeltaMessage(i)}catch(e){return n({error:"Problem parsing message object.",detail:e,res:i,type:"parse_error"})}return t&&r.globalOptions.autoMarkDelivery&&m(r,s,t.threadID,t.messageID),r.globalOptions.selfListen||t.senderID!==r.i_userID&&t.senderID!==r.userID?void n(null,t):void 0}if(Array.isArray(i.delta.attachments) && "photo"!=i.delta.attachments[a]?.mercury?.attach_type)return t(a+1);s.resolvePhotoUrl((typeof i?.delta?.attachments !== "undefined")?i?.delta?.attachments[a]?.fbid:null,((e,s)=>(e||(i.delta.attachments[a].mercury.metadata.url=s),t(a+1))))}(0)}if("ClientPayload"==i.delta.class){const l=e.decodeClientPayload(i.delta.payload);if(l&&l.deltas){for(const i in l.deltas){var o=l.deltas[i];if(o.deltaMessageReaction&&r.globalOptions.listenEvents)n(null,{type:"message_reaction",threadID:(o.deltaMessageReaction.threadKey.threadFbId?o.deltaMessageReaction.threadKey.threadFbId:o.deltaMessageReaction.threadKey.otherUserFbId).toString(),messageID:o.deltaMessageReaction.messageId,reaction:o.deltaMessageReaction.reaction,senderID:0==o.deltaMessageReaction.senderId?o.deltaMessageReaction.userId.toString():o.deltaMessageReaction.senderId.toString(),userID:(o.deltaMessageReaction.userId||o.deltaMessageReaction.senderId).toString()});else if(o.deltaRecallMessageData&&r.globalOptions.listenEvents)n(null,{type:"message_unsend",threadID:(o.deltaRecallMessageData.threadKey.threadFbId?o.deltaRecallMessageData.threadKey.threadFbId:o.deltaRecallMessageData.threadKey.otherUserFbId).toString(),messageID:o.deltaRecallMessageData.messageID,senderID:o.deltaRecallMessageData.senderID.toString(),deletionTimestamp:o.deltaRecallMessageData.deletionTimestamp,timestamp:o.deltaRecallMessageData.timestamp});else if(o.deltaRemoveMessage&&r.globalOptions.listenEvents)n(null,{type:"message_self_delete",threadID:(o.deltaRemoveMessage.threadKey.threadFbId?o.deltaRemoveMessage.threadKey.threadFbId:o.deltaRemoveMessage.threadKey.otherUserFbId).toString(),messageID:1==o.deltaRemoveMessage.messageIds.length?o.deltaRemoveMessage.messageIds[0]:o.deltaRemoveMessage.messageIds,senderID:s.getCurrentUserID(),deletionTimestamp:o.deltaRemoveMessage.deletionTimestamp,timestamp:o.deltaRemoveMessage.timestamp});else if(o.deltaMessageReply){let i=void 0===o.deltaMessageReply.message||void 0===o.deltaMessageReply.message.data||void 0===o.deltaMessageReply.message.data.prng?[]:JSON.parse(o.deltaMessageReply.message.data.prng),l=i.map((e=>e.i)),d=i.map((e=>e.o)),g=i.map((e=>e.l));const c={};for(let e=0;e<l.length;e++)c[l[e]]=(o.deltaMessageReply.message.body||"").substring(d[e],d[e]+g[e]);const p={type:"message_reply",threadID:(o.deltaMessageReply.message.messageMetadata.threadKey.threadFbId?o.deltaMessageReply.message.messageMetadata.threadKey.threadFbId:o.deltaMessageReply.message.messageMetadata.threadKey.otherUserFbId).toString(),messageID:o.deltaMessageReply.message.messageMetadata.messageId,senderID:o.deltaMessageReply.message.messageMetadata.actorFbId.toString(),attachments:o.deltaMessageReply.message.attachments?.map((function(e){const t=JSON.parse(e.mercuryJSON);return Object.assign(e,t),e})).map((t=>{let a;try{a=e._formatAttachment(t)}catch(e){a=t,a.error=e,a.type="unknown"}return a})),body:o.deltaMessageReply.message.body||"",isGroup:!!o.deltaMessageReply.message.messageMetadata.threadKey.threadFbId,mentions:c,timestamp:o.deltaMessageReply.message.messageMetadata.timestamp,participantIDs:(o.deltaMessageReply.message.participants||[]).map((e=>e.toString()))};if(o.deltaMessageReply.repliedToMessage){i=void 0===o.deltaMessageReply.repliedToMessage||void 0===o.deltaMessageReply.repliedToMessage.data||void 0===o.deltaMessageReply.repliedToMessage.data.prng?[]:JSON.parse(o.deltaMessageReply.repliedToMessage.data.prng),l=i.map((e=>e.i)),d=i.map((e=>e.o)),g=i.map((e=>e.l));const t={};for(let e=0;e<l.length;e++)t[l[e]]=(o.deltaMessageReply.repliedToMessage.body||"").substring(d[e],d[e]+g[e]);p.messageReply={threadID:(o.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId?o.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId:o.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.otherUserFbId).toString(),messageID:o.deltaMessageReply.repliedToMessage.messageMetadata.messageId,senderID:o.deltaMessageReply.repliedToMessage.messageMetadata.actorFbId.toString(),attachments:o.deltaMessageReply.repliedToMessage.attachments.map((function(e){const t=JSON.parse(e.mercuryJSON);return Object.assign(e,t),e})).map((t=>{let a;try{a=e._formatAttachment(t)}catch(e){a=t,a.error=e,a.type="unknown"}return a})),body:o.deltaMessageReply.repliedToMessage.body||"",isGroup:!!o.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId,mentions:t,timestamp:o.deltaMessageReply.repliedToMessage.messageMetadata.timestamp,participantIDs:(o.deltaMessageReply.repliedToMessage.participants||[]).map((e=>e.toString()))}}else{if(o.deltaMessageReply.replyToMessageId)return a.post("https://www.facebook.com/api/graphqlbatch/",r.jar,{av:r.globalOptions.pageID,queries:JSON.stringify({o0:{doc_id:"2848441488556444",query_params:{thread_and_message_id:{thread_id:p.threadID,message_id:o.deltaMessageReply.replyToMessageId.id}}}})}).then(e.parseAndCheckLogin(r,a)).then((t=>{if(t[t.length-1].error_results>0)throw t[0].o0.errors;if(0===t[t.length-1].successful_results)throw{error:"forcedFetch: there was no successful_results",res:t};const a=t[0].o0.data.message,s={};for(const e in a.message.ranges)s[a.message.ranges[e].entity.id]=(a.message.text||"").substr(a.message.ranges[e].offset,a.message.ranges[e].length);p.messageReply={threadID:p.threadID,messageID:a.message_id,senderID:a.message_sender.id.toString(),attachments:a.message.blob_attachment.map((t=>{let a;try{a=e._formatAttachment({blob_attachment:t})}catch(e){a=t,a.error=e,a.type="unknown"}return a})),body:a.message.text||"",isGroup:p.isGroup,mentions:s,timestamp:parseInt(a.timestamp_precise)}})).catch((e=>{t.error("forcedFetch",e)})).finally((function(){r.globalOptions.autoMarkDelivery&&m(r,s,p.threadID,p.messageID),(r.globalOptions.selfListen||p.senderID!==r.i_userID&&p.senderID!==r.userID)&&n(null,p)}));p.delta=o}return r.globalOptions.autoMarkDelivery&&m(r,s,p.threadID,p.messageID),r.globalOptions.selfListen||p.senderID!==r.i_userID&&p.senderID!==r.userID?void n(null,p):void 0}}return}}if("NewMessage"===i.delta.class||r.globalOptions.listenEvents)switch(i.delta.class){case"ReadReceipt":try{l=e.formatDeltaReadReceipt(i.delta)}catch(e){return n({error:"Problem parsing message object.",detail:e,res:i.delta,type:"parse_error"})}return void n(null,l);case"AdminTextMessage":switch(i.delta.type){case"change_thread_theme":case"change_thread_nickname":case"change_thread_icon":case"change_thread_admins":case"group_poll":var l;try{l=e.formatDeltaEvent(i.delta)}catch(e){return n({error:"Problem parsing message object.",detail:e,res:i.delta,type:"parse_error"})}return void n(null,l);default:return}case"ForcedFetch":if(!i.delta.threadKey)return;var d=i.delta.messageId,g=i.delta.threadKey.threadFbId;if(d&&g){const s={av:r.globalOptions.pageID,queries:JSON.stringify({o0:{doc_id:"2848441488556444",query_params:{thread_and_message_id:{thread_id:g.toString(),message_id:d}}}})};a.post("https://www.facebook.com/api/graphqlbatch/",r.jar,s).then(e.parseAndCheckLogin(r,a)).then((a=>{if(a[a.length-1].error_results>0)throw a[0].o0.errors;if(0===a[a.length-1].successful_results)throw{error:"forcedFetch: there was no successful_results",res:a};const s=a[0].o0.data.message;if("Object"==e.getType(s))switch(t.info("forcedFetch",s),s.__typename){case"ThreadImageMessage":(r.globalOptions.selfListenEvent||s.message_sender.id.toString()!==r.i_userID&&s.message_sender.id.toString()!==r.userID)&&r.loggedIn&&n(null,{type:"event",threadID:e.formatID(g.toString()),messageID:s.message_id,logMessageType:"log:thread-image",logMessageData:{attachmentID:s.image_with_metadata&&s.image_with_metadata.legacy_attachment_id,width:s.image_with_metadata&&s.image_with_metadata.original_dimensions.x,height:s.image_with_metadata&&s.image_with_metadata.original_dimensions.y,url:s.image_with_metadata&&s.image_with_metadata.preview.uri},logMessageBody:s.snippet,timestamp:s.timestamp_precise,author:s.message_sender.id});break;case"UserMessage":t.info("ff-Return",{type:"message",senderID:e.formatID(s.message_sender.id),body:s.message.text||"",threadID:e.formatID(g.toString()),messageID:s.message_id,attachments:[{type:"share",ID:s.extensible_attachment.legacy_attachment_id,url:s.extensible_attachment.story_attachment.url,title:s.extensible_attachment.story_attachment.title_with_entities.text,description:s.extensible_attachment.story_attachment.description.text,source:s.extensible_attachment.story_attachment.source,image:((s.extensible_attachment.story_attachment.media||{}).image||{}).uri,width:((s.extensible_attachment.story_attachment.media||{}).image||{}).width,height:((s.extensible_attachment.story_attachment.media||{}).image||{}).height,playable:(s.extensible_attachment.story_attachment.media||{}).is_playable||!1,duration:(s.extensible_attachment.story_attachment.media||{}).playable_duration_in_ms||0,subattachments:s.extensible_attachment.subattachments,properties:s.extensible_attachment.story_attachment.properties}],mentions:{},timestamp:parseInt(s.timestamp_precise),isGroup:s.message_sender.id!=g.toString()}),n(null,{type:"message",senderID:e.formatID(s.message_sender.id),body:s.message.text||"",threadID:e.formatID(g.toString()),messageID:s.message_id,attachments:[{type:"share",ID:s.extensible_attachment.legacy_attachment_id,url:s.extensible_attachment.story_attachment.url,title:s.extensible_attachment.story_attachment.title_with_entities.text,description:s.extensible_attachment.story_attachment.description.text,source:s.extensible_attachment.story_attachment.source,image:((s.extensible_attachment.story_attachment.media||{}).image||{}).uri,width:((s.extensible_attachment.story_attachment.media||{}).image||{}).width,height:((s.extensible_attachment.story_attachment.media||{}).image||{}).height,playable:(s.extensible_attachment.story_attachment.media||{}).is_playable||!1,duration:(s.extensible_attachment.story_attachment.media||{}).playable_duration_in_ms||0,subattachments:s.extensible_attachment.subattachments,properties:s.extensible_attachment.story_attachment.properties}],mentions:{},timestamp:parseInt(s.timestamp_precise),isGroup:s.message_sender.id!=g.toString()})}else t.error("forcedFetch",s)})).catch((e=>{t.error("forcedFetch",e)}))}break;case"ThreadName":case"ParticipantsAddedToGroupThread":case"ParticipantLeftGroupThread":case"ApprovalQueue":var c;try{c=e.formatDeltaEvent(i.delta)}catch(e){return n({error:"Problem parsing message object.",detail:e,res:i.delta,type:"parse_error"})}return(r.globalOptions.selfListenEvent||c.author.toString()!==r.i_userID&&c.author.toString()!==r.userID)&&r.loggedIn?void n(null,c):void 0}}function m(e,a,s,r){s&&r&&a.markAsDelivered(s,r,(r=>{r?t.error("markAsDelivered",r):e.globalOptions.autoMarkRead&&a.markAsRead(s,(e=>{e&&t.error("markAsDelivered",e)}))}))}module.exports=function(t,a,s){let r=i;return l=function(){return s.t_mqttCalled=!1,t.post("https://www.facebook.com/api/graphqlbatch/",s.jar,o).then(e.parseAndCheckLogin(s,t)).then((n=>{if("Array"!=e.getType(n)){const e=new Error("Not logged in");throw e.res=n,e.error="Not logged in",e}if(n&&n[n.length-1].error_results>0)throw n[0].o0.errors;if(0===n[n.length-1].successful_results)throw{error:"getSeqId: there was no successful_results",res:n};if(!n[0].o0.data.viewer.message_threads.sync_sequence_id){const e=new Error("No sync_sequence_id found.");throw e.res=n,e.error="getSeqId: no sync_sequence_id found.",e}s.lastSeqId=n[0].o0.data.viewer.message_threads.sync_sequence_id,g(t,a,s,r)})).catch((t=>{throw"Object"!=e.getType(t)||"Not logged in"!==t.error&&"Not logged in."!==t.error||(s.loggedIn=!1),t}))},function(e){const d=new class extends n{stopListening(e){e=e||(()=>{}),r=i,s.mqttClient&&(s.mqttClient.unsubscribe("/webrtc"),s.mqttClient.unsubscribe("/rtc_multi"),s.mqttClient.unsubscribe("/onevc"),s.mqttClient.publish("/browser_close","{}"),s.mqttClient.end(!1,(function(...t){e(t),s.mqttClient=void 0})))}async stopListeningSync(){return new Promise((e=>{this.stopListening(((...t)=>{e(t)}))}))}};return r=e||function(e,t){if(e)return d.emit("error",e);d.emit("message",t)},s.firstListen||(s.lastSeqId=null),s.syncToken=void 0,s.t_mqttCalled=!1,o={av:s.globalOptions.pageID,queries:JSON.stringify({o0:{doc_id:"3336396659757871",query_params:{limit:1,before:null,tags:["INBOX"],includeDeliveryReceipts:!1,includeSeqID:!0}}})},s.firstListen&&s.lastSeqId?g(t,a,s,r):l().catch((()=>{g(t,a,s,r)})),s.firstListen=!1,a.stopListening=d.stopListening,a.stopListeningSync=d.stopListeningSync,d}};