fca-smart-shankar 12.0.0 → 13.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (285) hide show
  1. package/.replit +12 -3
  2. package/.upm/store.json +1 -0
  3. package/CHANGELOG.md +2 -0
  4. package/README.md +0 -1
  5. package/generated-icon.png +0 -0
  6. package/index.js +507 -437
  7. package/package.json +378 -42
  8. package/replit.nix +3 -1
  9. package/shankar-fca.json +4 -0
  10. package/src/addUserToGroup.js +3 -3
  11. package/src/changeAdminStatus.js +2 -2
  12. package/src/changeArchivedStatus.js +2 -2
  13. package/src/changeAvatar.js +8 -8
  14. package/src/changeAvatarV2.js +1 -1
  15. package/src/changeBio.js +4 -4
  16. package/src/changeBlockedStatus.js +2 -2
  17. package/src/changeCover.js +2 -2
  18. package/src/changeGroupImage.js +4 -4
  19. package/src/changeName.js +2 -2
  20. package/src/changeNickname.js +2 -2
  21. package/src/changeThreadColor.js +3 -3
  22. package/src/changeThreadEmoji.js +2 -2
  23. package/src/changeUsername.js +3 -3
  24. package/src/createCommentPost.js +5 -5
  25. package/src/createNewGroup.js +5 -5
  26. package/src/createPoll.js +2 -2
  27. package/src/createPost.js +6 -5
  28. package/src/deleteMessage.js +2 -2
  29. package/src/deleteThread.js +2 -2
  30. package/src/editMessage.js +30 -18
  31. package/src/follow.js +8 -8
  32. package/src/forwardAttachment.js +2 -2
  33. package/src/getAccess.js +2 -2
  34. package/src/getAvatarUser.js +2 -2
  35. package/src/getCurrentUserID.js +4 -4
  36. package/src/getFriendsList.js +3 -3
  37. package/src/getMessage.js +2 -2
  38. package/src/getThreadHistory.js +2 -2
  39. package/src/getThreadHistoryDeprecated.js +2 -2
  40. package/src/getThreadInfo.js +1 -1
  41. package/src/getThreadInfoDeprecated.js +2 -2
  42. package/src/getThreadList.js +3 -3
  43. package/src/getThreadListDeprecated.js +3 -3
  44. package/src/getThreadPictures.js +2 -2
  45. package/src/getUID.js +4 -4
  46. package/src/getUserID.js +3 -3
  47. package/src/getUserInfo.js +52 -18
  48. package/src/handleFriendRequest.js +5 -5
  49. package/src/handleMessageRequest.js +2 -2
  50. package/src/httpGet.js +3 -3
  51. package/src/httpPost.js +3 -3
  52. package/src/httpPostFormData.js +3 -3
  53. package/src/listenMqtt.js +648 -659
  54. package/src/listenNotification.js +1 -1
  55. package/src/logout.js +3 -3
  56. package/src/markAsDelivered.js +5 -2
  57. package/src/markAsRead.js +5 -2
  58. package/src/markAsReadAll.js +2 -2
  59. package/src/markAsSeen.js +2 -2
  60. package/src/muteThread.js +2 -2
  61. package/src/refreshFb_dtsg.js +3 -3
  62. package/src/removeUserFromGroup.js +2 -2
  63. package/src/resolvePhotoUrl.js +2 -2
  64. package/src/searchStickers.js +1 -1
  65. package/src/sendMessage.js +11 -8
  66. package/src/sendMessageMqtt.js +4 -4
  67. package/src/sendTypingIndicator.js +14 -5
  68. package/src/sendTypingIndicatorV2.js +1 -1
  69. package/src/setMessageReaction.js +3 -3
  70. package/src/setPostReaction.js +4 -4
  71. package/src/setProfileGuard.js +3 -3
  72. package/src/setStoryReaction.js +1 -1
  73. package/src/setTitle.js +3 -3
  74. package/src/shareContact.js +1 -1
  75. package/src/shareLink.js +1 -1
  76. package/src/stopListenMqtt.js +5 -2
  77. package/src/unfriend.js +2 -2
  78. package/src/unsendMessage.js +2 -2
  79. package/src/uploadAttachment.js +2 -2
  80. package/test/data/shareAttach.js +146 -0
  81. package/test/data/something.mov +0 -0
  82. package/test/data/test.png +0 -0
  83. package/test/data/test.txt +7 -0
  84. package/test/test-page.js +1 -1
  85. package/utils.js +564 -391
  86. package/.cache/nix/binary-cache-v6.sqlite +0 -0
  87. package/.cache/nix/binary-cache-v6.sqlite-journal +0 -0
  88. package/.cache/replit/env/latest +0 -125
  89. package/.cache/replit/env/latest.json +0 -1
  90. package/.cache/replit/modules/nix.res +0 -1
  91. package/.cache/replit/modules/nodejs-20.res +0 -1
  92. package/.cache/replit/modules/replit.res +0 -1
  93. package/.cache/replit/modules.stamp +0 -0
  94. package/.cache/replit/nix/env.json +0 -1
  95. package/.cache/typescript/5.6/node_modules/.package-lock.json +0 -171
  96. package/.cache/typescript/5.6/node_modules/@types/bluebird/LICENSE +0 -21
  97. package/.cache/typescript/5.6/node_modules/@types/bluebird/README.md +0 -15
  98. package/.cache/typescript/5.6/node_modules/@types/bluebird/index.d.ts +0 -1365
  99. package/.cache/typescript/5.6/node_modules/@types/bluebird/package.json +0 -25
  100. package/.cache/typescript/5.6/node_modules/@types/caseless/LICENSE +0 -21
  101. package/.cache/typescript/5.6/node_modules/@types/caseless/README.md +0 -48
  102. package/.cache/typescript/5.6/node_modules/@types/caseless/index.d.ts +0 -29
  103. package/.cache/typescript/5.6/node_modules/@types/caseless/package.json +0 -35
  104. package/.cache/typescript/5.6/node_modules/@types/cheerio/LICENSE +0 -21
  105. package/.cache/typescript/5.6/node_modules/@types/cheerio/README.md +0 -15
  106. package/.cache/typescript/5.6/node_modules/@types/cheerio/index.d.ts +0 -318
  107. package/.cache/typescript/5.6/node_modules/@types/cheerio/package.json +0 -71
  108. package/.cache/typescript/5.6/node_modules/@types/mocha/LICENSE +0 -21
  109. package/.cache/typescript/5.6/node_modules/@types/mocha/README.md +0 -15
  110. package/.cache/typescript/5.6/node_modules/@types/mocha/index.d.ts +0 -2929
  111. package/.cache/typescript/5.6/node_modules/@types/mocha/package.json +0 -56
  112. package/.cache/typescript/5.6/node_modules/@types/node/LICENSE +0 -21
  113. package/.cache/typescript/5.6/node_modules/@types/node/README.md +0 -15
  114. package/.cache/typescript/5.6/node_modules/@types/node/assert/strict.d.ts +0 -8
  115. package/.cache/typescript/5.6/node_modules/@types/node/assert.d.ts +0 -1040
  116. package/.cache/typescript/5.6/node_modules/@types/node/async_hooks.d.ts +0 -541
  117. package/.cache/typescript/5.6/node_modules/@types/node/buffer.buffer.d.ts +0 -385
  118. package/.cache/typescript/5.6/node_modules/@types/node/buffer.d.ts +0 -1933
  119. package/.cache/typescript/5.6/node_modules/@types/node/child_process.d.ts +0 -1549
  120. package/.cache/typescript/5.6/node_modules/@types/node/cluster.d.ts +0 -579
  121. package/.cache/typescript/5.6/node_modules/@types/node/compatibility/disposable.d.ts +0 -16
  122. package/.cache/typescript/5.6/node_modules/@types/node/compatibility/index.d.ts +0 -9
  123. package/.cache/typescript/5.6/node_modules/@types/node/compatibility/indexable.d.ts +0 -23
  124. package/.cache/typescript/5.6/node_modules/@types/node/compatibility/iterators.d.ts +0 -21
  125. package/.cache/typescript/5.6/node_modules/@types/node/console.d.ts +0 -452
  126. package/.cache/typescript/5.6/node_modules/@types/node/constants.d.ts +0 -19
  127. package/.cache/typescript/5.6/node_modules/@types/node/crypto.d.ts +0 -4475
  128. package/.cache/typescript/5.6/node_modules/@types/node/dgram.d.ts +0 -596
  129. package/.cache/typescript/5.6/node_modules/@types/node/diagnostics_channel.d.ts +0 -554
  130. package/.cache/typescript/5.6/node_modules/@types/node/dns/promises.d.ts +0 -476
  131. package/.cache/typescript/5.6/node_modules/@types/node/dns.d.ts +0 -865
  132. package/.cache/typescript/5.6/node_modules/@types/node/dom-events.d.ts +0 -124
  133. package/.cache/typescript/5.6/node_modules/@types/node/domain.d.ts +0 -170
  134. package/.cache/typescript/5.6/node_modules/@types/node/events.d.ts +0 -931
  135. package/.cache/typescript/5.6/node_modules/@types/node/fs/promises.d.ts +0 -1275
  136. package/.cache/typescript/5.6/node_modules/@types/node/fs.d.ts +0 -4396
  137. package/.cache/typescript/5.6/node_modules/@types/node/globals.d.ts +0 -566
  138. package/.cache/typescript/5.6/node_modules/@types/node/globals.typedarray.d.ts +0 -21
  139. package/.cache/typescript/5.6/node_modules/@types/node/http.d.ts +0 -1958
  140. package/.cache/typescript/5.6/node_modules/@types/node/http2.d.ts +0 -2558
  141. package/.cache/typescript/5.6/node_modules/@types/node/https.d.ts +0 -543
  142. package/.cache/typescript/5.6/node_modules/@types/node/index.d.ts +0 -92
  143. package/.cache/typescript/5.6/node_modules/@types/node/inspector.d.ts +0 -3966
  144. package/.cache/typescript/5.6/node_modules/@types/node/module.d.ts +0 -402
  145. package/.cache/typescript/5.6/node_modules/@types/node/net.d.ts +0 -1001
  146. package/.cache/typescript/5.6/node_modules/@types/node/os.d.ts +0 -495
  147. package/.cache/typescript/5.6/node_modules/@types/node/package.json +0 -220
  148. package/.cache/typescript/5.6/node_modules/@types/node/path.d.ts +0 -200
  149. package/.cache/typescript/5.6/node_modules/@types/node/perf_hooks.d.ts +0 -965
  150. package/.cache/typescript/5.6/node_modules/@types/node/process.d.ts +0 -1963
  151. package/.cache/typescript/5.6/node_modules/@types/node/punycode.d.ts +0 -117
  152. package/.cache/typescript/5.6/node_modules/@types/node/querystring.d.ts +0 -153
  153. package/.cache/typescript/5.6/node_modules/@types/node/readline/promises.d.ts +0 -162
  154. package/.cache/typescript/5.6/node_modules/@types/node/readline.d.ts +0 -589
  155. package/.cache/typescript/5.6/node_modules/@types/node/repl.d.ts +0 -430
  156. package/.cache/typescript/5.6/node_modules/@types/node/sea.d.ts +0 -153
  157. package/.cache/typescript/5.6/node_modules/@types/node/sqlite.d.ts +0 -213
  158. package/.cache/typescript/5.6/node_modules/@types/node/stream/consumers.d.ts +0 -12
  159. package/.cache/typescript/5.6/node_modules/@types/node/stream/promises.d.ts +0 -90
  160. package/.cache/typescript/5.6/node_modules/@types/node/stream/web.d.ts +0 -609
  161. package/.cache/typescript/5.6/node_modules/@types/node/stream.d.ts +0 -1726
  162. package/.cache/typescript/5.6/node_modules/@types/node/string_decoder.d.ts +0 -67
  163. package/.cache/typescript/5.6/node_modules/@types/node/test.d.ts +0 -2248
  164. package/.cache/typescript/5.6/node_modules/@types/node/timers/promises.d.ts +0 -97
  165. package/.cache/typescript/5.6/node_modules/@types/node/timers.d.ts +0 -240
  166. package/.cache/typescript/5.6/node_modules/@types/node/tls.d.ts +0 -1226
  167. package/.cache/typescript/5.6/node_modules/@types/node/trace_events.d.ts +0 -197
  168. package/.cache/typescript/5.6/node_modules/@types/node/ts5.6/buffer.buffer.d.ts +0 -385
  169. package/.cache/typescript/5.6/node_modules/@types/node/ts5.6/globals.typedarray.d.ts +0 -19
  170. package/.cache/typescript/5.6/node_modules/@types/node/ts5.6/index.d.ts +0 -92
  171. package/.cache/typescript/5.6/node_modules/@types/node/tty.d.ts +0 -208
  172. package/.cache/typescript/5.6/node_modules/@types/node/url.d.ts +0 -972
  173. package/.cache/typescript/5.6/node_modules/@types/node/util.d.ts +0 -2371
  174. package/.cache/typescript/5.6/node_modules/@types/node/v8.d.ts +0 -808
  175. package/.cache/typescript/5.6/node_modules/@types/node/vm.d.ts +0 -976
  176. package/.cache/typescript/5.6/node_modules/@types/node/wasi.d.ts +0 -181
  177. package/.cache/typescript/5.6/node_modules/@types/node/worker_threads.d.ts +0 -745
  178. package/.cache/typescript/5.6/node_modules/@types/node/zlib.d.ts +0 -539
  179. package/.cache/typescript/5.6/node_modules/@types/request/LICENSE +0 -21
  180. package/.cache/typescript/5.6/node_modules/@types/request/README.md +0 -15
  181. package/.cache/typescript/5.6/node_modules/@types/request/index.d.ts +0 -395
  182. package/.cache/typescript/5.6/node_modules/@types/request/package.json +0 -70
  183. package/.cache/typescript/5.6/node_modules/@types/tough-cookie/LICENSE +0 -21
  184. package/.cache/typescript/5.6/node_modules/@types/tough-cookie/README.md +0 -15
  185. package/.cache/typescript/5.6/node_modules/@types/tough-cookie/index.d.ts +0 -321
  186. package/.cache/typescript/5.6/node_modules/@types/tough-cookie/package.json +0 -35
  187. package/.cache/typescript/5.6/node_modules/asynckit/LICENSE +0 -21
  188. package/.cache/typescript/5.6/node_modules/asynckit/README.md +0 -233
  189. package/.cache/typescript/5.6/node_modules/asynckit/bench.js +0 -76
  190. package/.cache/typescript/5.6/node_modules/asynckit/index.js +0 -6
  191. package/.cache/typescript/5.6/node_modules/asynckit/lib/abort.js +0 -29
  192. package/.cache/typescript/5.6/node_modules/asynckit/lib/async.js +0 -34
  193. package/.cache/typescript/5.6/node_modules/asynckit/lib/defer.js +0 -26
  194. package/.cache/typescript/5.6/node_modules/asynckit/lib/iterate.js +0 -75
  195. package/.cache/typescript/5.6/node_modules/asynckit/lib/readable_asynckit.js +0 -91
  196. package/.cache/typescript/5.6/node_modules/asynckit/lib/readable_parallel.js +0 -25
  197. package/.cache/typescript/5.6/node_modules/asynckit/lib/readable_serial.js +0 -25
  198. package/.cache/typescript/5.6/node_modules/asynckit/lib/readable_serial_ordered.js +0 -29
  199. package/.cache/typescript/5.6/node_modules/asynckit/lib/state.js +0 -37
  200. package/.cache/typescript/5.6/node_modules/asynckit/lib/streamify.js +0 -141
  201. package/.cache/typescript/5.6/node_modules/asynckit/lib/terminator.js +0 -29
  202. package/.cache/typescript/5.6/node_modules/asynckit/package.json +0 -63
  203. package/.cache/typescript/5.6/node_modules/asynckit/parallel.js +0 -43
  204. package/.cache/typescript/5.6/node_modules/asynckit/serial.js +0 -17
  205. package/.cache/typescript/5.6/node_modules/asynckit/serialOrdered.js +0 -75
  206. package/.cache/typescript/5.6/node_modules/asynckit/stream.js +0 -21
  207. package/.cache/typescript/5.6/node_modules/combined-stream/License +0 -19
  208. package/.cache/typescript/5.6/node_modules/combined-stream/Readme.md +0 -138
  209. package/.cache/typescript/5.6/node_modules/combined-stream/lib/combined_stream.js +0 -208
  210. package/.cache/typescript/5.6/node_modules/combined-stream/package.json +0 -25
  211. package/.cache/typescript/5.6/node_modules/combined-stream/yarn.lock +0 -17
  212. package/.cache/typescript/5.6/node_modules/delayed-stream/License +0 -19
  213. package/.cache/typescript/5.6/node_modules/delayed-stream/Makefile +0 -7
  214. package/.cache/typescript/5.6/node_modules/delayed-stream/Readme.md +0 -141
  215. package/.cache/typescript/5.6/node_modules/delayed-stream/lib/delayed_stream.js +0 -107
  216. package/.cache/typescript/5.6/node_modules/delayed-stream/package.json +0 -27
  217. package/.cache/typescript/5.6/node_modules/form-data/License +0 -19
  218. package/.cache/typescript/5.6/node_modules/form-data/Readme.md +0 -350
  219. package/.cache/typescript/5.6/node_modules/form-data/index.d.ts +0 -51
  220. package/.cache/typescript/5.6/node_modules/form-data/lib/browser.js +0 -2
  221. package/.cache/typescript/5.6/node_modules/form-data/lib/form_data.js +0 -484
  222. package/.cache/typescript/5.6/node_modules/form-data/lib/populate.js +0 -10
  223. package/.cache/typescript/5.6/node_modules/form-data/package.json +0 -72
  224. package/.cache/typescript/5.6/node_modules/mime-db/HISTORY.md +0 -507
  225. package/.cache/typescript/5.6/node_modules/mime-db/LICENSE +0 -23
  226. package/.cache/typescript/5.6/node_modules/mime-db/README.md +0 -100
  227. package/.cache/typescript/5.6/node_modules/mime-db/db.json +0 -8519
  228. package/.cache/typescript/5.6/node_modules/mime-db/index.js +0 -12
  229. package/.cache/typescript/5.6/node_modules/mime-db/package.json +0 -60
  230. package/.cache/typescript/5.6/node_modules/mime-types/HISTORY.md +0 -397
  231. package/.cache/typescript/5.6/node_modules/mime-types/LICENSE +0 -23
  232. package/.cache/typescript/5.6/node_modules/mime-types/README.md +0 -113
  233. package/.cache/typescript/5.6/node_modules/mime-types/index.js +0 -188
  234. package/.cache/typescript/5.6/node_modules/mime-types/package.json +0 -44
  235. package/.cache/typescript/5.6/node_modules/safe-buffer/LICENSE +0 -21
  236. package/.cache/typescript/5.6/node_modules/safe-buffer/README.md +0 -584
  237. package/.cache/typescript/5.6/node_modules/safe-buffer/index.d.ts +0 -187
  238. package/.cache/typescript/5.6/node_modules/safe-buffer/index.js +0 -65
  239. package/.cache/typescript/5.6/node_modules/safe-buffer/package.json +0 -51
  240. package/.cache/typescript/5.6/node_modules/types-registry/README.md +0 -2
  241. package/.cache/typescript/5.6/node_modules/types-registry/index.json +0 -1
  242. package/.cache/typescript/5.6/node_modules/types-registry/package.json +0 -20
  243. package/.cache/typescript/5.6/node_modules/undici-types/LICENSE +0 -21
  244. package/.cache/typescript/5.6/node_modules/undici-types/README.md +0 -6
  245. package/.cache/typescript/5.6/node_modules/undici-types/agent.d.ts +0 -31
  246. package/.cache/typescript/5.6/node_modules/undici-types/api.d.ts +0 -43
  247. package/.cache/typescript/5.6/node_modules/undici-types/balanced-pool.d.ts +0 -29
  248. package/.cache/typescript/5.6/node_modules/undici-types/cache.d.ts +0 -36
  249. package/.cache/typescript/5.6/node_modules/undici-types/client.d.ts +0 -108
  250. package/.cache/typescript/5.6/node_modules/undici-types/connector.d.ts +0 -34
  251. package/.cache/typescript/5.6/node_modules/undici-types/content-type.d.ts +0 -21
  252. package/.cache/typescript/5.6/node_modules/undici-types/cookies.d.ts +0 -28
  253. package/.cache/typescript/5.6/node_modules/undici-types/diagnostics-channel.d.ts +0 -66
  254. package/.cache/typescript/5.6/node_modules/undici-types/dispatcher.d.ts +0 -255
  255. package/.cache/typescript/5.6/node_modules/undici-types/env-http-proxy-agent.d.ts +0 -21
  256. package/.cache/typescript/5.6/node_modules/undici-types/errors.d.ts +0 -149
  257. package/.cache/typescript/5.6/node_modules/undici-types/eventsource.d.ts +0 -61
  258. package/.cache/typescript/5.6/node_modules/undici-types/fetch.d.ts +0 -209
  259. package/.cache/typescript/5.6/node_modules/undici-types/file.d.ts +0 -39
  260. package/.cache/typescript/5.6/node_modules/undici-types/filereader.d.ts +0 -54
  261. package/.cache/typescript/5.6/node_modules/undici-types/formdata.d.ts +0 -108
  262. package/.cache/typescript/5.6/node_modules/undici-types/global-dispatcher.d.ts +0 -9
  263. package/.cache/typescript/5.6/node_modules/undici-types/global-origin.d.ts +0 -7
  264. package/.cache/typescript/5.6/node_modules/undici-types/handlers.d.ts +0 -15
  265. package/.cache/typescript/5.6/node_modules/undici-types/header.d.ts +0 -4
  266. package/.cache/typescript/5.6/node_modules/undici-types/index.d.ts +0 -71
  267. package/.cache/typescript/5.6/node_modules/undici-types/interceptors.d.ts +0 -17
  268. package/.cache/typescript/5.6/node_modules/undici-types/mock-agent.d.ts +0 -50
  269. package/.cache/typescript/5.6/node_modules/undici-types/mock-client.d.ts +0 -25
  270. package/.cache/typescript/5.6/node_modules/undici-types/mock-errors.d.ts +0 -12
  271. package/.cache/typescript/5.6/node_modules/undici-types/mock-interceptor.d.ts +0 -93
  272. package/.cache/typescript/5.6/node_modules/undici-types/mock-pool.d.ts +0 -25
  273. package/.cache/typescript/5.6/node_modules/undici-types/package.json +0 -55
  274. package/.cache/typescript/5.6/node_modules/undici-types/patch.d.ts +0 -33
  275. package/.cache/typescript/5.6/node_modules/undici-types/pool-stats.d.ts +0 -19
  276. package/.cache/typescript/5.6/node_modules/undici-types/pool.d.ts +0 -39
  277. package/.cache/typescript/5.6/node_modules/undici-types/proxy-agent.d.ts +0 -28
  278. package/.cache/typescript/5.6/node_modules/undici-types/readable.d.ts +0 -60
  279. package/.cache/typescript/5.6/node_modules/undici-types/retry-agent.d.ts +0 -8
  280. package/.cache/typescript/5.6/node_modules/undici-types/retry-handler.d.ts +0 -116
  281. package/.cache/typescript/5.6/node_modules/undici-types/util.d.ts +0 -18
  282. package/.cache/typescript/5.6/node_modules/undici-types/webidl.d.ts +0 -222
  283. package/.cache/typescript/5.6/node_modules/undici-types/websocket.d.ts +0 -150
  284. package/.cache/typescript/5.6/package-lock.json +0 -183
  285. package/.cache/typescript/5.6/package.json +0 -1
package/src/listenMqtt.js CHANGED
@@ -1,14 +1,16 @@
1
+
2
+
1
3
  "use strict";
2
4
  var utils = require("../utils");
3
- // @NethWs3Dev
5
+ var log = require("npmlog");
4
6
  var mqtt = require('mqtt');
5
7
  var websocket = require('websocket-stream');
6
8
  var HttpsProxyAgent = require('https-proxy-agent');
7
9
  const EventEmitter = require('events');
8
10
 
9
- var identity = function() {};
11
+ var identity = function () { };
10
12
  var form = {};
11
- var getSeqID = function() {};
13
+ var getSeqID = function () { };
12
14
 
13
15
  var topics = [
14
16
  "/legacy_web",
@@ -35,669 +37,656 @@ var topics = [
35
37
  ];
36
38
 
37
39
  function listenMqtt(defaultFuncs, api, ctx, globalCallback) {
38
- //Don't really know what this does but I think it's for the active state?
39
- //TODO: Move to ctx when implemented
40
- var chatOn = ctx.globalOptions.online;
41
- var foreground = false;
42
-
43
- const sessionID = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER) + 1;
44
- const GUID = utils.getGUID()
45
- const username = {
46
- u: ctx.userID,
47
- s: sessionID,
48
- chat_on: chatOn,
49
- fg: foreground,
50
- d: GUID,
51
- ct: 'websocket',
52
- aid: '219994525426954',
53
- aids: null,
54
- mqtt_sid: '',
55
- cp: 3,
56
- ecp: 10,
57
- st: [],
58
- pm: [],
59
- dc: '',
60
- no_auto_fg: true,
61
- gas: null,
62
- pack: [],
63
- a: ctx.globalOptions.userAgent,
64
- p: null,
65
- aids: null,
66
- php_override: ""
67
- };
68
-
69
- const cookies = ctx.jar.getCookies('https://www.facebook.com').join('; ');
70
-
71
- let host;
72
- if (ctx.mqttEndpoint) {
73
- host = `${ctx.mqttEndpoint}&sid=${sessionID}`;
74
- } else if (ctx.region) {
75
- host = `wss://edge-chat.facebook.com/chat?region=${ctx.region.toLowerCase()}&sid=${sessionID}`;
76
- } else {
77
- host = `wss://edge-chat.facebook.com/chat?sid=${sessionID}`;
78
- }
79
-
80
- const options = {
81
- clientId: 'mqttwsclient',
82
- protocolId: 'MQIsdp',
83
- protocolVersion: 3,
84
- username: JSON.stringify(username),
85
- clean: true,
86
- wsOptions: {
87
- headers: {
88
- Cookie: cookies,
89
- Origin: 'https://www.facebook.com',
90
- 'User-Agent': ctx.globalOptions.userAgent || 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36',
91
- Referer: 'https://www.facebook.com/',
92
- Host: new URL(host).hostname,
93
- },
94
- origin: 'https://www.facebook.com',
95
- protocolVersion: 13,
96
- binaryType: 'arraybuffer',
97
- },
98
- keepalive: 60,
99
- reschedulePings: true,
100
- reconnectPeriod: 3,
101
- };
102
-
103
- if (typeof ctx.globalOptions.proxy != "undefined") {
104
- var agent = new HttpsProxyAgent(ctx.globalOptions.proxy);
105
- options.wsOptions.agent = agent;
106
- }
107
-
108
- ctx.mqttClient = new mqtt.Client(_ => websocket(host, options.wsOptions), options);
109
-
110
- var mqttClient = ctx.mqttClient;
111
-
112
-
113
- function stopListening() {
114
- if (mqttClient) {
115
- mqttClient.unsubscribe("/webrtc");
116
- mqttClient.unsubscribe("/rtc_multi");
117
- mqttClient.unsubscribe("/onevc");
118
- mqttClient.publish("/browser_close", "{}");
119
- mqttClient.end(false, function(...data) {
120
- ctx.mqttClient = null; mqttClient = null;
121
- });
122
- }
123
- }
124
-
125
- mqttClient.on('error', function(err) {
126
- stopListening();
127
- if (ctx.globalOptions.autoReconnect) {
128
- getSeqID();
129
- } else {
130
- globalCallback({ type: "stop_listen", error: "Connection refused: Server unavailable" }, null);
131
- }
132
- console.warn("login", "Error detected. Will relogin automatically...");
133
- api.ws3.relogin();
134
- return;
135
- });
136
-
137
- mqttClient.on('connect', function() {
138
- topics.forEach(topicsub => mqttClient.subscribe(topicsub));
139
- var topic;
140
- var queue = {
141
- sync_api_version: 10,
142
- max_deltas_able_to_process: 1000,
143
- delta_batch_size: 500,
144
- encoding: "JSON",
145
- entity_fbid: ctx.userID,
146
- };
147
-
148
- if (ctx.syncToken) {
149
- topic = "/messenger_sync_get_diffs";
150
- queue.last_seq_id = ctx.lastSeqId;
151
- queue.sync_token = ctx.syncToken;
152
- } else {
153
- topic = "/messenger_sync_create_queue";
154
- queue.initial_titan_sequence_id = ctx.lastSeqId;
155
- queue.device_params = null;
156
- }
157
-
158
- mqttClient.publish(topic, JSON.stringify(queue), { qos: 1, retain: false });
159
- mqttClient.publish("/foreground_state", JSON.stringify({ "foreground": chatOn }), { qos: 1 });
160
- var rTimeout = setTimeout(function() {
161
- mqttClient.end();
162
- getSeqID();
163
- }, 3000);
164
-
165
- ctx.tmsWait = function() {
166
- clearTimeout(rTimeout);
167
- ctx.globalOptions.emitReady ? globalCallback({
168
- type: "ready",
169
- error: null
170
- }) : "";
171
- delete ctx.tmsWait;
172
- };
173
- });
174
-
175
- mqttClient.on('message', function(topic, message, _packet) {
176
- try {
177
- var jsonMessage = JSON.parse(message);
178
- } catch (ex) {
179
- return console.error("listenMqtt", ex);
180
- }
181
- if (topic === "/t_ms") {
182
- if (ctx.tmsWait && typeof ctx.tmsWait == "function") ctx.tmsWait();
183
-
184
- if (jsonMessage.firstDeltaSeqId && jsonMessage.syncToken) {
185
- ctx.lastSeqId = jsonMessage.firstDeltaSeqId;
186
- ctx.syncToken = jsonMessage.syncToken;
187
- }
188
-
189
- if (jsonMessage.lastIssuedSeqId) ctx.lastSeqId = parseInt(jsonMessage.lastIssuedSeqId);
190
-
191
- //If it contains more than 1 delta
192
- for (var i in jsonMessage.deltas) {
193
- var delta = jsonMessage.deltas[i];
194
- parseDelta(defaultFuncs, api, ctx, globalCallback, { "delta": delta });
195
- }
196
- } else if (topic === "/thread_typing" || topic === "/orca_typing_notifications") {
197
- var typ = {
198
- type: "typ",
199
- isTyping: !!jsonMessage.state,
200
- from: jsonMessage.sender_fbid.toString(),
201
- threadID: utils.formatID((jsonMessage.thread || jsonMessage.sender_fbid).toString())
202
- };
203
- (function() { globalCallback(null, typ); })();
204
- } else if (topic === "/orca_presence") {
205
- if (!ctx.globalOptions.updatePresence) {
206
- for (var i in jsonMessage.list) {
207
- var data = jsonMessage.list[i];
208
- var userID = data["u"];
209
-
210
- var presence = {
211
- type: "presence",
212
- userID: userID.toString(),
213
- //Convert to ms
214
- timestamp: data["l"] * 1000,
215
- statuses: data["p"]
216
- };
217
- (function() { globalCallback(null, presence); })();
218
- }
219
- }
220
- }
221
-
222
- });
223
-
224
- mqttClient.on('close', function() {
225
- //(function () { globalCallback("Connection closed."); })();
226
- // client.end();
227
- });
40
+ //Don't really know what this does but I think it's for the active state?
41
+ //TODO: Move to ctx when implemented
42
+ var chatOn = ctx.globalOptions.online;
43
+ var foreground = false;
44
+
45
+ const sessionID = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER) + 1;
46
+ const GUID = utils.getGUID()
47
+ const username = {
48
+ u: ctx.userID,
49
+ s: sessionID,
50
+ chat_on: chatOn,
51
+ fg: foreground,
52
+ d: GUID,
53
+ ct: 'websocket',
54
+ aid: '219994525426954',
55
+ aids: null,
56
+ mqtt_sid: '',
57
+ cp: 3,
58
+ ecp: 10,
59
+ st: [],
60
+ pm: [],
61
+ dc: '',
62
+ no_auto_fg: true,
63
+ gas: null,
64
+ pack: [],
65
+ a: ctx.globalOptions.userAgent,
66
+ p: null,
67
+ aids: null,
68
+ php_override: ""
69
+ };
70
+
71
+ const cookies = ctx.jar.getCookies('https://www.facebook.com').join('; ');
72
+
73
+ let host;
74
+ if (ctx.mqttEndpoint) {
75
+ host = `${ctx.mqttEndpoint}&sid=${sessionID}`;
76
+ } else if (ctx.region) {
77
+ host = `wss://edge-chat.facebook.com/chat?region=${ctx.region.toLowerCase()}&sid=${sessionID}`;
78
+ } else {
79
+ host = `wss://edge-chat.facebook.com/chat?sid=${sessionID}`;
80
+ }
81
+
82
+ const options = {
83
+ clientId: 'mqttwsclient',
84
+ protocolId: 'MQIsdp',
85
+ protocolVersion: 3,
86
+ username: JSON.stringify(username),
87
+ clean: true,
88
+ wsOptions: {
89
+ headers: {
90
+ Cookie: cookies,
91
+ Origin: 'https://www.facebook.com',
92
+ 'User-Agent': ctx.globalOptions.userAgent || 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36',
93
+ Referer: 'https://www.facebook.com/',
94
+ Host: new URL(host).hostname,
95
+ },
96
+ origin: 'https://www.facebook.com',
97
+ protocolVersion: 13,
98
+ binaryType: 'arraybuffer',
99
+ },
100
+ keepalive: 60,
101
+ reschedulePings: true,
102
+ reconnectPeriod: 3,
103
+ };
104
+
105
+ if (typeof ctx.globalOptions.proxy != "undefined") {
106
+ var agent = new HttpsProxyAgent(ctx.globalOptions.proxy);
107
+ options.wsOptions.agent = agent;
108
+ }
109
+
110
+ ctx.mqttClient = new mqtt.Client(_ => websocket(host, options.wsOptions), options);
111
+
112
+ var mqttClient = ctx.mqttClient;
113
+
114
+ mqttClient.on('error', function (err) {
115
+ log.error("listenMqtt", err);
116
+ mqttClient.end();
117
+ if (ctx.globalOptions.autoReconnect) getSeqID();
118
+ else globalCallback({ type: "stop_listen", error: "Connection refused: Server unavailable" }, null);
119
+ });
120
+
121
+ mqttClient.on('connect', function () {
122
+ topics.forEach(topicsub => mqttClient.subscribe(topicsub));
123
+
124
+ var topic;
125
+ var queue = {
126
+ sync_api_version: 10,
127
+ max_deltas_able_to_process: 1000,
128
+ delta_batch_size: 500,
129
+ encoding: "JSON",
130
+ entity_fbid: ctx.userID,
131
+ };
132
+
133
+ if (ctx.syncToken) {
134
+ topic = "/messenger_sync_get_diffs";
135
+ queue.last_seq_id = ctx.lastSeqId;
136
+ queue.sync_token = ctx.syncToken;
137
+ } else {
138
+ topic = "/messenger_sync_create_queue";
139
+ queue.initial_titan_sequence_id = ctx.lastSeqId;
140
+ queue.device_params = null;
141
+ }
142
+
143
+ mqttClient.publish(topic, JSON.stringify(queue), { qos: 1, retain: false });
144
+ mqttClient.publish("/foreground_state", JSON.stringify({ "foreground": chatOn }), { qos: 1 });
145
+ var rTimeout = setTimeout(function () {
146
+ mqttClient.end();
147
+ getSeqID();
148
+ }, 3000);
149
+
150
+ ctx.tmsWait = function () {
151
+ clearTimeout(rTimeout);
152
+ ctx.globalOptions.emitReady ? globalCallback({
153
+ type: "ready",
154
+ error: null
155
+ }) : "";
156
+ delete ctx.tmsWait;
157
+ };
158
+ });
159
+
160
+ mqttClient.on('message', function (topic, message, _packet) {
161
+ try {
162
+ var jsonMessage = JSON.parse(message);
163
+ } catch (ex) {
164
+ return log.error("listenMqtt", ex);
165
+ }
166
+ if (topic === "/t_ms") {
167
+ if (ctx.tmsWait && typeof ctx.tmsWait == "function") ctx.tmsWait();
168
+
169
+ if (jsonMessage.firstDeltaSeqId && jsonMessage.syncToken) {
170
+ ctx.lastSeqId = jsonMessage.firstDeltaSeqId;
171
+ ctx.syncToken = jsonMessage.syncToken;
172
+ }
173
+
174
+ if (jsonMessage.lastIssuedSeqId) ctx.lastSeqId = parseInt(jsonMessage.lastIssuedSeqId);
175
+
176
+ //If it contains more than 1 delta
177
+ for (var i in jsonMessage.deltas) {
178
+ var delta = jsonMessage.deltas[i];
179
+ parseDelta(defaultFuncs, api, ctx, globalCallback, { "delta": delta });
180
+ }
181
+ } else if (topic === "/thread_typing" || topic === "/orca_typing_notifications") {
182
+ var typ = {
183
+ type: "typ",
184
+ isTyping: !!jsonMessage.state,
185
+ from: jsonMessage.sender_fbid.toString(),
186
+ threadID: utils.formatID((jsonMessage.thread || jsonMessage.sender_fbid).toString())
187
+ };
188
+ (function () { globalCallback(null, typ); })();
189
+ } else if (topic === "/orca_presence") {
190
+ if (!ctx.globalOptions.updatePresence) {
191
+ for (var i in jsonMessage.list) {
192
+ var data = jsonMessage.list[i];
193
+ var userID = data["u"];
194
+
195
+ var presence = {
196
+ type: "presence",
197
+ userID: userID.toString(),
198
+ //Convert to ms
199
+ timestamp: data["l"] * 1000,
200
+ statuses: data["p"]
201
+ };
202
+ (function () { globalCallback(null, presence); })();
203
+ }
204
+ }
205
+ }
206
+
207
+ });
208
+
209
+ mqttClient.on('close', function () {
210
+ //(function () { globalCallback("Connection closed."); })();
211
+ // client.end();
212
+ });
228
213
  }
229
214
 
230
215
  function parseDelta(defaultFuncs, api, ctx, globalCallback, v) {
231
- if (v.delta.class == "NewMessage") {
232
- //Not tested for pages
233
- if (ctx.globalOptions.pageID && ctx.globalOptions.pageID != v.queue) return;
234
-
235
- (function resolveAttachmentUrl(i) {
236
- if (v.delta.attachments && (i == v.delta.attachments.length)) {
237
- var fmtMsg;
238
- try {
239
- fmtMsg = utils.formatDeltaMessage(v);
240
- } catch (err) {
241
- return globalCallback({
242
- error: "Problem parsing message object. Please open an issue at https://github.com/Schmavery/facebook-chat-api/issues.",
243
- detail: err,
244
- res: v,
245
- type: "parse_error"
246
- });
247
- }
248
- if (fmtMsg)
249
- if (ctx.globalOptions.autoMarkDelivery) markDelivery(ctx, api, fmtMsg.threadID, fmtMsg.messageID);
250
-
251
- return !ctx.globalOptions.selfListen && fmtMsg.senderID === ctx.userID ? undefined : (function() { globalCallback(null, fmtMsg); })();
252
- } else {
253
- if (v.delta.attachments && (v.delta.attachments[i].mercury.attach_type == "photo")) {
254
- api.resolvePhotoUrl(v.delta.attachments[i].fbid, (err, url) => {
255
- if (!err) v.delta.attachments[i].mercury.metadata.url = url;
256
- return resolveAttachmentUrl(i + 1);
257
- });
258
- } else return resolveAttachmentUrl(i + 1);
259
- }
260
- })(0);
261
- }
262
-
263
- if (v.delta.class == "ClientPayload") {
264
- var clientPayload = utils.decodeClientPayload(v.delta.payload);
265
- if (clientPayload && clientPayload.deltas) {
266
- for (var i in clientPayload.deltas) {
267
- var delta = clientPayload.deltas[i];
268
- if (delta.deltaMessageReaction && !!ctx.globalOptions.listenEvents) {
269
- (function() {
270
- globalCallback(null, {
271
- type: "message_reaction",
272
- threadID: (delta.deltaMessageReaction.threadKey.threadFbId ? delta.deltaMessageReaction.threadKey.threadFbId : delta.deltaMessageReaction.threadKey.otherUserFbId).toString(),
273
- messageID: delta.deltaMessageReaction.messageId,
274
- reaction: delta.deltaMessageReaction.reaction,
275
- senderID: delta.deltaMessageReaction.senderId.toString(),
276
- userID: delta.deltaMessageReaction.userId.toString()
277
- });
278
- })();
279
- } else if (delta.deltaRecallMessageData && !!ctx.globalOptions.listenEvents) {
280
- (function() {
281
- globalCallback(null, {
282
- type: "message_unsend",
283
- threadID: (delta.deltaRecallMessageData.threadKey.threadFbId ? delta.deltaRecallMessageData.threadKey.threadFbId : delta.deltaRecallMessageData.threadKey.otherUserFbId).toString(),
284
- messageID: delta.deltaRecallMessageData.messageID,
285
- senderID: delta.deltaRecallMessageData.senderID.toString(),
286
- deletionTimestamp: delta.deltaRecallMessageData.deletionTimestamp,
287
- timestamp: delta.deltaRecallMessageData.timestamp
288
- });
289
- })();
290
- } else if (delta.deltaMessageReply) {
291
- //Mention block - #1
292
- var mdata =
293
- delta.deltaMessageReply.message === undefined ? [] :
294
- delta.deltaMessageReply.message.data === undefined ? [] :
295
- delta.deltaMessageReply.message.data.prng === undefined ? [] :
296
- JSON.parse(delta.deltaMessageReply.message.data.prng);
297
- var m_id = mdata.map(u => u.i);
298
- var m_offset = mdata.map(u => u.o);
299
- var m_length = mdata.map(u => u.l);
300
-
301
- var mentions = {};
302
-
303
- for (var i = 0; i < m_id.length; i++) mentions[m_id[i]] = (delta.deltaMessageReply.message.body || "").substring(m_offset[i], m_offset[i] + m_length[i]);
304
- //Mention block - 1#
305
- var callbackToReturn = {
306
- type: "message_reply",
307
- threadID: (delta.deltaMessageReply.message.messageMetadata.threadKey.threadFbId ? delta.deltaMessageReply.message.messageMetadata.threadKey.threadFbId : delta.deltaMessageReply.message.messageMetadata.threadKey.otherUserFbId).toString(),
308
- messageID: delta.deltaMessageReply.message.messageMetadata.messageId,
309
- senderID: delta.deltaMessageReply.message.messageMetadata.actorFbId.toString(),
310
- attachments: delta.deltaMessageReply.message.attachments.map(function(att) {
311
- var mercury = JSON.parse(att.mercuryJSON);
312
- Object.assign(att, mercury);
313
- return att;
314
- }).map(att => {
315
- var x;
316
- try {
317
- x = utils._formatAttachment(att);
318
- } catch (ex) {
319
- x = att;
320
- x.error = ex;
321
- x.type = "unknown";
322
- }
323
- return x;
324
- }),
325
- args: (delta.deltaMessageReply.message.body || "").trim().split(/\s+/),
326
- body: (delta.deltaMessageReply.message.body || ""),
327
- isGroup: !!delta.deltaMessageReply.message.messageMetadata.threadKey.threadFbId,
328
- mentions: mentions,
329
- timestamp: delta.deltaMessageReply.message.messageMetadata.timestamp,
330
- participantIDs: (delta.deltaMessageReply.message.participants || []).map(e => e.toString())
331
- };
332
-
333
- if (delta.deltaMessageReply.repliedToMessage) {
334
- //Mention block - #2
335
- mdata =
336
- delta.deltaMessageReply.repliedToMessage === undefined ? [] :
337
- delta.deltaMessageReply.repliedToMessage.data === undefined ? [] :
338
- delta.deltaMessageReply.repliedToMessage.data.prng === undefined ? [] :
339
- JSON.parse(delta.deltaMessageReply.repliedToMessage.data.prng);
340
- m_id = mdata.map(u => u.i);
341
- m_offset = mdata.map(u => u.o);
342
- m_length = mdata.map(u => u.l);
343
-
344
- var rmentions = {};
345
-
346
- for (var i = 0; i < m_id.length; i++) rmentions[m_id[i]] = (delta.deltaMessageReply.repliedToMessage.body || "").substring(m_offset[i], m_offset[i] + m_length[i]);
347
- //Mention block - 2#
348
- callbackToReturn.messageReply = {
349
- threadID: (delta.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId ? delta.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId : delta.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.otherUserFbId).toString(),
350
- messageID: delta.deltaMessageReply.repliedToMessage.messageMetadata.messageId,
351
- senderID: delta.deltaMessageReply.repliedToMessage.messageMetadata.actorFbId.toString(),
352
- attachments: delta.deltaMessageReply.repliedToMessage.attachments.map(function(att) {
353
- var mercury = JSON.parse(att.mercuryJSON);
354
- Object.assign(att, mercury);
355
- return att;
356
- }).map(att => {
357
- var x;
358
- try {
359
- x = utils._formatAttachment(att);
360
- } catch (ex) {
361
- x = att;
362
- x.error = ex;
363
- x.type = "unknown";
364
- }
365
- return x;
366
- }),
367
- args: (delta.deltaMessageReply.repliedToMessage.body || "").trim().split(/\s+/),
368
- body: delta.deltaMessageReply.repliedToMessage.body || "",
369
- isGroup: !!delta.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId,
370
- mentions: rmentions,
371
- timestamp: delta.deltaMessageReply.repliedToMessage.messageMetadata.timestamp,
372
- participantIDs: (delta.deltaMessageReply.repliedToMessage.participants || []).map(e => e.toString())
373
- };
374
- } else if (delta.deltaMessageReply.replyToMessageId) {
375
- return defaultFuncs
376
- .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, {
377
- "av": ctx.globalOptions.pageID,
378
- "queries": JSON.stringify({
379
- "o0": {
380
- //Using the same doc_id as forcedFetch
381
- "doc_id": "2848441488556444",
382
- "query_params": {
383
- "thread_and_message_id": {
384
- "thread_id": callbackToReturn.threadID,
385
- "message_id": delta.deltaMessageReply.replyToMessageId.id,
386
- }
387
- }
388
- }
389
- })
390
- })
391
- .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
392
- .then((resData) => {
393
- if (resData[resData.length - 1].error_results > 0) {
394
- const errorL = resData[0].o0.errors;
395
- throw errorL;
396
- }
397
- if (resData[resData.length - 1].successful_results === 0) throw { error: "forcedFetch: there was no successful_results", res: resData };
398
- var fetchData = resData[0].o0.data.message;
399
- var mobj = {};
400
- for (var n in fetchData.message.ranges) mobj[fetchData.message.ranges[n].entity.id] = (fetchData.message.text || "").substr(fetchData.message.ranges[n].offset, fetchData.message.ranges[n].length);
401
-
402
- callbackToReturn.messageReply = {
403
- threadID: callbackToReturn.threadID,
404
- messageID: fetchData.message_id,
405
- senderID: fetchData.message_sender.id.toString(),
406
- attachments: fetchData.message.blob_attachment.map(att => {
407
- var x;
408
- try {
409
- x = utils._formatAttachment({ blob_attachment: att });
410
- } catch (ex) {
411
- x = att;
412
- x.error = ex;
413
- x.type = "unknown";
414
- }
415
- return x;
416
- }),
417
- args: (fetchData.message.text || "").trim().split(/\s+/) || [],
418
- body: fetchData.message.text || "",
419
- isGroup: callbackToReturn.isGroup,
420
- mentions: mobj,
421
- timestamp: parseInt(fetchData.timestamp_precise)
422
- };
423
- })
424
- .catch(err => console.error("forcedFetch", err))
425
- .finally(function() {
426
- if (ctx.globalOptions.autoMarkDelivery) markDelivery(ctx, api, callbackToReturn.threadID, callbackToReturn.messageID);
427
- !ctx.globalOptions.selfListen && callbackToReturn.senderID === ctx.userID ? undefined : (function() { globalCallback(null, callbackToReturn); })();
428
- });
429
- } else callbackToReturn.delta = delta;
430
-
431
- if (ctx.globalOptions.autoMarkDelivery) markDelivery(ctx, api, callbackToReturn.threadID, callbackToReturn.messageID);
432
-
433
- return !ctx.globalOptions.selfListen && callbackToReturn.senderID === ctx.userID ? undefined : (function() { globalCallback(null, callbackToReturn); })();
434
- }
435
- }
436
- return;
437
- }
438
- }
439
-
440
- if (v.delta.class !== "NewMessage" && !ctx.globalOptions.listenEvents) return;
441
- switch (v.delta.class) {
442
- case "ReadReceipt":
443
- var fmtMsg;
444
- try {
445
- fmtMsg = utils.formatDeltaReadReceipt(v.delta);
446
- } catch (err) {
447
- return globalCallback({
448
- error: "Problem parsing message object. Please open an issue at https://github.com/Schmavery/facebook-chat-api/issues.",
449
- detail: err,
450
- res: v.delta,
451
- type: "parse_error"
452
- });
453
- }
454
- return (function() { globalCallback(null, fmtMsg); })();
455
- case "AdminTextMessage":
456
- switch (v.delta.type) {
457
- case "change_thread_theme":
458
- case "change_thread_nickname":
459
- case "change_thread_admins":
460
- case "change_thread_approval_mode":
461
- case "joinable_group_link_mode_change":
462
- case "rtc_call_log":
463
- case "group_poll":
464
- case "update_vote":
465
- case "magic_words":
466
- case "messenger_call_log":
467
- case "participant_joined_group_call":
468
- var fmtMsg;
469
- try {
470
- fmtMsg = utils.formatDeltaEvent(v.delta);
471
- } catch (err) {
472
- return globalCallback({
473
- error: "Problem parsing message object. Please open an issue at https://github.com/Schmavery/facebook-chat-api/issues.",
474
- detail: err,
475
- res: v.delta,
476
- type: "parse_error"
477
- });
478
- }
479
- return (function() { globalCallback(null, fmtMsg); })();
480
- default:
481
- return;
482
- }
483
- break;
484
- //For group images
485
- case "ForcedFetch":
486
- if (!v.delta.threadKey) return;
487
- var mid = v.delta.messageId;
488
- var tid = v.delta.threadKey.threadFbId;
489
- if (mid && tid) {
490
- const form = {
491
- "av": ctx.globalOptions.pageID,
492
- "queries": JSON.stringify({
493
- "o0": {
494
- //This doc_id is valid as of March 25, 2020
495
- "doc_id": "2848441488556444",
496
- "query_params": {
497
- "thread_and_message_id": {
498
- "thread_id": tid.toString(),
499
- "message_id": mid,
500
- }
501
- }
502
- }
503
- })
504
- };
505
-
506
- defaultFuncs
507
- .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form)
508
- .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
509
- .then((resData) => {
510
- if (resData[resData.length - 1].error_results > 0) {
511
- const errorL = resData[0].o0.errors;
512
- throw errorL;
513
- }
514
-
515
- if (resData[resData.length - 1].successful_results === 0) throw { error: "forcedFetch: there was no successful_results", res: resData };
516
-
517
- var fetchData = resData[0].o0.data.message;
518
-
519
- if (utils.getType(fetchData) == "Object") {
520
- console.log("forcedFetch", fetchData);
521
- switch (fetchData.__typename) {
522
- case "ThreadImageMessage":
523
- (!ctx.globalOptions.selfListen &&
524
- fetchData.message_sender.id.toString() === ctx.userID) ||
525
- !ctx.loggedIn ?
526
- undefined :
527
- (function() {
528
- globalCallback(null, {
529
- type: "change_thread_image",
530
- threadID: utils.formatID(tid.toString()),
531
- snippet: fetchData.snippet,
532
- timestamp: fetchData.timestamp_precise,
533
- author: fetchData.message_sender.id,
534
- image: {
535
- attachmentID: fetchData.image_with_metadata && fetchData.image_with_metadata.legacy_attachment_id,
536
- width: fetchData.image_with_metadata && fetchData.image_with_metadata.original_dimensions.x,
537
- height: fetchData.image_with_metadata && fetchData.image_with_metadata.original_dimensions.y,
538
- url: fetchData.image_with_metadata && fetchData.image_with_metadata.preview.uri
539
- }
540
- });
541
- })();
542
- break;
543
- case "UserMessage":
544
- console.log("ff-Return", {
545
- type: "message",
546
- senderID: utils.formatID(fetchData.message_sender.id),
547
- body: fetchData.message.text || "",
548
- threadID: utils.formatID(tid.toString()),
549
- messageID: fetchData.message_id,
550
- attachments: [{
551
- type: "share",
552
- ID: fetchData.extensible_attachment.legacy_attachment_id,
553
- url: fetchData.extensible_attachment.story_attachment.url,
554
-
555
- title: fetchData.extensible_attachment.story_attachment.title_with_entities.text,
556
- description: fetchData.extensible_attachment.story_attachment.description.text,
557
- source: fetchData.extensible_attachment.story_attachment.source,
558
-
559
- image: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).uri,
560
- width: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).width,
561
- height: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).height,
562
- playable: (fetchData.extensible_attachment.story_attachment.media || {}).is_playable || false,
563
- duration: (fetchData.extensible_attachment.story_attachment.media || {}).playable_duration_in_ms || 0,
564
-
565
- subattachments: fetchData.extensible_attachment.subattachments,
566
- properties: fetchData.extensible_attachment.story_attachment.properties,
216
+ if (v.delta.class == "NewMessage") {
217
+ //Not tested for pages
218
+ if (ctx.globalOptions.pageID && ctx.globalOptions.pageID != v.queue) return;
219
+
220
+ (function resolveAttachmentUrl(i) {
221
+ if (v.delta.attachments && (i == v.delta.attachments.length)) {
222
+ var fmtMsg;
223
+ try {
224
+ fmtMsg = utils.formatDeltaMessage(v);
225
+ } catch (err) {
226
+ return globalCallback({
227
+ error: "Problem parsing message object. Please open an issue at https://github.com/Schmavery/facebook-chat-api/issues.",
228
+ detail: err,
229
+ res: v,
230
+ type: "parse_error"
231
+ });
232
+ }
233
+ if (fmtMsg)
234
+ if (ctx.globalOptions.autoMarkDelivery) markDelivery(ctx, api, fmtMsg.threadID, fmtMsg.messageID);
235
+
236
+ return !ctx.globalOptions.selfListen && fmtMsg.senderID === ctx.userID ? undefined : (function () { globalCallback(null, fmtMsg); })();
237
+ } else {
238
+ if (v.delta.attachments && (v.delta.attachments[i].mercury.attach_type == "photo")) {
239
+ api.resolvePhotoUrl(v.delta.attachments[i].fbid, (err, url) => {
240
+ if (!err) v.delta.attachments[i].mercury.metadata.url = url;
241
+ return resolveAttachmentUrl(i + 1);
242
+ });
243
+ } else return resolveAttachmentUrl(i + 1);
244
+ }
245
+ })(0);
246
+ }
247
+
248
+ if (v.delta.class == "ClientPayload") {
249
+ var clientPayload = utils.decodeClientPayload(v.delta.payload);
250
+ if (clientPayload && clientPayload.deltas) {
251
+ for (var i in clientPayload.deltas) {
252
+ var delta = clientPayload.deltas[i];
253
+ if (delta.deltaMessageReaction && !!ctx.globalOptions.listenEvents) {
254
+ (function () {
255
+ globalCallback(null, {
256
+ type: "message_reaction",
257
+ threadID: (delta.deltaMessageReaction.threadKey.threadFbId ? delta.deltaMessageReaction.threadKey.threadFbId : delta.deltaMessageReaction.threadKey.otherUserFbId).toString(),
258
+ messageID: delta.deltaMessageReaction.messageId,
259
+ reaction: delta.deltaMessageReaction.reaction,
260
+ senderID: delta.deltaMessageReaction.senderId.toString(),
261
+ userID: delta.deltaMessageReaction.userId.toString()
262
+ });
263
+ })();
264
+ } else if (delta.deltaRecallMessageData && !!ctx.globalOptions.listenEvents) {
265
+ (function () {
266
+ globalCallback(null, {
267
+ type: "message_unsend",
268
+ threadID: (delta.deltaRecallMessageData.threadKey.threadFbId ? delta.deltaRecallMessageData.threadKey.threadFbId : delta.deltaRecallMessageData.threadKey.otherUserFbId).toString(),
269
+ messageID: delta.deltaRecallMessageData.messageID,
270
+ senderID: delta.deltaRecallMessageData.senderID.toString(),
271
+ deletionTimestamp: delta.deltaRecallMessageData.deletionTimestamp,
272
+ timestamp: delta.deltaRecallMessageData.timestamp
273
+ });
274
+ })();
275
+ } else if (delta.deltaMessageReply) {
276
+ //Mention block - #1
277
+ var mdata =
278
+ delta.deltaMessageReply.message === undefined ? [] :
279
+ delta.deltaMessageReply.message.data === undefined ? [] :
280
+ delta.deltaMessageReply.message.data.prng === undefined ? [] :
281
+ JSON.parse(delta.deltaMessageReply.message.data.prng);
282
+ var m_id = mdata.map(u => u.i);
283
+ var m_offset = mdata.map(u => u.o);
284
+ var m_length = mdata.map(u => u.l);
285
+
286
+ var mentions = {};
287
+
288
+ for (var i = 0; i < m_id.length; i++) mentions[m_id[i]] = (delta.deltaMessageReply.message.body || "").substring(m_offset[i], m_offset[i] + m_length[i]);
289
+ //Mention block - 1#
290
+ var callbackToReturn = {
291
+ type: "message_reply",
292
+ threadID: (delta.deltaMessageReply.message.messageMetadata.threadKey.threadFbId ? delta.deltaMessageReply.message.messageMetadata.threadKey.threadFbId : delta.deltaMessageReply.message.messageMetadata.threadKey.otherUserFbId).toString(),
293
+ messageID: delta.deltaMessageReply.message.messageMetadata.messageId,
294
+ senderID: delta.deltaMessageReply.message.messageMetadata.actorFbId.toString(),
295
+ attachments: delta.deltaMessageReply.message.attachments.map(function (att) {
296
+ var mercury = JSON.parse(att.mercuryJSON);
297
+ Object.assign(att, mercury);
298
+ return att;
299
+ }).map(att => {
300
+ var x;
301
+ try {
302
+ x = utils._formatAttachment(att);
303
+ } catch (ex) {
304
+ x = att;
305
+ x.error = ex;
306
+ x.type = "unknown";
307
+ }
308
+ return x;
309
+ }),
310
+ args: (delta.deltaMessageReply.message.body || "").trim().split(/\s+/),
311
+ body: (delta.deltaMessageReply.message.body || ""),
312
+ isGroup: !!delta.deltaMessageReply.message.messageMetadata.threadKey.threadFbId,
313
+ mentions: mentions,
314
+ timestamp: delta.deltaMessageReply.message.messageMetadata.timestamp,
315
+ participantIDs: (delta.deltaMessageReply.message.participants || []).map(e => e.toString())
316
+ };
317
+
318
+ if (delta.deltaMessageReply.repliedToMessage) {
319
+ //Mention block - #2
320
+ mdata =
321
+ delta.deltaMessageReply.repliedToMessage === undefined ? [] :
322
+ delta.deltaMessageReply.repliedToMessage.data === undefined ? [] :
323
+ delta.deltaMessageReply.repliedToMessage.data.prng === undefined ? [] :
324
+ JSON.parse(delta.deltaMessageReply.repliedToMessage.data.prng);
325
+ m_id = mdata.map(u => u.i);
326
+ m_offset = mdata.map(u => u.o);
327
+ m_length = mdata.map(u => u.l);
328
+
329
+ var rmentions = {};
330
+
331
+ for (var i = 0; i < m_id.length; i++) rmentions[m_id[i]] = (delta.deltaMessageReply.repliedToMessage.body || "").substring(m_offset[i], m_offset[i] + m_length[i]);
332
+ //Mention block - 2#
333
+ callbackToReturn.messageReply = {
334
+ threadID: (delta.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId ? delta.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId : delta.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.otherUserFbId).toString(),
335
+ messageID: delta.deltaMessageReply.repliedToMessage.messageMetadata.messageId,
336
+ senderID: delta.deltaMessageReply.repliedToMessage.messageMetadata.actorFbId.toString(),
337
+ attachments: delta.deltaMessageReply.repliedToMessage.attachments.map(function (att) {
338
+ var mercury = JSON.parse(att.mercuryJSON);
339
+ Object.assign(att, mercury);
340
+ return att;
341
+ }).map(att => {
342
+ var x;
343
+ try {
344
+ x = utils._formatAttachment(att);
345
+ } catch (ex) {
346
+ x = att;
347
+ x.error = ex;
348
+ x.type = "unknown";
349
+ }
350
+ return x;
351
+ }),
352
+ args: (delta.deltaMessageReply.repliedToMessage.body || "").trim().split(/\s+/),
353
+ body: delta.deltaMessageReply.repliedToMessage.body || "",
354
+ isGroup: !!delta.deltaMessageReply.repliedToMessage.messageMetadata.threadKey.threadFbId,
355
+ mentions: rmentions,
356
+ timestamp: delta.deltaMessageReply.repliedToMessage.messageMetadata.timestamp,
357
+ participantIDs: (delta.deltaMessageReply.repliedToMessage.participants || []).map(e => e.toString())
358
+ };
359
+ } else if (delta.deltaMessageReply.replyToMessageId) {
360
+ return defaultFuncs
361
+ .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, {
362
+ "av": ctx.globalOptions.pageID,
363
+ "queries": JSON.stringify({
364
+ "o0": {
365
+ //Using the same doc_id as forcedFetch
366
+ "doc_id": "2848441488556444",
367
+ "query_params": {
368
+ "thread_and_message_id": {
369
+ "thread_id": callbackToReturn.threadID,
370
+ "message_id": delta.deltaMessageReply.replyToMessageId.id,
371
+ }
372
+ }
373
+ }
374
+ })
375
+ })
376
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
377
+ .then((resData) => {
378
+ if (resData[resData.length - 1].error_results > 0) throw resData[0].o0.errors;
379
+ if (resData[resData.length - 1].successful_results === 0) throw { error: "forcedFetch: there was no successful_results", res: resData };
380
+ var fetchData = resData[0].o0.data.message;
381
+ var mobj = {};
382
+ for (var n in fetchData.message.ranges) mobj[fetchData.message.ranges[n].entity.id] = (fetchData.message.text || "").substr(fetchData.message.ranges[n].offset, fetchData.message.ranges[n].length);
383
+
384
+ callbackToReturn.messageReply = {
385
+ threadID: callbackToReturn.threadID,
386
+ messageID: fetchData.message_id,
387
+ senderID: fetchData.message_sender.id.toString(),
388
+ attachments: fetchData.message.blob_attachment.map(att => {
389
+ var x;
390
+ try {
391
+ x = utils._formatAttachment({ blob_attachment: att });
392
+ } catch (ex) {
393
+ x = att;
394
+ x.error = ex;
395
+ x.type = "unknown";
396
+ }
397
+ return x;
398
+ }),
399
+ args: (fetchData.message.text || "").trim().split(/\s+/) || [],
400
+ body: fetchData.message.text || "",
401
+ isGroup: callbackToReturn.isGroup,
402
+ mentions: mobj,
403
+ timestamp: parseInt(fetchData.timestamp_precise)
404
+ };
405
+ })
406
+ .catch(err => log.error("forcedFetch", err))
407
+ .finally(function () {
408
+ if (ctx.globalOptions.autoMarkDelivery) markDelivery(ctx, api, callbackToReturn.threadID, callbackToReturn.messageID);
409
+ !ctx.globalOptions.selfListen && callbackToReturn.senderID === ctx.userID ? undefined : (function () { globalCallback(null, callbackToReturn); })();
410
+ });
411
+ } else callbackToReturn.delta = delta;
412
+
413
+ if (ctx.globalOptions.autoMarkDelivery) markDelivery(ctx, api, callbackToReturn.threadID, callbackToReturn.messageID);
414
+
415
+ return !ctx.globalOptions.selfListen && callbackToReturn.senderID === ctx.userID ? undefined : (function () { globalCallback(null, callbackToReturn); })();
416
+ }
417
+ }
418
+ return;
419
+ }
420
+ }
421
+
422
+ if (v.delta.class !== "NewMessage" && !ctx.globalOptions.listenEvents) return;
423
+ switch (v.delta.class) {
424
+ case "ReadReceipt":
425
+ var fmtMsg;
426
+ try {
427
+ fmtMsg = utils.formatDeltaReadReceipt(v.delta);
428
+ } catch (err) {
429
+ return globalCallback({
430
+ error: "Problem parsing message object. Please open an issue at https://github.com/Schmavery/facebook-chat-api/issues.",
431
+ detail: err,
432
+ res: v.delta,
433
+ type: "parse_error"
434
+ });
435
+ }
436
+ return (function () { globalCallback(null, fmtMsg); })();
437
+ case "AdminTextMessage":
438
+ switch (v.delta.type) {
439
+ case "change_thread_theme":
440
+ case "change_thread_nickname":
441
+ case "change_thread_admins":
442
+ case "change_thread_approval_mode":
443
+ case "joinable_group_link_mode_change":
444
+ case "rtc_call_log":
445
+ case "group_poll":
446
+ case "update_vote":
447
+ case "magic_words":
448
+ case "messenger_call_log":
449
+ case "participant_joined_group_call":
450
+ var fmtMsg;
451
+ try {
452
+ fmtMsg = utils.formatDeltaEvent(v.delta);
453
+ } catch (err) {
454
+ return globalCallback({
455
+ error: "Problem parsing message object. Please open an issue at https://github.com/Schmavery/facebook-chat-api/issues.",
456
+ detail: err,
457
+ res: v.delta,
458
+ type: "parse_error"
459
+ });
460
+ }
461
+ return (function () { globalCallback(null, fmtMsg); })();
462
+ default:
463
+ return;
464
+ }
465
+ break;
466
+ //For group images
467
+ case "ForcedFetch":
468
+ if (!v.delta.threadKey) return;
469
+ var mid = v.delta.messageId;
470
+ var tid = v.delta.threadKey.threadFbId;
471
+ if (mid && tid) {
472
+ const form = {
473
+ "av": ctx.globalOptions.pageID,
474
+ "queries": JSON.stringify({
475
+ "o0": {
476
+ //This doc_id is valid as of March 25, 2020
477
+ "doc_id": "2848441488556444",
478
+ "query_params": {
479
+ "thread_and_message_id": {
480
+ "thread_id": tid.toString(),
481
+ "message_id": mid,
482
+ }
483
+ }
484
+ }
485
+ })
486
+ };
487
+
488
+ defaultFuncs
489
+ .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form)
490
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
491
+ .then((resData) => {
492
+ if (resData[resData.length - 1].error_results > 0) throw resData[0].o0.errors;
493
+
494
+ if (resData[resData.length - 1].successful_results === 0) throw { error: "forcedFetch: there was no successful_results", res: resData };
495
+
496
+ var fetchData = resData[0].o0.data.message;
497
+
498
+ if (utils.getType(fetchData) == "Object") {
499
+ log.info("forcedFetch", fetchData);
500
+ switch (fetchData.__typename) {
501
+ case "ThreadImageMessage":
502
+ (!ctx.globalOptions.selfListen &&
503
+ fetchData.message_sender.id.toString() === ctx.userID) ||
504
+ !ctx.loggedIn ?
505
+ undefined :
506
+ (function () {
507
+ globalCallback(null, {
508
+ type: "change_thread_image",
509
+ threadID: utils.formatID(tid.toString()),
510
+ snippet: fetchData.snippet,
511
+ timestamp: fetchData.timestamp_precise,
512
+ author: fetchData.message_sender.id,
513
+ image: {
514
+ attachmentID: fetchData.image_with_metadata && fetchData.image_with_metadata.legacy_attachment_id,
515
+ width: fetchData.image_with_metadata && fetchData.image_with_metadata.original_dimensions.x,
516
+ height: fetchData.image_with_metadata && fetchData.image_with_metadata.original_dimensions.y,
517
+ url: fetchData.image_with_metadata && fetchData.image_with_metadata.preview.uri
518
+ }
519
+ });
520
+ })();
521
+ break;
522
+ case "UserMessage":
523
+ log.info("ff-Return", {
524
+ type: "message",
525
+ senderID: utils.formatID(fetchData.message_sender.id),
526
+ body: fetchData.message.text || "",
527
+ threadID: utils.formatID(tid.toString()),
528
+ messageID: fetchData.message_id,
529
+ attachments: [{
530
+ type: "share",
531
+ ID: fetchData.extensible_attachment.legacy_attachment_id,
532
+ url: fetchData.extensible_attachment.story_attachment.url,
533
+
534
+ title: fetchData.extensible_attachment.story_attachment.title_with_entities.text,
535
+ description: fetchData.extensible_attachment.story_attachment.description.text,
536
+ source: fetchData.extensible_attachment.story_attachment.source,
537
+
538
+ image: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).uri,
539
+ width: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).width,
540
+ height: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).height,
541
+ playable: (fetchData.extensible_attachment.story_attachment.media || {}).is_playable || false,
542
+ duration: (fetchData.extensible_attachment.story_attachment.media || {}).playable_duration_in_ms || 0,
543
+
544
+ subattachments: fetchData.extensible_attachment.subattachments,
545
+ properties: fetchData.extensible_attachment.story_attachment.properties,
567
546
  }],
568
- mentions: {},
569
- timestamp: parseInt(fetchData.timestamp_precise),
570
- isGroup: (fetchData.message_sender.id != tid.toString())
571
- });
572
- globalCallback(null, {
573
- type: "message",
574
- senderID: utils.formatID(fetchData.message_sender.id),
575
- body: fetchData.message.text || "",
576
- threadID: utils.formatID(tid.toString()),
577
- messageID: fetchData.message_id,
578
- attachments: [{
579
- type: "share",
580
- ID: fetchData.extensible_attachment.legacy_attachment_id,
581
- url: fetchData.extensible_attachment.story_attachment.url,
582
-
583
- title: fetchData.extensible_attachment.story_attachment.title_with_entities.text,
584
- description: fetchData.extensible_attachment.story_attachment.description.text,
585
- source: fetchData.extensible_attachment.story_attachment.source,
586
-
587
- image: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).uri,
588
- width: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).width,
589
- height: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).height,
590
- playable: (fetchData.extensible_attachment.story_attachment.media || {}).is_playable || false,
591
- duration: (fetchData.extensible_attachment.story_attachment.media || {}).playable_duration_in_ms || 0,
592
-
593
- subattachments: fetchData.extensible_attachment.subattachments,
594
- properties: fetchData.extensible_attachment.story_attachment.properties,
547
+ mentions: {},
548
+ timestamp: parseInt(fetchData.timestamp_precise),
549
+ isGroup: (fetchData.message_sender.id != tid.toString())
550
+ });
551
+ globalCallback(null, {
552
+ type: "message",
553
+ senderID: utils.formatID(fetchData.message_sender.id),
554
+ body: fetchData.message.text || "",
555
+ threadID: utils.formatID(tid.toString()),
556
+ messageID: fetchData.message_id,
557
+ attachments: [{
558
+ type: "share",
559
+ ID: fetchData.extensible_attachment.legacy_attachment_id,
560
+ url: fetchData.extensible_attachment.story_attachment.url,
561
+
562
+ title: fetchData.extensible_attachment.story_attachment.title_with_entities.text,
563
+ description: fetchData.extensible_attachment.story_attachment.description.text,
564
+ source: fetchData.extensible_attachment.story_attachment.source,
565
+
566
+ image: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).uri,
567
+ width: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).width,
568
+ height: ((fetchData.extensible_attachment.story_attachment.media || {}).image || {}).height,
569
+ playable: (fetchData.extensible_attachment.story_attachment.media || {}).is_playable || false,
570
+ duration: (fetchData.extensible_attachment.story_attachment.media || {}).playable_duration_in_ms || 0,
571
+
572
+ subattachments: fetchData.extensible_attachment.subattachments,
573
+ properties: fetchData.extensible_attachment.story_attachment.properties,
595
574
  }],
596
- mentions: {},
597
- timestamp: parseInt(fetchData.timestamp_precise),
598
- isGroup: (fetchData.message_sender.id != tid.toString())
599
- });
600
- }
601
- } else console.error("forcedFetch", fetchData);
602
- })
603
- .catch((err) => console.error("forcedFetch", err));
604
- }
605
- break;
606
- case "ThreadName":
607
- case "ParticipantsAddedToGroupThread":
608
- case "ParticipantLeftGroupThread":
609
- var formattedEvent;
610
- try {
611
- formattedEvent = utils.formatDeltaEvent(v.delta);
612
- } catch (err) {
613
- return globalCallback({
614
- error: "Problem parsing message object. Please open an issue at https://github.com/Schmavery/facebook-chat-api/issues.",
615
- detail: err,
616
- res: v.delta,
617
- type: "parse_error"
618
- });
619
- }
620
- return (!ctx.globalOptions.selfListen && formattedEvent.author.toString() === ctx.userID) || !ctx.loggedIn ? undefined : (function() { globalCallback(null, formattedEvent); })();
621
- }
575
+ mentions: {},
576
+ timestamp: parseInt(fetchData.timestamp_precise),
577
+ isGroup: (fetchData.message_sender.id != tid.toString())
578
+ });
579
+ }
580
+ } else log.error("forcedFetch", fetchData);
581
+ })
582
+ .catch((err) => log.error("forcedFetch", err));
583
+ }
584
+ break;
585
+ case "ThreadName":
586
+ case "ParticipantsAddedToGroupThread":
587
+ case "ParticipantLeftGroupThread":
588
+ var formattedEvent;
589
+ try {
590
+ formattedEvent = utils.formatDeltaEvent(v.delta);
591
+ } catch (err) {
592
+ return globalCallback({
593
+ error: "Problem parsing message object. Please open an issue at https://github.com/Schmavery/facebook-chat-api/issues.",
594
+ detail: err,
595
+ res: v.delta,
596
+ type: "parse_error"
597
+ });
598
+ }
599
+ return (!ctx.globalOptions.selfListen && formattedEvent.author.toString() === ctx.userID) || !ctx.loggedIn ? undefined : (function () { globalCallback(null, formattedEvent); })();
600
+ }
622
601
  }
623
602
 
624
603
  function markDelivery(ctx, api, threadID, messageID) {
625
- if (threadID && messageID) {
626
- api.markAsDelivered(threadID, messageID, (err) => {
627
- if (err) console.error("markAsDelivered", err);
628
- else {
629
- if (ctx.globalOptions.autoMarkRead) {
630
- api.markAsRead(threadID, (err) => {
631
- if (err) console.error("markAsDelivered", err);
632
- });
633
- }
634
- }
635
- });
636
- }
604
+ if (threadID && messageID) {
605
+ api.markAsDelivered(threadID, messageID, (err) => {
606
+ if (err) log.error("markAsDelivered", err);
607
+ else {
608
+ if (ctx.globalOptions.autoMarkRead) {
609
+ api.markAsRead(threadID, (err) => {
610
+ if (err) log.error("markAsDelivered", err);
611
+ });
612
+ }
613
+ }
614
+ });
615
+ }
637
616
  }
638
617
 
639
- module.exports = function(defaultFuncs, api, ctx) {
640
- var globalCallback = identity;
641
- getSeqID = function getSeqID() {
642
- ctx.t_mqttCalled = false;
643
- defaultFuncs
644
- .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form)
645
- .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
646
- .then((resData) => {
647
- if (utils.getType(resData) != "Array")
648
- throw { error: "Not logged in", res: resData };
649
- if (resData[resData.length - 1].error_results > 0) {
650
- const errorL = resData[0].o0.errors;
651
- throw errorL;
652
- }
653
- if (resData[resData.length - 1].successful_results === 0) throw { error: "getSeqId: there was no successful_results", res: resData };
654
- if (resData[0].o0.data.viewer.message_threads.sync_sequence_id) {
655
- ctx.lastSeqId = resData[0].o0.data.viewer.message_threads.sync_sequence_id;
656
- listenMqtt(defaultFuncs, api, ctx, globalCallback);
657
- } else throw { error: "getSeqId: no sync_sequence_id found.", res: resData };
658
- })
659
- .catch((err) => {
660
- if (utils.getType(err) == "Object" && err.error === "Not logged in") {
661
- ctx.loggedIn = false;
662
- }
663
- return globalCallback(err);
664
- });
665
- };
666
-
667
- return async function(callback) {
668
-
669
- var msgEmitter = new EventEmitter();
670
- globalCallback = (callback || function(error, message) {
671
- if (error) return msgEmitter.emit("error", error);
672
- msgEmitter.emit("message", message);
673
- });
674
-
675
- //Reset some stuff
676
- if (!ctx.firstListen) ctx.lastSeqId = null;
677
- ctx.syncToken = undefined;
678
- ctx.t_mqttCalled = false;
679
- //Same request as getThreadList
680
- form = {
681
- "av": ctx.globalOptions.pageID,
682
- "queries": JSON.stringify({
683
- "o0": {
684
- "doc_id": "3336396659757871",
685
- "query_params": {
686
- "limit": 1,
687
- "before": null,
688
- "tags": ["INBOX"],
689
- "includeDeliveryReceipts": false,
690
- "includeSeqID": true
691
- }
692
- }
693
- })
694
- };
695
-
696
- if (!ctx.firstListen || !ctx.lastSeqId) getSeqID();
697
- else {
698
- listenMqtt(defaultFuncs, api, ctx, globalCallback);
699
- }
700
- ctx.firstListen = false;
701
- return msgEmitter;
702
- };
703
- };
618
+ module.exports = function (defaultFuncs, api, ctx) {
619
+ var globalCallback = identity;
620
+ getSeqID = function getSeqID() {
621
+ ctx.t_mqttCalled = false;
622
+ defaultFuncs
623
+ .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form)
624
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
625
+ .then((resData) => {
626
+ if (utils.getType(resData) != "Array") throw { error: "Not logged in", res: resData };
627
+ if (resData && resData[resData.length - 1].error_results > 0) throw resData[0].o0.errors;
628
+ if (resData[resData.length - 1].successful_results === 0) throw { error: "getSeqId: there was no successful_results", res: resData };
629
+ if (resData[0].o0.data.viewer.message_threads.sync_sequence_id) {
630
+ ctx.lastSeqId = resData[0].o0.data.viewer.message_threads.sync_sequence_id;
631
+ listenMqtt(defaultFuncs, api, ctx, globalCallback);
632
+ } else throw { error: "getSeqId: no sync_sequence_id found.", res: resData };
633
+ })
634
+ .catch((err) => {
635
+ log.error("getSeqId", err);
636
+ if (utils.getType(err) == "Object" && err.error === "Not logged in") ctx.loggedIn = false;
637
+ return globalCallback(err);
638
+ });
639
+ };
640
+
641
+ return async function (callback) {
642
+ class MessageEmitter extends EventEmitter {
643
+ stopListening(callback) {
644
+ callback = callback || (() => { });
645
+ globalCallback = identity;
646
+ if (ctx.mqttClient) {
647
+ ctx.mqttClient.unsubscribe("/webrtc");
648
+ ctx.mqttClient.unsubscribe("/rtc_multi");
649
+ ctx.mqttClient.unsubscribe("/onevc");
650
+ ctx.mqttClient.publish("/browser_close", "{}");
651
+ ctx.mqttClient.end(false, function (...data) {
652
+ callback(data);
653
+ ctx.mqttClient = undefined;
654
+ });
655
+ }
656
+ }
657
+ }
658
+
659
+ var msgEmitter = new MessageEmitter();
660
+ globalCallback = (callback || function (error, message) {
661
+ if (error) return msgEmitter.emit("error", error);
662
+ msgEmitter.emit("message", message);
663
+ });
664
+
665
+ //Reset some stuff
666
+ if (!ctx.firstListen) ctx.lastSeqId = null;
667
+ ctx.syncToken = undefined;
668
+ ctx.t_mqttCalled = false;
669
+
670
+ //Same request as getThreadList
671
+ form = {
672
+ "av": ctx.globalOptions.pageID,
673
+ "queries": JSON.stringify({
674
+ "o0": {
675
+ "doc_id": "3336396659757871",
676
+ "query_params": {
677
+ "limit": 1,
678
+ "before": null,
679
+ "tags": ["INBOX"],
680
+ "includeDeliveryReceipts": false,
681
+ "includeSeqID": true
682
+ }
683
+ }
684
+ })
685
+ };
686
+
687
+ if (!ctx.firstListen || !ctx.lastSeqId) getSeqID();
688
+ else listenMqtt(defaultFuncs, api, ctx, globalCallback);
689
+ ctx.firstListen = false;
690
+ return msgEmitter;
691
+ };
692
+ };